Week 8 — Shapes, Lights & Shadows

Light makes a 3D world feel real. This week you use many built-in shapes, give them physically based materials, light them with ambient, point and spot lights, switch on real-time shadows, and look around with OrbitControls — then build Torch Hunt, where your torch beam is the only way to find six gems hidden in a dark room.

🎯 Objectives

  • Use built-in shapes: PlaneGeometry, SphereGeometry, CylinderGeometry, ConeGeometry and more.
  • Describe surfaces with MeshStandardMaterial: color, roughness, metalness, emissive.
  • Light a scene with AmbientLight, PointLight and SpotLight.
  • Turn on real-time shadows with shadowMap, castShadow and receiveShadow.
  • Build a scene from many meshes with a helper function and an array.
  • Import an add-on and look around with OrbitControls.
  • Move an object smoothly while keys are held down (a key-state object).
  • Detect when objects are close with distanceTo, and run a countdown.

🛠 Weekly tasks

  1. Objective 1 — use several built-in geometries: Activity 1 + build torchHunt.html.
  2. Objective 2 — style surfaces with a standard material: Activity 2 + build torchHunt.html.
  3. Objective 3 — light the room with three kinds of light: Activity 3 + build torchHunt.html.
  4. Objective 4 — switch on real-time shadows: Activity 4 + build torchHunt.html.
  5. Objective 5 — build the room with a helper function: Activity 5 + build torchHunt.html.
  6. Objective 6 — look around with OrbitControls: Activity 6 + build torchHunt.html.
  7. Objective 7 — steer the torch with held-down keys: Activity 7 + build torchHunt.html.
  8. Objective 8 — detect found gems and run a countdown: Activity 8 + build torchHunt.html.
  9. Examples — build the lecture examples materials.html, lights.html, shadows.html, orbit.html, one file per concept, and try each change. (Concepts 1–4)
  10. Build your own torchHunt_yourname.html — add a best time, a torch battery that drains, and a second level with more gems. (All objectives)

🎓 Lecture activity Open lecture slides →

A 90-minute session of 35 slides. Each concept is taught four ways: the big idea, a short example with its live 3D output, a line-by-line explanation, and a 5-minute “try it” task. The lab work at 1:00 uses the Lab activity below.

Session plan

  1. 0:0010 minWarm-upReview questions on last week
  2. 0:1010 minGame & objectivesThis week’s game, objectives and key words
  3. 0:2035 minConceptsBig idea → code with live 3D output → line by line → try it
  4. 0:555 minCheck understandingCommon mistakes and a 4-question quiz
  5. 1:0025 minLabBuild the files in the Lab activity below
  6. 1:255 minWrap-upBuild-your-own task, marking guide and recap

Concepts this week

  • 1. Materials — roughness, metalness and emissive
  • 2. Lights — Ambient, point, spot (and directional)
  • 3. Shadows — Three switches: renderer, light, objects
  • 4. Orbit and find — OrbitControls add-on and distanceTo

The slides open as a page on this site. Press F for full screen, the arrow keys to move, N for speaker notes, and P to save as PDF (turn on “Background graphics”).

🧪 Lab activity: work through the files Printable lab sheet

Set up your Week8 npm project (step 1). Build Torch Hunt below, writing the code shown for each step. Everything goes in one file, torchHunt.html. OrbitControls comes with the three package, so there is nothing extra to install. Start with the four example files from the lecture (one per concept), then build the game.

