Explorer 4: Menu, Pause & Sound
The game works; now it needs to feel finished. A stranger who opens it should see a title screen that says what to do, be able to pause, hear what happens, get a proper ending, and want to beat their time. This last step adds:
- a state machine with title, playing, paused and won states, and an HTML menu for each screen;
- pause with P or Esc (and the play kit's automatic pause when the game loses focus);
- sound effects synthesized with the Web Audio API, a volume slider, and the user-gesture rule;
- a best time saved with a storage fallback, and restart without reloading.
The screens as states
title --Play--> playing --P/Esc--> paused --Resume--> playing
|
+--enter open portal--> won --Play again--> playing (reset)state is one of 'title' | 'playing' | 'paused' | 'won'. The update runs only in 'playing'; in every other state the scene still renders behind a semi-transparent menu, which makes a nice living background. One function, showMenu(html, buttonLabel, onClick), fills the #menu overlay for every screen, so the title, pause and win screens share their markup, style and volume slider.
Two details connect the menus to the play kit:
- Clicking a menu button moves keyboard focus to the button, which blurs the canvas, and the play kit stops updating. So every button that returns to the game calls
cv.focus()(inresume()). - While a menu is open, the play kit's own "click to continue" veil would be redundant, so a CSS rule hides it:
body:has(#menu:not(.off)) #veil { display: none; }.
Restart without reloading
reset() puts every piece of mutable game state back: counters, the hero's physics body (setTranslation plus setNextKinematicTranslation, so the kinematic body doesn't interpolate back across the map), crystals (visible again, colliders re-enabled), the portal, the camera yaw. The rule that makes this easy: keep all mutable state in a few obvious variables, and build the static world once. Reloading the page to restart works in a jam, but it re-downloads and recompiles everything, and loses audio permission.
Sound with Web Audio, no files
The effects are made from oscillators: tone(freq, start, duration, type, gain) schedules a short beep with an exponential fade, and each effect is a few tones (a two-note blip for a jump, a rising arpeggio for a crystal, a chord when the portal opens, a fanfare for the win). Everything goes through one master gain node, which the volume slider controls.
Browsers only let a page start audio after a user gesture (a click or key press), and in an iframe the frame itself must receive it. So the AudioContext is created in the menu button's click handler (initAudio()), and resumed there if the browser suspended it. Effects requested before that (there are none here, but a game with a title-screen jingle has to think about it) are silently skipped by tone().
For real games, load recorded sounds instead: THREE.AudioListener on the camera plus THREE.PositionalAudio on objects gives 3D sound that pans and fades with distance, and libraries like howler.js handle formats, sprites and mobile quirks. The structure (one master volume, effects triggered by game events) stays the same.
Saving the best time
The best time goes through the same storage wrapper as Settings & Saving: try localStorage once and, if it throws (it does in this course's sandboxed playgrounds), fall back to an in-memory Map. The game code only calls store.get and store.set, and the win screen shows "new best!" when you beat it. On your own site, the record survives reloads.
Play it
<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; }
#menu { position: fixed; inset: 0; display: grid; place-content: center; gap: 8px; background: rgba(8, 12, 20, 0.78); color: #fff; font: 14px system-ui, sans-serif; text-align: center; }
#menu.off { display: none; }
body:has(#menu:not(.off)) #veil { display: none; } /* a menu replaces the pause veil */
#menu h1 { margin: 0; font-size: 24px; } #menu p { margin: 0; color: #c8d3e0; }
#menu button { justify-self: center; padding: 6px 18px; font: 600 14px system-ui, sans-serif; border: 0; border-radius: 6px; background: #4fc3f7; cursor: pointer; }
</style>
<div id="hud"></div>
<div id="veil">Paused<small>click the game to continue</small></div>
<div id="menu"></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 ----
// ---------- seeded random numbers ----------
function mulberry32(seed) {
return () => {
seed |= 0; seed = (seed + 0x6d2b79f5) | 0;
let t = Math.imul(seed ^ (seed >>> 15), 1 | seed);
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
const rng = mulberry32(2024);
// ---------- scene, lights ----------
renderer.shadowMap.enabled = true;
const scene = new THREE.Scene();
scene.background = new THREE.Color('#9fc6ea');
scene.fog = new THREE.Fog('#9fc6ea', 25, 70);
const camera = new THREE.PerspectiveCamera(60, innerWidth / innerHeight, 0.1, 150);
scene.add(new THREE.HemisphereLight('#e4f0ff', '#58704a', 1.4));
const sun = new THREE.DirectionalLight('#fff3dd', 2.4);
sun.castShadow = true;
sun.shadow.mapSize.set(1024, 1024);
Object.assign(sun.shadow.camera, { left: -14, right: 14, top: 14, bottom: -14, near: 1, far: 60 });
sun.shadow.normalBias = 0.03;
scene.add(sun, sun.target);
const SUN_OFFSET = new THREE.Vector3(-12, 20, 8);
// ---------- physics world ----------
const world = new RAPIER.World({ x: 0, y: -9.81, z: 0 });
const events = new RAPIER.EventQueue(true);
const blockers = []; // meshes the camera must not pass through
function solid(mesh, colliderDesc) { // a static mesh + its fixed collider
mesh.castShadow = mesh.receiveShadow = true;
scene.add(mesh);
blockers.push(mesh);
world.createCollider(colliderDesc.setTranslation(mesh.position.x, mesh.position.y, mesh.position.z)
.setRotation(mesh.quaternion));
}
// ---------- the world ----------
const HALF = 30; // the meadow spans -30..30
const ground = new THREE.Mesh(new THREE.PlaneGeometry(HALF * 2, HALF * 2), new THREE.MeshStandardMaterial({ color: '#6f9e58' }));
ground.rotation.x = -Math.PI / 2;
ground.receiveShadow = true;
scene.add(ground);
world.createCollider(RAPIER.ColliderDesc.cuboid(HALF, 0.5, HALF).setTranslation(0, -0.5, 0));
const stone = new THREE.MeshStandardMaterial({ color: '#a39a8a', roughness: 0.9 });
for (const [x, z, w, d] of [[0, -HALF, HALF * 2, 1], [0, HALF, HALF * 2, 1], [-HALF, 0, 1, HALF * 2], [HALF, 0, 1, HALF * 2]]) {
const wall = new THREE.Mesh(new THREE.BoxGeometry(w, 1, d), stone);
wall.position.set(x, 0.5, z);
solid(wall, RAPIER.ColliderDesc.cuboid(w / 2, 2, d / 2)); // the collider is taller than it looks
}
// Plateaus: one with stairs, one with a ramp, one you must jump onto.
const rock = new THREE.MeshStandardMaterial({ color: '#8d8577', roughness: 0.95 });
function box(w, h, d, x, y, z, mat, rotX = 0) {
const m = new THREE.Mesh(new THREE.BoxGeometry(w, h, d), mat);
m.position.set(x, y, z);
m.rotation.x = rotX;
solid(m, RAPIER.ColliderDesc.cuboid(w / 2, h / 2, d / 2));
return m;
}
box(6, 1.6, 6, -16, 0.8, -14, rock); // plateau A, top 1.6
for (let i = 0; i < 4; i++) box(2, 0.4 * (i + 1), 1, -16, 0.2 * (i + 1), -8.5 - i, rock); // its stairs
box(6, 2.4, 6, 16, 1.2, -14, rock); // plateau B, top 2.4
box(2.5, 0.3, 7, 16, 1.15, -7.6, rock, 0.37); // its ramp (~21°)
box(4, 1.1, 4, 15, 0.55, 14, rock); // plateau C, top 1.1: jump
// Ruins around the shrine.
for (const [x, z, w, d] of [[-5, -5, 4, 0.6], [5, -5, 4, 0.6], [-5, 5, 0.6, 4], [5, 5, 0.6, 3]]) box(w, 1.8, d, x, 0.9, z, stone);
// Trees and rocks, scattered with the seeded RNG, away from the important places.
const keepClear = [[0, 0, 8], [-16, -12, 6], [16, -11, 6], [15, 14, 4]];
function freeSpot(margin) {
for (;;) {
const x = (rng() * 2 - 1) * (HALF - 3), z = (rng() * 2 - 1) * (HALF - 3);
if (keepClear.every(([cx, cz, r]) => Math.hypot(x - cx, z - cz) > r + margin)) return [x, z];
}
}
const trunkGeo = new THREE.CylinderGeometry(0.2, 0.3, 1.6, 8);
const leafGeo = new THREE.ConeGeometry(1.3, 3, 8);
const trunkMat = new THREE.MeshStandardMaterial({ color: '#6b4a2b' });
const leafMat = new THREE.MeshStandardMaterial({ color: '#2f6e3a', flatShading: true });
for (let i = 0; i < 34; i++) {
const [x, z] = freeSpot(1.5);
const s = 0.8 + rng() * 0.6;
const trunk = new THREE.Mesh(trunkGeo, trunkMat);
trunk.position.set(x, 0.8 * s, z);
trunk.scale.setScalar(s);
const leaves = new THREE.Mesh(leafGeo, leafMat);
leaves.position.set(x, (1.6 + 1.3) * s, z);
leaves.scale.setScalar(s);
leaves.castShadow = true;
scene.add(leaves);
solid(trunk, RAPIER.ColliderDesc.cylinder(0.8 * s, 0.35 * s));
}
const rockGeo = new THREE.IcosahedronGeometry(1, 0);
for (let i = 0; i < 14; i++) {
const [x, z] = freeSpot(1.5);
const r = 0.5 + rng() * 0.8;
const m = new THREE.Mesh(rockGeo, rock);
m.position.set(x, r * 0.5, z);
m.scale.setScalar(r);
m.rotation.set(rng() * 3, rng() * 3, 0);
solid(m, RAPIER.ColliderDesc.ball(r * 0.9));
}
// ---------- the hero: a little explorer built from primitives ----------
const hero = new THREE.Group();
const skin = new THREE.MeshStandardMaterial({ color: '#f1c27d' });
const cloth = new THREE.MeshStandardMaterial({ color: '#e86a3a' });
const dark = new THREE.MeshStandardMaterial({ color: '#3b3f4a' });
const torso = new THREE.Mesh(new THREE.CapsuleGeometry(0.28, 0.45, 4, 12), cloth);
torso.position.y = 1.0;
const head = new THREE.Mesh(new THREE.SphereGeometry(0.22, 16, 12), skin);
head.position.y = 1.55;
const pack = new THREE.Mesh(new THREE.BoxGeometry(0.4, 0.45, 0.2), dark);
pack.position.set(0, 1.05, -0.3);
function limb(w, h, x, y, mat) { // a box hanging from a pivot at its top
const pivot = new THREE.Group();
pivot.position.set(x, y, 0);
const m = new THREE.Mesh(new THREE.BoxGeometry(w, h, w), mat);
m.position.y = -h / 2;
m.castShadow = true;
pivot.add(m);
hero.add(pivot);
return pivot;
}
const legL = limb(0.16, 0.6, -0.13, 0.62, dark), legR = limb(0.16, 0.6, 0.13, 0.62, dark);
const armL = limb(0.12, 0.5, -0.38, 1.3, cloth), armR = limb(0.12, 0.5, 0.38, 1.3, cloth);
for (const m of [torso, head, pack]) m.castShadow = true;
hero.add(torso, head, pack);
scene.add(hero);
// Physics body for the hero: a kinematic capsule driven by Rapier's character controller.
const CAPSULE_HALF = 0.5, CAPSULE_R = 0.32, FOOT = CAPSULE_HALF + CAPSULE_R; // centre is FOOT above the ground
const START = new THREE.Vector3(0, FOOT + 0.05, 9);
const heroBody = world.createRigidBody(RAPIER.RigidBodyDesc.kinematicPositionBased().setTranslation(START.x, START.y, START.z));
const heroCol = world.createCollider(RAPIER.ColliderDesc.capsule(CAPSULE_HALF, CAPSULE_R), heroBody);
const controller = world.createCharacterController(0.02);
controller.enableAutostep(0.45, 0.2, false);
controller.enableSnapToGround(0.3);
controller.setMaxSlopeClimbAngle(THREE.MathUtils.degToRad(40));
// ---------- crystals and the portal ----------
const SENSOR = RAPIER.ActiveCollisionTypes.DEFAULT | RAPIER.ActiveCollisionTypes.KINEMATIC_FIXED;
const crystalGeo = new THREE.OctahedronGeometry(0.4);
const crystalMat = new THREE.MeshStandardMaterial({ color: '#7fe3ff', emissive: '#1f86b0', emissiveIntensity: 1.2, roughness: 0.2 });
const crystals = [];
const sensorOwner = new Map(); // collider handle -> crystal or 'portal'
const CRYSTAL_SPOTS = [[-16, 2.4, -14], [16, 3.2, -14], [15, 1.9, 14], [-22, 0.9, 18], [24, 0.9, 2], [0, 0.9, -3.5]];
for (const [x, y, z] of CRYSTAL_SPOTS) {
const mesh = new THREE.Mesh(crystalGeo, crystalMat);
mesh.position.set(x, y, z);
mesh.castShadow = true;
scene.add(mesh);
const col = world.createCollider(RAPIER.ColliderDesc.ball(0.7).setTranslation(x, y, z).setSensor(true)
.setActiveEvents(RAPIER.ActiveEvents.COLLISION_EVENTS).setActiveCollisionTypes(SENSOR));
const crystal = { mesh, col, baseY: y, taken: false };
sensorOwner.set(col.handle, crystal);
crystals.push(crystal);
}
const portalMat = new THREE.MeshStandardMaterial({ color: '#555b66', emissive: '#000000', roughness: 0.4 });
const portal = new THREE.Mesh(new THREE.TorusGeometry(1.3, 0.18, 12, 40), portalMat);
portal.position.set(0, 1.5, 0);
portal.castShadow = true;
scene.add(portal);
const portalCore = new THREE.Mesh(new THREE.CircleGeometry(1.15, 32), new THREE.MeshBasicMaterial({ color: '#b6f0ff', transparent: true, opacity: 0, side: THREE.DoubleSide, depthWrite: false }));
portalCore.position.copy(portal.position);
scene.add(portalCore);
const portalCol = world.createCollider(RAPIER.ColliderDesc.cuboid(1, 1.5, 0.6).setTranslation(0, 1.5, 0).setSensor(true)
.setActiveEvents(RAPIER.ActiveEvents.COLLISION_EVENTS).setActiveCollisionTypes(SENSOR));
sensorOwner.set(portalCol.handle, 'portal');
// Pickup sparkles: a small pool of points that fly outward and fade.
const SPARKS = 40;
const sparkPos = new Float32Array(SPARKS * 3), sparkVel = new Float32Array(SPARKS * 3);
const sparkGeo = new THREE.BufferGeometry();
sparkGeo.setAttribute('position', new THREE.BufferAttribute(sparkPos, 3));
const sparkMat = new THREE.PointsMaterial({ color: '#bff4ff', size: 0.15, transparent: true, opacity: 0, depthWrite: false });
const sparks = new THREE.Points(sparkGeo, sparkMat);
sparks.frustumCulled = false;
scene.add(sparks);
let sparkLife = 0;
function burst(at) {
for (let i = 0; i < SPARKS; i++) {
sparkPos.set([at.x, at.y, at.z], i * 3);
const a = rng() * Math.PI * 2, up = rng() * 4 + 1, out = rng() * 3 + 1;
sparkVel.set([Math.cos(a) * out, up, Math.sin(a) * out], i * 3);
}
sparkLife = 0.8;
}
// ---------- sound: tiny synthesized effects (Web Audio needs a user gesture first) ----------
let audio = null, master = null, volume = 0.5;
function initAudio() {
if (audio) { if (audio.state === 'suspended') audio.resume(); return; }
audio = new AudioContext();
master = audio.createGain();
master.gain.value = volume;
master.connect(audio.destination);
}
function tone(freq, start, dur, type = 'sine', gain = 0.3) {
if (!audio) return;
const t0 = audio.currentTime + start;
const osc = audio.createOscillator(), g = audio.createGain();
osc.type = type;
osc.frequency.setValueAtTime(freq, t0);
g.gain.setValueAtTime(gain, t0);
g.gain.exponentialRampToValueAtTime(0.001, t0 + dur);
osc.connect(g).connect(master);
osc.start(t0);
osc.stop(t0 + dur);
}
const sfx = {
jump: () => { tone(330, 0, 0.12, 'square', 0.08); tone(495, 0.05, 0.1, 'square', 0.06); },
pickup: () => { tone(880, 0, 0.12, 'triangle'); tone(1320, 0.08, 0.2, 'triangle'); },
portal: () => [523, 659, 784, 1047].forEach((f, i) => tone(f, i * 0.09, 0.5, 'sine', 0.2)),
win: () => [523, 659, 784, 659, 784, 1047].forEach((f, i) => tone(f, i * 0.12, 0.35, 'triangle', 0.25)),
};
// ---------- saving the best time (sandboxed frames block localStorage: fall back to memory) ----------
const store = (() => {
try {
const s = window.localStorage;
s.setItem('__probe', '1');
s.removeItem('__probe');
return { get: (k) => s.getItem(k), set: (k, v) => s.setItem(k, v) };
} catch {
const m = new Map();
return { get: (k) => m.get(k) ?? null, set: (k, v) => m.set(k, v) };
}
})();
let best = Number(store.get('explorer-best')) || 0;
// ---------- camera: orbit with the mouse, follow with damping, avoid walls ----------
let camYaw = 0, camPitch = 0.45, camDist = 7;
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.05, 1.2);
});
cv.addEventListener('wheel', (e) => { e.preventDefault(); camDist = THREE.MathUtils.clamp(camDist + e.deltaY * 0.005, 3, 12); }, { passive: false });
const raycaster = new THREE.Raycaster();
const lookAt = new THREE.Vector3(), camDir = new THREE.Vector3(), camWanted = new THREE.Vector3();
function updateCamera(dt, snap = false) {
lookAt.set(hero.position.x, hero.position.y + 1.4, hero.position.z);
camDir.set(Math.sin(camYaw) * Math.cos(camPitch), Math.sin(camPitch), Math.cos(camYaw) * Math.cos(camPitch));
raycaster.set(lookAt, camDir);
raycaster.far = camDist;
const hit = raycaster.intersectObjects(blockers, false)[0];
const dist = hit ? Math.max(1, hit.distance - 0.3) : camDist;
camWanted.copy(lookAt).addScaledVector(camDir, dist);
if (snap || hit) camera.position.copy(camWanted);
else camera.position.lerp(camWanted, 1 - Math.exp(-8 * dt));
camera.lookAt(lookAt);
}
// ---------- game state ----------
const hud = document.getElementById('hud'), menu = document.getElementById('menu');
let state = 'title'; // title | playing | paused | won
let found = 0, time = 0, vy = 0, grounded = false, heroYaw = 0, walkPhase = 0, portalOpen = false;
const fmt = (s) => `${Math.floor(s / 60)}:${(s % 60).toFixed(1).padStart(4, '0')}`;
function showMenu(html, button, onClick) {
menu.innerHTML = `${html}<button>${button}</button><p><label>volume <input type="range" min="0" max="1" step="0.1" value="${volume}"></label></p>`;
menu.querySelector('button').onclick = () => { initAudio(); onClick(); };
menu.querySelector('input').oninput = (e) => { volume = +e.target.value; if (master) master.gain.value = volume; };
menu.classList.remove('off');
state = state === 'playing' ? 'paused' : state;
}
function resume() {
menu.classList.add('off');
state = 'playing';
cv.focus(); // the button took the focus; give it back to the game
}
function reset() {
found = 0; time = 0; vy = 0; portalOpen = false;
heroBody.setTranslation(START, true);
heroBody.setNextKinematicTranslation(START);
for (const c of crystals) {
c.taken = false;
c.mesh.visible = true;
c.col.setEnabled(true);
}
portalMat.emissive.set('#000000');
portalCore.material.opacity = 0;
camYaw = 0;
}
function title() {
state = 'title';
showMenu(`<h1>Crystal Meadow</h1><p>Find the 6 crystals, then step into the portal.</p><p>WASD move · Space jump · drag to look · P pause</p>${best ? `<p>Best time: ${fmt(best)}</p>` : ''}`,
'Play', () => { reset(); resume(); });
}
function pause() {
showMenu('<h1>Paused</h1>', 'Resume', resume);
state = 'paused';
}
function win() {
state = 'won';
sfx.win();
const record = !best || time < best;
if (record) { best = time; store.set('explorer-best', String(best)); }
showMenu(`<h1>You made it!</h1><p>Time: ${fmt(time)}${record ? ' (new best!)' : ` · best ${fmt(best)}`}</p>`, 'Play again', () => { reset(); resume(); });
}
function onSensor(h1, h2, started) {
if (!started || state !== 'playing') return;
const thing = sensorOwner.get(h1) ?? sensorOwner.get(h2);
if (thing === 'portal') { if (portalOpen) win(); return; }
if (thing && !thing.taken) {
thing.taken = true;
thing.mesh.visible = false;
thing.col.setEnabled(false); // no more events from it
found++;
burst(thing.mesh.position);
sfx.pickup();
if (found === crystals.length) { portalOpen = true; sfx.portal(); }
}
}
// ---------- the update ----------
const GRAVITY = 22, JUMP = 8, SPEED = 5.5;
run(scene, camera, (dt) => {
if (pressed.has('KeyP') || pressed.has('Escape')) { if (state === 'playing') { pause(); return; } }
if (state !== 'playing') return;
time += dt;
// Camera-relative input.
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(camYaw) * f + Math.cos(camYaw) * s, mz = -Math.cos(camYaw) * f - Math.sin(camYaw) * s;
const len = Math.hypot(mx, mz);
if (len > 1) { mx /= len; mz /= len; }
if (grounded) vy = Math.max(vy, -1);
if (grounded && pressed.has('Space')) { vy = JUMP; sfx.jump(); }
vy -= GRAVITY * dt;
controller.computeColliderMovement(heroCol, { x: mx * SPEED * dt, y: vy * dt, z: mz * SPEED * dt }, RAPIER.QueryFilterFlags.EXCLUDE_SENSORS);
const m = controller.computedMovement();
grounded = controller.computedGrounded();
if (grounded && vy < 0) vy = 0;
const p = heroBody.translation();
heroBody.setNextKinematicTranslation({ x: p.x + m.x, y: p.y + m.y, z: p.z + m.z });
world.step(events);
events.drainCollisionEvents(onSensor);
if (state !== 'playing') return; // the portal may have ended the game
// Visuals: position, facing, walk cycle.
const q = heroBody.translation();
hero.position.set(q.x, q.y - FOOT, q.z);
if (len > 0.01) {
let diff = Math.atan2(mx, mz) - heroYaw;
diff = Math.atan2(Math.sin(diff), Math.cos(diff));
heroYaw += diff * (1 - Math.exp(-14 * dt));
hero.rotation.y = heroYaw;
}
walkPhase += grounded ? Math.min(len, 1) * dt * 11 : 0;
const swing = grounded ? Math.sin(walkPhase) * 0.7 * Math.min(len, 1) : 0.5;
legL.rotation.x = swing; legR.rotation.x = grounded ? -swing : -0.3;
armL.rotation.x = -swing * 0.8; armR.rotation.x = swing * 0.8;
for (const c of crystals) if (!c.taken) {
c.mesh.rotation.y += dt * 1.5;
c.mesh.position.y = c.baseY + Math.sin(time * 2 + c.baseY) * 0.15;
}
if (portalOpen) {
portal.rotation.z += dt;
portalMat.emissive.setHSL(0.53, 0.8, 0.35 + Math.sin(time * 4) * 0.1);
portalCore.material.opacity = 0.5 + Math.sin(time * 3) * 0.15;
}
if (sparkLife > 0) {
sparkLife -= dt;
for (let i = 0; i < SPARKS * 3; i += 3) {
sparkVel[i + 1] -= 9 * dt;
sparkPos[i] += sparkVel[i] * dt; sparkPos[i + 1] += sparkVel[i + 1] * dt; sparkPos[i + 2] += sparkVel[i + 2] * dt;
}
sparkGeo.attributes.position.needsUpdate = true;
sparkMat.opacity = Math.max(0, sparkLife / 0.8);
}
sun.target.position.copy(hero.position);
sun.position.copy(hero.position).add(SUN_OFFSET);
updateCamera(dt);
hud.textContent = `Crystals ${found} / ${crystals.length} ${fmt(time)} ${portalOpen ? 'The portal is open: go to the centre!' : ''}`;
});
// First frame: place everything, then show the title screen.
const q0 = heroBody.translation();
hero.position.set(q0.x, q0.y - FOOT, q0.z);
sun.target.position.copy(hero.position);
sun.position.copy(hero.position).add(SUN_OFFSET);
updateCamera(0, true);
title();
</script>The finished game, in numbers
| Thing | Count |
|---|---|
| Lines of code | about 450, including the play kit |
| Meshes | about 120 (trees, rocks, stones, crystals, hero parts) |
| Physics colliders | about 75, all simple shapes |
| Lights | 2 (hemisphere + one shadow-casting sun) |
| External files | 0 |
The Performance lessons show how to check what this costs. The biggest easy win would be instancing the 34 trees and 14 rocks.
Ideas to extend it
- Checkpoint and hazards: a stream that sends you back to the last plateau you stood on.
- A minimap in a corner with an orthographic top-down camera (Cameras).
- A real character: a rigged glTF model with idle, walk, run and jump clips blended by speed (Skinned Meshes & Blending).
- Touch controls: a virtual joystick and a jump button for phones.
- Collectible counter juice: tween the HUD number's scale on each pickup (Tweening).
Test yourself
Why does resume() call cv.focus()?
- To start the audio
- Clicking the menu button moved focus to the button, so the canvas lost focus and the play kit stopped updating
- Focus resets the timer
- WebGL needs focus to render
Where must the AudioContext be created or resumed?
- At page load
- Inside a user-gesture handler, such as the Play button's click
- In the animation loop
- In a Web Worker
What makes restarting without a page reload easy?
- Rebuilding the whole scene on every restart
- Keeping mutable game state in a few variables that
reset()restores, and building the static world once - Using
location.reload() - Saving to localStorage