WEEK 04

Web Games Development · HTML5 Lab

Objects & Physics

Build reusable game objects, simulate gravity, and launch a projectile with the mouse.

objects

gravity

trigonometry

mouse events

Book: Chapter 4 · Cannonball and Slingshot · pp. 97–140

Today · 90 minutes

Plan for the session

StartSegmentTime
0:00Warm-up review10 min
0:10This week’s game and objectives10 min
0:20Concepts: idea, code, line by line, try it35 min
0:55Common mistakes and check your understanding5 min
1:00Lab: build the files25 min
1:25Build-your-own task, recap and exit quiz5 min

Week 4 · Objects & Physics

2 / 35

Warm-up · 5 minutes

Remember Week 3?

1

Which function repeats code on a timer?

2

How does the ball bounce off a wall?

3

What does Number() do?

4

What does drawImage need?

Week 4 · Objects & Physics

3 / 35

This week’s game

Launch a ball and hit the target

The ball keeps a constant horizontal speed while gravity changes its vertical speed, so it flies in an arc.

Three versions: a cannonball with speeds typed in; a cannon rotated to an angle, where a hit swaps the target image; a slingshot you drag with the mouse. Hit the chicken and only feathers remain.

FROM THE BOOK

Chapter 4 · Cannonball and Slingshot
pp. 97–140


YOU WILL BUILD

  • cannball1.html
  • cannBall2.html
  • slingshot.html

Week 4 · Objects & Physics

4 / 35

Objectives

By the end of Week 4 you can…

01

Create objects with constructor functions and new.

02

Give objects their own data and methods: draw(), moveit().

03

Keep every object in an array and redraw them all in one loop.

04

Handle mousedown, mousemove and mouseup.

05

Hit-test a click against a circle using squared distance.

06

Turn a drag into a velocity with atan2, cos and sin.

07

Simulate projectile motion with gravity.

08

Detect collisions with the target and the ground.

Week 4 · Objects & Physics

5 / 35

Key words this week

Vocabulary

TermMeaning
objectA bundle of data and functions (methods)
constructorA function used with new to make objects
methodA function that belongs to an object: draw, moveit
arrayAn ordered list; push adds to the end
gravityA constant added to the vertical speed every tick
radiansThe angle unit JavaScript trig uses: 180° = π
atan2Gives the angle from a pair of dy, dx distances
event listenerA function run when an event such as mousedown happens

Week 4 · Objects & Physics

6 / 35

What the program must do

What a ballistics game needs

Timed animation

The same interval technique as the bouncing ball.

Gravity

Change the vertical speed by a constant amount on every step.

A scene of objects

Ball, target, ground and cannon are kept in one list and redrawn together.

Mouse drag

Press, drag and release to set the launch speed and angle.

Week 4 · Objects & Physics

7 / 35

Big idea 1 · Objects & arrays

Build the scene from objects

1

Constructor

Ball(sx, sy, rad, style) describes a ball.

2

new

new Ball(…) makes one ball.

3

List

everything holds every object to draw.

Week 4 · Objects & Physics

8 / 35

Example 1 · Objects & arrays

Objects that draw themselves

A constructor makes objects; an array holds them; one loop draws them all.

CODE · script · canvas 400 × 200

function Ball(x, y, r, color) {
  this.x = x;  this.y = y;  this.r = r;
  this.color = color;
  this.draw = function () {
    ctx.fillStyle = this.color;
    ctx.beginPath();
    ctx.arc(this.x, this.y, this.r, 0, 2*Math.PI);
    ctx.fill();
  };
}
var things = [new Ball(60, 100, 30, "crimson"),
  new Ball(180, 80, 20, "teal"),
  new Ball(300, 120, 40, "gold")];
things.forEach(function (b) { b.draw(); });

OUTPUT · canvas 400 × 200, shown enlarged

Week 4 · Objects & Physics

9 / 35

Line by line · Example 1

Objects that draw themselves

function Ball(x, y, r, color)

A constructor: the recipe for a ball.

this.x = x;

Each ball keeps its own position.

this.draw = function () {…}

A method: each ball knows how to draw itself.

new Ball(60, 100, 30, "crimson")

Make one ball from the recipe.

things.forEach(… b.draw() …)

Draw every object in the list.

Week 4 · Objects & Physics

10 / 35

Try it · 5 minutes

Add an object

  1. Create a second Ball in a different colour.
  2. Push it into everything.
  3. Refresh and fire.

YOU SHOULD SEE

Two balls appear, but only cball flies when you fire.

Week 4 · Objects & Physics

11 / 35

Big idea 2 · Gravity

Constant sideways, changing downward

1

dx

Stays the same every tick.

2

Vertical speed

Gains gravity every tick.

3

Result

