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 everyUpdate()this frame, cameras should always follow inLateUpdate, so they track the player's final position for the frame instead of a stale one from before its last movement.Vector3.SmoothDampeases the camera toward a target position oversmoothTimeseconds, instead of snapping instantly, this is what makes camera movement feel smooth rather than jittery. It needs aref Vector3 velocityfield that it updates internally between calls, don't reset that field yourself.Mathf.Clampon the final x and y keeps the camera from ever showing area outsideminBounds/maxBounds, set those to the edges of your level so the camera stops panning once it reaches them.- The camera's own
zposition 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.