<ahref="global.html#Phaser.Path#numPointsreturn%257Bnumber%257DThetotalnumberofPathPointsinthisPath.">Phaser.Path#numPoints
return {number} The total number of PathPoints in this Path.</a>
* This is your main access to the P2 Physics World.
* From here you can create materials, listen for events and add bodies into the physics simulation.
*
* @class Phaser.Physics.P2
* @constructor
* @param {Phaser.Game} game - Reference to the current game instance.
* @param {object} [config] - Physics configuration object passed in from the game constructor.
*/
Phaser.Physics.P2 = function (game, config) {
/**
* @property {Phaser.Game} game - Local reference to game.
*/
this.game = game;
if (config === undefined)
{
config = { gravity: [0, 0], broadphase: new p2.SAPBroadphase() };
}
else
{
if (!config.hasOwnProperty('gravity'))
{
config.gravity = [0, 0];
}
if (!config.hasOwnProperty('broadphase'))
{
config.broadphase = new p2.SAPBroadphase();
}
}
/**
* @property {object} config - The p2 World configuration object.
* @protected
*/
this.config = config;
/**
* @property {p2.World} world - The p2 World in which the simulation is run.
* @protected
*/
this.world = new p2.World(this.config);
/**
* @property {number} frameRate - The frame rate the world will be stepped at. Defaults to 1 / 60, but you can change here. Also see useElapsedTime property.
* @default
*/
this.frameRate = 1 / 60;
/**
* @property {boolean} useElapsedTime - If true the frameRate value will be ignored and instead p2 will step with the value of Game.Time.physicsElapsed, which is a delta time value.
* @default
*/
this.useElapsedTime = false;
/**
* @property {boolean} paused - The paused state of the P2 World.
* @default
*/
this.paused = false;
/**
* @property {array<Phaser.Physics.P2.Material>} materials - A local array of all created Materials.
* @protected
*/
this.materials = [];
/**
* @property {Phaser.Physics.P2.InversePointProxy} gravity - The gravity applied to all bodies each step.
*/
this.gravity = new Phaser.Physics.P2.InversePointProxy(this, this.world.gravity);
/**
* @property {object} walls - An object containing the 4 wall bodies that bound the physics world.
* This signal is dispatched when a new Body is added to the World.
*
* It sends 1 argument: `body` which is the `Phaser.Physics.P2.Body` that was added to the world.
*
* @property {Phaser.Signal} onBodyAdded
*/
this.onBodyAdded = new Phaser.Signal();
/**
* This signal is dispatched when a Body is removed to the World.
*
* It sends 1 argument: `body` which is the `Phaser.Physics.P2.Body` that was removed from the world.
*
* @property {Phaser.Signal} onBodyRemoved
*/
this.onBodyRemoved = new Phaser.Signal();
/**
* This signal is dispatched when a Spring is added to the World.
*
* It sends 1 argument: `spring` which is either a `Phaser.Physics.P2.Spring`, `p2.LinearSpring` or `p2.RotationalSpring` that was added to the world.
*
* @property {Phaser.Signal} onSpringAdded
*/
this.onSpringAdded = new Phaser.Signal();
/**
* This signal is dispatched when a Spring is removed from the World.
*
* It sends 1 argument: `spring` which is either a `Phaser.Physics.P2.Spring`, `p2.LinearSpring` or `p2.RotationalSpring` that was removed from the world.
*
* @property {Phaser.Signal} onSpringRemoved
*/
this.onSpringRemoved = new Phaser.Signal();
/**
* This signal is dispatched when a Constraint is added to the World.
*
* It sends 1 argument: `constraint` which is the `Phaser.Physics.P2.Constraint` that was added to the world.
*
* @property {Phaser.Signal} onConstraintAdded
*/
this.onConstraintAdded = new Phaser.Signal();
/**
* This signal is dispatched when a Constraint is removed from the World.
*
* It sends 1 argument: `constraint` which is the `Phaser.Physics.P2.Constraint` that was removed from the world.
*
* @property {Phaser.Signal} onConstraintRemoved
*/
this.onConstraintRemoved = new Phaser.Signal();
/**
* This signal is dispatched when a Contact Material is added to the World.
*
* It sends 1 argument: `material` which is the `Phaser.Physics.P2.ContactMaterial` that was added to the world.
* This will add a P2 Physics body into the removal list for the next step.
*
* @method Phaser.Physics.P2#removeBodyNextStep
* @param {Phaser.Physics.P2.Body} body - The body to remove at the start of the next step.
*/
removeBodyNextStep: function (body) {
this._toRemove.push(body);
},
/**
* Called at the start of the core update loop. Purges flagged bodies from the world.
*
* @method Phaser.Physics.P2#preUpdate
*/
preUpdate: function () {
var i = this._toRemove.length;
while (i--)
{
this.removeBody(this._toRemove[i]);
}
this._toRemove.length = 0;
},
/**
* This will create a P2 Physics body on the given game object or array of game objects.
* A game object can only have 1 physics body active at any one time, and it can't be changed until the object is destroyed.
* Note: When the game object is enabled for P2 physics it has its anchor x/y set to 0.5 so it becomes centered.
*
* @method Phaser.Physics.P2#enable
* @param {object|array|Phaser.Group} object - The game object to create the physics body on. Can also be an array or Group of objects, a body will be created on every child that has a `body` property.
* @param {boolean} [debug=false] - Create a debug object to go with this body?
* @param {boolean} [children=true] - Should a body be created on all children of this object? If true it will recurse down the display list as far as it can go.
*/
enable: function (object, debug, children) {
if (debug === undefined) { debug = false; }
if (children === undefined) { children = true; }
var i = 1;
if (Array.isArray(object))
{
i = object.length;
while (i--)
{
if (object[i] instanceof Phaser.Group)
{
// If it's a Group then we do it on the children regardless
this.enable(object[i].children, debug, children);
}
else
{
this.enableBody(object[i], debug);
if (children && object[i].hasOwnProperty('children') && object[i].children.length > 0)
{
this.enable(object[i], debug, true);
}
}
}
}
else
{
if (object instanceof Phaser.Group)
{
// If it's a Group then we do it on the children regardless
this.enable(object.children, debug, children);
}
else
{
this.enableBody(object, debug);
if (children && object.hasOwnProperty('children') && object.children.length > 0)
{
this.enable(object.children, debug, true);
}
}
}
},
/**
* Creates a P2 Physics body on the given game object.
* A game object can only have 1 physics body active at any one time, and it can't be changed until the body is nulled.
*
* @method Phaser.Physics.P2#enableBody
* @param {object} object - The game object to create the physics body on. A body will only be created if this object has a null `body` property.
* @param {boolean} debug - Create a debug object to go with this body?
*/
enableBody: function (object, debug) {
if (object.hasOwnProperty('body') && object.body === null)
{
object.body = new Phaser.Physics.P2.Body(this.game, object, object.x, object.y, 1);
object.body.debug = debug;
if (typeof object.anchor !== 'undefined') {
object.anchor.set(0.5);
}
}
},
/**
* Impact event handling is disabled by default. Enable it before any impact events will be dispatched.
* In a busy world hundreds of impact events can be generated every step, so only enable this if you cannot do what you need via beginContact or collision masks.
*
* @method Phaser.Physics.P2#setImpactEvents
* @param {boolean} state - Set to true to enable impact events, or false to disable.
* @param {function} callback - The callback that will receive the postBroadphase event data. It must return a boolean. Set to null to disable an existing callback.
* @param {object} context - The context under which the callback will be fired.
*/
setPostBroadphaseCallback: function (callback, context) {
* @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyA - First connected body.
* @param {Array} pivotA - The point relative to the center of mass of bodyA which bodyA is constrained to. The value is an array with 2 elements matching x and y, i.e: [32, 32].
* @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyB - Second connected body.
* @param {Array} pivotB - The point relative to the center of mass of bodyB which bodyB is constrained to. The value is an array with 2 elements matching x and y, i.e: [32, 32].
* @param {number} [maxForce=0] - The maximum force that should be applied to constrain the bodies.
* @param {Float32Array} [worldPivot=null] - A pivot point given in world coordinates. If specified, localPivotA and localPivotB are automatically computed from this value.
* @return {Phaser.Physics.P2.RevoluteConstraint} The constraint
*/
createRevoluteConstraint: function (bodyA, pivotA, bodyB, pivotB, maxForce, worldPivot) {
bodyA = this.getBody(bodyA);
bodyB = this.getBody(bodyB);
if (!bodyA || !bodyB)
{
console.warn('Cannot create Constraint, invalid body objects given');
* @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyA - First connected body.
* @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyB - Second connected body.
* @param {boolean} [lockRotation=true] - If set to false, bodyB will be free to rotate around its anchor point.
* @param {Array} [anchorA] - Body A's anchor point, defined in its own local frame. The value is an array with 2 elements matching x and y, i.e: [32, 32].
* @param {Array} [anchorB] - Body A's anchor point, defined in its own local frame. The value is an array with 2 elements matching x and y, i.e: [32, 32].
* @param {Array} [axis] - An axis, defined in body A frame, that body B's anchor point may slide along. The value is an array with 2 elements matching x and y, i.e: [32, 32].
* @param {number} [maxForce] - The maximum force that should be applied to constrain the bodies.
* @return {Phaser.Physics.P2.PrismaticConstraint} The constraint
*/
createPrismaticConstraint: function (bodyA, bodyB, lockRotation, anchorA, anchorB, axis, maxForce) {
bodyA = this.getBody(bodyA);
bodyB = this.getBody(bodyB);
if (!bodyA || !bodyB)
{
console.warn('Cannot create Constraint, invalid body objects given');
* Sets the given Material against all Shapes owned by all the Bodies in the given array.
*
* @method Phaser.Physics.P2#setMaterial
* @param {Phaser.Physics.P2.Material} material - The Material to be applied to the given Bodies.
* @param {array<Phaser.Physics.P2.Body>} bodies - An Array of Body objects that the given Material will be set on.
*/
setMaterial: function (material, bodies) {
var i = bodies.length;
while (i--)
{
bodies[i].setMaterial(material);
}
},
/**
* Creates a Material. Materials are applied to Shapes owned by a Body and can be set with Body.setMaterial().
* Materials are a way to control what happens when Shapes collide. Combine unique Materials together to create Contact Materials.
* Contact Materials have properties such as friction and restitution that allow for fine-grained collision control between different Materials.
*
* @method Phaser.Physics.P2#createMaterial
* @param {string} [name] - Optional name of the Material. Each Material has a unique ID but string names are handy for debugging.
* @param {Phaser.Physics.P2.Body} [body] - Optional Body. If given it will assign the newly created Material to the Body shapes.
* @return {Phaser.Physics.P2.Material} The Material that was created. This is also stored in Phaser.Physics.P2.materials.
*/
createMaterial: function (name, body) {
name = name || '';
var material = new Phaser.Physics.P2.Material(name);
this.materials.push(material);
if (typeof body !== 'undefined')
{
body.setMaterial(material);
}
return material;
},
/**
* Creates a Contact Material from the two given Materials. You can then edit the properties of the Contact Material directly.
*
* @method Phaser.Physics.P2#createContactMaterial
* @param {Phaser.Physics.P2.Material} [materialA] - The first Material to create the ContactMaterial from. If undefined it will create a new Material object first.
* @param {Phaser.Physics.P2.Material} [materialB] - The second Material to create the ContactMaterial from. If undefined it will create a new Material object first.
* @param {object} [options] - Material options object.
* @return {Phaser.Physics.P2.ContactMaterial} The Contact Material that was created.
*/
createContactMaterial: function (materialA, materialB, options) {
if (materialA === undefined) { materialA = this.createMaterial(); }
if (materialB === undefined) { materialB = this.createMaterial(); }
var contact = new Phaser.Physics.P2.ContactMaterial(materialA, materialB, options);
return this.addContactMaterial(contact);
},
/**
* Populates and returns an array with references to of all current Bodies in the world.
*
* @method Phaser.Physics.P2#getBodies
* @return {array<Phaser.Physics.P2.Body>} An array containing all current Bodies in the world.
*/
getBodies: function () {
var output = [];
var i = this.world.bodies.length;
while (i--)
{
output.push(this.world.bodies[i].parent);
}
return output;
},
/**
* Checks the given object to see if it has a p2.Body and if so returns it.
*
* @method Phaser.Physics.P2#getBody
* @param {object} object - The object to check for a p2.Body on.
* @return {p2.Body} The p2.Body, or null if not found.
*/
getBody: function (object) {
if (object instanceof p2.Body)
{
// Native p2 body
return object;
}
else if (object instanceof Phaser.Physics.P2.Body)
{
// Phaser P2 Body
return object.data;
}
else if (object['body'] && object['body'].type === Phaser.Physics.P2JS)
{
// Sprite, TileSprite, etc
return object.body.data;
}
return null;
},
/**
* Populates and returns an array of all current Springs in the world.
*
* @method Phaser.Physics.P2#getSprings
* @return {array<Phaser.Physics.P2.Spring>} An array containing all current Springs in the world.
*/
getSprings: function () {
var output = [];
var i = this.world.springs.length;
while (i--)
{
output.push(this.world.springs[i].parent);
}
return output;
},
/**
* Populates and returns an array of all current Constraints in the world.
* You will get an array of p2 constraints back. This can be of mixed types, for example the array may contain
* PrismaticConstraints, RevoluteConstraints or any other valid p2 constraint type.
*
* @method Phaser.Physics.P2#getConstraints
* @return {array<Phaser.Physics.P2.Constraint>} An array containing all current Constraints in the world.
*/
getConstraints: function () {
var output = [];
var i = this.world.constraints.length;
while (i--)
{
output.push(this.world.constraints[i]);
}
return output;
},
/**
* Test if a world point overlaps bodies. You will get an array of actual P2 bodies back. You can find out which Sprite a Body belongs to
* (if any) by checking the Body.parent.sprite property. Body.parent is a Phaser.Physics.P2.Body property.
*
* @method Phaser.Physics.P2#hitTest
* @param {Phaser.Point} worldPoint - Point to use for intersection tests. The points values must be in world (pixel) coordinates.
* @param {Array<Phaser.Physics.P2.Body|Phaser.Sprite|p2.Body>} [bodies] - A list of objects to check for intersection. If not given it will check Phaser.Physics.P2.world.bodies (i.e. all world bodies)
* @param {number} [precision=5] - Used for matching against particles and lines. Adds some margin to these infinitesimal objects.
* @param {boolean} [filterStatic=false] - If true all Static objects will be removed from the results array.
* @return {Array} Array of bodies that overlap the point.
*/
hitTest: function (worldPoint, bodies, precision, filterStatic) {
if (bodies === undefined) { bodies = this.world.bodies; }
if (precision === undefined) { precision = 5; }
if (filterStatic === undefined) { filterStatic = false; }
var physicsPosition = [ this.pxmi(worldPoint.x), this.pxmi(worldPoint.y) ];
var query = [];
var i = bodies.length;
while (i--)
{
if (bodies[i] instanceof Phaser.Physics.P2.Body && !(filterStatic && bodies[i].data.type === p2.Body.STATIC))
* @return {object} A JSON representation of the world.
*/
toJSON: function () {
return this.world.toJSON();
},
/**
* Creates a new Collision Group and optionally applies it to the given object.
* Collision Groups are handled using bitmasks, therefore you have a fixed limit you can create before you need to re-use older groups.
*
* @method Phaser.Physics.P2#createCollisionGroup
* @param {Phaser.Group|Phaser.Sprite} [object] - An optional Sprite or Group to apply the Collision Group to. If a Group is given it will be applied to all top-level children.
*/
createCollisionGroup: function (object) {
var bitmask = Math.pow(2, this._collisionGroupID);
var group = new Phaser.Physics.P2.CollisionGroup(bitmask);
this.collisionGroups.push(group);
if (object)
{
this.setCollisionGroup(object, group);
}
return group;
},
/**
* Sets the given CollisionGroup to be the collision group for all shapes in this Body, unless a shape is specified.
* Note that this resets the collisionMask and any previously set groups. See Body.collides() for appending them.
*
* @method Phaser.Physics.P2y#setCollisionGroup
* @param {Phaser.Group|Phaser.Sprite} object - A Sprite or Group to apply the Collision Group to. If a Group is given it will be applied to all top-level children.
* @param {Phaser.Physics.CollisionGroup} group - The Collision Group that this Bodies shapes will use.
*/
setCollisionGroup: function (object, group) {
if (object instanceof Phaser.Group)
{
for (var i = 0; i < object.total; i++)
{
if (object.children[i]['body'] && object.children[i]['body'].type === Phaser.Physics.P2JS)
{
object.children[i].body.setCollisionGroup(group);
}
}
}
else
{
object.body.setCollisionGroup(group);
}
},
/**
* Creates a linear spring, connecting two bodies. A spring can have a resting length, a stiffness and damping.
*
* @method Phaser.Physics.P2#createSpring
* @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyA - First connected body.
* @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyB - Second connected body.
* @param {number} [restLength=1] - Rest length of the spring. A number > 0.
* @param {number} [stiffness=100] - Stiffness of the spring. A number >= 0.
* @param {number} [damping=1] - Damping of the spring. A number >= 0.
* @param {Array} [worldA] - Where to hook the spring to body A in world coordinates. This value is an array by 2 elements, x and y, i.e: [32, 32].
* @param {Array} [worldB] - Where to hook the spring to body B in world coordinates. This value is an array by 2 elements, x and y, i.e: [32, 32].
* @param {Array} [localA] - Where to hook the spring to body A in local body coordinates. This value is an array by 2 elements, x and y, i.e: [32, 32].
* @param {Array} [localB] - Where to hook the spring to body B in local body coordinates. This value is an array by 2 elements, x and y, i.e: [32, 32].
* @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyA - First connected body.
* @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyB - Second connected body.
* @param {number} [restAngle] - The relative angle of bodies at which the spring is at rest. If not given, it's set to the current relative angle between the bodies.
* @param {number} [stiffness=100] - Stiffness of the spring. A number >= 0.
* @param {number} [damping=1] - Damping of the spring. A number >= 0.
* @return {Phaser.Physics.P2.RotationalSpring} The spring
*/
createRotationalSpring: function (bodyA, bodyB, restAngle, stiffness, damping) {
bodyA = this.getBody(bodyA);
bodyB = this.getBody(bodyB);
if (!bodyA || !bodyB)
{
console.warn('Cannot create Rotational Spring, invalid body objects given');
* @param {number} mass - The mass of the Body. A mass of 0 means a 'static' Body is created.
* @param {boolean} [addToWorld=false] - Automatically add this Body to the world? (usually false as it won't have any shapes on construction).
* @param {object} options - An object containing the build options:
* @param {boolean} [options.optimalDecomp=false] - Set to true if you need optimal decomposition. Warning: very slow for polygons with more than 10 vertices.
* @param {boolean} [options.skipSimpleCheck=false] - Set to true if you already know that the path is not intersecting itself.
* @param {boolean|number} [options.removeCollinearPoints=false] - Set to a number (angle threshold value) to remove collinear points, or false to keep all points.
* @param {(number[]|...number)} points - An array of 2d vectors that form the convex or concave polygon.
* Either [[0,0], [0,1],...] or a flat array of numbers that will be interpreted as [x,y, x,y, ...],
* or the arguments passed can be flat x,y values e.g. `setPolygon(options, x,y, x,y, x,y, ...)` where `x` and `y` are numbers.
* @return {Phaser.Physics.P2.Body} The body
*/
createBody: function (x, y, mass, addToWorld, options, data) {
if (addToWorld === undefined) { addToWorld = false; }
var body = new Phaser.Physics.P2.Body(this.game, null, x, y, mass);
if (data)
{
var result = body.addPolygon(options, data);
if (!result)
{
return false;
}
}
if (addToWorld)
{
this.world.addBody(body.data);
}
return body;
},
/**
* Creates a new Particle and adds it to the World.
*
* @method Phaser.Physics.P2#createParticle
* @param {number} x - The x coordinate of Body.
* @param {number} y - The y coordinate of Body.
* @param {number} mass - The mass of the Body. A mass of 0 means a 'static' Body is created.
* @param {boolean} [addToWorld=false] - Automatically add this Body to the world? (usually false as it won't have any shapes on construction).
* @param {object} options - An object containing the build options:
* @param {boolean} [options.optimalDecomp=false] - Set to true if you need optimal decomposition. Warning: very slow for polygons with more than 10 vertices.
* @param {boolean} [options.skipSimpleCheck=false] - Set to true if you already know that the path is not intersecting itself.
* @param {boolean|number} [options.removeCollinearPoints=false] - Set to a number (angle threshold value) to remove collinear points, or false to keep all points.
* @param {(number[]|...number)} points - An array of 2d vectors that form the convex or concave polygon.
* Either [[0,0], [0,1],...] or a flat array of numbers that will be interpreted as [x,y, x,y, ...],
* or the arguments passed can be flat x,y values e.g. `setPolygon(options, x,y, x,y, x,y, ...)` where `x` and `y` are numbers.
*/
createParticle: function (x, y, mass, addToWorld, options, data) {
if (addToWorld === undefined) { addToWorld = false; }
var body = new Phaser.Physics.P2.Body(this.game, null, x, y, mass);
if (data)
{
var result = body.addPolygon(options, data);
if (!result)
{
return false;
}
}
if (addToWorld)
{
this.world.addBody(body.data);
}
return body;
},
/**
* Converts all of the polylines objects inside a Tiled ObjectGroup into physics bodies that are added to the world.
* Note that the polylines must be created in such a way that they can withstand polygon decomposition.
* @param {Phaser.Tilemap} map - The Tilemap to get the map data from.
* @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to map.currentLayer.
*/
clearTilemapLayerBodies: function (map, layer) {
layer = map.getLayer(layer);
var i = map.layers[layer].bodies.length;
while (i--)
{
map.layers[layer].bodies[i].destroy();
}
map.layers[layer].bodies.length = 0;
},
/**
* Goes through all tiles in the given Tilemap and TilemapLayer and converts those set to collide into physics bodies.
* Only call this *after* you have specified all of the tiles you wish to collide with calls like Tilemap.setCollisionBetween, etc.
* Every time you call this method it will destroy any previously created bodies and remove them from the world.
* Therefore understand it's a very expensive operation and not to be done in a core game update loop.
*
* @method Phaser.Physics.P2#convertTilemap
* @param {Phaser.Tilemap} map - The Tilemap to get the map data from.
* @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to map.currentLayer.
* @param {boolean} [addToWorld=true] - If true it will automatically add each body to the world, otherwise it's up to you to do so.
* @param {boolean} [optimize=true] - If true adjacent colliding tiles will be combined into a single body to save processing. However it means you cannot perform specific Tile to Body collision responses.
* @return {array} An array of the Phaser.Physics.P2.Body objects that were created.
*/
convertTilemap: function (map, layer, addToWorld, optimize) {
layer = map.getLayer(layer);
if (addToWorld === undefined) { addToWorld = true; }
if (optimize === undefined) { optimize = true; }
// If the bodies array is already populated we need to nuke it
this.clearTilemapLayerBodies(map, layer);
var width = 0;
var sx = 0;
var sy = 0;
for (var y = 0, h = map.layers[layer].height; y < h; y++)
{
width = 0;
for (var x = 0, w = map.layers[layer].width; x < w; x++)
{
var tile = map.layers[layer].data[y][x];
if (tile && tile.index > -1 && tile.collides)
* @property {number} restitution - Default coefficient of restitution between colliding bodies. This value is used if no matching ContactMaterial is found for a Material pair.
* 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.