TExcelTAD
Home › 3D Web Games with Three.js › Character Controller

Character Controller

A player character is not a crate. A dynamic rigid body capsule tips over, slides down gentle slopes, bounces off steps, gets launched by physics glitches and never stops exactly where the player let go. Almost every game therefore moves its characters kinematically: the game decides the movement, and a character controller only checks it against the world, sliding along walls, climbing steps and slopes, and snapping to the ground. Rapier ships one: KinematicCharacterController.

How it works

Each fixed step:

  1. Compute the desired movement for this step from input, speed and vertical velocity (gravity, jumps): desired = velocity * dt.
  2. Ask the controller what is actually possible: controller.computeColliderMovement(collider, desired). It sweeps the character's collider through the world and returns a corrected movement that slides along obstacles.
  3. Apply it: body.setNextKinematicTranslation(position + corrected).
  4. Read controller.computedGrounded() to know whether the character stands on something (to reset vertical speed and allow jumps).
js
const body = world.createRigidBody(RAPIER.RigidBodyDesc.kinematicPositionBased().setTranslation(0, 2, 0));
const collider = world.createCollider(RAPIER.ColliderDesc.capsule(0.5, 0.35), body);   // 1.7 m tall in total

const controller = world.createCharacterController(0.02);   // skin: a small gap kept from obstacles
controller.enableAutostep(0.4, 0.2, true);   // climb steps up to 0.4 m high, needing 0.2 m free width, also onto dynamic bodies
controller.enableSnapToGround(0.3);          // stick to the ground when walking down slopes and steps up to 0.3 m
controller.setMaxSlopeClimbAngle(THREE.MathUtils.degToRad(45));
controller.setMinSlopeSlideAngle(THREE.MathUtils.degToRad(35));
controller.setApplyImpulsesToDynamicBodies(true);   // push crates around

Jump maths

Designers think in jump height and time to apex, not in gravity and initial velocity. Derive the physics from the design values (constant acceleration: h = v²/2g and t = v/g):

js · try it yourself
// From design values (height in m, time to apex in s) to gravity and jump velocity.
function jumpParams(height, timeToApex) {
  const gravity = (2 * height) / (timeToApex * timeToApex);
  const velocity = gravity * timeToApex;
  return { gravity, velocity };
}
for (const [h, t] of [[1.2, 0.4], [1.2, 0.3], [2.5, 0.45]]) {
  const { gravity, velocity } = jumpParams(h, t);
  console.log(`height ${h} m, apex after ${t} s -> gravity ${gravity.toFixed(2)} m/s², jump speed ${velocity.toFixed(2)} m/s`);
}
// Check by simulating at 60 Hz with semi-implicit Euler:
const { gravity, velocity } = jumpParams(1.2, 0.4);
let y = 0, vy = velocity, peak = 0;
for (let i = 0; i < 60; i++) { vy -= gravity / 60; y += vy / 60; peak = Math.max(peak, y); }
console.log(`simulated peak ${peak.toFixed(3)} m (discrete steps land slightly below the exact 1.2)`);
height 1.2 m, apex after 0.4 s -> gravity 15.00 m/s², jump speed 6.00 m/s
height 1.2 m, apex after 0.3 s -> gravity 26.67 m/s², jump speed 8.00 m/s
height 2.5 m, apex after 0.45 s -> gravity 24.69 m/s², jump speed 11.11 m/s
simulated peak 1.150 m (discrete steps land slightly below the exact 1.2)

Game gravity is usually much stronger than 9.81 m/s²: real-world jumps feel floaty in a game. Many games also increase gravity while falling (snappier landings) and cut the upward speed when the jump button is released early (variable jump height). The Platformer lessons cover coyote time and jump buffering, which apply unchanged in 3D.

Play it

