Physics

The top-level namespace. All of PhysicsJS is contained in the Physics namespace.

It may (and should) be invoked as a function to create a world instance. For all intensive purposes, Physics and Physics.world are the same thing.

See new Physics.world for config options and function signature.

Example:

Physics( cfg, function( world ) {
    // use world
}); // -> world
Related to:Physics.world

source: src/intro.js : 37

Physics.transform

Vector Transformations class for rotating and translating vectors

source: src/math/transform.js : 8

Physics.vector

The vector class and factory function.

Call Physics.vector with the same arguments as new Physics.vector to create an instance.

The vector methods mostly modify the vector instance. This makes computations faster because creating vectors is avoided.

Creating vectors is generally an expensive operation so try to avoid doing this in the simulation loop. Instead you can use Physics.scratchpad to get temporary vectors for use in performance critical code.

Note: The coordinate system is left-handed, meaning that the clockwise angular direction is positive. This has implications for the cross-product rule.

source: src/math/vector.js : 38

this.clone()

Create a clone of this vector, or clone another vector into this instance.

  • this.clone(v); // -> this | Physics.vector

    accepts

    v
    (Vectorish)optional

    The vector-like object to clone

    returns

    this

    If v is specified as an argument

    Physics.vector

    A new vector instance that clones this vector, if no argument is specified

This is especially useful in vector algorithms that use temporary vectors (which most should). You can create temporary vectors and then do things like...

temp.clone( otherVector );
// compute things with temp...
// then save the result
result.clone( tmp );

source: src/math/vector.js : 632

this.perp()

Change this vector into a vector that will be perpendicular.

  • this.perp(ccw); // -> this

    accepts

    ccw
    (Boolean)optional

    flag to indicate that we should rotate counterclockwise

    returns

    this

In other words, rotate by (+-) 90 degrees.

source: src/math/vector.js : 426

this.rotate()

Rotate this vector.

  • this.rotate(t); // -> this

    accepts

    t
    (Physics.transform)

    The transformation to apply the rotational part of

    returns

    this
  • this.rotate(ang, o); // -> this

    accepts

    ang
    (Number)

    The angle (in radians), to rotate by

    o
    (Vectorish)optional

    The point of origin of the rotation

    returns

    this

An angle and rotation origin can be specified, or a transform can be specified and only the rotation portion of that transform will be applied

source: src/math/vector.js : 535

Physics.vector.axis

Read-only axis vectors for general reference.

  • Physics.vector.axis = Array;

Example:

Physics.vector.axis[0]; // The x axis unit vector
Physics.vector.axis[1]; // The y axis unit vector

source: src/math/vector.js : 777

Physics.world

The world class and factory function.

Use Physics to create worlds.

Related to:Physics

source: src/core/world.js : 8

new Physics.world()alias of:Physics

World Constructor.

  • new Physics.world(options, fn(world, Physics))

    accepts

    options
    (Object)optional

    configuration options (see description)

    fn(world, Physics)
    (Function|Array)optional

    Callback function or array of callbacks called with this === world

    Accepts:

    accepts

    world
    (Physics.world)

    The current world created

    Physics
    (Physics)

    The Physics namespace

Use Physics to create worlds.

Configuration options and defaults:

{
 // default timestep
 timestep: 6,
 // maximum number of iterations per step
 maxIPF: 4,

 // default integrator
 integrator: 'verlet',

 // is sleeping disabled?
 sleepDisabled: false,
 // speed at which bodies wake up
 sleepSpeedLimit: 0.1,
 // variance in position below which bodies fall asleep
 sleepVarianceLimit: 2,
 // time (ms) before sleepy bodies fall asleep
 sleepTimeLimit: 500
}

If called with an array of functions, and any functions return a promise-like object, each remaining callback will be called only when that promise is resolved.

Example:

// hypothetical resources need to be loaded...
Physics( cfg, [
    function( world ){
        var dfd = $.Deferred()
            ,images = []
            ,toLoad = myImages.length
            ,callback = function(){
                toLoad--;
                // wait for all images to be loaded
                if ( toLoad <= 0 ){
                    dfd.resolve();
                }
            }
            ;

        // load images
        $.each(myImages, function( src ){
            var img = new Image();
            img.onload = callback;
            img.src = src;
        });

        return dfd.promise();
    },
    function( world ){
        // won't be executed until images are loaded
        // initialize world... etc...
    }
]);

source: src/core/world.js : 124

this.add()

Multipurpose add method. Add one or many bodies, behaviors, integrators, renderers...

  • this.add(things); // -> this

    accepts

    things
    (Object|Array)

    The thing, or array of things (body, behavior, integrator, or renderer) to add.

    returns

    this

source: src/core/world.js : 204

this.remove()

Multipurpose remove method. Remove one or many bodies, behaviors, integrators, renderers...

  • this.remove(things); // -> this

    accepts

    things
    (Object|Array)

    The thing, or array of things (body, behavior, integrator, or renderer) to remove.

    returns

    this

source: src/core/world.js : 252

Physics.aabb()

