Search code examples
c#unity-game-enginerotationoffsetquaternions

How to make camera have same rotation as an object but with an offset (Unity)


So i have a car and a camera and so far here is the camera script:

 public GameObject car;
    public Vector3 offset;

    void Start()
    {
        offset = transform.position - car.transform.position;
        
    }

    // Update is called once per frame
    void FixedUpdate()
    {
        transform.position = transform.position = Vector3.Lerp(transform.position, car.transform.position + offset, 0.8f);
    }
}

This makes the camera smoothly move with the car, but now i want the camera to also have the same rotation as the car but with the starting offset.


Solution

  • You could just the "same" way store the original delta rotation like

    Quaternion offsetRotation;
    
    private void Start ()
    {
        offset = transform.position - car.transform.position;
    
        offsetRotation = transform.rotation * Quaternion.Inverse(car.transform.rotation);
    }
    

    And then later

    void FixedUpdate()
    {
        transform.position = Vector3.Lerp(transform.position, car.transform.position + offset, 0.8f);
    
        transform.rotation = Quaternion.Slerp(transform.rotation, car.transform.rotation * offsetRotation, 0.8f);
    }