I want to get the direction that the player is moving in relative to the camera, So for example if they’re moving right then the game will recognize that. I could just detect if they’re pressing the A or D buttons, But that wouldn’t work with anything that has a joystick.
I want the exact direction they’re heading relative to the camera position, But I haven’t been able to figure it out.
I’ve looked around the forum but couldn’t find anything for this specific issue.
I’ve tried this, But it seems to have weird results, And I’m not sure how to detect if you’re going left or right with this. It appears to change if you move which axis you’re moving on, rather than if you’re going left or right from the camera.
No, Doesn’t work. It seems to have the same issue. I need it to calculate the direction in local space relative to the camera. I may be able to get the input directly from the gamepad and just detect the direction the player is moving depending on the keys being pressed for keyboard controls, So this may not be necessary at all.
If you take the Unit of the above Vector, you will get the direction they are moving relative to the camera; defined by the direction of x/y/z with a magnitude of 1. We simply don’t use the Y, since we aren’t checking if they are moving up and down in this case.
local movementDirection = camera.CFrame:vectorToObjectSpace(humanoid.MoveDirection).Unit
if math.abs(movementDirection.X) > math.abs(movementDirection.Z) then
-- if x is negative then character is moving left, if its positive then they are moving right (in relation to camera)
elseif math.abs(movementDirection.X) < math.abs(movementDirection.Z) then
-- if z is negative then character is moving forward, else they are moving backward (in relation to camera)
else
-- not moving (or moving perfectly diagonally, but unlikely, may want to add a condition for that as well).
end
Note that you can incorporate both the x and z values to detect diagonal movement as well. If you need more than just the four cardinal directions, I can explain that as well.