Create an Axis Aligned Bounding Box.

  • Physics.aabb(minX, minY, maxX, maxY); // -> Object

    accepts

    minX
    (Number)

    The x coord of the "top left" point

    minY
    (Number)

    The y coord of the "top left" point

    maxX
    (Number)

    The x coord of the "bottom right" point

    maxY
    (Number)

    The y coord of the "bottom right" point

    returns

    Object
  • Physics.aabb(pt1, pt2); // -> Object

    accepts

    pt1
    (Vectorish)

    The first corner

    pt2
    (Vectorish)

    The opposite corner

    returns

    Object
  • Physics.aabb(width, height, pt); // -> Object

    accepts

    width
    (Number)

    The width of the bounding box

    height
    (Number)

    The height of the bounding box

    pt
    (Vectorish)optional

    The center point of the bounding box

    returns

    Object

Signature:

{
    x: Number, // the x coord of the center point
    y: Number, // the y coord of the center point
    hw: Number, // the half-width
    hh: Number, // the half-height
}

source: src/math/aabb.js : 30

Physics.aabb.union()

Get the union of two aabbs.

  • Physics.aabb.union(aabb1, aabb2, modify); // -> Object

    accepts

    aabb1
    (Object)

    The first aabb (returned if modify is true)

    aabb2
    (Object)

    The second aabb

    modify
    optional

    returns

    Object

    The union of two aabbs. If modify is true, then the first aabb will be modified and returned.

source: src/math/aabb.js : 110

Physics.behavior()

Factory function for creating Behaviors.

  • Physics.behavior(name, options); // -> Behavior

    accepts

    name
    (String)

    The name of the behavior to create

    options
    (Object)optional

    The configuration for that behavior ( depends on behavior ).

    Available options and defaults:

    {
       priority: 0 // the priority of this body
    }
    

    returns

    Behavior

Visit the PhysicsJS wiki on Behaviors for usage documentation.

Related to:Physics.util.decorator

source: src/core/behavior.js : 24

Behavior

The base class for behaviors created by Physics.behavior factory function.

source: src/core/behavior.js : 31

AttractorBehavior
extends:Behavior

Physics.behavior('attractor').

Attractor behavior attracts bodies to a specific point.

Additional options include:

  • pos: The position of the attraction point
  • strength: How strong the attraction is (default: 1)
  • order: The power of the inverse distance (default: 2 because that is newtonian gravity... inverse square)
  • max: The maximum distance in which to apply the attraction (default: Infinity)
  • min: The minimum distance above which to apply the attraction (default: very small non-zero)

source: src/behaviors/attractor.js : 15

BodyCollisionDetectionBehavior
extends:Behavior

Physics.behavior('body-collision-detection').

Detect collisions of bodies.

Publishes collision events to the world as a group of detected collisions per iteration.

The event data will have a .collisions property that is an array of collisions of the form:

{
    bodyA: // the first body
    bodyB: // the second body
    norm: // the normal vector (Vectorish)
    mtv: // the minimum transit vector. (the direction and length needed to extract bodyB from bodyA)
    pos: // the collision point relative to bodyA
    overlap: // the amount bodyA overlaps bodyB
}

Additional options include:

  • check: channel to listen to for collision candidates (default: collisions:candidates). set to true to force check every pair of bodies in the world
  • channel: channel to publish events to (default: collisions:detected)

source: src/behaviors/body-collision-detection.js : 27

BodyImpulseResponseBehavior
extends:Behavior

Physics.behavior('body-impulse-response').

Responds to collisions by applying impulses.

Additional options include:

  • check: channel to listen to for collisions (default: collisions:detected).
  • mtvThreshold: apply partial extraction of bodies if the minimum transit vector is less than this value ( default: 1) this will depend on your simulation characteristic length scale
  • bodyExtractDropoff: every body overlap correction (underneith mtvThreshold) will only extract by this fraction (0..1). Helps with stablizing contacts. (default: 0.5)
  • forceWakeupAboveOverlapThreshold: force bodies to wake up if the overlap is above mtvThreshold ( default: true )

source: src/behaviors/body-impulse-response.js : 15

this.collideBodes()
internal use only

Collide two bodies by modifying their positions and velocities to conserve momentum

  • this.collideBodes(bodyA, bodyB, normal, point, mtrans, contact); // -> void

    accepts

    bodyA
    (Object)

    First Body

    bodyB
    (Object)

    Second body

    normal
    (Vector)

    Normal vector of the collision surface

    point
    (Vector)

    Contact point of the collision

    mtrans
    (Vector)

    Minimum transit vector that is the smallest displacement to separate the bodies

    contact
    (Boolean)

    Are the bodies in resting contact relative to each other

source: src/behaviors/body-impulse-response.js : 66

ConstantAccelerationBehavior
extends:Behavior

Physics.behavior('constant-acceleration').

Constant acceleration behavior.

Basically the "gravity" behavior. Used to give "earth-like gravity" to the world.

Additional options include:

  • acc: The acceleration vector (Vectorish). (default: { x: 0, y: 0.0004 })

source: src/behaviors/constant-acceleration.js : 13

EdgeCollisionDetectionBehavior
extends:Behavior

Physics.behavior('edge-collision-detection').

Used to detect collisions with the boundaries of an AABB.

