Smooth camera follow including rotation and limiting

Hi guys,

I need a camera that follows my ship. I found many tutorials but they don’t take rotation into account.
This is my script so far which doesn’t work at all [rotation is not affected at all, position does not stay behind]:

public class CameraScript : MonoBehaviour {

    //  Target related
    public Transform Target;

    //  Self related
    Camera cam;
    Transform camTransform;

    //  Calculations
    Quaternion lookAt;

    [Header("Camera behaviour values")]
    public float camRotationSpeed = 5.0f;
    public float camFollowSpeed = 10.0f;
    public Vector3 camOffset;

    void Start () {
        cam = gameObject.GetComponent<Camera>();
        camTransform = cam.GetComponent<Transform>();
    }
   
    void LateUpdate () {
        //  Move the camera towards the target
        camTransform.position = Vector3.Slerp(camTransform.position, Target.position + camOffset, Time.fixedDeltaTime * camFollowSpeed);

        //  Look at the target
        lookAt = Quaternion.Slerp(camTransform.rotation, Target.rotation, Time.fixedDeltaTime * camRotationSpeed);
        camTransform.rotation = lookAt;
    }
}

What I like to achieve:

  • Follow the player in a chase-cam style
  • When the ship accelerates, the camera should lag behind a bit and eventually catch up [guess I need Slerp and take players Rigidbody velocity into account?]
  • Always look at the player, but also smoothly
  • Do not follow player rotations like a barrel roll, but if the player for example pitches the nose of the ship, slowly align the camera so the player can also look upwards.

Guess this is a more complex task but I have no real idea where to start and didn’t find helpful tutorials yet…

You have to just take it one piece at a time.

First, don’t use Slerp or Lerp. Any time you are passing the current position of something into either of these functions, you are abusing them, and this will cause you grief sooner or later. Yes, I know a lot of example code on the internet does this. There are a lot of crazy things on the internet. Read here for more.

Instead, you should update your position using Vector3.MoveTowards, and your orientation using Quaternion.RotateTowards.

I suggest you start with just the position. Use Vector3.MoveTowards to move the camera towards its target position (which you might represent as an empty GameObject, in the hierarchy under the player transform, and positioned above/behind the player) on every frame. Get this much working first.

Then deal with rotation. Here I would suggest you have a second target object, this one positioned out in front of the player. Use Quaternion.LookRotation to calculate the ideal rotation to look at this position, and then use Quaternion.RotateTowards to smoothly move your current rotation towards this ideal.

1 Like

Thanks alot, will try it out!

1 Like