HTML and CSS Reference
In-Depth Information
Rendering the Boxes
Torendertheboxes,weloopthroughtheboxesarrayin drawScreen() inasimilar mannerto
how we looped through the balls in CH5EX22.html . We retrieve the position and shape using
GetPosition() and GetShape() , preparing to render the boxes:
for
for ( i = 0 ; i < boxes . length ; i ++ ) {
var
var position = boxes [ i ]. GetPosition ();
var
var fixtureList = boxes [ i ]. GetFixtureList ();
var
var shape = fixtureList . GetShape ();
However, because these are boxes that fall and rotate, we need to perform some significantly
different operations to render the boxes correctly. First we retrieve the object we saved in the
user data attached to the body by calling GetUserData() :
var
var userData = boxes [ i ]. GetUserData ();
Next we save the Canvas context, reset the transformation matrix, and translate to the center
of the box. Because the origin of the objects in Box2D is set to the center, we don't have to
offset to the center for our transformation. Next we rotate the Canvas to the angle of the box.
We find the angle with a call to GetAngle() :
context . save ();
context . setTransform ( 1 , 0 , 0 , 1 , 0 , 0 );
context . translate ( position . x * scaleFactor , position . y * scaleFactor );
context . rotate ( boxes [ i ]. GetAngle ());
To draw the box, we need to offset the x and y from the position back to ½ width and height
because we draw on the Canvas with an origin at the upper-left corner. Then we restore the
context, and we are done with the box:
context . fillRect ( 0 - ( userData . width * scaleFactor / 2 ), 0 -
( userData . height * scaleFactor / 2 ),
userData . width * scaleFactor , userData . height * scaleFactor );
context . restore ();
}
We have nowmodeled boxes falling and reacting to gravity and collisions with other boxes in
Box2D. You can view this example by looking at CH5EX23.html in the code distribution.
Search WWH ::




Custom Search