Week 13 — Textures, Sound & HUD
Polish turns a demo into a game. This week you paint textures with the 2D canvas you learned in Weeks 2–6 and wrap them onto 3D shapes, read where a shot landed using texture coordinates, make sound effects with the Web Audio API (no sound files!), and build an HTML HUD with ammo, a crosshair and floating score popups — for Target Range, a shooting gallery.
🎯 Objectives
- Draw a texture on a 2D canvas and use it with
CanvasTextureandmaterial.map. - Repeat and wrap textures with
wrapS,wrapTandrepeat; set the colour space. - Score by where a ray hit a texture, using
hit.uvandface.materialIndex. - Make sound effects with the Web Audio API: oscillators, noise and a fading gain.
- Unlock audio on the first click (the browser autoplay rule).
- Build an HTML HUD over the canvas: score, timer, ammo and a crosshair.
- Turn a 3D point into screen pixels with
Vector3.projectfor popups. - Add game feel: limited ammo, a timed reload and recoil shake.
🛠 Weekly tasks
- Objective 1 — paint textures with a canvas: Activity 1 + build
targetRange.html. - Objective 2 — repeat the plank texture: Activity 2 + build
targetRange.html. - Objective 3 — score rings with texture coordinates: Activity 3 + build
targetRange.html. - Objective 4 — make sound effects with Web Audio: Activity 4 + build
targetRange.html. - Objective 5 — start audio on the first click: Activity 5 + build
targetRange.html. - Objective 6 — build the HUD and crosshair: Activity 6 + build
targetRange.html. - Objective 7 — show score popups at the hit point: Activity 7 + build
targetRange.html. - Objective 8 — add ammo, reloading and recoil: Activity 8 + build
targetRange.html. - Examples — build the lecture examples
canvasTexture.html,repeat.html,soundDemo.html,labels.html, one file per concept, and try each change. (Concepts 1–4) - Build your own
targetRange_yourname.html— add a moving bonus target, a combo multiplier and a background music loop. (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
- 0:0010 minWarm-upReview questions on last week
- 0:1010 minGame & objectivesThis week’s game, objectives and key words
- 0:2035 minConceptsBig idea → code with live 3D output → line by line → try it
- 0:555 minCheck understandingCommon mistakes and a 4-question quiz
- 1:0025 minLabBuild the files in the Lab activity below
- 1:255 minWrap-upBuild-your-own task, marking guide and recap
Concepts this week
- 1. Canvas textures — Paint with the 2D canvas, wrap it on 3D
- 2. Repeat and wrap — wrapS, wrapT, repeat and offset
- 3. Sound with Web Audio — Oscillator → gain → speakers
- 4. HUD and popups — HTML over the canvas; 3D → screen with project()
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 Week13 npm project (step 1). Build Target Range below, writing the code shown for each step, all in one file, targetRange.html. There are no image or sound files: everything is made in code. Start with the four example files from the lecture (one per concept), then build the game.
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.-
Set up your Week13 project npm · Vite
Week13\ — a new npm project, once at the start of the week.
- Create a folder named
Week13, open it in VS Code, and open the terminal with Ctrl+`. - 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 - Shortcut: download
package.jsonfrom Materials for this week into the folder, then runnpm installinstead. - Start the Vite dev server and leave it running. Open the address it prints plus a file name, for example
http://localhost:5173/canvasTexture.html. Press Ctrl+C in the terminal to stop it.npx vite
- Create a folder named
-
canvasTexture.html Concept 1 · Canvas textures
Week13\canvasTexture.html — Paint with the 2D canvas, wrap it on 3D.
- Create
canvasTexture.htmland 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> - Save. With
npx viterunning, openhttp://localhost:5173/canvasTexture.html. You should see a cube wearing a canvas-drawn dice face. - [Try it]
- Draw six dots instead of five.
- Change the dot colour and add a thin black border round each dot with
ctx.stroke(). - Write a number in the corner with
ctx.fontandctx.fillText.
- Create
-
repeat.html Concept 2 · Repeat and wrap
Week13\repeat.html — wrapS, wrapT, repeat and offset.
- Create
repeat.htmland 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> - Save. With
npx viterunning, openhttp://localhost:5173/repeat.html. You should see a checker texture repeating and scrolling. - [Try it]
- Freeze the repeat at
tex.repeat.set(3, 3). - Make the pattern slide sideways with
offset.x. - Remove
tex.wrapSandwrapT: what happens?
- Freeze the repeat at
- Create
-
soundDemo.html Concept 3 · Sound with Web Audio
Week13\soundDemo.html — Oscillator → gain → speakers.
- Create
soundDemo.htmland 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> - Save. With
npx viterunning, openhttp://localhost:5173/soundDemo.html. You should see a fading wave on screen and a beep (or a bang) each time you press a key. - [Try it]
- Change the beep frequency 880 to 440, then 1760.
- Make the beeps longer: 0.4 → 1.5 seconds.
- Add key 5 that plays two quick beeps (880, then 1320 with
setTimeout).
- Create
-
labels.html Concept 4 · HUD and popups
Week13\labels.html — HTML over the canvas; 3D → screen with project().
- Create
labels.htmland 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> - Save. With
npx viterunning, openhttp://localhost:5173/labels.html. You should see HTML labels pinned to moving 3D balls. - [Try it]
- Put each label under its ball instead of above it.
- Change the label text to the ball’s height:
ball.position.y.toFixed(1). - Add a fourth ball with its own label.
- Create
-
targetRange.html Objectives 1–8
Week13\targetRange.html — the shooting gallery.
- [Obj 6] Create
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> - Add the scene, the camera at eye height, and the lights.
// ---------- 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); - [Obj 1] Add
makeCanvas()andtargetTexture(): the rings are drawn witharc, 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; } - [Obj 1, 2] Add the repeating plank texture and the sky gradient, then the sky and the floor.
// 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); - [Obj 1] Add the targets on three rails, and
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; } }); } - [Obj 4, 5] Add the sound effects:
initAudio(),beep()andbang()(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(); } - [Obj 6, 7] Add the HUD: the ammo display and
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); } - [Obj 3, 5, 7, 8] Add shooting: the crosshair follows the mouse; a click fires a ray, and
hit.uvdecides 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; }); - [Obj 8] Add the game state.
// ---------- 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"; } - [Obj 8] Finish with the animation loop: timer, reload, targets and recoil shake.
// ---------- 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); }); - Save, click to start (sound needs that first click) and aim for the yellow.
- [Obj 6] Create
📝 Tasks for this file:
Click to start, then click on the targets. Press R to reload and M to mute. Sound starts after your first click.
📚 Using image files instead
- For photos or artwork, load an image file:
new THREE.TextureLoader().load("wood.jpg")(keep the file in your week folder). - For sound files, use an
<audio>element (Week 6) or Three.jsAudioLoaderwithTHREE.Audio. - Canvas textures and Web Audio are great for quick, file-free assets; image and sound files are better for detailed art and music.