The path bends into an arc.

Week 4 · Objects & Physics

12 / 35

Example 2 · Gravity

Gravity bends the path

Sideways speed stays the same; gravity adds to the downward speed every step.

CODE · script · canvas 400 × 200

var x = 20, y = 180, vx = 4, vy = -9;
var gravity = 0.3;
function step() {
  vy = vy + gravity;          // pull down
  x = x + vx;
  y = y + vy;
  ctx.beginPath();
  ctx.arc(x, y, 4, 0, 2 * Math.PI);
  ctx.fill();                 // leave a trail
  if (y > 190) clearInterval(timer);  // ground
}
var timer = setInterval(step, 30);

OUTPUT · running live, restarts after landing

Week 4 · Objects & Physics

13 / 35

Line by line · Example 2

Gravity bends the path

vx = 4, vy = -9

Start moving right and upward (y grows down).

vy = vy + gravity;

Every step, the upward speed shrinks, then turns downward.

x = x + vx;

Sideways speed never changes.

ctx.fill();

No clearRect, so each dot stays: a trail.

if (y > 190) clearInterval(timer);

Stop when the ball reaches the ground.

Week 4 · Objects & Physics

14 / 35

Try it · 5 minutes

Experiment with gravity

  1. Double the gravity value.
  2. Set gravity to 0.
  3. Try a negative value.

YOU SHOULD SEE

Double: a short, steep arc. Zero: a straight line. Negative: the ball floats upward.

Week 4 · Objects & Physics

15 / 35

Big idea 3 · Angles & rotation

Split one speed into two parts

1

Radians

Degrees × π / 180.

2

cos

cos(angle) × speed is the sideways part.

3

sin

sin(angle) × speed is the upward part; minus, because y grows down.

Week 4 · Objects & Physics

16 / 35

Example 3 · Angles & rotation

Aim with an angle

Trig splits a speed into sideways and upward parts; rotate() turns the drawing.

CODE · script · canvas 400 × 200

var deg = 40;
var angle = deg * Math.PI / 180;    // radians
ctx.save();
ctx.translate(60, 170);             // pivot
ctx.rotate(-angle);                 // turn
ctx.fillRect(0, -10, 120, 20);      // barrel
ctx.restore();
var vx = 10 * Math.cos(angle);
var vy = -10 * Math.sin(angle);
ctx.fillText("vx = " + vx.toFixed(1), 220, 70);
ctx.fillText("vy = " + vy.toFixed(1), 220, 110);

OUTPUT · canvas 400 × 200, shown enlarged

Week 4 · Objects & Physics

17 / 35

Line by line · Example 3

Aim with an angle

deg * Math.PI / 180

Degrees to radians: JavaScript trig uses radians.

ctx.translate(60, 170);

Move the origin to the pivot point.

ctx.rotate(-angle);

Turn everything drawn next (minus = upward).

ctx.save(); … ctx.restore();

Undo the move and turn afterwards.

10 * Math.cos(angle)

The sideways share of a speed of 10.

Week 4 · Objects & Physics

18 / 35

Try it · 5 minutes

Find the best angle

  1. Keep the speed the same.
  2. Fire at 30°, 45° and 60°.
  3. Note where each shot lands.

YOU SHOULD SEE

In simple physics, 45° goes furthest on flat ground, and 30° and 60° land close together.

Week 4 · Objects & Physics

19 / 35

Big idea 4 · Mouse events

Press, drag, release

1

mousedown

Is the click on the ball?

2

mousemove

Drag the ball and the sling while inmotion.

3

mouseup

Launch: the pull distance sets the speed.

Week 4 · Objects & Physics

20 / 35

Example 4 · Mouse events

Press, drag, release

Three listeners track the mouse: down starts a drag, move follows it, up ends it.

CODE · script · c = canvas 760 × 380

var dragging = false;
c.addEventListener("mousedown", function () {
  dragging = true;
});
c.addEventListener("mousemove", function (e) {
  if (dragging) {
    ctx.beginPath();
    ctx.arc(e.offsetX, e.offsetY, 6, 0, 2*Math.PI);
    ctx.fill();          // paint while dragging
  }
});
c.addEventListener("mouseup", function () {
  dragging = false; });

OUTPUT · demo moves the pointer by itself

Week 4 · Objects & Physics

21 / 35

Line by line · Example 4

Press, drag, release

addEventListener("mousedown", …)

Run this function when the button goes down.

dragging = true;

Remember the button is held.

if (dragging) { … }

Only draw while the button is held.

e.offsetX, e.offsetY

Where the mouse is, inside the canvas.

dragging = false;

Button released: stop drawing.

Week 4 · Objects & Physics

22 / 35

Try it · 5 minutes

