Hello everyone I’m wondering how to make my character face the direction of the arrow keys for example when I press the right arrow key I want my character to face 90 degrees on the Y axis and when I press the down down arrow key he faces 180 degrees but when I press both I want him to face 135 degrees. How would I do this?
To get the desired effect, you need to do two things-
first, in your script-
Vector3 movementDirection = new Vector3(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"), 0);
Vector3 realDirection = Camera.main.transform.TransformDirection(movementDirection);
// this line checks whether the player is making inputs.
if(realDirection.magnitude > 0.1f)
{
Quaternion newRotation = Quaternion.LookRotation(realDirection);
transform.rotation = Quaternion.Slerp(transform.rotation, newRotation, Time.deltaTime * 10);
}
EDIT: Code fixed- now with 100% more sanity.
EDIT EDIT: Code augmented- now doesn't reset angles.
Now, doing it that way will cause your player to smoothly rotate all the way around the axis- which is good under most circumstances, but sometimes you don't want this (retro-inspired movement style, 8-directions). To make it rotate sharply, change the transform.rotation line to
transform.rotation = newRotation;
And then instead of using
Input.GetAxis("whatever");
use
Input.GetAxisRaw();
which returns a 1 or 0 value.