Search code examples
c#unity-game-enginerotationtransformquaternions

Rotation third person in direction to camera?


I want my object to rotate towards the camera at the same time when I rotate the camera, so that the player while walking is always oriented in the direction of the camera, as in typical third-person games. Unfortunately, any method used so far leads me to a rotation of the object, slightly behind, the rotation of the camera. I've been looking for a solution for a week and I'm desperate. I publish a video of the rotation I have with an object.

video of the late rotation

private Rigidbody rb;
public float speed = 1.0f;

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

direction = Camera.main.transform.forward;
direction.y = 0.00f;

private void FixedUpdate ()
{

 Quaternion targetRotation = Quaternion.LookRotation(direction);
Quaternion newRotation = Quaternion.Lerp(rb.transform.rotation, targetRotation, speed * Time.fixedDeltaTime);
rb.MoveRotation(newRotation);
 }  

}

Solution

  • This is an inappropriate use for Quaternion.Lerp because you aren't working with a proportion of how far to move. Currently, you're basically telling it to only rotate a tiny percentage of the way to the target rotation.

    You should rather use Quaternion.RotateTowards, because you can easily calculate angular rotation based on deltaTime (or, fixedDeltaTime as you use):

    public float speed = 30f; // max rotation speed of 30 degrees per second
    
    // ...
    
    Quaternion newRotation = Quaternion.RotateTowards(rb.transform.rotation, targetRotation, 
            speed * Time.deltaTime);
    rb.MoveRotation(newRotation);
    

    After re-reading your question, now it seems that you don't want a smooth transition/lerp. In that case, just set the rotation to the target rotation:

    rb.MoveRotation(targetRotation);
    

    If even that is too much interpolation/not immediate enough, you could set the rigidbody's rotation in Update:

    private void Update ()
    {
        rb.rotation = Quaternion.LookRotation(direction);
    }