HTML and CSS Reference
In-Depth Information
The following code shows the newly defined variables:
var numBalls = 100 ;
var maxSize = 8;
var minSize = 5;
var maxSpeed = maxSize+5;
var balls = new Array();
We also create a set of temporary variables to hold the values for each ball before we
push it into the balls array:
var tempBall;
var tempX;
var tempY;
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 lo-
cation 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 play-
field. 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 Collid-
ing” on page 198 .
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 pro-
portional to the size (radius) of the ball. A larger ball has larger radius, so the value you
subtract from tempSpeed will be larger, thus making the ball move slower:
When you run CH5EX4.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 slower.
Search WWH ::

Custom Search