API Docs for: 0.7.1
Show:

World Class

Extends EventEmitter
Defined in: src/world/World.js:35

The dynamics world, where all bodies and constraints live.

Constructor

World

(
  • [options]
)

Parameters:

  • [options] Object optional
    • [solver] Solver optional

      Defaults to GSSolver.

    • [gravity] Array optional

      Defaults to y=-9.78.

    • [broadphase] Broadphase optional

      Defaults to SAPBroadphase

    • [islandSplit=true] Boolean optional

Example:

var world = new World({
            gravity: [0, -10],
            broadphase: new SAPBroadphase()
        });
        world.addBody(new Body());
        

Methods

addBody

(
  • body
)

Add a body to the simulation

Parameters:

Example:

var world = new World(),
    body = new Body();
world.addBody(body);

addConstraint

(
  • constraint
)

Add a constraint to the simulation.

Parameters:

Example:

var constraint = new LockConstraint(bodyA, bodyB);
world.addConstraint(constraint);

addContactMaterial

(
  • contactMaterial
)

Add a ContactMaterial to the simulation.

Parameters:

addSpring

(
  • spring
)

Add a spring to the simulation

Parameters:

clear

()

Resets the World, removes all bodies, constraints and springs.

disableBodyCollision

(
  • bodyA
  • bodyB
)

Disable collision between two bodies

Parameters:

emit

(
  • event
)
EventEmitter

Emit an event.

Parameters:

  • event Object
    • type String

Returns:

EventEmitter:

The self object, for chainability.

enableBodyCollision

(
  • bodyA
  • bodyB
)

Enable collisions between the given two bodies

Parameters:

getBodyById

(
  • id
)
Body

Get a body by its id.

Parameters:

  • id Number

Returns:

Body:

The body, or false if it was not found.

getContactMaterial

(
  • materialA
  • materialB
)
ContactMaterial

Get a contact material given two materials

Parameters:

Returns:

ContactMaterial:

The matching ContactMaterial, or false on fail.

has

(
  • type
  • listener
)
Boolean

Check if an event listener is added

Parameters:

  • type String
  • listener Function

Returns:

Boolean:

hitTest

(
  • worldPoint
  • bodies
  • precision
)
Array

Test if a world point overlaps bodies

Parameters:

  • worldPoint Array

    Point to use for intersection tests

  • bodies Array

    A list of objects to check for intersection

  • precision Number

    Used for matching against particles and lines. Adds some margin to these infinitesimal objects.

Returns:

Array:

Array of bodies that overlap the point

internalStep

(
  • dt
)
private

Make a fixed step.

Parameters:

  • dt Number

off

(
  • type
  • listener
)
EventEmitter

Remove an event listener

Parameters:

  • type String
  • listener Function

Returns:

EventEmitter:

The self object, for chainability.

on

(
  • type
  • listener
)
EventEmitter

Add an event listener

Parameters:

  • type String
  • listener Function

Returns:

EventEmitter:

The self object, for chainability.

raycast

(
  • result
  • ray
)
Boolean

Ray cast against all bodies in the world.

Parameters:

Returns:

Boolean:

True if any body was hit.

Example:

var ray = new Ray({
    mode: Ray.CLOSEST, // or ANY
    from: [0, 0],
    to: [10, 0],
});
var result = new RaycastResult();
world.raycast(result, ray);

// Get the hit point
var hitPoint = vec2.create();
result.getHitPoint(hitPoint, ray);
console.log('Hit point: ', hitPoint[0], hitPoint[1], ' at distance ' + result.getHitDistance(ray));
var ray = new Ray({
    mode: Ray.ALL,
    from: [0, 0],
    to: [10, 0],
    callback: function(result){

        // Print some info about the hit
        console.log('Hit body and shape: ', result.body, result.shape);

        // Get the hit point
        var hitPoint = vec2.create();
        result.getHitPoint(hitPoint, ray);
        console.log('Hit point: ', hitPoint[0], hitPoint[1], ' at distance ' + result.getHitDistance(ray));

        // If you are happy with the hits you got this far, you can stop the traversal here:
        result.stop();
    }
});
var result = new RaycastResult();
world.raycast(result, ray);

removeBody

(
  • body
)

Remove a body from the simulation. If this method is called during step(), the body removal is scheduled to after the step.

Parameters:

removeConstraint

(
  • constraint
)

Removes a constraint

Parameters:

removeContactMaterial

(
  • cm
)

Removes a contact material

Parameters:

removeSpring

(
  • spring
)

Remove a spring

Parameters:

runNarrowphase

(
  • np
  • bi
  • si
  • xi
  • ai
  • bj
  • sj
  • xj
  • aj
  • mu
)

Runs narrowphase for the shape pair i and j.

Parameters:

setGlobalRelaxation

(
  • relaxation
)

Set the relaxation for all equations and contact materials.

Parameters:

  • relaxation Number

setGlobalStiffness

(
  • stiffness
)

Set the stiffness for all equations and contact materials.

Parameters:

  • stiffness Number

step

(
  • dt
  • [timeSinceLastCalled=0]
  • [maxSubSteps=10]
)

Step the physics world forward in time.

There are two modes. The simple mode is fixed timestepping without interpolation. In this case you only use the first argument. The second case uses interpolation. In that you also provide the time since the function was last used, as well as the maximum fixed timesteps to take.

