HTML and CSS Reference
In-Depth Information
Implementing the World Component
Box2D, like many other physics engines, relies on a central
world
object to act as a container for any physical
bodies that will be added to the game. Because this is fairly analogous to the
stage
object in Quintus, it makes
sense for the
world
to be a component added onto the stage.
The method calls to set up and simulate a Box2D world are actually simple. All you need to do is create a
new
Box2D.Dynamics.b2World
object, passing in the world's gravity. Then, for every frame, you need
to call the world's
step
method with the time elapsed since the last time step and the number of velocity and
position iterations. Running more iterations means that each simulation step is smaller, and the results of the
simulation will be better and more stable (that is, objects won't go flying off or fall through other objects) at the
cost of more rendering time.
Box2D provides an extensive API, which this topic doesn't cover in depth, so instead the engine is just going
to cherry-pick a limited subset of features to get some objects joyously flying around the screen.
The world component needs to make only few calls to get a Box2D world set up and running. To let objects
and collisions reach back out into the engine, it's also going to need to add in a listener that has its callbacks
triggered whenever there is a collision.
To start implementing the
Quintus.Physics
module, create a new file called
quintus_physics.js
, and
add the code in
Listing 14-9
.
Listing 14-9:
The Quintus.Physics bootstrap
Quintus.Physics = function(Q) {
var B2d = Q.B2d = {
World: Box2D.Dynamics.b2World,
Vec: Box2D.Common.Math.b2Vec2,
BodyDef: Box2D.Dynamics.b2BodyDef,
Body: Box2D.Dynamics.b2Body,
FixtureDef: Box2D.Dynamics.b2FixtureDef,
Fixture: Box2D.Dynamics.b2Fixture,
PolygonShape: Box2D.Collision.Shapes.b2PolygonShape,
CircleShape: Box2D.Collision.Shapes.b2CircleShape,
Listener: Box2D.Dynamics.b2ContactListener
};
var defOpts = Q.PhysicsDefaults = {
gravityX: 0,
gravityY: 9.8,
scale: 30,
velocityIterations: 8,
positionIterations: 3
};
Q.register('world',{
added: function() {
this.opts = _(defOpts).clone();
this._gravity = new B2d.Vec(this.opts.gravityX,
this.opts.gravityY);