HTML and CSS Reference
In-Depth Information
createBody: function(def) {
return this._world.CreateBody(def);
destroyBody: function(body) {
return this._world.DestroyBody(body);
boxStep: function(dt) {
if(dt > 1/20) { dt = 1/20; }
Box2D.Dynamics.b2World is an example of one of the nicely namespaced objects that Box2D defines.
The only problem with this namespacing is that it is a little burdensome to type. For this reason it's common to
create a scoped set of shortened class names; Quintus follows this pattern as well by adding elements to a B2d
Next, the module defines a number of defaults that you can use to create and run the world. These include the
x and y components of gravity, a scale multiplier, and counters for the number of velocity and position iterations
to run.
The scale option is an interesting one. Although you might think that it shouldn't matter what size objects
are, Box2D works better when objects are measured on a smaller scale, such as in the range of 1-10, as opposed
to, say 100-1000. This means that the normal scale of pixels doesn't match well with Box2D's preferred object
scale. That's the reason for the scale option in the defaults. It's a divisor used to scale down objects from a
pixel-size scale to a smaller range. If you think of a single unit as a meter, and work with objects in the range of
one to a few meters, you can hit the sweet spot for Box2D's calculations.
Next, the added method does the primary work to create the world. This is actually easier than it sounds.
All that's needed is to create a gravity vector from the options hash and then create a new B2d.World object.
With that, you could start adding entities to Box2D and simulate the world.
The only problem would be that you'd have no information about when an object collided with another ob-
ject. Objects would still not overlap, as Box2D handles that part, but you'd lack any meaningful information
about interactions that is necessary to build a game. (Do you want that bullet just bouncing off the enemy?)
To get around this, Box2D provides the ability to set a contact listener. The world component ties into this
and then passes forward any collisions it receives to the sprites that received the collision by triggering con-
tact , endContact , and impulse events that correspond to Box2D's BeginContact , EndContact ,
and PostSolve callbacks. The first two— BeginContact and EndContact —are called when two entit-
ies start touching and stop touching, respectively.
The last, PostSolve , is called every time there is an impulse caused by another body. This can be quite
often (imagine a ball rolling down a hill), so you must to be careful to keep the impulse event handlers quick.
Search WWH ::

Custom Search