Moscrif API Docs for: 2012q3
Show:

b2World Class

Library: box2d

The world class manages all physics entities, dynamic simulation, and asynchronous queries. The world also contains efficient memory management facilities.

Methods

this

(
  • [xGravity=0]
  • [yGravity=9.8]
  • [doSleep]
  • [enableCollisions]
)

Construct a world object.

Parameters:

  • [xGravity=0] Float optional

    The world gravity on x axis. Default: 0 .

  • [yGravity=9.8] Float optional

    The world gravity on y axis. Default: 9.8 .

  • [doSleep] Boolean optional

    Improve performance by not simulating inactive bodies.

  • [enableCollisions] Boolean optional

    Enable collision between bodies.

Example:

var app = new Moscrif.Window(); app.terminate = false; app.onStart = function() { // create world this._world = new b2World(0.0, -9.8);

   // load image, which should be drawen into the body
   var bodyImg = Bitmap.fromFile("app://img.png");
   // create shape of body
   var shape = b2PolygonShape.fromRect(bodyImg.width, bodyImg.height);

   // create body
   var body = this._world.createBody(shape, #dynamic, 1, 1, 1, 50, 20);
   // draw body
   body.onDraw = function(sender, canvas)
   {
       var (l, t) = this.getPosition();
       canvas.drawBitmap(bodyImg, l.toInteger(), t.toInteger());
   }

}

app.onProcess = function(sender) { // recalculate world this._world.step(1.0/40.0, 4, 8); // redraw window this.invalidate(); return this.terminate ? 0 : 1; }

app.onDraw = function(sender, canvas) { // clear body canvas.clear(0xff000000); // draw b2 world this._world.doDraw(canvas); }

app.init().run();

clearForces

()

Manually clear the force buffer on all bodies. By default, forces are cleared automatically after each call to Step.

createBody

(
  • b2CircleShape
  • bodyTypeSym
  • [density=1]
  • [friction=0.3]
  • [bounce=0.2]
  • [x=0.0]
  • [y=0.0]
)
B2Body

Create new box2d body and place it to the x, y.

Parameters:

  • b2CircleShape B2CircleShape

    Shape of new object.

  • bodyTypeSym Symbol

    BodyType's parameter .

    • #static - A static body has does not move under simulation and behaves as if it has infinite mass. Internally, Box2D stores zero for the mass and the inverse mass. Static bodies can be moved manually by the user. A static body has zero velocity. Static bodies do not collide with other static or kinematic bodies.
    • #dynamic - A dynamic body is fully simulated. They can be moved manually by the user, but normally they move according to forces. A dynamic body can collide with all body types. A dynamic body always has finite, non-zero mass. If you try to set the mass of a dynamic body to zero, it will automatically acquire a mass of one kilogram.
    • #kinematic - A kinematic body moves under simulation according to its velocity. Kinematic bodies do not respond to forces. They can be moved manually by the user, but normally a kinematic body is moved by setting its velocity. A kinematic body behaves as if it has infinite mass, however, Box2D stores zero for the mass and the inverse mass. Kinematic bodies do not collide with other static or kinematic bodies.
  • [density=1] Float optional

    Density 0 to 1.

  • [friction=0.3] Float optional

    Friction 0 to 1.

  • [bounce=0.2] Float optional

    Bounce 0 to 1.

  • [x=0.0] Integer optional

    Position of object on x axis.

  • [y=0.0] Integer optional

    Position of object on y axis.

Returns:

B2Body: New instance of physics body interacting in the world.

createDistanceJoint

(
  • bodyA
  • bodyB
  • anchorXA
  • anchorYA
  • anchorXB
  • anchorYB
  • scriptDef
  • [collideConnected]
)
B2DistanceJoint

Create distance joint between two objects. Distance joints says that the distance between two points on two bodies must be constant.

Parameters:

  • bodyA B2Body

    First body.

  • bodyB B2Body

    Second body.

  • anchorXA Float

    X position of anchor point on the first body. Anchor point is point on the body, which is conected with the second body.

  • anchorYA Float

    Y position of anchor point on the first body. Anchor point is point on the body, which is conected with the second body.

  • anchorXB Float

    X position of anchor point on the second body. Anchor point is point on the body, which is conected with the first body.

  • anchorYB Float

    Y position of anchor point on the second body. Anchor point is point on the body, which is conected with the first body.

  • scriptDef Array

    Other joints properties:

    • distanceLength - Default length between bodies (between anchor points).
    • frequencyHz - The mass-spring-damper frequency in Hertz. A value of 0 disables softness.
    • dampingRatio - The damping ratio from 0 to 1.
  • [collideConnected] Boolean optional

    If this param is true colisions between connected bodies are allowed, otherwise their are denied. Bytes default this param is set top false.

Returns:

B2DistanceJoint: New distance joint.

Example:

this.bodyA = this.world.createBody(shape, #dynamic, 1, 1, 1, 50, 20);
this.bodyB = this.world.createBody(shape, #dynamic, 1, 1, 1, 50, 20);

var def =
{
    dampingRatio: 0.5; //from 0 to 1
};
var (xa, ya) = this.bodyA.getWorldCenter();
var (xb, yb) = this.bodyB.getWorldCenter();

this.joint = this.world.createDistanceJoint(this.bodyA, this.bodyB, xa, ya, xb, yb, def);

createFrictionJoint

(
  • bodyA
  • bodyB
  • anchorX
  • anchorY
  • scriptDef
  • [collideConnected]
)
B2FrictionJoint

The friction joint is used for top-down friction. The joint provides 2D translational friction and angular friction.

Parameters:

  • bodyA B2Body

    First body.

  • bodyB B2Body

    Second body.

  • anchorX Float

    X position of anchor point.

  • anchorY Float

    Y position of anchor point.

  • scriptDef Array

    Other joints properties:

    • maxForce - The maximum friction force in N.
    • maxTorque - The maximum friction torque in N-m.
  • [collideConnected] Boolean optional

    If this param is true colisions between connected bodies are allowed, otherwise their are denied. Bytes default this param is set top false.

Returns:

B2FrictionJoint: New friction joint.

createGearJoint

(
  • bodyA
  • bodyB
  • jojnt1
  • jojnt2
  • ratio
  • [collideConnected]
)
B2GearJoint

If you want to create a sophisticated mechanical contraption you might want to use gears. Gear joint connects two other types of joints and move them with set ratio.

Parameters:

  • bodyA B2Body

    First body.

  • bodyB B2Body

    Second body.

  • jojnt1 Float

    First joint.

  • jojnt2 Float

    Second joint.

  • ratio Float

    Ratio between both joints.

  • [collideConnected] Boolean optional

    If this param is true colisions between connected bodies are allowed, otherwise their are denied. Bytes default this param is set top false.

Returns:

B2GearJoint: New friction joint.

createLineJoint

(
  • bodyA
  • bodyB
  • anchorX
  • anchorY
  • axisX
  • axisY
  • referenceAngle
  • scriptDef
  • [collideConnected]
)
B2LineJoint

This joint provides two degrees of freedom: translation along an axis fixed in body1 and rotation in the plane. You can use a joint limit to restrict the range of motion and a joint motor to drive the motion or to model joint friction.

Parameters:

  • bodyA B2Body

    First body.

  • bodyB B2Body

    Second body.

  • anchorX Float

    X position of anchor point. Anchor point is point on the body, which is conected with the second body.

  • anchorY Float

    Y position of anchor point. Anchor point is point on the body, which is conected with the second body.

  • axisX Float

    X coordinate of axis.

  • axisY Float

    Y coordinate of axis.

  • referenceAngle Float

    ReferenceAngle angle

  • scriptDef Array

    Other joints properties:

    • lowerTranslation - The lower translation limit, usually in meters.
    • upperTranslation - The upper translation limit, usually in meters.
    • enableLimit - Enable/disable the joint limit.
    • maxMotorForce - The maximum motor torque, usually in N-m.
    • motorSpeed - The desired motor speed in radians per second.
    • enableMotor - Enable/disable the joint motor.
  • [collideConnected] Boolean optional

    If this param is true colisions between connected bodies are allowed, otherwise their are denied. Bytes default this param is set top false.

Returns:

B2LineJoint: New line joint.

createMouseJoint

(
  • bodyA
  • bodyB
  • scriptDef
  • [collideConnected]
)
B2MouseJoint

A mouse joint is used to make a point on a body track a specified world point. This a soft constraint with a maximum force. This allows the constraint to stretch and without applying huge forces.

Parameters:

  • bodyA B2Body

    First body.

  • bodyB B2Body

    Second body.

  • scriptDef Array

    Other joints properties:

    • maxForce - The maximum constraint force that can be exerted to move the candidate body. Usually you will express as some multiple of the weight (multiplier * mass * gravity).
    • frequencyHz - The response speed.
    • dampingRatio - The damping ratio. 0 = no damping, 1 = critical damping.
    • targetX - X coordinate of initial world target point. This is assumed to coincide with the body anchor initially.
    • targetY - Y coordinate of initial world target point. This is assumed to coincide with the body anchor initially.
  • [collideConnected] Boolean optional

    If this param is true colisions between connected bodies are allowed, otherwise their are denied. Bytes default this param is set top false.

Returns:

B2MouseJoint: New mouse joint.

Example:

var b2x = x / this._world.scale;
var b2y = (System.height-y) / this._world.scale;
var mouseJointDef = {
                maxForce : 2500,
                frequencyHz : 10000,
                dampingRatio : 0.0,
                targetX : b2x,
                targetY : b2y
            };

// crate mouse joint
this._mouseJoint = this._world.createMouseJoint(this._ground, body, mouseJointDef, true);

createPrismaticJoint

(
  • bodyA
  • bodyB
  • anchorX
  • anchorY
  • axisX
  • axisY
  • referenceAngle
  • scriptDef
  • [collideConnected]
)
B2PrismaticJoint

A prismatic joint allows for relative translation of two bodies along a specified axis. A prismatic joint prevents relative rotation. Therefore, a prismatic joint has a single degree of freedom.

Parameters:

  • bodyA B2Body

    First body.

  • bodyB B2Body

    Second body.

  • anchorX Float

    X position of anchor point. Anchor point is point on the body, which is conected with the second body.

  • anchorY Float

    Y position of anchor point. Anchor point is point on the body, which is conected with the second body.

  • axisX Float

    X coordinate of axis.

  • axisY Float

    Y coordinate of axis.

  • referenceAngle Float

    ReferenceAngle angle

  • scriptDef Array

    Other joints properties:

    • lowerTranslation - The lower translation limit, usually in meters.
    • upperTranslation - The upper translation limit, usually in meters.
    • enableLimit - Enable/disable the joint limit.
    • maxMotorForce - The maximum motor torque, usually in N-m.
    • motorSpeed - The desired motor speed in radians per second.
    • enableMotor - Enable/disable the joint motor.
  • [collideConnected] Boolean optional

    If this param is true colisions between connected bodies are allowed, otherwise their are denied. Bytes default this param is set top false.

Returns:

B2PrismaticJoint: New prismatic joint.

createPulleyJoint

(
  • bodyA
  • bodyB
  • groundAnchorAX
  • groundAnchorAY
  • groundAnchorBX
  • groundAnchorBY
  • anchorAX
  • anchorAY
  • anchorBX
  • anchorBY
  • ratio
  • [collideConnected]
)
B2PulleyJoint

The pulley joint is connected to two bodies and two fixed ground points. The pulley supports a ratio such that: length1 + ratio * length2 <= constant Yes, the force transmitted is scaled by the ratio.

Warning: the pulley joint can get a bit squirrelly by itself. They often work better when combined with prismatic joints. You should also cover the the anchor points with static shapes to prevent one side from going to zero length.

Parameters:

  • bodyA B2Body

    First body.

  • bodyB B2Body

    Second body.

  • groundAnchorAX Float

    X coordinatesof of the first ground anchor.

  • groundAnchorAY Float

    Y coordinatesof of the first ground anchor.

  • groundAnchorBX Float

    X coordinatesof of the second ground anchor.

  • groundAnchorBY Float

    Y coordinatesof of the second ground anchor.

  • anchorAX Float

    X world coordinate of the anchor point on bodyA.

  • anchorAY Float

    Y world coordinate of the anchor point on bodyA.

  • anchorBX Float

    X world coordinate of the anchor point on bodyB.

  • anchorBY Float

    Y world coordinate of the anchor point on bodyB.

  • ratio Float

    The pulley ratio.

  • [collideConnected] Boolean optional

    If this param is true colisions between connected bodies are allowed, otherwise their are denied. Bytes default this param is set top false.

Returns:

B2PulleyJoint: New pulley joint.

createRevoluteJoint

(
  • bodyA
  • bodyB
  • anchorX
  • anchorY
  • scriptDef
  • [collideConnected]
)
B2RevoluteJoint

A revolute joint forces two bodies to share a common anchor point, often called a hinge point. The revolute joint has a single degree of freedom: the relative rotation of the two bodies. This is called the joint angle.

Parameters:

  • bodyA B2Body

    First body.

  • bodyB B2Body

    Second body.

  • anchorX Float

    X position of anchor point. Anchor point is point around which bodies are rotated.

  • anchorY Float

    Y position of anchor point. Anchor point is point around which bodies are rotated.

  • scriptDef Array

    Other joints properties (A joint limit forces the joint angle to remain between a lower and upper bound. The limit range should include zero, otherwise the joint will lurch when the simulation begins. Angle is positive when rotates CCW.)

    • lowerAngle - The lower angle for the joint limit (radians).
    • upperAngle - The upper angle for the joint limit (radians).
    • enableLimit - True/false to enable joint limits.
    • maxMotorTorque - The maximum motor torque used to achieve the desired motor speed. Usually in N-m.
    • motorSpeed - The desired motor speed. Usually in radians per second.
    • enableMotor - True / false to enable the joint motor.
  • [collideConnected] Boolean optional

    If this param is true colisions between connected bodies are allowed, otherwise their are denied. Bytes default this param is set top false.

Returns:

B2RevoluteJoint: New revolute joint.

Example:

//properties like: enableLimit, lowerAngle, enableMotor etc.
var def =
{
    enableLimit: true;
    ...
};

var joint = this.world.createRevoluteJoint(bodyA, bodyB, x, y, def);

destroyBody

(
  • body
)

Destroy existing physics body. WARNING: The bodies should not be removed in PhysicsScene/onBeginContact and PhysicsScene/onEndContact. Probably the better way is to remove it in Game/onProcess event.

Parameters:

  • body B2Body

    Body to destroy.

Example:

this.body = this.world.createBody(shape, #dynamic, 1, 1, 1, 50, 20);
....
// destroy body
this.world.destroyBody(this.body);

destroyJoint

(
  • joint
)

Destroy a joint. WARNING: The joints should not be removed in PhysicsScene/onBeginContact and PhysicsScene/onEndContact. Probably the better way is to remove it in Game/onProcess event.

Parameters:

  • joint B2Joint

    Joint to destroy.

Example:

this.joint = this.world.createDistanceJoint(body, bodyB, xa, ya, xb, yb, def);
...
// destroy joint before closing the application
this.world.destroyJoint(this.joint);

doDebugDraw

(
  • canvas
)

Call this to draw shapes and other debug draw data.

Parameters:

  • canvas Integer

    Instance of canvas class into which world should be drawn.

Example:

var app = new Moscrif.Window();
app.terminate = false;

....onStart = function()
{
    // create world
    this._world = new b2World();

}

....onDraw = function(sender, canvas)
{
    // clear body
    canvas.clear(0xff000000);
    // draw b2 world
    this._world.doDebugDraw(canvas);
}

app.init().run();

doDraw

(
  • canvas
)

Call this to redraw all objects in the world.

Parameters:

  • canvas Integer

    Instance of canvas class into which world should be drawn.

Example:

var app = new Moscrif.Window();
app.terminate = false;

....onStart = function()
{
    // create world
    this._world = new b2World();

}

....onDraw = function(sender, canvas)
{
    // clear body
    canvas.clear(0xff000000);
    // draw b2 world
    this._world.doDraw(canvas);
}

app.init().run();

getBodyCount

() Integer

Get the number of bodies.

Returns:

Integer: Number of bodies.

Example:

// create world
this._world = new b2World();
// change gravity additionaly

var shape = b2PolygonShape.fromRect(50, 20);
// create body
var bodies = new Array();
var bodyCount = 4;
for (var i = 0; i &lt; bodyCount; i++) {
        bodies[i] = this._world.createBody(shape, #dynamic, 1, 1, 1, 50, 20);
        // draw body
        bodies[i].onDraw = function(sender, canvas)
        {
            ...
        }
    }
//  body count: 4
console<<"body count: "<<this._world.getBodyCount()<<"\n";

getContactCount

() Integer

Get the number of contacts (each may have 0 or more contact points).

Returns:

Integer: Number of contacts.

Example:

if (this.world.getContactCount () > 0)
    console<<"two or more bodies colide together\n";
else
    console<<"no colisions in world\n";

getGravity

() Multivalue

Get the global gravity.

Returns:

Multivalue: Pair of float values. First is gravity one x axis and second one y axis.

Example:

this.world = new b2World();
// get world's gravity (default gravity)
var (gx, gy) = this.world.getGravity();
// gx is now 0.0 and gy 9.8

getJointCount

() Integer

Get the number of joints.

Returns:

Integer: Number of joints

getProxyCount

() Integer

Get the number of broad-phase proxies.

Returns:

Integer: Number of broad-phase proxies.

setContinuousPhysics

(
  • flag
)

Enable/disable continuous physics. For testing. Continuous collision detection (also called CCD), is a box2d feature which ensures correct simulation of fast moving objects. Some older physical engines do not supports CCD, what means that they calculate positions and colisions of bodies for every time step, what is called discrete simulation. However in discrete simulation rigid body can move long distance in time step. (If the body has sufficiently high speed, it can be before time step few meters in front of the barrier and after time step it can be few meters behind the barrier.) It caused that the fast moving body can move throw another body without detection of collision between these two bodies. This effect is called tunneling. By default box2d uses CCD to prevent tunneling effect. CCD looks for all collisions between the position before and after time step. For every collision it calculates time of impact (TOI). On the next time step the body moves only to the next TOI and then wait for the rest of time step and does not move anymore during the time step. To ensure the best performace the CCD calculates contacts only between dynamic and static bodies (not between the dynamic bodies each other). However, onto dynamic bodies can be set CCD separately. If there is fast moving body, which hit other dynamic bodies, you can set the fast moving body’s property bullet to true to allows CCD onto it.

Parameters:

  • flag Boolean

    True / false to enable / disable.

setGravity

(
  • gx
  • gy
)

Set world’s gravity (separately for x and y axis).

Parameters:

  • gx Float

    Gravity on x axis.

  • gy Float

    Gravity on y axis.

Example:

// create world
this._world = new b2World();
// change gravity additionally
this._world.setGravity(0.0, 9.8);

setWarmStarting

(
  • flag
)

Enable/disable warm starting. If the warm starting is enabled some box2d solvers uses resoul from previous time step, what improves performance.

Parameters:

  • flag Boolean

    True / false to enable / disable.

step

(
  • [timeStep]
  • [velocityIterations]
  • [positionIterations]
)

Take a time step. This performs collision detection, integration, and constraint solution.

Parameters:

  • [timeStep] Float optional

    The amount of time to simulate. When this function is called from onProcess event in Moscrif, the value is usually 1.0/40.0 .

  • [velocityIterations] Integer optional

    For the velocity constraint solver.

  • [positionIterations] Integer optional

    For the position constraint solver.

Example:

....
....onStart = function()
{
    // create world
    this._world = new b2World(0.0, -9.8);

...
   // create body
    var body = this._world.createBody(shape, #dynamic, 1, 1, 1, 50, 20);
....
  }

....onProcess = function(sender)
{
    // recalculate world
    this._world.step(1.0/40.0, 4, 8);

    // redraw window
    this.invalidate();
    return this.terminate ? 0 : 1;
}

Properties

autoClearForces

Boolean

Flag to control automatic clearing of forces after each time step. By default it is set to true.

scale

Float

Value represent scale of box2d world against screen resolution. The width of the physics world is always 10 meters. I means that on different displays the world is scaled diferently. The scale property says how meny pixels on the screens represents one meter in physical simulation. It helps to convert screen coordinates to box2d coordinates, which also do not start from the left top corner as a screen pixels coordinates, but from the left bottom corner of the screen.

Example:

// converts x-coord from screen to box2d
function x2box2d(x)
{
    return x / this._world.scale;
}

// converts y-coord from screen to box2d
function y2box2d(y)
{
    return (System.height - y) / this._world.scale;
}

Events

onBeginContact

This function is called, when two bodies collide.

Event Payload:

  • sender B2World

    Object, which called this function.

  • contact B2Contact

    Instance of b2Contact contains all informations about contact.

Example:

this.world.onBeginContact = function(sender, contact)
{
    // manage contact
    var bodyA = current.getBodyA();
    var bodyB = current.getBodyB();
    ...
};

onEndContact

This function is called, when contact ends.

Event Payload:

  • sender B2World

    Object, which called this function.

  • contact B2Contact

    Instance of b2Contact contains all informations about contact.

Example:

this.world.onEndContact = function(sender, contact)
{
    // manage contact
    var bodyA = current.getBodyA();
    var bodyB = current.getBodyB();
    ...
};