Class World

The dynamics world, where all bodies and constraints live.

Example

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

Hierarchy

Constructors

Properties

accumulator: number = 0

Accumulator for the world

applyDamping: boolean = true

Enable to automatically apply body damping each step.

Default

true
applyGravity: boolean = true

Enable to automatically apply gravity each step.

Default

true
applySpringForces: boolean = true

Enable to automatically apply spring forces each step.

Default

true
bodies: Body[] = []

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

broadphase: Broadphase

The broadphase algorithm to use.

constraints: Constraint[] = []

User-added constraints.

contactMaterials: ContactMaterial[] = []

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: Body[] = []

Disabled body collision pairs. See disableBodyCollision.

emitImpactEvent: boolean = true

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

Default

true

Deprecated

Impact event will be removed. Use beginContact instead.

frictionGravity: number

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

gravity: Vec2

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

hasActiveBodies: boolean = false

True if any bodies are not sleeping, false if every body is sleeping.

islandSplit: boolean

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

Default

false
lastTimeStep: number = ...

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

narrowphase: Narrowphase = ...

The narrowphase to use to generate contacts.

overlapKeeper: OverlapKeeper = ...

Overlap keeper for the world

sleepMode: 2 | 1 | 4 = World.NO_SLEEPING

How to deactivate bodies during simulation. Possible modes are: ,NO_SLEEPING, BODY_SLEEPING and ISLAND_SLEEPING. If sleeping is enabled, you might need to wakeUp 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 allowSleep.

Default

World.NO_SLEEPING
solveConstraints: boolean = true

Enable/disable constraint solving in each step.

Default

true
solver: Solver

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

springs: Spring[] = []

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

stepping: boolean = false

Is true during step().

time: number = 0.0

World time.

useFrictionGravityOnZeroGravity: boolean = true

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 = true

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

Default

true
BODY_SLEEPING: 2 = ...

Deactivate individual bodies if they are sleepy.

ISLAND_SLEEPING: 4 = ...

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

NO_SLEEPING: 1 = ...

Never deactivate bodies.

Methods

  • Add a body to the simulation. Note that you can't add a body during step: you have to wait until after the step (see the postStep event). Also note that bodies can only be added to one World at a time.

    Parameters

    Returns void

    Example

    var world = new World(),
    body = new Body();
    world.addBody(body);
  • Add a constraint to the simulation. Note that both bodies connected to the constraint must be added to the world first. Also note that you can't run this method during step.

    Parameters

    Returns void

    Example

    var constraint = new LockConstraint(bodyA, bodyB);
    world.addConstraint(constraint);
  • Add a ContactMaterial to the simulation.

    Parameters

    Returns void

  • Add a spring to the simulation. Note that this operation can't be done during step.

    Parameters

    Returns void

  • Removes all bodies, constraints, springs, and contact materials from the world.

    Returns void

  • Disable collision between two bodies

    Parameters

    Returns void

  • Enable collisions between the given two bodies, if they were previously disabled using .disableBodyCollision().

    Parameters

    Returns void

  • Get a body by its id.

    Parameters

    • id: number

    Returns false | Body

    The body, or false if it was not found.

  • Get a contact material given two materials

    Parameters

    Returns false | ContactMaterial

    Todo

    Use faster hash map to lookup from material id's

  • Check if an event listener is added

    Type Parameters

    Parameters

    • type: E
    • Optional listener: ((e) => void)

    Returns boolean

  • Test if a world point overlaps bodies

    Parameters

    • worldPoint: Vec2

      Point to use for intersection tests

    • bodies: Body[]

      A list of objects to check for intersection

    • precision: number = 0

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

    Returns Body[]

    Array of bodies that overlap the point

    Todo

    Should use an api similar to the raycast function

    Todo

    Should probably implement a .containsPoint method for all shapes. Would be more efficient

    Todo

    Should use the broadphase

    Todo

    Returning the hit shape would be fine - it carries a reference to the body now

  • Remove an event listener

    Type Parameters

    Parameters

    • type: E
    • listener: ((e) => void)

    Returns EventEmitter<WorldEventMap>

    The self object, for chainability.

    Example

    emitter.on('myEvent', handler); // Add handler
    emitter.off('myEvent', handler); // Remove handler
  • Ray cast against all bodies in the world.

    Parameters

    Returns boolean

    true if any body was hit

    Example

    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);
  • Remove a body from the simulation. Note that bodies cannot be removed during step (for example, inside the beginContact event). In that case you need to wait until the step is done (see the postStep event).

    Also note that any constraints connected to the body must be removed before the body.

    Parameters

    Returns void

    Example

    var removeBody;
    world.on("beginContact",function(event){
    // We cannot remove the body here since the world is still stepping.
    // Instead, schedule the body to be removed after the step is done.
    removeBody = body;
    });
    world.on("postStep",function(event){
    if(removeBody){
    // Safely remove the body from the world.
    world.removeBody(removeBody);
    removeBody = null;
    }
    });
  • Removes a constraint. Note that you can't run this method during step.

    Parameters

    Returns void

  • Removes a contact material

    Parameters

    Returns void

  • Remove a spring. Note that this operation can't be done during step.

    Parameters

    Returns void

  • Set the relaxation for all equations and contact materials.

    Parameters

    • relaxation: number

    Returns void

  • Set the stiffness for all equations and contact materials.

    Parameters

    • stiffness: number

    Returns void

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

    • Optional timeSinceLastCalled: number

      The time elapsed since the function was last called.

    • maxSubSteps: number = 10

      Maximum number of fixed steps to take per function call.

    Returns void

    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);

    Example

    // Fixed timestepping with interpolation
    var maxSubSteps = 10;
    var lastTimeSeconds;

    function animate(time){
    requestAnimationFrame(animate);
    var timeSeconds = time / 1000;

    if(lastTimeSeconds){
    var deltaTime = timeSeconds - lastTimeSeconds;
    world.step(fixedTimeStep, deltaTime, maxSubSteps);
    }

    lastTimeSeconds = timeSeconds;

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

    // Start animation loop
    requestAnimationFrame(animate);

    See

    http://bulletphysics.org/mediawiki-1.5.8/index.php/Stepping_The_World