Additional options include:

  • aabb: The Physics.aabb bounds to use as the constraining boundary
  • restitution: The restitution of the boundary walls (default: 0.99)
  • cof: The coefficient of friction of the boundary walls (default: 1)
  • channel: The channel to publish collisions to. (default: 'collisions:detected')

source: src/behaviors/edge-collision-detection.js : 14

InteractiveBehavior
extends:Behavior

Physics.behavior('interactive').

User interaction helper.

Used to get mouse/touch events and add grab interactions.

Additional options include:

  • el: The element of the renderer. What you input as the el for the renderer.
  • moveThrottle: The min time between move events (default: 10).
  • minVel: The minimum velocity clamp Vectorish (default: { x: -5, y: -5 }) to restrict velocity a user can give to a body
  • maxVel: The maximum velocity clamp Vectorish (default: { x: 5, y: 5 }) to restrict velocity a user can give to a body

The behavior also triggers the following events on the world:

// a body has been grabbed
world.on('interact:grab', function( data ){
    data.x; // the x coord
    data.y; // the y coord
    data.body; // the body that was grabbed
});
// no body was grabbed, but the renderer area was clicked, or touched
world.on('interact:poke', function( data ){
    data.x; // the x coord
    data.y; // the y coord
});
// when a mouse or pointer moves
world.on('interact:move', function( data ){
    data.x; // the x coord
    data.y; // the y coord
    data.body; // the grabbed body that was moved (if applicable)
});
// when the viewport is released (mouseup, touchend)
world.on('interact:release', function( data ){
    data.x; // the x coord
    data.y; // the y coord
    data.body; // the body that was grabbed (if applicable)
});

The behavior also sets body.isGrabbed = true for any grabbed bodies while they are grabbed.

source: src/behaviors/interactive.js : 45

NewtonianBehavior
extends:Behavior

Physics.behavior('newtonian').

Newtonian attraction between bodies (inverse square law).

Additional options include:

  • strength: The strength of the interaction between bodies. (default: 1)
  • max: The maximum distance between bodies at which to apply the behavior. (default: false... infinite)
  • min: The minimum distance between bodies at which to apply the behavior. (default: false... autocalculate)

source: src/behaviors/newtonian.js : 13

SweepPruneBehavior
extends:Behavior

Physics.behavior('sweep-prune').

Sweep and Prune implementation for broad phase collision detection.

This massively improves the speed of collision detection. It's set up to always be used with BodyCollisionDetection, and BodyImpulseResponse.

Additional options include:

  • channel: The channel to publish collision candidates to. (default: collisions:candidates)

source: src/behaviors/sweep-prune.js : 13

VerletConstraintsBehavior
extends:Behavior

Physics.behavior('verlet-constraints').

Verlet constraints manager.

Handles distance constraints, and angle constraints

Additional options include:

  • iterations: The number of iterations to take to relax the constraints. (default: 2)

source: src/behaviors/verlet-constraints.js : 13

this.angleConstraint()

Constrain three bodies to a target relative angle

  • this.angleConstraint(bodyA, bodyB, bodyC, stiffness, targetAngle); // -> Object

    accepts

    bodyA
    (Body)

    First body

    bodyB
    (Body)

    Second body

    bodyC
    (Body)

    Third body

    stiffness
    (Number)optional

    A number between 0 and 1 that represents the stiffness of the constraint. Defaults to: 0.5

    targetAngle
    (Number)optional

    Target angle. Defaults to the current angle between bodies

    returns

    Object

    The constraint data object

Returns constraint data that can be used to remove the constraint later.

  • .bodyA, .bodyB, and .bodyC are references to the bodies
  • .type is the type of constraint
  • .id is the string ID of the constraint
  • .stiffness is the stiffness
  • .targetAngle is the target angle

source: src/behaviors/verlet-constraints.js : 129

this.distanceConstraint()

Constrain two bodies to a target relative distance.

  • this.distanceConstraint(bodyA, bodyB, stiffness, targetLength); // -> Object

    accepts

    bodyA
    (Body)

    First body

    bodyB
    (Body)

    Second body

    stiffness
    (Number)optional

    A number between 0 and 1 that represents the stiffness of the constraint. Defaults to: 0.5

    targetLength
    (Number)optional

    Target length. defaults to current distance between the bodies

    returns

    Object

    The constraint data object

Returns constraint data that can be used to remove the constraint later.

  • .bodyA and .bodyB are references to the bodies
  • .type is the type of constraint
  • .id is the string ID of the constraint
  • .stiffness is the stiffness
  • .targetLength is the target length

source: src/behaviors/verlet-constraints.js : 86

Physics.body()

Factory function for creating Bodies.

  • Physics.body(name, options); // -> Body

    accepts

    name
    (String)

    The name of the body to create

    options
    (Object)optional

    The configuration for that body ( depends on body ).

    Available options and defaults:

    {
        // is the body hidden (not to be rendered)?
        hidden: false,
        // is the body `dynamic`, `kinematic` or `static`?
        // http://www.box2d.org/manual.html#_Toc258082973
        treatment: 'dynamic',
        // body mass
        mass: 1.0,
        // body restitution. How "bouncy" is it?
        restitution: 1.0,
        // what is its coefficient of friction with another surface with COF = 1?
        cof: 0.8,
        // what is the view object (mixed) that should be used when rendering?
        view: null,
        // the vector offsetting the geometry from its center of mass
        offset: Physics.vector(0,0)
    }
    

    returns

    Body

