HTML and CSS Reference
In-Depth Information
balls
An array to hold all of the ball objects we will create
The following code shows the newly defined variables:
var
var numBalls = 100 ;
var
var maxSize = 8 ;
var
var minSize = 5 ;
var
var maxSpeed = maxSize + 5 ;
var
var balls = new
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
var tempBall ;
var
var tempX ;
var
var tempY ;
var
var tempSpeed ;
var
var tempAngle ;
var
var tempRadius ;
var
var tempRadians ;
var
var tempXunits ;
var
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 ( tempRa-
dius*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).
NOTE
Whenyoutrythisapp,youwillseethatoccasionallyaballstillgetsstuckinawall.Thereisafurther
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 .
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.
Search WWH ::




Custom Search