Problem with New Input System Cinemachine and Player Rotation

Hi! I’m trying for days to make a adventure/ platformer looking camera. But I never got good results. I’m using the new Input System whit Cinemachine. The big proble is: the camera follow the player direction when I press W ,but, when I press A and D or S and I release those keys the player turn back to the Z position… I’m trying to make a camera like this video. I made a lot of Unity projects following youtube/ udemy tutorials, but I never got good results. I really don’t know to make this kind of camera and what I need to study to achieve it. I would like to use a Rigidbody for physics simulation in future. Thanks for all!!

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerController : MonoBehaviour
{
    public float moveSpeed = 5.0f;
    public float rotationSpeed = 280.0f;

    float horizontal;
    float vertical;

    Rigidbody rb;

    private void Awake()
    {
        rb = GetComponent<Rigidbody>();
    }

    private void Update()
    {
        Vector3 moveDirection = Vector3.forward * vertical + Vector3.right * horizontal;
      

        Vector3 projectedCameraFoward = Vector3.ProjectOnPlane(Camera.main.transform.forward, Vector3.up);
        Quaternion rotationCamera = Quaternion.LookRotation(projectedCameraFoward, Vector3.up);
      

        moveDirection = rotationCamera * moveDirection;
        Quaternion rotationToMoveDirection = Quaternion.LookRotation(moveDirection);

        //transform.rotation = Quaternion.RotateTowards(transform.rotation, rotationCamera, rotationSpeed * Time.deltaTime);

        transform.rotation = Quaternion.RotateTowards(transform.rotation, rotationToMoveDirection, rotationSpeed * Time.deltaTime);
      
        transform.position += moveDirection * moveSpeed * Time.deltaTime;

      
    }

    public void OnMoveInput(float horizontal, float vertical)
    {
        this.vertical = vertical;
        this.horizontal = horizontal;
    }
}

See how your line 34 will ALWAYS turn rotation?

When your motion comes to zero or near zero, it returns to the facing you see.

Instead, check the size (magnitude) of your motion and only set the rotation if your motion is above a certain small amount.

Something like:

if (moveDirection.magnitude >= 0.1f)
{
// this line is just your line 34 above copied over with extra line breaks:
    transform.rotation = Quaternion.RotateTowards(
             transform.rotation,
             rotationToMoveDirection,
             rotationSpeed * Time.deltaTime);
}

Thanks!! You saved my life!

1 Like