Visit the PhysicsJS wiki on Bodies for usage documentation.

Related to:Physics.util.decorator

source: src/core/body.js : 91

Body

The base class for bodies created by Physics.body factory function.

source: src/core/body.js : 98

CircleBody
extends:Body

Physics.body('circle')

The circle body has a circular shape.

Additional options include:

  • radius: the radius

Example:

var round = Physics.body('circle', {
    x: 30,
    y: 20,
    radius: 5
});

source: src/bodies/circle.js : 24

CompoundBody
extends:Body

Physics.body('compound')

Not a body in itself. It's a container to group other bodies. The position of the body is the center of mass. It must have at least one child before being added to the world.

Additional config options:

  • children: Array of Body objects.

Example:

var thing = Physics.body('compound', {
    // place the center of mass at (300, 200)
    x: 300,
    y: 200,
    // the center of mass is automatically calculated and used to position the shape
    children: [
        body1,
        body2,
        // ...
    ]
});

source: src/bodies/compound.js : 32

ConvexPolygonBody
extends:Body

Physics.body('convex-polygon')

Body for convex polygons. The position of the body is the centroid of the polygon.

Additional config options:

  • vertices: Array of Vectorish objects representing the polygon vertices in clockwise (or counterclockwise) order.

Example:

var pentagon = Physics.body('convex-polygon', {
    // place the centroid of the polygon at (300, 200)
    x: 300,
    y: 200,
    // the centroid is automatically calculated and used to position the shape
    vertices: [
        { x: 0, y: -30 },
        { x: -29, y: -9 },
        { x: -18, y: 24 },
        { x: 18, y: 24 },
        { x: 29, y: -9 }
    ]
});

source: src/bodies/convex-polygon.js : 33

RectangleBody
extends:Body

Physics.body('rectangle')

Body for rectangles. The position of the body is the centroid of the rectangle.

Additional config options:

  • width: The width
  • height: The height

Example:

var rect = Physics.body('rectangle', {
    // place the centroid of the rectangle at (300, 200)
    x: 300,
    y: 200,
    width: 30,
    height: 40
});

source: src/bodies/rectangle.js : 28

this.cof

The coefficient of friction of the body.

  • this.cof = 0.8;

It's how much "slide" it has during collisions.

A cof of 0 will really slidy.

A cof of 1 has no slide.

This is a very simplistic implementation at the moment. What would be better is to have both static and kinetic friction. But that's not done yet.

source: src/core/body.js : 251

this.restitution

The restitution.

  • this.restitution = 1;

This is the "bounciness" of the body. It's a number between 0 and 1.

A restitution of 1 is the bounciest.

A restitution of 0 is not bouncy.

When colliding the restitutions of bodies are multiplied together to get the restitution between two bodies.

source: src/core/body.js : 235

this.sleep()

Get and/or set whether the body is asleep.

If called with a time (in ms), the time will be added to the idle time and sleep conditions will be checked.

source: src/core/body.js : 304

this.sleepCheck()

Check if the body should be sleeping.

  • this.sleepCheck(dt); // -> void

    accepts

    dt
    (Number)optional

    Time to advance the idle time

Call with no arguments if some event could possibly wake up the body. This will force the body to recheck.

source: src/core/body.js : 336

this.state

The physical state container.

  • this.state.pos (Physics.vector) The position vector.
  • this.state.vel (Physics.vector) The velocity vector.
  • this.state.acc (Physics.vector) The acceleration vector.
  • this.state.angular.pos (Number) The angular position (in radians, positive is clockwise starting along the x axis)
  • this.state.angular.vel (Number) The angular velocity
  • this.state.angular.acc (Number) The angular acceleration

Properties from the previous timestep are stored in:

this.state.old; // .pos, .vel, ...

source: src/core/body.js : 150

this.treatment

How the body is treated by the simulation.

  • this.treatment = String;

The body can be dynamic, kinematic or static as described by the analogous box2d docs.

  • dynamic bodies are treated "normally". They are integrated, and collide, and all that.
  • kinematic bodies are bodies that move at a specified velocity. Other bodies collide with them, but they don't bounce off of other bodies.
  • static bodies just stand still. They are like obstacles.

source: src/core/body.js : 264

this.view

Storage for use by the renderer.

  • this.view = it_depends;

The type of renderer will put different things in the view property. Basically, this is how the body "looks". It could be a HTMLElement, or an Image, etc...

If your body changes appearance (shape), you should modify this somehow otherwise the renderer will keep using this same view. If you're letting the renderer create the view for you, just set this to undefined if the body gets modified in shape during the simulation.

Related to:Physics.renderer

source: src/core/body.js : 285

Physics.geometry()

Factory function for creating Geometries.

  • Physics.geometry(name, options); // -> Geometry

    accepts

    name
    (String)

    The name of the geometry to create

    options
    (Object)optional

    The configuration for that geometry ( depends on geometry ).

    returns

    Geometry