3D files run through Vite. Each week is an npm project: Three.js is installed with npm install three, and the Vite dev server (npx vite) serves your files at http://localhost:5173/ and reloads them when you save. Opening an HTML file by double-clicking shows a blank page. New to Node.js? Week 7’s first step and the Setup guide show the installation.
  1. Set up your Week8 project npm · Vite

    Week8\ — a new npm project, once at the start of the week.

    1. Create a folder named Week8, open it in VS Code, and open the terminal with Ctrl+`.
    2. Create the project and install Three.js and Vite (the same commands as Week 7):
      npm init -y
      npm install three@0.170.0
      npm install --save-dev vite@5
    3. Shortcut: download package.json from Materials for this week into the folder, then run npm install instead.
    4. Start the Vite dev server and leave it running. Open the address it prints plus a file name, for example http://localhost:5173/materials.html. Press Ctrl+C in the terminal to stop it.
      npx vite
  2. materials.html Concept 1 · Materials

    Week8\materials.html — roughness, metalness and emissive.

    1. Create materials.html and add this code. Only the material settings change from ball to ball.
      <!DOCTYPE html>
      <html lang="en">
      <head>
      <meta charset="UTF-8" />
      <title>Same Shape, Four Materials</title>
      <style>
        body { margin: 0; overflow: hidden; background: #fffdf8; }
      </style>
      </head>
      <body>
      <script type="module">
      import * as THREE from "three";
      
      const scene = new THREE.Scene();
      scene.background = new THREE.Color(0xfffdf8);
      const camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 100);
      camera.position.set(0, 1, 8);
      camera.lookAt(0, 0, 0);
      const renderer = new THREE.WebGLRenderer({ antialias: true });
      renderer.setSize(window.innerWidth, window.innerHeight);
      document.body.appendChild(renderer.domElement);
      
      scene.add(new THREE.AmbientLight(0xffffff, 0.4));
      const sun = new THREE.DirectionalLight(0xffffff, 2.5);
      sun.position.set(3, 4, 5);
      scene.add(sun);
      const rim = new THREE.PointLight(0xffffff, 40, 20);   // a light that circles the balls
      scene.add(rim);
      
      // four looks: matt, shiny, metal, glowing
      const looks = [
        { color: 0x2563eb, roughness: 1,   metalness: 0 },
        { color: 0x2563eb, roughness: 0.2, metalness: 0 },
        { color: 0xd4a017, roughness: 0.3, metalness: 1 },
        { color: 0x222222, emissive: 0xff8800 },
      ];
      looks.forEach(function (look, i) {
        const ball = new THREE.Mesh(
          new THREE.SphereGeometry(0.7, 48, 24),
          new THREE.MeshStandardMaterial(look));
        ball.position.x = i * 1.8 - 2.7;
        scene.add(ball);
      });
      
      const clock = new THREE.Clock();
      renderer.setAnimationLoop(function () {
        const t = clock.getElapsedTime();
        rim.position.set(Math.cos(t) * 5, 3, Math.sin(t) * 5);   // move the highlights
        renderer.render(scene, camera);
      });
      </script>
      </body>
      </html>
    2. Save. With npx vite running, open http://localhost:5173/materials.html. You should see matt, shiny, metal and glowing.
    3. [Try it]
      1. Add a fifth ball with OctahedronGeometry(0.6) and { color: 0xffd34d, metalness: 0.6, roughness: 0.3 }.
      2. Move the balls closer together so all five fit.
      3. Give the new gem emissive: 0xffaa00.
  3. lights.html Concept 2 · Lights

    Week8\lights.html — Ambient, point, spot (and directional).

    1. Create lights.html and add this code. The spot light shines at its target; move the target to aim it.
      <!DOCTYPE html>
      <html lang="en">
      <head>
      <meta charset="UTF-8" />
      <title>A Bulb and a Torch</title>
      <style>
        body { margin: 0; overflow: hidden; background: #0b0d14; }
      </style>
      </head>
      <body>
      <script type="module">
      import * as THREE from "three";
      
      const scene = new THREE.Scene();
      scene.background = new THREE.Color(0x0b0d14);
      const camera = new THREE.PerspectiveCamera(50, window.innerWidth / window.innerHeight, 0.1, 100);
      camera.position.set(0, 7, 10);
      camera.lookAt(0, 0, 0);
      const renderer = new THREE.WebGLRenderer({ antialias: true });
      renderer.setSize(window.innerWidth, window.innerHeight);
      document.body.appendChild(renderer.domElement);
      
      // a floor and three boxes to light up
      const floor = new THREE.Mesh(new THREE.PlaneGeometry(14, 10),
                                   new THREE.MeshStandardMaterial({ color: 0x8a7f6b, roughness: 0.9 }));
      floor.rotation.x = -Math.PI / 2;
      scene.add(floor);
      [[-3, 0x2563eb], [0, 0x12854f], [3, 0xd9534f]].forEach(function (p) {
        const box = new THREE.Mesh(new THREE.BoxGeometry(1, 1, 1),
                                   new THREE.MeshStandardMaterial({ color: p[1] }));
        box.position.set(p[0], 0.5, -1);
        scene.add(box);
      });
      
      // 1. ambient: a faint fill everywhere
      scene.add(new THREE.AmbientLight(0x404a66, 0.25));
      
      // 2. a bulb (point light) and a small ball so we can see where it is
      const bulb = new THREE.PointLight(0xff8844, 30, 10);
      scene.add(bulb);
      const dot = new THREE.Mesh(new THREE.SphereGeometry(0.12),
                                 new THREE.MeshBasicMaterial({ color: 0xffaa66 }));
      scene.add(dot);
      
      // 3. a torch (spot light) that shines at its target
      const torch = new THREE.SpotLight(0xfff2cc, 300, 30, Math.PI / 10, 0.4);
      torch.position.set(0, 8, 3);
      scene.add(torch);
      scene.add(torch.target);                       // the target must be in the scene
      
      const clock = new THREE.Clock();
      renderer.setAnimationLoop(function () {
        const t = clock.getElapsedTime();
        bulb.position.set(Math.cos(t) * 4, 1, Math.sin(t) * 4);   // the bulb circles
        dot.position.copy(bulb.position);
        torch.target.position.x = Math.sin(t * 0.7) * 4;          // aim the torch by moving its target
        renderer.render(scene, camera);
      });
      </script>
      </body>
      </html>
    2. Save. With npx vite running, open http://localhost:5173/lights.html. You should see a moving point light and a spot light.
    3. [Try it]
      1. Make the torch cone wider: Math.PI / 6.
      2. Make its edge hard: change the last number (penumbra) to 0.
      3. Turn the AmbientLight up to 1, then back down.
  4. shadows.html Concept 3 · Shadows

    Week8\shadows.html — Three switches: renderer, light, objects.

    1. Create shadows.html and add this code. The floor receives; the box and ball cast. The light moves, so the shadows move.
      <!DOCTYPE html>
      <html lang="en">
      <head>
      <meta charset="UTF-8" />
      <title>Cast a Shadow</title>
      <style>
        body { margin: 0; overflow: hidden; background: #fffdf8; }
      </style>
      </head>
      <body>
      <script type="module">
      import * as THREE from "three";
      
      const scene = new THREE.Scene();
      scene.background = new THREE.Color(0xfffdf8);
      const camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 100);
      camera.position.set(0, 6, 9);
      camera.lookAt(0, 0, 0);
      const renderer = new THREE.WebGLRenderer({ antialias: true });
      renderer.setSize(window.innerWidth, window.innerHeight);
      renderer.shadowMap.enabled = true;                  // switch 1: the renderer
      renderer.shadowMap.type = THREE.PCFSoftShadowMap;   // softer edges
      document.body.appendChild(renderer.domElement);
      
      const floor = new THREE.Mesh(new THREE.PlaneGeometry(12, 8),
                                   new THREE.MeshStandardMaterial({ color: 0xe9e2d2 }));
      floor.rotation.x = -Math.PI / 2;
      floor.receiveShadow = true;                         // switch 3: the floor shows shadows
      scene.add(floor);
      
      const box = new THREE.Mesh(new THREE.BoxGeometry(1.4, 1.4, 1.4),
                                 new THREE.MeshStandardMaterial({ color: 0xe8823a }));
      box.position.set(-1.5, 0.7, 0);
      box.castShadow = true;                              // switch 3: objects cast shadows
      scene.add(box);
      
      const ball = new THREE.Mesh(new THREE.SphereGeometry(0.8, 32, 16),
                                  new THREE.MeshStandardMaterial({ color: 0x2563eb }));
      ball.position.set(1.5, 0.8, 0);
      ball.castShadow = true;
      scene.add(ball);
      
      scene.add(new THREE.AmbientLight(0xffffff, 0.5));
      const sun = new THREE.DirectionalLight(0xffffff, 2.5);
      sun.castShadow = true;                              // switch 2: the light makes shadows
      sun.shadow.mapSize.set(1024, 1024);
      scene.add(sun);
      
      const clock = new THREE.Clock();
      renderer.setAnimationLoop(function () {
        const t = clock.getElapsedTime() * 0.8;
        sun.position.set(Math.cos(t) * 6, 6, Math.sin(t) * 6);   // move the light: the shadows follow
        renderer.render(scene, camera);
      });
      </script>
      </body>
      </html>
    2. Save. With npx vite running, open http://localhost:5173/shadows.html. You should see moving shadows on the floor.
    3. [Try it]
      1. Comment out floor.receiveShadow = true and refresh.
      2. Put it back, then try sun.shadow.mapSize.set(256, 256).
      3. Stop the light moving by fixing sun.position.set(4, 6, 2).
  5. orbit.html Concept 4 · Orbit and find

    Week8\orbit.html — OrbitControls add-on and distanceTo.

    1. Create orbit.html and add this code. The gem lights up while the marker is within 1 unit of it.
      <!DOCTYPE html>
      <html lang="en">
      <head>
      <meta charset="UTF-8" />
      <title>Orbit and Detect</title>
      <style>
        body { margin: 0; overflow: hidden; background: #14171f; }
      </style>
      </head>
      <body>
      <script type="module">
      import * as THREE from "three";
      import { OrbitControls } from "three/addons/controls/OrbitControls.js";
      
      const scene = new THREE.Scene();
      scene.background = new THREE.Color(0x14171f);
      const camera = new THREE.PerspectiveCamera(50, window.innerWidth / window.innerHeight, 0.1, 100);
      camera.position.set(0, 6, 9);
      const renderer = new THREE.WebGLRenderer({ antialias: true });
      renderer.setSize(window.innerWidth, window.innerHeight);
      document.body.appendChild(renderer.domElement);
      
      // drag to orbit, scroll to zoom; it also turns slowly on its own
      const controls = new OrbitControls(camera, renderer.domElement);
      controls.enableDamping = true;
      controls.maxPolarAngle = Math.PI / 2.2;     // never look from under the floor
      controls.autoRotate = true;
      controls.autoRotateSpeed = 1.5;
      
      const floor = new THREE.Mesh(new THREE.PlaneGeometry(10, 10),
                                   new THREE.MeshStandardMaterial({ color: 0x5a6378 }));
      floor.rotation.x = -Math.PI / 2;
      scene.add(floor);
      scene.add(new THREE.AmbientLight(0xffffff, 0.6));
      const sun = new THREE.DirectionalLight(0xffffff, 2);
      sun.position.set(3, 6, 4);
      scene.add(sun);
      
      // a gem, and a green ring that wanders around the floor
      const gem = new THREE.Mesh(new THREE.OctahedronGeometry(0.5),
        new THREE.MeshStandardMaterial({ color: 0xffd34d, metalness: 0.6, roughness: 0.3 }));
      gem.position.set(1.5, 0.6, 0);
      scene.add(gem);
      const marker = new THREE.Mesh(new THREE.TorusGeometry(0.5, 0.06, 8, 40),
                                    new THREE.MeshBasicMaterial({ color: 0x22d3a6 }));
      marker.rotation.x = -Math.PI / 2;
      marker.position.y = 0.05;
      scene.add(marker);
      
      const clock = new THREE.Clock();
      renderer.setAnimationLoop(function () {
        const t = clock.getElapsedTime();
        marker.position.x = Math.cos(t) * 3;
        marker.position.z = Math.sin(t * 1.3) * 2;
      
        // compare at the same height, so only x and z count
        const aim = new THREE.Vector3(marker.position.x, gem.position.y, marker.position.z);
        if (gem.position.distanceTo(aim) < 1.0) {
          gem.material.emissive.set(0xffaa00);   // close enough: glow
        } else {
          gem.material.emissive.set(0x000000);
        }
        gem.rotation.y = t;
      
        controls.update();                       // needed every frame with damping
        renderer.render(scene, camera);
      });
      </script>
      </body>
      </html>
    2. Save. With npx vite running, open http://localhost:5173/orbit.html. You should see auto-orbiting camera; the gem glows when the marker is close.
    3. [Try it]
      1. Set controls.autoRotate = false and drag the view yourself.
      2. Add controls.minDistance = 4 and controls.maxDistance = 14.
      3. Make the gem glow from further away: change 1.0 to 2.0.
  6. torchHunt.html Objectives 1–8

    Week8\torchHunt.html — the torch game.

    1. [Obj 6] Create torchHunt.html. Both imports go at the top of the module: the library, and the OrbitControls add-on from three/addons/controls/.
      <!DOCTYPE html>
      <html lang="en">
      <head>
      <meta charset="UTF-8" />
      <title>Torch Hunt</title>
      <style>
        body { margin: 0; overflow: hidden; background: #05060a; font-family: Arial, Helvetica, sans-serif; }
        #hud { position: absolute; top: 10px; left: 12px; color: #ffe9a8; font-size: 20px; pointer-events: none; text-shadow: 0 1px 3px #000; }
        #msg { position: absolute; top: 38%; left: 0; right: 0; text-align: center; color: #ffffff; font-size: 28px; pointer-events: none; text-shadow: 0 2px 6px #000; }
      </style>
      </head>
      <body>
      <div id="hud">Gems: <span id="found">0</span> / 6 &nbsp;&nbsp; Time: <span id="time">60</span></div>
      <div id="msg">Find the 6 hidden gems with your torch<br>Arrow keys / WASD move the torch &middot; drag to look around<br>Press Enter to start</div>
      
      <script type="module">
      import * as THREE from "three";
      import { OrbitControls } from "three/addons/controls/OrbitControls.js";
      
      // TODO: the steps below go here
      </script>
      </body>
      </html>
    2. [Obj 4] Create the renderer with shadows switched on, then the scene and the camera.
      // ---------- renderer with shadows ----------
      const renderer = new THREE.WebGLRenderer({ antialias: true });
      renderer.setSize(window.innerWidth, window.innerHeight);
      renderer.shadowMap.enabled = true;                 // switch 1 of 3 for shadows
      renderer.shadowMap.type = THREE.PCFSoftShadowMap;  // softer shadow edges
      document.body.appendChild(renderer.domElement);
      
      const scene = new THREE.Scene();
      scene.background = new THREE.Color(0x05060a);
      
      const camera = new THREE.PerspectiveCamera(55, window.innerWidth / window.innerHeight, 0.1, 100);
      camera.position.set(0, 11, 13);
    3. [Obj 6] Add OrbitControls. The limits stop the camera going under the floor or too far away.
      // ---------- orbit controls: drag to look around ----------
      const controls = new OrbitControls(camera, renderer.domElement);
      controls.target.set(0, 0, 0);
      controls.enableDamping = true;            // smooth, slightly floaty movement
      controls.maxPolarAngle = Math.PI / 2.2;   // never look from under the floor
      controls.minDistance = 6;
      controls.maxDistance = 25;
    4. [Obj 1, 2, 5] Build the room. A PlaneGeometry stands upright, so rotate it to lie flat. One helper builds every wall.
      // ---------- the room ----------
      const ROOM = 8;   // half the room width: the floor runs from -8 to 8
      const floor = new THREE.Mesh(
        new THREE.PlaneGeometry(ROOM * 2, ROOM * 2),
        new THREE.MeshStandardMaterial({ color: 0x8a7f6b, roughness: 0.9 }));
      floor.rotation.x = -Math.PI / 2;          // a plane stands up; lay it flat
      floor.receiveShadow = true;
      scene.add(floor);
      
      const wallMat = new THREE.MeshStandardMaterial({ color: 0x5a6378, roughness: 1 });
      function addWall(width, x, z, turn) {
        const wall = new THREE.Mesh(new THREE.BoxGeometry(width, 3, 0.3), wallMat);
        wall.position.set(x, 1.5, z);
        wall.rotation.y = turn;
        wall.receiveShadow = true;
        scene.add(wall);
      }
      addWall(ROOM * 2, 0, -ROOM, 0);             // back wall
      addWall(ROOM * 2, -ROOM, 0, Math.PI / 2);   // left wall
      addWall(ROOM * 2, ROOM, 0, Math.PI / 2);    // right wall (no front wall, so we can see in)
    5. [Obj 1, 2, 4, 5] Add the toys. addToy() uses the geometry’s bounding box to sit any shape exactly on the floor, and switches on its shadows.
      // ---------- toys: one helper places any geometry on the floor ----------
      const toys = [];
      function addToy(geometry, colour, x, z) {
        geometry.computeBoundingBox();
        const toy = new THREE.Mesh(geometry, new THREE.MeshStandardMaterial({ color: colour, roughness: 0.5, metalness: 0.1 }));
        toy.position.set(x, -geometry.boundingBox.min.y, z);   // sit exactly on the floor
        toy.castShadow = true;                                 // switch 2: objects cast shadows
        toy.receiveShadow = true;
        scene.add(toy);
        toys.push(toy);
      }
      addToy(new THREE.BoxGeometry(1.5, 1.5, 1.5), 0xd9534f, -4, -3);
      addToy(new THREE.SphereGeometry(0.9, 32, 16), 0x2563eb, 3, -4);
      addToy(new THREE.CylinderGeometry(0.6, 0.6, 2.4, 24), 0x12854f, -5, 3);
      addToy(new THREE.ConeGeometry(0.9, 2, 24), 0xe8a33a, 4.5, 2.5);
      addToy(new THREE.TorusGeometry(0.8, 0.3, 16, 40), 0x9b59b6, 0, 4);
      addToy(new THREE.BoxGeometry(3, 0.8, 1.2), 0x16a085, 1, -1.5);
      addToy(new THREE.DodecahedronGeometry(0.8), 0xc0392b, -2, 1);
    6. [Obj 3, 4] Add the three lights. The spot light is the torch; it shines at torch.target, which must be added to the scene too.
      // ---------- lights ----------
      scene.add(new THREE.AmbientLight(0x404a66, 0.25));        // almost dark everywhere
      
      const lamp = new THREE.PointLight(0xffaa55, 12, 8);        // a small warm lamp in a corner
      lamp.position.set(-7, 2.5, -7);
      scene.add(lamp);
      
      const torch = new THREE.SpotLight(0xfff2cc, 300, 30, Math.PI / 10, 0.4);
      torch.position.set(0, 9, 4);
      torch.castShadow = true;                                   // switch 3: the light casts shadows
      torch.shadow.mapSize.set(1024, 1024);
      scene.add(torch);
      scene.add(torch.target);                                   // the point the torch shines at
    7. [Obj 1, 2] Add the gems. They are placed at random, but never inside a toy. userData stores whether each gem is found.
      // ---------- gems ----------
      const gemGeometry = new THREE.OctahedronGeometry(0.35);
      const gems = [];
      function placeGems() {
        gems.forEach(function (g) { scene.remove(g); });
        gems.length = 0;
        while (gems.length < 6) {
          const x = (Math.random() * 2 - 1) * (ROOM - 1.5);
          const z = (Math.random() * 2 - 1) * (ROOM - 1.5);
          const tooClose = toys.some(function (t) { return Math.hypot(t.position.x - x, t.position.z - z) < 1.8; });
          if (tooClose) continue;                                  // never inside a toy
          const gem = new THREE.Mesh(gemGeometry,
            new THREE.MeshStandardMaterial({ color: 0xffd34d, metalness: 0.6, roughness: 0.3, emissive: 0x000000 }));
          gem.position.set(x, 0.4, z);
          gem.castShadow = true;
          gem.userData = { found: false, glow: 0 };
          scene.add(gem);
          gems.push(gem);
        }
      }
    8. [Obj 8] Add the game state with startGame() and endGame().
      // ---------- game state ----------
      let state = "ready";     // "ready", "playing" or "over"
      let found = 0;
      let timeLeft = 60;
      const foundEl = document.getElementById("found");
      const timeEl = document.getElementById("time");
      const msgEl = document.getElementById("msg");
      
      function startGame() {
        placeGems();
        found = 0;
        timeLeft = 60;
        torch.target.position.set(0, 0, 0);
        foundEl.textContent = 0;
        msgEl.innerHTML = "";
        state = "playing";
      }
      
      function endGame(text) {
        state = "over";
        msgEl.innerHTML = text + "<br>Press Enter to play again";
      }
    9. [Obj 7] Add the keyboard. The keys object remembers which keys are held down, so the torch moves smoothly every frame.
      // ---------- keyboard: remember which keys are held down ----------
      const keys = {};
      window.addEventListener("keydown", function (e) {
        keys[e.code] = true;
        if (e.code.startsWith("Arrow")) e.preventDefault();
        if (e.code === "Enter" && state !== "playing") startGame();
      });
      window.addEventListener("keyup", function (e) { keys[e.code] = false; });
      
      const SPEED = 6;   // torch speed in units per second
      function moveTorch(dt) {
        const t = torch.target.position;
        if (keys.ArrowLeft || keys.KeyA) t.x -= SPEED * dt;
        if (keys.ArrowRight || keys.KeyD) t.x += SPEED * dt;
        if (keys.ArrowUp || keys.KeyW) t.z -= SPEED * dt;
        if (keys.ArrowDown || keys.KeyS) t.z += SPEED * dt;
        t.x = THREE.MathUtils.clamp(t.x, -ROOM + 0.5, ROOM - 0.5);   // stay inside the room
        t.z = THREE.MathUtils.clamp(t.z, -ROOM + 0.5, ROOM - 0.5);
        torch.position.x = t.x * 0.4;                                 // the torch leans as it turns
      }
    10. [Obj 2, 8] Add checkGems(). The torch must stay within 1 unit of a gem for half a second.
      // A gem is found when the torch stays on it for half a second
      function checkGems(dt) {
        gems.forEach(function (g) {
          if (g.userData.found) {                       // found gems float up and spin
            g.rotation.y += 3 * dt;
            g.position.y = Math.min(g.position.y + dt, 1.5);
            return;
          }
          if (state !== "playing") return;
          const aim = new THREE.Vector3(torch.target.position.x, g.position.y, torch.target.position.z);
          if (g.position.distanceTo(aim) < 1.0) {
            g.userData.glow += dt;
            if (g.userData.glow > 0.5) {
              g.userData.found = true;
              g.material.emissive.set(0xffaa00);         // make it glow
              found++;
              foundEl.textContent = found;
              if (found === gems.length) endGame("You found them all with " + Math.ceil(timeLeft) + " s left!");
            }
          } else {
            g.userData.glow = 0;
          }
        });
      }
    11. [Obj 3, 6, 8] Finish with the animation loop (countdown, controls.update()), the resize handler and the first placeGems().
      // ---------- animation loop ----------
      const clock = new THREE.Clock();
      renderer.setAnimationLoop(function () {
        const dt = Math.min(clock.getDelta(), 0.1);
        if (state === "playing") {
          moveTorch(dt);
          timeLeft -= dt;
          timeEl.textContent = Math.max(0, Math.ceil(timeLeft));
          if (timeLeft <= 0) endGame("Time is up! You found " + found + " of 6.");
        }
        checkGems(dt);
        controls.update();                              // needed for damping
        renderer.render(scene, camera);
      });
      
      window.addEventListener("resize", function () {
        camera.aspect = window.innerWidth / window.innerHeight;
        camera.updateProjectionMatrix();
        renderer.setSize(window.innerWidth, window.innerHeight);
      });
      
      placeGems();
    12. Save, press Enter and hunt. Keep the console (F12) open for errors.
Finished example output — click the game first so it receives your key presses

Click the game, press Enter, then steer the torch with the arrow keys or WASD. Drag to orbit and scroll to zoom.

📚 The four kinds of light