HTML and CSS Reference
In-Depth Information
The points on the line are not drawn when executed in the web browser
because they slowed down the ball far too much. We left them in Fig-
ure 5-5 to illustrate the angles of incidence and reflection.
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 programming 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.
In the case of 100 balls bouncing on the canvas, we will need to create a ball object with
a few 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. However, because we need to make sure everything works the same way in this
app, we make 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 since it is a radius):
angle:tempAngle, xunits:tempXunits, yunits:tempYunits}
Inside canvasApp() , we define some new variables to help manage the multiple balls
that will bounce around the canvas:
numBalls
The number of balls to randomly create
maxSize
The maximum radius length for any given ball
minSize
The minimum radius length for any given ball
maxSpeed
The maximum speed any ball can travel
balls
An array to hold all of the ball objects we will create
Search WWH ::

Custom Search