Checking what direction the mouse is moved in

Hello, I am just curious and I have experimented a bit, how can I check what direction you are currently moving your mouse in? In restaurant tycoon 2 there are some examples of this, like up and down, or side to side, how can I check? I have tried for hours and I can’t figure it out.

2 Likes

If you want to tell which direction your mouse is moving into relative to your local player’s body you need to translate the world position of your mouse.Hit.Position to object space of your character’s humanoidroot part

How can I do that? I’m not the best at scripting.

local players = game:GetService("Players")
local player = players.LocalPlayer
local mouse = player:GetMouse()

local lastMouseX, lastMouseY = mouse.X, mouse.Y

mouse.Move:Connect(function()
	if math.abs(mouse.X - lastMouseX) > math.abs(mouse.Y - lastMouseY) then
		if mouse.X - lastMouseX > 0 then
			print("Mouse is moving right!")
		else
			print("Mouse is moving left!")
		end
	else
		if mouse.Y - lastMouseY > 0 then
			print("Mouse is moving down!")
		else
			print("Mouse is moving up!")
		end
	end
	lastMouseX, lastMouseY = mouse.X, mouse.Y
end)

I believe this is what you’re looking for, assuming you’re referring to the mouse cursor’s screen position (2D).

11 Likes

Wow thanks man! But what is uh math.abs?

math.abs() is a math library function which returns the absolute value of a calculation. In other words it’ll always return a positive number value, even if its argument is a negative number value.

print(math.abs(-100)) --100

Thanks man, helpful stuff, you really are a Forummer.

This doesn’t work in first person, or when hold right click to move the camera. Any fixes to that?

In those cases you’ll need to check the camera’s rotation (as the cursor is static).

local Game = game --Local environment integration.
local Workspace = workspace
local RunService = Game:GetService("RunService")
local Camera = Workspace.CurrentCamera

local Abs = math.abs
local Deg = math.deg
local Round = math.round

local X, Y, Z = Camera.CFrame:ToOrientation()

local function OnRenderStep()
	local _X, _Y, _Z = Camera.CFrame:ToOrientation()
	_X, _Y, _Z = Round(Deg(_X)), Round(Deg(_Y)), Round(Deg(_Z))
	if Abs(_X - X) > Abs(_Y - Y) then
		if _X > X then
			print("Camera is rotating up.")
		elseif _X < X then
			print("Camera is rotating down.")
		end
	else
		if _Y > Y then
			print("Camera is rotating left.")
		elseif _Y < Y then
			print("Camera is rotating right.")
		end
	end
	X, Y, Z = _X, _Y, _Z
end

RunService.RenderStepped:Connect(OnRenderStep)
6 Likes