TExcelTAD
Home › 3D Web Games with Three.js › Mini Project: Lantern Hunt

Mini Project: Lantern Hunt

Your turn to build a complete 3D game, small enough to finish in an evening: Lantern Hunt. Night has fallen over a clearing in the woods. Five old lanterns stand among the rocks, dark. Walk to each one and press E to light it before dawn breaks (2 minutes 30 seconds). Light all five and you win; your best time is remembered.

It reuses most of what this course covered, in a different shape from the Explorer game:

Feature Where it was taught
Rules as plain, testable functions (no Three.js) Exercises, Triggers
Character with a follow camera and drag-to-orbit Third-Person Camera
Circle collisions against rocks, without a physics engine First-Person Controls
A night scene: fog, dim hemisphere light, warm point lights Lights, Color Spaces & Tone Mapping
60 trees in 2 draw calls InstancedMesh & BatchedMesh
A minimap: orthographic camera, layers, scissor Perspective & Orthographic Cameras
Pause, win, lose, restart; sound after a gesture; best time with a storage fallback Explorer 4

Step 1: the rules, without graphics

Write the game as data and a step(game, input, dt) function first. Nothing in it knows about meshes or the DOM, so it can be tested in milliseconds: here an autopilot walks to each lantern in turn and presses E, and a lazy player stands still mashing E until dawn. Because the step is fixed and nothing is random, the result is the same on every run:

js · try it yourself
// ---- Lantern Hunt rules: no Three.js, no DOM ----
const RULES = { speed: 4.5, reach: 1.6, nightLength: 150, playerRadius: 0.35 };
const LANTERNS = [[-14, -12], [12, -15], [16, 10], [-10, 14], [0, -3]];
const ROCKS = [[-6, -6, 1.2], [7, -7, 1.5], [9, 4, 1.0], [-8, 6, 1.4], [3, 9, 1.1], [-15, 0, 1.6], [15, -3, 1.3]];

function createGame() {
  return { x: 0, z: 10, time: 0, lit: LANTERNS.map(() => false), state: 'playing' };
}

// input: { mx, mz } movement in -1..1 (world axes), interact: true on the step E was pressed
function step(g, input, dt) {
  const events = [];
  if (g.state !== 'playing') return events;
  g.time += dt;
  let { mx, mz } = input;
  const len = Math.hypot(mx, mz);
  if (len > 1) { mx /= len; mz /= len; }
  g.x += mx * RULES.speed * dt;
  g.z += mz * RULES.speed * dt;
  for (const [rx, rz, rr] of ROCKS) {                         // push out of rocks (circles)
    const dx = g.x - rx, dz = g.z - rz, d = Math.hypot(dx, dz), min = rr + RULES.playerRadius;
    if (d < min && d > 1e-6) { g.x = rx + (dx / d) * min; g.z = rz + (dz / d) * min; }
  }
  g.x = Math.max(-19, Math.min(19, g.x));
  g.z = Math.max(-19, Math.min(19, g.z));
  if (input.interact) {
    LANTERNS.forEach(([lx, lz], i) => {
      if (!g.lit[i] && Math.hypot(g.x - lx, g.z - lz) <= RULES.reach) { g.lit[i] = true; events.push(`lit lantern ${i}`); }
    });
  }
  if (g.lit.every(Boolean)) { g.state = 'won'; events.push('won'); }
  else if (g.time >= RULES.nightLength) { g.state = 'lost'; events.push('dawn: lost'); }
  return events;
}

