Moscrif API Docs for: 2012q3
Show:

PhysicsScene Class

include "lib://box2d/physicsScene.ms";
Library: box2d

This class manages creates background for all physical entities like physical sprites, joints or contacts. It also sets basic hysical properties properties like gravity and provides time steps in simulation. The class contains an instance of native b2World class, which provides all calculations on background.

Example:

// create instance of physics scene (create method aoutomatically create an instance of b2World class)
var scene = PhysicsScene.create(0.0, -0.5);

// OR

// create an instance of b2World class manually in init function of extended class
class GameScene : PhysicsScene
{
    function init()
    {
        super.init();

        // create physics world
        this.world = new b2World(0.0, -9.8, true, false);
        ...
    }
    ...
}
// then instance of GameScene can be creates simply by key word new
var scene = new GameScene();

Methods

addCircleBody

(
  • image
  • bodyTypeSym
  • density
  • friction
  • bounce
  • radius
)

Add circle physics sprite.

Parameters:

  • image Bitmap
  • bodyTypeSym Symbol
    #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 Float

    Density of the sprite.

  • friction Float

    Friction of the sprite, affects the body adhesion.

  • bounce Float

    The bounce value is usually set to be between 0 and 1. Consider dropping a ball on a table. A value of zero means the ball won't bounce. This is called an inelastic collision. A value of one means the ball's velocity will be exactly reflected. This is called a perfectly elastic collision. If collide two bodies with different bounce the box2d uses larger value to simulate the bounce.

  • radius Float

    Radius of circle body. The radius should be same as a radious of an image, because the image drawen in the body is not limited by the sprites's shape.

Returns:

PhysicsSprite

Example:

