Explorer 3: Collectibles & Objective
A walk in the meadow is not a game yet. A game needs a goal, progress you can see, and an ending. This step adds all three:
- six crystals hidden around the level: on each plateau, in a corner of the meadow, by the ruins;
- a HUD with the crystal count and a timer;
- the portal in the centre, dark until you have all six; walking into it after that wins the game.
Crystals are sensors
Each crystal is a mesh plus a Rapier sensor collider, set up as in Triggers & Collision Events:
const col = world.createCollider(RAPIER.ColliderDesc.ball(0.7).setTranslation(x, y, z)
.setSensor(true)
.setActiveEvents(RAPIER.ActiveEvents.COLLISION_EVENTS)
.setActiveCollisionTypes(SENSOR)); // DEFAULT | KINEMATIC_FIXED: the hero is kinematic
sensorOwner.set(col.handle, crystal); // collider handle -> game objectThe sensor ball (0.7 m) is a little larger than the visible crystal, so a pickup triggers when the hero's body brushes it, not only when it is dead centre: generous pickups feel better. The character controller now passes RAPIER.QueryFilterFlags.EXCLUDE_SENSORS, or the crystals would be solid obstacles.
After world.step(events), events.drainCollisionEvents(onSensor) delivers each started or stopped overlap. onSensor looks up what was touched through sensorOwner, hides the crystal, disables its collider (col.setEnabled(false), so it stops producing events but can be re-enabled on restart), counts it, and fires a burst of sparkles. When the count reaches six, the portal opens.
The portal and winning
The portal is a TorusGeometry ring with a translucent disc, and a box sensor. While it's closed, entering the sensor does nothing; once open, the ring spins and pulses (emissive color animated with setHSL), and entering it calls win(). The game uses a tiny state variable, 'playing' or 'won', and the update returns early when the game is over, so the timer stops and the hero freezes. The next lesson grows this into a proper state machine with title and pause screens.
Juice: bob, spin and sparkles
Small touches make collectibles readable from a distance and satisfying to grab:
- crystals spin and bob with a sine of time (a phase offset per crystal so they don't move in unison) and glow (
emissive), so they stand out against the green; - a sparkle burst: a
THREE.Pointsobject with 40 points that fly outward under gravity and fade over 0.8 s. The same 40 points are reused for every pickup, a tiny object pool (Shooter 4: Object Pooling explains why).
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; }
</style>
<div id="hud"></div>
<div id="veil">Click to play<small>WASD move, Space jump, drag to look: find the 6 crystals</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 ----
// ---------- 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;
}
// ---------- 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');
let state = 'playing'; // playing | 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 win() {
state = 'won';
hud.textContent = `You made it in ${fmt(time)}! Run the example again to play again.`;
}
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);
if (found === crystals.length) portalOpen = true;
}
}
// ---------- the update ----------
const GRAVITY = 22, JUMP = 8, SPEED = 5.5;
run(scene, camera, (dt) => {
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;
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.
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);
</script>Where are they? One on each plateau (stairs, ramp, jump), one in the far left corner of the meadow, one by the east wall, and one between the ruins. The timer starts when you first click the game.
Design notes
- Teach with the level. The first crystal is between the ruins, straight ahead of the start and on the way to the portal: it teaches "walk into crystals" before the player has to hunt for the others. The plateaus then teach the stairs, the ramp and the jump, one each.
- Visible goal. The portal is in the middle of the map, so players see the goal from anywhere and have a reason to come back after collecting.
- Feedback for every event: a count change on the HUD, a burst of particles, and (next lesson) a sound. Players should never wonder whether something worked.
- Fair placement: crystals are placed with fixed coordinates (
CRYSTAL_SPOTS), and the seeded scenery generator keeps clear areas around them, so no crystal is ever inside a rock.
Test yourself
Why is the crystal's sensor bigger than the crystal mesh?
- Sensors must be larger than meshes
- Generous pickup zones feel better: the pickup triggers when the player brushes past
- To make the physics faster
- Because the mesh is scaled
After picking up a crystal, why is its collider disabled with setEnabled(false) rather than removed?
- Removing colliders is not possible
- It stops producing events but can be switched back on when the game restarts
- Disabled colliders are faster to render
- To keep the crystal visible
How does the game stop the timer and the hero after winning?
- It stops the renderer
- A state variable switches to 'won' and the update returns early
- It removes the hero from the scene
- It calls
world.free()