HTML and CSS Reference
In-Depth Information
Your browser does not support the HTML5 Canvas.
</canvas>
</canvas>
Next, we create a rigid body definition object, setting the
x
and
y
position in the
b2BodyDef
to the location of the mouse click, and we set the size of the ball radius to 7 pixels, which we
will use a few lines down:
var
var
ballDef
=
new
new
b2BodyDef
;
ballDef
.
type
=
b2Body
.
b2_dynamicBody
;
var
var
ypos
=
mouseY
/
scaleFactor
;
var
var
xpos
=
mouseX
/
scaleFactor
;
var
var
size
=
7
/
scaleFactor
;
ballDef
.
position
.
Set
(
xpos
,
ypos
);
Nextwecreatethefixture,settingthedensityoftheballto30(harderthantheboxes),friction
to.6(onlybecause itmakesthesimulation feelbetter whenrunning),andsettherestitution to
.2, which is more than both the boxes and the walls because we want to balls to bounce a bit
higher than the boxes when they hit another object:
var
var
ballFixture
=
new
new
b2FixtureDef
;
ballFixture
.
density
=
30.0
;
ballFixture
.
friction
=
0.6
;
ballFixture
.
restitution
=
.
2
;
ballFixture
.
shape
=
new
new
b2CircleShape
(
size
);
var
var
newBall
=
world
.
CreateBody
(
ballDef
)
newBall
.
CreateFixture
(
ballFixture
);
Then, we set the linear velocity of the balls to positive 15 on the x axis, which will have them
start moving across the Canvas to the right when they are created:
var
var
xVelocity
=
15
;
var
var
yVelocity
=
0
;
newBall
.
SetLinearVelocity
(
new
new
b2Vec2
(
xVelocity
,
yVelocity
))
balls
.
push
(
newBall
);
}
Finally, we need to render the balls in
drawScreen()
. Except for the fact that we color the
balls red, the rendering we do here is essentially the same as we did in the bouncing balls
demo in
CH5EX22
:
for
for
(
i
=
0
;
i
<
balls
.
length
;
i
++
) {
var
var
position
=
balls
[
i
].
GetPosition
();
var
var
fixtureList
=
balls
[
i
].
GetFixtureList
();
var
var
shape
=
fixtureList
.
GetShape
();
context
.
fillStyle
=
"#FF0000"
;
context
.
beginPath
();