HTML and CSS Reference
In-Depth Information
fixtureDef.shape = new B2d.CircleShape(p.r/scale);
case "polygon":
fixtureDef.shape = new B2d.PolygonShape;
var pointsObj =,function(pt) {
return { x: pt[0] / scale, y: pt[1] / scale };
fixtureDef.shape.SetAsArray(pointsObj, p.points.length);
this._body._bbid =;
removed: function() {
var entity = this.entity,
stage = entity.parent;;
step: function() {
var p = this.entity.p,
stage = this.entity.parent,
pos = this._body.GetPosition(),
angle = this._body.GetAngle();
p.x = pos.x *;
p.y = pos.y *;
p.angle = angle / Math.PI * 180;
When this component is added to a sprite, it first checks if the sprite has already been added to a stage. If so
it calls inserted immediately; otherwise, it waits until the inserted event is triggered.
The bulk of the code for the physics component, as you can see, is in the inserted method. This method
creates the Box2D body, sets up the fixture definition based on the shape of the object, and creates the fixture
on the body.
Two helper methods— position and velocity —let you set those properties onto the sprite's body. Both
of those methods also call SetAwake(true) on the body. Box2D puts objects that aren't moving and causing
collisions “asleep” after a period of time to save on CPU cycles. To ensure that the object “wakes up” and starts
responding to forces again when it is artificially moved, SetAwake needs to be called manually. (Normally,
box 2D handles this for you anytime an object is involved in a collision.)
The removed method simply ensures that the body is destroyed from the Box2D world, in addition to the
sprite being removed from the screen.
Finally the step method, which is called after every step, has the responsibility to translate the position and
angle of the body in the Box2D back into the position of the sprite, taking into consideration the scale property
discussed earlier.
Search WWH ::

Custom Search