Player rotating towards direction of movement, but rotates back after movement stops

I’ve tried different methods for this and followed 2 tutorials but every time my player rotates towards the direction of movement while I’m moving, but when i stop holding down the movement buttons he rotates back to his default position. My code (sorry if its messy, I’m still very new to this):

public class Movement : MonoBehaviour
{

    private Rigidbody rb;

    private float horizontalInput;
    private float verticalInput;
    public float speed;
    public float turnSpeed;
    Vector3 dir;

    // Start is called before the first frame update
    void Start()
    {
        rb = GetComponent<Rigidbody>();  
    }

    // Update is called once per frame
    void Update()
    {
        horizontalInput = Input.GetAxis("Horizontal");
        verticalInput = Input.GetAxis("Vertical");
        _Movement();
    }

    void _Movement()
    {
        dir = new Vector3(horizontalInput, 0, verticalInput);
       
         rb.MovePosition(transform.position + dir * Time.deltaTime * speed);
      

        Quaternion targetRotataion = Quaternion.LookRotation(dir);
        targetRotataion = Quaternion.RotateTowards(transform.rotation, targetRotataion, 360 * Time.deltaTime * turnSpeed) ;
        rb.MoveRotation(targetRotataion);
       
       
    }

Don’t do the rotation if the magnitude of the motion is less than a certain amount, eg., wrap lines 34-36 inside an if statement, something like:

if (dir.magnitude > 0.1f)
{
   // put line 34, 35 and 36 above here)
}
1 Like