HTML and CSS Reference
In-Depth Information
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 dif-
ferent masses will create more interesting effects. To do this, we set minSize to 3 and
maxSize to 12 , meaning 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 we could calculate conservation of mo-
mentum 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 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 may
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 i = 0; i <balls.length; i++) {
ball = balls[i];
ball.velocityx = ball.velocityx - ( ball.velocityx*friction);
ball.velocityy = ball.velocityy - ( ball.velocityy*friction);
ball.nextx = (ball.x += ball.velocityx);
ball.nexty = (ball.y += ball.velocityy);
You can see the full version of this code by executing CH5EX8.html from the code
distribution, or by typing in Example 5-8 . You should notice that the smaller balls have
less of an effect on the larger balls when they collide, and vice versa. Also, the balls slow
down as they move due to the applied friction.
Search WWH ::

Custom Search