Visit the PhysicsJS wiki on Geometries for usage documentation.

Related to:Physics.util.decorator

source: src/core/geometry.js : 12

Geometry

The base class for geometries created by Physics.geometry factory function.

source: src/core/geometry.js : 19

CircleGeometry
extends:Geometry

Physics.geometry('circle')

The circle geometry has a circular shape.

Additional options include:

  • radius: the radius

Example:

var round = Physics.body('circle', {
    x: 30,
    y: 20,
    radius: 5
});

source: src/geometries/circle.js : 21

CompoundGeometry
extends:Geometry

Physics.geometry('compound')

Geometry for compound shapes.

Example:

var thing = Physics.geometry('compound');
thing.addChild( child, pos, rotation );

source: src/geometries/compound.js : 15

ConvexPolygonGeometry
extends:Geometry

Physics.geometry('convex-polygon')

Geometry for convex polygons.

Additional config options:

  • vertices: Array of Vectorish objects representing the polygon vertices in clockwise (or counterclockwise) order.

Example:

var pentagon = Physics.geometry('convex-polygon', {
    // the centroid is automatically calculated and used to position the shape
    vertices: [
        { x: 0, y: -30 },
        { x: -29, y: -9 },
        { x: -18, y: 24 },
        { x: 18, y: 24 },
        { x: 29, y: -9 }
    ]
});

source: src/geometries/convex-polygon.js : 27

this.getFarthestCorePoint()

Get farthest point on the core shape of this geometry along the direction vector dir returns local coordinates. Replaces result if provided.

This does almost the same thing as Geometry#getFarthestHullPoint but shrinks the shape by subtracting "margin" from it. Return the position of the point on the "core" shape.

Related to:Geometry#getFarthestHullPoint

source: src/core/geometry.js : 104

this.getFarthestHullPoint()

Get farthest point on the hull of this geometry along the direction vector dir returns local coordinates. Replaces result if provided.

Assume all coordinates are relative to the geometry centroid (IE: in the body frame).

This should take a direction vector then it should calculate the location (in that frame of reference) of the point on the perimeter (hull) if you traveled in a straight line from the centroid in the provided direction. The result should be returned/set just like it is in the other geometries.

source: src/core/geometry.js : 82

Physics.gjk()

Implementation agnostic GJK function.

  • Physics.gjk(support(axis), seed, checkOverlapOnly, debugFn); // -> Object

    accepts

    support(axis)
    (Function)

    The support function. Must return an object containing

    the witness points (.a, .b) and the support point (.pt).

    Recommended to use simple objects.

    Eg:

    return {
         a: { x: 1, y:2 },
         b: { x: 3, y: 4 },
         pt: { x: 2, y: 2 }
    };
    

    Accepts:

    accepts

    axis
    seed
    (Physics.vector)optional

    The starting direction for the simplex (defaults to x-axis)

    checkOverlapOnly
    (Boolean)optional

    only check whether there is an overlap, don't calculate the depth

    debugFn
    (Function)optional

    For debugging. Called at every iteration with the current simplex.

    returns

    Object

Gilbert–Johnson–Keerthi object collison algorithm For general information about GJK see:

The algorithm information returned:

{
    overlap: Boolean,
    simplex: [] // array containing simplex points as simple x/y objects
}

source: src/math/gjk.js : 134

Physics.integrator()

Factory function for creating Integrators.

  • Physics.integrator(name, options); // -> Integrator

    accepts

    name
    (String)

    The name of the integrator to create

    options
    (Object)optional

    The configuration for that integrator ( depends on integrator ).

    Available options and defaults:

    {
        // drag applied during integration
        // 0 means vacuum
        // 0.9 means molasses
        drag: 0
    }
    

    returns

    Integrator

Visit the PhysicsJS wiki on Integrators for usage documentation.

Related to:Physics.util.decorator

source: src/core/integrator.js : 31

Integrator

The base class for integrators created by Physics.integrator factory function.

source: src/core/integrator.js : 38

Physics.query()

Creates a function that can be used to perform tests on objects.

  • Physics.query(rules); // -> Function

    accepts

    rules
    (Object)

    The mongodb-like search rules. (See description).

    returns

    Function

    The test function

The test function will return a Boolean; true if the object matches the tests.

Query rules are mongodb-like. You can specify a hash of values to match like this:

{
    foo: 'bar',
    baz: 2,
    some: {
        nested: 'value'
    }
}

