Menu
CoddyTech

Smooth Follow

Part of the Physics and Gameplay section of Coddy's Unity journey. Lesson 45 of 63.

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

The camera looks down on the player from a fixed height. Make it follow smoothly with Vector3.SmoothDamp and smoothTime (0.25), easing toward this spot:

  • x: the player's x;
  • z: back (5) units behind the player, toward -z;
  • y: always height (12), whatever the player's own height. Space makes the player hop, and the view must not bob.

Press Play, run and hop, 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.
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Physics and Gameplay