Parameters:

  • dt Number

    The fixed time step size to use.

  • [timeSinceLastCalled=0] Number optional

    The time elapsed since the function was last called.

  • [maxSubSteps=10] Number optional

    Maximum number of fixed steps to take per function call.

Example:

// Simple fixed timestepping without interpolation
var fixedTimeStep = 1 / 60;
var world = new World();
var body = new Body({ mass: 1 });
world.addBody(body);

function animate(){
    requestAnimationFrame(animate);
    world.step(fixedTimeStep);
    renderBody(body.position, body.angle);
}

// Start animation loop
requestAnimationFrame(animate);
// Fixed timestepping with interpolation
var maxSubSteps = 10;
var lastTimeSeconds;

function animate(t){
    requestAnimationFrame(animate);
    timeSeconds = t / 1000;
    lastTimeSeconds = lastTimeSeconds || timeSeconds;

    deltaTime = timeSeconds - lastTimeSeconds;
    world.step(fixedTimeStep, deltaTime, maxSubSteps);

    renderBody(body.interpolatedPosition, body.interpolatedAngle);
}

// Start animation loop
requestAnimationFrame(animate);

Properties

applyDamping

Boolean

Enable to automatically apply body damping each step.

Default: true

applyGravity

Boolean

Enable to automatically apply gravity each step.

Default: true

applySpringForces

Boolean

Enable to automatically apply spring forces each step.

Default: true

bodies

Array

All bodies in the world. To add a body to the world, use addBody.

bodiesToBeRemoved

Array private

Bodies that are scheduled to be removed at the end of the step.

BODY_SLEEPING

Number static

Deactivate individual bodies if they are sleepy.

broadphase

Broadphase

The broadphase algorithm to use.

constraints

Array

User-added constraints.

contactMaterials

Array

The ContactMaterials added to the World.

defaultContactMaterial

ContactMaterial

The default contact material to use, if no contact material was set for the colliding materials.

defaultMaterial

Material

Dummy default material in the world, used in .defaultContactMaterial

disabledBodyCollisionPairs

Array private

Disabled body collision pairs. See {{#crossLink "World/disableBodyCollision:method"}}.

emitImpactEvent

Boolean

Set to true if you want to the world to emit the "impact" event. Turning this off could improve performance.

Default: true

frictionGravity

Number

Gravity to use when approximating the friction max force (mumassgravity).

gravity

Array

Gravity in the world. This is applied on all bodies in the beginning of each step().

ISLAND_SLEEPING

Number static

Deactivates bodies that are in contact, if all of them are sleepy. Note that you must enable .islandSplit for this to work.

islandManager

IslandManager

The island manager of this world.

islandSplit

Boolean

Whether to enable island splitting. Island splitting can be an advantage for both precision and performance. See IslandManager.

Default: true

lastTimeStep

Number

For keeping track of what time step size we used last step

narrowphase

Narrowphase

The narrowphase to use to generate contacts.

NO_SLEEPING

Number static

Never deactivate bodies.

overlapKeeper

OverlapKeeper

sleepMode

Number

How to deactivate bodies during simulation. Possible modes are: World.NO_SLEEPING, World.BODY_SLEEPING and World.ISLAND_SLEEPING. If sleeping is enabled, you might need to wake up the bodies if they fall asleep when they shouldn't. If you want to enable sleeping in the world, but want to disable it for a particular body, see Body.allowSleep.

Default: World.NO_SLEEPING

solveConstraints

Boolean

Enable/disable constraint solving in each step.

Default: true

solver

Solver

The solver used to satisfy constraints and contacts. Default is GSSolver.

springs

Array

All springs in the world. To add a spring to the world, use addSpring.

stepping

Boolean

Is true during step().

time

Number

World time.

useFrictionGravityOnZeroGravity

Boolean

If the length of .gravity is zero, and .useWorldGravityAsFrictionGravity=true, then switch to using .frictionGravity for friction instead. This fallback is useful for gravityless games.

Default: true

useWorldGravityAsFrictionGravity

Boolean

Set to true if you want .frictionGravity to be automatically set to the length of .gravity.

Default: true

Events

addBody

Fired when a body is added to the world.

Event Payload:

addSpring

Fired when a spring is added to the world.

Event Payload:

beginContact

Fired when two shapes starts start to overlap. Fired in the narrowphase, during step.

Event Payload:

endContact

Fired when two shapes stop overlapping, after the narrowphase (during step).

Event Payload:

impact

Fired when a first contact is created between two bodies. This event is fired after the step has been done.

Event Payload:

postBroadphase

Fired after the Broadphase has collected collision pairs in the world. Inside the event handler, you can modify the pairs array as you like, to prevent collisions between objects that you don't want.

Event Payload:

  • pairs Array

    An array of collision pairs. If this array is [body1,body2,body3,body4], then the body pairs 1,2 and 3,4 would advance to narrowphase.

postStep

Fired after the step().

preSolve

Fired just before equations are added to the solver to be solved. Can be used to control what equations goes into the solver.

Event Payload:

  • contactEquations Array

    An array of contacts to be solved.

  • frictionEquations Array

    An array of friction equations to be solved.

removeBody

Fired when a body is removed from the world.

Event Payload: