Web Games Development · Materials, lights & shadows · ~150 minutes
PlaneGeometry, SphereGeometry, CylinderGeometry, ConeGeometry and more.MeshStandardMaterial: color, roughness, metalness, emissive.AmbientLight, PointLight and SpotLight.shadowMap, castShadow and receiveShadow.OrbitControls.distanceTo, and run a countdown.Set up a Week8 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.
Week8\
Week8, 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/materials.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/.Week8\materials.html
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>
npx vite running, open http://localhost:5173/materials.html. You should see matt, shiny, metal and glowing.OctahedronGeometry(0.6) and { color: 0xffd34d, metalness: 0.6, roughness: 0.3 }.emissive: 0xffaa00.Week8\lights.html
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>
npx vite running, open http://localhost:5173/lights.html. You should see a moving point light and a spot light.Math.PI / 6.AmbientLight up to 1, then back down.Week8\shadows.html
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>
npx vite running, open http://localhost:5173/shadows.html. You should see moving shadows on the floor.floor.receiveShadow = true and refresh.sun.shadow.mapSize.set(256, 256).sun.position.set(4, 6, 2).Week8\orbit.html
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>
npx vite running, open http://localhost:5173/orbit.html. You should see auto-orbiting camera; the gem glows when the marker is close.controls.autoRotate = false and drag the view yourself.controls.minDistance = 4 and controls.maxDistance = 14.Week8\torchHunt.html
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 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 · 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>
// ---------- 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);
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;
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)
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);
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
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);
}
}
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";
}
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
}
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;
}
});
}
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();
| Criterion | Points | Score |
|---|---|---|
| Room and toys built from several geometries | 2 | |
| Standard materials with roughness / metalness / emissive | 2 | |
| Ambient, point and spot lights | 3 | |
| Shadows working (all three switches) | 3 | |
| OrbitControls, key-state movement, distance check and timer | 4 | |
| Runs with no console errors | 1 | |
| Total | 15 |
three/addons/controls/OrbitControls.js.torch.position instead of torch.target.position.scene.add(torch.target).Progress and quiz scores are also tracked on the Week 8 lab page in the class website.