// An autopilot walks to each lantern in turn and presses E when close; a lazy player never moves.
function autopilot(g) {
  const i = g.lit.findIndex((l) => !l);
  if (i < 0) return { mx: 0, mz: 0, interact: false };
  const [lx, lz] = LANTERNS[i];
  const dx = lx - g.x, dz = lz - g.z, d = Math.hypot(dx, dz);
  return { mx: dx / d, mz: dz / d, interact: d < 1.2 };
}
function play(name, brain) {
  const g = createGame();
  const DT = 1 / 60;
  while (g.state === 'playing') {
    for (const e of step(g, brain(g), DT)) console.log(`${name.padEnd(9)} t=${g.time.toFixed(2).padStart(6)}s  ${e}`);
  }
  console.log(`${name.padEnd(9)} result: ${g.state} after ${g.time.toFixed(1)} s, ${g.lit.filter(Boolean).length}/${LANTERNS.length} lanterns`);
}
play('autopilot', autopilot);
play('lazy', () => ({ mx: 0, mz: 0, interact: true }));
autopilot t=  5.55s  lit lantern 0
autopilot t= 11.02s  lit lantern 1
autopilot t= 16.40s  lit lantern 2
autopilot t= 22.00s  lit lantern 3
autopilot t= 25.98s  lit lantern 4
autopilot t= 25.98s  won
autopilot result: won after 26.0 s, 5/5 lanterns
lazy      t=150.00s  dawn: lost
lazy      result: lost after 150.0 s, 0/5 lanterns

The autopilot wins in about 26 seconds, which tells you the night (150 s) is generous for a first-time player who has to search; the lazy player loses at exactly 150 s, so the lose condition works. Tune nightLength with numbers like these before you ever draw a frame. The game below pastes this block unchanged and calls step() from its fixed-step update.

Step 2: the game

Click to play. WASD to walk (relative to the camera), drag to look around, E (or Space) to light a lantern when the prompt appears, P to pause, R to restart after the game ends. The minimap in the corner shows lit and unlit lanterns.

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; }
  #prompt { position: fixed; left: 0; right: 0; bottom: 18px; text-align: center; color: #ffe8a8; font: 600 15px system-ui, sans-serif; pointer-events: none; text-shadow: 0 1px 3px #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; }
  #panel { position: fixed; inset: 0; display: grid; place-content: center; background: rgba(5, 8, 16, 0.7); color: #fff; font: 15px system-ui, sans-serif; text-align: center; pointer-events: none; }
  #panel.off { display: none; }
  #panel b { display: block; font-size: 24px; margin-bottom: 6px; }
  body:has(#panel:not(.off)) #veil { display: none; }
</style>
<div id="hud"></div><div id="prompt"></div>
<div id="veil">Click to play<small>Light all 5 lanterns before dawn. WASD move, E light, drag to look, P pause</small></div>
<div id="panel" class="off"></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, draw = () => renderer.render(scene, camera)) {   // draw: optional custom render
  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
    draw();
    drawn = true;
  });
}
// ---- end of play kit ----

// ---- Lantern Hunt rules: no Three.js, no DOM ----
const RULES = { speed: 4.5, reach: 1.6, nightLength: 150, playerRadius: 0.35 };
const LANTERNS = [[-14, -12], [12, -15], [16, 10], [-10, 14], [0, -3]];
const ROCKS = [[-6, -6, 1.2], [7, -7, 1.5], [9, 4, 1.0], [-8, 6, 1.4], [3, 9, 1.1], [-15, 0, 1.6], [15, -3, 1.3]];

function createGame() {
  return { x: 0, z: 10, time: 0, lit: LANTERNS.map(() => false), state: 'playing' };
}

// input: { mx, mz } movement in -1..1 (world axes), interact: true on the step E was pressed
function step(g, input, dt) {
  const events = [];
  if (g.state !== 'playing') return events;
  g.time += dt;
  let { mx, mz } = input;
  const len = Math.hypot(mx, mz);
  if (len > 1) { mx /= len; mz /= len; }
  g.x += mx * RULES.speed * dt;
  g.z += mz * RULES.speed * dt;
  for (const [rx, rz, rr] of ROCKS) {                         // push out of rocks (circles)
    const dx = g.x - rx, dz = g.z - rz, d = Math.hypot(dx, dz), min = rr + RULES.playerRadius;
    if (d < min && d > 1e-6) { g.x = rx + (dx / d) * min; g.z = rz + (dz / d) * min; }
  }
  g.x = Math.max(-19, Math.min(19, g.x));
  g.z = Math.max(-19, Math.min(19, g.z));
  if (input.interact) {
    LANTERNS.forEach(([lx, lz], i) => {
      if (!g.lit[i] && Math.hypot(g.x - lx, g.z - lz) <= RULES.reach) { g.lit[i] = true; events.push(`lit lantern ${i}`); }
    });
  }
  if (g.lit.every(Boolean)) { g.state = 'won'; events.push('won'); }
  else if (g.time >= RULES.nightLength) { g.state = 'lost'; events.push('dawn: lost'); }
  return events;
}

