Menu
CoddyTech

Smooth Follow

Part of the Physics and Gameplay section of Coddy's Unity journey. Lesson 47 of 71.

A camera that copies the player's position plus an offset in LateUpdate() makes every jolt of the player a jolt of the view. Vector3.SmoothDamp(current, target, ref velocity, smoothTime) returns a position moved toward target the way a damped spring moves: it speeds up, slows down as it nears the target, and arrives without overshooting. This camera follows the player from 3 units up and 6 behind, a little late:

public Transform player;
public Vector3 offset = new Vector3(0, 3, -6);
public float smoothTime = 0.3f;
Vector3 velocity;

void LateUpdate()
{
    Vector3 target = player.position + offset;
    transform.position = Vector3.SmoothDamp(transform.position, target, ref velocity, smoothTime);
}

ref hands SmoothDamp the variable itself instead of a copy, so the method can change it. SmoothDamp keeps the camera's current speed, on all three axes, in velocity and needs it back on the next frame, which is why it is a field. Declared inside LateUpdate(), it would start from zero on every frame and the camera would crawl, about half a percent of the way per frame. For a single number, such as a camera's zoom, Mathf.SmoothDamp works the same way with a float velocity.

smoothTime sets how far behind the camera lags: with 0.3, it covers about 60% of a sudden jump in 0.3 seconds and is almost there after 1 second. A smaller value follows more tightly. SmoothDamp reads Time.deltaTime itself, so nothing in the call is multiplied by it.

challenge icon

Challenge

Medium

Make the camera follow the player smoothly from a fixed height.

  1. Add a field Vector3 velocity;.
  2. In LateUpdate(), build Vector3 target = new Vector3(player.position.x, height, player.position.z - back);, so a hop does not move the view.
  3. Set transform.position = Vector3.SmoothDamp(transform.position, target, ref velocity, smoothTime);.

Press Play, run and hop: the camera trails a little, and never bobs. Then Check.

Try it yourself

using UnityEngine;

public class TopDownCamera : MonoBehaviour
{
    public Transform player;
    public float height = 12f;
    public float back = 5f;
    public float smoothTime = 0.25f;

    void LateUpdate()
    {
        // Ease toward the spot above the player (x), back units behind it (z), at a fixed height.
    }
}

All lessons in Physics and Gameplay

Practice on your own: Unity playground