var puck = this.addCircleBody(res.images.puck, #dynamic, density, friction, bounce,  res.images.puck.width / 2);
// place puck to center of the table
puck.setPosition(System.width / 2, System.height / 2);

addEdgeBody

(
  • image
  • bodyTypeSym
  • density
  • friction
  • bounce
  • v1x
  • v1y
  • v2x
  • v2y
)

Add edge physics sprite into scene. Edge shapes are line segments. These are provided to assist in making a free-form static environment. Edge shapes can collide with circles and polygons bodies but not with themselves. Edge bodies have no volume.

Parameters:

  • image Bitmap

    Image drawn in the body

  • bodyTypeSym Symbol
    #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 Float

    Density of the sprite.

  • friction Float

    Friction of the sprite, affects the body adhesion.

  • bounce Float

    The bounce value is usually set to be between 0 and 1. Consider dropping a ball on a table. A value of zero means the ball won't bounce. This is called an inelastic collision. A value of one means the ball's velocity will be exactly reflected. This is called a perfectly elastic collision. If collide two bodies with different bounce the box2d uses larger value to simulate the bounce.

  • v1x Float

    X coordinate of the first point of the body. The coordinate are in pixels, from the centre of the shape. The positive values are in right and top directions.

  • v1y Float

    Y coordinate of the first point of the body. The coordinate are in pixels, from the centre of the shape. The positive values are in right and top directions.

  • v2x Float

    X coordinate of the second point of the body. The coordinate are in pixels, from the centre of the shape. The positive values are in right and top directions.

  • v2y Float

    Y coordinate of the second point of the body. The coordinate are in pixels, from the centre of the shape. The positive values are in right and top directions.

Returns:

PhysicsSprite

Example:

var ground = Bitmap.fromFile("app://ground.png");
var sprite = this.addEdgeBody(ground, #static, 0.0, 0.0, 0.0, ground.width / -2, 1, ground.width / 2, 10)
sprite.setPosition(System.width / 2, System.height/2);

addPolygonBody

(
  • image
  • bodyTypeSym
  • density
  • friction
  • bounce
  • width/array
  • height
)

Add polygon physics sprite into scene.

Parameters:

  • image Bitmap

    Image drawn in the body

  • bodyTypeSym Symbol
    #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 Float

    Density of the sprite.

  • friction Float

    Friction of the sprite, affects the body adhesion.

  • bounce Float

    The bounce value is usually set to be between 0 and 1. Consider dropping a ball on a table. A value of zero means the ball won't bounce. This is called an inelastic collision. A value of one means the ball's velocity will be exactly reflected. This is called a perfectly elastic collision. If collide two bodies with different bounce the box2d uses larger value to simulate the bounce.

  • width/array Integer/Array

    Width of polygon body in pixels or array of vectors. If the value is integer typical rectangle body is created. If it is an array a polygon body is created and last parameter is ignored. The array should contains objects with two values: x and y -> distance from center in pixels (positive values are located up and right). Points in array should by in CCW order. Minimum number of vertex are 3 maximum (ussally) 8.

  • height Integer

    Height of polygon body in pixels. The sprite height should be same as a height of image, otherwise the image will be drawen outside (or innear) real body shape. The image is not limited by sprite width or height.

Returns:

PhysicsSprite

Example:

// create rectangle body
var ramp = Bitmap.fromFile("app://ramp.png");
var body = this.addPolygonBody(ramp, #static, 1.0, 1.0, 0.0, ramp.width, ramp.height);
body.setPosition(System.width / 2, System.height);
// create triangle body
var shape = new Array(
    // top - left
    {x : width /-2, y : height / 2},
    // bottom - left
    {x : width /-2, y : height / -2},
    // bottom - right
    {x : width /2, y : height / -2}
)
// create triangle body
var body = this._world.addPolygonBody(imgBox, #dynamic, 0.9 , 0.0, 0.0, shape);

beginContact

(
  • PhysicsContact
)
protected

beginContact function is called as a reaction on the onBeginContact event. This event is called when two bodies collide.

Parameters:

  • PhysicsContact Object

    List of all contacts which appeared in last time step.

Example:

function beginContact(contact)
{
    // get the first contact
    var current = contact;
    while (current) {
        // get the bodies in the contact
        var bodyA = current.getBodyA();
        var bodyB = current.getBodyB();
        ...
        // get the next contact (they can be more contacts during the one step)
        current = current.getNext();
    }
}

clearForces

()

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

create

(
  • gx
  • gy
  • options
)

Create an instance of box2d body. Using the create function ensures that native b2World object will be automatically created and it is not needed to create it manually in init method.

Parameters:

  • gx Float

    component of the world gravity vector on the x-axis

  • gy Float

    component of the world gravity vector on the y-axis

  • options Object
    sleep Boolean  If the sleeping is allowed inactive bodies are not simulated, what improves performance. Default is sleeping disabled.
    enableCollisions Boolean  Enable collisions between bodies. By defeault they are allowed.
    calledClass Class The called class, default is PhysicsScene.
    

Example:

// create instance of physics scene (create method aoutomatically create an instance of b2World class)
var scene = PhysicsScene.create(0.0, -0.5, { calledClass: GameScene } );

createDistanceJoint

(
  • bodyA
  • bodyB
  • anchorAx
  • anchorAy
  • Float
  • anchorBy
  • jointDef
  • collideConnected
)

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

Parameters:

  • bodyA PhysicsBody

    first connected body

  • bodyB PhysicsBody

    second connected body

  • anchorAx Float
     X position of anchor point on the first body. Anchor point is point on the body, which is conected with the second body.
    
  • anchorAy Float
    Y position of anchor point on the first body. Anchor point is point on the body, which is conected with the second body.
    
  • Float Object

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

  • anchorBy Float
     Y position of anchor point on the second body. Anchor point is point on the body, which is conected with the first body.
    
  • jointDef Object
     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
    If this param is true colisions between connected bodies are allowed, otherwise their are denied.
    By default is set to false.
    

Returns:

b2DistanceJoint

Example:

// create the distance joint
var jointDef = {
    frequencyHz     : 100,
    dampingRatio    : 0.0,
   // distanceLength  : use default distance (distance which was between the bodies when they were created
}
this._distanceJoint = this.createDistanceJoint(this._rect1, this._rect2, System.width / 2,System.height / 2,System.width / 2,3*System.height / 4, jointDef, false)

createFrictionJoint

(
  • bodyA
  • bpdyB
  • x
  • y
  • jointDef
  • collideConnected
)

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

Parameters:

  • bodyA PhysicsBody

    first connected body

  • bpdyB PhysicsBody

    second connected body

  • x Float
     X position of anchor point.
    
  • y Float
     Y position of anchor point.
    
  • jointDef Object
     Other joints properties:
        maxForce  - The maximum friction force in N.
        maxTorque - The maximum friction torque in N-m.
    
  • collideConnected Boolean
    If this param is true colisions between connected bodies are allowed, otherwise their are denied.
    By default is set to false.
    

Returns:

b2FrictionJoint

createGearJoint

(
  • bodyA
  • bodyB
  • joint1
  • joint2
  • ratio
  • collideConnected
)

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 PhysicsBody

    first connected body

  • bodyB PhysicsBody

    second connected body

  • joint1 B2Joint

    First connected joint

  • joint2 B2Joint

    Second connected joint

  • ratio Object

    {Float] Ratio between the joints motion. Ratio 1.0 means that both joint move same distance (speed).

  • collideConnected Boolean
    If this param is true colisions between connected bodies are allowed, otherwise their are denied.
    By default is set to false.
    

Returns:

b2GearJoint

Example:

// create the prismatic joint
// set limits
var jointDef = {
    ...
}
var prismaticJoint = this.createPrismaticJoint(this._leftWall, this._rect2, System.width / 2, System.height / 5, 0.0, 1.0, 0.0, jointDef, true)

// create the revolute joint
jointDef = {
   ...
}
// create joint
var revoluteJoint = this.createRevoluteJoint(this._ground, this._rect1, System.width / 2, System.height / 5, jointDef, true);

// connect bodies with gear joint
this._gearJoint = this.createGearJoint(this._rect1, this._rect2, prismaticJoint, revoluteJoint, 0.8, true);

createLineJoint

(
  • bodyA
  • bodyB
  • anchorX
  • anchorY
  • axisX
  • axisY
  • referenceAngle
  • jointDef
  • collideConnected
)

This joint provides two degrees of freedom: translation along an axis fixed in body1 and rotation in the plane.

Parameters:

  • bodyA PhysicsBody

    first connected body

  • bodyB PhysicsBody

    second connected 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

    reference Angle

  • jointDef Object
        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
        If this param is true colisions between connected bodies are allowed, otherwise their are denied.
        By default is set to false.
    

Returns:

b2LineJoint

createMouseJoint

(
  • PhysicsBody
  • PhysicsBody
  • Array
  • Boolean
)
B2MouseJoint

A mouse joint is used to make a point on a body track a specified world point. It is usually used to track user finger on the screen.

Parameters:

  • PhysicsBody Object

    First body in joint, also called as a ground body. This body is is not important it can be also body with zero width and height placed anywhere in the scene.

  • PhysicsBody Object

    Body, which chould track a pointer

  • Array Object

    jointDef 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.

  • Boolean Object

    collideConnected If this param is true colisions between connected bodies are allowed, otherwise their are denied. By default is set to false.

Returns:

B2MouseJoint:

Example:

// mouse joint definition
var mouseJointDef = {
    maxForce : 10000,
    frequencyHz : 1000,
    dampingRatio : 0.0,
    targetX : table.x2box2d(x), // specified in box2d coords
    targetY : table.y2box2d(y)  // specified in box2d coords
};
this.joint = table.createMouseJoint(table.ground, this.paddle, mouseJointDef, true);

createPrismaticJoint

(
  • bodyA
  • bodyB
  • anchorX
  • anchorY
  • axisX
  • axisY
  • referenceAngle
  • jointDef
  • collideConnected
)

A prismatic joint allows for relative translation of two bodies along a specified axis.

Parameters:

  • bodyA PhysicsBody

    first connected body

  • bodyB PhysicsBody

    second connected 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

    reference Angle

  • jointDef Object
    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
    If this param is true colisions between connected bodies are allowed, otherwise their are denied.
    By default is set to false.
    

Returns:

b2PrismaticJoint

Example:

// create the prismatic joint
// set joint
var jointDef = {
    lowerTranslation    : -3.0, // meters
    upperTranslation    : 5.0,  // meters
    enableLimit         : true,
    enableMotor         : true,
    motorSpeed          : 1.0,
    maxMotorForce       : 100.0,
}
this._prismaticJoint = this.createPrismaticJoint(this._ground, this._rect1, System.width / 2, System.height / 2, 0.0, 1.0, 0.0, jointDef, true)

createPulleyJoint

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

The pulley joint is connection of two bodies and two fixed ground points. It looks like the body are connected with a rope, which comes throw the specified fixed ground points.

Parameters:

  • bodyA PhysicsBody

    first connected body

  • bodyB PhysicsBody

    second connected 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
    If this param is true colisions between connected bodies are allowed, otherwise their are denied.
    By default is set to false.
    

Returns:

b2PulleyJoint

Example:

// create the pulley joint
this._pulleyJoint = this.createPulleyJoint(this._rect1, this._rect2, System.width / 4, System.height / 8, 3 * System.width / 4, System.height / 8, System.width / 4, System.height / 2, 3 * System.width / 4, System.height / 2, 1.0 , true)

createRevoluteJoint

(
  • bodyA
  • bodyB
  • x
  • y
  • jointDef
  • collideConnected
)

The revolute joint can be thought of as a hinge, a pin, or an axle. Revolute joints can be given limits so that the bodies can rotate only to a certain point.

Parameters:

  • bodyA PhysicsSprite

    first body in the joint

  • bodyB PhysicsSprite

    second body in the joint

  • x Float
    X position of anchor point. Anchor point is point around which bodies are rotated.
    
  • y Float
    Y position of anchor point. Anchor point is point around which bodies are rotated.
    
  • jointDef Object

    {Object] 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 in radians per second. enableMotor- True / false to enable the joint motor

  • collideConnected Boolean
    If this param is true colisions between connected bodies are allowed, otherwise their are denied.
    By default is set to false.
    

Returns:

b2RevoluteJoint

Example:

// joint's options
var jointSet = {
    enableMotor : true,             // enable motor
    motorSpeed  : (- 2 * Math.PI / 3) * (800.0 / System.width), // final speed is linearly depends on radius (screen resolution)
    maxMotorTorque : 2100000000,    // maximum torque

}
// create joint
var joint = this.createRevoluteJoint(obj.bodyA, obj.bodyB, x, y, jointSet, true);

createWeldJoint

(
  • bodyA
  • bodyB
  • anchorX
  • anchorY
  • collideConnected
)

A weld joint essentially glues two bodies together. It may distort somewhat because the island constraint solver is approximate.

Parameters:

  • bodyA PhysicsBody

    first connected body

  • bodyB PhysicsBody

    second connected body

  • anchorX Float
    X position of anchor point.
    
  • anchorY Float
    Y position of anchor point.
    
  • collideConnected Boolean
    If this param is true colisions between connected bodies are allowed, otherwise their are denied.
    By default is set to false.
    

Returns:

b2WeldJoint

Example:

// create the weld joint
this._weldJoint = this.createWeldJoint(this._rect1, this._rect2, System.width / 2,System.height / 2, true)

destroyBody

(
  • body
)

Destroy body and remove it from bodies array. CAUTION: bodies should not be removed in the call back functions (onBeginContact or onEndContact). The better way is push all sprites to remove to an array and then remove it in onProcess event.

Parameters:

  • body PhysicsBody

Example:

function process()
{
    // remove sprites from the scene
    for (var i in this._bodiesToDestory)
        this.destroyBody(i);
}

destroyJoint

(
  • joint
)

Destroy existing joint. CAUTION: Joints should not be removed in the call back functions (like onBeginContact or onEndContact). The better way is push all joints to remove to an array and then remove it in onProcess event.

Parameters:

  • joint B2Joint

    Joint to destroy

Example:

function process()
{
    // remove joints from the scene
    for (var i in this._jointsToDestory)
        this.destroyJoint(i);
}

doDebugDraw

(
  • Canvas
)

Draw physics scene, in debug mode

Parameters:

  • Canvas Object

    canvas

draw

(
  • canvas
)

Draw physics scene. This function draws all sprites included in the scene. The function is called automatically as a reaction onto onDraw event. To customize scene appearance can be this function extended, but it can is neede to call also parent's draw method to ensure correct drawing of all objects in the scene.

Parameters:

  • canvas Canvas

    Current scene canvas

Example:

function draw(canvas)
{
    // draw background
    canvas.drawRect(0, 0, System.width, System.height, this._bg);
    // draw all other elements in the scene
    super.draw(canvas);
}

endContact

(
  • PhysicsContact
)
protected

endContact function is called as a reaction on the onEndContact event. This event is called when contact ends.

Parameters:

  • PhysicsContact Object

    List of all contacts which appeared in last time step.

Example:

function endContact(contact)
{
    // get the first contact
    var current = contact;
    while (current) {
        // get the bodies in the contact
        var bodyA = current.getBodyA();
        var bodyB = current.getBodyB();
        ...
        // get the next contact (they can be more contacts during the one step)
        current = current.getNext();
    }
}

getBody

(
  • body
)
PhysicsSprite

Get body from bodies array.

Parameters:

  • body B2Body

Returns:

PhysicsSprite: Object instance or null

getBodyCount

() Integer

Get the number of bodies in the scene.

Returns:

Integer: number of bodies

getContactCount

() Integer

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

Returns:

Integer: number of contacts

getGravity

() Multivalue

Get the global gravity. The gravity affects all dynamic bodies (sprites) in the scene.

Returns:

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

Example:

var (gx, gy) = scene.getGravity();

getJointCount

() Integer

Get the number of joints in the scene.

Returns:

Integer: number of joints

getProxyCount

() Integer

Get the number of broad-phase proxies.

Returns:

Integer: number of proxy

init

()

Initialize basic properties, like debugDraw

setContinuousPhysics

(
  • Boolean
)

Enable/disable continuous physics. 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:

  • Boolean Object

    flag

setGravity

(
  • gx
  • gy
)

Set the global gravity. The gravity affects all dynamic bodies (sprites) in the scene.

Parameters:

  • gx Float

    Gravity on x-axis

  • gy Float

    Gravity on y-axis

Example:

scene.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

    Ture / false to enable / disable warm starting

step

(
  • [timeStep=1.0/40.0]
  • [velocityIterations=4]
  • [positionIterations=8]
)

Take a time step. This performs collision detection, integration, and constraint solution. This functin is usually called from process method every about 25 miliseconds.

Parameters:

  • [timeStep=1.0/40.0] Float optional

    The amount of time to simulate.

  • [velocityIterations=4] Integer optional

    For the velocity constraint solver.

  • [positionIterations=8] Integer optional

    For the position constraint solver.

Example:

function process()
{
    // call parents process method
    super.process();

    // do physics math
    this.step(1.0 / 40.0, 4, 8);
    // redraw window
    game.invalidate();
}

Properties

autoClearForces

Boolean

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

debugDraw

Boolean

Allow do draw box2d debug data, like real bodies borders.

native

B2World

An instance of native b2World class used in physics scene for physical simulation. The value of this property is same as a value of PhysicsScene/world. This property is get only. To set the native world use PhysicsScene/world.

scale

Float

The width of the ohysics 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;
}

world

B2World

An instance of native b2World class used in physics scene for physical simulation. This property can be used to manually set world, if PhysicsScene is not created by create method.

Example:

// create an instance of b2World class manually in init function of extended class
class GameScene : PhysicsScene
{
    function init()
    {
        super.init();

        // create physics world
        this.world = new b2World(0.0, -9.8, true, false);
        ...
    }
    ...
}
// then instance of GameScene can be creates simply by key word new
var scene = new GameScene();

Events

onBeginContact

Event to be called, when two bodies collide.

Example:

this.onBeginContact = function(contact)
{
    // get the first contact
    var current = contact;
    while (current) {
        // get the bodies in the contact
        var bodyA = current.getBodyA();
        var bodyB = current.getBodyB();
        ...
        // get the next contact (they can be more contacts during the one step)
        current = current.getNext();
    }
}

onEndContact

Event to be called, when contact ends.

Example:

this.onEndContact = function(contact)
{
    // get the first contact
    var current = contact;
    while (current) {
        // get the bodies in the contact
        var bodyA = current.getBodyA();
        var bodyB = current.getBodyB();
        ...
        // get the next contact (they can be more contacts during the one step)
        current = current.getNext();
    }
}