// ---------- the night scene ----------
const scene = new THREE.Scene();
scene.background = new THREE.Color('#0b1022');
scene.fog = new THREE.FogExp2('#0b1022', 0.045);
const camera = new THREE.PerspectiveCamera(60, innerWidth / innerHeight, 0.1, 80);
scene.add(new THREE.HemisphereLight('#3a4a7a', '#141a10', 0.7));     // moonlit sky, dark ground
const moon = new THREE.DirectionalLight('#9fb4ff', 0.6);
moon.position.set(-10, 20, -5);
scene.add(moon);

const ground = new THREE.Mesh(new THREE.PlaneGeometry(44, 44), new THREE.MeshStandardMaterial({ color: '#2f4a2a' }));
ground.rotation.x = -Math.PI / 2;
scene.add(ground);

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(11);

// Trees around the edge: two InstancedMeshes (trunks, crowns) = 2 draw calls for 60 trees.
const TREES = 60;
const trunks = new THREE.InstancedMesh(new THREE.CylinderGeometry(0.25, 0.35, 2, 6), new THREE.MeshStandardMaterial({ color: '#3b2a1c' }), TREES);
const crowns = new THREE.InstancedMesh(new THREE.ConeGeometry(1.6, 4, 7), new THREE.MeshStandardMaterial({ color: '#1d3b25', flatShading: true }), TREES);
const dummy = new THREE.Object3D();
for (let i = 0; i < TREES; i++) {
  const a = (i / TREES) * Math.PI * 2 + rng() * 0.1, r = 21 + rng() * 2.5, s = 0.8 + rng() * 0.6;
  dummy.position.set(Math.cos(a) * r, 1 * s, Math.sin(a) * r);
  dummy.scale.setScalar(s);
  dummy.updateMatrix();
  trunks.setMatrixAt(i, dummy.matrix);
  dummy.position.y = 3.6 * s;
  dummy.updateMatrix();
  crowns.setMatrixAt(i, dummy.matrix);
}
scene.add(trunks, crowns);

// Rocks: the same circles the rules collide with.
const rockMat = new THREE.MeshStandardMaterial({ color: '#5b5e66', flatShading: true });
for (const [x, z, r] of ROCKS) {
  const rock = new THREE.Mesh(new THREE.IcosahedronGeometry(r, 0), rockMat);
  rock.position.set(x, r * 0.55, z);
  rock.rotation.set(rng() * 3, rng() * 3, 0);
  scene.add(rock);
}

// Stars.
const starPos = new Float32Array(400 * 3);
for (let i = 0; i < 400; i++) {
  const a = rng() * Math.PI * 2, h = 0.15 + rng() * 0.85;
  starPos.set([Math.cos(a) * 60 * Math.sqrt(1 - h * h), 60 * h, Math.sin(a) * 60 * Math.sqrt(1 - h * h)], i * 3);
}
const starGeo = new THREE.BufferGeometry();
starGeo.setAttribute('position', new THREE.BufferAttribute(starPos, 3));
scene.add(new THREE.Points(starGeo, new THREE.PointsMaterial({ color: '#dfe6ff', size: 0.25, fog: false })));

