HTML and CSS Reference
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
Forthisexample,wearegoingtocreatean elasticcollision ,whichmeansthatthetotalkinetic
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 velocit-
ies of two colliding balls, and draw a “line of action” between their centers. This is illustrated
in Figure 5-9 ,whichhasbeenadaptedfromJobeMakarandBenWiniarczyk'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.
addanewproperty: mass .Massisthemeasurement ofhowmuchaball(oranyobject)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.
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 of each other
Wewillworkfromthecodewecreatedfor Example 5-6 ( CH5EX6.html ).Thefirstbigchange