A small obstacle course: walk with WASD, jump with Space. Try the stairs (auto-step), the ramp (slope limit: the steep one can't be climbed), the low wall (too high to step onto, so jump), and push the crates (impulses on dynamic bodies). The HUD shows whether the controller reports the character as grounded.

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 move, Space to jump</small></div>
<script type="module">
import * as THREE from 'three';
import RAPIER from '@dimforge/rapier3d-compat';
await RAPIER.init();

// ---- 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('#a9c6e4');
const camera = new THREE.PerspectiveCamera(55, innerWidth / innerHeight, 0.1, 100);
scene.add(new THREE.HemisphereLight('#eef4ff', '#5b5043', 1.5));
const sun = new THREE.DirectionalLight('#fff', 2);
sun.position.set(-4, 10, 6);
scene.add(sun);

const world = new RAPIER.World({ x: 0, y: -9.81, z: 0 });
world.timestep = 1 / 60;

// Static level pieces: a mesh and a matching fixed collider for each box.
function block(w, h, d, x, y, z, color, rotZ = 0) {
  const mesh = new THREE.Mesh(new THREE.BoxGeometry(w, h, d), new THREE.MeshStandardMaterial({ color }));
  mesh.position.set(x, y, z);
  mesh.rotation.z = rotZ;
  scene.add(mesh);
  world.createCollider(RAPIER.ColliderDesc.cuboid(w / 2, h / 2, d / 2).setTranslation(x, y, z)
    .setRotation(new THREE.Quaternion().setFromEuler(mesh.rotation)));
}
block(30, 1, 30, 0, -0.5, 0, '#7da36a');                                 // ground (top at y = 0)
for (let i = 0; i < 5; i++) block(1, 0.3 * (i + 1), 2, -6 + i, 0.15 * (i + 1), -3, '#c9b99a');   // stairs, 0.3 m steps
block(1, 2, 2, -1, 0.75, -3, '#c9b99a');                                 // landing, top at 1.75 m
block(4, 0.3, 2, 3, 1, -3, '#d0a274', 0.4);                              // gentle ramp, ~23°
block(4, 0.3, 2, 3, 1.4, 1.5, '#b5674d', 1.0);                           // steep ramp, ~57°: too steep
block(0.4, 0.8, 4, -4, 0.4, 3, '#8e8e9a');                               // low wall: jump over it

// Dynamic crates to push.
const crates = [];
for (const [x, y, z] of [[1, 0.5, 4], [2.1, 0.5, 4], [1.55, 1.5, 4]]) {     // two crates and one on top
  const body = world.createRigidBody(RAPIER.RigidBodyDesc.dynamic().setTranslation(x, y, z));
  world.createCollider(RAPIER.ColliderDesc.cuboid(0.5, 0.5, 0.5).setDensity(0.5), body);
  const mesh = new THREE.Mesh(new THREE.BoxGeometry(1, 1, 1), new THREE.MeshStandardMaterial({ color: '#c58a3c' }));
  scene.add(mesh);
  crates.push({ body, mesh });
}

// The character: a kinematic body with a capsule collider and Rapier's controller.
const HALF = 0.5, RADIUS = 0.35;
const body = world.createRigidBody(RAPIER.RigidBodyDesc.kinematicPositionBased().setTranslation(0, 1, 4));
const collider = world.createCollider(RAPIER.ColliderDesc.capsule(HALF, RADIUS), body);
const controller = world.createCharacterController(0.02);
controller.enableAutostep(0.35, 0.2, true);
controller.enableSnapToGround(0.3);
controller.setMaxSlopeClimbAngle(THREE.MathUtils.degToRad(45));
controller.setMinSlopeSlideAngle(THREE.MathUtils.degToRad(40));
controller.setApplyImpulsesToDynamicBodies(true);
const hero = new THREE.Mesh(new THREE.CapsuleGeometry(RADIUS, HALF * 2, 4, 12), new THREE.MeshStandardMaterial({ color: '#ff7043' }));
scene.add(hero);

const GRAVITY = 20, JUMP = 7.5, SPEED = 4.5;
let vy = 0, grounded = false;
const hud = document.getElementById('hud');
const camOffset = new THREE.Vector3(0, 6, 8), camTarget = new THREE.Vector3();

function sync() {
  const p = body.translation();
  hero.position.set(p.x, p.y, p.z);
  for (const c of crates) {
    const t = c.body.translation(), q = c.body.rotation();
    c.mesh.position.set(t.x, t.y, t.z);
    c.mesh.quaternion.set(q.x, q.y, q.z, q.w);
  }
}

run(scene, camera, (dt) => {
  const ix = (keys.has('KeyD') || keys.has('ArrowRight') ? 1 : 0) - (keys.has('KeyA') || keys.has('ArrowLeft') ? 1 : 0);
  const iz = (keys.has('KeyS') || keys.has('ArrowDown') ? 1 : 0) - (keys.has('KeyW') || keys.has('ArrowUp') ? 1 : 0);
  const len = Math.hypot(ix, iz) || 1;
  if (grounded && vy < 0) vy = 0;                         // standing: no accumulated fall speed
  if (grounded && pressed.has('Space')) vy = JUMP;
  vy -= GRAVITY * dt;
  const desired = { x: (ix / len) * SPEED * dt, y: vy * dt, z: (iz / len) * SPEED * dt };

  controller.computeColliderMovement(collider, desired);  // sweep the capsule, slide, step, snap
  const move = controller.computedMovement();
  grounded = controller.computedGrounded();
  if (!grounded && move.y > desired.y + 1e-4 && vy > 0) vy = 0;   // bumped our head: stop rising
  const p = body.translation();
  body.setNextKinematicTranslation({ x: p.x + move.x, y: p.y + move.y, z: p.z + move.z });
  world.step();
  sync();

  camTarget.copy(hero.position).add(camOffset);
  camera.position.lerp(camTarget, 1 - Math.exp(-6 * dt));
  camera.lookAt(hero.position.x, hero.position.y + 0.5, hero.position.z);
  hud.textContent = `grounded: ${grounded ? 'yes' : 'no'}   height ${hero.position.y.toFixed(2)} m`;
});
sync();
camera.position.copy(hero.position).add(camOffset);
camera.lookAt(hero.position);
</script>

The update order matters: compute the movement, set the next kinematic translation, then world.step(), then copy positions to meshes. The kinematic body only reaches its new position during the step, which is also when it pushes the crates.

Controller options

Method Purpose
createCharacterController(offset) offset: a small gap (skin) kept between the character and obstacles, avoids getting stuck
enableAutostep(maxHeight, minWidth, includeDynamicBodies) climb steps automatically
enableSnapToGround(distance) keep contact going down slopes and stairs instead of "skiing" off
setMaxSlopeClimbAngle(rad) / setMinSlopeSlideAngle(rad) which slopes can be walked up; on which ones the character slides down
setSlideEnabled(bool) slide along obstacles (default on)
setApplyImpulsesToDynamicBodies(bool), setCharacterMass(kg) push dynamic objects
computedGrounded() standing on something after the last computation
numComputedCollisions(), computedCollision(i) what was hit this step (enemies, walls)
setUp(vector) a different "up" (walls, planets)
computeColliderMovement(collider, desired, filterFlags, filterGroups) the optional filters choose what blocks the character; pass RAPIER.QueryFilterFlags.EXCLUDE_SENSORS or sensors (coins, trigger zones) act as walls (Triggers)

Design checklist

  • Acceleration and friction: real controllers ramp horizontal speed up and down (v = moveTowards(v, target, accel * dt)), with less control in the air.
  • Rotate the visual, not the collider: the capsule never rotates; turn the mesh toward the movement direction.
  • Coyote time and jump buffering: allow a jump for ~0.1 s after leaving a ledge, and remember a jump pressed ~0.1 s before landing.
  • Moving platforms: add the platform's movement for this step to the character's desired movement while standing on it.
  • Ceilings: as in the demo, zero the upward speed when the controller cuts the vertical movement.

Test yourself

Why are player characters usually kinematic bodies with a character controller rather than dynamic rigid bodies?

  1. Dynamic bodies can't collide
  2. The game needs exact, responsive control; dynamic capsules tip over, slide on slopes and react unpredictably to collisions
  3. Kinematic bodies are cheaper to render
  4. Rapier forbids dynamic characters

Designers want a 1.2 m jump that peaks after 0.4 s. What gravity does that need?

  1. 9.81 m/s²
  2. 15 m/s²
  3. 6 m/s²
  4. 30 m/s²

What does enableSnapToGround(0.3) prevent?

  1. Falling through the floor
  2. The character briefly leaving the ground (and losing 'grounded') when walking down slopes or steps
  3. Climbing steep slopes
  4. Pushing crates