// Lanterns: a post, a glass box and a point light each. All five lights exist from the start
// (at intensity 0), so lighting one never changes the light count or recompiles shaders.
const MAP_LAYER = 1;                                  // objects only the minimap camera sees
const lanterns = LANTERNS.map(([x, z]) => {
  const post = new THREE.Mesh(new THREE.CylinderGeometry(0.06, 0.08, 1.6, 6), new THREE.MeshStandardMaterial({ color: '#2a2a2e' }));
  post.position.set(x, 0.8, z);
  const glassMat = new THREE.MeshStandardMaterial({ color: '#555048', emissive: '#000000' });
  const glass = new THREE.Mesh(new THREE.BoxGeometry(0.32, 0.4, 0.32), glassMat);
  glass.position.set(x, 1.75, z);
  const light = new THREE.PointLight('#ffb35c', 0, 12, 2);
  light.position.set(x, 1.8, z);
  const marker = new THREE.Mesh(new THREE.CircleGeometry(1.4, 16), new THREE.MeshBasicMaterial({ color: '#9a9a9a' }));
  marker.rotation.x = -Math.PI / 2;
  marker.position.set(x, 0.05, z);
  marker.layers.set(MAP_LAYER);
  scene.add(post, glass, light, marker);
  return { glassMat, light, marker };
});

// The player: a hooded figure carrying a small lamp (its own dim light).
const hero = new THREE.Group();
const cloak = new THREE.Mesh(new THREE.ConeGeometry(0.42, 1.3, 10), new THREE.MeshStandardMaterial({ color: '#6b3f8f' }));
cloak.position.y = 0.65;
const head = new THREE.Mesh(new THREE.SphereGeometry(0.2, 14, 10), new THREE.MeshStandardMaterial({ color: '#e9c9a3' }));
head.position.y = 1.4;
const lamp = new THREE.Mesh(new THREE.SphereGeometry(0.09, 10, 8), new THREE.MeshBasicMaterial({ color: '#ffe2a0' }));
lamp.position.set(0.35, 0.9, 0.25);
const lampLight = new THREE.PointLight('#ffd9a0', 3, 7, 2);
lampLight.position.copy(lamp.position);
const arrow = new THREE.Mesh(new THREE.ConeGeometry(0.7, 1.6, 3), new THREE.MeshBasicMaterial({ color: '#7fd0ff' }));
arrow.rotation.x = Math.PI / 2;                       // points along +Z, the hero's front, on the minimap
arrow.position.y = 0.1;
arrow.layers.set(MAP_LAYER);
hero.add(cloak, head, lamp, lampLight, arrow);
scene.add(hero);

// Minimap: an orthographic camera looking straight down, drawn in a corner with a scissor.
const mapCam = new THREE.OrthographicCamera(-21, 21, 21, -21, 1, 50);
mapCam.position.set(0, 30, 0);
mapCam.lookAt(0, 0, 0);
mapCam.layers.enable(MAP_LAYER);                      // sees normal objects and the map markers

// ---------- sound (created on the first key press or click: browsers require a gesture) ----------
let audio = null;
function ensureAudio() { if (!audio) audio = new AudioContext(); else if (audio.state === 'suspended') audio.resume(); }
addEventListener('keydown', ensureAudio);
cv.addEventListener('pointerdown', ensureAudio);
function tone(freq, start, dur, type = 'sine', gain = 0.2) {
  if (!audio) return;
  const t0 = audio.currentTime + start, 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(audio.destination);
  osc.start(t0);
  osc.stop(t0 + dur);
}
const sfx = {
  light: () => { tone(392, 0, 0.3, 'triangle'); tone(587, 0.1, 0.4, 'triangle'); },
  won: () => [392, 494, 587, 784].forEach((f, i) => tone(f, i * 0.15, 0.6, 'triangle')),
  lost: () => [330, 262, 196].forEach((f, i) => tone(f, i * 0.25, 0.5, 'sine')),
};

