- Home /
Convert WASD to local rotation
I am using a script to make WASD relate to the camera, so W is not forward on the player Z axis, but to the top of the camera, irrelevant where the player is looking.
That works like this:
horizontalInput = Mathf.Clamp(horizontalInput, -1f, 1f);
verticalInput = Mathf.Clamp(verticalInput, -1f, 1f);
Vector3 direction = new Vector3(horizontalInput, 0f, verticalInput).normalized;
if (direction.magnitude >= 0.1f)
{
float targetAngle = Mathf.Atan2(direction.x, direction.z) * Mathf.Rad2Deg +
_camera.transform.eulerAngles.y;
Vector3 moveDirection = Quaternion.Euler(0f, targetAngle, 0f) * Vector3.forward;
transform.Translate(moveDirection.normalized * (moveSpeed * Time.deltaTime), Space.World);
}
The character is constantly rotating to the mouse cursor (using ScreenPointToRay).
Now, because of the movement animations. I want to convert the WASD inputs related to the local rotation, which means that I want A to always be to the left of the character.
I need this to set the animator movement parameters to animate strafes, walking forward, backwards, etc.
_animator.SetFloat("moveX", horizontalInput);
_animator.SetFloat("moveY", verticalInput);
Any ideas?
Answer by Captain_Pineapple · Jun 03, 2020 at 06:47 AM
Assuming you have a setup where your movement is always in the x-z-Plane and your camera rotation might be anything i'd do it like this:
Vector3 forwardVec = Vector3.ProjectOnPlane(_camera.transform.forward, Vector3.up).normalized;
Vector3 sideVec = Vector3.Cross(forwardVec, Vector3.up);
Vector3 movementVec = forwardVec * verticalInput + sideVec * horizontalInput;
transform.Translate(movementVec.normalized * (moveSpeed * Time.deltaTime));
not tested though, might also not work.
Your answer
Follow this Question
Related Questions
Moving only if straight path dijkstra 1 Answer
MoveTowards inside Coroutine 2 Answers
Move Character to touched Position 2D (Without RigidBody and Animated Movement) 1 Answer
How to set a target position in Vector3.MoveTowards using a variable 2 Answers
Unexpected behavior on Vector3.moveTowards for Player 0 Answers