TExcelTAD
Home › 3D Web Games with Three.js › First-Person Controls

First-Person Controls

A first-person camera is the player's head: the mouse turns it, WASD moves it along the ground. Three parts make it feel right: mouse-look with yaw and clamped pitch, movement relative to where you look, and collision so you can't walk through walls.

Mouse-look: yaw and pitch

Store two angles, not a free rotation:

  • yaw: turning left/right, around the world's vertical (Y) axis, unlimited;
  • pitch: looking up/down, around the camera's own X axis, clamped to about ±85° so the view never flips over.

Apply them with the Euler order 'YXZ' (yaw first, then pitch in the turned frame) and never touch roll:

js
camera.rotation.order = 'YXZ';
// on mouse movement (dx, dy in pixels):
yaw -= dx * sensitivity;
pitch -= dy * sensitivity;
pitch = THREE.MathUtils.clamp(pitch, -1.48, 1.48);   // about ±85°
camera.rotation.set(pitch, yaw, 0);

Pointer lock and PointerLockControls

On a real web page, first-person games use the Pointer Lock API: the cursor disappears and mousemove events report unlimited relative motion (movementX, movementY), so the player can turn forever without the cursor hitting the screen edge. Three.js wraps this in PointerLockControls:

js
import { PointerLockControls } from 'three/addons/controls/PointerLockControls.js';

const controls = new PointerLockControls(camera, document.body);
startButton.addEventListener('click', () => controls.lock());   // must come from a user gesture
controls.addEventListener('lock', () => { menu.hidden = true; paused = false; });
controls.addEventListener('unlock', () => { menu.hidden = false; paused = true; });   // Esc unlocks

// in the update:
if (controls.isLocked) {
  controls.moveForward(input.forward * speed * dt);   // along the view direction, flattened to the ground
  controls.moveRight(input.right * speed * dt);
}

The browser always lets the player press Esc to release the lock, and you can't prevent that, so treat unlock as "open the pause menu". controls.lock(true) asks for unadjusted (raw, unaccelerated) mouse movement where the browser supports it, which competitive players prefer. minPolarAngle/maxPolarAngle limit the pitch and pointerSpeed scales the sensitivity.

Note: Pointer lock doesn't work in this course's playgrounds: they run in sandboxed iframes without the allow-pointer-lock permission, so requestPointerLock() fails with a SecurityError. If you embed your own game in an iframe (itch.io, a portal), the host page's iframe needs allow="pointer-lock" / sandbox="… allow-pointer-lock". The demo below uses drag-to-look instead, which needs no permission and is also how many mobile and casual games work.

Movement relative to the view

Movement uses only the yaw: looking at the floor shouldn't slow you down or make you dig into the ground. Build forward and right vectors on the ground plane from the yaw and combine them with the input:

js · try it yourself
// Ground-plane movement from yaw (radians) and input (-1..1). Three.js: camera looks down -Z.
function moveVector(yaw, forwardInput, rightInput) {
  const fx = -Math.sin(yaw), fz = -Math.cos(yaw);    // forward on the ground
  const rx = Math.cos(yaw), rz = -Math.sin(yaw);     // right on the ground
  let x = fx * forwardInput + rx * rightInput;
  let z = fz * forwardInput + rz * rightInput;
  const len = Math.hypot(x, z);
  if (len > 1) { x /= len; z /= len; }               // diagonal is not faster
  const f = (n) => (Math.abs(n) < 0.005 ? 0 : n).toFixed(2);   // avoid printing -0.00
  return `(${f(x)}, ${f(z)})`;
}
const deg = (d) => d * Math.PI / 180;
console.log('yaw   0, W     ->', moveVector(0, 1, 0));
console.log('yaw   0, D     ->', moveVector(0, 0, 1));
console.log('yaw  90, W     ->', moveVector(deg(90), 1, 0));
console.log('yaw   0, W + D ->', moveVector(0, 1, 1));
console.log('yaw 180, S     ->', moveVector(deg(180), -1, 0));
yaw   0, W     -> (0.00, -1.00)
yaw   0, D     -> (1.00, 0.00)
yaw  90, W     -> (-1.00, 0.00)
yaw   0, W + D -> (0.71, -0.71)
yaw 180, S     -> (0.00, -1.00)

With yaw 0 the camera looks down −Z, so W moves toward −Z and D toward +X; a positive yaw turns left (counter-clockwise seen from above), so W then moves toward −X. Normalizing the combined input stops the old bug where running diagonally is 41% faster.

Walk around

Click the scene, drag to look around, WASD or arrows to walk, Shift to run. The pillars and the walls block you: the player is a circle on the ground that is pushed out of anything it overlaps.

