TExcelTAD
Home › 3D Web Games with Three.js › Third-Person Camera

Third-Person Camera

A third-person camera follows the character from behind and above. Done badly it is the most criticised part of a game ("the camera fought me"). Done well, nobody notices it. The core is only four ideas:

  1. a desired position: an offset behind the character, rotated by the camera's own yaw;
  2. smoothing: move toward that position a fraction per frame, framerate-independently;
  3. a look-at point slightly above (and ahead of) the character;
  4. collision: if a wall is between the character and the camera, pull the camera in front of it.

Smoothing that doesn't depend on the frame rate

The classic one-liner camera.position.lerp(desired, 0.1) moves 10% of the remaining distance per frame. At 144 Hz that's more than twice as many steps per second as at 60 Hz, so the camera is snappier on fast screens and sluggish on slow ones. The fix is to make the fraction depend on dt: 1 - Math.exp(-sharpness * dt). This model follows a target 10 m away for half a second at three frame rates:

js · try it yourself
// Distance left to a target after 0.5 s, with per-frame lerp vs exponential damping.
function follow(fps, factorFor) {
  let x = 0;
  const target = 10, dt = 1 / fps;
  for (let i = 0; i < fps / 2; i++) x += (target - x) * factorFor(dt);
  return (target - x).toFixed(3);
}
const naive = () => 0.1;                              // "10% per frame"
const damped = (dt) => 1 - Math.exp(-6 * dt);         // sharpness 6 per second

for (const fps of [30, 60, 144]) {
  console.log(`${String(fps).padStart(3)} fps  lerp 0.1/frame: ${follow(fps, naive).padStart(6)} m left   exp damping: ${follow(fps, damped)} m left`);
}
 30 fps  lerp 0.1/frame:  2.059 m left   exp damping: 0.498 m left
 60 fps  lerp 0.1/frame:  0.424 m left   exp damping: 0.498 m left
144 fps  lerp 0.1/frame:  0.005 m left   exp damping: 0.498 m left

The naive camera is 400 times "tighter" at 144 Hz than at 30 Hz; the damped one behaves identically everywhere. sharpness reads naturally: after 1 / sharpness seconds about 63% of the gap is closed. Use the same formula for rotations (quaternion.slerp(target, 1 - Math.exp(-k * dt))), zoom and anything else you smooth. See Damping in Math for Games.

The full camera

The playground has a character that walks relative to the camera (W moves away from the camera, wherever it points), a camera you orbit by dragging, smoothing, and camera collision against the walls of a small maze. Walk next to a wall and orbit the camera behind it: instead of looking through the wall, the camera slides in toward the character.