// ---------- best time, with a fallback when storage is blocked (it is in this sandbox) ----------
const store = (() => {
  try { const s = window.localStorage; s.setItem('__p', '1'); s.removeItem('__p'); 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('lantern-best')) || 0;

// ---------- camera: drag to orbit, smoothed follow ----------
let camYaw = 0, camPitch = 0.55;
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.2, 1.25);
});
const lookAt = new THREE.Vector3(), camWanted = new THREE.Vector3();
function updateCamera(dt, snap) {
  lookAt.set(hero.position.x, 1.1, hero.position.z);
  camWanted.set(Math.sin(camYaw) * Math.cos(camPitch), Math.sin(camPitch), Math.cos(camYaw) * Math.cos(camPitch)).multiplyScalar(7).add(lookAt);
  if (snap) camera.position.copy(camWanted);
  else camera.position.lerp(camWanted, 1 - Math.exp(-8 * dt));
  camera.lookAt(lookAt);
}

// ---------- game flow ----------
const hud = document.getElementById('hud'), prompt = document.getElementById('prompt'), panel = document.getElementById('panel');
let game = createGame(), paused = false, heroYaw = Math.PI;
const clock = (s) => `${Math.floor(s / 60)}:${String(Math.floor(s % 60)).padStart(2, '0')}`;
function show(html) { panel.innerHTML = html; panel.classList.remove('off'); }
function restart() {
  game = createGame();
  paused = false;
  panel.classList.add('off');
  for (const l of lanterns) { l.light.intensity = 0; l.glassMat.emissive.set('#000000'); l.marker.material.color.set('#9a9a9a'); }
  camYaw = 0;
  syncHero(0);
  updateCamera(0, true);
}
function syncHero(dt, mx = 0, mz = 0) {
  hero.position.set(game.x, 0, game.z);
  if (Math.hypot(mx, mz) > 0.01) {
    let d = Math.atan2(mx, mz) - heroYaw;
    d = Math.atan2(Math.sin(d), Math.cos(d));
    heroYaw += d * (1 - Math.exp(-12 * dt));
  }
  hero.rotation.y = heroYaw;
}

// Each frame: the main view, then the minimap in a scissored corner (no fog on the map).
function draw() {
  renderer.render(scene, camera);
  const size = Math.min(innerWidth, innerHeight) * 0.32;
  renderer.setScissorTest(true);
  renderer.setScissor(innerWidth - size - 8, 8, size, size);
  renderer.setViewport(innerWidth - size - 8, 8, size, size);
  const fog = scene.fog;
  scene.fog = null;
  renderer.render(scene, mapCam);
  scene.fog = fog;
  renderer.setScissorTest(false);
  renderer.setViewport(0, 0, innerWidth, innerHeight);
}

run(scene, camera, (dt) => {
  if (pressed.has('KeyR') && game.state !== 'playing') { restart(); return; }
  if ((pressed.has('KeyP') || pressed.has('Escape')) && game.state === 'playing') {
    paused = !paused;
    if (paused) show('<b>Paused</b>P to resume'); else panel.classList.add('off');
  }
  if (paused || game.state !== 'playing') return;

  // Camera-relative input, turned into world axes for the rules.
  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);
  const mx = -Math.sin(camYaw) * f + Math.cos(camYaw) * s, mz = -Math.cos(camYaw) * f - Math.sin(camYaw) * s;
  const events = step(game, { mx, mz, interact: pressed.has('KeyE') || pressed.has('Space') }, dt);

  for (const e of events) {
    if (e.startsWith('lit')) {
      const l = lanterns[Number(e.split(' ')[2])];
      l.light.intensity = 14;                         // a uniform change: no shader recompile
      l.glassMat.emissive.set('#ffb35c');
      l.marker.material.color.set('#ffc94d');
      sfx.light();
    } else if (e === 'won') {
      const record = !best || game.time < best;
      if (record) { best = game.time; store.set('lantern-best', String(best)); }
      sfx.won();
      show(`<b>The meadow is lit!</b>Time ${clock(game.time)}${record ? ' (new best)' : `, best ${clock(best)}`}<br>R to play again`);
    } else if (e.startsWith('dawn')) {
      sfx.lost();
      show(`<b>Dawn broke</b>${game.lit.filter(Boolean).length} of ${LANTERNS.length} lanterns lit<br>R to try again`);
    }
  }

  syncHero(dt, mx, mz);
  for (const l of lanterns) if (l.light.intensity > 0) l.light.intensity = 14 + Math.sin(game.time * 9 + l.light.position.x) * 1.5;   // flicker
  updateCamera(dt);

  const near = LANTERNS.findIndex(([x, z], i) => !game.lit[i] && Math.hypot(game.x - x, game.z - z) <= RULES.reach);
  prompt.textContent = near >= 0 && game.state === 'playing' ? 'Press E to light the lantern' : '';
  const left = Math.max(0, RULES.nightLength - game.time);
  hud.textContent = `Lanterns ${game.lit.filter(Boolean).length} / ${LANTERNS.length}   Dawn in ${clock(left)}${best ? `   Best ${clock(best)}` : ''}`;
}, draw);

