Multiple Balls Bouncing with Friction
If we want the balls to slow down and eventually stop, we need to add friction to Example 5-7. For our purposes, simple friction is a value we use to modify the velocity of our objects every time they are drawn to the canvas.
In canvasApp()
, we now want to
create balls of various sizes. In the previous example, the balls were
all the same size. It worked, but having balls of different sizes with
different masses will create more interesting effects. To do this, we
set minSize
to 3
and maxSize
to 12
, meaning that the radii for our balls will
range from 3
to 12
pixels. We also add a new property named
friction
. This is a global property,
so it will not be applied to each individual ball. We set it to .01
, which means our balls will degrade their
x
and y
velocities by .01
pixels per frame (every time drawScreen()
is called):
var
numBalls
=
50
;
var
maxSize
=
12
;
var
minSize
=
3
;
var
maxSpeed
=
maxSize
+
5
;
var
friction
=
.
01
;
We will now allow for various ball sizes. The mass of each ball
will be different, and balls will have different effects on one another
depending on their sizes. Recall that in Example 5-7 we needed a mass
property so that we could calculate
conservation of momentum when the balls collided. We are doing the same
thing here, but now the masses are different depending on the
size:
for
(
var
i
=
0
;
i
<
numBalls
;
i
++
)
{
tempRadius
=
Math
.
floor
(
Math
.
random
()
*
maxSize
)
+
minSize
;
In update()
, we apply the
friction
value by calculating the ...
Get HTML5 Canvas, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.