html · try it yourself
<style>
  html, body { margin: 0; height: 100%; overflow: hidden; background: #0e1018; }
  canvas { display: block; outline: none; touch-action: none; }
  #hud { position: fixed; left: 10px; top: 8px; color: #fff; font: 13px system-ui, sans-serif; pointer-events: none; text-shadow: 0 1px 2px #000; }
  #veil { position: fixed; inset: 0; display: grid; place-content: center; background: rgba(0, 0, 0, 0.55); color: #fff; font: 600 20px system-ui, sans-serif; text-align: center; pointer-events: none; }
  #veil small { display: block; margin-top: 6px; font-weight: 400; font-size: 13px; }
  #veil.off { display: none; }
</style>
<div id="hud"></div>
<div id="veil">Click to play<small>WASD to walk, drag to orbit the camera, wheel to zoom</small></div>
<script type="module">
import * as THREE from 'three';

// ---- 3D play kit: renderer, click to focus, keys, pause on blur, fixed-step loop ----
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.setSize(innerWidth, innerHeight);
document.body.prepend(renderer.domElement);
const cv = renderer.domElement, veil = document.getElementById('veil');
const keys = new Set(), pressed = new Set();   // held now / pressed since the last update
let active = false, drawn = false;
cv.tabIndex = 0;
cv.addEventListener('pointerdown', () => cv.focus());
cv.addEventListener('focus', () => { active = true; veil.classList.add('off'); });
cv.addEventListener('blur', () => { active = false; drawn = false; veil.classList.remove('off'); keys.clear(); pressed.clear(); });
addEventListener('keydown', (e) => {
  if (e.code.startsWith('Arrow') || e.code === 'Space') e.preventDefault();   // don't scroll the lesson
  if (!e.repeat) pressed.add(e.code);
  keys.add(e.code);
});
addEventListener('keyup', (e) => keys.delete(e.code));
function run(scene, camera, update) {
  const STEP = 1 / 60, timer = new THREE.Timer();
  let acc = 0;
  addEventListener('resize', () => {
    camera.aspect = innerWidth / innerHeight;
    camera.updateProjectionMatrix();
    renderer.setSize(innerWidth, innerHeight);
    drawn = false;
  });
  renderer.setAnimationLoop((t) => {
    timer.update(t);
    if (active) {
      acc += Math.min(timer.getDelta(), 0.1);
      while (acc >= STEP) { update(STEP); pressed.clear(); acc -= STEP; }
    } else if (drawn) return;          // paused: the last frame stays on screen
    renderer.render(scene, camera);
    drawn = true;
  });
}
// ---- end of play kit ----

const scene = new THREE.Scene();
scene.background = new THREE.Color('#9cbcd8');
const camera = new THREE.PerspectiveCamera(60, innerWidth / innerHeight, 0.1, 100);
scene.add(new THREE.HemisphereLight('#eef4ff', '#5d5140', 1.5));
const sun = new THREE.DirectionalLight('#fff', 2);
sun.position.set(-3, 8, 5);
scene.add(sun);
const floor = new THREE.Mesh(new THREE.PlaneGeometry(30, 30), new THREE.MeshStandardMaterial({ color: '#7a9a63' }));
floor.rotation.x = -Math.PI / 2;
scene.add(floor);

// Maze walls: boxes the camera collides with (and the player is blocked by, as AABBs).
const walls = [];
const wallMat = new THREE.MeshStandardMaterial({ color: '#c4b79f' });
for (const [x, z, w, d] of [[0, -6, 12, 0.5], [-6, 0, 0.5, 12], [6, 0, 0.5, 12], [-2, -2, 6, 0.5], [2, 2, 6, 0.5], [0, 6, 6, 0.5]]) {
  const m = new THREE.Mesh(new THREE.BoxGeometry(w, 2.5, d), wallMat);
  m.position.set(x, 1.25, z);
  scene.add(m);
  walls.push(m);
}
const boxes = walls.map((m) => new THREE.Box3().setFromObject(m));

const hero = new THREE.Group();
const body = new THREE.Mesh(new THREE.CapsuleGeometry(0.3, 0.8, 4, 12), new THREE.MeshStandardMaterial({ color: '#ff7043' }));
body.position.y = 0.7;
const visor = new THREE.Mesh(new THREE.BoxGeometry(0.4, 0.12, 0.1), new THREE.MeshStandardMaterial({ color: '#263238' }));
visor.position.set(0, 1.0, 0.27);
hero.add(body, visor);
hero.position.set(0, 0, 4);
scene.add(hero);

// Camera state: orbit angles around the hero, a distance, and the smoothed position.
let camYaw = 0, camPitch = 0.35, camDist = 5;
cv.addEventListener('pointermove', (e) => {
  if (!active || !(e.buttons & 1)) return;
  camYaw -= e.movementX * 0.005;
  camPitch = THREE.MathUtils.clamp(camPitch + e.movementY * 0.004, -0.1, 1.2);
});
cv.addEventListener('wheel', (e) => { e.preventDefault(); camDist = THREE.MathUtils.clamp(camDist + e.deltaY * 0.005, 2.5, 9); }, { passive: false });

const raycaster = new THREE.Raycaster();
const lookAt = new THREE.Vector3(), desired = new THREE.Vector3(), dir = new THREE.Vector3();
const hud = document.getElementById('hud');
let heroYaw = 0, blocked = false;

function blockedAt(x, z) {
  const r = 0.3;
  return boxes.some((b) => x + r > b.min.x && x - r < b.max.x && z + r > b.min.z && z - r < b.max.z);
}

function updateCamera(dt, snap = false) {
  lookAt.set(hero.position.x, 1.4, hero.position.z);              // aim above the feet
  // Where the camera wants to be: behind the hero along the camera's yaw, raised by the pitch.
  dir.set(Math.sin(camYaw) * Math.cos(camPitch), Math.sin(camPitch), Math.cos(camYaw) * Math.cos(camPitch));
  let dist = camDist;
  // Collision: cast from the look-at point toward the camera; stop in front of the first wall.
  raycaster.set(lookAt, dir);
  raycaster.far = camDist;
  const hit = raycaster.intersectObjects(walls, false)[0];
  blocked = !!hit;
  if (hit) dist = Math.max(0.6, hit.distance - 0.25);
  desired.copy(lookAt).addScaledVector(dir, dist);
  if (snap || hit) camera.position.copy(desired);                  // never smooth *into* a wall
  else camera.position.lerp(desired, 1 - Math.exp(-10 * dt));
  camera.lookAt(lookAt);
}

run(scene, camera, (dt) => {
  const f = (keys.has('KeyW') || keys.has('ArrowUp') ? 1 : 0) - (keys.has('KeyS') || keys.has('ArrowDown') ? 1 : 0);
  const s = (keys.has('KeyD') || keys.has('ArrowRight') ? 1 : 0) - (keys.has('KeyA') || keys.has('ArrowLeft') ? 1 : 0);
  if (f || s) {
    // Camera-relative input: "forward" is away from the camera on the ground plane.
    const fx = -Math.sin(camYaw), fz = -Math.cos(camYaw), rx = Math.cos(camYaw), rz = -Math.sin(camYaw);
    let mx = fx * f + rx * s, mz = fz * f + rz * s;
    const len = Math.hypot(mx, mz);
    mx /= len; mz /= len;
    const step = 4 * dt;
    if (!blockedAt(hero.position.x + mx * step, hero.position.z)) hero.position.x += mx * step;   // slide per axis
    if (!blockedAt(hero.position.x, hero.position.z + mz * step)) hero.position.z += mz * step;
    // Turn the hero smoothly toward the movement direction (shortest way around).
    const want = Math.atan2(mx, mz);
    let diff = want - heroYaw;
    diff = Math.atan2(Math.sin(diff), Math.cos(diff));
    heroYaw += diff * (1 - Math.exp(-12 * dt));
    hero.rotation.y = heroYaw;
  }
  updateCamera(dt);
  hud.textContent = `camera distance ${camera.position.distanceTo(lookAt).toFixed(1)} m${blocked ? '  (pulled in by a wall)' : ''}`;
});
updateCamera(0, true);
</script>

Things to notice in updateCamera:

  • The collision ray goes from the character toward the camera, not the other way. Anything it hits within the camera distance is between the two, so the camera moves in front of it (minus a small margin, so the near plane doesn't clip into the wall).
  • When pulled in, the camera snaps instead of smoothing: smoothing would let it drift through the wall for a few frames. When the obstacle is gone, it eases back out.
  • The character turns toward its movement direction with atan2, wrapping the angle difference into −π…π so it always turns the short way.

Production cameras usually replace the single ray with a sphere cast (a thick ray, from the physics engine), so the camera also avoids corners and thin poles, and add a short delay before zooming back out.

Variations

Camera Change
Over-the-shoulder (aiming) offset the look-at point sideways (+0.5 m right), shorten the distance, narrow the FOV
Lock-on yaw the camera toward the midpoint of player and target
Auto-follow when the player isn't touching the camera, slowly ease camYaw toward the hero's back
Platformer follow position with damping, but keep the height steady until the player lands (no bobbing on every jump)
Top-down / isometric fixed rotation, follow only x/z with damping; an OrthographicCamera for the isometric look

Tip: Update the camera after the character moves, in the same update step. If the camera reads the character's position before it moves, the view lags one frame and jitters.

Test yourself

camera.position.lerp(target, 0.1) every frame makes the camera feel different on 60 Hz and 144 Hz screens. What is the frame-rate-independent factor?

  1. 0.1 * dt
  2. 1 - Math.exp(-sharpness * dt)
  3. Math.min(0.1, dt)
  4. 0.1 / 60

Which way should the camera-collision ray be cast?

  1. From the camera toward the character
  2. From the character (look-at point) toward the desired camera position, up to the camera distance
  3. Straight down from the camera
  4. From the camera along its view direction

Why does the demo move the hero along x and z separately when checking walls?

  1. It is faster
  2. So that when one axis is blocked, movement along the other still happens: the hero slides along walls
  3. Box3 only supports one axis
  4. To avoid gimbal lock