39
var tempSpeed;
var tempAngle;
var tempRadius;
var tempRadians;
var tempXunits;
var tempYunits;
Next, in canvasApp(), we iterate through a loop to create all the ball objects. Notice how
tempX and tempY are created below. These values represent the ball’s starting location
on the canvas. We create a random value for each, but we offset it by the size of the ball
(tempRadius*2). If we did not do that, some of the balls would get “stuck” in a wall when
the app starts because their x or y location would be “through” the wall, but their speed
would not be enough so that a “bounce” would get them back on the playfield. They
would be stuck in bouncing limbo forever (which is kind of sad when you think
about it).
When you try this app, you will see that occasionally a ball still gets
stuck in a wall. There is a further optimization we need to make to
prevent this, but it is a bigger subject than this little iteration. We will
talk about it in the section “Multiple Balls Bouncing and Colliding” on
page 219.
The tempSpeed variable is created by subtracting the value of tempRadius from the value
of maxSpeed, which we created earlier. The speed is not random, but it is inversely
proportional to the size (radius) of the ball. A larger ball has a larger radius, so the value
you subtract from tempSpeed will be larger, thus making the ball move more slowly.
When you run CH5EX5.html in your web browser, you will notice that
this little trick makes the ball appear more “real” because your brain
expects larger objects to move more slowly.
for (var i = 0; i < numBalls; i++) {
tempRadius = Math.floor(Math.random()*maxSize)+minSize;
tempX = tempRadius*2 + (Math.floor(Math.random()*theCanvas.width)
-tempRadius*2);
tempY = tempRadius*2 + (Math.floor(Math.random()*theCanvas.height)
-tempRadius*2);
tempSpeed = maxSpeed-tempRadius;
tempAngle = Math.floor(Math.random()*360);
tempRadians = tempAngle * Math.PI/ 180;
tempXunits = Math.cos(tempRadians) * tempSpeed;
tempYunits = Math.sin(tempRadians) * tempSpeed;
tempBall = {x:tempX,y:tempY,radius:tempRadius, speed:tempSpeed,
210 | Chapter 5: Math, Physics, and Animation