html · try it yourself
<style>
  html, body { margin: 0; height: 100%; overflow: hidden; background: #0e1018; }
  canvas { display: block; outline: none; touch-action: none; cursor: grab; }
  #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; }
  #cross { position: fixed; left: 50%; top: 50%; width: 6px; height: 6px; margin: -3px; border-radius: 50%; background: rgba(255,255,255,.8); pointer-events: none; }
</style>
<div id="hud"></div><div id="cross"></div>
<div id="veil">Click to play<small>drag to look, WASD to walk, Shift to run</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('#87a9c9');
scene.fog = new THREE.Fog('#87a9c9', 10, 32);
const camera = new THREE.PerspectiveCamera(70, innerWidth / innerHeight, 0.05, 100);
camera.rotation.order = 'YXZ';
scene.add(new THREE.HemisphereLight('#e6f0ff', '#5b4a3a', 1.6));
const sun = new THREE.DirectionalLight('#fff3e0', 2);
sun.position.set(-4, 10, 6);
scene.add(sun);

// A walled courtyard with pillars. Colliders: circles (pillars) and the square boundary.
const SIZE = 12;
const floor = new THREE.Mesh(new THREE.PlaneGeometry(SIZE * 2, SIZE * 2), new THREE.MeshStandardMaterial({ color: '#8d8473' }));
floor.rotation.x = -Math.PI / 2;
scene.add(floor);
const wallMat = new THREE.MeshStandardMaterial({ color: '#b9ae99' });
for (const [x, z, w, d] of [[0, -SIZE, SIZE * 2, 0.6], [0, SIZE, SIZE * 2, 0.6], [-SIZE, 0, 0.6, SIZE * 2], [SIZE, 0, 0.6, SIZE * 2]]) {
  const wall = new THREE.Mesh(new THREE.BoxGeometry(w, 3, d), wallMat);
  wall.position.set(x, 1.5, z);
  scene.add(wall);
}
const pillars = [];
const pillarGeo = new THREE.CylinderGeometry(0.6, 0.7, 4, 20);
const pillarMat = new THREE.MeshStandardMaterial({ color: '#d7cdb8' });
for (let i = 0; i < 4; i++) for (let j = 0; j < 4; j++) {
  const x = -6 + i * 4, z = -6 + j * 4;
  const p = new THREE.Mesh(pillarGeo, pillarMat);
  p.position.set(x, 2, z);
  scene.add(p);
  pillars.push({ x, z, r: 0.7 });
}

// Drag-to-look: pointer movement while a button is held changes yaw and pitch.
let yaw = Math.PI / 4, pitch = -0.1;
const SENS = 0.004;                               // radians per pixel
cv.addEventListener('pointermove', (e) => {
  if (!active || !(e.buttons & 1)) return;
  yaw -= e.movementX * SENS;
  pitch = THREE.MathUtils.clamp(pitch - e.movementY * SENS, -1.48, 1.48);
});

const player = { x: 0, z: 2, r: 0.35, eye: 1.6 };
const hud = document.getElementById('hud');
let bob = 0;
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);
  let mx = -Math.sin(yaw) * f + Math.cos(yaw) * s;
  let mz = -Math.cos(yaw) * f - Math.sin(yaw) * s;
  const len = Math.hypot(mx, mz);
  if (len > 1) { mx /= len; mz /= len; }
  const speed = keys.has('ShiftLeft') || keys.has('ShiftRight') ? 6 : 3.5;
  player.x += mx * speed * dt;
  player.z += mz * speed * dt;

  // Collision: push the player's circle out of each pillar, then clamp inside the walls.
  for (const p of pillars) {
    const dx = player.x - p.x, dz = player.z - p.z, d = Math.hypot(dx, dz), min = p.r + player.r;
    if (d < min && d > 1e-6) { player.x = p.x + (dx / d) * min; player.z = p.z + (dz / d) * min; }
  }
  const lim = SIZE - 0.3 - player.r;
  player.x = THREE.MathUtils.clamp(player.x, -lim, lim);
  player.z = THREE.MathUtils.clamp(player.z, -lim, lim);

  bob += len > 0 ? dt * speed * 2.2 : 0;           // a subtle head bob while walking
  camera.position.set(player.x, player.eye + Math.sin(bob) * 0.04, player.z);
  camera.rotation.set(pitch, yaw, 0);
  hud.textContent = `yaw ${THREE.MathUtils.radToDeg(yaw).toFixed(0)}°  pitch ${THREE.MathUtils.radToDeg(pitch).toFixed(0)}°`;
});
camera.position.set(player.x, player.eye, player.z);
camera.rotation.set(pitch, yaw, 0);
</script>

Because the pillars are pushed against and not simply blocked, you slide along them when you walk in at an angle, which feels much better than stopping dead. Physics engines do this for you with a character controller (Character Controller).

Making it feel good

Detail Typical value / technique
Field of view 70–90° vertical in first person; offer a setting
Mouse sensitivity a setting, plus "invert Y"; apply it to movementX/Y
Near plane small (0.05) so walls don't clip when you stand against them
Eye height about 1.6–1.7 m for a standing adult
Acceleration ramp speed up/down over ~0.1 s instead of instant start/stop
Head bob, FOV kick when sprinting subtle, and with an option to turn them off (motion sickness)
Weapon / hands render them in a second pass (or with a separate camera layer) so they never clip into walls

Test yourself

Why do first-person cameras use camera.rotation.order = 'YXZ'?

  1. It is required by PointerLockControls
  2. Yaw is applied around world up, then pitch around the turned camera's X axis, so the horizon never tilts
  3. It prevents z-fighting
  4. It is faster to compute

Why does the demo use drag-to-look instead of pointer lock?

  1. Pointer lock is deprecated
  2. The playground iframe is sandboxed without allow-pointer-lock, so requestPointerLock() fails
  3. Three.js has no pointer lock support
  4. Drag-to-look is more precise

The player moves 41% faster when holding W and D together. What fixes it?

  1. Halve the speed
  2. Normalize the combined movement vector when its length exceeds 1
  3. Use quaternions
  4. Clamp the pitch