HTML and CSS Reference
In-Depth Information
To keep the memory usage down, all the collision handlers also reuse the same col object among all the events
and use the helper method setCollisionData to populate the data for the callbacks.
Each callback triggers three events, one on each object and then one on the stage. This allows you to central-
ize collision detection in the stage in lieu of on each object if necessary.
With the contact listener set, the added method binds itself to the stage's step method to trigger the
boxStep callback. boxStep is responsible for stepping the world at the correct rate using the dt passed into
the callback along with the number of velocity and position iterations.
The only other methods— createBody and destroyBody —act as proxies for the Box2D world's meth-
ods of the same name.
Implementing the Physics Component
With the world component built, up next is a component to add physics support to the sprites. This component
will be called, not surprisingly, physics . Its job is to create a Box2d body that matches the sprite's size and
shape when added, update the sprite's position based on Box2D's simulation, and remove the body when the
sprite is removed.
Box2D supports two types of objects: static and dynamic. Static objects don't do anything but wait for dy-
namic objects to collide into them. They are also much lighter on the processor because they don't need to be
actively updated each step. The component enables the creation of either type based on a type property, with
the default being dynamic objects.
The main complexity of the component resides in the insert method, which is called after the sprite has
been added to the stage. This method is responsible to create the body object that will be added into the Box2D
world. Bodies have a number of properties, including a position and whether the body is static or dynamic.
These properties need to be set to initial values before the body is created.
None of those properties, however, tell Box2D anything about the shape. That job is the responsibility of one
or more fixtures added to the body. Each fixture must be a convex shape (meaning it has no dents), and although
multiple fixtures are supported in Box2D, the physics component will just support one. The fixtures also have
details like the object's density, friction, and restitution (bounciness).
To get the physics component into the engine, add the code in Listing 14-10 to the bottom of quin-
tus_physics.js , before the final closing curly brace.
Listing 14-10: The physics component
var entityDefaults = Q.PhysicsEntityDefaults = {
density: 1,
friction: 1,
restitution: .1
added: function() {
if(this.entity.parent) {
} else {
Search WWH ::

Custom Search