And they will all need to match (it's an AND rule).

You can also use operators for more versatility. The operators you can use include:

  • $eq: Test if some property is equal to a value (this is done by default, and is thus redundant)
  • $ne: Test if some property is NOT equal to a value
  • $in: Test if some value (or array of values) is one of the specified array of values
  • $nin: Test if some value (or array of values) is NOT one of the specified array of values
  • $at: Test if a body's Physics.aabb includes specified point. It's a primative hit-test.

Example:

var wheelsArray = [];

var queryFn = Physics.query({
    name: 'circle', // only circles
    $nin: wheelsArray, // not in the wheelsArray
    labels: { $in: [ 'player', 'monster' ] } // that have player OR monster labels
});

var obj = {
    name: 'circle',
    labels: [ 'round' ]
};

queryFn( obj ); // -> false
// give it a player tag
obj.labels.push('player');
queryFn( obj ); // -> true
// put it inside the wheelsArray
wheelsArray.push( obj );
queryFn( obj ); // -> false
Related to:Physics.world#find

source: src/core/query.js : 262

Physics.renderer()

Factory function for creating Renderers.

  • Physics.renderer(name, options); // -> Renderer

    accepts

    name
    (String)

    The name of the renderer to create

    options
    (Object)optional

    The configuration for that renderer ( depends on renderer ).

    Available options and defaults:

    {
        // draw meta data (fps, steps, etc)
        meta: false,
        // refresh rate of meta info
        metaRefresh: 200,
    
    
        // width of viewport
        width: 600,
        // height of viewport
        height: 600
        // automatically resize the renderer
        autoResize: true
    }
    

    returns

    Renderer

Visit the PhysicsJS wiki on Renderers for usage documentation.

Related to:Physics.util.decorator

source: src/core/renderer.js : 44

Renderer

The base class for renderers created by Physics.renderer factory function.

source: src/core/renderer.js : 51

CanvasRenderer
extends:Renderer

Physics.renderer('canvas')

Renderer that uses HTMLCanvas to render the world bodies.

Additional config options:

  • metaEl: HTMLElement to write meta information like FPS and IPF into. (default: autogenerated)
  • offset: Offset the shapes by this amount. (default: { x: 0, y: 0 })
  • styles: Styles to use to draw the shapes. (see below)

The styles property should contain default styles for each shape you want to draw.

Example:

styles: {

   'circle' : {
       strokeStyle: '#542437',
       lineWidth: 1,
       fillStyle: '#542437',
       angleIndicator: 'white'
   },

   'convex-polygon' : {
       strokeStyle: '#542437',
       lineWidth: 1,
       fillStyle: '#542437',
       angleIndicator: 'white'
   }
}

source: src/renderers/canvas.js : 37

Layer

A rendering layer for the canvas renderer.

Create by calling CanvasRenderer#addLayer.

source: src/renderers/canvas.js : 204

this.addToStack()

Add body (bodies) to the rendering stack for this layer.

  • this.addToStack(arr); // -> this

    accepts

    arr
    (Array)

    Array of bodies to add

    returns

    this
  • this.addToStack(body); // -> this

    accepts

    body
    (Body)

    Body to add

    returns

    this

Bodies must be added to the stack in order to be rendered by this layer UNLESS it is the "main" layer.

source: src/renderers/canvas.js : 293

this.render()

Render the bodies in this layer's stack.

  • this.render(clear); // -> this

    accepts

    clear
    (Boolean)optional

    Clear the canvas (default: true)

    returns

    this

If you want you can replace this function with your own to do custom rendering.

Example:

layer.render = myCustomRenderFn;

source: src/renderers/canvas.js : 342

this.addLayer()

Create a new layer.

  • this.addLayer(id, el, opts); // -> Layer

    accepts

    id
    (String)

    The id for the layer

    el
    (HTMLElement)optional

    The canvas element to use for this layer

    opts
    (Object)optional

    The options for this layer (see below)

    returns

    Layer

Layers can have the following options:

  • width: The width
  • height: The height
  • manual: Draw manually (default: false)
  • autoResize: Automatically resize the layer when the renderer's CanvasRenderer#resize method is called. (default: true)
  • follow: A Body. Offset this layer's rendering to follow a body's position. (default: null)
  • offset: The offset Vectorish for this layer. (default: null)
  • scale: Scale the layer by this amount. (default: 1)
  • zIndex: The zIndex for the layer's HTMLElement. (default: 1)

source: src/renderers/canvas.js : 195

DebugRenderer
extends:Renderer

Physics.renderer('debug')

Extends canvas renderer with special debugging functionality.

Additional config options:

  • metaEl: HTMLElement to write meta information like FPS and IPF into. (default: autogenerated)
  • offset: Offset the shapes by this amount. (default: { x: 0, y: 0 })
  • styles: Styles to use to draw the shapes. (see below)
  • drawAABB: whether or not to draw bounding boxes. (default: true)
  • drawRealPosition: whether or not to draw the non-interpolated position of bodies. (default: false)
  • drawIntervals: whether or not to draw the broadphase (sweep-prune) intervals. (default: false)
  • drawContacts: whether or not to draw contact points. (default: false)
  • drawSleepState: whether or not to highlight sleeping bodies. (default: false)
  • drawBodyState: whether or not to show body position and velocity. (default: false)
  • aabbColor: the color of AABBs
  • realBodyStyle: styles used to draw the image of the body at its true non-interpolated position
  • intervalMinColor: color of interval minima
  • intervalMaxColor: color of interval maxima
  • mtvColor: color of minimum transit vector for contacts (overlaps)
  • contactColor: color of contact points

The styles property should contain default styles for each shape you want to draw.

Example:

styles: {

   'circle' : {
       strokeStyle: '#542437',
       lineWidth: 1,
       fillStyle: '#542437',
       angleIndicator: 'white'
   },

   'convex-polygon' : {
       strokeStyle: '#542437',
       lineWidth: 1,
       fillStyle: '#542437',
       angleIndicator: 'white'
   }
}

source: src/renderers/debug.js : 52

DomRenderer
extends:Renderer

Physics.renderer('dom')

Renderer that manipulates DOM elements according to the physics simulation. Very primative...

source: src/renderers/dom.js : 8

PixiRenderer
extends:Renderer

Physics.renderer('pixi')

Renderer that uses the PIXI.js library. Documentation can be found here.

Additional config options:

  • metaEl: HTMLElement to write meta information like FPS and IPF into. (default: autogenerated)
  • offset: Offset the shapes by this amount. (default: { x: 0, y: 0 })
  • styles: Styles to use to draw the shapes. (see below)

The styles property should contain default styles for each shape you want to draw.

Example:

styles: {
   // Defines the default canvas colour
   'color': '0x66FF99',

   'circle' : {
       strokeStyle: '0xE8900C',
       lineWidth: 3,
       fillStyle: '0xD5DE4C',
       angleIndicator: '0xE8900C'
   },

   'convex-polygon' : {
       strokeStyle: '0xE8900C',
       lineWidth: 3,
       fillStyle: '0xD5DE4C',
       angleIndicator: '0xE8900C'
   }
}

source: src/renderers/pixi-renderer.js : 42

this.createView()

Create a view for the specified geometry.

  • this.createView(geometry, styles); // -> Mixed

    accepts

    geometry
    (Geometry)

    geometry The geometry

    styles
    (Object|String)

    The styles configuration

    returns

    Mixed

    Whatever the renderer needs to render the body.

The view is used to render the body. It is a cached version of the body that gets moved and rotated according to the simulation.

The styles are used to modify the appearance of the view. They depend on the renderer.

Override this when creating renderers.

source: src/core/renderer.js : 182

this.drawMeta()

Draw the meta data.

  • this.drawMeta(meta); // -> void

    accepts

    meta
    (Object)

    The meta data

The meta data will look like this:

meta = {
    fps: 60, // the frames per second
    ipf: 4 // the number of iterations per frame
};

Override this when creating renderers.

source: src/core/renderer.js : 209

Physics.scratchpad()

Get a new scratch session to work from or wrap a function in a scratch session.

  • Physics.scratchpad(fn); // -> Function | Scratch

    accepts

    fn
    (Function)optional

    Some function you'd like to wrap in a scratch session. First argument is the scratch instance.

    returns

    Function

    The wrapped function (if fn arg specified) that can be reused like the original minus the first (scratch) parameter.

    Scratch

    The scratch session.

Call .done() on it when finished.

Example:

// get a scratch session manually
var myAlg = function( scratch, arg1, arg2, ... ){
    var scratch = Physics.scratchpad()
    ,vec = scratch.vector().set( 0, 0 ) // need to reinitialize... it's recycled!
    ;
    // ...
    return scratch.done( result );
};
// later...
while( awesome ){
    myAlg( arg1, arg2, ... );
}

Example:

// wrap a function in a scratch session
var myAlg = Physics.scratchpad(function( scratch, arg1, arg2, ... ){
    var vec = scratch.vector().set( 0, 0 ); // need to reinitialize... it's recycled!
    //...
    return result;
});
// later...
while( awesome ){
    myAlg( arg1, arg2, ... );
}

source: src/util/scratchpad.js : 128

Scratch

A scratchpad session.

This class keeps track of temporary objects used in this session and releases them when finished (call to .done()).

Use this to retrieve temporary objects:

See Physics.scratchpad for more info.

source: src/util/scratchpad.js : 37

this.done()

Declare that your work is finished.

  • this.done(val); // -> Mixed

    accepts

    val
    (Mixed)optional

    No effect on this method, just passed on to the return value so you can do things like:

     return scratch.done( myReturnVal );
    

    returns

    Mixed

    Whatever you specified as val

Release temp objects for use elsewhere. Must be called when immediate work is done.

You can wrap the return value in scratch.done() so that you don't forget to call it.

Example:

return scratch.done( myReturnValue );

source: src/util/scratchpad.js : 68

Physics.util

Namespace for utility functions.

source: src/intro.js : 47

Physics.util.pubsub

Fast pubsub implementation.

Can be mixed into other classes easily.

source: src/util/pubsub.js : 19

this.off()

Unsubscribe callback(s) from topic(s).

  • this.off(topic, fn, scope); // -> this

    accepts

    topic
    (String)

    topic The topic name. Specify true to remove all listeners for all topics

    fn
    (Function)

    The original callback function. Specify true to remove all listeners for specified topic

    scope
    (Object)optional

    The scope the callback was bound to. This is important if you are binding methods that come from object prototypes.

    returns

    this
  • this.off(topicCfg); // -> this

    accepts

    topicCfg
    (Object)

    A config with key/value pairs of { topic: callbackFn, ... }

    returns

    this

source: src/util/pubsub.js : 96

this.on()

Subscribe callback(s) to a topic(s).

  • this.on(topic, fn(data, event), scope, priority); // -> this

    accepts

    topic
    (String)

    The topic name

    fn(data, event)
    (Function)

    The callback function (if not using Object as previous argument)

    Accepts:

    accepts

    data
    event
    scope
    (Object)optional

    The scope to bind callback to

    priority
    (Number)optional

    The priority of the callback (higher is earlier)

    returns

    this
  • this.on(topicConfig, scope, priority); // -> this

    accepts

    topicConfig
    (Object)

    A config with key/value pairs of { topic: callbackFn, ... }

    scope
    (Object)optional

    The scope to bind callback to

    priority
    (Number)optional

    The priority of the callback (higher is earlier)

    returns

    this

source: src/util/pubsub.js : 41

this.one()

Subscribe callback(s) to a topic(s), but only ONCE.

  • this.one(topic, fn(data, event), scope, priority); // -> this

    accepts

    topic
    (String)

    The topic name

    fn(data, event)
    (Function)

    The callback function (if not using Object as previous argument)

    Accepts:

    accepts

    data
    event
    scope
    (Object)optional

    The scope to bind callback to

    priority
    (Number)optional

    The priority of the callback (higher is earlier)

    returns

    this
  • this.one(topicConfig, scope, priority); // -> this

    accepts

    topicConfig
    (Object)

    A config with key/value pairs of { topic: callbackFn, ... }

    scope
    (Object)optional

    The scope to bind callback to

    priority
    (Number)optional

    The priority of the callback (higher is earlier)

    returns

    this

source: src/util/pubsub.js : 211

Physics.util.ticker

The Ticker singleton for easily binding callbacks to animation loops (requestAnimationFrame).

Requires window.requestAnimationFrame... so polyfill it if you need to.

source: src/util/ticker.js : 8

Physics.util.decorator()

Facilitates creation of decorator factory functions.

  • Physics.util.decorator(type, protoDef); // -> Function

    accepts

    type
    (String)

    The name of the factory you are creating

    protoDef
    (Object)optional

    The top-level prototype

    returns

    Function

    The factory function

See the factory definition for the factory signatures. For full documentation and examples, please visit the wiki.

Example:

var factory = Physics.util.decorator('factory', {
     // prototype methods...
     method: function( args ){
     }
});

// define
factory( 'name', 'parent-name', function( parent ){

     // extend further...
     return {
         // overrides
         init: function( cfg ){
             parent.init.call(this, cfg);
         }
     };
});

// instantiate
var options = { key: 'val' };
var instance = factory( 'name', options );
Related to:factory

source: src/util/decorator.js : 38

factory

Factory function for definition and instantiation of subclasses.

  • factory(name, parentName, decorator, cfg); // -> void

    accepts

    name
    (String)

    The class name

    parentName
    (String)optional

    The name of parent class to extend

    decorator
    (Function)

    The decorator function that should define and return methods to extend (decorate) the base class

    cfg
    (Object)optional

    The configuration to pass to the class initializer

  • factory(name, cfg); // -> Object

    accepts

    name
    (String)

    The class name

    cfg
    (Object)

    The configuration to pass to the class initializer

    returns

    Object

Use the first signature (once) to define it first. If defining without the "cfg" parameter, void will be returned. Otherwise the class instance will be returned.

See Physics.util.decorator for more information.

source: src/util/decorator.js : 129

Physics.util.filter()

Test an array of values against a test function and return another array of values for which the test function returns true.

  • Physics.util.filter(collection, fn(value, index, collection)); // -> Array

    accepts

    collection
    (Array)

    Collection of values to test

    fn(value, index, collection)
    (Function)

    The test function

    Accepts:

    accepts

    value
    (Mixed)

    The value to test

    index
    (Number)

    The index of value in collection

    collection
    (Array)

    Collection of values to test

    returns

    Array

source: src/util/helpers.js : 235

Physics.util.find()

Test an array of values against a test function and return the first value for which the function returns true.

  • Physics.util.find(collection, fn(value, index, collection)); // -> Mixed

    accepts

    collection
    (Array)

    Collection of values to test

    fn(value, index, collection)
    (Function)

    The test function

    Accepts:

    accepts

    value
    (Mixed)

    The value to test

    index
    (Number)

    The index of value in collection

    collection
    (Array)

    Collection of values to test

    returns

    Mixed

source: src/util/helpers.js : 209

Physics.util.options()

Options helper to keep track of options. Call it with a config object. Access options directly on the function.

  • Physics.util.options(def, target); // -> Function

    accepts

    def
    (Object)

    Default options to set

    target
    (Object)optional

    Where to copy the options to. Defaults to the returned function.

    returns

    Function

    The options function

Example:

this.options = Physics.util.options({ foo: 'bar', opt: 'def' });
this.options({ opt: 'myVal' });

this.options.foo; // === 'bar'
this.options.def; // === 'myVal'

// can also change defaults later
this.options.defaults({ foo: 'baz' });

// can add a change callback
this.options.onChange(function( opts ){
    // some option changed
    // opts is the target
});

source: src/util/helpers.js : 102

Special

This section contains miscellaneous functionality.

source: src/intro.js : 54

Vectorish

Any object with .x and .y properties.

A Vectorish isn't really a class. In this documentation, when an argument is specified as a Vectorish it means either a true Physics.vector instance, or an object literal with .x and .y properties.

source: src/math/vector.js : 49