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

How to detect mouse movement direction?

So when you use mouse.move in first person, the position of the mouse never moves. How can I detect in which direction the camera is moving (up down left right) ?

I've tried using this but it resets after a while and doesn't work at all barely:

local mouseUnit=(mouse.Hit.p-mouse.Origin.p).unit

1 answer

✓ Accepted answer

You can use UserInputService. Mouse.Move works fine when the mouse is free, like you said, but you can use UserInputService to determine the mouse delta while the mouse is locked (either because you're in first person or you set the MouseBehavior to LockCenter, or some other reason).

The following code demonstrates both. Throw it in a LocalScript somewhere and look how the function that's outputting meaningful values switches when you're in first person vs. freely moving the mouse.

-- mouse.Move for when the mouse is free:
local mouse = game.Players.LocalPlayer:GetMouse();
local lastX, lastY = 0, 0;

mouse.Move:connect(function()
	print("Move:	(" .. 
		tostring(mouse.X - lastX) .. ",	" .. 
		tostring(mouse.Y - lastY) .. ")"
	);
	lastX = mouse.X;
	lastY = mouse.Y;
end)

-- UserInputService for when the mouse is locked:
local userinput = game:GetService("UserInputService");

userinput.InputChanged:connect(function(inputObj)
	if (inputObj.UserInputType == Enum.UserInputType.MouseMovement) then
		local dx = inputObj.Delta.X;
		local dy = inputObj.Delta.Y;
		print("UI:	(" .. 
			tostring(dx) .. ",	" .. 
			tostring(dy) .. ")"
		);
	end
end)

1 comment

0

I actually found an alternative to what I needed to do, but I appreciate the answer and I'm sure some other people that read your answer were helped as well. Thanks! :)

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