Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Detect if a player is moving up or down?

I'm trying to detect if a player is moving up or down based on the difference between the current and last Y position, but it doesn't seem to be working.

-- //Everything is defined above
loopCheck = Services['runService'].Heartbeat:connect(function(Rate)
	local loopRate = workspace:GetRealPhysicsFPS()
	local fastestMovement = speedStat.Value/loopRate -- //SpeedStat is their basespeed, 16 studs per second for example
	-- //Movement calculations
	if lastYPosition ~= nil then
		print'a' -- //This is never printed
		if Player.Character.Torso.Position.Y - lastYPosition >= fastestMovement*.9 then
			moveDirection = 'Up'
		elseif Player.Character.Torso.Position.Y - lastYPosition <= -fastestMovement*.9 then
			moveDirection = 'Down'
		else
			moveDirection = 'Still'
		end
	end
	local lastYPosition = Player.Character.Torso.Position.Y
	print(moveDirection) -- //Always prints nil
	print(lastYPosition) --//Correctly prints the y position
end)

1 comment

1 answer

✓ Accepted answer

The problem with your code is this line: local lastYPosition = Player.Character.Torso.Position.Y. Since you're setting that variable as local to the current scope, When you run the function again in the next frame, it won't have access to it, so that if lastYPosition ~= nil then is never passed.

However, a much easier way would be to just check the Y component of the velocity of the player, i.e.

if (Player.Character.HumanoidRootPart.Velocity.Y > fastestMovement*.9) then
	return "Up";
elseif (Player.Character.HumanoidRootPart.Velocity.Y < -fastestMovement*.9) then
	return "Down";
else
	return "Still";
end

This discussion is preserved as it was. New answers, comments, and votes are closed.