I have a script that rotates the player in the direction of movement. For example, I press the A key - the player turns to the left, I press the D key - the player turns to the right.
But the script does not take into account the rotation of the camera and I don’t know how to fix it
public Transform player;
public Transform direction; //empty object in player
float horizontal = Input.GetAxis(Axis.Horizontal);
float vertical = Input.GetAxis(Axis.Vertical);
//rotate player
Vector3 viewDir = player.position - new Vector3(transform.position.x, player.position.y, transform.position.z);
direction.forward = viewDir.normalized;
Vector3 inputDir = direction.forward * vertical + direction.right * horizontal;
if (inputDir != Vector3.zero)
{
player.forward = Vector3.Slerp(player.forward, inputDir.normalized, rotationSpeed * Time.deltaTime);
}
Axis.cs
public class Axis : MonoBehaviour
{
public static string Horizontal = "Horizontal";
public static string Vertical = "Vertical";
}