Web Games Development · Textures, sound & HUD · ~150 minutes
CanvasTexture and material.map.wrapS, wrapT and repeat; set the colour space.hit.uv and face.materialIndex.Vector3.project for popups.Set up a Week13 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.
Week13\
Week13, 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/canvasTexture.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/.Week13\canvasTexture.html
canvasTexture.html and add this code. The same drawing code as Week 2’s dice: one canvas painted on every face of a cube.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>A 3D Die Painted with Canvas</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, 5);
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, 0x887766, 1.6));
const sun = new THREE.DirectionalLight(0xffffff, 1.5);
sun.position.set(3, 4, 5);
scene.add(sun);
// 1. draw a dice face on a canvas that is never shown on the page
const c = document.createElement("canvas");
c.width = 128;
c.height = 128;
const ctx = c.getContext("2d");
ctx.fillStyle = "#ffffff";
ctx.fillRect(0, 0, 128, 128);
ctx.strokeStyle = "#cccccc";
ctx.lineWidth = 6;
ctx.strokeRect(3, 3, 122, 122);
ctx.fillStyle = "#d62828";
[[32, 32], [96, 32], [64, 64], [32, 96], [96, 96]].forEach(function (p) { // five dots
ctx.beginPath();
ctx.arc(p[0], p[1], 12, 0, Math.PI * 2);
ctx.fill();
});
// 2. turn the canvas into a texture
const tex = new THREE.CanvasTexture(c);
tex.colorSpace = THREE.SRGBColorSpace; // keep the colours the same as on the canvas
// 3. wrap it onto a cube with material.map
const die = new THREE.Mesh(new THREE.BoxGeometry(1.5, 1.5, 1.5),
new THREE.MeshStandardMaterial({ map: tex }));
scene.add(die);
const clock = new THREE.Clock();
renderer.setAnimationLoop(function () {
const dt = clock.getDelta();
die.rotation.x += 0.5 * dt;
die.rotation.y += 0.8 * dt;
renderer.render(scene, camera);
});
</script>
</body>
</html>
npx vite running, open http://localhost:5173/canvasTexture.html. You should see a cube wearing a canvas-drawn dice face.ctx.stroke().ctx.font and ctx.fillText.Week13\repeat.html
repeat.html and add this code. The repeat count grows and shrinks; the offset makes the pattern flow.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Tile It, Then Slide It</title>
<style>
body { margin: 0; overflow: hidden; background: #fffdf8; font-family: monospace; }
#info { position: absolute; left: 16px; top: 12px; font-size: 22px; color: #1b2030; }
</style>
</head>
<body>
<div id="info"></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, 4, 5);
camera.lookAt(0, 0, -1);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
scene.add(new THREE.HemisphereLight(0xffffff, 0x887766, 2));
// one small checker tile, drawn on a 64 x 64 canvas
const c = document.createElement("canvas");
c.width = 64;
c.height = 64;
const ctx = c.getContext("2d");
ctx.fillStyle = "#2563eb";
ctx.fillRect(0, 0, 64, 64);
ctx.fillStyle = "#ffd34d";
ctx.fillRect(0, 0, 32, 32);
ctx.fillRect(32, 32, 32, 32);
const tex = new THREE.CanvasTexture(c);
tex.colorSpace = THREE.SRGBColorSpace;
tex.wrapS = THREE.RepeatWrapping; // repeat across (u)
tex.wrapT = THREE.RepeatWrapping; // repeat along (v)
tex.magFilter = THREE.NearestFilter; // keep the squares crisp
const plane = new THREE.Mesh(new THREE.PlaneGeometry(6, 6),
new THREE.MeshStandardMaterial({ map: tex }));
plane.rotation.x = -Math.PI / 2;
scene.add(plane);
const info = document.getElementById("info");
const clock = new THREE.Clock();
renderer.setAnimationLoop(function () {
const dt = clock.getDelta();
const t = clock.elapsedTime * 0.6;
const n = 2 + Math.round((Math.sin(t) + 1) * 3); // between 2 and 8 copies
tex.repeat.set(n, n);
tex.offset.y += 0.3 * dt; // slide the pattern
info.textContent = "tex.repeat.set(" + n + ", " + n + ")";
renderer.render(scene, camera);
});
</script>
</body>
</html>
npx vite running, open http://localhost:5173/repeat.html. You should see a checker texture repeating and scrolling.tex.repeat.set(3, 3).offset.x.tex.wrapS and wrapT: what happens?Week13\soundDemo.html
soundDemo.html and add this code. Press 1 to 4 to hear the four wave types, and Space for a noise “bang”. The line shows the shape of the sound you just played.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Sound Effects with Web Audio</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; line-height: 1.5; color: #1b2030; }
</style>
</head>
<body>
<div id="info">Press 1, 2, 3 or 4 for a beep (sine, square, triangle, sawtooth) · Space for a bang</div>
<script type="module">
import * as THREE from "three";
// ---------- a picture of the last sound: a wave that fades out ----------
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xfffdf8);
const camera = new THREE.OrthographicCamera(-6, 6, 3, -3, 0.1, 10);
camera.position.z = 5;
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
camera.left = -3 * window.innerWidth / window.innerHeight;
camera.right = -camera.left;
camera.updateProjectionMatrix();
const N = 400;
const points = [];
for (let i = 0; i < N; i++) points.push(new THREE.Vector3(-5 + 10 * i / N, 0, 0));
const waveGeo = new THREE.BufferGeometry().setFromPoints(points);
scene.add(new THREE.Line(waveGeo, new THREE.LineBasicMaterial({ color: 0xa84c14 })));
function drawWave(type, cycles) {
const pos = waveGeo.attributes.position;
for (let i = 0; i < N; i++) {
const k = i / N;
const fade = 2.5 * Math.pow(0.001, k); // the volume fading out
const s = Math.sin(k * cycles * Math.PI * 2);
let y = s;
if (type === "square") y = Math.sign(s);
if (type === "triangle") y = 2 / Math.PI * Math.asin(s);
if (type === "sawtooth") y = 2 * ((k * cycles) % 1) - 1;
if (type === "noise") y = Math.random() * 2 - 1;
pos.setY(i, fade * y);
}
pos.needsUpdate = true;
}
// ---------- the sound engine ----------
let audio = null;
function initAudio() { // only allowed after the user presses a key or clicks
if (!audio) audio = new AudioContext();
if (audio.state === "suspended") audio.resume();
}
function beep(freq, duration, type, volume) {
const osc = audio.createOscillator();
const gain = audio.createGain();
osc.type = type; // "sine", "square", "triangle" or "sawtooth"
osc.frequency.value = freq; // pitch in hertz
gain.gain.setValueAtTime(volume, audio.currentTime);
gain.gain.exponentialRampToValueAtTime(0.001, audio.currentTime + duration); // fade out
osc.connect(gain).connect(audio.destination);
osc.start();
osc.stop(audio.currentTime + duration);
}
function bang() { // random noise that fades = a gunshot
const length = Math.floor(audio.sampleRate * 0.15);
const buffer = audio.createBuffer(1, length, audio.sampleRate);
const data = buffer.getChannelData(0);
for (let i = 0; i < length; i++) data[i] = (Math.random() * 2 - 1) * (1 - i / length);
const src = audio.createBufferSource();
const gain = audio.createGain();
gain.gain.value = 0.35;
src.buffer = buffer;
src.connect(gain).connect(audio.destination);
src.start();
}
const TYPES = { Digit1: "sine", Digit2: "square", Digit3: "triangle", Digit4: "sawtooth" };
window.addEventListener("keydown", function (e) {
initAudio();
if (TYPES[e.code]) {
beep(880, 0.4, TYPES[e.code], 0.3);
drawWave(TYPES[e.code], 9);
}
if (e.code === "Space") {
e.preventDefault();
bang();
drawWave("noise", 0);
}
});
drawWave("sine", 9);
renderer.setAnimationLoop(function () {
renderer.render(scene, camera);
});
</script>
</body>
</html>
npx vite running, open http://localhost:5173/soundDemo.html. You should see a fading wave on screen and a beep (or a bang) each time you press a key.setTimeout).Week13\labels.html
labels.html and add this code. Each frame, each ball’s position is projected to the screen and its HTML label moved there.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Labels That Follow 3D Objects</title>
<style>
body { margin: 0; overflow: hidden; background: #fffdf8; font-family: Arial, Helvetica, sans-serif; }
.label { position: absolute; transform: translate(-50%, -100%); font-size: 26px; font-weight: bold; color: #1b2030;
background: #ffffff; border: 2px solid #1b2030; border-radius: 8px; padding: 2px 8px; pointer-events: none; }
</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(50, window.innerWidth / window.innerHeight, 0.1, 100);
camera.position.set(0, 3, 8);
camera.lookAt(0, 0.5, 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, 0x887766, 1.6));
const sun = new THREE.DirectionalLight(0xffffff, 1.5);
sun.position.set(3, 4, 5);
scene.add(sun);
// three balls, each with an HTML label
const items = [];
[["+10", 0xffd60a], ["+5", 0xd62828], ["+2", 0x2563eb]].forEach(function (info, i) {
const ball = new THREE.Mesh(new THREE.SphereGeometry(0.5, 24, 16),
new THREE.MeshStandardMaterial({ color: info[1] }));
scene.add(ball);
const label = document.createElement("div");
label.className = "label";
label.textContent = info[0];
document.body.appendChild(label);
items.push({ ball: ball, label: label, index: i });
});
// 3D point -> screen pixels
const p = new THREE.Vector3();
function placeLabel(label, point) {
p.copy(point).project(camera); // -1..+1 on screen
label.style.left = ((p.x + 1) / 2 * window.innerWidth) + "px";
label.style.top = ((1 - p.y) / 2 * window.innerHeight) + "px"; // flip y for pixels
}
const clock = new THREE.Clock();
renderer.setAnimationLoop(function () {
const t = clock.getElapsedTime();
items.forEach(function (it) {
const a = t * 0.7 + it.index * 2.1;
it.ball.position.set(Math.cos(a) * 3, 0.5 + Math.sin(t * 2 + it.index) * 0.4, Math.sin(a) * 2);
placeLabel(it.label, it.ball.position.clone().add(new THREE.Vector3(0, 0.6, 0))); // just above the ball
});
renderer.render(scene, camera);
});
</script>
</body>
</html>
npx vite running, open http://localhost:5173/labels.html. You should see HTML labels pinned to moving 3D balls.ball.position.y.toFixed(1).Week13\targetRange.html
targetRange.html. The CSS draws the HUD, the crosshair (the real cursor is hidden) and the popup style.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Target Range</title>
<style>
body { margin: 0; overflow: hidden; background: #2b2118; font-family: Arial, Helvetica, sans-serif; cursor: none; user-select: none; }
#hud { position: absolute; top: 10px; left: 12px; right: 12px; display: flex; justify-content: space-between; color: #fff7e0; font-size: 22px; pointer-events: none; text-shadow: 0 1px 3px #000; }
#ammo { letter-spacing: 4px; }
#cross { position: absolute; width: 34px; height: 34px; margin: -17px 0 0 -17px; pointer-events: none;
border: 2px solid #ffffff; border-radius: 50%; box-shadow: 0 0 4px #000; }
#cross::after { content: ""; position: absolute; left: 15px; top: 15px; width: 4px; height: 4px; background: #ff3333; border-radius: 50%; }
.popup { position: absolute; color: #ffe066; font-size: 28px; font-weight: bold; pointer-events: none; text-shadow: 0 2px 4px #000;
transform: translate(-50%, -50%); transition: transform 0.8s ease-out, opacity 0.8s ease-out; }
#msg { position: absolute; top: 32%; 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">
<div>Score: <span id="score">0</span></div>
<div>Time: <span id="time">45</span></div>
<div id="ammo"></div>
</div>
<div id="cross"></div>
<div id="msg">Shoot the targets: the centre scores most<br>Click to shoot · R to reload · M to mute<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();
const camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 0.1, 100);
camera.position.set(0, 1.6, 6);
camera.lookAt(0, 1.6, -10);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
scene.add(new THREE.HemisphereLight(0xfff2dd, 0x4a3520, 1.4));
const lamp = new THREE.DirectionalLight(0xffffff, 1.6);
lamp.position.set(2, 6, 8);
scene.add(lamp);
makeCanvas() and targetTexture(): the rings are drawn with arc, biggest first.
// ---------- textures drawn with a 2D canvas ----------
function makeCanvas(w, h) {
const c = document.createElement("canvas");
c.width = w;
c.height = h;
return c;
}
// A bullseye: rings drawn from the outside in
function targetTexture() {
const c = makeCanvas(256, 256);
const ctx = c.getContext("2d");
const colours = ["#ffffff", "#d62828", "#ffffff", "#d62828", "#ffd60a"];
colours.forEach(function (col, i) {
ctx.beginPath();
ctx.arc(128, 128, 128 - i * 25, 0, Math.PI * 2);
ctx.fillStyle = col;
ctx.fill();
});
const tex = new THREE.CanvasTexture(c);
tex.colorSpace = THREE.SRGBColorSpace; // colours look the same as on the canvas
return tex;
}
// Wooden planks that repeat across the floor
function plankTexture() {
const c = makeCanvas(256, 256);
const ctx = c.getContext("2d");
for (let i = 0; i < 4; i++) {
const shade = 90 + Math.floor(Math.random() * 40);
ctx.fillStyle = "rgb(" + shade + "," + Math.floor(shade * 0.65) + "," + Math.floor(shade * 0.35) + ")";
ctx.fillRect(0, i * 64, 256, 64);
ctx.fillStyle = "rgba(0, 0, 0, 0.35)";
ctx.fillRect(0, i * 64, 256, 3); // the gap between planks
}
const tex = new THREE.CanvasTexture(c);
tex.colorSpace = THREE.SRGBColorSpace;
tex.wrapS = THREE.RepeatWrapping; // repeat across...
tex.wrapT = THREE.RepeatWrapping; // ...and along
tex.repeat.set(6, 12);
return tex;
}
// A sunset gradient for the background
function skyTexture() {
const c = makeCanvas(2, 256);
const ctx = c.getContext("2d");
const g = ctx.createLinearGradient(0, 0, 0, 256);
g.addColorStop(0, "#1e3c72");
g.addColorStop(0.6, "#f08a5d");
g.addColorStop(1, "#f9d976");
ctx.fillStyle = g;
ctx.fillRect(0, 0, 2, 256);
const tex = new THREE.CanvasTexture(c);
tex.colorSpace = THREE.SRGBColorSpace;
return tex;
}
scene.background = skyTexture();
const floor = new THREE.Mesh(new THREE.PlaneGeometry(30, 40),
new THREE.MeshStandardMaterial({ map: plankTexture() }));
floor.rotation.x = -Math.PI / 2;
floor.position.z = -10;
scene.add(floor);
updateTargets(). Each target uses three materials: edge, front face and back face.
// ---------- targets on three rails ----------
const bullseye = targetTexture();
const faceMat = new THREE.MeshStandardMaterial({ map: bullseye });
const edgeMat = new THREE.MeshStandardMaterial({ color: 0x6b4423 });
const targetGeo = new THREE.CylinderGeometry(0.8, 0.8, 0.12, 48);
targetGeo.rotateX(Math.PI / 2); // the round face now looks at the camera
const ROWS = [ { z: -5, y: 1.2, speed: 2.0 }, { z: -9, y: 2.2, speed: -2.8 }, { z: -13, y: 3.2, speed: 3.6 } ];
const targets = [];
ROWS.forEach(function (row) {
const rail = new THREE.Mesh(new THREE.BoxGeometry(20, 0.1, 0.1), edgeMat);
rail.position.set(0, row.y - 0.9, row.z);
scene.add(rail);
for (let i = 0; i < 3; i++) {
const t = new THREE.Mesh(targetGeo, [edgeMat, faceMat, faceMat]); // side, front, back
t.position.set(-8 + i * 5.5, row.y, row.z);
t.userData = { speed: row.speed, down: 0 }; // down > 0 while knocked over
scene.add(t);
targets.push(t);
}
});
function updateTargets(dt) {
targets.forEach(function (t) {
const u = t.userData;
t.position.x += u.speed * dt;
if (t.position.x > 9) t.position.x = -9; // wrap round to the other side
if (t.position.x < -9) t.position.x = 9;
if (u.down > 0) { // knocked over: lie flat, then stand up again
u.down -= dt;
t.rotation.x = Math.max(t.rotation.x - 8 * dt, -Math.PI / 2);
if (u.down <= 0) t.rotation.x = 0;
}
});
}
initAudio(), beep() and bang() (a burst of noise).
// ---------- sound effects with the Web Audio API (no sound files) ----------
let audio = null;
let muted = false;
function initAudio() { // browsers only allow sound after a click
if (!audio) audio = new AudioContext();
if (audio.state === "suspended") audio.resume();
}
function beep(freq, duration, type, volume) {
if (!audio || muted) return;
const osc = audio.createOscillator();
const gain = audio.createGain();
osc.type = type; // "sine", "square", "triangle" or "sawtooth"
osc.frequency.value = freq;
gain.gain.setValueAtTime(volume, audio.currentTime);
gain.gain.exponentialRampToValueAtTime(0.001, audio.currentTime + duration); // fade out
osc.connect(gain).connect(audio.destination);
osc.start();
osc.stop(audio.currentTime + duration);
}
function bang() { // a short burst of noise = a gunshot
if (!audio || muted) return;
const length = Math.floor(audio.sampleRate * 0.15);
const buffer = audio.createBuffer(1, length, audio.sampleRate);
const data = buffer.getChannelData(0);
for (let i = 0; i < length; i++) data[i] = (Math.random() * 2 - 1) * (1 - i / length);
const src = audio.createBufferSource();
const gain = audio.createGain();
gain.gain.value = 0.35;
src.buffer = buffer;
src.connect(gain).connect(audio.destination);
src.start();
}
popup(), which projects a 3D point to the screen.
// ---------- HUD: crosshair, ammo and popups ----------
const cross = document.getElementById("cross");
const scoreEl = document.getElementById("score");
const timeEl = document.getElementById("time");
const ammoEl = document.getElementById("ammo");
const msgEl = document.getElementById("msg");
const MAX_AMMO = 6;
let ammo = MAX_AMMO;
let reloading = 0;
function showAmmo() {
ammoEl.textContent = reloading > 0 ? "RELOADING" : "●".repeat(ammo) + "○".repeat(MAX_AMMO - ammo);
}
// Turn a 3D point into screen pixels and float a "+10" there
function popup(text, point) {
const p = point.clone().project(camera); // -1..+1 on screen
const div = document.createElement("div");
div.className = "popup";
div.textContent = text;
div.style.left = ((p.x + 1) / 2 * window.innerWidth) + "px";
div.style.top = ((1 - p.y) / 2 * window.innerHeight) + "px";
document.body.appendChild(div);
requestAnimationFrame(function () { // next frame: float up and fade
div.style.transform = "translate(-50%, -150%)";
div.style.opacity = "0";
});
setTimeout(function () { div.remove(); }, 900);
}
hit.uv decides the points.
// ---------- shooting: a ray from the camera; uv tells us which ring ----------
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
const centre = new THREE.Vector2(0.5, 0.5);
let shake = 0;
window.addEventListener("pointermove", function (e) {
cross.style.left = e.clientX + "px";
cross.style.top = e.clientY + "px";
pointer.x = (e.clientX / window.innerWidth) * 2 - 1;
pointer.y = -(e.clientY / window.innerHeight) * 2 + 1;
});
window.addEventListener("pointerdown", function (e) {
initAudio();
if (state !== "playing") { startGame(); return; }
if (reloading > 0) return;
if (ammo === 0) { beep(180, 0.05, "square", 0.2); return; } // click: empty
ammo--;
showAmmo();
bang();
shake = 0.08;
pointer.x = (e.clientX / window.innerWidth) * 2 - 1;
pointer.y = -(e.clientY / window.innerHeight) * 2 + 1;
raycaster.setFromCamera(pointer, camera);
const hits = raycaster.intersectObjects(targets.filter(function (t) { return t.userData.down <= 0; }));
if (hits.length === 0) return;
const hit = hits[0];
let points = 1; // the wooden edge
if (hit.face.materialIndex === 1) { // the bullseye face
const d = hit.uv.distanceTo(centre) * 2; // 0 = centre, 1 = edge
points = d < 0.22 ? 10 : d < 0.6 ? 5 : 2;
}
score += points;
scoreEl.textContent = score;
popup("+" + points, hit.point);
beep(points === 10 ? 1320 : 880, 0.18, "triangle", 0.3);
hit.object.userData.down = 2; // knocked over for 2 seconds
});
window.addEventListener("keydown", function (e) {
if (e.code === "KeyR" && state === "playing" && reloading <= 0 && ammo < MAX_AMMO) {
reloading = 1; // a one-second reload
showAmmo();
beep(300, 0.06, "square", 0.15);
}
if (e.code === "KeyM") muted = !muted;
});
// ---------- game state ----------
let state = "ready";
let score = 0;
let timeLeft = 45;
function startGame() {
score = 0;
timeLeft = 45;
ammo = MAX_AMMO;
reloading = 0;
scoreEl.textContent = 0;
msgEl.innerHTML = "";
showAmmo();
state = "playing";
}
// ---------- animation loop ----------
const clock = new THREE.Clock();
showAmmo();
renderer.setAnimationLoop(function () {
const dt = Math.min(clock.getDelta(), 0.05);
if (state === "playing") {
timeLeft -= dt;
timeEl.textContent = Math.max(0, Math.ceil(timeLeft));
if (reloading > 0) {
reloading -= dt;
if (reloading <= 0) { ammo = MAX_AMMO; showAmmo(); beep(500, 0.06, "square", 0.15); }
}
if (timeLeft <= 0) {
state = "over";
msgEl.innerHTML = "Time! You scored " + score + "<br>Click to play again";
}
}
updateTargets(dt);
shake *= 0.85; // recoil: a tiny camera shake
camera.position.x = (Math.random() - 0.5) * shake;
camera.position.y = 1.6 + (Math.random() - 0.5) * shake;
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 |
|---|---|---|
| Canvas textures: bullseye, planks, sky | 3 | |
| Repeating floor texture with the right colour space | 2 | |
| uv-based ring scoring | 2 | |
| Web Audio sound effects, unlocked on first click | 3 | |
| HUD, crosshair and projected popups | 3 | |
| Ammo, reload and recoil | 1 | |
| Runs with no console errors | 1 | |
| Total | 15 |
colorSpace = SRGBColorSpace, so colours look pale.repeat without RepeatWrapping, so the edge pixels stretch.AudioContext before any click, so it stays suspended.clone().Progress and quiz scores are also tracked on the Week 13 lab page in the class website.