HTML and CSS Reference
In-Depth Information
Defining the Walls in Box2D
We now have our walls defined with locations and sizes based on MTS units. We can start
defining the walls based on Box2D objects. We start by creating an array to hold our walls,
and then we loop through the wallDefs array to create the four walls that bound the screen.
var walls = new
new Array ();
for ( var
var i = 0 ; i < wallDefs . length ; i ++ ) {
Next we start to define a wall by creating an instance b2BodyDef . A b2BodyDef object will
hold the definitions we need to define a rigid body. Recall that a rigid body will have a shape
and fixture applied to create a Box2D object that we can manipulate. We set the type to be
b2_staticBody , which means that this object will never move and has infinite mass: perfect
for the walls that bound our Canvas. We then set the position of wallDef to the position for
thiswallassetinthearrayofdynamicobjects.Finally,wecall world.createBody(wallDef)
to create a rigid body in Box2D, based on the definitions set in the b2BodyDef object:
var wallDef = new
new b2BodyDef ;
wallDef . type = b2Body . b2_staticBody ;
wallDef . position . Set ( wallDefs [ i ]. x , wallDefs [ i ]. y );
var newWall = world . CreateBody ( wallDef )
the rigid body, and it contains properties for our Box2D object. First, we create a new b2Fix-
tureDef , and then we set the density (mass per unit volume), friction (resistance, usually
between 0 and 1), and the restitution (elasticity, usually between 0 and 1):
var wallFixture = new
new b2FixtureDef ;
wallFixture . density = 10.0 ;
wallFixture . friction = 0.5 ;
wallFixture . restitution = 1 ;
Now that we have the fixture, we need to create the shape. We set the shape property of the
fixtureas b2PolygonShape ,andthenwecalltheshape's setAsBox() method(passthe width
and height of the wall) to finish defining the shape. Next we close the loop by calling the
createFixture() methodofourrigidbody,passing wallFixture astheparameter.Thissets
the fixture and shape to the rigid body. Finally, we add the rigid body to our walls array.
wallFixture . shape = new
new b2PolygonShape ;
wallFixture . shape . SetAsBox ( wallDefs [ i ]. w , wallDefs [ i ]. h );
newWall . CreateFixture ( wallFixture );
walls . push ( newWall );
Search WWH ::

Custom Search