HTML and CSS Reference
In-Depth Information
Multiple Balls Bouncing Off Walls
One ball is cool, but what about 100? Is the code 100 times more complicated? No, not at
all. In fact, the code is only slightly more complicated, but it is also more refined. Most pro-
gramming tasks that require only a single object of a type tend to allow you to be a bit lazy.
However, when you need to build an application that must support n number of objects, you
need to make sure the code will work in many different cases.
more properties. Recall that the ball object we created previously had only x and y properties
and looked like this:
var ball = { x : p1 . x , y : p1 . y };
All the other variables that represented the ball ( speed , angle , xunits , yunits ) were global
in scope to the canvasApp() . We used global variables because we could get away with it.
all those values properties of each ball object.
For the multiple-ball-bounce application, we will create an object that holds all the pertinent
information about each bouncing ball: x , y , speed , angle , xunits , and yunits . Because we
are going to create 100 balls of various sizes, we also add a property named radius , which
represents the size of the ball (well, half the size because it is a radius):
tempBall = { x : tempX , y : tempY , radius : tempRadius , speed : tempSpeed ,
angle : tempAngle , xunits : tempXunits , yunits : tempYunits }
Inside canvasApp() ,wedefinesomenewvariablestohelpmanagethemultipleballsthatwill
bounce around the canvas:
The number of balls to randomly create
The maximum radius length for any given ball
The minimum radius length for any given ball
The maximum speed any ball can travel
Search WWH ::

Custom Search