Web Games Development · Projectile physics · ~150 minutes
Vector3 and move with position.addScaledVector(v, dt).v.y -= g × dt every frame.Line.Sphere and Box3.intersectsSphere.Set up a Week12 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.
Week12\
Week12, 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/throw.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/.Week12\throw.html
throw.html and 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>
npx vite running, open http://localhost:5173/throw.html. You should see a ball thrown in an arc, bouncing to a stop.GRAVITY to 1.6 (the Moon), then 25.-v.y * 0.85.v.set(6, 12, 0).Week12\aimDemo.html
aimDemo.html and 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>
npx vite running, open http://localhost:5173/aimDemo.html. You should see the cannon turning and tilting with the arrow pointing exactly along the barrel.aimDirection(): what breaks?Week12\pathDemo.html
pathDemo.html and 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>
npx vite running, open http://localhost:5173/pathDemo.html. You should see the predicted arc change as you aim and change the power.GRAVITY to 4.Week12\knockDemo.html
knockDemo.html and 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>
npx vite running, open http://localhost:5173/knockDemo.html. You should see a ball knocking blocks out of a stack.Vector3(0, 3, 0)).Week12\cannonTower.html
cannonTower.html with 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>
// ---------- 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);
// ---------- 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
aimDirection() and muzzlePosition().
// 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));
}
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);
});
}
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);
});
});
}
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;
}
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);
}
}
}
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;
}
});
}
// ---------- 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
}
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);
}
// ---------- 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";
}
}
// ---------- 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);
});
| Criterion | Points | Score |
|---|---|---|
| Velocity Vector3 and gravity | 3 | |
| Cannon aims with yaw / pitch groups | 3 | |
| Charged launch along the aim direction | 2 | |
| Predicted path drawn with a Line | 2 | |
| Sphere-box hits; blocks tumble; stacks settle | 3 | |
| Bounce, tidy-up and win / lose rules | 1 | |
| Runs with no console errors | 1 | |
| Total | 15 |
Vector3 between balls.setFromPoints (r170 reuses the geometry).Progress and quiz scores are also tracked on the Week 12 lab page in the class website.