Week 11 Lab Sheet — Mouse Picking

Web Games Development · Mouse picking · ~150 minutes

Objectives

  1. Convert the mouse position to normalised device coordinates (−1 to +1).
  2. Cast a ray from the camera with Raycaster.setFromCamera.
  3. Find objects under the pointer with intersectObjects (including groups).
  4. Use the hit result: the closest object, its point and distance.
  5. Give hover feedback: a highlight and a pointer cursor.
  6. Place an object on a surface under the pointer with ray.intersectPlane.
  7. Run game objects as state machines with timed random spawning.
  8. Animate feedback: squash with scale and swing with Math.sin.

Instructions

Set up a Week11 npm project (step 1), keep npx vite running, and open each file at http://localhost:5173/ followed by its name. Build the example files, then the game, writing the code shown. Save after each step and watch the browser reload. Tick each checkpoint.

Files

1. Set up your Week11 project npm · Vite

Week11\

  1. Create a folder named Week11, 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/ray.html. Press Ctrl+C in the terminal to stop it.
    npx vite
Checkpoint: the folder has package.json and node_modules, and npx vite shows Local: http://localhost:5173/.

2. ray.html Concept 1 · From pixels to a ray

Week11\ray.html

  1. Create ray.html and add this code. Move the mouse over the floor: the red dot follows the point where the ray from the camera meets the floor.
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8" />
    <title>Where Does the Ray Meet the Floor?</title>
    <style>
      body { margin: 0; overflow: hidden; background: #fffdf8; font-family: monospace; }
      #info { position: absolute; left: 16px; top: 12px; font-size: 20px; color: #1b2030; }
    </style>
    </head>
    <body>
    <div id="info">Move the mouse over the floor</div>
    <script type="module">
    import * as THREE from "three";
    
    const scene = new THREE.Scene();
    scene.background = new THREE.Color(0xfffdf8);
    const camera = new THREE.PerspectiveCamera(50, window.innerWidth / window.innerHeight, 0.1, 100);
    camera.position.set(0, 7, 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.HemisphereLight(0xffffff, 0x445566, 1.5));
    scene.add(new THREE.GridHelper(12, 12, 0x888888, 0xcccccc));   // a grid to show the floor
    
    const dot = new THREE.Mesh(new THREE.SphereGeometry(0.2, 16, 12),
                               new THREE.MeshStandardMaterial({ color: 0xff3333 }));
    scene.add(dot);
    
    const raycaster = new THREE.Raycaster();
    const pointer = new THREE.Vector2();                                   // -1 to +1
    const floorPlane = new THREE.Plane(new THREE.Vector3(0, 1, 0), 0);     // the plane y = 0
    const hit = new THREE.Vector3();
    const info = document.getElementById("info");
    
    window.addEventListener("pointermove", function (e) {
      // pixels -> normalised coordinates (flip y: screen y goes down, 3D y goes up)
      pointer.x = (e.clientX / window.innerWidth) * 2 - 1;
      pointer.y = -(e.clientY / window.innerHeight) * 2 + 1;
      raycaster.setFromCamera(pointer, camera);           // a ray from the camera through the pointer
      if (raycaster.ray.intersectPlane(floorPlane, hit)) {
        dot.position.copy(hit);                           // put the dot where the ray meets the floor
      }
      info.textContent = "pointer = (" + pointer.x.toFixed(2) + ", " + pointer.y.toFixed(2) + ")";
    });
    
    renderer.setAnimationLoop(function () {
      renderer.render(scene, camera);
    });
    </script>
    </body>
    </html>
  2. Save. With npx vite running, open http://localhost:5173/ray.html. You should see a red dot under the mouse and the pointer numbers changing from −1 to +1.
  3. [Try it]
    1. Move the mouse to each corner and write down the four pairs of numbers.
    2. Remove the minus sign from the pointer.y line: what goes wrong?
    3. Put it back, then make the dot bigger.
Checkpoint: about (−1, 1) top-left and (1, −1) bottom-right; without the minus the dot moves the opposite way up and down.

3. pick.html Concept 2 · What did I hit?

Week11\pick.html

  1. Create pick.html and add this code. Move the mouse over the cubes: the nearest cube under the mouse turns red and the yellow dot marks the exact hit point.
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8" />
    <title>The Nearest Cube Lights Up</title>
    <style>
      body { margin: 0; overflow: hidden; background: #fffdf8; font-family: monospace; }
      #info { position: absolute; left: 16px; top: 12px; font-size: 20px; color: #1b2030; }
    </style>
    </head>
    <body>
    <div id="info">Move the mouse over the cubes</div>
    <script type="module">
    import * as THREE from "three";
    
    const scene = new THREE.Scene();
    scene.background = new THREE.Color(0xfffdf8);
    const camera = new THREE.PerspectiveCamera(50, 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);
    document.body.appendChild(renderer.domElement);
    scene.add(new THREE.HemisphereLight(0xffffff, 0x445566, 1.5));
    const sun = new THREE.DirectionalLight(0xffffff, 1.5);
    sun.position.set(3, 6, 5);
    scene.add(sun);
    
    // three rows of five cubes, each with its own material
    const cubes = [];
    for (let row = 0; row < 3; row++) {
      for (let col = 0; col < 5; col++) {
        const cube = new THREE.Mesh(new THREE.BoxGeometry(1, 1, 1),
                                    new THREE.MeshStandardMaterial({ color: 0x2563eb }));
        cube.position.set(col * 1.6 - 3.2, 0.5, row * 1.6 - 1.6);
        scene.add(cube);
        cubes.push(cube);
      }
    }
    
    // a small yellow ball marks the exact point the ray touched
    const marker = new THREE.Mesh(new THREE.SphereGeometry(0.1),
                                  new THREE.MeshBasicMaterial({ color: 0xffcc00 }));
    scene.add(marker);
    
    const raycaster = new THREE.Raycaster();
    const pointer = new THREE.Vector2();
    const info = document.getElementById("info");
    
    window.addEventListener("pointermove", function (e) {
      pointer.x = (e.clientX / window.innerWidth) * 2 - 1;
      pointer.y = -(e.clientY / window.innerHeight) * 2 + 1;
      raycaster.setFromCamera(pointer, camera);
    
      const hits = raycaster.intersectObjects(cubes, true);    // every hit, nearest first
      cubes.forEach(function (c) { c.material.color.set(0x2563eb); });
      marker.visible = hits.length > 0;
      if (hits.length > 0) {
        const first = hits[0];                                 // the nearest one
        first.object.material.color.set(0xff3333);
        marker.position.copy(first.point);
        info.textContent = "hits: " + hits.length + "   nearest distance: " + first.distance.toFixed(2);
      } else {
        info.textContent = "hits: 0";
      }
    });
    
    renderer.setAnimationLoop(function () {
      renderer.render(scene, camera);
    });
    </script>
    </body>
    </html>
  2. Save. With npx vite running, open http://localhost:5173/pick.html. You should see the cube under the mouse turn red, with a yellow dot where the ray touched it.
  3. [Try it]
    1. Show hits.length: point at a gap between two rows. How many hits?
    2. Colour every hit cube orange, and only the nearest red.
    3. Lower the camera to (0, 2, 9) so cubes hide behind each other.
Checkpoint: one ray can pass through several cubes; only hits[0] (the nearest) is red.

4. hover.html Concept 3 · Hover and click

Week11\hover.html

  1. Create hover.html and add this code. Hover over a ball to make it glow, then click to pop it. Popped balls grow back.
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8" />
    <title>Highlight, Then Pop</title>
    <style>
      body { margin: 0; overflow: hidden; background: #fffdf8; font-family: Arial, Helvetica, sans-serif; }
      #info { position: absolute; left: 16px; top: 12px; font-size: 20px; color: #1b2030; }
    </style>
    </head>
    <body>
    <div id="info">Hover over a ball, then click to pop it</div>
    <script type="module">
    import * as THREE from "three";
    
    const scene = new THREE.Scene();
    scene.background = new THREE.Color(0xfffdf8);
    const camera = new THREE.PerspectiveCamera(50, window.innerWidth / window.innerHeight, 0.1, 100);
    camera.position.set(0, 5, 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.HemisphereLight(0xffffff, 0x445566, 1.5));
    const sun = new THREE.DirectionalLight(0xffffff, 1.5);
    sun.position.set(3, 6, 5);
    scene.add(sun);
    
    const balls = [];
    const colours = [0xe8823a, 0x2563eb, 0x12854f];
    for (let i = 0; i < 7; i++) {
      const ball = new THREE.Mesh(new THREE.SphereGeometry(0.55, 24, 16),
                                  new THREE.MeshStandardMaterial({ color: colours[i % 3] }));
      ball.position.set(i * 1.4 - 4.2, 0.6, 0);
      scene.add(ball);
      balls.push(ball);
    }
    
    const raycaster = new THREE.Raycaster();
    const pointer = new THREE.Vector2();
    let hovered = null;                     // the ball under the mouse, or null
    
    window.addEventListener("pointermove", function (e) {
      pointer.x = (e.clientX / window.innerWidth) * 2 - 1;
      pointer.y = -(e.clientY / window.innerHeight) * 2 + 1;
      raycaster.setFromCamera(pointer, camera);
      const hits = raycaster.intersectObjects(balls);
      hovered = hits.length ? hits[0].object : null;
      balls.forEach(function (b) {
        b.material.emissive.set(b === hovered ? 0x664422 : 0x000000);   // glow only the hovered ball
      });
      document.body.style.cursor = hovered ? "pointer" : "default";
    });
    
    window.addEventListener("pointerdown", function () {
      if (hovered) hovered.scale.setScalar(0.01);   // pop!
    });
    
    const clock = new THREE.Clock();
    renderer.setAnimationLoop(function () {
      const dt = clock.getDelta();
      balls.forEach(function (b) {                  // popped balls slowly grow back
        b.scale.setScalar(Math.min(1, b.scale.x + 0.8 * dt));
      });
      renderer.render(scene, camera);
    });
    </script>
    </body>
    </html>
  2. Save. With npx vite running, open http://localhost:5173/hover.html. You should see balls that glow under the mouse, a hand cursor, and pops when you click.
  3. [Try it]
    1. Make the hovered ball grow to 1.2 as well as glow.
    2. Count the pops and show the number in #info.
    3. Make balls grow back twice as slowly.
Checkpoint: a bigger, glowing hovered ball and a pop counter that goes up with each click.

5. moleStates.html Concept 4 · State machines

Week11\moleStates.html

  1. Create moleStates.html and add this code. The label shows the current state as the mole goes round the cycle.
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8" />
    <title>One Mole, Four States</title>
    <style>
      body { margin: 0; overflow: hidden; background: #fffdf8; font-family: monospace; }
      #label { position: absolute; left: 0; right: 0; top: 20px; text-align: center; font-size: 30px; font-weight: bold; color: #a84c14; }
    </style>
    </head>
    <body>
    <div id="label"></div>
    <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, 3, 6);
    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.HemisphereLight(0xffffff, 0x557744, 1.4));
    const sun = new THREE.DirectionalLight(0xffffff, 1.5);
    sun.position.set(3, 6, 5);
    scene.add(sun);
    
    // a board (top at y = 0) with one hole, and a mole hidden inside it
    const board = new THREE.Mesh(new THREE.BoxGeometry(4, 1.5, 3),
                                 new THREE.MeshStandardMaterial({ color: 0x6aa84f }));
    board.position.y = -0.75;
    scene.add(board);
    const hole = new THREE.Mesh(new THREE.CircleGeometry(0.7, 32),
                                new THREE.MeshBasicMaterial({ color: 0x1a1208 }));
    hole.rotation.x = -Math.PI / 2;
    hole.position.y = 0.01;
    scene.add(hole);
    const mole = new THREE.Mesh(new THREE.CapsuleGeometry(0.45, 0.5, 8, 16),
                                new THREE.MeshStandardMaterial({ color: 0x7a5230 }));
    mole.position.y = -1;
    scene.add(mole);
    
    const DOWN_Y = -1, UP_Y = 0.35, SPEED = 3;
    let state = "down";       // "down", "rising", "up" or "falling"
    let timer = 1;            // seconds left in this state
    const label = document.getElementById("label");
    
    const clock = new THREE.Clock();
    renderer.setAnimationLoop(function () {
      const dt = Math.min(clock.getDelta(), 0.05);
    
      // only the code for the current state runs
      if (state === "down") {
        timer -= dt;
        if (timer <= 0) state = "rising";
      } else if (state === "rising") {
        mole.position.y = Math.min(UP_Y, mole.position.y + SPEED * dt);
        if (mole.position.y === UP_Y) { state = "up"; timer = 1.2; }
      } else if (state === "up") {
        timer -= dt;
        if (timer <= 0) state = "falling";
      } else if (state === "falling") {
        mole.position.y = Math.max(DOWN_Y, mole.position.y - SPEED * dt);
        if (mole.position.y === DOWN_Y) { state = "down"; timer = 1; }
      }
    
      label.textContent = 'state = "' + state + '"';
      renderer.render(scene, camera);
    });
    </script>
    </body>
    </html>
  2. Save. With npx vite running, open http://localhost:5173/moleStates.html. You should see a mole cycling through its states.
  3. [Try it]
    1. Change how long the mole stays up from 1.2 to 0.5 seconds.
    2. Add a "peek" state: rise only to y = −0.3, wait 0.4 s, then fall.
    3. Use "peek" every second time the mole comes up.
Checkpoint: the label shows the new state, and the mole sometimes only peeks out of the hole.

6. whackAMole.html Objectives 1–8

Week11\whackAMole.html

  1. Create whackAMole.html with this scaffold.
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8" />
    <title>Whack-a-Mole 3D</title>
    <style>
      body { margin: 0; overflow: hidden; background: #8fd3ff; font-family: Arial, Helvetica, sans-serif; }
      #hud { position: absolute; top: 10px; left: 12px; color: #ffffff; font-size: 22px; pointer-events: none; text-shadow: 0 1px 3px #000; }
      #msg { position: absolute; top: 30%; left: 0; right: 0; text-align: center; color: #ffffff; font-size: 30px; pointer-events: none; text-shadow: 0 2px 6px #000; }
    </style>
    </head>
    <body>
    <div id="hud">Score: <span id="score">0</span> &nbsp;&nbsp; Misses: <span id="misses">0</span> &nbsp;&nbsp; Time: <span id="time">45</span></div>
    <div id="msg">Whack the moles before they hide!<br>Golden moles are worth 3<br>Click to start</div>
    
    <script type="module">
    import * as THREE from "three";
    
    // TODO: the steps below go here
    </script>
    </body>
    </html>
  2. Add the scene, camera, renderer and lights. The camera looks down at the board from the front.
    // ---------- scene, camera, renderer ----------
    const scene = new THREE.Scene();
    scene.background = new THREE.Color(0x8fd3ff);
    const camera = new THREE.PerspectiveCamera(50, window.innerWidth / window.innerHeight, 0.1, 100);
    camera.position.set(0, 9, 8);
    camera.lookAt(0, 0, 0.5);
    const renderer = new THREE.WebGLRenderer({ antialias: true });
    renderer.setSize(window.innerWidth, window.innerHeight);
    renderer.shadowMap.enabled = true;
    document.body.appendChild(renderer.domElement);
    
    scene.add(new THREE.HemisphereLight(0xffffff, 0x557744, 1.3));
    const sun = new THREE.DirectionalLight(0xffffff, 2);
    sun.position.set(4, 10, 6);
    sun.castShadow = true;
    scene.add(sun);
  3. Add the board and the nine holes. The top of the board is at y = 0, so anything below that is hidden.
    // ---------- the board with nine holes ----------
    const board = new THREE.Mesh(new THREE.BoxGeometry(8, 1.5, 8),
                                 new THREE.MeshStandardMaterial({ color: 0x6aa84f }));
    board.position.y = -0.75;            // the top of the board is at y = 0
    board.receiveShadow = true;
    scene.add(board);
    
    const HOLES = [];
    for (let row = -1; row <= 1; row++) {
      for (let col = -1; col <= 1; col++) {
        HOLES.push(new THREE.Vector3(col * 2.4, 0, row * 2.4));
      }
    }
    const holeGeo = new THREE.CircleGeometry(0.7, 32);
    const holeMat = new THREE.MeshBasicMaterial({ color: 0x1a1208 });
    HOLES.forEach(function (p) {
      const hole = new THREE.Mesh(holeGeo, holeMat);
      hole.rotation.x = -Math.PI / 2;
      hole.position.set(p.x, 0.01, p.z);
      scene.add(hole);
    });
  4. [Obj 7] Add makeMole(). Each mole is a group with its own fur material, and starts in the "down" state.
    // ---------- moles ----------
    const DOWN_Y = -1.0;     // hidden inside the board
    const UP_Y = 0.35;       // head and shoulders out of the hole
    const moles = [];
    const BROWN = 0x7a5230, GOLD = 0xffcc33;
    
    function makeMole(p) {
      const mole = new THREE.Group();
      const fur = new THREE.MeshStandardMaterial({ color: BROWN, roughness: 0.8 });   // its own material
      const body = new THREE.Mesh(new THREE.CapsuleGeometry(0.45, 0.5, 8, 16), fur);
      mole.add(body);
      const white = new THREE.MeshBasicMaterial({ color: 0xffffff });
      const black = new THREE.MeshBasicMaterial({ color: 0x000000 });
      [-0.17, 0.17].forEach(function (x) {
        const eye = new THREE.Mesh(new THREE.SphereGeometry(0.1, 12, 8), white);
        eye.position.set(x, 0.35, 0.38);
        const pupil = new THREE.Mesh(new THREE.SphereGeometry(0.05, 8, 6), black);
        pupil.position.set(x, 0.35, 0.47);
        mole.add(eye, pupil);
      });
      const nose = new THREE.Mesh(new THREE.SphereGeometry(0.09, 12, 8),
                                  new THREE.MeshStandardMaterial({ color: 0xff8fa3 }));
      nose.position.set(0, 0.2, 0.45);
      mole.add(nose);
      mole.traverse(function (part) { part.castShadow = true; });
      mole.position.set(p.x, DOWN_Y, p.z);
      mole.userData = { state: "down", timer: 0, body: body, golden: false };
      scene.add(mole);
      return mole;
    }
    HOLES.forEach(function (p) { moles.push(makeMole(p)); });
  5. [Obj 6] Add the hammer: a handle and a head in a group.
    // ---------- the hammer follows the mouse across the board ----------
    const hammer = new THREE.Group();
    const handle = new THREE.Mesh(new THREE.CylinderGeometry(0.08, 0.08, 1.6, 12),
                                  new THREE.MeshStandardMaterial({ color: 0x8b5a2b }));
    handle.position.y = 0.8;
    const head = new THREE.Mesh(new THREE.CylinderGeometry(0.35, 0.35, 0.9, 20),
                                new THREE.MeshStandardMaterial({ color: 0x555a66, metalness: 0.6, roughness: 0.4 }));
    head.rotation.z = Math.PI / 2;
    head.position.y = 1.6;
    hammer.add(handle, head);
    hammer.traverse(function (part) { part.castShadow = true; });
    scene.add(hammer);
    let swing = 0;           // > 0 while the hammer is swinging down
  6. [Obj 1, 2, 3, 4] Add the raycaster. setPointer() converts the mouse to −1…+1 and aims the ray; moleUnderPointer() finds the nearest mole (the board blocks hidden ones).
    // ---------- the raycaster: what is under the mouse? ----------
    const raycaster = new THREE.Raycaster();
    const pointer = new THREE.Vector2();                         // -1 to +1 on both axes
    const boardTop = new THREE.Plane(new THREE.Vector3(0, 1, 0), 0);   // the plane y = 0
    const hitPoint = new THREE.Vector3();
    
    function setPointer(e) {
      pointer.x = (e.clientX / window.innerWidth) * 2 - 1;
      pointer.y = -(e.clientY / window.innerHeight) * 2 + 1;    // screen y goes down, 3D y goes up
      raycaster.setFromCamera(pointer, camera);
    }
    
    // Which mole (if any) is the ray pointing at? The board blocks moles hidden inside it.
    function moleUnderPointer() {
      const hits = raycaster.intersectObjects([board].concat(moles), true);
      if (hits.length === 0) return null;
      let obj = hits[0].object;                                  // the closest thing hit
      while (obj && !moles.includes(obj)) obj = obj.parent;      // climb up to the mole group
      return obj;
    }
  7. [Obj 3, 5, 6] Add the two pointer listeners: pointermove moves the hammer and finds the hovered mole; pointerdown whacks.
    let hovered = null;
    window.addEventListener("pointermove", function (e) {
      setPointer(e);
      if (raycaster.ray.intersectPlane(boardTop, hitPoint)) {    // hammer follows the board
        hammer.position.x = THREE.MathUtils.clamp(hitPoint.x, -4, 4);
        hammer.position.z = THREE.MathUtils.clamp(hitPoint.z, -4, 4) + 1.4;   // stand in front, land on the spot
      }
      const mole = moleUnderPointer();
      hovered = mole && mole.userData.state === "up" ? mole : null;
      document.body.style.cursor = hovered ? "pointer" : "default";
    });
    
    window.addEventListener("pointerdown", function (e) {
      if (state !== "playing") { startGame(); return; }
      setPointer(e);
      swing = 1;
      const mole = moleUnderPointer();
      if (mole && (mole.userData.state === "up" || mole.userData.state === "rising")) {
        mole.userData.state = "hit";
        mole.userData.timer = 0.25;
        score += mole.userData.golden ? 3 : 1;
        scoreEl.textContent = score;
      } else {
        misses++;
        missesEl.textContent = misses;
      }
    });
  8. [Obj 5, 7, 8] Add updateMole(), the state machine, with the squash and the hover glow.
    // ---------- each mole is a little state machine ----------
    //   down -> rising -> up -> falling -> down     (or up -> hit -> falling)
    const RISE_SPEED = 6;
    let upTime = 1.3;        // how long a mole stays up (gets shorter)
    function updateMole(m, dt) {
      const u = m.userData;
      if (u.state === "rising") {
        m.position.y = Math.min(UP_Y, m.position.y + RISE_SPEED * dt);
        if (m.position.y === UP_Y) { u.state = "up"; u.timer = upTime; }
      } else if (u.state === "up") {
        u.timer -= dt;
        if (u.timer <= 0) u.state = "falling";
      } else if (u.state === "hit") {
        u.timer -= dt;
        m.scale.set(1.3, 0.5, 1.3);                              // squashed!
        if (u.timer <= 0) { m.scale.set(1, 1, 1); u.state = "falling"; }
      } else if (u.state === "falling") {
        m.position.y = Math.max(DOWN_Y, m.position.y - RISE_SPEED * dt);
        if (m.position.y === DOWN_Y) u.state = "down";
      }
      u.body.material.emissive.set(m === hovered ? 0x664422 : 0x000000);   // glow under the mouse
    }
  9. [Obj 7] Add spawn(): now and then, a random hidden mole starts rising.
    // ---------- spawning: pop up a random hidden mole now and then ----------
    let spawnTimer = 0;
    function spawn(dt) {
      spawnTimer -= dt;
      if (spawnTimer > 0) return;
      spawnTimer = 0.5 + Math.random() * 0.6;
      const hidden = moles.filter(function (m) { return m.userData.state === "down"; });
      if (hidden.length === 0) return;
      const m = hidden[Math.floor(Math.random() * hidden.length)];
      m.userData.golden = Math.random() < 0.12;                 // sometimes a golden mole
      m.userData.body.material.color.set(m.userData.golden ? GOLD : BROWN);
      m.userData.state = "rising";
    }
  10. Add the game state.
    // ---------- game state ----------
    let state = "ready";
    let score = 0, misses = 0, timeLeft = 45;
    const scoreEl = document.getElementById("score");
    const missesEl = document.getElementById("misses");
    const timeEl = document.getElementById("time");
    const msgEl = document.getElementById("msg");
    
    function startGame() {
      score = 0; misses = 0; timeLeft = 45; upTime = 1.3;
      scoreEl.textContent = 0; missesEl.textContent = 0;
      msgEl.innerHTML = "";
      state = "playing";
    }
  11. [Obj 8] Finish with the animation loop (the hammer swing uses Math.sin) and the resize handler.
    // ---------- animation loop ----------
    const clock = new THREE.Clock();
    renderer.setAnimationLoop(function () {
      const dt = Math.min(clock.getDelta(), 0.05);
      if (state === "playing") {
        spawn(dt);
        timeLeft -= dt;
        upTime = Math.max(0.6, upTime - 0.01 * dt);             // moles get quicker
        timeEl.textContent = Math.max(0, Math.ceil(timeLeft));
        if (timeLeft <= 0) {
          state = "over";
          msgEl.innerHTML = "Time! Score " + score + " (" + misses + " misses)<br>Click to play again";
        }
      }
      moles.forEach(function (m) { updateMole(m, dt); });
    
      // swing the hammer down and back up
      swing = Math.max(0, swing - 5 * dt);
      hammer.rotation.x = -Math.sin(swing * Math.PI) * 1.3;
    
      renderer.render(scene, camera);
    });
    
    window.addEventListener("resize", function () {
      camera.aspect = window.innerWidth / window.innerHeight;
      camera.updateProjectionMatrix();
      renderer.setSize(window.innerWidth, window.innerHeight);
    });
  12. Save, click to start and whack. Keep the console (F12) open for errors.
Checkpoint: moles pop up, glow under the mouse, squash when clicked; the hammer follows and swings; score, misses and time work (Objectives 1-8).

Marking rubric

CriterionPointsScore
Pointer converted to normalised coordinates2
Raycaster finds the clicked mole (groups, nearest hit)4
Hover glow and hammer on the board3
Moles run as state machines with random spawns3
Squash and swing feedback; score, misses, time2
Runs with no console errors1
Total15

Common errors

Progress and quiz scores are also tracked on the Week 11 lab page in the class website.