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 because it is a radius):

tempBall = {x:tempX,y:tempY,radius:tempRadius, speed:tempSpeed,
            angle:tempAngle, xunits:tempXunits, yunits:tempYunits}

Inside ...

Get HTML5 Canvas, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.