Online Book Reader

Home Category

HTML5 Canvas [69]

By Root 6566 0
on which the ball is traveling. This gives us the angle of reflection. Alternatively, if the ball hits the top (ball.y < 0) or bottom (ball.y > theCanvas.height) of the canvas, we calculate the angle of reflection with 360 degrees minus the angle of the vector on which the ball is traveling:

if (ball.x > theCanvas.width || ball.x < 0 ) {

angle = 180 - angle;

updateBall();

} else if (ball.y > theCanvas.height || ball.y < 0) {

angle = 360 - angle;

updateBall();

}

That’s it. Example 5-4 demonstrates a ball that bounces off walls using the rules of physics. Figure 5-5 illustrates the code.

Example 5-4. Ball bounce

CH5EX4: Ball Bounce

Your browser does not support HTML5 Canvas.

Figure 5-5. A single ball bouncing off a wall

NOTE

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 Figure 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):

tempBall = {x:tempX,y:tempY,radius:tempRadius, speed:tempSpeed,

angle:tempAngle, xunits:tempXunits, yunits:tempYunits}

Inside canvasApp(), we define some new variables

Return Main Page Previous Page Next Page

®Online Book Reader