Week 12 — Gravity & Projectiles
Week 4’s cannonball is back — in 3D. This week you store velocity as a
Vector3, let gravity pull it down every frame, aim a cannon with nested yaw and pitch
groups, draw the predicted flight path, and knock blocks off a tower with sphere-versus-box collisions — in
Cannon Tower.
🎯 Objectives
- Store velocity as a
Vector3and move withposition.addScaledVector(v, dt). - Apply gravity as an acceleration:
v.y -= g × dtevery frame. - Aim in 3D with nested groups for yaw (left / right) and pitch (up / down).
- Turn yaw and pitch into a launch direction, and charge power by holding a key.
- Predict the flight path by simulating ahead and drawing a
Line. - Detect sphere-versus-box hits with
SphereandBox3.intersectsSphere. - Make hit objects fly and tumble, and let stacks fall into the gaps.
- Bounce with energy loss, and tidy up objects you no longer need.
🛠 Weekly tasks
- Objective 1 — move balls with a velocity vector: Activity 1 + build
cannonTower.html. - Objective 2 — pull balls down with gravity: Activity 2 + build
cannonTower.html. - Objective 3 — aim the cannon with yaw and pitch: Activity 3 + build
cannonTower.html. - Objective 4 — launch along the aim with charged power: Activity 4 + build
cannonTower.html. - Objective 5 — draw the predicted path: Activity 5 + build
cannonTower.html. - Objective 6 — detect ball-block hits: Activity 6 + build
cannonTower.html. - Objective 7 — knock blocks off and settle the stacks: Activity 7 + build
cannonTower.html. - Objective 8 — bounce, then tidy up old balls: Activity 8 + build
cannonTower.html. - Examples — build the lecture examples
throw.html,aimDemo.html,pathDemo.html,knockDemo.html, one file per concept, and try each change. (Concepts 1–4) - Build your own
cannonTower_yourname.html— add wind, a moving target tower and a three-level campaign. (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. Velocity and gravity — p += v·dt, then v.y −= g·dt
- 2. Aiming in 3D — Yaw and pitch become a direction
- 3. Predicting the path — Run the physics ahead, draw a Line
- 4. Hits and tumbling — Sphere vs Box3, flying blocks, falling stacks
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 Week12 npm project (step 1). Build Cannon Tower below, writing the code shown for each step, all in one file, cannonTower.html. 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 Week12 project npm · Vite
Week12\ — a new npm project, once at the start of the week.
- Create a folder named
Week12, 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/throw.html. Press Ctrl+C in the terminal to stop it.npx vite
- Create a folder named
-
throw.html Concept 1 · Velocity and gravity
Week12\throw.html — p += v·dt, then v.y −= g·dt.
- Create
throw.htmland add this code. The orange dots show where the ball was every few frames: the classic arc.<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>Throw, Fall, Bounce</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, 4, 16); camera.lookAt(0, 3, 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 ground = new THREE.Mesh(new THREE.PlaneGeometry(40, 10), new THREE.MeshStandardMaterial({ color: 0x7cb36a })); ground.rotation.x = -Math.PI / 2; scene.add(ground); const ball = new THREE.Mesh(new THREE.SphereGeometry(0.3, 20, 14), new THREE.MeshStandardMaterial({ color: 0x222222 })); scene.add(ball); const GRAVITY = 9.8; const v = new THREE.Vector3(); // the velocity: units per second in x, y, z // orange dots show where the ball has been const dots = []; const dotGeo = new THREE.SphereGeometry(0.06); const dotMat = new THREE.MeshBasicMaterial({ color: 0xe8823a }); let frame = 0; function throwBall() { ball.position.set(-9, 0.3, 0); v.set(4, 9, 0); // 4 to the right, 9 up dots.forEach(function (d) { scene.remove(d); }); dots.length = 0; } throwBall(); const clock = new THREE.Clock(); renderer.setAnimationLoop(function () { const dt = Math.min(clock.getDelta(), 0.05); v.y -= GRAVITY * dt; // gravity changes the velocity ball.position.addScaledVector(v, dt); // the velocity changes the position if (ball.position.y < 0.3) { // hit the ground: bounce ball.position.y = 0.3; v.y = -v.y * 0.6; // lose some energy v.x *= 0.8; // ground friction } if (frame++ % 4 === 0) { const dot = new THREE.Mesh(dotGeo, dotMat); dot.position.copy(ball.position); scene.add(dot); dots.push(dot); } // start again when the ball leaves the screen or stops bouncing if (ball.position.x > 9 || (Math.abs(v.y) < 0.4 && ball.position.y < 0.31)) throwBall(); renderer.render(scene, camera); }); </script> </body> </html> - Save. With
npx viterunning, openhttp://localhost:5173/throw.html. You should see a ball thrown in an arc, bouncing to a stop. - [Try it]
- Change
GRAVITYto 1.6 (the Moon), then 25. - Make the bounce livelier:
-v.y * 0.85. - Throw harder:
v.set(6, 12, 0).
- Change
- Create
-
aimDemo.html Concept 2 · Aiming in 3D
Week12\aimDemo.html — Yaw and pitch become a direction.
- Create
aimDemo.htmland add this code. Aim with the arrow keys or WASD. The blue arrow is worked out only from the two angles, yet it always lines up with the barrel.<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>From Angles to a Direction</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">Arrow keys / WASD aim the cannon</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(5, 4, 5); camera.lookAt(0, 0.8, -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, 0x445566, 1.5)); const sun = new THREE.DirectionalLight(0xffffff, 1.5); sun.position.set(3, 6, 5); scene.add(sun); scene.add(new THREE.GridHelper(10, 10, 0xbbbbbb, 0xdddddd)); // the cannon group turns left / right (yaw); the pivot inside it tilts up / down (pitch) const cannon = new THREE.Group(); scene.add(cannon); const base = new THREE.Mesh(new THREE.CylinderGeometry(0.9, 1.1, 0.6, 24), new THREE.MeshStandardMaterial({ color: 0x5b3a1e })); base.position.y = 0.3; cannon.add(base); const pitchPivot = new THREE.Group(); pitchPivot.position.y = 0.9; cannon.add(pitchPivot); const barrel = new THREE.Mesh(new THREE.CylinderGeometry(0.28, 0.35, 2.2, 20), new THREE.MeshStandardMaterial({ color: 0x2d3038 })); barrel.rotation.x = -Math.PI / 2; // lie the cylinder along -z barrel.position.z = -0.9; pitchPivot.add(barrel); // the blue arrow is worked out only from the two angles const arrow = new THREE.ArrowHelper(new THREE.Vector3(0, 0, -1), new THREE.Vector3(0, 0.9, 0), 4, 0x2563eb, 0.5, 0.3); scene.add(arrow); let yaw = 0, pitch = 0.5; function aimDirection() { return new THREE.Vector3( -Math.sin(yaw) * Math.cos(pitch), Math.sin(pitch), -Math.cos(yaw) * Math.cos(pitch)); } const keys = {}; window.addEventListener("keydown", function (e) { keys[e.code] = true; if (e.code.startsWith("Arrow")) e.preventDefault(); }); window.addEventListener("keyup", function (e) { keys[e.code] = false; }); const info = document.getElementById("info"); const clock = new THREE.Clock(); renderer.setAnimationLoop(function () { const dt = Math.min(clock.getDelta(), 0.05); if (keys.ArrowLeft || keys.KeyA) yaw += 0.8 * dt; if (keys.ArrowRight || keys.KeyD) yaw -= 0.8 * dt; if (keys.ArrowUp || keys.KeyW) pitch += 0.6 * dt; if (keys.ArrowDown || keys.KeyS) pitch -= 0.6 * dt; yaw = THREE.MathUtils.clamp(yaw, -0.8, 0.8); pitch = THREE.MathUtils.clamp(pitch, 0, 1.3); cannon.rotation.y = yaw; pitchPivot.rotation.x = pitch; arrow.setDirection(aimDirection()); info.textContent = "yaw " + yaw.toFixed(2) + " pitch " + pitch.toFixed(2); renderer.render(scene, camera); }); </script> </body> </html> - Save. With
npx viterunning, openhttp://localhost:5173/aimDemo.html. You should see the cannon turning and tilting with the arrow pointing exactly along the barrel. - [Try it]
- Widen the yaw limits to ±1.5.
- Let pitch go up to 1.55 (almost straight up).
- Swap the minus sign on the x part of
aimDirection(): what breaks?
- Create
-
pathDemo.html Concept 3 · Predicting the path
Week12\pathDemo.html — Run the physics ahead, draw a Line.
- Create
pathDemo.htmland add this code. Up / Down change the angle, Left / Right change the power. The line shows where a ball would fly.<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>Draw the Arc</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"></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(14, 6, 2); camera.lookAt(0, 2, -9); 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 ground = new THREE.Mesh(new THREE.PlaneGeometry(60, 60), new THREE.MeshStandardMaterial({ color: 0x7cb36a })); ground.rotation.x = -Math.PI / 2; scene.add(ground); const cannon = new THREE.Mesh(new THREE.CylinderGeometry(0.6, 0.8, 0.8, 20), new THREE.MeshStandardMaterial({ color: 0x5b3a1e })); cannon.position.y = 0.4; scene.add(cannon); // the predicted path is a Line through 30 points const GRAVITY = 9.8; const pathGeo = new THREE.BufferGeometry(); const path = new THREE.Line(pathGeo, new THREE.LineBasicMaterial({ color: 0x1b2030 })); scene.add(path); let pitch = 0.6; // the angle, in radians let power = 15; // the launch speed function updatePath() { const dir = new THREE.Vector3(0, Math.sin(pitch), -Math.cos(pitch)); // aiming along -z const p = new THREE.Vector3(0, 0.9, 0).addScaledVector(dir, 1.5); // start at the muzzle const v = dir.multiplyScalar(power); // launch velocity const points = []; for (let i = 0; i < 30; i++) { // 30 steps of 0.05 s points.push(p.clone()); v.y -= GRAVITY * 0.05; // the same physics as a real ball p.addScaledVector(v, 0.05); if (p.y < 0) { p.y = 0; v.set(0, 0, 0); } // stop at the ground (keep 30 points) } pathGeo.setFromPoints(points); } const keys = {}; window.addEventListener("keydown", function (e) { keys[e.code] = true; if (e.code.startsWith("Arrow")) e.preventDefault(); }); window.addEventListener("keyup", function (e) { keys[e.code] = false; }); const info = document.getElementById("info"); const clock = new THREE.Clock(); renderer.setAnimationLoop(function () { const dt = Math.min(clock.getDelta(), 0.05); if (keys.ArrowUp || keys.KeyW) pitch += 0.6 * dt; if (keys.ArrowDown || keys.KeyS) pitch -= 0.6 * dt; if (keys.ArrowRight || keys.KeyD) power += 6 * dt; if (keys.ArrowLeft || keys.KeyA) power -= 6 * dt; pitch = THREE.MathUtils.clamp(pitch, 0.05, 1.4); power = THREE.MathUtils.clamp(power, 5, 25); updatePath(); info.textContent = "Up/Down: angle " + (pitch * 180 / Math.PI).toFixed(0) + "° Left/Right: power " + power.toFixed(1); renderer.render(scene, camera); }); </script> </body> </html> - Save. With
npx viterunning, openhttp://localhost:5173/pathDemo.html. You should see the predicted arc change as you aim and change the power. - [Try it]
- Find the angle that throws furthest (watch where the line lands).
- Change 30 steps to 60, then to 12.
- Change
GRAVITYto 4.
- Create
-
knockDemo.html Concept 4 · Hits and tumbling
Week12\knockDemo.html — Sphere vs Box3, flying blocks, falling stacks.
- Create
knockDemo.htmland add this code. The knocked block takes some of the ball’s velocity, plus a hop and a random spin.<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>Knock Blocks Out of a Stack</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(8, 4, 6); camera.lookAt(0, 2, -3); 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, 8, 5); scene.add(sun); const ground = new THREE.Mesh(new THREE.PlaneGeometry(40, 40), new THREE.MeshStandardMaterial({ color: 0x7cb36a })); ground.rotation.x = -Math.PI / 2; scene.add(ground); const GRAVITY = 9.8; const blockGeo = new THREE.BoxGeometry(1, 1, 1); let column = []; // standing blocks, bottom first let flying = []; // knocked-out blocks const ball = new THREE.Mesh(new THREE.SphereGeometry(0.3, 16, 12), new THREE.MeshStandardMaterial({ color: 0x222222 })); scene.add(ball); const v = new THREE.Vector3(); // the ball's velocity const ballSphere = new THREE.Sphere(new THREE.Vector3(), 0.3); // its collision shape const blockBox = new THREE.Box3(); let timer = 0; // build a stack of six blocks and fire the ball at a random height function reset() { column.concat(flying).forEach(function (b) { scene.remove(b); }); column = []; flying = []; for (let i = 0; i < 6; i++) { const block = new THREE.Mesh(blockGeo, new THREE.MeshStandardMaterial({ color: new THREE.Color().setHSL(0.05 + i * 0.03, 0.6, 0.55) })); block.position.set(0, 0.5 + i, -4); block.userData = { velocity: new THREE.Vector3(), spin: new THREE.Vector3() }; scene.add(block); column.push(block); } ball.position.set(0, 1.2 + Math.random() * 3, 6); v.set(0, 4, -13); timer = 0; } reset(); const clock = new THREE.Clock(); renderer.setAnimationLoop(function () { const dt = Math.min(clock.getDelta(), 0.05); timer += dt; // the ball flies with gravity v.y -= GRAVITY * dt; ball.position.addScaledVector(v, dt); ballSphere.center.copy(ball.position); // did it hit a standing block? (check from the top down) for (let j = column.length - 1; j >= 0; j--) { blockBox.setFromObject(column[j]); if (blockBox.intersectsSphere(ballSphere)) { const block = column.splice(j, 1)[0]; // out of the stack block.userData.velocity.copy(v).multiplyScalar(0.6).add(new THREE.Vector3(0, 3, 0)); block.userData.spin.set(Math.random() * 6 - 3, 0, Math.random() * 6 - 3); flying.push(block); v.multiplyScalar(0.7); // the ball slows down } } // standing blocks drop down to fill any gap column.forEach(function (b, i) { b.position.y = Math.max(0.5 + i, b.position.y - 8 * dt); }); // knocked blocks fly, tumble and land flying.forEach(function (b) { const u = b.userData; u.velocity.y -= GRAVITY * dt; b.position.addScaledVector(u.velocity, dt); b.rotation.x += u.spin.x * dt; b.rotation.z += u.spin.z * dt; if (b.position.y < 0.5) { b.position.y = 0.5; u.velocity.multiplyScalar(0.4); u.spin.multiplyScalar(0.5); } }); if (timer > 4) reset(); // try again every 4 seconds renderer.render(scene, camera); }); </script> </body> </html> - Save. With
npx viterunning, openhttp://localhost:5173/knockDemo.html. You should see a ball knocking blocks out of a stack. - [Try it]
- Change 0.6 to 0.25 where a knocked block takes the ball’s velocity.
- Remove the upward hop (the
Vector3(0, 3, 0)). - Make the stack 10 blocks tall.
- Create
-
cannonTower.html Objectives 1–8
Week12\cannonTower.html — the cannon game.
- Create
cannonTower.htmlwith this scaffold. It includes a power bar under the game.<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>Cannon Tower</title> <style> body { margin: 0; overflow: hidden; background: #a7d3f2; font-family: Arial, Helvetica, sans-serif; } #hud { position: absolute; top: 10px; left: 12px; color: #ffffff; font-size: 20px; pointer-events: none; text-shadow: 0 1px 3px #000; } #power { position: absolute; bottom: 20px; left: 50%; width: 240px; height: 16px; margin-left: -120px; border: 2px solid #fff; border-radius: 8px; overflow: hidden; } #powerFill { height: 100%; width: 0%; background: linear-gradient(90deg, #ffd34d, #ff4d4d); } #msg { position: absolute; top: 30%; 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">Blocks left: <span id="left">0</span> Shots: <span id="shots">8</span></div> <div id="power"><div id="powerFill"></div></div> <div id="msg">Knock every block off the tower<br>Arrow keys / WASD aim · hold Space to charge, release to fire<br>Press Enter to start</div> <script type="module"> import * as THREE from "three"; // TODO: the steps below go here </script> </body> </html> - Add the scene, a side-on camera (so the arc is easy to see), lights and the ground.
// ---------- scene, camera, renderer ---------- const scene = new THREE.Scene(); scene.background = new THREE.Color(0xa7d3f2); scene.fog = new THREE.Fog(0xa7d3f2, 40, 90); const camera = new THREE.PerspectiveCamera(55, window.innerWidth / window.innerHeight, 0.1, 200); camera.position.set(7, 5, 7); // off to one side, so the arc of each shot is easy to see camera.lookAt(0, 2, -9); 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.2)); const sun = new THREE.DirectionalLight(0xffffff, 2); sun.position.set(-8, 15, 6); sun.castShadow = true; sun.shadow.camera.left = -15; sun.shadow.camera.right = 15; sun.shadow.camera.top = 15; sun.shadow.camera.bottom = -25; scene.add(sun); const ground = new THREE.Mesh(new THREE.PlaneGeometry(200, 200), new THREE.MeshStandardMaterial({ color: 0x7cb36a })); ground.rotation.x = -Math.PI / 2; ground.receiveShadow = true; scene.add(ground); - [Obj 3] Build the cannon: the outer group turns (yaw), the inner pivot tilts (pitch).
// ---------- the cannon: yaw (left / right) group holding a pitch (up / down) group ---------- const cannon = new THREE.Group(); // turns left and right (rotation.y) const base = new THREE.Mesh(new THREE.CylinderGeometry(0.9, 1.1, 0.6, 24), new THREE.MeshStandardMaterial({ color: 0x5b3a1e })); base.position.y = 0.3; cannon.add(base); const pitchPivot = new THREE.Group(); // tilts up and down (rotation.x) pitchPivot.position.y = 0.9; cannon.add(pitchPivot); const barrel = new THREE.Mesh(new THREE.CylinderGeometry(0.28, 0.35, 2.2, 20), new THREE.MeshStandardMaterial({ color: 0x2d3038, metalness: 0.7, roughness: 0.4 })); barrel.rotation.x = -Math.PI / 2; // lie the cylinder along -z barrel.position.z = -0.9; pitchPivot.add(barrel); cannon.traverse(function (p) { p.castShadow = true; }); scene.add(cannon); let yaw = 0; // radians, + turns left let pitch = 0.35; // radians, + aims higher - [Obj 4] Add
aimDirection()andmuzzlePosition().// Turn the two angles into a direction (length 1) the barrel points in function aimDirection() { return new THREE.Vector3( -Math.sin(yaw) * Math.cos(pitch), Math.sin(pitch), -Math.cos(yaw) * Math.cos(pitch)); } function muzzlePosition() { // the end of the barrel, where balls start return new THREE.Vector3(0, 0.9, 0).add(aimDirection().multiplyScalar(2)); } - [Obj 7] Build the tower: three columns of five blocks. Each block keeps its own velocity and spin in
userData.// ---------- the tower: columns of blocks on a platform ---------- const PLATFORM_TOP = 2; const platform = new THREE.Mesh(new THREE.BoxGeometry(5, PLATFORM_TOP, 3), new THREE.MeshStandardMaterial({ color: 0x8d8d8d })); platform.position.set(0, PLATFORM_TOP / 2, -16); platform.castShadow = true; platform.receiveShadow = true; scene.add(platform); const platformBox = new THREE.Box3().setFromObject(platform); // it never moves const BLOCK = 1; const COLS = [-1.05, 0, 1.05]; const HEIGHT = 5; let columns = []; // columns[c] = standing blocks, bottom first let flying = []; // blocks knocked off, tumbling const blockGeo = new THREE.BoxGeometry(BLOCK, BLOCK, BLOCK); function buildTower() { columns.forEach(function (col) { col.forEach(function (b) { scene.remove(b); }); }); flying.forEach(function (b) { scene.remove(b); }); columns = []; flying = []; COLS.forEach(function (x, c) { const col = []; for (let level = 0; level < HEIGHT; level++) { const block = new THREE.Mesh(blockGeo, new THREE.MeshStandardMaterial({ color: new THREE.Color().setHSL(0.05 + level * 0.03, 0.6, 0.5 + (c % 2) * 0.08) })); block.position.set(x, PLATFORM_TOP + BLOCK / 2 + level * BLOCK, -16); block.castShadow = true; block.receiveShadow = true; block.userData = { velocity: new THREE.Vector3(), spin: new THREE.Vector3(), counted: false }; scene.add(block); col.push(block); } columns.push(col); }); } - [Obj 7] Add
settleColumns(): blocks fall to fill gaps below them.// Standing blocks fall down to fill any gap below them function settleColumns(dt) { columns.forEach(function (col) { col.forEach(function (block, i) { const restY = PLATFORM_TOP + BLOCK / 2 + i * BLOCK; if (block.position.y > restY) block.position.y = Math.max(restY, block.position.y - 8 * dt); }); }); } - [Obj 1, 4] Add the cannonballs and
fire(): the launch velocity is the aim direction times the power.// ---------- cannonballs: velocity, gravity, bounce ---------- const GRAVITY = 9.8; const BALL_R = 0.3; const balls = []; const ballGeo = new THREE.SphereGeometry(BALL_R, 20, 14); const ballMat = new THREE.MeshStandardMaterial({ color: 0x222222, metalness: 0.6, roughness: 0.3 }); function fire(power) { const ball = new THREE.Mesh(ballGeo, ballMat); ball.castShadow = true; ball.position.copy(muzzlePosition()); ball.userData = { velocity: aimDirection().multiplyScalar(power), age: 0 }; scene.add(ball); balls.push(ball); shots--; shotsEl.textContent = shots; } - [Obj 1, 2, 6, 8] Add
updateBalls(): gravity, movement, bouncing, hitting the platform and the blocks, and tidying up.const ballSphere = new THREE.Sphere(new THREE.Vector3(), BALL_R); const blockBox = new THREE.Box3(); function updateBalls(dt) { for (let i = balls.length - 1; i >= 0; i--) { const ball = balls[i]; const v = ball.userData.velocity; v.y -= GRAVITY * dt; // gravity changes the velocity ball.position.addScaledVector(v, dt); // velocity changes the position ball.userData.age += dt; if (ball.position.y < BALL_R) { // bounce on the ground ball.position.y = BALL_R; v.y = -v.y * 0.45; // lose energy in the bounce v.x *= 0.8; v.z *= 0.8; } ballSphere.center.copy(ball.position); if (platformBox.intersectsSphere(ballSphere)) { // bounce off the stone platform if (ball.position.y > PLATFORM_TOP) { // landed on top ball.position.y = PLATFORM_TOP + BALL_R; v.y = Math.abs(v.y) * 0.45; } else { // hit the front face ball.position.z = platformBox.max.z + BALL_R; v.z = Math.abs(v.z) * 0.4; } } // did it hit a standing block? columns.forEach(function (col) { for (let j = col.length - 1; j >= 0; j--) { blockBox.setFromObject(col[j]); if (blockBox.intersectsSphere(ballSphere)) { const block = col.splice(j, 1)[0]; // knock it out of its column block.userData.velocity.copy(v).multiplyScalar(0.6).add(new THREE.Vector3(0, 3, 0)); block.userData.spin.set(Math.random() * 6 - 3, Math.random() * 6 - 3, Math.random() * 6 - 3); flying.push(block); v.multiplyScalar(0.7); // the ball slows down } } }); if (ball.userData.age > 8 || ball.position.length() > 80) { // tidy up old balls scene.remove(ball); balls.splice(i, 1); } } } - [Obj 2, 7] Add
updateFlying(): knocked blocks fall, tumble, land, and count once they are off the tower.// ---------- knocked blocks tumble and fall ---------- function updateFlying(dt) { flying.forEach(function (block) { const u = block.userData; u.velocity.y -= GRAVITY * dt; block.position.addScaledVector(u.velocity, dt); block.rotation.x += u.spin.x * dt; block.rotation.y += u.spin.y * dt; block.rotation.z += u.spin.z * dt; if (block.position.y < BLOCK / 2) { // land on the grass block.position.y = BLOCK / 2; u.velocity.multiplyScalar(0.5); u.velocity.y = Math.abs(u.velocity.y) * 0.3; u.spin.multiplyScalar(0.6); } if (!u.counted && block.position.y < PLATFORM_TOP - 0.2) { // off the tower: it counts u.counted = true; knocked++; leftEl.textContent = HEIGHT * COLS.length - knocked; } }); } - [Obj 5] Add the predicted path.
// ---------- the predicted path: run the physics ahead of time ---------- const pathGeo = new THREE.BufferGeometry(); const path = new THREE.Line(pathGeo, new THREE.LineBasicMaterial({ color: 0xffffff })); scene.add(path); function updatePath(power) { const points = []; const p = muzzlePosition(); const v = aimDirection().multiplyScalar(power); for (let i = 0; i < 30; i++) { // 30 steps of 0.05 s = 1.5 s ahead points.push(p.clone()); v.y -= GRAVITY * 0.05; p.addScaledVector(v, 0.05); if (p.y < 0) { p.y = 0; v.set(0, 0, 0); } // stop at the ground } pathGeo.setFromPoints(points); // always 30 points } - [Obj 3, 4] Add the keyboard: hold Space to charge, release to fire;
aim()turns and tilts the cannon.// ---------- keyboard: aim, charge, fire ---------- const keys = {}; let charging = false; let power = 0; const MIN_POWER = 8, MAX_POWER = 28; window.addEventListener("keydown", function (e) { keys[e.code] = true; if (e.code.startsWith("Arrow") || e.code === "Space") e.preventDefault(); if (e.code === "Enter" && state !== "playing") startGame(); if (e.code === "Space" && state === "playing" && !charging && shots > 0) { charging = true; power = MIN_POWER; } }); window.addEventListener("keyup", function (e) { keys[e.code] = false; if (e.code === "Space" && charging) { charging = false; fire(power); } }); function aim(dt) { if (keys.ArrowLeft || keys.KeyA) yaw += 0.8 * dt; if (keys.ArrowRight || keys.KeyD) yaw -= 0.8 * dt; if (keys.ArrowUp || keys.KeyW) pitch += 0.6 * dt; if (keys.ArrowDown || keys.KeyS) pitch -= 0.6 * dt; yaw = THREE.MathUtils.clamp(yaw, -0.6, 0.6); pitch = THREE.MathUtils.clamp(pitch, 0.05, 1.2); cannon.rotation.y = yaw; pitchPivot.rotation.x = pitch; if (charging) power = Math.min(MAX_POWER, power + 14 * dt); } - [Obj 8] Add the game state with the win and lose checks.
// ---------- game state ---------- let state = "ready"; let shots = 8; let knocked = 0; const leftEl = document.getElementById("left"); const shotsEl = document.getElementById("shots"); const msgEl = document.getElementById("msg"); const powerFill = document.getElementById("powerFill"); function startGame() { buildTower(); balls.forEach(function (b) { scene.remove(b); }); balls.length = 0; shots = 8; knocked = 0; shotsEl.textContent = shots; leftEl.textContent = HEIGHT * COLS.length; msgEl.innerHTML = ""; state = "playing"; } function checkEnd() { if (knocked === HEIGHT * COLS.length) { state = "over"; msgEl.innerHTML = "Tower down with " + shots + " shots to spare!<br>Press Enter to play again"; } else if (shots === 0 && balls.length === 0) { state = "over"; msgEl.innerHTML = "Out of shots! " + knocked + " blocks knocked off.<br>Press Enter to try again"; } } - Finish with the animation loop and the resize handler.
// ---------- animation loop ---------- const clock = new THREE.Clock(); buildTower(); leftEl.textContent = HEIGHT * COLS.length; renderer.setAnimationLoop(function () { const dt = Math.min(clock.getDelta(), 0.05); if (state === "playing") { aim(dt); checkEnd(); } updatePath(charging ? power : (MIN_POWER + MAX_POWER) / 2); path.visible = state === "playing"; powerFill.style.width = (charging ? (power - MIN_POWER) / (MAX_POWER - MIN_POWER) * 100 : 0) + "%"; updateBalls(dt); updateFlying(dt); settleColumns(dt); renderer.render(scene, camera); }); window.addEventListener("resize", function () { camera.aspect = window.innerWidth / window.innerHeight; camera.updateProjectionMatrix(); renderer.setSize(window.innerWidth, window.innerHeight); }); - Save, press Enter, aim and fire. Keep the console (F12) open for errors.
- Create
📝 Tasks for this file:
Click the game, press Enter, aim with the arrow keys or WASD, then hold Space and release to fire.
📚 From Week 4 (2D) to Week 12 (3D)
- Week 4:
dxanddynumbers,dy += gravity,x += dx; y += dy. - Week 12: one
Vector3velocity,v.y -= 9.8 * dt,position.addScaledVector(v, dt). - Same idea, one more axis — and multiplying by
dtmakes it frame-rate independent.