WEEK 12
Web Games Development · 3D with Three.js
Gravity & Projectiles
Velocity, gravity, 3D aiming and a predicted path: knock down a tower with a cannon.
velocity
gravity
yaw & pitch
trajectory
Sphere vs Box3
Game: Cannon Tower
Today · 90 minutes
Plan for the session
| Start | Segment | Time |
|---|---|---|
| 0:00 | Warm-up review | 10 min |
| 0:10 | This week’s game and objectives | 10 min |
| 0:20 | Concepts: idea, code, line by line, try it | 35 min |
| 0:55 | Common mistakes and check your understanding | 5 min |
| 1:00 | Lab: build the game | 25 min |
| 1:25 | Build-your-own task, recap and exit quiz | 5 min |
Week 12 · Gravity & Projectiles
2 / 35
Warm-up · 5 minutes
Remember Weeks 4 and 11?
1
In the Week 4 cannonball, how was gravity added?
2
What does Raycaster.intersectObjects return first?
3
What does a Box3 store?
4
Why multiply movement by dt?
Week 12 · Gravity & Projectiles
3 / 35
This week’s game
Bring the tower down
A tower of 15 blocks stands on a stone platform. You have a cannon and 8 cannonballs.
Aim left, right, up and down with the keys; a white line shows where the ball will fly. Hold Space to charge, release to fire.
Blocks that are hit fly off and tumble; the blocks above them drop down. Knock every block off the platform to win.
HOW TO PLAY
Enter to start.
Arrows / WASD aim.
Hold Space to charge, release to fire.
YOU WILL BUILD
- cannonTower.html
- package.json
Week 12 · Gravity & Projectiles
4 / 35
Objectives
By the end of Week 12 you can…
01
Move with a velocity Vector3: p += v × dt.
02
Apply gravity every frame: v.y −= g × dt.
03
Aim with nested yaw and pitch groups.
04
Turn two angles into a 3D launch direction.
05
Predict and draw the flight path with a Line.
06
Detect hits with Sphere and intersectsSphere.
07
Make blocks fly, tumble and stacks settle.
08
Bounce with energy loss; remove old objects.
Week 12 · Gravity & Projectiles
5 / 35
Key words this week
Vocabulary
| Term | Meaning |
|---|---|
| velocity | Speed and direction as a Vector3 (units per second) |
| acceleration | How fast the velocity changes (gravity is one) |
| gravity | A constant downward acceleration, 9.8 m/s² |
| yaw / pitch | Turning left–right / tilting up–down |
| trajectory | The path a projectile follows |
| Sphere | A collision shape: centre and radius |
| restitution | How bouncy a collision is (0 = dead, 1 = perfect) |
| addScaledVector | v.addScaledVector(w, k) means v += w × k |
Week 12 · Gravity & Projectiles
6 / 35
What the program must do
What a cannon game needs
Aiming
Turn and tilt the cannon; see where it will hit.
Physics
Velocity and gravity for an arcing shot.
A target
A tower of blocks that reacts to hits.
Limits
A shot count and win / lose rules.
Week 12 · Gravity & Projectiles
7 / 35
Big idea 1 · Velocity and gravity
Two lines of physics move every projectile
1
velocity
A Vector3: how far it moves per second in x, y, z.
2
position
position += velocity × dt
3
gravity
velocity.y −= 9.8 × dt: it curves down.
Week 12 · Gravity & Projectiles
8 / 35
Example 1 · Velocity and gravity
Throw, fall, bounce
The orange dots show where the ball was every few frames: the classic arc.
CODE · throw.html
const GRAVITY = 9.8;
const v = new THREE.Vector3(4, 9, 0); // up and to the right
// every frame:
v.y -= GRAVITY * dt; // gravity
ball.position.addScaledVector(v, dt); // move
if (ball.position.y < 0.3) { // hit the ground
ball.position.y = 0.3;
v.y = -v.y * 0.6; // bounce, losing energy
v.x *= 0.8; // ground friction
}
OUTPUT · a ball thrown in an arc, bouncing to a stop
Week 12 · Gravity & Projectiles
9 / 35
Line by line · Example 1
Throw, fall, bounce
new THREE.Vector3(4, 9, 0)
4 per second to the right, 9 per second up.
v.y -= GRAVITY * dt
Gravity only changes the up / down part.
ball.position.addScaledVector(v, dt)
position += v × dt, for x, y and z at once.
v.y = -v.y * 0.6
Bounce: reverse y, keep 60% of the speed.
v.x *= 0.8
Friction with the ground slows it sideways.
Week 12 · Gravity & Projectiles
10 / 35
Try it · 5 minutes
Moon gravity
- In Cannon Tower set GRAVITY = 1.6 (the Moon).
- Fire a weak shot.
- Now try GRAVITY = 25.
YOU SHOULD SEE
On the Moon the balls float far over the tower; at 25 they drop just in front of the cannon.
Week 12 · Gravity & Projectiles
11 / 35
Big idea 2 · Aiming in 3D
Two angles point anywhere
1
yaw
Turn left / right: the cannon group’s rotation.y.
2
pitch
Tilt up / down: an inner group’s rotation.x.
3
direction
(−sin yaw · cos pitch, sin pitch, −cos yaw · cos pitch)
Week 12 · Gravity & Projectiles
12 / 35
Example 2 · Aiming in 3D
From angles to a launch direction
The blue arrow is aimDirection(); it always matches the barrel.
CODE · cannonTower.html · aim
const cannon = new THREE.Group(); // yaw: rotation.y
const pitchPivot = new THREE.Group(); // pitch: rotation.x
cannon.add(pitchPivot);
pitchPivot.add(barrel);
cannon.rotation.y = yaw;
pitchPivot.rotation.x = pitch;
function aimDirection() {
return new THREE.Vector3(
-Math.sin(yaw) * Math.cos(pitch),
Math.sin(pitch),
-Math.cos(yaw) * Math.cos(pitch));
}
OUTPUT · the cannon sweeping; the arrow shows the direction
Week 12 · Gravity & Projectiles
13 / 35
Line by line · Example 2
From angles to a launch direction
cannon.add(pitchPivot)
The tilt group sits inside the turn group.
cannon.rotation.y = yaw
Turn the whole cannon left or right.
pitchPivot.rotation.x = pitch
Tilt only the barrel up or down.
Math.sin(pitch)
How much of the direction points up.
Math.cos(pitch)
How much is left for the flat (x, z) part.
Week 12 · Gravity & Projectiles
14 / 35
Try it · 5 minutes
Change the limits
- Change the yaw clamp to ±1.2.
- Let pitch go up to 1.5 (almost straight up).
- Fire straight up: where does the ball land?
YOU SHOULD SEE
A wider turning range; a near-vertical shot climbs high and drops back near the cannon.
Week 12 · Gravity & Projectiles
15 / 35
Big idea 3 · Predicting the path
Simulate the shot before you take it
1
copy
Start from the muzzle with the launch velocity.
2
step
30 small steps of the same physics, saving each point.
3
draw
A Line through the points: the predicted arc.
Week 12 · Gravity & Projectiles
16 / 35
Example 3 · Predicting the path
Draw the arc
Always 30 points: setFromPoints in r170 reuses the geometry, so the count must not change.
CODE · cannonTower.html · updatePath()
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++) {
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); }
}
pathGeo.setFromPoints(points);
}
OUTPUT · the predicted path changing as the aim moves
Week 12 · Gravity & Projectiles
17 / 35
Line by line · Example 3
Draw the arc
new THREE.Line(pathGeo, material)
A line joining points in order.
const v = aimDirection().multiplyScalar(power)
Launch velocity = direction × power.
points.push(p.clone())
clone, or every point would be the same Vector3.
v.y -= GRAVITY * 0.05
The same gravity as the real ball, in 0.05 s steps.
pathGeo.setFromPoints(points)
Put the new points into the line’s geometry.
Week 12 · Gravity & Projectiles
18 / 35
Try it · 5 minutes
A longer preview
- Change 30 steps to 60.
- Change the line colour to yellow.
- Is aiming now too easy? Try 12 steps.
YOU SHOULD SEE
With 60 steps the whole flight is shown; with 12 only the start, so the player must guess the rest.
Week 12 · Gravity & Projectiles
19 / 35
Big idea 4 · Hits and tumbling
Hit, knock out, let the rest fall
1
Sphere
The ball is a Sphere: a centre and a radius.
2
intersectsSphere
Does a block’s Box3 touch the ball’s Sphere?
3
knock out
The block leaves its column and flies; blocks above drop down.
Week 12 · Gravity & Projectiles
20 / 35
Example 4 · Hits and tumbling
Knock a block out of its column
The knocked block takes some of the ball’s velocity, plus a hop and a random spin.
CODE · cannonTower.html · updateBalls()
const ballSphere = new THREE.Sphere(new THREE.Vector3(), BALL_R);
ballSphere.center.copy(ball.position);
for (let j = col.length - 1; j >= 0; j--) {
blockBox.setFromObject(col[j]);
if (blockBox.intersectsSphere(ballSphere)) {
const block = col.splice(j, 1)[0]; // out of the column
block.userData.velocity.copy(v).multiplyScalar(0.6)
.add(new THREE.Vector3(0, 3, 0)); // a hop
block.userData.spin.set(Math.random() * 6 - 3, 0, Math.random() * 6 - 3);
flying.push(block);
v.multiplyScalar(0.7); // the ball slows
}
}
OUTPUT · a ball knocking blocks out of a stack
Week 12 · Gravity & Projectiles
21 / 35
Line by line · Example 4
Knock a block out of its column
new THREE.Sphere(centre, radius)
The ball’s collision shape.
blockBox.intersectsSphere(ballSphere)
Box versus sphere: did they touch?
col.splice(j, 1)[0]
Take the block out of its column array.
velocity.copy(v).multiplyScalar(0.6)
It flies on with 60% of the ball’s velocity…
.add(new THREE.Vector3(0, 3, 0))
…plus a little hop upwards.
Week 12 · Gravity & Projectiles
22 / 35
Try it · 5 minutes
Heavier blocks
- Change 0.6 to 0.25 when a block is hit.
- Remove the upward hop.
- Is the tower easier or harder to clear?
YOU SHOULD SEE
Blocks barely move and drop straight down, so some land back on the platform: much harder.
Week 12 · Gravity & Projectiles
23 / 35
Common mistakes
When it goes wrong, check these first
The ball flies straight forever
Fix: Subtract GRAVITY × dt from v.y every frame, before moving.
The ball goes the wrong way
Fix: Check the signs in aimDirection(): the cannon faces −z, so x and z have minus signs.
Error in setFromPoints after aiming low
Fix: In r170 the point count must stay the same: always push 30 points (stop at the ground instead of breaking).
All balls share one velocity
Fix: Create a new Vector3 for each ball: aimDirection() returns a fresh one every call.
Week 12 · Gravity & Projectiles
24 / 35
Check your understanding · 1 of 4
Which line makes a projectile curve down?
A
position.y -= 1
B
v.y -= GRAVITY * dt
C
v.multiplyScalar(0.9)
D
rotation.x += dt
Week 12 · Gravity & Projectiles
25 / 35
Check your understanding · 2 of 4
Why is the pitch group inside the yaw group?
A
To save memory
B
So tilting happens in the direction the cannon faces
C
Groups must be nested
D
For shadows
Week 12 · Gravity & Projectiles
26 / 35
Check your understanding · 3 of 4
How is the predicted path drawn?
A
With a raycaster
B
By running the physics ahead and joining the points with a Line
C
With a texture
D
With OrbitControls
Week 12 · Gravity & Projectiles
27 / 35
Check your understanding · 4 of 4
Which test checks if the ball touches a block?
A
box.intersectsSphere(sphere)
B
box.containsBox(box)
C
sphere.distanceTo(0)
D
ray.intersectPlane
Week 12 · Gravity & Projectiles
28 / 35
Check your understanding
Answers
| Q | Answer | Why |
|---|---|---|
| Q1 | B · v.y -= GRAVITY * dt | Gravity changes the vertical velocity a little every frame. |
| Q2 | B · So tilting happens in the direction the cannon faces | The inner group inherits the outer group’s turn. |
| Q3 | B · By running the physics ahead and joining the points with a Line | The same physics, simulated ahead in small steps. |
| Q4 | A · box.intersectsSphere(sphere) | Box3.intersectsSphere tests a box against a sphere. |
Week 12 · Gravity & Projectiles
29 / 35
Lab time · 25 minutes
Your workflow for 3D files
1
Folder
Create a folder named Week12 and open it in VS Code.
2
Install
In the terminal: npm init -y, npm install three, npm install -D vite.
3
Run
npx vite starts the dev server. Leave it running.
4
Open
http://localhost:5173/ plus the file name, e.g. /first3d.html.
5
Check
Save with Ctrl+S; the page reloads. Open the console (F12).
Each week is an npm project: Vite finds “three” in node_modules, so a double-clicked file shows a blank page. Build the four example files first, then the game; work on a copy named cannonTower_yourname.html.
Week 12 · Gravity & Projectiles
30 / 35
Lab activity · cannonTower.html
Build Cannon Tower in nine stages
| Step | Objectives | Checkpoint |
|---|---|---|
| Scaffold + scene, ground | — | Grass and sky, no errors |
| Cannon: yaw and pitch groups | 3 | A cannon in the foreground |
| aimDirection(), muzzlePosition() | 4 | Ready to aim |
| Tower: buildTower(), settleColumns() | 7 | Three columns on a platform |
| fire() + updateBalls() | 1, 2, 6, 8 | Balls fly, bounce and hit |
| updateFlying() | 2, 7 | Hit blocks tumble off |
| updatePath() | 5 | The white arc shows the aim |
| Keyboard: aim, charge, fire | 3, 4 | Space charges and fires |
| Game state + loop | 8 | Shots, blocks left, win / lose |
Week 12 · Gravity & Projectiles
31 / 35
Stuck?
A five-step 3D debugging checklist
- Open the console (F12) and read the first red error.
- Blank page? Check npx vite is running and you opened http://localhost:5173/…, not the file itself.
- “Failed to resolve import three”? Run npm install in the week folder.
- Check the spelling and capitals: THREE.BoxGeometry, not THREE.boxGeometry.
- Nothing visible? Check the camera is not inside or behind the object.
THIS WEEK’S TIP
Slow everything down to watch a collision: in the loop use const dt = Math.min(clock.getDelta(), 0.05) * 0.25; (quarter speed).
Week 12 · Gravity & Projectiles
32 / 35
BUILD YOUR OWN · ALL OBJECTIVES
Make it yours: wind, levels and a moving target
Week12\cannonTower_yourname.html
- Wind: a random sideways acceleration each level, shown as an arrow; the predicted path ignores it!
- Levels: taller towers, farther away, fewer shots.
- Bonus: the platform slides slowly left and right.
Week 12 · Gravity & Projectiles
33 / 35
How the build-your-own task is marked
Marking guide
| Criterion | What we look for | Marks |
|---|---|---|
| Runs cleanly | Runs with npx vite with no console errors | 2 |
| Required features | Wind affects the balls; at least three levels | 4 |
| Readable code | Indented, sensible names, a comment on each function | 2 |
| Your own touch | New tower shapes, sounds, camera or effects | 2 |
| Total | 10 |
Week 12 · Gravity & Projectiles
34 / 35
Recap · Week 12
What you can do now
- Velocity is a Vector3; addScaledVector(v, dt) moves by it.
- Gravity: v.y −= 9.8 × dt; bounce with energy loss.
- Yaw and pitch in nested groups; sin and cos make the direction.
- Predict paths by simulating ahead; draw with a Line.
- Sphere + intersectsSphere; knock out, tumble, settle.
NEXT WEEK
Week 13 · Textures, Sound & HUD
Make games look and sound finished: canvas textures, Web Audio sound effects and an on-screen HUD.
Week 12 · Gravity & Projectiles
35 / 35