Web Games Development · Mouse picking · ~150 minutes
Raycaster.setFromCamera.intersectObjects (including groups).object, its point and distance.ray.intersectPlane.scale and swing with Math.sin.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.
Week11\
Week11, open it in VS Code, and open the terminal with Ctrl+`.npm init -y
npm install three@0.170.0
npm install --save-dev vite@5
package.json from Materials for this week into the folder, then run npm install instead.http://localhost:5173/ray.html. Press Ctrl+C in the terminal to stop it.
npx vite
package.json and node_modules, and npx vite shows Local: http://localhost:5173/.Week11\ray.html
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>
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.pointer.y line: what goes wrong?Week11\pick.html
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>
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.hits.length: point at a gap between two rows. How many hits?(0, 2, 9) so cubes hide behind each other.Week11\hover.html
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>
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.#info.Week11\moleStates.html
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>
npx vite running, open http://localhost:5173/moleStates.html. You should see a mole cycling through its states.Week11\whackAMole.html
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> Misses: <span id="misses">0</span> 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>
// ---------- 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);
// ---------- 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);
});
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)); });
// ---------- 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
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;
}
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;
}
});
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
}
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";
}
// ---------- 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";
}
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);
});
| Criterion | Points | Score |
|---|---|---|
| Pointer converted to normalised coordinates | 2 | |
| Raycaster finds the clicked mole (groups, nearest hit) | 4 | |
| Hover glow and hammer on the board | 3 | |
| Moles run as state machines with random spawns | 3 | |
| Squash and swing feedback; score, misses, time | 2 | |
| Runs with no console errors | 1 | |
| Total | 15 |
pointer.y, so clicks are upside down.true in intersectObjects, so mole parts are not tested.click instead of pointerdown, so fast clicks feel slow.Progress and quiz scores are also tracked on the Week 11 lab page in the class website.