Build a 2D Platformer using Unity and C#

Lesson 3 of 7

Camera Follow and Bounds

A platformer camera needs to track the player smoothly, without jittering or showing empty space past the edges of the level.

using UnityEngine;

public class CameraFollow : MonoBehaviour
{
    public Transform target;
    public float smoothTime = 0.15f;
    public Vector2 minBounds;
    public Vector2 maxBounds;

    Vector3 velocity;

    void LateUpdate()
    {
        Vector3 desired = new Vector3(target.position.x, target.position.y, transform.position.z);
        Vector3 smoothed = Vector3.SmoothDamp(transform.position, desired, ref velocity, smoothTime);

        smoothed.x = Mathf.Clamp(smoothed.x, minBounds.x, maxBounds.x);
        smoothed.y = Mathf.Clamp(smoothed.y, minBounds.y, maxBounds.y);

        transform.position = smoothed;
    }
}

The pieces

  • LateUpdate() runs after every Update() this frame, cameras should always follow in LateUpdate, so they track the player's final position for the frame instead of a stale one from before its last movement.
  • Vector3.SmoothDamp eases the camera toward a target position over smoothTime seconds, instead of snapping instantly, this is what makes camera movement feel smooth rather than jittery. It needs a ref Vector3 velocity field that it updates internally between calls, don't reset that field yourself.
  • Mathf.Clamp on the final x and y keeps the camera from ever showing area outside minBounds/maxBounds, set those to the edges of your level so the camera stops panning once it reaches them.
  • The camera's own z position is preserved (transform.position.z) rather than copied from the player, since the player lives on the 2D gameplay plane but the camera needs distance from it to actually render anything.

TIP

Unity's Cinemachine package does all of this (smoothing, bounds via a Confiner) with no code and far more polish, writing your own follow script first is worth doing once so you understand what Cinemachine is actually doing under the hood.

📝 Camera Follow Quiz

Passing score: 70%
  1. 1.Why should camera-follow logic run in LateUpdate instead of Update?

  2. 2.Vector3.____ eases a value toward a target over time instead of snapping to it instantly.

  3. 3.Mathf.Clamp on the camera's position can prevent it from showing area outside the level bounds.