HTML and CSS Reference
Bouncing Balls Revisited
Doyourecallfrom CH5EX7.html howwecreatedbouncingballsthatbounceoffoneanother?
We are going to iterate the last example with just a few simple changes to create a world that
acts a lot like that example.
Instead of looking at balls from the side, we are looking at balls from the top (like it's a flat
2Dworldandweare looking down).Wewill also set ourdemo tohave 50balls instead of30.
var world = new
new b2World ( new
new b2Vec2 ( 0 , 0 ), true
var numBalls = 50 ;
Because there is no gravity in this world, we need some way for the balls to move when the
demostarts. Todothis,wewill addarandom x and y velocity toeach ball andthenpassthose
asparametersofanew b2Vec2() objectwithacalltotheball's SetLinearVelocity() meth-
var xVelocity = Math . floor ( Math . random () * 10 ) − 5 ;
var yVelocity = Math . floor ( Math . random () * 10 ) − 5 ;
newBall . SetLinearVelocity ( new
new b2Vec2 ( xVelocity , yVelocity ))
That's all we need to do to change our falling balls demo into something similar to the boun-
cing balls demo from earlier in the chapter.
Youcan test this example byopening CH5EX21.html inthe code distribution. The results will
look something like what you see in Figure 5-26 .