Tune the slingshot

  1. Change 700 to 350.
  2. Then change it to 1400.
  3. Which makes the sling stronger?

YOU SHOULD SEE

350 doubles the launch speed; 1400 halves it.

Week 4 · Objects & Physics

23 / 35

Common mistakes

When it goes wrong, check these first

Nothing draws

Fix: Inside a constructor write this.sx = sx, not sx = sx.

An object never appears

Fix: Push it into everything, then call drawall().

The ball flies the wrong way

Fix: Convert degrees to radians before cos/sin, and keep the minus on the vertical part.

Dragging does nothing

Fix: Attach the listeners to the canvas, and read the mouse position the way slingshot.html does (layerX / offsetX).

Week 4 · Objects & Physics

24 / 35

Check your understanding · 1 of 4

What does new Ball(…) do?

A

Draws a ball

B

Creates a ball object

C

Deletes a ball

D

Loads an image

Week 4 · Objects & Physics

25 / 35

Check your understanding · 2 of 4

Each tick, gravity changes the…

A

Horizontal speed

B

Vertical speed

C

Ball radius

D

Cannon angle

Week 4 · Objects & Physics

26 / 35

Check your understanding · 3 of 4

Why multiply degrees by Math.PI/180?

A

JavaScript trig uses radians

B

To make it bigger

C

To round it

D

To rotate the canvas

Week 4 · Objects & Physics

27 / 35

Check your understanding · 4 of 4

Which event starts the drag?

A

mouseup

B

mousemove

C

mousedown

D

click

Week 4 · Objects & Physics

28 / 35

Check your understanding

Answers

QAnswerWhy
Q1B · Creates a ball objectnew runs the constructor and returns a new object.
Q2B · Vertical speedHorizontal speed stays constant.
Q3A · JavaScript trig uses radiansMath.cos and Math.sin expect radians.
Q4C · mousedownfindball runs on mousedown and sets inmotion.

Week 4 · Objects & Physics

29 / 35

Lab time · 25 minutes

Your workflow for every file

1

Folder

Create a folder named Week4.

2

Copy

Copy the example files and their images, audio or video into it.

3

Open

Open the folder in VS Code or Sublime Text.

4

Save

Edit, then save with Ctrl+S.

5

Check

Refresh the browser (F5). Open the console (F12).

Never edit the original example for grading. Work on a copy named with your name, for example slingshot_yourname.html.

Week 4 · Objects & Physics

30 / 35

Lab activity · Week4 folder

From cannonball to slingshot

FileObjectivesCheckpoint
cannball1.html1, 2, 3, 7A fired ball follows a gravity arc
cannBall2.html1, 2, 3, 6, 7The cannon rotates; a hit swaps the hill for the plateau
slingshot.html1–8Drag to launch; a hit turns the chicken into feathers

Compare the three files: the flight code barely changes. Only the way the player sets speed and angle is new.

Week 4 · Objects & Physics

31 / 35

Stuck?

A five-step debugging checklist

  1. Open the console (F12) and read the first red error.
  2. Check the spelling and capitals of every name and id.
  3. Check that brackets, braces and quotes come in pairs.
  4. Check file names, and that every file is in the same folder.
  5. Save, then hard-refresh with Ctrl+F5.

THIS WEEK’S TIP

Add console.log(horvelocity, verticalvel1) in fire() to check that your angle maths gives sensible speeds.

Week 4 · Objects & Physics

32 / 35

BUILD YOUR OWN · ALL OBJECTIVES

Keep score of chicken hits

Week4\slingshot_yourname.html

Week 4 · Objects & Physics

33 / 35

How the build-your-own task is marked

Marking guide

CriterionWhat we look forMarks
Runs cleanlyOpens with no errors in the console (F12)2
Required featuresScore rises on every chicken hit; the score is shown; the chicken can be reset4
Readable codeIndented, sensible names, a comment on each function2
Your own touchA personal change: colours, images, text or an extra feature2
Total10

Week 4 · Objects & Physics

34 / 35

RECAP · CHAPTER 4 · CANNONBALL AND SLINGSHOT SUMMARY

What you can do now

  • Programmer-defined objects.
  • An array built with push as the list of what to draw; splice to change it.
  • Trig to rotate the cannon and split the velocity.
  • Mouse events with addEventListener.
  • Drawing arcs, rectangles, lines and images.

NEXT WEEK

Week 5 · Memory Game

Cards as objects, shuffling, click hit-tests, pauses, timing and polygons.

Week 4 · Objects & Physics

35 / 35

Keyboard
→ Space next   ← previous   Home/End first / last
F full screen   N speaker notes   P print / save as PDF
Click the right or left half of a slide to move forward or back.

Save as PDF: press P, choose “Save as PDF”, and turn on “Background graphics”.