restart();
</script>

How it's put together

One source of truth. The game object from the rules is the state; the scene only shows it. Each update turns input into a step() call, then copies game.x/z to the hero mesh and reacts to the returned events (lit lantern 2, won, dawn: lost): lighting a lamp, playing a sound, showing a panel. Restarting is game = createGame() plus resetting the visuals, nothing else.

Lights that never change in number. All five lantern PointLights exist from the start at intensity 0; lighting one sets its intensity. Adding a light at runtime would recompile every lit material's shader, a visible hitch at exactly the moment the player should feel rewarded (Field Notes, note 8). Each light also has a distance of 12 m, so it doesn't cost anything for pixels far away.

A night that reads. Darkness is mostly contrast: a dark blue background and FogExp2 hide the edges of the clearing, a weak bluish hemisphere light keeps silhouettes readable, and the warm lamp the player carries (a small point light that moves with the hero) makes the area around them the brightest thing on screen. Lit lanterns become warm landmarks you can see across the clearing.

The minimap. A second, orthographic camera looks straight down. The markers (grey or gold discs, and the blue arrow parented to the hero) are on layer 1, which only the minimap camera has enabled, so they never appear in the main view. The play kit's run() takes an optional draw function here; draw() renders the main view, then restricts drawing to a square in the corner with setScissor/setViewport and renders again with the minimap camera, temporarily without fog.

Trees as instances. The ring of 60 trees is two InstancedMeshes (trunks and crowns): two draw calls instead of 120. The rocks stay individual meshes because the rules need their exact positions and sizes (the ROCKS list drives both the collision and the meshes, so they can't disagree).

Make it yours

Pick a few, in order of difficulty:

  1. Fireflies: a THREE.Points cloud of small glowing dots drifting with sine waves. Keep them few and small (overdraw).
  2. A lantern counter that pops: tween the HUD number's scale when a lantern is lit (Tweening).
  3. Harder nights: a difficulty setting that shortens nightLength; check it with the autopilot first.
  4. Wandering will-o'-wisps: a light that drifts toward the player; touching it costs 10 seconds. Write it as part of the rules, with a test.
  5. A real character: replace the cone with a rigged glTF model and blend idle/walk animations by speed (Skinned Meshes & Blending).
  6. Rapier: move the hero with a character controller and make the rocks real colliders (Character Controller), then add a fallen log to jump over.
  7. Ship it: move the code into a Vite project, split it into modules (rules.ts, scene.ts, ui.ts), build it and upload it to itch.io (Vite, TypeScript & Shipping).

Test yourself

Why are the rules written without any Three.js or DOM code?

  1. Three.js can't run game logic
  2. So they can be tested quickly and deterministically (autopilot runs) and the scene just displays the state
  3. To make the bundle smaller
  4. Because WebGL is asynchronous

How do the minimap markers stay out of the main view?

  1. They are transparent
  2. They are on layer 1, and only the minimap camera has that layer enabled
  3. They are drawn behind the ground
  4. They are removed before each main render

Why do all five lantern lights exist from the start with intensity 0?

  1. Point lights must be created before the renderer
  2. Adding lights later changes the light count and recompiles every lit shader, causing a hitch
  3. Intensity 0 lights are free
  4. To make shadows work