Multiple Balls Bouncing and Colliding

Now it’s time to step it up again. Testing balls bouncing off walls is one thing, but what about balls bouncing off one another? We will need to add some pretty intricate code to handle this type of interaction.

Ball interactions in physics

For this example, we are going to create an elastic collision, which means that the total kinetic energy of the objects is the same before and after the collision. This is known as the law of conservation of momentum (Newton’s third law). To do this, we will take the x and y velocities of two colliding balls, and draw a “line of action” between their centers. This is illustrated in Figure 5-9, which has been adapted from Jobe Makar and Ben Winiarczyk’s Macromedia’s Flash MX 2004 Game Design Demystified (Macromedia Press). Then we will create new x and y velocities for each ball based on this angle and the law of conservation of momentum.

To properly calculate conservation of momentum when balls collide on the canvas, we need to add a new property: mass. Mass is the measurement of how much a ball (or any object) resists any change in its velocity. Because collisions tend to change the velocity of objects, this is an important addition to the ball objects we will use on the canvas.

Two balls colliding at different angles with a line of action drawn between them

Figure 5-9. Two balls colliding at different angles with a line of action drawn between them

Making sure the balls don’t start on top ...

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

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.