HTML and CSS Reference
In-Depth Information
Multiple Balls Bouncing with Friction
Ifwewanttheballstoslowdownandeventuallystop,weneedtoaddfrictionto 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
willcreate moreinteresting effects.Todothis,weset minSize to 3 and maxSize to 12 ,mean-
ing 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 ;
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
for ( var
var i = 0 ; i < numBalls ; i ++ ) {
tempRadius = Math . floor ( Math . random () * maxSize ) + minSize ;
In update() , we apply the friction value by calculating the product of the current velocity
multiplied by friction and then subtracting that value from the current velocity. We do this for
both the x and y velocities. Why must we do this instead of simply subtracting the friction
value from the x and y velocities? Because the x and y velocities are not always proportional
to each other. If we simply subtract the friction, we might alter the velocity unintentionally.
Instead, we need to subtract a value for the friction that is proportional to the velocity itself,
and that value is the product of the velocity multiplied by the friction value. This method
will give you a smooth degradation of the velocity when the friction value is applied:
function update () {
for ( var
var i = 0 ; i < balls . length ; i ++ ) {
ball = balls [ i ];
Search WWH ::

Custom Search