- Home /
Rotate Locally Player Towards Joystick/Axis Input
So this is basically the code of Unity's Stealth Tutorial
void Rotating(float horizontal, float vertical)
{
// Create a new vector of the horizontal and vertical inputs.
Vector3 targetDirection = new Vector3(horizontal, 0f, vertical);
// Create a rotation based on this new vector assuming that up is the global y axis.
Quaternion targetRotation = Quaternion.LookRotation(targetDirection, Vector3.up);
// Create a rotation that is an increment closer to the target rotation from the player's rotation.
Quaternion newRotation = Quaternion.Lerp(rigidbody.rotation, targetRotation, 8f * Time.deltaTime);
// Change the players rotation to this new rotation.
rigidbody.MoveRotation(newRotation);
}
As you can see this function takes the horizontal and vertical axis input to create a new vector and set it as the target direction which works fine, but this codes expects that the camera will always look in the direction of Vector3.forward, this is the global system.
By locally I mean that no matter which direction the camera is looking the player will always rotate to the direction your axis is being input.
Answer by robertbu · Oct 14, 2014 at 10:29 PM
Language can get in the way with these kinds of questions. I'm going to assume you want the movement relative to the camera. If so, insert at line 5:
targetDirection = Camera.main.transform.TransformDirection(targetDirection);
This code assumes the camera is not tilted up or down. If you camera is tilted, you probably want:
targetDirection = Camera.main.transform.TransformDirection(targetDirection);
targetDirection.y = 0.0f;
targetDirection.Normalize();