HTML and CSS Reference
In-Depth Information
Creating the Boxes
The world we are going to simulate is essentially the same as in the last example, with a pos-
itive y-axis gravitation force of 10 and a
scaleFactor
of 30.
var
var
world
=
new
new
b2World
(
new
new
b2Vec2
(
0
,
10
),
true
true
);
var
var
scaleFactor
=
30
;
In this world, we will create a set of eight 25×25 pixel boxes that are piled on top of each
other, 100 pixels from the right side of the Canvas, and starting 100 pixels from the bottom so
that they will fall to the ground when the demo starts:
var
var
numBoxes
=
8
;
var
var
boxes
=
new
new
Array
();
var
var
boxHeight
=
25
;
var
var
boxWidth
=
25
;
var
var
startX
=
(
theCanvas
.
width
-
100
);
var
var
startY
=
(
theCanvas
.
height
-
boxHeight
)
-
100
When we loop through, creating the boxes, we perform essentially the same operations as
when we create walls. We use the
scaleFactor
to convert to MTS units, but instead of de-
fining a
b2_staticBody
, we define the box as a
b2_dynamicBody
, which means it can move
and be affected by the physics-driven models in Box2D.
One other thing we do here is offset each box to the right by
(i*2)
pixels. We do this so that
eachsuccessiveboxwillfallatinybittotherightoftheboxunderit.Thiswillmakethestack
unstable so that the boxes fall over when they hit the ground. We want to do this so that we
can illustrate rotating the boxes on the Canvas:
for
for
(
var
var
i
=
0
;
i
<
numBoxes
;
i
++
) {
var
var
boxDef
=
new
new
b2BodyDef
;
boxDef
.
type
=
b2Body
.
b2_dynamicBody
;
var
var
ypos
=
(
startY
-
(
i
*
boxHeight
))
/
scaleFactor
;
var
var
xpos
=
(
startX
+
(
i
*
2
))
/
scaleFactor
;
boxDef
.
position
.
Set
(
xpos
,
ypos
);
var
var
newBox
=
world
.
CreateBody
(
boxDef
)
var
var
boxFixture
=
new
new
b2FixtureDef
;
boxFixture
.
density
=
10.0
;
boxFixture
.
friction
=
0.5
;
boxFixture
.
restitution
=
1
;
boxFixture
.
shape
=
new
new
b2PolygonShape
;
boxFixture
.
shape
.
SetAsBox
((
boxWidth
/
scaleFactor
)
/
2
, (
boxHeight
/
scaleFactor
)
/
2
);
newBox
.
CreateFixture
(
boxFixture
);