phaser/build/phaser.js
2014-03-10 11:08:07 +00:00

70440 lines
2 MiB

/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2014 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*
* @overview
*
* Phaser - http://www.phaser.io
*
* v2.0.0 "Aes Sedai" - Built: Mon Mar 10 2014 11:07:15
*
* By Richard Davey http://www.photonstorm.com @photonstorm
*
* Phaser is a fun, free and fast 2D game framework for making HTML5 games
* for desktop and mobile web browsers, supporting Canvas and WebGL.
*
* Phaser uses Pixi.js for rendering, created by Mat Groves http://matgroves.com @Doormat23
* Phaser uses p2.js for full-body physics, created by Stefan Hedman https://github.com/schteppe/p2.js @schteppe
* Phaser contains a port of N+ Physics, converted by Richard Davey, original by http://www.metanetsoftware.com
*
* Many thanks to Adam Saltsman (@ADAMATOMIC) for releasing Flixel, from which both Phaser
* and my love of framework development can be traced.
*
* Follow development at http://phaser.io and on our forum
*
* "If you want your children to be intelligent, read them fairy tales."
* "If you want them to be more intelligent, read them more fairy tales."
* -- Albert Einstein
*/
/**
* @author Mat Groves http://matgroves.com/ @Doormat23
*/
(function(){
var root = this;
/**
* @author Mat Groves http://matgroves.com/ @Doormat23
*/
/**
* @module PIXI
*/
var PIXI = PIXI || {};
/*
*
* This file contains a lot of pixi consts which are used across the rendering engine
* @class Consts
*/
PIXI.WEBGL_RENDERER = 0;
PIXI.CANVAS_RENDERER = 1;
// useful for testing against if your lib is using pixi.
PIXI.VERSION = "v1.5.0";
// the various blend modes supported by pixi
PIXI.blendModes = {
NORMAL:0,
ADD:1,
MULTIPLY:2,
SCREEN:3,
OVERLAY:4,
DARKEN:5,
LIGHTEN:6,
COLOR_DODGE:7,
COLOR_BURN:8,
HARD_LIGHT:9,
SOFT_LIGHT:10,
DIFFERENCE:11,
EXCLUSION:12,
HUE:13,
SATURATION:14,
COLOR:15,
LUMINOSITY:16
};
// the scale modes
PIXI.scaleModes = {
DEFAULT:0,
LINEAR:0,
NEAREST:1
};
// interaction frequency
PIXI.INTERACTION_FREQUENCY = 30;
PIXI.AUTO_PREVENT_DEFAULT = true;
PIXI.RAD_TO_DEG = 180 / Math.PI;
PIXI.DEG_TO_RAD = Math.PI / 180;
/**
* @author Mat Groves http://matgroves.com/ @Doormat23
*/
/**
* The Point object represents a location in a two-dimensional coordinate system, where x represents the horizontal axis and y represents the vertical axis.
*
* @class Point
* @constructor
* @param x {Number} position of the point on the x axis
* @param y {Number} position of the point on the y axis
*/
PIXI.Point = function(x, y)
{
/**
* @property x
* @type Number
* @default 0
*/
this.x = x || 0;
/**
* @property y
* @type Number
* @default 0
*/
this.y = y || 0;
};
/**
* Creates a clone of this point
*
* @method clone
* @return {Point} a copy of the point
*/
PIXI.Point.prototype.clone = function()
{
return new PIXI.Point(this.x, this.y);
};
// constructor
PIXI.Point.prototype.constructor = PIXI.Point;
PIXI.Point.prototype.set = function(x, y)
{
this.x = x || 0;
this.y = y || ( (y !== 0) ? this.x : 0 ) ;
};
/**
* @author Mat Groves http://matgroves.com/
*/
/**
* the Rectangle object is an area defined by its position, as indicated by its top-left corner point (x, y) and by its width and its height.
*
* @class Rectangle
* @constructor
* @param x {Number} The X coord of the upper-left corner of the rectangle
* @param y {Number} The Y coord of the upper-left corner of the rectangle
* @param width {Number} The overall width of this rectangle
* @param height {Number} The overall height of this rectangle
*/
PIXI.Rectangle = function(x, y, width, height)
{
/**
* @property x
* @type Number
* @default 0
*/
this.x = x || 0;
/**
* @property y
* @type Number
* @default 0
*/
this.y = y || 0;
/**
* @property width
* @type Number
* @default 0
*/
this.width = width || 0;
/**
* @property height
* @type Number
* @default 0
*/
this.height = height || 0;
};
/**
* Creates a clone of this Rectangle
*
* @method clone
* @return {Rectangle} a copy of the rectangle
*/
PIXI.Rectangle.prototype.clone = function()
{
return new PIXI.Rectangle(this.x, this.y, this.width, this.height);
};
/**
* Checks whether the x and y coordinates passed to this function are contained within this Rectangle
*
* @method contains
* @param x {Number} The X coordinate of the point to test
* @param y {Number} The Y coordinate of the point to test
* @return {Boolean} Whether the x/y coords are within this Rectangle
*/
PIXI.Rectangle.prototype.contains = function(x, y)
{
if(this.width <= 0 || this.height <= 0)
return false;
var x1 = this.x;
if(x >= x1 && x <= x1 + this.width)
{
var y1 = this.y;
if(y >= y1 && y <= y1 + this.height)
{
return true;
}
}
return false;
};
// constructor
PIXI.Rectangle.prototype.constructor = PIXI.Rectangle;
PIXI.EmptyRectangle = new PIXI.Rectangle(0,0,0,0);
/**
* @author Adrien Brault <adrien.brault@gmail.com>
*/
/**
* @class Polygon
* @constructor
* @param points* {Array<Point>|Array<Number>|Point...|Number...} This can be an array of Points that form the polygon,
* a flat array of numbers that will be interpreted as [x,y, x,y, ...], or the arguments passed can be
* all the points of the polygon e.g. `new PIXI.Polygon(new PIXI.Point(), new PIXI.Point(), ...)`, or the
* arguments passed can be flat x,y values e.g. `new PIXI.Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are
* Numbers.
*/
PIXI.Polygon = function(points)
{
//if points isn't an array, use arguments as the array
if(!(points instanceof Array))
points = Array.prototype.slice.call(arguments);
//if this is a flat array of numbers, convert it to points
if(typeof points[0] === 'number') {
var p = [];
for(var i = 0, il = points.length; i < il; i+=2) {
p.push(
new PIXI.Point(points[i], points[i + 1])
);
}
points = p;
}
this.points = points;
};
/**
* Creates a clone of this polygon
*
* @method clone
* @return {Polygon} a copy of the polygon
*/
PIXI.Polygon.prototype.clone = function()
{
var points = [];
for (var i=0; i<this.points.length; i++) {
points.push(this.points[i].clone());
}
return new PIXI.Polygon(points);
};
/**
* Checks whether the x and y coordinates passed to this function are contained within this polygon
*
* @method contains
* @param x {Number} The X coordinate of the point to test
* @param y {Number} The Y coordinate of the point to test
* @return {Boolean} Whether the x/y coordinates are within this polygon
*/
PIXI.Polygon.prototype.contains = function(x, y)
{
var inside = false;
// use some raycasting to test hits
// https://github.com/substack/point-in-polygon/blob/master/index.js
for(var i = 0, j = this.points.length - 1; i < this.points.length; j = i++) {
var xi = this.points[i].x, yi = this.points[i].y,
xj = this.points[j].x, yj = this.points[j].y,
intersect = ((yi > y) !== (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi);
if(intersect) inside = !inside;
}
return inside;
};
// constructor
PIXI.Polygon.prototype.constructor = PIXI.Polygon;
/**
* @author Chad Engler <chad@pantherdev.com>
*/
/**
* The Circle object can be used to specify a hit area for displayObjects
*
* @class Circle
* @constructor
* @param x {Number} The X coordinate of the upper-left corner of the framing rectangle of this circle
* @param y {Number} The Y coordinate of the upper-left corner of the framing rectangle of this circle
* @param radius {Number} The radius of the circle
*/
PIXI.Circle = function(x, y, radius)
{
/**
* @property x
* @type Number
* @default 0
*/
this.x = x || 0;
/**
* @property y
* @type Number
* @default 0
*/
this.y = y || 0;
/**
* @property radius
* @type Number
* @default 0
*/
this.radius = radius || 0;
};
/**
* Creates a clone of this Circle instance
*
* @method clone
* @return {Circle} a copy of the polygon
*/
PIXI.Circle.prototype.clone = function()
{
return new PIXI.Circle(this.x, this.y, this.radius);
};
/**
* Checks whether the x, and y coordinates passed to this function are contained within this circle
*
* @method contains
* @param x {Number} The X coordinate of the point to test
* @param y {Number} The Y coordinate of the point to test
* @return {Boolean} Whether the x/y coordinates are within this polygon
*/
PIXI.Circle.prototype.contains = function(x, y)
{
if(this.radius <= 0)
return false;
var dx = (this.x - x),
dy = (this.y - y),
r2 = this.radius * this.radius;
dx *= dx;
dy *= dy;
return (dx + dy <= r2);
};
// constructor
PIXI.Circle.prototype.constructor = PIXI.Circle;
/**
* @author Chad Engler <chad@pantherdev.com>
*/
/**
* The Ellipse object can be used to specify a hit area for displayObjects
*
* @class Ellipse
* @constructor
* @param x {Number} The X coordinate of the upper-left corner of the framing rectangle of this ellipse
* @param y {Number} The Y coordinate of the upper-left corner of the framing rectangle of this ellipse
* @param width {Number} The overall width of this ellipse
* @param height {Number} The overall height of this ellipse
*/
PIXI.Ellipse = function(x, y, width, height)
{
/**
* @property x
* @type Number
* @default 0
*/
this.x = x || 0;
/**
* @property y
* @type Number
* @default 0
*/
this.y = y || 0;
/**
* @property width
* @type Number
* @default 0
*/
this.width = width || 0;
/**
* @property height
* @type Number
* @default 0
*/
this.height = height || 0;
};
/**
* Creates a clone of this Ellipse instance
*
* @method clone
* @return {Ellipse} a copy of the ellipse
*/
PIXI.Ellipse.prototype.clone = function()
{
return new PIXI.Ellipse(this.x, this.y, this.width, this.height);
};
/**
* Checks whether the x and y coordinates passed to this function are contained within this ellipse
*
* @method contains
* @param x {Number} The X coordinate of the point to test
* @param y {Number} The Y coordinate of the point to test
* @return {Boolean} Whether the x/y coords are within this ellipse
*/
PIXI.Ellipse.prototype.contains = function(x, y)
{
if(this.width <= 0 || this.height <= 0)
return false;
//normalize the coords to an ellipse with center 0,0
var normx = ((x - this.x) / this.width),
normy = ((y - this.y) / this.height);
normx *= normx;
normy *= normy;
return (normx + normy <= 1);
};
/**
* Returns the framing rectangle of the ellipse as a PIXI.Rectangle object
*
* @method getBounds
* @return {Rectangle} the framing rectangle
*/
PIXI.Ellipse.prototype.getBounds = function()
{
return new PIXI.Rectangle(this.x, this.y, this.width, this.height);
};
// constructor
PIXI.Ellipse.prototype.constructor = PIXI.Ellipse;
/**
* @author Mat Groves http://matgroves.com/ @Doormat23
*/
PIXI.determineMatrixArrayType = function() {
return (typeof Float32Array !== 'undefined') ? Float32Array : Array;
};
/*
* @class Matrix2
* The Matrix2 class will choose the best type of array to use between
* a regular javascript Array and a Float32Array if the latter is available
*
*/
PIXI.Matrix2 = PIXI.determineMatrixArrayType();
/*
* @class Matrix
* The Matrix class is now an object, which makes it a lot faster,
* here is a representation of it :
* | a | b | tx|
* | c | c | ty|
* | 0 | 0 | 1 |
*
*/
PIXI.Matrix = function()
{
this.a = 1;
this.b = 0;
this.c = 0;
this.d = 1;
this.tx = 0;
this.ty = 0;
};
/**
* Creates a pixi matrix object based on the array given as a parameter
*
* @method fromArray
* @param array {Array} The array that the matrix will be filled with
*/
PIXI.Matrix.prototype.fromArray = function(array)
{
this.a = array[0];
this.b = array[1];
this.c = array[3];
this.d = array[4];
this.tx = array[2];
this.ty = array[5];
};
/**
* Creates an array from the current Matrix object
*
* @method toArray
* @param transpose {Boolean} Whether we need to transpose the matrix or not
* @return array {Array} the newly created array which contains the matrix
*/
PIXI.Matrix.prototype.toArray = function(transpose)
{
if(!this.array) this.array = new Float32Array(9);
var array = this.array;
if(transpose)
{
this.array[0] = this.a;
this.array[1] = this.c;
this.array[2] = 0;
this.array[3] = this.b;
this.array[4] = this.d;
this.array[5] = 0;
this.array[6] = this.tx;
this.array[7] = this.ty;
this.array[8] = 1;
}
else
{
this.array[0] = this.a;
this.array[1] = this.b;
this.array[2] = this.tx;
this.array[3] = this.c;
this.array[4] = this.d;
this.array[5] = this.ty;
this.array[6] = 0;
this.array[7] = 0;
this.array[8] = 1;
}
return array;//[this.a, this.b, this.tx, this.c, this.d, this.ty, 0, 0, 1];
};
PIXI.identityMatrix = new PIXI.Matrix();
/**
* @author Mat Groves http://matgroves.com/ @Doormat23
*/
/**
* The base class for all objects that are rendered on the screen.
*
* @class DisplayObject
* @constructor
*/
PIXI.DisplayObject = function()
{
/**
* The coordinate of the object relative to the local coordinates of the parent.
*
* @property position
* @type Point
*/
this.position = new PIXI.Point();
/**
* The scale factor of the object.
*
* @property scale
* @type Point
*/
this.scale = new PIXI.Point(1,1);//{x:1, y:1};
/**
* The pivot point of the displayObject that it rotates around
*
* @property pivot
* @type Point
*/
this.pivot = new PIXI.Point(0,0);
/**
* The rotation of the object in radians.
*
* @property rotation
* @type Number
*/
this.rotation = 0;
/**
* The opacity of the object.
*
* @property alpha
* @type Number
*/
this.alpha = 1;
/**
* The visibility of the object.
*
* @property visible
* @type Boolean
*/
this.visible = true;
/**
* This is the defined area that will pick up mouse / touch events. It is null by default.
* Setting it is a neat way of optimising the hitTest function that the interactionManager will use (as it will not need to hit test all the children)
*
* @property hitArea
* @type Rectangle|Circle|Ellipse|Polygon
*/
this.hitArea = null;
/**
* This is used to indicate if the displayObject should display a mouse hand cursor on rollover
*
* @property buttonMode
* @type Boolean
*/
this.buttonMode = false;
/**
* Can this object be rendered
*
* @property renderable
* @type Boolean
*/
this.renderable = false;
/**
* [read-only] The display object container that contains this display object.
*
* @property parent
* @type DisplayObjectContainer
* @readOnly
*/
this.parent = null;
/**
* [read-only] The stage the display object is connected to, or undefined if it is not connected to the stage.
*
* @property stage
* @type Stage
* @readOnly
*/
this.stage = null;
/**
* [read-only] The multiplied alpha of the displayObject
*
* @property worldAlpha
* @type Number
* @readOnly
*/
this.worldAlpha = 1;
/**
* [read-only] Whether or not the object is interactive, do not toggle directly! use the `interactive` property
*
* @property _interactive
* @type Boolean
* @readOnly
* @private
*/
this._interactive = false;
/**
* This is the cursor that will be used when the mouse is over this object. To enable this the element must have interaction = true and buttonMode = true
*
* @property defaultCursor
* @type String
*
*/
this.defaultCursor = 'pointer';
/**
* [read-only] Current transform of the object based on world (parent) factors
*
* @property worldTransform
* @type Mat3
* @readOnly
* @private
*/
this.worldTransform = new PIXI.Matrix();
/**
* [NYI] Unknown
*
* @property color
* @type Array<>
* @private
*/
this.color = [];
/**
* [NYI] Holds whether or not this object is dynamic, for rendering optimization
*
* @property dynamic
* @type Boolean
* @private
*/
this.dynamic = true;
// cached sin rotation and cos rotation
this._sr = 0;
this._cr = 1;
/**
* The area the filter is applied to
*
* @property filterArea
* @type Rectangle
*/
this.filterArea = new PIXI.Rectangle(0,0,1,1);
/**
* The original, cached bounds of the object
*
* @property _bounds
* @type Rectangle
* @private
*/
this._bounds = new PIXI.Rectangle(0, 0, 1, 1);
/**
* The most up-to-date bounds of the object
*
* @property _currentBounds
* @type Rectangle
* @private
*/
this._currentBounds = null;
/**
* The original, cached mask of the object
*
* @property _currentBounds
* @type Rectangle
* @private
*/
this._mask = null;
this._cacheAsBitmap = false;
this._cacheIsDirty = false;
/*
* MOUSE Callbacks
*/
/**
* A callback that is used when the users clicks on the displayObject with their mouse
* @method click
* @param interactionData {InteractionData}
*/
/**
* A callback that is used when the user clicks the mouse down over the sprite
* @method mousedown
* @param interactionData {InteractionData}
*/
/**
* A callback that is used when the user releases the mouse that was over the displayObject
* for this callback to be fired the mouse must have been pressed down over the displayObject
* @method mouseup
* @param interactionData {InteractionData}
*/
/**
* A callback that is used when the user releases the mouse that was over the displayObject but is no longer over the displayObject
* for this callback to be fired, The touch must have started over the displayObject
* @method mouseupoutside
* @param interactionData {InteractionData}
*/
/**
* A callback that is used when the users mouse rolls over the displayObject
* @method mouseover
* @param interactionData {InteractionData}
*/
/**
* A callback that is used when the users mouse leaves the displayObject
* @method mouseout
* @param interactionData {InteractionData}
*/
/*
* TOUCH Callbacks
*/
/**
* A callback that is used when the users taps on the sprite with their finger
* basically a touch version of click
* @method tap
* @param interactionData {InteractionData}
*/
/**
* A callback that is used when the user touches over the displayObject
* @method touchstart
* @param interactionData {InteractionData}
*/
/**
* A callback that is used when the user releases a touch over the displayObject
* @method touchend
* @param interactionData {InteractionData}
*/
/**
* A callback that is used when the user releases the touch that was over the displayObject
* for this callback to be fired, The touch must have started over the sprite
* @method touchendoutside
* @param interactionData {InteractionData}
*/
};
// constructor
PIXI.DisplayObject.prototype.constructor = PIXI.DisplayObject;
/**
* [Deprecated] Indicates if the sprite will have touch and mouse interactivity. It is false by default
* Instead of using this function you can now simply set the interactive property to true or false
*
* @method setInteractive
* @param interactive {Boolean}
* @deprecated Simply set the `interactive` property directly
*/
PIXI.DisplayObject.prototype.setInteractive = function(interactive)
{
this.interactive = interactive;
};
/**
* Indicates if the sprite will have touch and mouse interactivity. It is false by default
*
* @property interactive
* @type Boolean
* @default false
*/
Object.defineProperty(PIXI.DisplayObject.prototype, 'interactive', {
get: function() {
return this._interactive;
},
set: function(value) {
this._interactive = value;
// TODO more to be done here..
// need to sort out a re-crawl!
if(this.stage)this.stage.dirty = true;
}
});
/**
* [read-only] Indicates if the sprite is globaly visible.
*
* @property worldVisible
* @type Boolean
*/
Object.defineProperty(PIXI.DisplayObject.prototype, 'worldVisible', {
get: function() {
var item = this;
do
{
if(!item.visible)return false;
item = item.parent;
}
while(item);
return true;
}
});
/**
* Sets a mask for the displayObject. A mask is an object that limits the visibility of an object to the shape of the mask applied to it.
* In PIXI a regular mask must be a PIXI.Graphics object. This allows for much faster masking in canvas as it utilises shape clipping.
* To remove a mask, set this property to null.
*
* @property mask
* @type Graphics
*/
Object.defineProperty(PIXI.DisplayObject.prototype, 'mask', {
get: function() {
return this._mask;
},
set: function(value) {
if(this._mask)this._mask.isMask = false;
this._mask = value;
if(this._mask)this._mask.isMask = true;
}
});
/**
* Sets the filters for the displayObject.
* * IMPORTANT: This is a webGL only feature and will be ignored by the canvas renderer.
* To remove filters simply set this property to 'null'
* @property filters
* @type Array An array of filters
*/
Object.defineProperty(PIXI.DisplayObject.prototype, 'filters', {
get: function() {
return this._filters;
},
set: function(value) {
if(value)
{
// now put all the passes in one place..
var passes = [];
for (var i = 0; i < value.length; i++)
{
var filterPasses = value[i].passes;
for (var j = 0; j < filterPasses.length; j++)
{
passes.push(filterPasses[j]);
}
}
// TODO change this as it is legacy
this._filterBlock = {target:this, filterPasses:passes};
}
this._filters = value;
}
});
Object.defineProperty(PIXI.DisplayObject.prototype, 'cacheAsBitmap', {
get: function() {
return this._cacheAsBitmap;
},
set: function(value) {
if(this._cacheAsBitmap === value)return;
if(value)
{
//this._cacheIsDirty = true;
this._generateCachedSprite();
}
else
{
this._destroyCachedSprite();
}
this._cacheAsBitmap = value;
}
});
/*
* Updates the object transform for rendering
*
* @method updateTransform
* @private
*/
PIXI.DisplayObject.prototype.updateTransform = function()
{
// TODO OPTIMIZE THIS!! with dirty
if(this.rotation !== this.rotationCache)
{
this.rotationCache = this.rotation;
this._sr = Math.sin(this.rotation);
this._cr = Math.cos(this.rotation);
}
// var localTransform = this.localTransform//.toArray();
var parentTransform = this.parent.worldTransform;//.toArray();
var worldTransform = this.worldTransform;//.toArray();
var px = this.pivot.x;
var py = this.pivot.y;
var a00 = this._cr * this.scale.x,
a01 = -this._sr * this.scale.y,
a10 = this._sr * this.scale.x,
a11 = this._cr * this.scale.y,
a02 = this.position.x - a00 * px - py * a01,
a12 = this.position.y - a11 * py - px * a10,
b00 = parentTransform.a, b01 = parentTransform.b,
b10 = parentTransform.c, b11 = parentTransform.d;
worldTransform.a = b00 * a00 + b01 * a10;
worldTransform.b = b00 * a01 + b01 * a11;
worldTransform.tx = b00 * a02 + b01 * a12 + parentTransform.tx;
worldTransform.c = b10 * a00 + b11 * a10;
worldTransform.d = b10 * a01 + b11 * a11;
worldTransform.ty = b10 * a02 + b11 * a12 + parentTransform.ty;
this.worldAlpha = this.alpha * this.parent.worldAlpha;
};
/**
* Retrieves the bounds of the displayObject as a rectangle object
*
* @method getBounds
* @return {Rectangle} the rectangular bounding area
*/
PIXI.DisplayObject.prototype.getBounds = function( matrix )
{
matrix = matrix;//just to get passed js hinting (and preserve inheritance)
return PIXI.EmptyRectangle;
};
/**
* Retrieves the local bounds of the displayObject as a rectangle object
*
* @method getLocalBounds
* @return {Rectangle} the rectangular bounding area
*/
PIXI.DisplayObject.prototype.getLocalBounds = function()
{
return this.getBounds(PIXI.identityMatrix);///PIXI.EmptyRectangle();
};
/**
* Sets the object's stage reference, the stage this object is connected to
*
* @method setStageReference
* @param stage {Stage} the stage that the object will have as its current stage reference
*/
PIXI.DisplayObject.prototype.setStageReference = function(stage)
{
this.stage = stage;
if(this._interactive)this.stage.dirty = true;
};
PIXI.DisplayObject.prototype.generateTexture = function(renderer)
{
var bounds = this.getLocalBounds();
var renderTexture = new PIXI.RenderTexture(bounds.width | 0, bounds.height | 0, renderer);
renderTexture.render(this);
return renderTexture;
};
PIXI.DisplayObject.prototype.updateCache = function()
{
this._generateCachedSprite();
};
PIXI.DisplayObject.prototype._renderCachedSprite = function(renderSession)
{
if(renderSession.gl)
{
PIXI.Sprite.prototype._renderWebGL.call(this._cachedSprite, renderSession);
}
else
{
PIXI.Sprite.prototype._renderCanvas.call(this._cachedSprite, renderSession);
}
};
PIXI.DisplayObject.prototype._generateCachedSprite = function()//renderSession)
{
this._cacheAsBitmap = false;
var bounds = this.getLocalBounds();
if(!this._cachedSprite)
{
var renderTexture = new PIXI.RenderTexture(bounds.width | 0, bounds.height | 0);//, renderSession.renderer);
this._cachedSprite = new PIXI.Sprite(renderTexture);
this._cachedSprite.worldTransform = this.worldTransform;
}
else
{
this._cachedSprite.texture.resize(bounds.width | 0, bounds.height | 0);
}
//REMOVE filter!
var tempFilters = this._filters;
this._filters = null;
this._cachedSprite.filters = tempFilters;
this._cachedSprite.texture.render(this);
this._filters = tempFilters;
this._cacheAsBitmap = true;
};
/**
* Renders the object using the WebGL renderer
*
* @method _renderWebGL
* @param renderSession {RenderSession}
* @private
*/
PIXI.DisplayObject.prototype._destroyCachedSprite = function()
{
if(!this._cachedSprite)return;
this._cachedSprite.texture.destroy(true);
// console.log("DESTROY")
// let the gc collect the unused sprite
// TODO could be object pooled!
this._cachedSprite = null;
};
PIXI.DisplayObject.prototype._renderWebGL = function(renderSession)
{
// OVERWRITE;
// this line is just here to pass jshinting :)
renderSession = renderSession;
};
/**
* Renders the object using the Canvas renderer
*
* @method _renderCanvas
* @param renderSession {RenderSession}
* @private
*/
PIXI.DisplayObject.prototype._renderCanvas = function(renderSession)
{
// OVERWRITE;
// this line is just here to pass jshinting :)
renderSession = renderSession;
};
/**
* The position of the displayObject on the x axis relative to the local coordinates of the parent.
*
* @property x
* @type Number
*/
Object.defineProperty(PIXI.DisplayObject.prototype, 'x', {
get: function() {
return this.position.x;
},
set: function(value) {
this.position.x = value;
}
});
/**
* The position of the displayObject on the y axis relative to the local coordinates of the parent.
*
* @property y
* @type Number
*/
Object.defineProperty(PIXI.DisplayObject.prototype, 'y', {
get: function() {
return this.position.y;
},
set: function(value) {
this.position.y = value;
}
});
/**
* @author Mat Groves http://matgroves.com/ @Doormat23
*/
/**
* A DisplayObjectContainer represents a collection of display objects.
* It is the base class of all display objects that act as a container for other objects.
*
* @class DisplayObjectContainer
* @extends DisplayObject
* @constructor
*/
PIXI.DisplayObjectContainer = function()
{
PIXI.DisplayObject.call( this );
/**
* [read-only] The array of children of this container.
*
* @property children
* @type Array<DisplayObject>
* @readOnly
*/
this.children = [];
};
// constructor
PIXI.DisplayObjectContainer.prototype = Object.create( PIXI.DisplayObject.prototype );
PIXI.DisplayObjectContainer.prototype.constructor = PIXI.DisplayObjectContainer;
/**
* The width of the displayObjectContainer, setting this will actually modify the scale to achieve the value set
*
* @property width
* @type Number
*/
/*
Object.defineProperty(PIXI.DisplayObjectContainer.prototype, 'width', {
get: function() {
return this.scale.x * this.getLocalBounds().width;
},
set: function(value) {
this.scale.x = value / (this.getLocalBounds().width/this.scale.x);
this._width = value;
}
});
*/
/**
* The height of the displayObjectContainer, setting this will actually modify the scale to achieve the value set
*
* @property height
* @type Number
*/
/*
Object.defineProperty(PIXI.DisplayObjectContainer.prototype, 'height', {
get: function() {
return this.scale.y * this.getLocalBounds().height;
},
set: function(value) {
this.scale.y = value / (this.getLocalBounds().height/this.scale.y);
this._height = value;
}
});
*/
/**
* Adds a child to the container.
*
* @method addChild
* @param child {DisplayObject} The DisplayObject to add to the container
*/
PIXI.DisplayObjectContainer.prototype.addChild = function(child)
{
this.addChildAt(child, this.children.length);
};
/**
* Adds a child to the container at a specified index. If the index is out of bounds an error will be thrown
*
* @method addChildAt
* @param child {DisplayObject} The child to add
* @param index {Number} The index to place the child in
*/
PIXI.DisplayObjectContainer.prototype.addChildAt = function(child, index)
{
if(index >= 0 && index <= this.children.length)
{
if(child.parent)
{
child.parent.removeChild(child);
}
child.parent = this;
this.children.splice(index, 0, child);
if(this.stage)child.setStageReference(this.stage);
}
else
{
throw new Error(child + ' The index '+ index +' supplied is out of bounds ' + this.children.length);
}
};
/**
* [NYI] Swaps the depth of 2 displayObjects
*
* @method swapChildren
* @param child {DisplayObject}
* @param child2 {DisplayObject}
* @private
*/
PIXI.DisplayObjectContainer.prototype.swapChildren = function(child, child2)
{
if(child === child2) {
return;
}
var index1 = this.children.indexOf(child);
var index2 = this.children.indexOf(child2);
if(index1 < 0 || index2 < 0) {
throw new Error('swapChildren: Both the supplied DisplayObjects must be a child of the caller.');
}
this.children[index1] = child2;
this.children[index2] = child;
};
/**
* Returns the child at the specified index
*
* @method getChildAt
* @param index {Number} The index to get the child from
*/
PIXI.DisplayObjectContainer.prototype.getChildAt = function(index)
{
if(index >= 0 && index < this.children.length)
{
return this.children[index];
}
else
{
throw new Error('The supplied DisplayObjects must be a child of the caller ' + this);
}
};
/**
* Removes a child from the container.
*
* @method removeChild
* @param child {DisplayObject} The DisplayObject to remove
*/
PIXI.DisplayObjectContainer.prototype.removeChild = function(child)
{
var index = this.children.indexOf( child );
if ( index !== -1 )
{
// update the stage reference..
if(this.stage)child.removeStageReference();
child.parent = undefined;
this.children.splice( index, 1 );
}
else
{
throw new Error(child + ' The supplied DisplayObject must be a child of the caller ' + this);
}
};
/**
* Removes all the children
*
* @method removeAll
* NOT tested yet
*/
/* PIXI.DisplayObjectContainer.prototype.removeAll = function()
{
for(var i = 0 , j = this.children.length; i < j; i++)
{
this.removeChild(this.children[i]);
}
};
*/
/*
* Updates the container's childrens transform for rendering
*
* @method updateTransform
* @private
*/
PIXI.DisplayObjectContainer.prototype.updateTransform = function()
{
//this._currentBounds = null;
if(!this.visible)return;
PIXI.DisplayObject.prototype.updateTransform.call( this );
if(this._cacheAsBitmap)return;
for(var i=0,j=this.children.length; i<j; i++)
{
this.children[i].updateTransform();
}
};
/**
* Retrieves the bounds of the displayObjectContainer as a rectangle object
*
* @method getBounds
* @return {Rectangle} the rectangular bounding area
*/
PIXI.DisplayObjectContainer.prototype.getBounds = function(matrix)
{
if(this.children.length === 0)return PIXI.EmptyRectangle;
// TODO the bounds have already been calculated this render session so return what we have
if(matrix)
{
var matrixCache = this.worldTransform;
this.worldTransform = matrix;
this.updateTransform();
this.worldTransform = matrixCache;
}
var minX = Infinity;
var minY = Infinity;
var maxX = -Infinity;
var maxY = -Infinity;
var childBounds;
var childMaxX;
var childMaxY;
var childVisible = false;
for(var i=0,j=this.children.length; i<j; i++)
{
var child = this.children[i];
if(!child.visible)continue;
childVisible = true;
childBounds = this.children[i].getBounds( matrix );
minX = minX < childBounds.x ? minX : childBounds.x;
minY = minY < childBounds.y ? minY : childBounds.y;
childMaxX = childBounds.width + childBounds.x;
childMaxY = childBounds.height + childBounds.y;
maxX = maxX > childMaxX ? maxX : childMaxX;
maxY = maxY > childMaxY ? maxY : childMaxY;
}
if(!childVisible)
return PIXI.EmptyRectangle;
var bounds = this._bounds;
bounds.x = minX;
bounds.y = minY;
bounds.width = maxX - minX;
bounds.height = maxY - minY;
// TODO: store a reference so that if this function gets called again in the render cycle we do not have to recalculate
//this._currentBounds = bounds;
return bounds;
};
PIXI.DisplayObjectContainer.prototype.getLocalBounds = function()
{
var matrixCache = this.worldTransform;
this.worldTransform = PIXI.identityMatrix;
for(var i=0,j=this.children.length; i<j; i++)
{
this.children[i].updateTransform();
}
var bounds = this.getBounds();
this.worldTransform = matrixCache;
return bounds;
};
/**
* Sets the container's stage reference, the stage this object is connected to
*
* @method setStageReference
* @param stage {Stage} the stage that the container will have as its current stage reference
*/
PIXI.DisplayObjectContainer.prototype.setStageReference = function(stage)
{
this.stage = stage;
if(this._interactive)this.stage.dirty = true;
for(var i=0,j=this.children.length; i<j; i++)
{
var child = this.children[i];
child.setStageReference(stage);
}
};
/**
* removes the current stage reference of the container
*
* @method removeStageReference
*/
PIXI.DisplayObjectContainer.prototype.removeStageReference = function()
{
for(var i=0,j=this.children.length; i<j; i++)
{
var child = this.children[i];
child.removeStageReference();
}
if(this._interactive)this.stage.dirty = true;
this.stage = null;
};
/**
* Renders the object using the WebGL renderer
*
* @method _renderWebGL
* @param renderSession {RenderSession}
* @private
*/
PIXI.DisplayObjectContainer.prototype._renderWebGL = function(renderSession)
{
if(!this.visible || this.alpha <= 0)return;
if(this._cacheAsBitmap)
{
this._renderCachedSprite(renderSession);
return;
}
var i,j;
if(this._mask || this._filters)
{
if(this._mask)
{
renderSession.spriteBatch.stop();
renderSession.maskManager.pushMask(this.mask, renderSession);
renderSession.spriteBatch.start();
}
if(this._filters)
{
renderSession.spriteBatch.flush();
renderSession.filterManager.pushFilter(this._filterBlock);
}
// simple render children!
for(i=0,j=this.children.length; i<j; i++)
{
this.children[i]._renderWebGL(renderSession);
}
renderSession.spriteBatch.stop();
if(this._filters)renderSession.filterManager.popFilter();
if(this._mask)renderSession.maskManager.popMask(renderSession);
renderSession.spriteBatch.start();
}
else
{
// simple render children!
for(i=0,j=this.children.length; i<j; i++)
{
this.children[i]._renderWebGL(renderSession);
}
}
};
/**
* Renders the object using the Canvas renderer
*
* @method _renderCanvas
* @param renderSession {RenderSession}
* @private
*/
PIXI.DisplayObjectContainer.prototype._renderCanvas = function(renderSession)
{
if(this.visible === false || this.alpha === 0)return;
if(this._cacheAsBitmap)
{
this._renderCachedSprite(renderSession);
return;
}
if(this._mask)
{
renderSession.maskManager.pushMask(this._mask, renderSession.context);
}
for(var i=0,j=this.children.length; i<j; i++)
{
var child = this.children[i];
child._renderCanvas(renderSession);
}
if(this._mask)
{
renderSession.maskManager.popMask(renderSession.context);
}
};
/**
* @author Mat Groves http://matgroves.com/ @Doormat23
*/
/**
* The Sprite object is the base for all textured objects that are rendered to the screen
*
* @class Sprite
* @extends DisplayObjectContainer
* @constructor
* @param texture {Texture} The texture for this sprite
*
* A sprite can be created directly from an image like this :
* var sprite = nex PIXI.Sprite.FromImage('assets/image.png');
* yourStage.addChild(sprite);
* then obviously don't forget to add it to the stage you have already created
*/
PIXI.Sprite = function(texture)
{
PIXI.DisplayObjectContainer.call( this );
/**
* The anchor sets the origin point of the texture.
* The default is 0,0 this means the texture's origin is the top left
* Setting than anchor to 0.5,0.5 means the textures origin is centred
* Setting the anchor to 1,1 would mean the textures origin points will be the bottom right corner
*
* @property anchor
* @type Point
*/
this.anchor = new PIXI.Point();
/**
* The texture that the sprite is using
*
* @property texture
* @type Texture
*/
this.texture = texture;
/**
* The width of the sprite (this is initially set by the texture)
*
* @property _width
* @type Number
* @private
*/
this._width = 0;
/**
* The height of the sprite (this is initially set by the texture)
*
* @property _height
* @type Number
* @private
*/
this._height = 0;
/**
* The tint applied to the sprite. This is a hex value
*
* @property tint
* @type Number
* @default 0xFFFFFF
*/
this.tint = 0xFFFFFF;// * Math.random();
/**
* The blend mode to be applied to the sprite
*
* @property blendMode
* @type Number
* @default PIXI.blendModes.NORMAL;
*/
this.blendMode = PIXI.blendModes.NORMAL;
if(texture.baseTexture.hasLoaded)
{
this.onTextureUpdate();
}
else
{
this.onTextureUpdateBind = this.onTextureUpdate.bind(this);
this.texture.addEventListener( 'update', this.onTextureUpdateBind );
}
this.renderable = true;
};
// constructor
PIXI.Sprite.prototype = Object.create( PIXI.DisplayObjectContainer.prototype );
PIXI.Sprite.prototype.constructor = PIXI.Sprite;
/**
* The width of the sprite, setting this will actually modify the scale to achieve the value set
*
* @property width
* @type Number
*/
Object.defineProperty(PIXI.Sprite.prototype, 'width', {
get: function() {
return this.scale.x * this.texture.frame.width;
},
set: function(value) {
this.scale.x = value / this.texture.frame.width;
this._width = value;
}
});
/**
* The height of the sprite, setting this will actually modify the scale to achieve the value set
*
* @property height
* @type Number
*/
Object.defineProperty(PIXI.Sprite.prototype, 'height', {
get: function() {
return this.scale.y * this.texture.frame.height;
},
set: function(value) {
this.scale.y = value / this.texture.frame.height;
this._height = value;
}
});
/**
* Sets the texture of the sprite
*
* @method setTexture
* @param texture {Texture} The PIXI texture that is displayed by the sprite
*/
PIXI.Sprite.prototype.setTexture = function(texture)
{
// stop current texture;
if(this.texture.baseTexture !== texture.baseTexture)
{
this.textureChange = true;
this.texture = texture;
}
else
{
this.texture = texture;
}
this.cachedTint = 0xFFFFFF;
this.updateFrame = true;
};
/**
* When the texture is updated, this event will fire to update the scale and frame
*
* @method onTextureUpdate
* @param event
* @private
*/
PIXI.Sprite.prototype.onTextureUpdate = function()
{
// so if _width is 0 then width was not set..
if(this._width)this.scale.x = this._width / this.texture.frame.width;
if(this._height)this.scale.y = this._height / this.texture.frame.height;
this.updateFrame = true;
};
/**
* Returns the framing rectangle of the sprite as a PIXI.Rectangle object
*
* @method getBounds
* @param matrix {Matrix} the transformation matrix of the sprite
* @return {Rectangle} the framing rectangle
*/
PIXI.Sprite.prototype.getBounds = function(matrix)
{
var width = this.texture.frame.width;
var height = this.texture.frame.height;
var w0 = width * (1-this.anchor.x);
var w1 = width * -this.anchor.x;
var h0 = height * (1-this.anchor.y);
var h1 = height * -this.anchor.y;
var worldTransform = matrix || this.worldTransform ;
var a = worldTransform.a;
var b = worldTransform.c;
var c = worldTransform.b;
var d = worldTransform.d;
var tx = worldTransform.tx;
var ty = worldTransform.ty;
var x1 = a * w1 + c * h1 + tx;
var y1 = d * h1 + b * w1 + ty;
var x2 = a * w0 + c * h1 + tx;
var y2 = d * h1 + b * w0 + ty;
var x3 = a * w0 + c * h0 + tx;
var y3 = d * h0 + b * w0 + ty;
var x4 = a * w1 + c * h0 + tx;
var y4 = d * h0 + b * w1 + ty;
var maxX = -Infinity;
var maxY = -Infinity;
var minX = Infinity;
var minY = Infinity;
minX = x1 < minX ? x1 : minX;
minX = x2 < minX ? x2 : minX;
minX = x3 < minX ? x3 : minX;
minX = x4 < minX ? x4 : minX;
minY = y1 < minY ? y1 : minY;
minY = y2 < minY ? y2 : minY;
minY = y3 < minY ? y3 : minY;
minY = y4 < minY ? y4 : minY;
maxX = x1 > maxX ? x1 : maxX;
maxX = x2 > maxX ? x2 : maxX;
maxX = x3 > maxX ? x3 : maxX;
maxX = x4 > maxX ? x4 : maxX;
maxY = y1 > maxY ? y1 : maxY;
maxY = y2 > maxY ? y2 : maxY;
maxY = y3 > maxY ? y3 : maxY;
maxY = y4 > maxY ? y4 : maxY;
var bounds = this._bounds;
bounds.x = minX;
bounds.width = maxX - minX;
bounds.y = minY;
bounds.height = maxY - minY;
// store a reference so that if this function gets called again in the render cycle we do not have to recalculate
this._currentBounds = bounds;
return bounds;
};
/**
* Renders the object using the WebGL renderer
*
* @method _renderWebGL
* @param renderSession {RenderSession}
* @private
*/
PIXI.Sprite.prototype._renderWebGL = function(renderSession)
{
// if the sprite is not visible or the alpha is 0 then no need to render this element
if(!this.visible || this.alpha <= 0)return;
var i,j;
// do a quick check to see if this element has a mask or a filter.
if(this._mask || this._filters)
{
var spriteBatch = renderSession.spriteBatch;
if(this._mask)
{
spriteBatch.stop();
renderSession.maskManager.pushMask(this.mask, renderSession);
spriteBatch.start();
}
if(this._filters)
{
spriteBatch.flush();
renderSession.filterManager.pushFilter(this._filterBlock);
}
// add this sprite to the batch
spriteBatch.render(this);
// now loop through the children and make sure they get rendered
for(i=0,j=this.children.length; i<j; i++)
{
this.children[i]._renderWebGL(renderSession);
}
// time to stop the sprite batch as either a mask element or a filter draw will happen next
spriteBatch.stop();
if(this._filters)renderSession.filterManager.popFilter();
if(this._mask)renderSession.maskManager.popMask(renderSession);
spriteBatch.start();
}
else
{
renderSession.spriteBatch.render(this);
// simple render children!
for(i=0,j=this.children.length; i<j; i++)
{
this.children[i]._renderWebGL(renderSession);
}
}
//TODO check culling
};
/**
* Renders the object using the Canvas renderer
*
* @method _renderCanvas
* @param renderSession {RenderSession}
* @private
*/
PIXI.Sprite.prototype._renderCanvas = function(renderSession)
{
// if the sprite is not visible or the alpha is 0 then no need to render this element
if(this.visible === false || this.alpha === 0)return;
var frame = this.texture.frame;
var context = renderSession.context;
var texture = this.texture;
if(this.blendMode !== renderSession.currentBlendMode)
{
renderSession.currentBlendMode = this.blendMode;
context.globalCompositeOperation = PIXI.blendModesCanvas[renderSession.currentBlendMode];
}
if(this._mask)
{
renderSession.maskManager.pushMask(this._mask, renderSession.context);
}
//ignore null sources
if(frame && frame.width && frame.height && texture.baseTexture.source)
{
context.globalAlpha = this.worldAlpha;
var transform = this.worldTransform;
// allow for trimming
if (renderSession.roundPixels)
{
context.setTransform(transform.a, transform.c, transform.b, transform.d, transform.tx | 0, transform.ty | 0);
}
else
{
context.setTransform(transform.a, transform.c, transform.b, transform.d, transform.tx, transform.ty);
}
//if smoothingEnabled is supported and we need to change the smoothing property for this texture
if(renderSession.smoothProperty && renderSession.scaleMode !== this.texture.baseTexture.scaleMode) {
renderSession.scaleMode = this.texture.baseTexture.scaleMode;
context[renderSession.smoothProperty] = (renderSession.scaleMode === PIXI.scaleModes.LINEAR);
}
if(this.tint !== 0xFFFFFF)
{
if(this.cachedTint !== this.tint)
{
// no point tinting an image that has not loaded yet!
if(!texture.baseTexture.hasLoaded)return;
this.cachedTint = this.tint;
//TODO clean up caching - how to clean up the caches?
this.tintedTexture = PIXI.CanvasTinter.getTintedTexture(this, this.tint);
}
context.drawImage(this.tintedTexture,
0,
0,
frame.width,
frame.height,
(this.anchor.x) * -frame.width,
(this.anchor.y) * -frame.height,
frame.width,
frame.height);
}
else
{
if(texture.trim)
{
var trim = texture.trim;
context.drawImage(this.texture.baseTexture.source,
frame.x,
frame.y,
frame.width,
frame.height,
trim.x - this.anchor.x * trim.width,
trim.y - this.anchor.y * trim.height,
frame.width,
frame.height);
}
else
{
context.drawImage(this.texture.baseTexture.source,
frame.x,
frame.y,
frame.width,
frame.height,
(this.anchor.x) * -frame.width,
(this.anchor.y) * -frame.height,
frame.width,
frame.height);
}
}
}
// OVERWRITE
for(var i=0,j=this.children.length; i<j; i++)
{
var child = this.children[i];
child._renderCanvas(renderSession);
}
if(this._mask)
{
renderSession.maskManager.popMask(renderSession.context);
}
};
// some helper functions..
/**
*
* Helper function that creates a sprite that will contain a texture from the TextureCache based on the frameId
* The frame ids are created when a Texture packer file has been loaded
*
* @method fromFrame
* @static
* @param frameId {String} The frame Id of the texture in the cache
* @return {Sprite} A new Sprite using a texture from the texture cache matching the frameId
*/
PIXI.Sprite.fromFrame = function(frameId)
{
var texture = PIXI.TextureCache[frameId];
if(!texture) throw new Error('The frameId "' + frameId + '" does not exist in the texture cache' + this);
return new PIXI.Sprite(texture);
};
/**
*
* Helper function that creates a sprite that will contain a texture based on an image url
* If the image is not in the texture cache it will be loaded
*
* @method fromImage
* @static
* @param imageId {String} The image url of the texture
* @return {Sprite} A new Sprite using a texture from the texture cache matching the image id
*/
PIXI.Sprite.fromImage = function(imageId, crossorigin, scaleMode)
{
var texture = PIXI.Texture.fromImage(imageId, crossorigin, scaleMode);
return new PIXI.Sprite(texture);
};
/**
* @author Mat Groves http://matgroves.com/
*/
/**
* The SpriteBatch class is a really fast version of the DisplayObjectContainer
* built solely for speed, so use when you need a lot of sprites or particles.
* And it's extremely easy to use :
var container = new PIXI.SpriteBatch();
stage.addChild(container);
for(var i = 0; i < 100; i++)
{
var sprite = new PIXI.Sprite.fromImage("myImage.png");
container.addChild(sprite);
}
* And here you have a hundred sprites that will be renderer at the speed of light
*
* @class SpriteBatch
* @constructor
* @param texture {Texture}
*/
PIXI.SpriteBatch = function(texture)
{
PIXI.DisplayObjectContainer.call( this);
this.textureThing = texture;
this.ready = false;
};
PIXI.SpriteBatch.prototype = Object.create(PIXI.DisplayObjectContainer.prototype);
PIXI.SpriteBatch.constructor = PIXI.SpriteBatch;
/*
* Initialises the spriteBatch
*
* @method initWebGL
* @param gl {WebGLContext} the current WebGL drawing context
*/
PIXI.SpriteBatch.prototype.initWebGL = function(gl)
{
// TODO only one needed for the whole engine really?
this.fastSpriteBatch = new PIXI.WebGLFastSpriteBatch(gl);
this.ready = true;
};
/*
* Updates the object transform for rendering
*
* @method updateTransform
* @private
*/
PIXI.SpriteBatch.prototype.updateTransform = function()
{
// TODO dont need to!
PIXI.DisplayObject.prototype.updateTransform.call( this );
// PIXI.DisplayObjectContainer.prototype.updateTransform.call( this );
};
/**
* Renders the object using the WebGL renderer
*
* @method _renderWebGL
* @param renderSession {RenderSession}
* @private
*/
PIXI.SpriteBatch.prototype._renderWebGL = function(renderSession)
{
if(!this.visible || this.alpha <= 0 || !this.children.length)return;
if(!this.ready)this.initWebGL( renderSession.gl );
renderSession.spriteBatch.stop();
renderSession.shaderManager.activateShader(renderSession.shaderManager.fastShader);
this.fastSpriteBatch.begin(this, renderSession);
this.fastSpriteBatch.render(this);
renderSession.shaderManager.activateShader(renderSession.shaderManager.defaultShader);
renderSession.spriteBatch.start();
};
/**
* Renders the object using the Canvas renderer
*
* @method _renderCanvas
* @param renderSession {RenderSession}
* @private
*/
PIXI.SpriteBatch.prototype._renderCanvas = function(renderSession)
{
var context = renderSession.context;
context.globalAlpha = this.worldAlpha;
PIXI.DisplayObject.prototype.updateTransform.call(this);
var transform = this.worldTransform;
// alow for trimming
var isRotated = true;
for (var i = 0; i < this.children.length; i++) {
var child = this.children[i];
if(!child.visible)continue;
var texture = child.texture;
var frame = texture.frame;
context.globalAlpha = this.worldAlpha * child.alpha;
if(child.rotation % (Math.PI * 2) === 0)
{
if(isRotated)
{
context.setTransform(transform.a, transform.c, transform.b, transform.d, transform.tx, transform.ty);
isRotated = false;
}
// this is the fastest way to optimise! - if rotation is 0 then we can avoid any kind of setTransform call
context.drawImage(texture.baseTexture.source,
frame.x,
frame.y,
frame.width,
frame.height,
((child.anchor.x) * (-frame.width * child.scale.x) + child.position.x + 0.5) | 0,
((child.anchor.y) * (-frame.height * child.scale.y) + child.position.y + 0.5) | 0,
frame.width * child.scale.x,
frame.height * child.scale.y);
}
else
{
if(!isRotated)isRotated = true;
PIXI.DisplayObject.prototype.updateTransform.call(child);
var childTransform = child.worldTransform;
// allow for trimming
if (renderSession.roundPixels)
{
context.setTransform(childTransform.a, childTransform.c, childTransform.b, childTransform.d, childTransform.tx | 0, childTransform.ty | 0);
}
else
{
context.setTransform(childTransform.a, childTransform.c, childTransform.b, childTransform.d, childTransform.tx, childTransform.ty);
}
context.drawImage(texture.baseTexture.source,
frame.x,
frame.y,
frame.width,
frame.height,
((child.anchor.x) * (-frame.width) + 0.5) | 0,
((child.anchor.y) * (-frame.height) + 0.5) | 0,
frame.width,
frame.height);
}
// context.restore();
}
// context.restore();
};
/**
* @author Mat Groves http://matgroves.com/ @Doormat23
*/
PIXI.FilterBlock = function()
{
this.visible = true;
this.renderable = true;
};
/**
* @author Mat Groves http://matgroves.com/ @Doormat23
*/
/**
* A Text Object will create a line(s) of text. To split a line you can use '\n'
* or add a wordWrap property set to true and and wordWrapWidth property with a value
* in the style object
*
* @class Text
* @extends Sprite
* @constructor
* @param text {String} The copy that you would like the text to display
* @param [style] {Object} The style parameters
* @param [style.font] {String} default 'bold 20px Arial' The style and size of the font
* @param [style.fill='black'] {String|Number} A canvas fillstyle that will be used on the text e.g 'red', '#00FF00'
* @param [style.align='left'] {String} Alignment for multiline text ('left', 'center' or 'right'), does not affect single line text
* @param [style.stroke] {String|Number} A canvas fillstyle that will be used on the text stroke e.g 'blue', '#FCFF00'
* @param [style.strokeThickness=0] {Number} A number that represents the thickness of the stroke. Default is 0 (no stroke)
* @param [style.wordWrap=false] {Boolean} Indicates if word wrap should be used
* @param [style.wordWrapWidth=100] {Number} The width at which text will wrap, it needs wordWrap to be set to true
*/
PIXI.Text = function(text, style)
{
/**
* The canvas element that everything is drawn to
*
* @property canvas
* @type HTMLCanvasElement
*/
this.canvas = document.createElement('canvas');
/**
* The canvas 2d context that everything is drawn with
* @property context
* @type HTMLCanvasElement 2d Context
*/
this.context = this.canvas.getContext('2d');
PIXI.Sprite.call(this, PIXI.Texture.fromCanvas(this.canvas));
this.setText(text);
this.setStyle(style);
this.updateText();
this.dirty = false;
};
// constructor
PIXI.Text.prototype = Object.create(PIXI.Sprite.prototype);
PIXI.Text.prototype.constructor = PIXI.Text;
/**
* Set the style of the text
*
* @method setStyle
* @param [style] {Object} The style parameters
* @param [style.font='bold 20pt Arial'] {String} The style and size of the font
* @param [style.fill='black'] {Object} A canvas fillstyle that will be used on the text eg 'red', '#00FF00'
* @param [style.align='left'] {String} Alignment for multiline text ('left', 'center' or 'right'), does not affect single line text
* @param [style.stroke='black'] {String} A canvas fillstyle that will be used on the text stroke eg 'blue', '#FCFF00'
* @param [style.strokeThickness=0] {Number} A number that represents the thickness of the stroke. Default is 0 (no stroke)
* @param [style.wordWrap=false] {Boolean} Indicates if word wrap should be used
* @param [style.wordWrapWidth=100] {Number} The width at which text will wrap
*/
PIXI.Text.prototype.setStyle = function(style)
{
style = style || {};
style.font = style.font || 'bold 20pt Arial';
style.fill = style.fill || 'black';
style.align = style.align || 'left';
style.stroke = style.stroke || 'black'; //provide a default, see: https://github.com/GoodBoyDigital/pixi.js/issues/136
style.strokeThickness = style.strokeThickness || 0;
style.wordWrap = style.wordWrap || false;
style.wordWrapWidth = style.wordWrapWidth || 100;
this.style = style;
this.dirty = true;
};
/**
* Set the copy for the text object. To split a line you can use '\n'
*
* @method setText
* @param {String} text The copy that you would like the text to display
*/
PIXI.Text.prototype.setText = function(text)
{
this.text = text.toString() || ' ';
this.dirty = true;
};
/**
* Renders text and updates it when needed
*
* @method updateText
* @private
*/
PIXI.Text.prototype.updateText = function()
{
this.context.font = this.style.font;
var outputText = this.text;
// word wrap
// preserve original text
if(this.style.wordWrap)outputText = this.wordWrap(this.text);
//split text into lines
var lines = outputText.split(/(?:\r\n|\r|\n)/);
//calculate text width
var lineWidths = [];
var maxLineWidth = 0;
for (var i = 0; i < lines.length; i++)
{
var lineWidth = this.context.measureText(lines[i]).width;
lineWidths[i] = lineWidth;
maxLineWidth = Math.max(maxLineWidth, lineWidth);
}
this.canvas.width = maxLineWidth + this.style.strokeThickness;
//calculate text height
var lineHeight = this.determineFontHeight('font: ' + this.style.font + ';') + this.style.strokeThickness;
this.canvas.height = lineHeight * lines.length;
if(navigator.isCocoonJS) this.context.clearRect(0,0,this.canvas.width,this.canvas.height);
//set canvas text styles
this.context.fillStyle = this.style.fill;
this.context.font = this.style.font;
this.context.strokeStyle = this.style.stroke;
this.context.lineWidth = this.style.strokeThickness;
this.context.textBaseline = 'top';
//draw lines line by line
for (i = 0; i < lines.length; i++)
{
var linePosition = new PIXI.Point(this.style.strokeThickness / 2, this.style.strokeThickness / 2 + i * lineHeight);
if(this.style.align === 'right')
{
linePosition.x += maxLineWidth - lineWidths[i];
}
else if(this.style.align === 'center')
{
linePosition.x += (maxLineWidth - lineWidths[i]) / 2;
}
if(this.style.stroke && this.style.strokeThickness)
{
this.context.strokeText(lines[i], linePosition.x, linePosition.y);
}
if(this.style.fill)
{
this.context.fillText(lines[i], linePosition.x, linePosition.y);
}
}
this.updateTexture();
};
/**
* Updates texture size based on canvas size
*
* @method updateTexture
* @private
*/
PIXI.Text.prototype.updateTexture = function()
{
this.texture.baseTexture.width = this.canvas.width;
this.texture.baseTexture.height = this.canvas.height;
this.texture.frame.width = this.canvas.width;
this.texture.frame.height = this.canvas.height;
this._width = this.canvas.width;
this._height = this.canvas.height;
this.requiresUpdate = true;
};
/**
* Renders the object using the WebGL renderer
*
* @method _renderWebGL
* @param renderSession {RenderSession}
* @private
*/
PIXI.Text.prototype._renderWebGL = function(renderSession)
{
if(this.requiresUpdate)
{
this.requiresUpdate = false;
PIXI.updateWebGLTexture(this.texture.baseTexture, renderSession.gl);
}
PIXI.Sprite.prototype._renderWebGL.call(this, renderSession);
};
/**
* Updates the transform of this object
*
* @method updateTransform
* @private
*/
PIXI.Text.prototype.updateTransform = function()
{
if(this.dirty)
{
this.updateText();
this.dirty = false;
}
PIXI.Sprite.prototype.updateTransform.call(this);
};
/*
* http://stackoverflow.com/users/34441/ellisbben
* great solution to the problem!
* returns the height of the given font
*
* @method determineFontHeight
* @param fontStyle {Object}
* @private
*/
PIXI.Text.prototype.determineFontHeight = function(fontStyle)
{
// build a little reference dictionary so if the font style has been used return a
// cached version...
var result = PIXI.Text.heightCache[fontStyle];
if(!result)
{
var body = document.getElementsByTagName('body')[0];
var dummy = document.createElement('div');
var dummyText = document.createTextNode('M');
dummy.appendChild(dummyText);
dummy.setAttribute('style', fontStyle + ';position:absolute;top:0;left:0');
body.appendChild(dummy);
result = dummy.offsetHeight;
PIXI.Text.heightCache[fontStyle] = result;
body.removeChild(dummy);
}
return result;
};
/**
* Applies newlines to a string to have it optimally fit into the horizontal
* bounds set by the Text object's wordWrapWidth property.
*
* @method wordWrap
* @param text {String}
* @private
*/
PIXI.Text.prototype.wordWrap = function(text)
{
// Greedy wrapping algorithm that will wrap words as the line grows longer
// than its horizontal bounds.
var result = '';
var lines = text.split('\n');
for (var i = 0; i < lines.length; i++)
{
var spaceLeft = this.style.wordWrapWidth;
var words = lines[i].split(' ');
for (var j = 0; j < words.length; j++)
{
var wordWidth = this.context.measureText(words[j]).width;
var wordWidthWithSpace = wordWidth + this.context.measureText(' ').width;
if(wordWidthWithSpace > spaceLeft)
{
// Skip printing the newline if it's the first word of the line that is
// greater than the word wrap width.
if(j > 0)
{
result += '\n';
}
result += words[j] + ' ';
spaceLeft = this.style.wordWrapWidth - wordWidth;
}
else
{
spaceLeft -= wordWidthWithSpace;
result += words[j] + ' ';
}
}
if (i < lines.length-1)
{
result += '\n';
}
}
return result;
};
/**
* Destroys this text object
*
* @method destroy
* @param destroyTexture {Boolean}
*/
PIXI.Text.prototype.destroy = function(destroyTexture)
{
if(destroyTexture)
{
this.texture.destroy();
}
};
PIXI.Text.heightCache = {};
/**
* @author Mat Groves http://matgroves.com/ @Doormat23
*/
/**
* A Text Object will create a line(s) of text using bitmap font. To split a line you can use '\n', '\r' or '\r\n'
* You can generate the fnt files using
* http://www.angelcode.com/products/bmfont/ for windows or
* http://www.bmglyph.com/ for mac.
*
* @class BitmapText
* @extends DisplayObjectContainer
* @constructor
* @param text {String} The copy that you would like the text to display
* @param style {Object} The style parameters
* @param style.font {String} The size (optional) and bitmap font id (required) eq 'Arial' or '20px Arial' (must have loaded previously)
* @param [style.align='left'] {String} Alignment for multiline text ('left', 'center' or 'right'), does not affect single line text
*/
PIXI.BitmapText = function(text, style)
{
PIXI.DisplayObjectContainer.call(this);
this._pool = [];
this.setText(text);
this.setStyle(style);
this.updateText();
this.dirty = false;
};
// constructor
PIXI.BitmapText.prototype = Object.create(PIXI.DisplayObjectContainer.prototype);
PIXI.BitmapText.prototype.constructor = PIXI.BitmapText;
/**
* Set the copy for the text object
*
* @method setText
* @param text {String} The copy that you would like the text to display
*/
PIXI.BitmapText.prototype.setText = function(text)
{
this.text = text || ' ';
this.dirty = true;
};
/**
* Set the style of the text
* style.font {String} The size (optional) and bitmap font id (required) eq 'Arial' or '20px Arial' (must have loaded previously)
* [style.align='left'] {String} Alignment for multiline text ('left', 'center' or 'right'), does not affect single line text
*
* @method setStyle
* @param style {Object} The style parameters, contained as properties of an object
*/
PIXI.BitmapText.prototype.setStyle = function(style)
{
style = style || {};
style.align = style.align || 'left';
this.style = style;
var font = style.font.split(' ');
this.fontName = font[font.length - 1];
this.fontSize = font.length >= 2 ? parseInt(font[font.length - 2], 10) : PIXI.BitmapText.fonts[this.fontName].size;
this.dirty = true;
this.tint = style.tint;
};
/**
* Renders text and updates it when needed
*
* @method updateText
* @private
*/
PIXI.BitmapText.prototype.updateText = function()
{
var data = PIXI.BitmapText.fonts[this.fontName];
var pos = new PIXI.Point();
var prevCharCode = null;
var chars = [];
var maxLineWidth = 0;
var lineWidths = [];
var line = 0;
var scale = this.fontSize / data.size;
for(var i = 0; i < this.text.length; i++)
{
var charCode = this.text.charCodeAt(i);
if(/(?:\r\n|\r|\n)/.test(this.text.charAt(i)))
{
lineWidths.push(pos.x);
maxLineWidth = Math.max(maxLineWidth, pos.x);
line++;
pos.x = 0;
pos.y += data.lineHeight;
prevCharCode = null;
continue;
}
var charData = data.chars[charCode];
if(!charData) continue;
if(prevCharCode && charData[prevCharCode])
{
pos.x += charData.kerning[prevCharCode];
}
chars.push({texture:charData.texture, line: line, charCode: charCode, position: new PIXI.Point(pos.x + charData.xOffset, pos.y + charData.yOffset)});
pos.x += charData.xAdvance;
prevCharCode = charCode;
}
lineWidths.push(pos.x);
maxLineWidth = Math.max(maxLineWidth, pos.x);
var lineAlignOffsets = [];
for(i = 0; i <= line; i++)
{
var alignOffset = 0;
if(this.style.align === 'right')
{
alignOffset = maxLineWidth - lineWidths[i];
}
else if(this.style.align === 'center')
{
alignOffset = (maxLineWidth - lineWidths[i]) / 2;
}
lineAlignOffsets.push(alignOffset);
}
var lenChildren = this.children.length;
var lenChars = chars.length;
var tint = this.tint || 0xFFFFFF;
for(i = 0; i < lenChars; i++)
{
var c = i < lenChildren ? this.children[i] : this._pool.pop(); // get old child if have. if not - take from pool.
if (c) c.setTexture(chars[i].texture); // check if got one before.
else c = new PIXI.Sprite(chars[i].texture); // if no create new one.
c.position.x = (chars[i].position.x + lineAlignOffsets[chars[i].line]) * scale;
c.position.y = chars[i].position.y * scale;
c.scale.x = c.scale.y = scale;
c.tint = tint;
if (!c.parent) this.addChild(c);
}
// remove unnecessary children.
// and put their into the pool.
while(this.children.length > lenChars)
{
var child = this.getChildAt(this.children.length - 1);
this._pool.push(child);
this.removeChild(child);
}
/**
* [read-only] The width of the overall text, different from fontSize,
* which is defined in the style object
*
* @property textWidth
* @type Number
*/
this.textWidth = maxLineWidth * scale;
/**
* [read-only] The height of the overall text, different from fontSize,
* which is defined in the style object
*
* @property textHeight
* @type Number
*/
this.textHeight = (pos.y + data.lineHeight) * scale;
};
/**
* Updates the transform of this object
*
* @method updateTransform
* @private
*/
PIXI.BitmapText.prototype.updateTransform = function()
{
if(this.dirty)
{
this.updateText();
this.dirty = false;
}
PIXI.DisplayObjectContainer.prototype.updateTransform.call(this);
};
PIXI.BitmapText.fonts = {};
/**
* @author Mat Groves http://matgroves.com/ @Doormat23
*/
/**
* A Stage represents the root of the display tree. Everything connected to the stage is rendered
*
* @class Stage
* @extends DisplayObjectContainer
* @constructor
* @param backgroundColor {Number} the background color of the stage, you have to pass this in is in hex format
* like: 0xFFFFFF for white
*
* Creating a stage is a mandatory process when you use Pixi, which is as simple as this :
* var stage = new PIXI.Stage(0xFFFFFF);
* where the parameter given is the background colour of the stage, in hex
* you will use this stage instance to add your sprites to it and therefore to the renderer
* Here is how to add a sprite to the stage :
* stage.addChild(sprite);
*/
PIXI.Stage = function(backgroundColor)
{
PIXI.DisplayObjectContainer.call( this );
/**
* [read-only] Current transform of the object based on world (parent) factors
*
* @property worldTransform
* @type Mat3
* @readOnly
* @private
*/
this.worldTransform = new PIXI.Matrix();
/**
* Whether or not the stage is interactive
*
* @property interactive
* @type Boolean
*/
this.interactive = true;
/**
* The interaction manage for this stage, manages all interactive activity on the stage
*
* @property interactive
* @type InteractionManager
*/
this.interactionManager = new PIXI.InteractionManager(this);
/**
* Whether the stage is dirty and needs to have interactions updated
*
* @property dirty
* @type Boolean
* @private
*/
this.dirty = true;
//the stage is its own stage
this.stage = this;
//optimize hit detection a bit
this.stage.hitArea = new PIXI.Rectangle(0,0,100000, 100000);
this.setBackgroundColor(backgroundColor);
};
// constructor
PIXI.Stage.prototype = Object.create( PIXI.DisplayObjectContainer.prototype );
PIXI.Stage.prototype.constructor = PIXI.Stage;
/**
* Sets another DOM element which can receive mouse/touch interactions instead of the default Canvas element.
* This is useful for when you have other DOM elements on top of the Canvas element.
*
* @method setInteractionDelegate
* @param domElement {DOMElement} This new domElement which will receive mouse/touch events
*/
PIXI.Stage.prototype.setInteractionDelegate = function(domElement)
{
this.interactionManager.setTargetDomElement( domElement );
};
/*
* Updates the object transform for rendering
*
* @method updateTransform
* @private
*/
PIXI.Stage.prototype.updateTransform = function()
{
this.worldAlpha = 1;
for(var i=0,j=this.children.length; i<j; i++)
{
this.children[i].updateTransform();
}
if(this.dirty)
{
this.dirty = false;
// update interactive!
this.interactionManager.dirty = true;
}
if(this.interactive)this.interactionManager.update();
};
/**
* Sets the background color for the stage
*
* @method setBackgroundColor
* @param backgroundColor {Number} the color of the background, easiest way to pass this in is in hex format
* like: 0xFFFFFF for white
*/
PIXI.Stage.prototype.setBackgroundColor = function(backgroundColor)
{
this.backgroundColor = backgroundColor || 0x000000;
this.backgroundColorSplit = PIXI.hex2rgb(this.backgroundColor);
var hex = this.backgroundColor.toString(16);
hex = '000000'.substr(0, 6 - hex.length) + hex;
this.backgroundColorString = '#' + hex;
};
/**
* This will return the point containing global coords of the mouse.
*
* @method getMousePosition
* @return {Point} The point containing the coords of the global InteractionData position.
*/
PIXI.Stage.prototype.getMousePosition = function()
{
return this.interactionManager.mouse.global;
};
/**
* @author Mat Groves http://matgroves.com/ @Doormat23
*/
// http://paulirish.com/2011/requestanimationframe-for-smart-animating/
// http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating
// requestAnimationFrame polyfill by Erik Möller. fixes from Paul Irish and Tino Zijdel
// MIT license
/**
* A polyfill for requestAnimationFrame
* You can actually use both requestAnimationFrame and requestAnimFrame,
* you will still benefit from the polyfill
*
* @method requestAnimationFrame
*/
/**
* A polyfill for cancelAnimationFrame
*
* @method cancelAnimationFrame
*/
var lastTime = 0;
var vendors = ['ms', 'moz', 'webkit', 'o'];
for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
window.requestAnimationFrame = window[vendors[x] + 'RequestAnimationFrame'];
window.cancelAnimationFrame = window[vendors[x] + 'CancelAnimationFrame'] ||
window[vendors[x] + 'CancelRequestAnimationFrame'];
}
if (!window.requestAnimationFrame) {
window.requestAnimationFrame = function(callback) {
var currTime = new Date().getTime();
var timeToCall = Math.max(0, 16 - (currTime - lastTime));
var id = window.setTimeout(function() { callback(currTime + timeToCall); },
timeToCall);
lastTime = currTime + timeToCall;
return id;
};
}
if (!window.cancelAnimationFrame) {
window.cancelAnimationFrame = function(id) {
clearTimeout(id);
};
}
window.requestAnimFrame = window.requestAnimationFrame;
/**
* Converts a hex color number to an [R, G, B] array
*
* @method hex2rgb
* @param hex {Number}
*/
PIXI.hex2rgb = function(hex) {
return [(hex >> 16 & 0xFF) / 255, ( hex >> 8 & 0xFF) / 255, (hex & 0xFF)/ 255];
};
/**
* Converts a color as an [R, G, B] array to a hex number
*
* @method rgb2hex
* @param rgb {Array}
*/
PIXI.rgb2hex = function(rgb) {
return ((rgb[0]*255 << 16) + (rgb[1]*255 << 8) + rgb[2]*255);
};
/**
* A polyfill for Function.prototype.bind
*
* @method bind
*/
if (typeof Function.prototype.bind !== 'function') {
Function.prototype.bind = (function () {
var slice = Array.prototype.slice;
return function (thisArg) {
var target = this, boundArgs = slice.call(arguments, 1);
if (typeof target !== 'function') throw new TypeError();
function bound() {
var args = boundArgs.concat(slice.call(arguments));
target.apply(this instanceof bound ? this : thisArg, args);
}
bound.prototype = (function F(proto) {
if (proto) F.prototype = proto;
if (!(this instanceof F)) return new F();
})(target.prototype);
return bound;
};
})();
}
/**
* A wrapper for ajax requests to be handled cross browser
*
* @class AjaxRequest
* @constructor
*/
PIXI.AjaxRequest = function()
{
var activexmodes = ['Msxml2.XMLHTTP.6.0', 'Msxml2.XMLHTTP.3.0', 'Microsoft.XMLHTTP']; //activeX versions to check for in IE
if (window.ActiveXObject)
{ //Test for support for ActiveXObject in IE first (as XMLHttpRequest in IE7 is broken)
for (var i=0; i<activexmodes.length; i++)
{
try{
return new window.ActiveXObject(activexmodes[i]);
}
catch(e) {
//suppress error
}
}
}
else if (window.XMLHttpRequest) // if Mozilla, Safari etc
{
return new window.XMLHttpRequest();
}
else
{
return false;
}
};
/*
PIXI.packColorRGBA = function(r, g, b, a)//r, g, b, a)
{
// console.log(r, b, c, d)
return (Math.floor((r)*63) << 18) | (Math.floor((g)*63) << 12) | (Math.floor((b)*63) << 6);// | (Math.floor((a)*63))
// i = i | (Math.floor((a)*63));
// return i;
// var r = (i / 262144.0 ) / 64;
// var g = (i / 4096.0)%64 / 64;
// var b = (i / 64.0)%64 / 64;
// var a = (i)%64 / 64;
// console.log(r, g, b, a);
// return i;
};
*/
/*
PIXI.packColorRGB = function(r, g, b)//r, g, b, a)
{
return (Math.floor((r)*255) << 16) | (Math.floor((g)*255) << 8) | (Math.floor((b)*255));
};
PIXI.unpackColorRGB = function(r, g, b)//r, g, b, a)
{
return (Math.floor((r)*255) << 16) | (Math.floor((g)*255) << 8) | (Math.floor((b)*255));
};
*/
/**
* Checks whether the Canvas BlendModes are supported by the current browser
*
* @method canUseNewCanvasBlendModes
* @return {Boolean} whether they are supported
*/
PIXI.canUseNewCanvasBlendModes = function()
{
var canvas = document.createElement('canvas');
canvas.width = 1;
canvas.height = 1;
var context = canvas.getContext('2d');
context.fillStyle = '#000';
context.fillRect(0,0,1,1);
context.globalCompositeOperation = 'multiply';
context.fillStyle = '#fff';
context.fillRect(0,0,1,1);
return context.getImageData(0,0,1,1).data[0] === 0;
};
/**
* Given a number, this function returns the closest number that is a power of two
* this function is taken from Starling Framework as its pretty neat ;)
*
* @method getNextPowerOfTwo
* @param number {Number}
* @return {Number} the closest number that is a power of two
*/
PIXI.getNextPowerOfTwo = function(number)
{
if (number > 0 && (number & (number - 1)) === 0) // see: http://goo.gl/D9kPj
return number;
else
{
var result = 1;
while (result < number) result <<= 1;
return result;
}
};
/**
* @author Mat Groves http://matgroves.com/ @Doormat23
*/
/**
* https://github.com/mrdoob/eventtarget.js/
* THankS mr DOob!
*/
/**
* Adds event emitter functionality to a class
*
* @class EventTarget
* @example
* function MyEmitter() {
* PIXI.EventTarget.call(this); //mixes in event target stuff
* }
*
* var em = new MyEmitter();
* em.emit({ type: 'eventName', data: 'some data' });
*/
PIXI.EventTarget = function () {
/**
* Holds all the listeners
*
* @property listeneners
* @type Object
*/
var listeners = {};
/**
* Adds a listener for a specific event
*
* @method addEventListener
* @param type {string} A string representing the event type to listen for.
* @param listener {function} The callback function that will be fired when the event occurs
*/
this.addEventListener = this.on = function ( type, listener ) {
if ( listeners[ type ] === undefined ) {
listeners[ type ] = [];
}
if ( listeners[ type ].indexOf( listener ) === - 1 ) {
listeners[ type ].push( listener );
}
};
/**
* Fires the event, ie pretends that the event has happened
*
* @method dispatchEvent
* @param event {Event} the event object
*/
this.dispatchEvent = this.emit = function ( event ) {
if ( !listeners[ event.type ] || !listeners[ event.type ].length ) {
return;
}
for(var i = 0, l = listeners[ event.type ].length; i < l; i++) {
listeners[ event.type ][ i ]( event );
}
};
/**
* Removes the specified listener that was assigned to the specified event type
*
* @method removeEventListener
* @param type {string} A string representing the event type which will have its listener removed
* @param listener {function} The callback function that was be fired when the event occured
*/
this.removeEventListener = this.off = function ( type, listener ) {
var index = listeners[ type ].indexOf( listener );
if ( index !== - 1 ) {
listeners[ type ].splice( index, 1 );
}
};
/**
* Removes all the listeners that were active for the specified event type
*
* @method removeAllEventListeners
* @param type {string} A string representing the event type which will have all its listeners removed
*/
this.removeAllEventListeners = function( type ) {
var a = listeners[type];
if (a)
a.length = 0;
};
};
/*
PolyK library
url: http://polyk.ivank.net
Released under MIT licence.
Copyright (c) 2012 Ivan Kuckir
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
This is an amazing lib!
slightly modified by Mat Groves (matgroves.com);
*/
/**
* Based on the Polyk library http://polyk.ivank.net released under MIT licence.
* This is an amazing lib!
* slightly modified by Mat Groves (matgroves.com);
* @class PolyK
*
*/
PIXI.PolyK = {};
/**
* Triangulates shapes for webGL graphic fills
*
* @method Triangulate
*
*/
PIXI.PolyK.Triangulate = function(p)
{
var sign = true;
var n = p.length >> 1;
if(n < 3) return [];
var tgs = [];
var avl = [];
for(var i = 0; i < n; i++) avl.push(i);
i = 0;
var al = n;
while(al > 3)
{
var i0 = avl[(i+0)%al];
var i1 = avl[(i+1)%al];
var i2 = avl[(i+2)%al];
var ax = p[2*i0], ay = p[2*i0+1];
var bx = p[2*i1], by = p[2*i1+1];
var cx = p[2*i2], cy = p[2*i2+1];
var earFound = false;
if(PIXI.PolyK._convex(ax, ay, bx, by, cx, cy, sign))
{
earFound = true;
for(var j = 0; j < al; j++)
{
var vi = avl[j];
if(vi === i0 || vi === i1 || vi === i2) continue;
if(PIXI.PolyK._PointInTriangle(p[2*vi], p[2*vi+1], ax, ay, bx, by, cx, cy)) {
earFound = false;
break;
}
}
}
if(earFound)
{
tgs.push(i0, i1, i2);
avl.splice((i+1)%al, 1);
al--;
i = 0;
}
else if(i++ > 3*al)
{
// need to flip flip reverse it!
// reset!
if(sign)
{
tgs = [];
avl = [];
for(i = 0; i < n; i++) avl.push(i);
i = 0;
al = n;
sign = false;
}
else
{
window.console.log("PIXI Warning: shape too complex to fill");
return [];
}
}
}
tgs.push(avl[0], avl[1], avl[2]);
return tgs;
};
/**
* Checks whether a point is within a triangle
*
* @method _PointInTriangle
* @param px {Number} x coordinate of the point to test
* @param py {Number} y coordinate of the point to test
* @param ax {Number} x coordinate of the a point of the triangle
* @param ay {Number} y coordinate of the a point of the triangle
* @param bx {Number} x coordinate of the b point of the triangle
* @param by {Number} y coordinate of the b point of the triangle
* @param cx {Number} x coordinate of the c point of the triangle
* @param cy {Number} y coordinate of the c point of the triangle
* @private
*/
PIXI.PolyK._PointInTriangle = function(px, py, ax, ay, bx, by, cx, cy)
{
var v0x = cx-ax;
var v0y = cy-ay;
var v1x = bx-ax;
var v1y = by-ay;
var v2x = px-ax;
var v2y = py-ay;
var dot00 = v0x*v0x+v0y*v0y;
var dot01 = v0x*v1x+v0y*v1y;
var dot02 = v0x*v2x+v0y*v2y;
var dot11 = v1x*v1x+v1y*v1y;
var dot12 = v1x*v2x+v1y*v2y;
var invDenom = 1 / (dot00 * dot11 - dot01 * dot01);
var u = (dot11 * dot02 - dot01 * dot12) * invDenom;
var v = (dot00 * dot12 - dot01 * dot02) * invDenom;
// Check if point is in triangle
return (u >= 0) && (v >= 0) && (u + v < 1);
};
/**
* Checks whether a shape is convex
*
* @method _convex
*
* @private
*/
PIXI.PolyK._convex = function(ax, ay, bx, by, cx, cy, sign)
{
return ((ay-by)*(cx-bx) + (bx-ax)*(cy-by) >= 0) === sign;
};
/**
* @author Mat Groves http://matgroves.com/ @Doormat23
*/
// TODO Alvin and Mat
// Should we eventually create a Utils class ?
// Or just move this file to the pixi.js file ?
PIXI.initDefaultShaders = function()
{
// PIXI.stripShader = new PIXI.StripShader();
// PIXI.stripShader.init();
};
PIXI.CompileVertexShader = function(gl, shaderSrc)
{
return PIXI._CompileShader(gl, shaderSrc, gl.VERTEX_SHADER);
};
PIXI.CompileFragmentShader = function(gl, shaderSrc)
{
return PIXI._CompileShader(gl, shaderSrc, gl.FRAGMENT_SHADER);
};
PIXI._CompileShader = function(gl, shaderSrc, shaderType)
{
var src = shaderSrc.join("\n");
var shader = gl.createShader(shaderType);
gl.shaderSource(shader, src);
gl.compileShader(shader);
if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
window.console.log(gl.getShaderInfoLog(shader));
return null;
}
return shader;
};
PIXI.compileProgram = function(gl, vertexSrc, fragmentSrc)
{
var fragmentShader = PIXI.CompileFragmentShader(gl, fragmentSrc);
var vertexShader = PIXI.CompileVertexShader(gl, vertexSrc);
var shaderProgram = gl.createProgram();
gl.attachShader(shaderProgram, vertexShader);
gl.attachShader(shaderProgram, fragmentShader);
gl.linkProgram(shaderProgram);
if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {
window.console.log("Could not initialise shaders");
}
return shaderProgram;
};
/**
* @author Mat Groves http://matgroves.com/ @Doormat23
* @author Richard Davey http://www.photonstorm.com @photonstorm
*/
/**
* @class PixiShader
* @constructor
*/
PIXI.PixiShader = function(gl)
{
/**
* @property gl
* @type WebGLContext
*/
this.gl = gl;
/**
* @property {any} program - The WebGL program.
*/
this.program = null;
/**
* @property {array} fragmentSrc - The fragment shader.
*/
this.fragmentSrc = [
'precision lowp float;',
'varying vec2 vTextureCoord;',
'varying vec4 vColor;',
'uniform sampler2D uSampler;',
'void main(void) {',
' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;',
'}'
];
/**
* @property {number} textureCount - A local texture counter for multi-texture shaders.
*/
this.textureCount = 0;
this.attributes = [];
this.init();
};
/**
* Initialises the shader
* @method init
*
*/
PIXI.PixiShader.prototype.init = function()
{
var gl = this.gl;
var program = PIXI.compileProgram(gl, this.vertexSrc || PIXI.PixiShader.defaultVertexSrc, this.fragmentSrc);
gl.useProgram(program);
// get and store the uniforms for the shader
this.uSampler = gl.getUniformLocation(program, 'uSampler');
this.projectionVector = gl.getUniformLocation(program, 'projectionVector');
this.offsetVector = gl.getUniformLocation(program, 'offsetVector');
this.dimensions = gl.getUniformLocation(program, 'dimensions');
// get and store the attributes
this.aVertexPosition = gl.getAttribLocation(program, 'aVertexPosition');
this.aTextureCoord = gl.getAttribLocation(program, 'aTextureCoord');
this.colorAttribute = gl.getAttribLocation(program, 'aColor');
// Begin worst hack eva //
// WHY??? ONLY on my chrome pixel the line above returns -1 when using filters?
// maybe its something to do with the current state of the gl context.
// Im convinced this is a bug in the chrome browser as there is NO reason why this should be returning -1 especially as it only manifests on my chrome pixel
// If theres any webGL people that know why could happen please help :)
if(this.colorAttribute === -1)
{
this.colorAttribute = 2;
}
this.attributes = [this.aVertexPosition, this.aTextureCoord, this.colorAttribute];
// End worst hack eva //
// add those custom shaders!
for (var key in this.uniforms)
{
// get the uniform locations..
this.uniforms[key].uniformLocation = gl.getUniformLocation(program, key);
}
this.initUniforms();
this.program = program;
};
/**
* Initialises the shader uniform values.
* Uniforms are specified in the GLSL_ES Specification: http://www.khronos.org/registry/webgl/specs/latest/1.0/
* http://www.khronos.org/registry/gles/specs/2.0/GLSL_ES_Specification_1.0.17.pdf
*
* @method initUniforms
*/
PIXI.PixiShader.prototype.initUniforms = function()
{
this.textureCount = 1;
var gl = this.gl;
var uniform;
for (var key in this.uniforms)
{
uniform = this.uniforms[key];
var type = uniform.type;
if (type === 'sampler2D')
{
uniform._init = false;
if (uniform.value !== null)
{
this.initSampler2D(uniform);
}
}
else if (type === 'mat2' || type === 'mat3' || type === 'mat4')
{
// These require special handling
uniform.glMatrix = true;
uniform.glValueLength = 1;
if (type === 'mat2')
{
uniform.glFunc = gl.uniformMatrix2fv;
}
else if (type === 'mat3')
{
uniform.glFunc = gl.uniformMatrix3fv;
}
else if (type === 'mat4')
{
uniform.glFunc = gl.uniformMatrix4fv;
}
}
else
{
// GL function reference
uniform.glFunc = gl['uniform' + type];
if (type === '2f' || type === '2i')
{
uniform.glValueLength = 2;
}
else if (type === '3f' || type === '3i')
{
uniform.glValueLength = 3;
}
else if (type === '4f' || type === '4i')
{
uniform.glValueLength = 4;
}
else
{
uniform.glValueLength = 1;
}
}
}
};
/**
* Initialises a Sampler2D uniform (which may only be available later on after initUniforms once the texture has loaded)
*
* @method initSampler2D
*/
PIXI.PixiShader.prototype.initSampler2D = function(uniform)
{
if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded)
{
return;
}
var gl = this.gl;
gl.activeTexture(gl['TEXTURE' + this.textureCount]);
gl.bindTexture(gl.TEXTURE_2D, uniform.value.baseTexture._glTextures[gl.id]);
// Extended texture data
if (uniform.textureData)
{
var data = uniform.textureData;
// GLTexture = mag linear, min linear_mipmap_linear, wrap repeat + gl.generateMipmap(gl.TEXTURE_2D);
// GLTextureLinear = mag/min linear, wrap clamp
// GLTextureNearestRepeat = mag/min NEAREST, wrap repeat
// GLTextureNearest = mag/min nearest, wrap clamp
// AudioTexture = whatever + luminance + width 512, height 2, border 0
// KeyTexture = whatever + luminance + width 256, height 2, border 0
// magFilter can be: gl.LINEAR, gl.LINEAR_MIPMAP_LINEAR or gl.NEAREST
// wrapS/T can be: gl.CLAMP_TO_EDGE or gl.REPEAT
var magFilter = (data.magFilter) ? data.magFilter : gl.LINEAR;
var minFilter = (data.minFilter) ? data.minFilter : gl.LINEAR;
var wrapS = (data.wrapS) ? data.wrapS : gl.CLAMP_TO_EDGE;
var wrapT = (data.wrapT) ? data.wrapT : gl.CLAMP_TO_EDGE;
var format = (data.luminance) ? gl.LUMINANCE : gl.RGBA;
if (data.repeat)
{
wrapS = gl.REPEAT;
wrapT = gl.REPEAT;
}
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, !!data.flipY);
if (data.width)
{
var width = (data.width) ? data.width : 512;
var height = (data.height) ? data.height : 2;
var border = (data.border) ? data.border : 0;
// void texImage2D(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, ArrayBufferView? pixels);
gl.texImage2D(gl.TEXTURE_2D, 0, format, width, height, border, format, gl.UNSIGNED_BYTE, null);
}
else
{
// void texImage2D(GLenum target, GLint level, GLenum internalformat, GLenum format, GLenum type, ImageData? pixels);
gl.texImage2D(gl.TEXTURE_2D, 0, format, gl.RGBA, gl.UNSIGNED_BYTE, uniform.value.baseTexture.source);
}
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, wrapS);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, wrapT);
}
gl.uniform1i(uniform.uniformLocation, this.textureCount);
uniform._init = true;
this.textureCount++;
};
/**
* Updates the shader uniform values.
*
* @method syncUniforms
*/
PIXI.PixiShader.prototype.syncUniforms = function()
{
this.textureCount = 1;
var uniform;
var gl = this.gl;
// This would probably be faster in an array and it would guarantee key order
for (var key in this.uniforms)
{
uniform = this.uniforms[key];
if (uniform.glValueLength === 1)
{
if (uniform.glMatrix === true)
{
uniform.glFunc.call(gl, uniform.uniformLocation, uniform.transpose, uniform.value);
}
else
{
uniform.glFunc.call(gl, uniform.uniformLocation, uniform.value);
}
}
else if (uniform.glValueLength === 2)
{
uniform.glFunc.call(gl, uniform.uniformLocation, uniform.value.x, uniform.value.y);
}
else if (uniform.glValueLength === 3)
{
uniform.glFunc.call(gl, uniform.uniformLocation, uniform.value.x, uniform.value.y, uniform.value.z);
}
else if (uniform.glValueLength === 4)
{
uniform.glFunc.call(gl, uniform.uniformLocation, uniform.value.x, uniform.value.y, uniform.value.z, uniform.value.w);
}
else if (uniform.type === 'sampler2D')
{
if (uniform._init)
{
gl.activeTexture(gl['TEXTURE' + this.textureCount]);
gl.bindTexture(gl.TEXTURE_2D, uniform.value.baseTexture._glTextures[gl.id] || PIXI.createWebGLTexture( uniform.value.baseTexture, gl));
gl.uniform1i(uniform.uniformLocation, this.textureCount);
this.textureCount++;
}
else
{
this.initSampler2D(uniform);
}
}
}
};
/**
* Destroys the shader
* @method destroy
*/
PIXI.PixiShader.prototype.destroy = function()
{
this.gl.deleteProgram( this.program );
this.uniforms = null;
this.gl = null;
this.attributes = null;
};
/**
* The Default Vertex shader source
* @property defaultVertexSrc
* @type String
*/
PIXI.PixiShader.defaultVertexSrc = [
'attribute vec2 aVertexPosition;',
'attribute vec2 aTextureCoord;',
'attribute vec2 aColor;',
'uniform vec2 projectionVector;',
'uniform vec2 offsetVector;',
'varying vec2 vTextureCoord;',
'varying vec4 vColor;',
'const vec2 center = vec2(-1.0, 1.0);',
'void main(void) {',
' gl_Position = vec4( ((aVertexPosition + offsetVector) / projectionVector) + center , 0.0, 1.0);',
' vTextureCoord = aTextureCoord;',
' vec3 color = mod(vec3(aColor.y/65536.0, aColor.y/256.0, aColor.y), 256.0) / 256.0;',
' vColor = vec4(color * aColor.x, aColor.x);',
'}'
];
/**
* @author Mat Groves http://matgroves.com/ @Doormat23
* @author Richard Davey http://www.photonstorm.com @photonstorm
*/
/**
* @class PixiFastShader
* @constructor
* @param gl {WebGLContext} the current WebGL drawing context
*/
PIXI.PixiFastShader = function(gl)
{
/**
* @property gl
* @type WebGLContext
*/
this.gl = gl;
/**
* @property {any} program - The WebGL program.
*/
this.program = null;
/**
* @property {array} fragmentSrc - The fragment shader.
*/
this.fragmentSrc = [
'precision lowp float;',
'varying vec2 vTextureCoord;',
'varying float vColor;',
'uniform sampler2D uSampler;',
'void main(void) {',
' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;',
'}'
];
/**
* @property {array} vertexSrc - The vertex shader
*/
this.vertexSrc = [
'attribute vec2 aVertexPosition;',
'attribute vec2 aPositionCoord;',
'attribute vec2 aScale;',
'attribute float aRotation;',
'attribute vec2 aTextureCoord;',
'attribute float aColor;',
'uniform vec2 projectionVector;',
'uniform vec2 offsetVector;',
'uniform mat3 uMatrix;',
'varying vec2 vTextureCoord;',
'varying float vColor;',
'const vec2 center = vec2(-1.0, 1.0);',
'void main(void) {',
' vec2 v;',
' vec2 sv = aVertexPosition * aScale;',
' v.x = (sv.x) * cos(aRotation) - (sv.y) * sin(aRotation);',
' v.y = (sv.x) * sin(aRotation) + (sv.y) * cos(aRotation);',
' v = ( uMatrix * vec3(v + aPositionCoord , 1.0) ).xy ;',
' gl_Position = vec4( ( v / projectionVector) + center , 0.0, 1.0);',
' vTextureCoord = aTextureCoord;',
// ' vec3 color = mod(vec3(aColor.y/65536.0, aColor.y/256.0, aColor.y), 256.0) / 256.0;',
' vColor = aColor;',
'}'
];
/**
* @property {number} textureCount - A local texture counter for multi-texture shaders.
*/
this.textureCount = 0;
this.init();
};
/**
* Initialises the shader
* @method init
*
*/
PIXI.PixiFastShader.prototype.init = function()
{
var gl = this.gl;
var program = PIXI.compileProgram(gl, this.vertexSrc, this.fragmentSrc);
gl.useProgram(program);
// get and store the uniforms for the shader
this.uSampler = gl.getUniformLocation(program, 'uSampler');
this.projectionVector = gl.getUniformLocation(program, 'projectionVector');
this.offsetVector = gl.getUniformLocation(program, 'offsetVector');
this.dimensions = gl.getUniformLocation(program, 'dimensions');
this.uMatrix = gl.getUniformLocation(program, 'uMatrix');
// get and store the attributes
this.aVertexPosition = gl.getAttribLocation(program, 'aVertexPosition');
this.aPositionCoord = gl.getAttribLocation(program, 'aPositionCoord');
this.aScale = gl.getAttribLocation(program, 'aScale');
this.aRotation = gl.getAttribLocation(program, 'aRotation');
this.aTextureCoord = gl.getAttribLocation(program, 'aTextureCoord');
this.colorAttribute = gl.getAttribLocation(program, 'aColor');
// Begin worst hack eva //
// WHY??? ONLY on my chrome pixel the line above returns -1 when using filters?
// maybe its somthing to do with the current state of the gl context.
// Im convinced this is a bug in the chrome browser as there is NO reason why this should be returning -1 especially as it only manifests on my chrome pixel
// If theres any webGL people that know why could happen please help :)
if(this.colorAttribute === -1)
{
this.colorAttribute = 2;
}
this.attributes = [this.aVertexPosition, this.aPositionCoord, this.aScale, this.aRotation, this.aTextureCoord, this.colorAttribute];
// End worst hack eva //
this.program = program;
};
/**
* Destroys the shader
* @method destroy
*
*/
PIXI.PixiFastShader.prototype.destroy = function()
{
this.gl.deleteProgram( this.program );
this.uniforms = null;
this.gl = null;
this.attributes = null;
};
/**
* @author Mat Groves http://matgroves.com/ @Doormat23
*/
PIXI.StripShader = function()
{
/**
* @property {any} program - The WebGL program.
*/
this.program = null;
/**
* @property {array} fragmentSrc - The fragment shader.
*/
this.fragmentSrc = [
'precision mediump float;',
'varying vec2 vTextureCoord;',
'varying float vColor;',
'uniform float alpha;',
'uniform sampler2D uSampler;',
'void main(void) {',
' gl_FragColor = texture2D(uSampler, vec2(vTextureCoord.x, vTextureCoord.y));',
' gl_FragColor = gl_FragColor * alpha;',
'}'
];
/**
* @property {array} fragmentSrc - The fragment shader.
*/
this.vertexSrc = [
'attribute vec2 aVertexPosition;',
'attribute vec2 aTextureCoord;',
'attribute float aColor;',
'uniform mat3 translationMatrix;',
'uniform vec2 projectionVector;',
'varying vec2 vTextureCoord;',
'uniform vec2 offsetVector;',
'varying float vColor;',
'void main(void) {',
' vec3 v = translationMatrix * vec3(aVertexPosition, 1.0);',
' v -= offsetVector.xyx;',
' gl_Position = vec4( v.x / projectionVector.x -1.0, v.y / projectionVector.y + 1.0 , 0.0, 1.0);',
' vTextureCoord = aTextureCoord;',
' vColor = aColor;',
'}'
];
};
/**
* Initialises the shader
* @method init
*
*/
PIXI.StripShader.prototype.init = function()
{
var gl = PIXI.gl;
var program = PIXI.compileProgram(gl, this.vertexSrc, this.fragmentSrc);
gl.useProgram(program);
// get and store the uniforms for the shader
this.uSampler = gl.getUniformLocation(program, 'uSampler');
this.projectionVector = gl.getUniformLocation(program, 'projectionVector');
this.offsetVector = gl.getUniformLocation(program, 'offsetVector');
this.colorAttribute = gl.getAttribLocation(program, 'aColor');
//this.dimensions = gl.getUniformLocation(this.program, 'dimensions');
// get and store the attributes
this.aVertexPosition = gl.getAttribLocation(program, 'aVertexPosition');
this.aTextureCoord = gl.getAttribLocation(program, 'aTextureCoord');
this.translationMatrix = gl.getUniformLocation(program, 'translationMatrix');
this.alpha = gl.getUniformLocation(program, 'alpha');
this.program = program;
};
/**
* @author Mat Groves http://matgroves.com/ @Doormat23
*/
/**
* @class PrimitiveShader
* @constructor
* @param gl {WebGLContext} the current WebGL drawing context
*/
PIXI.PrimitiveShader = function(gl)
{
/**
* @property gl
* @type WebGLContext
*/
this.gl = gl;
/**
* @property {any} program - The WebGL program.
*/
this.program = null;
/**
* @property fragmentSrc
* @type Array
*/
this.fragmentSrc = [
'precision mediump float;',
'varying vec4 vColor;',
'void main(void) {',
' gl_FragColor = vColor;',
'}'
];
/**
* @property vertexSrc
* @type Array
*/
this.vertexSrc = [
'attribute vec2 aVertexPosition;',
'attribute vec4 aColor;',
'uniform mat3 translationMatrix;',
'uniform vec2 projectionVector;',
'uniform vec2 offsetVector;',
'uniform float alpha;',
'uniform vec3 tint;',
'varying vec4 vColor;',
'void main(void) {',
' vec3 v = translationMatrix * vec3(aVertexPosition , 1.0);',
' v -= offsetVector.xyx;',
' gl_Position = vec4( v.x / projectionVector.x -1.0, v.y / -projectionVector.y + 1.0 , 0.0, 1.0);',
' vColor = aColor * vec4(tint * alpha, alpha);',
'}'
];
this.init();
};
/**
* Initialises the shader
* @method init
*
*/
PIXI.PrimitiveShader.prototype.init = function()
{
var gl = this.gl;
var program = PIXI.compileProgram(gl, this.vertexSrc, this.fragmentSrc);
gl.useProgram(program);
// get and store the uniforms for the shader
this.projectionVector = gl.getUniformLocation(program, 'projectionVector');
this.offsetVector = gl.getUniformLocation(program, 'offsetVector');
this.tintColor = gl.getUniformLocation(program, 'tint');
// get and store the attributes
this.aVertexPosition = gl.getAttribLocation(program, 'aVertexPosition');
this.colorAttribute = gl.getAttribLocation(program, 'aColor');
this.attributes = [this.aVertexPosition, this.colorAttribute];
this.translationMatrix = gl.getUniformLocation(program, 'translationMatrix');
this.alpha = gl.getUniformLocation(program, 'alpha');
this.program = program;
};
/**
* Destroys the shader
* @method destroy
*
*/
PIXI.PrimitiveShader.prototype.destroy = function()
{
this.gl.deleteProgram( this.program );
this.uniforms = null;
this.gl = null;
this.attribute = null;
};
/**
* @author Mat Groves http://matgroves.com/ @Doormat23
*/
/**
* A set of functions used by the webGL renderer to draw the primitive graphics data
*
* @class WebGLGraphics
* @private
* @static
*/
PIXI.WebGLGraphics = function()
{
};
/**
* Renders the graphics object
*
* @static
* @private
* @method renderGraphics
* @param graphics {Graphics}
* @param renderSession {Object}
*/
PIXI.WebGLGraphics.renderGraphics = function(graphics, renderSession)//projection, offset)
{
var gl = renderSession.gl;
var projection = renderSession.projection,
offset = renderSession.offset,
shader = renderSession.shaderManager.primitiveShader;
if(!graphics._webGL[gl.id])graphics._webGL[gl.id] = {points:[], indices:[], lastIndex:0,
buffer:gl.createBuffer(),
indexBuffer:gl.createBuffer()};
var webGL = graphics._webGL[gl.id];
if(graphics.dirty)
{
graphics.dirty = false;
if(graphics.clearDirty)
{
graphics.clearDirty = false;
webGL.lastIndex = 0;
webGL.points = [];
webGL.indices = [];
}
PIXI.WebGLGraphics.updateGraphics(graphics, gl);
}
renderSession.shaderManager.activatePrimitiveShader();
// This could be speeded up for sure!
// set the matrix transform
gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
gl.uniformMatrix3fv(shader.translationMatrix, false, graphics.worldTransform.toArray(true));
gl.uniform2f(shader.projectionVector, projection.x, -projection.y);
gl.uniform2f(shader.offsetVector, -offset.x, -offset.y);
gl.uniform3fv(shader.tintColor, PIXI.hex2rgb(graphics.tint));
gl.uniform1f(shader.alpha, graphics.worldAlpha);
gl.bindBuffer(gl.ARRAY_BUFFER, webGL.buffer);
gl.vertexAttribPointer(shader.aVertexPosition, 2, gl.FLOAT, false, 4 * 6, 0);
gl.vertexAttribPointer(shader.colorAttribute, 4, gl.FLOAT, false,4 * 6, 2 * 4);
// set the index buffer!
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, webGL.indexBuffer);
gl.drawElements(gl.TRIANGLE_STRIP, webGL.indices.length, gl.UNSIGNED_SHORT, 0 );
renderSession.shaderManager.deactivatePrimitiveShader();
// return to default shader...
// PIXI.activateShader(PIXI.defaultShader);
};
/**
* Updates the graphics object
*
* @static
* @private
* @method updateGraphics
* @param graphicsData {Graphics} The graphics object to update
* @param gl {WebGLContext} the current WebGL drawing context
*/
PIXI.WebGLGraphics.updateGraphics = function(graphics, gl)
{
var webGL = graphics._webGL[gl.id];
for (var i = webGL.lastIndex; i < graphics.graphicsData.length; i++)
{
var data = graphics.graphicsData[i];
if(data.type === PIXI.Graphics.POLY)
{
if(data.fill)
{
if(data.points.length>3)
PIXI.WebGLGraphics.buildPoly(data, webGL);
}
if(data.lineWidth > 0)
{
PIXI.WebGLGraphics.buildLine(data, webGL);
}
}
else if(data.type === PIXI.Graphics.RECT)
{
PIXI.WebGLGraphics.buildRectangle(data, webGL);
}
else if(data.type === PIXI.Graphics.CIRC || data.type === PIXI.Graphics.ELIP)
{
PIXI.WebGLGraphics.buildCircle(data, webGL);
}
}
webGL.lastIndex = graphics.graphicsData.length;
webGL.glPoints = new Float32Array(webGL.points);
gl.bindBuffer(gl.ARRAY_BUFFER, webGL.buffer);
gl.bufferData(gl.ARRAY_BUFFER, webGL.glPoints, gl.STATIC_DRAW);
webGL.glIndicies = new Uint16Array(webGL.indices);
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, webGL.indexBuffer);
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, webGL.glIndicies, gl.STATIC_DRAW);
};
/**
* Builds a rectangle to draw
*
* @static
* @private
* @method buildRectangle
* @param graphicsData {Graphics} The graphics object containing all the necessary properties
* @param webGLData {Object}
*/
PIXI.WebGLGraphics.buildRectangle = function(graphicsData, webGLData)
{
// --- //
// need to convert points to a nice regular data
//
var rectData = graphicsData.points;
var x = rectData[0];
var y = rectData[1];
var width = rectData[2];
var height = rectData[3];
if(graphicsData.fill)
{
var color = PIXI.hex2rgb(graphicsData.fillColor);
var alpha = graphicsData.fillAlpha;
var r = color[0] * alpha;
var g = color[1] * alpha;
var b = color[2] * alpha;
var verts = webGLData.points;
var indices = webGLData.indices;
var vertPos = verts.length/6;
// start
verts.push(x, y);
verts.push(r, g, b, alpha);
verts.push(x + width, y);
verts.push(r, g, b, alpha);
verts.push(x , y + height);
verts.push(r, g, b, alpha);
verts.push(x + width, y + height);
verts.push(r, g, b, alpha);
// insert 2 dead triangles..
indices.push(vertPos, vertPos, vertPos+1, vertPos+2, vertPos+3, vertPos+3);
}
if(graphicsData.lineWidth)
{
var tempPoints = graphicsData.points;
graphicsData.points = [x, y,
x + width, y,
x + width, y + height,
x, y + height,
x, y];
PIXI.WebGLGraphics.buildLine(graphicsData, webGLData);
graphicsData.points = tempPoints;
}
};
/**
* Builds a circle to draw
*
* @static
* @private
* @method buildCircle
* @param graphicsData {Graphics} The graphics object to draw
* @param webGLData {Object}
*/
PIXI.WebGLGraphics.buildCircle = function(graphicsData, webGLData)
{
// need to convert points to a nice regular data
var rectData = graphicsData.points;
var x = rectData[0];
var y = rectData[1];
var width = rectData[2];
var height = rectData[3];
var totalSegs = 40;
var seg = (Math.PI * 2) / totalSegs ;
var i = 0;
if(graphicsData.fill)
{
var color = PIXI.hex2rgb(graphicsData.fillColor);
var alpha = graphicsData.fillAlpha;
var r = color[0] * alpha;
var g = color[1] * alpha;
var b = color[2] * alpha;
var verts = webGLData.points;
var indices = webGLData.indices;
var vecPos = verts.length/6;
indices.push(vecPos);
for (i = 0; i < totalSegs + 1 ; i++)
{
verts.push(x,y, r, g, b, alpha);
verts.push(x + Math.sin(seg * i) * width,
y + Math.cos(seg * i) * height,
r, g, b, alpha);
indices.push(vecPos++, vecPos++);
}
indices.push(vecPos-1);
}
if(graphicsData.lineWidth)
{
var tempPoints = graphicsData.points;
graphicsData.points = [];
for (i = 0; i < totalSegs + 1; i++)
{
graphicsData.points.push(x + Math.sin(seg * i) * width,
y + Math.cos(seg * i) * height);
}
PIXI.WebGLGraphics.buildLine(graphicsData, webGLData);
graphicsData.points = tempPoints;
}
};
/**
* Builds a line to draw
*
* @static
* @private
* @method buildLine
* @param graphicsData {Graphics} The graphics object containing all the necessary properties
* @param webGLData {Object}
*/
PIXI.WebGLGraphics.buildLine = function(graphicsData, webGLData)
{
// TODO OPTIMISE!
var i = 0;
var points = graphicsData.points;
if(points.length === 0)return;
// if the line width is an odd number add 0.5 to align to a whole pixel
if(graphicsData.lineWidth%2)
{
for (i = 0; i < points.length; i++) {
points[i] += 0.5;
}
}
// get first and last point.. figure out the middle!
var firstPoint = new PIXI.Point( points[0], points[1] );
var lastPoint = new PIXI.Point( points[points.length - 2], points[points.length - 1] );
// if the first point is the last point - gonna have issues :)
if(firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y)
{
points.pop();
points.pop();
lastPoint = new PIXI.Point( points[points.length - 2], points[points.length - 1] );
var midPointX = lastPoint.x + (firstPoint.x - lastPoint.x) *0.5;
var midPointY = lastPoint.y + (firstPoint.y - lastPoint.y) *0.5;
points.unshift(midPointX, midPointY);
points.push(midPointX, midPointY);
}
var verts = webGLData.points;
var indices = webGLData.indices;
var length = points.length / 2;
var indexCount = points.length;
var indexStart = verts.length/6;
// DRAW the Line
var width = graphicsData.lineWidth / 2;
// sort color
var color = PIXI.hex2rgb(graphicsData.lineColor);
var alpha = graphicsData.lineAlpha;
var r = color[0] * alpha;
var g = color[1] * alpha;
var b = color[2] * alpha;
var px, py, p1x, p1y, p2x, p2y, p3x, p3y;
var perpx, perpy, perp2x, perp2y, perp3x, perp3y;
var a1, b1, c1, a2, b2, c2;
var denom, pdist, dist;
p1x = points[0];
p1y = points[1];
p2x = points[2];
p2y = points[3];
perpx = -(p1y - p2y);
perpy = p1x - p2x;
dist = Math.sqrt(perpx*perpx + perpy*perpy);
perpx /= dist;
perpy /= dist;
perpx *= width;
perpy *= width;
// start
verts.push(p1x - perpx , p1y - perpy,
r, g, b, alpha);
verts.push(p1x + perpx , p1y + perpy,
r, g, b, alpha);
for (i = 1; i < length-1; i++)
{
p1x = points[(i-1)*2];
p1y = points[(i-1)*2 + 1];
p2x = points[(i)*2];
p2y = points[(i)*2 + 1];
p3x = points[(i+1)*2];
p3y = points[(i+1)*2 + 1];
perpx = -(p1y - p2y);
perpy = p1x - p2x;
dist = Math.sqrt(perpx*perpx + perpy*perpy);
perpx /= dist;
perpy /= dist;
perpx *= width;
perpy *= width;
perp2x = -(p2y - p3y);
perp2y = p2x - p3x;
dist = Math.sqrt(perp2x*perp2x + perp2y*perp2y);
perp2x /= dist;
perp2y /= dist;
perp2x *= width;
perp2y *= width;
a1 = (-perpy + p1y) - (-perpy + p2y);
b1 = (-perpx + p2x) - (-perpx + p1x);
c1 = (-perpx + p1x) * (-perpy + p2y) - (-perpx + p2x) * (-perpy + p1y);
a2 = (-perp2y + p3y) - (-perp2y + p2y);
b2 = (-perp2x + p2x) - (-perp2x + p3x);
c2 = (-perp2x + p3x) * (-perp2y + p2y) - (-perp2x + p2x) * (-perp2y + p3y);
denom = a1*b2 - a2*b1;
if(Math.abs(denom) < 0.1 )
{
denom+=10.1;
verts.push(p2x - perpx , p2y - perpy,
r, g, b, alpha);
verts.push(p2x + perpx , p2y + perpy,
r, g, b, alpha);
continue;
}
px = (b1*c2 - b2*c1)/denom;
py = (a2*c1 - a1*c2)/denom;
pdist = (px -p2x) * (px -p2x) + (py -p2y) + (py -p2y);
if(pdist > 140 * 140)
{
perp3x = perpx - perp2x;
perp3y = perpy - perp2y;
dist = Math.sqrt(perp3x*perp3x + perp3y*perp3y);
perp3x /= dist;
perp3y /= dist;
perp3x *= width;
perp3y *= width;
verts.push(p2x - perp3x, p2y -perp3y);
verts.push(r, g, b, alpha);
verts.push(p2x + perp3x, p2y +perp3y);
verts.push(r, g, b, alpha);
verts.push(p2x - perp3x, p2y -perp3y);
verts.push(r, g, b, alpha);
indexCount++;
}
else
{
verts.push(px , py);
verts.push(r, g, b, alpha);
verts.push(p2x - (px-p2x), p2y - (py - p2y));
verts.push(r, g, b, alpha);
}
}
p1x = points[(length-2)*2];
p1y = points[(length-2)*2 + 1];
p2x = points[(length-1)*2];
p2y = points[(length-1)*2 + 1];
perpx = -(p1y - p2y);
perpy = p1x - p2x;
dist = Math.sqrt(perpx*perpx + perpy*perpy);
perpx /= dist;
perpy /= dist;
perpx *= width;
perpy *= width;
verts.push(p2x - perpx , p2y - perpy);
verts.push(r, g, b, alpha);
verts.push(p2x + perpx , p2y + perpy);
verts.push(r, g, b, alpha);
indices.push(indexStart);
for (i = 0; i < indexCount; i++)
{
indices.push(indexStart++);
}
indices.push(indexStart-1);
};
/**
* Builds a polygon to draw
*
* @static
* @private
* @method buildPoly
* @param graphicsData {Graphics} The graphics object containing all the necessary properties
* @param webGLData {Object}
*/
PIXI.WebGLGraphics.buildPoly = function(graphicsData, webGLData)
{
var points = graphicsData.points;
if(points.length < 6)return;
// get first and last point.. figure out the middle!
var verts = webGLData.points;
var indices = webGLData.indices;
var length = points.length / 2;
// sort color
var color = PIXI.hex2rgb(graphicsData.fillColor);
var alpha = graphicsData.fillAlpha;
var r = color[0] * alpha;
var g = color[1] * alpha;
var b = color[2] * alpha;
var triangles = PIXI.PolyK.Triangulate(points);
var vertPos = verts.length / 6;
var i = 0;
for (i = 0; i < triangles.length; i+=3)
{
indices.push(triangles[i] + vertPos);
indices.push(triangles[i] + vertPos);
indices.push(triangles[i+1] + vertPos);
indices.push(triangles[i+2] +vertPos);
indices.push(triangles[i+2] + vertPos);
}
for (i = 0; i < length; i++)
{
verts.push(points[i * 2], points[i * 2 + 1],
r, g, b, alpha);
}
};
/**
* @author Mat Groves http://matgroves.com/ @Doormat23
*/
PIXI.glContexts = []; // this is where we store the webGL contexts for easy access.
/**
* the WebGLRenderer draws the stage and all its content onto a webGL enabled canvas. This renderer
* should be used for browsers that support webGL. This Render works by automatically managing webGLBatch's.
* So no need for Sprite Batch's or Sprite Cloud's
* Dont forget to add the view to your DOM or you will not see anything :)
*
* @class WebGLRenderer
* @constructor
* @param width=0 {Number} the width of the canvas view
* @param height=0 {Number} the height of the canvas view
* @param view {HTMLCanvasElement} the canvas to use as a view, optional
* @param transparent=false {Boolean} If the render view is transparent, default false
* @param antialias=false {Boolean} sets antialias (only applicable in chrome at the moment)
*
*/
PIXI.WebGLRenderer = function(width, height, view, transparent, antialias)
{
if(!PIXI.defaultRenderer)PIXI.defaultRenderer = this;
this.type = PIXI.WEBGL_RENDERER;
// do a catch.. only 1 webGL renderer..
/**
* Whether the render view is transparent
*
* @property transparent
* @type Boolean
*/
this.transparent = !!transparent;
/**
* The width of the canvas view
*
* @property width
* @type Number
* @default 800
*/
this.width = width || 800;
/**
* The height of the canvas view
*
* @property height
* @type Number
* @default 600
*/
this.height = height || 600;
/**
* The canvas element that everything is drawn to
*
* @property view
* @type HTMLCanvasElement
*/
this.view = view || document.createElement( 'canvas' );
this.view.width = this.width;
this.view.height = this.height;
// deal with losing context..
this.contextLost = this.handleContextLost.bind(this);
this.contextRestoredLost = this.handleContextRestored.bind(this);
this.view.addEventListener('webglcontextlost', this.contextLost, false);
this.view.addEventListener('webglcontextrestored', this.contextRestoredLost, false);
this.options = {
alpha: this.transparent,
antialias:!!antialias, // SPEED UP??
premultipliedAlpha:!!transparent,
stencil:true
};
//try 'experimental-webgl'
try {
this.gl = this.view.getContext('experimental-webgl', this.options);
} catch (e) {
//try 'webgl'
try {
this.gl = this.view.getContext('webgl', this.options);
} catch (e2) {
// fail, not able to get a context
throw new Error(' This browser does not support webGL. Try using the canvas renderer' + this);
}
}
var gl = this.gl;
this.glContextId = gl.id = PIXI.WebGLRenderer.glContextId ++;
PIXI.glContexts[this.glContextId] = gl;
if(!PIXI.blendModesWebGL)
{
PIXI.blendModesWebGL = [];
PIXI.blendModesWebGL[PIXI.blendModes.NORMAL] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
PIXI.blendModesWebGL[PIXI.blendModes.ADD] = [gl.SRC_ALPHA, gl.DST_ALPHA];
PIXI.blendModesWebGL[PIXI.blendModes.MULTIPLY] = [gl.DST_COLOR, gl.ONE_MINUS_SRC_ALPHA];
PIXI.blendModesWebGL[PIXI.blendModes.SCREEN] = [gl.SRC_ALPHA, gl.ONE];
PIXI.blendModesWebGL[PIXI.blendModes.OVERLAY] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
PIXI.blendModesWebGL[PIXI.blendModes.DARKEN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
PIXI.blendModesWebGL[PIXI.blendModes.LIGHTEN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
PIXI.blendModesWebGL[PIXI.blendModes.COLOR_DODGE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
PIXI.blendModesWebGL[PIXI.blendModes.COLOR_BURN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
PIXI.blendModesWebGL[PIXI.blendModes.HARD_LIGHT] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
PIXI.blendModesWebGL[PIXI.blendModes.SOFT_LIGHT] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
PIXI.blendModesWebGL[PIXI.blendModes.DIFFERENCE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
PIXI.blendModesWebGL[PIXI.blendModes.EXCLUSION] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
PIXI.blendModesWebGL[PIXI.blendModes.HUE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
PIXI.blendModesWebGL[PIXI.blendModes.SATURATION] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
PIXI.blendModesWebGL[PIXI.blendModes.COLOR] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
PIXI.blendModesWebGL[PIXI.blendModes.LUMINOSITY] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
}
this.projection = new PIXI.Point();
this.projection.x = this.width/2;
this.projection.y = -this.height/2;
this.offset = new PIXI.Point(0, 0);
this.resize(this.width, this.height);
this.contextLost = false;
// time to create the render managers! each one focuses on managine a state in webGL
this.shaderManager = new PIXI.WebGLShaderManager(gl); // deals with managing the shader programs and their attribs
this.spriteBatch = new PIXI.WebGLSpriteBatch(gl); // manages the rendering of sprites
this.maskManager = new PIXI.WebGLMaskManager(gl); // manages the masks using the stencil buffer
this.filterManager = new PIXI.WebGLFilterManager(gl, this.transparent); // manages the filters
this.renderSession = {};
this.renderSession.gl = this.gl;
this.renderSession.drawCount = 0;
this.renderSession.shaderManager = this.shaderManager;
this.renderSession.maskManager = this.maskManager;
this.renderSession.filterManager = this.filterManager;
this.renderSession.spriteBatch = this.spriteBatch;
this.renderSession.renderer = this;
gl.useProgram(this.shaderManager.defaultShader.program);
gl.disable(gl.DEPTH_TEST);
gl.disable(gl.CULL_FACE);
gl.enable(gl.BLEND);
gl.colorMask(true, true, true, this.transparent);
};
// constructor
PIXI.WebGLRenderer.prototype.constructor = PIXI.WebGLRenderer;
/**
* Renders the stage to its webGL view
*
* @method render
* @param stage {Stage} the Stage element to be rendered
*/
PIXI.WebGLRenderer.prototype.render = function(stage)
{
if(this.contextLost)return;
// if rendering a new stage clear the batches..
if(this.__stage !== stage)
{
if(stage.interactive)stage.interactionManager.removeEvents();
// TODO make this work
// dont think this is needed any more?
this.__stage = stage;
}
// update any textures this includes uvs and uploading them to the gpu
PIXI.WebGLRenderer.updateTextures();
// update the scene graph
stage.updateTransform();
// interaction
if(stage._interactive)
{
//need to add some events!
if(!stage._interactiveEventsAdded)
{
stage._interactiveEventsAdded = true;
stage.interactionManager.setTarget(this);
}
}
var gl = this.gl;
// -- Does this need to be set every frame? -- //
//gl.colorMask(true, true, true, this.transparent);
gl.viewport(0, 0, this.width, this.height);
// make sure we are bound to the main frame buffer
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
if(this.transparent)
{
gl.clearColor(0, 0, 0, 0);
}
else
{
gl.clearColor(stage.backgroundColorSplit[0],stage.backgroundColorSplit[1],stage.backgroundColorSplit[2], 1);
}
gl.clear(gl.COLOR_BUFFER_BIT);
this.renderDisplayObject( stage, this.projection );
// interaction
if(stage.interactive)
{
//need to add some events!
if(!stage._interactiveEventsAdded)
{
stage._interactiveEventsAdded = true;
stage.interactionManager.setTarget(this);
}
}
else
{
if(stage._interactiveEventsAdded)
{
stage._interactiveEventsAdded = false;
stage.interactionManager.setTarget(this);
}
}
/*
//can simulate context loss in Chrome like so:
this.view.onmousedown = function(ev) {
console.dir(this.gl.getSupportedExtensions());
var ext = (
gl.getExtension("WEBGL_scompressed_texture_s3tc")
// gl.getExtension("WEBGL_compressed_texture_s3tc") ||
// gl.getExtension("MOZ_WEBGL_compressed_texture_s3tc") ||
// gl.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc")
);
console.dir(ext);
var loseCtx = this.gl.getExtension("WEBGL_lose_context");
console.log("killing context");
loseCtx.loseContext();
setTimeout(function() {
console.log("restoring context...");
loseCtx.restoreContext();
}.bind(this), 1000);
}.bind(this);
*/
};
/**
* Renders a display Object
*
* @method renderDIsplayObject
* @param displayObject {DisplayObject} The DisplayObject to render
* @param projection {Point} The projection
* @param buffer {Array} a standard WebGL buffer
*/
PIXI.WebGLRenderer.prototype.renderDisplayObject = function(displayObject, projection, buffer)
{
// reset the render session data..
this.renderSession.drawCount = 0;
this.renderSession.currentBlendMode = 9999;
this.renderSession.projection = projection;
this.renderSession.offset = this.offset;
// start the sprite batch
this.spriteBatch.begin(this.renderSession);
// start the filter manager
this.filterManager.begin(this.renderSession, buffer);
// render the scene!
displayObject._renderWebGL(this.renderSession);
// finish the sprite batch
this.spriteBatch.end();
};
/**
* Updates the textures loaded into this webgl renderer
*
* @static
* @method updateTextures
* @private
*/
PIXI.WebGLRenderer.updateTextures = function()
{
var i = 0;
//TODO break this out into a texture manager...
//for (i = 0; i < PIXI.texturesToUpdate.length; i++)
// PIXI.WebGLRenderer.updateTexture(PIXI.texturesToUpdate[i]);
for (i=0; i < PIXI.Texture.frameUpdates.length; i++)
PIXI.WebGLRenderer.updateTextureFrame(PIXI.Texture.frameUpdates[i]);
for (i = 0; i < PIXI.texturesToDestroy.length; i++)
PIXI.WebGLRenderer.destroyTexture(PIXI.texturesToDestroy[i]);
PIXI.texturesToUpdate.length = 0;
PIXI.texturesToDestroy.length = 0;
PIXI.Texture.frameUpdates.length = 0;
};
/**
* Destroys a loaded webgl texture
*
* @method destroyTexture
* @param texture {Texture} The texture to update
* @private
*/
PIXI.WebGLRenderer.destroyTexture = function(texture)
{
//TODO break this out into a texture manager...
for (var i = texture._glTextures.length - 1; i >= 0; i--)
{
var glTexture = texture._glTextures[i];
var gl = PIXI.glContexts[i];
if(gl && glTexture)
{
gl.deleteTexture(glTexture);
}
}
texture._glTextures.length = 0;
};
/**
*
* @method updateTextureFrame
* @param texture {Texture} The texture to update the frame from
* @private
*/
PIXI.WebGLRenderer.updateTextureFrame = function(texture)
{
texture.updateFrame = false;
// now set the uvs. Figured that the uv data sits with a texture rather than a sprite.
// so uv data is stored on the texture itself
texture._updateWebGLuvs();
};
/**
* resizes the webGL view to the specified width and height
*
* @method resize
* @param width {Number} the new width of the webGL view
* @param height {Number} the new height of the webGL view
*/
PIXI.WebGLRenderer.prototype.resize = function(width, height)
{
this.width = width;
this.height = height;
this.view.width = width;
this.view.height = height;
this.gl.viewport(0, 0, this.width, this.height);
this.projection.x = this.width/2;
this.projection.y = -this.height/2;
};
/**
* Creates a WebGL texture
*
* @method createWebGLTexture
* @param texture {Texture} the texture to render
* @param gl {webglContext} the WebGL context
* @static
*/
PIXI.createWebGLTexture = function(texture, gl)
{
if(texture.hasLoaded)
{
texture._glTextures[gl.id] = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, texture._glTextures[gl.id]);
gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, texture.source);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, texture.scaleMode === PIXI.scaleModes.LINEAR ? gl.LINEAR : gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, texture.scaleMode === PIXI.scaleModes.LINEAR ? gl.LINEAR : gl.NEAREST);
// reguler...
if(!texture._powerOf2)
{
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
}
else
{
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT);
}
gl.bindTexture(gl.TEXTURE_2D, null);
}
return texture._glTextures[gl.id];
};
/**
* Updates a WebGL texture
*
* @method updateWebGLTexture
* @param texture {Texture} the texture to update
* @param gl {webglContext} the WebGL context
* @private
*/
PIXI.updateWebGLTexture = function(texture, gl)
{
if( texture._glTextures[gl.id] )
{
gl.bindTexture(gl.TEXTURE_2D, texture._glTextures[gl.id]);
gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, texture.source);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, texture.scaleMode === PIXI.scaleModes.LINEAR ? gl.LINEAR : gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, texture.scaleMode === PIXI.scaleModes.LINEAR ? gl.LINEAR : gl.NEAREST);
// reguler...
if(!texture._powerOf2)
{
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
}
else
{
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT);
}
gl.bindTexture(gl.TEXTURE_2D, null);
}
};
/**
* Handles a lost webgl context
*
* @method handleContextLost
* @param event {Event}
* @private
*/
PIXI.WebGLRenderer.prototype.handleContextLost = function(event)
{
event.preventDefault();
this.contextLost = true;
};
/**
* Handles a restored webgl context
*
* @method handleContextRestored
* @param event {Event}
* @private
*/
PIXI.WebGLRenderer.prototype.handleContextRestored = function()
{
//try 'experimental-webgl'
try {
this.gl = this.view.getContext('experimental-webgl', this.options);
} catch (e) {
//try 'webgl'
try {
this.gl = this.view.getContext('webgl', this.options);
} catch (e2) {
// fail, not able to get a context
throw new Error(' This browser does not support webGL. Try using the canvas renderer' + this);
}
}
var gl = this.gl;
gl.id = PIXI.WebGLRenderer.glContextId ++;
// need to set the context...
this.shaderManager.setContext(gl);
this.spriteBatch.setContext(gl);
this.maskManager.setContext(gl);
this.filterManager.setContext(gl);
this.renderSession.gl = this.gl;
gl.disable(gl.DEPTH_TEST);
gl.disable(gl.CULL_FACE);
gl.enable(gl.BLEND);
gl.colorMask(true, true, true, this.transparent);
this.gl.viewport(0, 0, this.width, this.height);
for(var key in PIXI.TextureCache)
{
var texture = PIXI.TextureCache[key].baseTexture;
texture._glTextures = [];
}
/**
* Whether the context was lost
* @property contextLost
* @type Boolean
*/
this.contextLost = false;
};
/**
* Removes everything from the renderer (event listeners, spritebatch, etc...)
*
* @method destroy
*/
PIXI.WebGLRenderer.prototype.destroy = function()
{
// deal with losing context..
// remove listeners
this.view.removeEventListener('webglcontextlost', this.contextLost);
this.view.removeEventListener('webglcontextrestored', this.contextRestoredLost);
PIXI.glContexts[this.glContextId] = null;
this.projection = null;
this.offset = null;
// time to create the render managers! each one focuses on managine a state in webGL
this.shaderManager.destroy();
this.spriteBatch.destroy();
this.maskManager.destroy();
this.filterManager.destroy();
this.shaderManager = null;
this.spriteBatch = null;
this.maskManager = null;
this.filterManager = null;
this.gl = null;
//
this.renderSession = null;
};
PIXI.WebGLRenderer.glContextId = 0;
/**
* @author Mat Groves http://matgroves.com/ @Doormat23
*/
/**
* @class WebGLMaskManager
* @constructor
* @param gl {WebGLContext} the current WebGL drawing context
* @private
*/
PIXI.WebGLMaskManager = function(gl)
{
this.maskStack = [];
this.maskPosition = 0;
this.setContext(gl);
};
/**
* Sets the drawing context to the one given in parameter
* @method setContext
* @param gl {WebGLContext} the current WebGL drawing context
*/
PIXI.WebGLMaskManager.prototype.setContext = function(gl)
{
this.gl = gl;
};
/**
* Applies the Mask and adds it to the current filter stack
* @method pushMask
* @param maskData {Array}
* @param renderSession {RenderSession}
*/
PIXI.WebGLMaskManager.prototype.pushMask = function(maskData, renderSession)
{
var gl = this.gl;
if(this.maskStack.length === 0)
{
gl.enable(gl.STENCIL_TEST);
gl.stencilFunc(gl.ALWAYS,1,1);
}
// maskData.visible = false;
this.maskStack.push(maskData);
gl.colorMask(false, false, false, true);
gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR);
PIXI.WebGLGraphics.renderGraphics(maskData, renderSession);
gl.colorMask(true, true, true, true);
gl.stencilFunc(gl.NOTEQUAL,0, this.maskStack.length);
gl.stencilOp(gl.KEEP,gl.KEEP,gl.KEEP);
};
/**
* Removes the last filter from the filter stack and doesn't return it
* @method popMask
*
* @param renderSession {RenderSession} an object containing all the useful parameters
*/
PIXI.WebGLMaskManager.prototype.popMask = function(renderSession)
{
var gl = this.gl;
var maskData = this.maskStack.pop();
if(maskData)
{
gl.colorMask(false, false, false, false);
//gl.stencilFunc(gl.ALWAYS,1,1);
gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR);
PIXI.WebGLGraphics.renderGraphics(maskData, renderSession);
gl.colorMask(true, true, true, true);
gl.stencilFunc(gl.NOTEQUAL,0,this.maskStack.length);
gl.stencilOp(gl.KEEP,gl.KEEP,gl.KEEP);
}
if(this.maskStack.length === 0)gl.disable(gl.STENCIL_TEST);
};
/**
* Destroys the mask stack
* @method destroy
*/
PIXI.WebGLMaskManager.prototype.destroy = function()
{
this.maskStack = null;
this.gl = null;
};
/**
* @author Mat Groves http://matgroves.com/ @Doormat23
*/
/**
* @class WebGLShaderManager
* @constructor
* @param gl {WebGLContext} the current WebGL drawing context
* @private
*/
PIXI.WebGLShaderManager = function(gl)
{
this.maxAttibs = 10;
this.attribState = [];
this.tempAttribState = [];
for (var i = 0; i < this.maxAttibs; i++) {
this.attribState[i] = false;
}
this.setContext(gl);
// the final one is used for the rendering strips
//this.stripShader = new PIXI.StripShader(gl);
};
/**
* Initialises the context and the properties
* @method setContext
* @param gl {WebGLContext} the current WebGL drawing context
* @param transparent {Boolean} Whether or not the drawing context should be transparent
*/
PIXI.WebGLShaderManager.prototype.setContext = function(gl)
{
this.gl = gl;
// the next one is used for rendering primatives
this.primitiveShader = new PIXI.PrimitiveShader(gl);
// this shader is used for the default sprite rendering
this.defaultShader = new PIXI.PixiShader(gl);
// this shader is used for the fast sprite rendering
this.fastShader = new PIXI.PixiFastShader(gl);
this.activateShader(this.defaultShader);
};
/**
* Takes the attributes given in parameters
* @method setAttribs
* @param attribs {Array} attribs
*/
PIXI.WebGLShaderManager.prototype.setAttribs = function(attribs)
{
// reset temp state
var i;
for (i = 0; i < this.tempAttribState.length; i++)
{
this.tempAttribState[i] = false;
}
// set the new attribs
for (i = 0; i < attribs.length; i++)
{
var attribId = attribs[i];
this.tempAttribState[attribId] = true;
}
var gl = this.gl;
for (i = 0; i < this.attribState.length; i++)
{
if(this.attribState[i] !== this.tempAttribState[i])
{
this.attribState[i] = this.tempAttribState[i];
if(this.tempAttribState[i])
{
gl.enableVertexAttribArray(i);
}
else
{
gl.disableVertexAttribArray(i);
}
}
}
};
/**
* Sets-up the given shader
*
* @method activateShader
* @param shader {Object} the shader that is going to be activated
*/
PIXI.WebGLShaderManager.prototype.activateShader = function(shader)
{
//if(this.currentShader == shader)return;
this.currentShader = shader;
this.gl.useProgram(shader.program);
this.setAttribs(shader.attributes);
};
/**
* Triggers the primitive shader
* @method activatePrimitiveShader
*/
PIXI.WebGLShaderManager.prototype.activatePrimitiveShader = function()
{
var gl = this.gl;
gl.useProgram(this.primitiveShader.program);
this.setAttribs(this.primitiveShader.attributes);
};
/**
* Disable the primitive shader
* @method deactivatePrimitiveShader
*/
PIXI.WebGLShaderManager.prototype.deactivatePrimitiveShader = function()
{
var gl = this.gl;
gl.useProgram(this.defaultShader.program);
this.setAttribs(this.defaultShader.attributes);
};
/**
* Destroys
* @method destroy
*/
PIXI.WebGLShaderManager.prototype.destroy = function()
{
this.attribState = null;
this.tempAttribState = null;
this.primitiveShader.destroy();
this.defaultShader.destroy();
this.fastShader.destroy();
this.gl = null;
};
/**
* @author Mat Groves
*
* Big thanks to the very clever Matt DesLauriers <mattdesl> https://github.com/mattdesl/
* for creating the original pixi version!
*
* Heavily inspired by LibGDX's WebGLSpriteBatch:
* https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/WebGLSpriteBatch.java
*/
/**
*
* @class WebGLSpriteBatch
* @private
* @constructor
* @param gl {WebGLContext} the current WebGL drawing context
*
*/
PIXI.WebGLSpriteBatch = function(gl)
{
/**
*
*
* @property vertSize
* @type Number
*/
this.vertSize = 6;
/**
* The number of images in the SpriteBatch before it flushes
* @property size
* @type Number
*/
this.size = 2000;//Math.pow(2, 16) / this.vertSize;
//the total number of floats in our batch
var numVerts = this.size * 4 * this.vertSize;
//the total number of indices in our batch
var numIndices = this.size * 6;
//vertex data
/**
* Holds the vertices
*
* @property vertices
* @type Float32Array
*/
this.vertices = new Float32Array(numVerts);
//index data
/**
* Holds the indices
*
* @property indices
* @type Uint16Array
*/
this.indices = new Uint16Array(numIndices);
this.lastIndexCount = 0;
for (var i=0, j=0; i < numIndices; i += 6, j += 4)
{
this.indices[i + 0] = j + 0;
this.indices[i + 1] = j + 1;
this.indices[i + 2] = j + 2;
this.indices[i + 3] = j + 0;
this.indices[i + 4] = j + 2;
this.indices[i + 5] = j + 3;
}
this.drawing = false;
this.currentBatchSize = 0;
this.currentBaseTexture = null;
this.setContext(gl);
};
/**
*
* @method setContext
*
* @param gl {WebGLContext} the current WebGL drawing context
*/
PIXI.WebGLSpriteBatch.prototype.setContext = function(gl)
{
this.gl = gl;
// create a couple of buffers
this.vertexBuffer = gl.createBuffer();
this.indexBuffer = gl.createBuffer();
// 65535 is max index, so 65535 / 6 = 10922.
//upload the index data
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer);
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.indices, gl.STATIC_DRAW);
gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);
gl.bufferData(gl.ARRAY_BUFFER, this.vertices, gl.DYNAMIC_DRAW);
this.currentBlendMode = 99999;
};
/**
*
* @method begin
*
* @param renderSession {RenderSession} the RenderSession
*/
PIXI.WebGLSpriteBatch.prototype.begin = function(renderSession)
{
this.renderSession = renderSession;
this.shader = this.renderSession.shaderManager.defaultShader;
this.start();
};
/**
*
* @method end
*
*/
PIXI.WebGLSpriteBatch.prototype.end = function()
{
this.flush();
};
/**
*
* @method render
*
* @param sprite {Sprite} the sprite to render when using this spritebatch
*/
PIXI.WebGLSpriteBatch.prototype.render = function(sprite)
{
var texture = sprite.texture;
// check texture..
if(texture.baseTexture !== this.currentBaseTexture || this.currentBatchSize >= this.size)
{
this.flush();
this.currentBaseTexture = texture.baseTexture;
}
// check blend mode
if(sprite.blendMode !== this.currentBlendMode)
{
this.setBlendMode(sprite.blendMode);
}
// get the uvs for the texture
var uvs = sprite._uvs || sprite.texture._uvs;
// if the uvs have not updated then no point rendering just yet!
if(!uvs)return;
// get the sprites current alpha
var alpha = sprite.worldAlpha;
var tint = sprite.tint;
var verticies = this.vertices;
// TODO trim??
var aX = sprite.anchor.x;
var aY = sprite.anchor.y;
var w0, w1, h0, h1;
if (sprite.texture.trim)
{
// if the sprite is trimmed then we need to add the extra space before transforming the sprite coords..
var trim = sprite.texture.trim;
w1 = trim.x - aX * trim.width;
w0 = w1 + texture.frame.width;
h1 = trim.y - aY * trim.height;
h0 = h1 + texture.frame.height;
}
else
{
w0 = (texture.frame.width ) * (1-aX);
w1 = (texture.frame.width ) * -aX;
h0 = texture.frame.height * (1-aY);
h1 = texture.frame.height * -aY;
}
var index = this.currentBatchSize * 4 * this.vertSize;
var worldTransform = sprite.worldTransform;//.toArray();
var a = worldTransform.a;//[0];
var b = worldTransform.c;//[3];
var c = worldTransform.b;//[1];
var d = worldTransform.d;//[4];
var tx = worldTransform.tx;//[2];
var ty = worldTransform.ty;///[5];
// xy
verticies[index++] = a * w1 + c * h1 + tx;
verticies[index++] = d * h1 + b * w1 + ty;
// uv
verticies[index++] = uvs.x0;
verticies[index++] = uvs.y0;
// color
verticies[index++] = alpha;
verticies[index++] = tint;
// xy
verticies[index++] = a * w0 + c * h1 + tx;
verticies[index++] = d * h1 + b * w0 + ty;
// uv
verticies[index++] = uvs.x1;
verticies[index++] = uvs.y1;
// color
verticies[index++] = alpha;
verticies[index++] = tint;
// xy
verticies[index++] = a * w0 + c * h0 + tx;
verticies[index++] = d * h0 + b * w0 + ty;
// uv
verticies[index++] = uvs.x2;
verticies[index++] = uvs.y2;
// color
verticies[index++] = alpha;
verticies[index++] = tint;
// xy
verticies[index++] = a * w1 + c * h0 + tx;
verticies[index++] = d * h0 + b * w1 + ty;
// uv
verticies[index++] = uvs.x3;
verticies[index++] = uvs.y3;
// color
verticies[index++] = alpha;
verticies[index++] = tint;
// increment the batchsize
this.currentBatchSize++;
};
/**
* Renders a tilingSprite using the spriteBatch
* @method renderTilingSprite
*
* @param sprite {TilingSprite} the tilingSprite to render
*/
PIXI.WebGLSpriteBatch.prototype.renderTilingSprite = function(tilingSprite)
{
var texture = tilingSprite.tilingTexture;
if(texture.baseTexture !== this.currentBaseTexture || this.currentBatchSize >= this.size)
{
this.flush();
this.currentBaseTexture = texture.baseTexture;
}
// check blend mode
if(tilingSprite.blendMode !== this.currentBlendMode)
{
this.setBlendMode(tilingSprite.blendMode);
}
// set the textures uvs temporarily
// TODO create a separate texture so that we can tile part of a texture
if(!tilingSprite._uvs)tilingSprite._uvs = new PIXI.TextureUvs();
var uvs = tilingSprite._uvs;
tilingSprite.tilePosition.x %= texture.baseTexture.width * tilingSprite.tileScaleOffset.x;
tilingSprite.tilePosition.y %= texture.baseTexture.height * tilingSprite.tileScaleOffset.y;
var offsetX = tilingSprite.tilePosition.x/(texture.baseTexture.width*tilingSprite.tileScaleOffset.x);
var offsetY = tilingSprite.tilePosition.y/(texture.baseTexture.height*tilingSprite.tileScaleOffset.y);
var scaleX = (tilingSprite.width / texture.baseTexture.width) / (tilingSprite.tileScale.x * tilingSprite.tileScaleOffset.x);
var scaleY = (tilingSprite.height / texture.baseTexture.height) / (tilingSprite.tileScale.y * tilingSprite.tileScaleOffset.y);
uvs.x0 = 0 - offsetX;
uvs.y0 = 0 - offsetY;
uvs.x1 = (1 * scaleX) - offsetX;
uvs.y1 = 0 - offsetY;
uvs.x2 = (1 * scaleX) - offsetX;
uvs.y2 = (1 * scaleY) - offsetY;
uvs.x3 = 0 - offsetX;
uvs.y3 = (1 *scaleY) - offsetY;
// get the tilingSprites current alpha
var alpha = tilingSprite.worldAlpha;
var tint = tilingSprite.tint;
var verticies = this.vertices;
var width = tilingSprite.width;
var height = tilingSprite.height;
// TODO trim??
var aX = tilingSprite.anchor.x; // - tilingSprite.texture.trim.x
var aY = tilingSprite.anchor.y; //- tilingSprite.texture.trim.y
var w0 = width * (1-aX);
var w1 = width * -aX;
var h0 = height * (1-aY);
var h1 = height * -aY;
var index = this.currentBatchSize * 4 * this.vertSize;
var worldTransform = tilingSprite.worldTransform;
var a = worldTransform.a;//[0];
var b = worldTransform.c;//[3];
var c = worldTransform.b;//[1];
var d = worldTransform.d;//[4];
var tx = worldTransform.tx;//[2];
var ty = worldTransform.ty;///[5];
// xy
verticies[index++] = a * w1 + c * h1 + tx;
verticies[index++] = d * h1 + b * w1 + ty;
// uv
verticies[index++] = uvs.x0;
verticies[index++] = uvs.y0;
// color
verticies[index++] = alpha;
verticies[index++] = tint;
// xy
verticies[index++] = a * w0 + c * h1 + tx;
verticies[index++] = d * h1 + b * w0 + ty;
// uv
verticies[index++] = uvs.x1;
verticies[index++] = uvs.y1;
// color
verticies[index++] = alpha;
verticies[index++] = tint;
// xy
verticies[index++] = a * w0 + c * h0 + tx;
verticies[index++] = d * h0 + b * w0 + ty;
// uv
verticies[index++] = uvs.x2;
verticies[index++] = uvs.y2;
// color
verticies[index++] = alpha;
verticies[index++] = tint;
// xy
verticies[index++] = a * w1 + c * h0 + tx;
verticies[index++] = d * h0 + b * w1 + ty;
// uv
verticies[index++] = uvs.x3;
verticies[index++] = uvs.y3;
// color
verticies[index++] = alpha;
verticies[index++] = tint;
// increment the batchs
this.currentBatchSize++;
};
/**
* Renders the content and empties the current batch
*
* @method flush
*
*/
PIXI.WebGLSpriteBatch.prototype.flush = function()
{
// If the batch is length 0 then return as there is nothing to draw
if (this.currentBatchSize===0)return;
var gl = this.gl;
// bind the current texture
gl.bindTexture(gl.TEXTURE_2D, this.currentBaseTexture._glTextures[gl.id] || PIXI.createWebGLTexture(this.currentBaseTexture, gl));
// upload the verts to the buffer
if(this.currentBatchSize > ( this.size * 0.5 ) )
{
gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices);
}
else
{
var view = this.vertices.subarray(0, this.currentBatchSize * 4 * this.vertSize);
gl.bufferSubData(gl.ARRAY_BUFFER, 0, view);
}
// var view = this.vertices.subarray(0, this.currentBatchSize * 4 * this.vertSize);
//gl.bufferSubData(gl.ARRAY_BUFFER, 0, view);
// now draw those suckas!
gl.drawElements(gl.TRIANGLES, this.currentBatchSize * 6, gl.UNSIGNED_SHORT, 0);
// then reset the batch!
this.currentBatchSize = 0;
// increment the draw count
this.renderSession.drawCount++;
};
/**
*
* @method stop
*
*/
PIXI.WebGLSpriteBatch.prototype.stop = function()
{
this.flush();
};
/**
*
* @method start
*
*/
PIXI.WebGLSpriteBatch.prototype.start = function()
{
var gl = this.gl;
// bind the main texture
gl.activeTexture(gl.TEXTURE0);
// bind the buffers
gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer);
// set the projection
var projection = this.renderSession.projection;
gl.uniform2f(this.shader.projectionVector, projection.x, projection.y);
// set the pointers
var stride = this.vertSize * 4;
gl.vertexAttribPointer(this.shader.aVertexPosition, 2, gl.FLOAT, false, stride, 0);
gl.vertexAttribPointer(this.shader.aTextureCoord, 2, gl.FLOAT, false, stride, 2 * 4);
gl.vertexAttribPointer(this.shader.colorAttribute, 2, gl.FLOAT, false, stride, 4 * 4);
// set the blend mode..
if(this.currentBlendMode !== PIXI.blendModes.NORMAL)
{
this.setBlendMode(PIXI.blendModes.NORMAL);
}
};
/**
* Sets-up the given blendMode from WebGL's point of view
* @method setBlendMode
*
* @param blendMode {Number} the blendMode, should be a Pixi const, such as PIXI.BlendModes.ADD
*/
PIXI.WebGLSpriteBatch.prototype.setBlendMode = function(blendMode)
{
this.flush();
this.currentBlendMode = blendMode;
var blendModeWebGL = PIXI.blendModesWebGL[this.currentBlendMode];
this.gl.blendFunc(blendModeWebGL[0], blendModeWebGL[1]);
};
/**
* Destroys the SpriteBatch
* @method destroy
*/
PIXI.WebGLSpriteBatch.prototype.destroy = function()
{
this.vertices = null;
this.indices = null;
this.gl.deleteBuffer( this.vertexBuffer );
this.gl.deleteBuffer( this.indexBuffer );
this.currentBaseTexture = null;
this.gl = null;
};
/**
* @author Mat Groves
*
* Big thanks to the very clever Matt DesLauriers <mattdesl> https://github.com/mattdesl/
* for creating the original pixi version!
*
* Heavily inspired by LibGDX's WebGLSpriteBatch:
* https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/WebGLSpriteBatch.java
*/
PIXI.WebGLFastSpriteBatch = function(gl)
{
this.vertSize = 10;
this.maxSize = 6000;//Math.pow(2, 16) / this.vertSize;
this.size = this.maxSize;
//the total number of floats in our batch
var numVerts = this.size * 4 * this.vertSize;
//the total number of indices in our batch
var numIndices = this.maxSize * 6;
//vertex data
this.vertices = new Float32Array(numVerts);
//index data
this.indices = new Uint16Array(numIndices);
this.vertexBuffer = null;
this.indexBuffer = null;
this.lastIndexCount = 0;
for (var i=0, j=0; i < numIndices; i += 6, j += 4)
{
this.indices[i + 0] = j + 0;
this.indices[i + 1] = j + 1;
this.indices[i + 2] = j + 2;
this.indices[i + 3] = j + 0;
this.indices[i + 4] = j + 2;
this.indices[i + 5] = j + 3;
}
this.drawing = false;
this.currentBatchSize = 0;
this.currentBaseTexture = null;
this.currentBlendMode = 0;
this.renderSession = null;
this.shader = null;
this.matrix = null;
this.setContext(gl);
};
PIXI.WebGLFastSpriteBatch.prototype.setContext = function(gl)
{
this.gl = gl;
// create a couple of buffers
this.vertexBuffer = gl.createBuffer();
this.indexBuffer = gl.createBuffer();
// 65535 is max index, so 65535 / 6 = 10922.
//upload the index data
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer);
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.indices, gl.STATIC_DRAW);
gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);
gl.bufferData(gl.ARRAY_BUFFER, this.vertices, gl.DYNAMIC_DRAW);
this.currentBlendMode = 99999;
};
PIXI.WebGLFastSpriteBatch.prototype.begin = function(spriteBatch, renderSession)
{
this.renderSession = renderSession;
this.shader = this.renderSession.shaderManager.fastShader;
this.matrix = spriteBatch.worldTransform.toArray(true);
this.start();
};
PIXI.WebGLFastSpriteBatch.prototype.end = function()
{
this.flush();
};
PIXI.WebGLFastSpriteBatch.prototype.render = function(spriteBatch)
{
var children = spriteBatch.children;
var sprite = children[0];
// if the uvs have not updated then no point rendering just yet!
// check texture.
if(!sprite.texture._uvs)return;
this.currentBaseTexture = sprite.texture.baseTexture;
// check blend mode
if(sprite.blendMode !== this.currentBlendMode)
{
this.setBlendMode(sprite.blendMode);
}
for(var i=0,j= children.length; i<j; i++)
{
this.renderSprite(children[i]);
}
this.flush();
};
PIXI.WebGLFastSpriteBatch.prototype.renderSprite = function(sprite)
{
//sprite = children[i];
if(!sprite.visible)return;
// TODO trim??
if(sprite.texture.baseTexture !== this.currentBaseTexture)
{
this.flush();
this.currentBaseTexture = sprite.texture.baseTexture;
if(!sprite.texture._uvs)return;
}
var uvs, verticies = this.vertices, width, height, w0, w1, h0, h1, index;
uvs = sprite.texture._uvs;
width = sprite.texture.frame.width;
height = sprite.texture.frame.height;
if (sprite.texture.trim)
{
// if the sprite is trimmed then we need to add the extra space before transforming the sprite coords..
var trim = sprite.texture.trim;
w1 = trim.x - sprite.anchor.x * trim.width;
w0 = w1 + sprite.texture.frame.width;
h1 = trim.y - sprite.anchor.y * trim.height;
h0 = h1 + sprite.texture.frame.height;
}
else
{
w0 = (sprite.texture.frame.width ) * (1-sprite.anchor.x);
w1 = (sprite.texture.frame.width ) * -sprite.anchor.x;
h0 = sprite.texture.frame.height * (1-sprite.anchor.y);
h1 = sprite.texture.frame.height * -sprite.anchor.y;
}
index = this.currentBatchSize * 4 * this.vertSize;
// xy
verticies[index++] = w1;
verticies[index++] = h1;
verticies[index++] = sprite.position.x;
verticies[index++] = sprite.position.y;
//scale
verticies[index++] = sprite.scale.x;
verticies[index++] = sprite.scale.y;
//rotation
verticies[index++] = sprite.rotation;
// uv
verticies[index++] = uvs.x0;
verticies[index++] = uvs.y1;
// color
verticies[index++] = sprite.alpha;
// xy
verticies[index++] = w0;
verticies[index++] = h1;
verticies[index++] = sprite.position.x;
verticies[index++] = sprite.position.y;
//scale
verticies[index++] = sprite.scale.x;
verticies[index++] = sprite.scale.y;
//rotation
verticies[index++] = sprite.rotation;
// uv
verticies[index++] = uvs.x1;
verticies[index++] = uvs.y1;
// color
verticies[index++] = sprite.alpha;
// xy
verticies[index++] = w0;
verticies[index++] = h0;
verticies[index++] = sprite.position.x;
verticies[index++] = sprite.position.y;
//scale
verticies[index++] = sprite.scale.x;
verticies[index++] = sprite.scale.y;
//rotation
verticies[index++] = sprite.rotation;
// uv
verticies[index++] = uvs.x2;
verticies[index++] = uvs.y2;
// color
verticies[index++] = sprite.alpha;
// xy
verticies[index++] = w1;
verticies[index++] = h0;
verticies[index++] = sprite.position.x;
verticies[index++] = sprite.position.y;
//scale
verticies[index++] = sprite.scale.x;
verticies[index++] = sprite.scale.y;
//rotation
verticies[index++] = sprite.rotation;
// uv
verticies[index++] = uvs.x3;
verticies[index++] = uvs.y3;
// color
verticies[index++] = sprite.alpha;
// increment the batchs
this.currentBatchSize++;
if(this.currentBatchSize >= this.size)
{
this.flush();
}
};
PIXI.WebGLFastSpriteBatch.prototype.flush = function()
{
// If the batch is length 0 then return as there is nothing to draw
if (this.currentBatchSize===0)return;
var gl = this.gl;
// bind the current texture
if(!this.currentBaseTexture._glTextures[gl.id])PIXI.createWebGLTexture(this.currentBaseTexture, gl);
gl.bindTexture(gl.TEXTURE_2D, this.currentBaseTexture._glTextures[gl.id]);// || PIXI.createWebGLTexture(this.currentBaseTexture, gl));
// upload the verts to the buffer
if(this.currentBatchSize > ( this.size * 0.5 ) )
{
gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices);
}
else
{
var view = this.vertices.subarray(0, this.currentBatchSize * 4 * this.vertSize);
gl.bufferSubData(gl.ARRAY_BUFFER, 0, view);
}
// now draw those suckas!
gl.drawElements(gl.TRIANGLES, this.currentBatchSize * 6, gl.UNSIGNED_SHORT, 0);
// then reset the batch!
this.currentBatchSize = 0;
// increment the draw count
this.renderSession.drawCount++;
};
PIXI.WebGLFastSpriteBatch.prototype.stop = function()
{
this.flush();
};
PIXI.WebGLFastSpriteBatch.prototype.start = function()
{
var gl = this.gl;
// bind the main texture
gl.activeTexture(gl.TEXTURE0);
// bind the buffers
gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer);
// set the projection
var projection = this.renderSession.projection;
gl.uniform2f(this.shader.projectionVector, projection.x, projection.y);
// set the matrix
gl.uniformMatrix3fv(this.shader.uMatrix, false, this.matrix);
// set the pointers
var stride = this.vertSize * 4;
gl.vertexAttribPointer(this.shader.aVertexPosition, 2, gl.FLOAT, false, stride, 0);
gl.vertexAttribPointer(this.shader.aPositionCoord, 2, gl.FLOAT, false, stride, 2 * 4);
gl.vertexAttribPointer(this.shader.aScale, 2, gl.FLOAT, false, stride, 4 * 4);
gl.vertexAttribPointer(this.shader.aRotation, 1, gl.FLOAT, false, stride, 6 * 4);
gl.vertexAttribPointer(this.shader.aTextureCoord, 2, gl.FLOAT, false, stride, 7 * 4);
gl.vertexAttribPointer(this.shader.colorAttribute, 1, gl.FLOAT, false, stride, 9 * 4);
// set the blend mode..
if(this.currentBlendMode !== PIXI.blendModes.NORMAL)
{
this.setBlendMode(PIXI.blendModes.NORMAL);
}
};
PIXI.WebGLFastSpriteBatch.prototype.setBlendMode = function(blendMode)
{
this.flush();
this.currentBlendMode = blendMode;
var blendModeWebGL = PIXI.blendModesWebGL[this.currentBlendMode];
this.gl.blendFunc(blendModeWebGL[0], blendModeWebGL[1]);
};
/**
* @author Mat Groves http://matgroves.com/ @Doormat23
*/
/**
* @class WebGLFilterManager
* @constructor
* @param gl {WebGLContext} the current WebGL drawing context
* @param transparent {Boolean} Whether or not the drawing context should be transparent
* @private
*/
PIXI.WebGLFilterManager = function(gl, transparent)
{
this.transparent = transparent;
this.filterStack = [];
this.offsetX = 0;
this.offsetY = 0;
this.setContext(gl);
};
// API
/**
* Initialises the context and the properties
* @method setContext
* @param gl {WebGLContext} the current WebGL drawing context
*/
PIXI.WebGLFilterManager.prototype.setContext = function(gl)
{
this.gl = gl;
this.texturePool = [];
this.initShaderBuffers();
};
/**
*
* @method begin
* @param renderSession {RenderSession}
* @param buffer {ArrayBuffer}
*/
PIXI.WebGLFilterManager.prototype.begin = function(renderSession, buffer)
{
this.renderSession = renderSession;
this.defaultShader = renderSession.shaderManager.defaultShader;
var projection = this.renderSession.projection;
// console.log(this.width)
this.width = projection.x * 2;
this.height = -projection.y * 2;
this.buffer = buffer;
};
/**
* Applies the filter and adds it to the current filter stack
* @method pushFilter
* @param filterBlock {Object} the filter that will be pushed to the current filter stack
*/
PIXI.WebGLFilterManager.prototype.pushFilter = function(filterBlock)
{
var gl = this.gl;
var projection = this.renderSession.projection;
var offset = this.renderSession.offset;
// filter program
// OPTIMISATION - the first filter is free if its a simple color change?
this.filterStack.push(filterBlock);
var filter = filterBlock.filterPasses[0];
this.offsetX += filterBlock.target.filterArea.x;
this.offsetY += filterBlock.target.filterArea.y;
var texture = this.texturePool.pop();
if(!texture)
{
texture = new PIXI.FilterTexture(this.gl, this.width, this.height);
}
else
{
texture.resize(this.width, this.height);
}
gl.bindTexture(gl.TEXTURE_2D, texture.texture);
filterBlock.target.filterArea = filterBlock.target.getBounds();
var filterArea = filterBlock.target.filterArea;
var padidng = filter.padding;
filterArea.x -= padidng;
filterArea.y -= padidng;
filterArea.width += padidng * 2;
filterArea.height += padidng * 2;
// cap filter to screen size..
if(filterArea.x < 0)filterArea.x = 0;
if(filterArea.width > this.width)filterArea.width = this.width;
if(filterArea.y < 0)filterArea.y = 0;
if(filterArea.height > this.height)filterArea.height = this.height;
//gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, filterArea.width, filterArea.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
gl.bindFramebuffer(gl.FRAMEBUFFER, texture.frameBuffer);
// set view port
gl.viewport(0, 0, filterArea.width, filterArea.height);
projection.x = filterArea.width/2;
projection.y = -filterArea.height/2;
offset.x = -filterArea.x;
offset.y = -filterArea.y;
// update projection
gl.uniform2f(this.defaultShader.projectionVector, filterArea.width/2, -filterArea.height/2);
gl.uniform2f(this.defaultShader.offsetVector, -filterArea.x, -filterArea.y);
gl.colorMask(true, true, true, true);
gl.clearColor(0,0,0, 0);
gl.clear(gl.COLOR_BUFFER_BIT);
filterBlock._glFilterTexture = texture;
};
/**
* Removes the last filter from the filter stack and doesn't return it
* @method popFilter
*/
PIXI.WebGLFilterManager.prototype.popFilter = function()
{
var gl = this.gl;
var filterBlock = this.filterStack.pop();
var filterArea = filterBlock.target.filterArea;
var texture = filterBlock._glFilterTexture;
var projection = this.renderSession.projection;
var offset = this.renderSession.offset;
if(filterBlock.filterPasses.length > 1)
{
gl.viewport(0, 0, filterArea.width, filterArea.height);
gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);
this.vertexArray[0] = 0;
this.vertexArray[1] = filterArea.height;
this.vertexArray[2] = filterArea.width;
this.vertexArray[3] = filterArea.height;
this.vertexArray[4] = 0;
this.vertexArray[5] = 0;
this.vertexArray[6] = filterArea.width;
this.vertexArray[7] = 0;
gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertexArray);
gl.bindBuffer(gl.ARRAY_BUFFER, this.uvBuffer);
// now set the uvs..
this.uvArray[2] = filterArea.width/this.width;
this.uvArray[5] = filterArea.height/this.height;
this.uvArray[6] = filterArea.width/this.width;
this.uvArray[7] = filterArea.height/this.height;
gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.uvArray);
var inputTexture = texture;
var outputTexture = this.texturePool.pop();
if(!outputTexture)outputTexture = new PIXI.FilterTexture(this.gl, this.width, this.height);
outputTexture.resize(this.width, this.height);
// need to clear this FBO as it may have some left over elements from a previous filter.
gl.bindFramebuffer(gl.FRAMEBUFFER, outputTexture.frameBuffer );
gl.clear(gl.COLOR_BUFFER_BIT);
gl.disable(gl.BLEND);
for (var i = 0; i < filterBlock.filterPasses.length-1; i++)
{
var filterPass = filterBlock.filterPasses[i];
gl.bindFramebuffer(gl.FRAMEBUFFER, outputTexture.frameBuffer );
// set texture
gl.activeTexture(gl.TEXTURE0);
gl.bindTexture(gl.TEXTURE_2D, inputTexture.texture);
// draw texture..
//filterPass.applyFilterPass(filterArea.width, filterArea.height);
this.applyFilterPass(filterPass, filterArea, filterArea.width, filterArea.height);
// swap the textures..
var temp = inputTexture;
inputTexture = outputTexture;
outputTexture = temp;
}
gl.enable(gl.BLEND);
texture = inputTexture;
this.texturePool.push(outputTexture);
}
var filter = filterBlock.filterPasses[filterBlock.filterPasses.length-1];
this.offsetX -= filterArea.x;
this.offsetY -= filterArea.y;
var sizeX = this.width;
var sizeY = this.height;
var offsetX = 0;
var offsetY = 0;
var buffer = this.buffer;
// time to render the filters texture to the previous scene
if(this.filterStack.length === 0)
{
gl.colorMask(true, true, true, true);//this.transparent);
}
else
{
var currentFilter = this.filterStack[this.filterStack.length-1];
filterArea = currentFilter.target.filterArea;
sizeX = filterArea.width;
sizeY = filterArea.height;
offsetX = filterArea.x;
offsetY = filterArea.y;
buffer = currentFilter._glFilterTexture.frameBuffer;
}
// TODO need toremove thease global elements..
projection.x = sizeX/2;
projection.y = -sizeY/2;
offset.x = offsetX;
offset.y = offsetY;
filterArea = filterBlock.target.filterArea;
var x = filterArea.x-offsetX;
var y = filterArea.y-offsetY;
// update the buffers..
// make sure to flip the y!
gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);
this.vertexArray[0] = x;
this.vertexArray[1] = y + filterArea.height;
this.vertexArray[2] = x + filterArea.width;
this.vertexArray[3] = y + filterArea.height;
this.vertexArray[4] = x;
this.vertexArray[5] = y;
this.vertexArray[6] = x + filterArea.width;
this.vertexArray[7] = y;
gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertexArray);
gl.bindBuffer(gl.ARRAY_BUFFER, this.uvBuffer);
this.uvArray[2] = filterArea.width/this.width;
this.uvArray[5] = filterArea.height/this.height;
this.uvArray[6] = filterArea.width/this.width;
this.uvArray[7] = filterArea.height/this.height;
gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.uvArray);
//console.log(this.vertexArray)
//console.log(this.uvArray)
//console.log(sizeX + " : " + sizeY)
gl.viewport(0, 0, sizeX, sizeY);
// bind the buffer
gl.bindFramebuffer(gl.FRAMEBUFFER, buffer );
// set the blend mode!
//gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA)
// set texture
gl.activeTexture(gl.TEXTURE0);
gl.bindTexture(gl.TEXTURE_2D, texture.texture);
// apply!
this.applyFilterPass(filter, filterArea, sizeX, sizeY);
// now restore the regular shader..
gl.useProgram(this.defaultShader.program);
gl.uniform2f(this.defaultShader.projectionVector, sizeX/2, -sizeY/2);
gl.uniform2f(this.defaultShader.offsetVector, -offsetX, -offsetY);
// return the texture to the pool
this.texturePool.push(texture);
filterBlock._glFilterTexture = null;
};
/**
* Applies the filter to the specified area
* @method applyFilterPass
* @param filter {AbstractFilter} the filter that needs to be applied
* @param filterArea {texture} TODO - might need an update
* @param width {Number} the horizontal range of the filter
* @param height {Number} the vertical range of the filter
*/
PIXI.WebGLFilterManager.prototype.applyFilterPass = function(filter, filterArea, width, height)
{
// use program
var gl = this.gl;
var shader = filter.shaders[gl.id];
if(!shader)
{
shader = new PIXI.PixiShader(gl);
shader.fragmentSrc = filter.fragmentSrc;
shader.uniforms = filter.uniforms;
shader.init();
filter.shaders[gl.id] = shader;
}
// set the shader
gl.useProgram(shader.program);
gl.uniform2f(shader.projectionVector, width/2, -height/2);
gl.uniform2f(shader.offsetVector, 0,0);
if(filter.uniforms.dimensions)
{
filter.uniforms.dimensions.value[0] = this.width;//width;
filter.uniforms.dimensions.value[1] = this.height;//height;
filter.uniforms.dimensions.value[2] = this.vertexArray[0];
filter.uniforms.dimensions.value[3] = this.vertexArray[5];//filterArea.height;
}
// console.log(this.uvArray )
shader.syncUniforms();
gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);
gl.vertexAttribPointer(shader.aVertexPosition, 2, gl.FLOAT, false, 0, 0);
gl.bindBuffer(gl.ARRAY_BUFFER, this.uvBuffer);
gl.vertexAttribPointer(shader.aTextureCoord, 2, gl.FLOAT, false, 0, 0);
gl.bindBuffer(gl.ARRAY_BUFFER, this.colorBuffer);
gl.vertexAttribPointer(shader.colorAttribute, 2, gl.FLOAT, false, 0, 0);
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer);
// draw the filter...
gl.drawElements(gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
this.renderSession.drawCount++;
};
/**
* Initialises the shader buffers
* @method initShaderBuffers
*/
PIXI.WebGLFilterManager.prototype.initShaderBuffers = function()
{
var gl = this.gl;
// create some buffers
this.vertexBuffer = gl.createBuffer();
this.uvBuffer = gl.createBuffer();
this.colorBuffer = gl.createBuffer();
this.indexBuffer = gl.createBuffer();
// bind and upload the vertexs..
// keep a reference to the vertexFloatData..
this.vertexArray = new Float32Array([0.0, 0.0,
1.0, 0.0,
0.0, 1.0,
1.0, 1.0]);
gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);
gl.bufferData(
gl.ARRAY_BUFFER,
this.vertexArray,
gl.STATIC_DRAW);
// bind and upload the uv buffer
this.uvArray = new Float32Array([0.0, 0.0,
1.0, 0.0,
0.0, 1.0,
1.0, 1.0]);
gl.bindBuffer(gl.ARRAY_BUFFER, this.uvBuffer);
gl.bufferData(
gl.ARRAY_BUFFER,
this.uvArray,
gl.STATIC_DRAW);
this.colorArray = new Float32Array([1.0, 0xFFFFFF,
1.0, 0xFFFFFF,
1.0, 0xFFFFFF,
1.0, 0xFFFFFF]);
gl.bindBuffer(gl.ARRAY_BUFFER, this.colorBuffer);
gl.bufferData(
gl.ARRAY_BUFFER,
this.colorArray,
gl.STATIC_DRAW);
// bind and upload the index
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer);
gl.bufferData(
gl.ELEMENT_ARRAY_BUFFER,
new Uint16Array([0, 1, 2, 1, 3, 2]),
gl.STATIC_DRAW);
};
/**
* Destroys the filter and removes it from the filter stack
* @method destroy
*/
PIXI.WebGLFilterManager.prototype.destroy = function()
{
var gl = this.gl;
this.filterStack = null;
this.offsetX = 0;
this.offsetY = 0;
// destroy textures
for (var i = 0; i < this.texturePool.length; i++) {
this.texturePool.destroy();
}
this.texturePool = null;
//destroy buffers..
gl.deleteBuffer(this.vertexBuffer);
gl.deleteBuffer(this.uvBuffer);
gl.deleteBuffer(this.colorBuffer);
gl.deleteBuffer(this.indexBuffer);
};
/**
* @author Mat Groves http://matgroves.com/ @Doormat23
*/
/**
* @class FilterTexture
* @constructor
* @param gl {WebGLContext} the current WebGL drawing context
* @param width {Number} the horizontal range of the filter
* @param height {Number} the vertical range of the filter
* @private
*/
PIXI.FilterTexture = function(gl, width, height)
{
/**
* @property gl
* @type WebGLContext
*/
this.gl = gl;
// next time to create a frame buffer and texture
this.frameBuffer = gl.createFramebuffer();
this.texture = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, this.texture);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffer );
gl.bindFramebuffer(gl.FRAMEBUFFER, this.frameBuffer );
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, this.texture, 0);
this.resize(width, height);
};
/**
* Clears the filter texture
* @method clear
*/
PIXI.FilterTexture.prototype.clear = function()
{
var gl = this.gl;
gl.clearColor(0,0,0, 0);
gl.clear(gl.COLOR_BUFFER_BIT);
};
/**
* Resizes the texture to the specified width and height
*
* @method resize
* @param width {Number} the new width of the texture
* @param height {Number} the new height of the texture
*/
PIXI.FilterTexture.prototype.resize = function(width, height)
{
if(this.width === width && this.height === height) return;
this.width = width;
this.height = height;
var gl = this.gl;
gl.bindTexture(gl.TEXTURE_2D, this.texture);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
};
/**
* Destroys the filter texture
* @method destroy
*/
PIXI.FilterTexture.prototype.destroy = function()
{
var gl = this.gl;
gl.deleteFramebuffer( this.frameBuffer );
gl.deleteTexture( this.texture );
this.frameBuffer = null;
this.texture = null;
};
/**
* @author Mat Groves
*
*
*/
/**
* A set of functions used to handle masking
*
* @class CanvasMaskManager
*/
PIXI.CanvasMaskManager = function()
{
};
/**
* This method adds it to the current stack of masks
*
* @method pushMask
* @param maskData the maskData that will be pushed
* @param context {Context2D} the 2d drawing method of the canvas
*/
PIXI.CanvasMaskManager.prototype.pushMask = function(maskData, context)
{
context.save();
var cacheAlpha = maskData.alpha;
var transform = maskData.worldTransform;
context.setTransform(transform.a, transform.c, transform.b, transform.d, transform.tx, transform.ty);
PIXI.CanvasGraphics.renderGraphicsMask(maskData, context);
context.clip();
maskData.worldAlpha = cacheAlpha;
};
/**
* Restores the current drawing context to the state it was before the mask was applied
*
* @method popMask
* @param context {Context2D} the 2d drawing method of the canvas
*/
PIXI.CanvasMaskManager.prototype.popMask = function(context)
{
context.restore();
};
/**
* @author Mat Groves
*
*
*/
/**
* @class CanvasTinter
* @constructor
* @static
*/
PIXI.CanvasTinter = function()
{
/// this.textureCach
};
//PIXI.CanvasTinter.cachTint = true;
/**
* Basically this method just needs a sprite and a color and tints the sprite
* with the given color
*
* @method getTintedTexture
* @param sprite {Sprite} the sprite to tint
* @param color {Number} the color to use to tint the sprite with
*/
PIXI.CanvasTinter.getTintedTexture = function(sprite, color)
{
var texture = sprite.texture;
color = PIXI.CanvasTinter.roundColor(color);
var stringColor = "#" + ("00000" + ( color | 0).toString(16)).substr(-6);
texture.tintCache = texture.tintCache || {};
if(texture.tintCache[stringColor]) return texture.tintCache[stringColor];
// clone texture..
var canvas = PIXI.CanvasTinter.canvas || document.createElement("canvas");
//PIXI.CanvasTinter.tintWithPerPixel(texture, stringColor, canvas);
PIXI.CanvasTinter.tintMethod(texture, color, canvas);
if(PIXI.CanvasTinter.convertTintToImage)
{
// is this better?
var tintImage = new Image();
tintImage.src = canvas.toDataURL();
texture.tintCache[stringColor] = tintImage;
}
else
{
texture.tintCache[stringColor] = canvas;
// if we are not converting the texture to an image then we need to lose the reference to the canvas
PIXI.CanvasTinter.canvas = null;
}
return canvas;
};
/**
* Tint a texture using the "multiply" operation
* @method tintWithMultiply
* @param texture {texture} the texture to tint
* @param color {Number} the color to use to tint the sprite with
* @param canvas {HTMLCanvasElement} the current canvas
*/
PIXI.CanvasTinter.tintWithMultiply = function(texture, color, canvas)
{
var context = canvas.getContext( "2d" );
var frame = texture.frame;
canvas.width = frame.width;
canvas.height = frame.height;
context.fillStyle = "#" + ("00000" + ( color | 0).toString(16)).substr(-6);
context.fillRect(0, 0, frame.width, frame.height);
context.globalCompositeOperation = "multiply";
context.drawImage(texture.baseTexture.source,
frame.x,
frame.y,
frame.width,
frame.height,
0,
0,
frame.width,
frame.height);
context.globalCompositeOperation = "destination-atop";
context.drawImage(texture.baseTexture.source,
frame.x,
frame.y,
frame.width,
frame.height,
0,
0,
frame.width,
frame.height);
};
/**
* Tint a texture using the "overlay" operation
* @method tintWithOverlay
* @param texture {texture} the texture to tint
* @param color {Number} the color to use to tint the sprite with
* @param canvas {HTMLCanvasElement} the current canvas
*/
PIXI.CanvasTinter.tintWithOverlay = function(texture, color, canvas)
{
var context = canvas.getContext( "2d" );
var frame = texture.frame;
canvas.width = frame.width;
canvas.height = frame.height;
context.globalCompositeOperation = "copy";
context.fillStyle = "#" + ("00000" + ( color | 0).toString(16)).substr(-6);
context.fillRect(0, 0, frame.width, frame.height);
context.globalCompositeOperation = "destination-atop";
context.drawImage(texture.baseTexture.source,
frame.x,
frame.y,
frame.width,
frame.height,
0,
0,
frame.width,
frame.height);
//context.globalCompositeOperation = "copy";
};
/**
* Tint a texture pixel per pixel
* @method tintPerPixel
* @param texture {texture} the texture to tint
* @param color {Number} the color to use to tint the sprite with
* @param canvas {HTMLCanvasElement} the current canvas
*/
PIXI.CanvasTinter.tintWithPerPixel = function(texture, color, canvas)
{
var context = canvas.getContext( "2d" );
var frame = texture.frame;
canvas.width = frame.width;
canvas.height = frame.height;
context.globalCompositeOperation = "copy";
context.drawImage(texture.baseTexture.source,
frame.x,
frame.y,
frame.width,
frame.height,
0,
0,
frame.width,
frame.height);
var rgbValues = PIXI.hex2rgb(color);
var r = rgbValues[0], g = rgbValues[1], b = rgbValues[2];
var pixelData = context.getImageData(0, 0, frame.width, frame.height);
var pixels = pixelData.data;
for (var i = 0; i < pixels.length; i += 4)
{
pixels[i+0] *= r;
pixels[i+1] *= g;
pixels[i+2] *= b;
}
context.putImageData(pixelData, 0, 0);
};
/**
* Rounds the specified color according to the PIXI.CanvasTinter.cacheStepsPerColorChannel
* @method roundColor
* @param color {number} the color to round, should be a hex color
*/
PIXI.CanvasTinter.roundColor = function(color)
{
var step = PIXI.CanvasTinter.cacheStepsPerColorChannel;
var rgbValues = PIXI.hex2rgb(color);
rgbValues[0] = Math.min(255, (rgbValues[0] / step) * step);
rgbValues[1] = Math.min(255, (rgbValues[1] / step) * step);
rgbValues[2] = Math.min(255, (rgbValues[2] / step) * step);
return PIXI.rgb2hex(rgbValues);
};
/**
*
* Number of steps which will be used as a cap when rounding colors
*
* @property cacheStepsPerColorChannel
* @type Number
*/
PIXI.CanvasTinter.cacheStepsPerColorChannel = 8;
/**
*
* Number of steps which will be used as a cap when rounding colors
*
* @property convertTintToImage
* @type Boolean
*/
PIXI.CanvasTinter.convertTintToImage = false;
/**
* Whether or not the Canvas BlendModes are supported, consequently the ability to tint using the multiply method
*
* @property canUseMultiply
* @type Boolean
*/
PIXI.CanvasTinter.canUseMultiply = PIXI.canUseNewCanvasBlendModes();
PIXI.CanvasTinter.tintMethod = PIXI.CanvasTinter.canUseMultiply ? PIXI.CanvasTinter.tintWithMultiply : PIXI.CanvasTinter.tintWithPerPixel;
/**
* @author Mat Groves http://matgroves.com/ @Doormat23
*/
/**
* the CanvasRenderer draws the stage and all its content onto a 2d canvas. This renderer should be used for browsers that do not support webGL.
* Dont forget to add the view to your DOM or you will not see anything :)
*
* @class CanvasRenderer
* @constructor
* @param width=800 {Number} the width of the canvas view
* @param height=600 {Number} the height of the canvas view
* @param [view] {HTMLCanvasElement} the canvas to use as a view, optional
* @param [transparent=false] {Boolean} the transparency of the render view, default false
*/
PIXI.CanvasRenderer = function(width, height, view, transparent)
{
PIXI.defaultRenderer = PIXI.defaultRenderer || this;
this.type = PIXI.CANVAS_RENDERER;
/**
* This sets if the CanvasRenderer will clear the canvas or not before the new render pass.
* If the Stage is NOT transparent Pixi will use a canvas sized fillRect operation every frame to set the canvas background color.
* If the Stage is transparent Pixi will use clearRect to clear the canvas every frame.
* Disable this by setting this to false. For example if your game has a canvas filling background image you often don't need this set.
*
* @property clearBeforeRender
* @type Boolean
* @default
*/
this.clearBeforeRender = true;
/**
* If true Pixi will Math.floor() x/y values when rendering, stopping pixel interpolation.
* Handy for crisp pixel art and speed on legacy devices.
*
* @property roundPixels
* @type Boolean
* @default
*/
this.roundPixels = false;
/**
* Whether the render view is transparent
*
* @property transparent
* @type Boolean
*/
this.transparent = !!transparent;
if(!PIXI.blendModesCanvas)
{
PIXI.blendModesCanvas = [];
if(PIXI.canUseNewCanvasBlendModes())
{
PIXI.blendModesCanvas[PIXI.blendModes.NORMAL] = "source-over";
PIXI.blendModesCanvas[PIXI.blendModes.ADD] = "lighter"; //IS THIS OK???
PIXI.blendModesCanvas[PIXI.blendModes.MULTIPLY] = "multiply";
PIXI.blendModesCanvas[PIXI.blendModes.SCREEN] = "screen";
PIXI.blendModesCanvas[PIXI.blendModes.OVERLAY] = "overlay";
PIXI.blendModesCanvas[PIXI.blendModes.DARKEN] = "darken";
PIXI.blendModesCanvas[PIXI.blendModes.LIGHTEN] = "lighten";
PIXI.blendModesCanvas[PIXI.blendModes.COLOR_DODGE] = "color-dodge";
PIXI.blendModesCanvas[PIXI.blendModes.COLOR_BURN] = "color-burn";
PIXI.blendModesCanvas[PIXI.blendModes.HARD_LIGHT] = "hard-light";
PIXI.blendModesCanvas[PIXI.blendModes.SOFT_LIGHT] = "soft-light";
PIXI.blendModesCanvas[PIXI.blendModes.DIFFERENCE] = "difference";
PIXI.blendModesCanvas[PIXI.blendModes.EXCLUSION] = "exclusion";
PIXI.blendModesCanvas[PIXI.blendModes.HUE] = "hue";
PIXI.blendModesCanvas[PIXI.blendModes.SATURATION] = "saturation";
PIXI.blendModesCanvas[PIXI.blendModes.COLOR] = "color";
PIXI.blendModesCanvas[PIXI.blendModes.LUMINOSITY] = "luminosity";
}
else
{
// this means that the browser does not support the cool new blend modes in canvas "cough" ie "cough"
PIXI.blendModesCanvas[PIXI.blendModes.NORMAL] = "source-over";
PIXI.blendModesCanvas[PIXI.blendModes.ADD] = "lighter"; //IS THIS OK???
PIXI.blendModesCanvas[PIXI.blendModes.MULTIPLY] = "source-over";
PIXI.blendModesCanvas[PIXI.blendModes.SCREEN] = "source-over";
PIXI.blendModesCanvas[PIXI.blendModes.OVERLAY] = "source-over";
PIXI.blendModesCanvas[PIXI.blendModes.DARKEN] = "source-over";
PIXI.blendModesCanvas[PIXI.blendModes.LIGHTEN] = "source-over";
PIXI.blendModesCanvas[PIXI.blendModes.COLOR_DODGE] = "source-over";
PIXI.blendModesCanvas[PIXI.blendModes.COLOR_BURN] = "source-over";
PIXI.blendModesCanvas[PIXI.blendModes.HARD_LIGHT] = "source-over";
PIXI.blendModesCanvas[PIXI.blendModes.SOFT_LIGHT] = "source-over";
PIXI.blendModesCanvas[PIXI.blendModes.DIFFERENCE] = "source-over";
PIXI.blendModesCanvas[PIXI.blendModes.EXCLUSION] = "source-over";
PIXI.blendModesCanvas[PIXI.blendModes.HUE] = "source-over";
PIXI.blendModesCanvas[PIXI.blendModes.SATURATION] = "source-over";
PIXI.blendModesCanvas[PIXI.blendModes.COLOR] = "source-over";
PIXI.blendModesCanvas[PIXI.blendModes.LUMINOSITY] = "source-over";
}
}
/**
* The width of the canvas view
*
* @property width
* @type Number
* @default 800
*/
this.width = width || 800;
/**
* The height of the canvas view
*
* @property height
* @type Number
* @default 600
*/
this.height = height || 600;
/**
* The canvas element that everything is drawn to
*
* @property view
* @type HTMLCanvasElement
*/
this.view = view || document.createElement( "canvas" );
/**
* The canvas 2d context that everything is drawn with
* @property context
* @type HTMLCanvasElement 2d Context
*/
this.context = this.view.getContext( "2d", { alpha: this.transparent } );
this.refresh = true;
// hack to enable some hardware acceleration!
//this.view.style["transform"] = "translatez(0)";
this.view.width = this.width;
this.view.height = this.height;
this.count = 0;
/**
* Instance of a PIXI.CanvasMaskManager, handles masking when using the canvas renderer
* @property CanvasMaskManager
* @type CanvasMaskManager
*/
this.maskManager = new PIXI.CanvasMaskManager();
/**
* The render session is just a bunch of parameter used for rendering
* @property renderSession
* @type Object
*/
this.renderSession = {
context: this.context,
maskManager: this.maskManager,
scaleMode: null,
smoothProperty: null
};
if("imageSmoothingEnabled" in this.context)
this.renderSession.smoothProperty = "imageSmoothingEnabled";
else if("webkitImageSmoothingEnabled" in this.context)
this.renderSession.smoothProperty = "webkitImageSmoothingEnabled";
else if("mozImageSmoothingEnabled" in this.context)
this.renderSession.smoothProperty = "mozImageSmoothingEnabled";
else if("oImageSmoothingEnabled" in this.context)
this.renderSession.smoothProperty = "oImageSmoothingEnabled";
};
// constructor
PIXI.CanvasRenderer.prototype.constructor = PIXI.CanvasRenderer;
/**
* Renders the stage to its canvas view
*
* @method render
* @param stage {Stage} the Stage element to be rendered
*/
PIXI.CanvasRenderer.prototype.render = function(stage)
{
// update textures if need be
PIXI.texturesToUpdate.length = 0;
PIXI.texturesToDestroy.length = 0;
stage.updateTransform();
this.context.setTransform(1,0,0,1,0,0);
this.context.globalAlpha = 1;
if (!this.transparent && this.clearBeforeRender)
{
this.context.fillStyle = stage.backgroundColorString;
this.context.fillRect(0, 0, this.width, this.height);
}
else if (this.transparent && this.clearBeforeRender)
{
this.context.clearRect(0, 0, this.width, this.height);
}
this.renderDisplayObject(stage);
// run interaction!
if(stage.interactive)
{
//need to add some events!
if(!stage._interactiveEventsAdded)
{
stage._interactiveEventsAdded = true;
stage.interactionManager.setTarget(this);
}
}
// remove frame updates..
if(PIXI.Texture.frameUpdates.length > 0)
{
PIXI.Texture.frameUpdates.length = 0;
}
};
/**
* Resizes the canvas view to the specified width and height
*
* @method resize
* @param width {Number} the new width of the canvas view
* @param height {Number} the new height of the canvas view
*/
PIXI.CanvasRenderer.prototype.resize = function(width, height)
{
this.width = width;
this.height = height;
this.view.width = width;
this.view.height = height;
};
/**
* Renders a display object
*
* @method renderDisplayObject
* @param displayObject {DisplayObject} The displayObject to render
* @param context {Context2D} the context 2d method of the canvas
* @private
*/
PIXI.CanvasRenderer.prototype.renderDisplayObject = function(displayObject, context)
{
// no longer recursive!
//var transform;
//var context = this.context;
this.renderSession.context = context || this.context;
displayObject._renderCanvas(this.renderSession);
};
/**
* Renders a flat strip
*
* @method renderStripFlat
* @param strip {Strip} The Strip to render
* @private
*/
PIXI.CanvasRenderer.prototype.renderStripFlat = function(strip)
{
var context = this.context;
var verticies = strip.verticies;
var length = verticies.length/2;
this.count++;
context.beginPath();
for (var i=1; i < length-2; i++)
{
// draw some triangles!
var index = i*2;
var x0 = verticies[index], x1 = verticies[index+2], x2 = verticies[index+4];
var y0 = verticies[index+1], y1 = verticies[index+3], y2 = verticies[index+5];
context.moveTo(x0, y0);
context.lineTo(x1, y1);
context.lineTo(x2, y2);
}
context.fillStyle = "#FF0000";
context.fill();
context.closePath();
};
/**
* Renders a strip
*
* @method renderStrip
* @param strip {Strip} The Strip to render
* @private
*/
PIXI.CanvasRenderer.prototype.renderStrip = function(strip)
{
var context = this.context;
// draw triangles!!
var verticies = strip.verticies;
var uvs = strip.uvs;
var length = verticies.length/2;
this.count++;
for (var i = 1; i < length-2; i++)
{
// draw some triangles!
var index = i*2;
var x0 = verticies[index], x1 = verticies[index+2], x2 = verticies[index+4];
var y0 = verticies[index+1], y1 = verticies[index+3], y2 = verticies[index+5];
var u0 = uvs[index] * strip.texture.width, u1 = uvs[index+2] * strip.texture.width, u2 = uvs[index+4]* strip.texture.width;
var v0 = uvs[index+1]* strip.texture.height, v1 = uvs[index+3] * strip.texture.height, v2 = uvs[index+5]* strip.texture.height;
context.save();
context.beginPath();
context.moveTo(x0, y0);
context.lineTo(x1, y1);
context.lineTo(x2, y2);
context.closePath();
context.clip();
// Compute matrix transform
var delta = u0*v1 + v0*u2 + u1*v2 - v1*u2 - v0*u1 - u0*v2;
var deltaA = x0*v1 + v0*x2 + x1*v2 - v1*x2 - v0*x1 - x0*v2;
var deltaB = u0*x1 + x0*u2 + u1*x2 - x1*u2 - x0*u1 - u0*x2;
var deltaC = u0*v1*x2 + v0*x1*u2 + x0*u1*v2 - x0*v1*u2 - v0*u1*x2 - u0*x1*v2;
var deltaD = y0*v1 + v0*y2 + y1*v2 - v1*y2 - v0*y1 - y0*v2;
var deltaE = u0*y1 + y0*u2 + u1*y2 - y1*u2 - y0*u1 - u0*y2;
var deltaF = u0*v1*y2 + v0*y1*u2 + y0*u1*v2 - y0*v1*u2 - v0*u1*y2 - u0*y1*v2;
context.transform(deltaA / delta, deltaD / delta,
deltaB / delta, deltaE / delta,
deltaC / delta, deltaF / delta);
context.drawImage(strip.texture.baseTexture.source, 0, 0);
context.restore();
}
};
/**
* Creates a Canvas element of the given size
*
* @method CanvasBuffer
* @param width {Number} the width for the newly created canvas
* @param height {Number} the height for the newly created canvas
* @static
* @private
*/
PIXI.CanvasBuffer = function(width, height)
{
this.width = width;
this.height = height;
this.canvas = document.createElement( "canvas" );
this.context = this.canvas.getContext( "2d" );
this.canvas.width = width;
this.canvas.height = height;
};
/**
* Clears the canvas that was created by the CanvasBuffer class
*
* @method clear
* @private
*/
PIXI.CanvasBuffer.prototype.clear = function()
{
this.context.clearRect(0,0, this.width, this.height);
};
/**
* Resizes the canvas that was created by the CanvasBuffer class to the specified width and height
*
* @method resize
* @param width {Number} the new width of the canvas
* @param height {Number} the new height of the canvas
* @private
*/
PIXI.CanvasBuffer.prototype.resize = function(width, height)
{
this.width = this.canvas.width = width;
this.height = this.canvas.height = height;
};
/**
* @author Mat Groves http://matgroves.com/ @Doormat23
*/
/**
* A set of functions used by the canvas renderer to draw the primitive graphics data
*
* @class CanvasGraphics
*/
PIXI.CanvasGraphics = function()
{
};
/*
* Renders the graphics object
*
* @static
* @private
* @method renderGraphics
* @param graphics {Graphics} the actual graphics object to render
* @param context {Context2D} the 2d drawing method of the canvas
*/
PIXI.CanvasGraphics.renderGraphics = function(graphics, context)
{
var worldAlpha = graphics.worldAlpha;
var color = '';
for (var i = 0; i < graphics.graphicsData.length; i++)
{
var data = graphics.graphicsData[i];
var points = data.points;
context.strokeStyle = color = '#' + ('00000' + ( data.lineColor | 0).toString(16)).substr(-6);
context.lineWidth = data.lineWidth;
if(data.type === PIXI.Graphics.POLY)
{
context.beginPath();
context.moveTo(points[0], points[1]);
for (var j=1; j < points.length/2; j++)
{
context.lineTo(points[j * 2], points[j * 2 + 1]);
}
// if the first and last point are the same close the path - much neater :)
if(points[0] === points[points.length-2] && points[1] === points[points.length-1])
{
context.closePath();
}
if(data.fill)
{
context.globalAlpha = data.fillAlpha * worldAlpha;
context.fillStyle = color = '#' + ('00000' + ( data.fillColor | 0).toString(16)).substr(-6);
context.fill();
}
if(data.lineWidth)
{
context.globalAlpha = data.lineAlpha * worldAlpha;
context.stroke();
}
}
else if(data.type === PIXI.Graphics.RECT)
{
if(data.fillColor || data.fillColor === 0)
{
context.globalAlpha = data.fillAlpha * worldAlpha;
context.fillStyle = color = '#' + ('00000' + ( data.fillColor | 0).toString(16)).substr(-6);
context.fillRect(points[0], points[1], points[2], points[3]);
}
if(data.lineWidth)
{
context.globalAlpha = data.lineAlpha * worldAlpha;
context.strokeRect(points[0], points[1], points[2], points[3]);
}
}
else if(data.type === PIXI.Graphics.CIRC)
{
// TODO - need to be Undefined!
context.beginPath();
context.arc(points[0], points[1], points[2],0,2*Math.PI);
context.closePath();
if(data.fill)
{
context.globalAlpha = data.fillAlpha * worldAlpha;
context.fillStyle = color = '#' + ('00000' + ( data.fillColor | 0).toString(16)).substr(-6);
context.fill();
}
if(data.lineWidth)
{
context.globalAlpha = data.lineAlpha * worldAlpha;
context.stroke();
}
}
else if(data.type === PIXI.Graphics.ELIP)
{
// ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas
var ellipseData = data.points;
var w = ellipseData[2] * 2;
var h = ellipseData[3] * 2;
var x = ellipseData[0] - w/2;
var y = ellipseData[1] - h/2;
context.beginPath();
var kappa = 0.5522848,
ox = (w / 2) * kappa, // control point offset horizontal
oy = (h / 2) * kappa, // control point offset vertical
xe = x + w, // x-end
ye = y + h, // y-end
xm = x + w / 2, // x-middle
ym = y + h / 2; // y-middle
context.moveTo(x, ym);
context.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);
context.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);
context.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);
context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);
context.closePath();
if(data.fill)
{
context.globalAlpha = data.fillAlpha * worldAlpha;
context.fillStyle = color = '#' + ('00000' + ( data.fillColor | 0).toString(16)).substr(-6);
context.fill();
}
if(data.lineWidth)
{
context.globalAlpha = data.lineAlpha * worldAlpha;
context.stroke();
}
}
}
};
/*
* Renders a graphics mask
*
* @static
* @private
* @method renderGraphicsMask
* @param graphics {Graphics} the graphics which will be used as a mask
* @param context {Context2D} the context 2d method of the canvas
*/
PIXI.CanvasGraphics.renderGraphicsMask = function(graphics, context)
{
var len = graphics.graphicsData.length;
if(len === 0) return;
if(len > 1)
{
len = 1;
window.console.log('Pixi.js warning: masks in canvas can only mask using the first path in the graphics object');
}
for (var i = 0; i < 1; i++)
{
var data = graphics.graphicsData[i];
var points = data.points;
if(data.type === PIXI.Graphics.POLY)
{
context.beginPath();
context.moveTo(points[0], points[1]);
for (var j=1; j < points.length/2; j++)
{
context.lineTo(points[j * 2], points[j * 2 + 1]);
}
// if the first and last point are the same close the path - much neater :)
if(points[0] === points[points.length-2] && points[1] === points[points.length-1])
{
context.closePath();
}
}
else if(data.type === PIXI.Graphics.RECT)
{
context.beginPath();
context.rect(points[0], points[1], points[2], points[3]);
context.closePath();
}
else if(data.type === PIXI.Graphics.CIRC)
{
// TODO - need to be Undefined!
context.beginPath();
context.arc(points[0], points[1], points[2],0,2*Math.PI);
context.closePath();
}
else if(data.type === PIXI.Graphics.ELIP)
{
// ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas
var ellipseData = data.points;
var w = ellipseData[2] * 2;
var h = ellipseData[3] * 2;
var x = ellipseData[0] - w/2;
var y = ellipseData[1] - h/2;
context.beginPath();
var kappa = 0.5522848,
ox = (w / 2) * kappa, // control point offset horizontal
oy = (h / 2) * kappa, // control point offset vertical
xe = x + w, // x-end
ye = y + h, // y-end
xm = x + w / 2, // x-middle
ym = y + h / 2; // y-middle
context.moveTo(x, ym);
context.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);
context.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);
context.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);
context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);
context.closePath();
}
}
};
/**
* @author Mat Groves http://matgroves.com/ @Doormat23
*/
/**
* The Graphics class contains a set of methods that you can use to create primitive shapes and lines.
* It is important to know that with the webGL renderer only simple polygons can be filled at this stage
* Complex polygons will not be filled. Heres an example of a complex polygon: http://www.goodboydigital.com/wp-content/uploads/2013/06/complexPolygon.png
*
* @class Graphics
* @extends DisplayObjectContainer
* @constructor
*/
PIXI.Graphics = function()
{
PIXI.DisplayObjectContainer.call( this );
this.renderable = true;
/**
* The alpha of the fill of this graphics object
*
* @property fillAlpha
* @type Number
*/
this.fillAlpha = 1;
/**
* The width of any lines drawn
*
* @property lineWidth
* @type Number
*/
this.lineWidth = 0;
/**
* The color of any lines drawn
*
* @property lineColor
* @type String
*/
this.lineColor = "black";
/**
* Graphics data
*
* @property graphicsData
* @type Array
* @private
*/
this.graphicsData = [];
/**
* The tint applied to the graphic shape. This is a hex value
*
* @property tint
* @type Number
* @default 0xFFFFFF
*/
this.tint = 0xFFFFFF;// * Math.random();
/**
* The blend mode to be applied to the graphic shape
*
* @property blendMode
* @type Number
* @default PIXI.blendModes.NORMAL;
*/
this.blendMode = PIXI.blendModes.NORMAL;
/**
* Current path
*
* @property currentPath
* @type Object
* @private
*/
this.currentPath = {points:[]};
/**
* Array containing some WebGL-related properties used by the WebGL renderer
*
* @property _webGL
* @type Array
* @private
*/
this._webGL = [];
/**
* Whether this shape is being used as a mask
*
* @property isMask
* @type isMask
*/
this.isMask = false;
/**
* The bounds of the graphic shape as rectangle object
*
* @property bounds
* @type Rectangle
*/
this.bounds = null;
/**
* the bounds' padding used for bounds calculation
*
* @property bounds
* @type Number
*/
this.boundsPadding = 10;
};
// constructor
PIXI.Graphics.prototype = Object.create( PIXI.DisplayObjectContainer.prototype );
PIXI.Graphics.prototype.constructor = PIXI.Graphics;
/**
* If cacheAsBitmap is true the graphics object will then be rendered as if it was a sprite.
* This is useful if your graphics element does not change often as it will speed up the rendering of the object
* It is also usful as the graphics object will always be antialiased because it will be rendered using canvas
* Not recommended if you are constanly redrawing the graphics element.
*
* @property cacheAsBitmap
* @default false
* @type Boolean
* @private
*/
Object.defineProperty(PIXI.Graphics.prototype, "cacheAsBitmap", {
get: function() {
return this._cacheAsBitmap;
},
set: function(value) {
this._cacheAsBitmap = value;
if(this._cacheAsBitmap)
{
this._generateCachedSprite();
}
else
{
this.destroyCachedSprite();
this.dirty = true;
}
}
});
/**
* Specifies the line style used for subsequent calls to Graphics methods such as the lineTo() method or the drawCircle() method.
*
* @method lineStyle
* @param lineWidth {Number} width of the line to draw, will update the object's stored style
* @param color {Number} color of the line to draw, will update the object's stored style
* @param alpha {Number} alpha of the line to draw, will update the object's stored style
*/
PIXI.Graphics.prototype.lineStyle = function(lineWidth, color, alpha)
{
if (!this.currentPath.points.length) this.graphicsData.pop();
this.lineWidth = lineWidth || 0;
this.lineColor = color || 0;
this.lineAlpha = (arguments.length < 3) ? 1 : alpha;
this.currentPath = {lineWidth:this.lineWidth, lineColor:this.lineColor, lineAlpha:this.lineAlpha,
fillColor:this.fillColor, fillAlpha:this.fillAlpha, fill:this.filling, points:[], type:PIXI.Graphics.POLY};
this.graphicsData.push(this.currentPath);
return this;
};
/**
* Moves the current drawing position to (x, y).
*
* @method moveTo
* @param x {Number} the X coordinate to move to
* @param y {Number} the Y coordinate to move to
*/
PIXI.Graphics.prototype.moveTo = function(x, y)
{
if (!this.currentPath.points.length) this.graphicsData.pop();
this.currentPath = this.currentPath = {lineWidth:this.lineWidth, lineColor:this.lineColor, lineAlpha:this.lineAlpha,
fillColor:this.fillColor, fillAlpha:this.fillAlpha, fill:this.filling, points:[], type:PIXI.Graphics.POLY};
this.currentPath.points.push(x, y);
this.graphicsData.push(this.currentPath);
return this;
};
/**
* Draws a line using the current line style from the current drawing position to (x, y);
* the current drawing position is then set to (x, y).
*
* @method lineTo
* @param x {Number} the X coordinate to draw to
* @param y {Number} the Y coordinate to draw to
*/
PIXI.Graphics.prototype.lineTo = function(x, y)
{
this.currentPath.points.push(x, y);
this.dirty = true;
return this;
};
/**
* Specifies a simple one-color fill that subsequent calls to other Graphics methods
* (such as lineTo() or drawCircle()) use when drawing.
*
* @method beginFill
* @param color {Number} the color of the fill
* @param alpha {Number} the alpha of the fill
*/
PIXI.Graphics.prototype.beginFill = function(color, alpha)
{
this.filling = true;
this.fillColor = color || 0;
this.fillAlpha = (arguments.length < 2) ? 1 : alpha;
return this;
};
/**
* Applies a fill to the lines and shapes that were added since the last call to the beginFill() method.
*
* @method endFill
*/
PIXI.Graphics.prototype.endFill = function()
{
this.filling = false;
this.fillColor = null;
this.fillAlpha = 1;
return this;
};
/**
* @method drawRect
*
* @param x {Number} The X coord of the top-left of the rectangle
* @param y {Number} The Y coord of the top-left of the rectangle
* @param width {Number} The width of the rectangle
* @param height {Number} The height of the rectangle
*/
PIXI.Graphics.prototype.drawRect = function( x, y, width, height )
{
if (!this.currentPath.points.length) this.graphicsData.pop();
this.currentPath = {lineWidth:this.lineWidth, lineColor:this.lineColor, lineAlpha:this.lineAlpha,
fillColor:this.fillColor, fillAlpha:this.fillAlpha, fill:this.filling,
points:[x, y, width, height], type:PIXI.Graphics.RECT};
this.graphicsData.push(this.currentPath);
this.dirty = true;
return this;
};
/**
* Draws a circle.
*
* @method drawCircle
* @param x {Number} The X coordinate of the center of the circle
* @param y {Number} The Y coordinate of the center of the circle
* @param radius {Number} The radius of the circle
*/
PIXI.Graphics.prototype.drawCircle = function( x, y, radius)
{
if (!this.currentPath.points.length) this.graphicsData.pop();
this.currentPath = {lineWidth:this.lineWidth, lineColor:this.lineColor, lineAlpha:this.lineAlpha,
fillColor:this.fillColor, fillAlpha:this.fillAlpha, fill:this.filling,
points:[x, y, radius, radius], type:PIXI.Graphics.CIRC};
this.graphicsData.push(this.currentPath);
this.dirty = true;
return this;
};
/**
* Draws an ellipse.
*
* @method drawEllipse
* @param x {Number} The X coordinate of the upper-left corner of the framing rectangle of this ellipse
* @param y {Number} The Y coordinate of the upper-left corner of the framing rectangle of this ellipse
* @param width {Number} The width of the ellipse
* @param height {Number} The height of the ellipse
*/
PIXI.Graphics.prototype.drawEllipse = function( x, y, width, height)
{
if (!this.currentPath.points.length) this.graphicsData.pop();
this.currentPath = {lineWidth:this.lineWidth, lineColor:this.lineColor, lineAlpha:this.lineAlpha,
fillColor:this.fillColor, fillAlpha:this.fillAlpha, fill:this.filling,
points:[x, y, width, height], type:PIXI.Graphics.ELIP};
this.graphicsData.push(this.currentPath);
this.dirty = true;
return this;
};
/**
* Clears the graphics that were drawn to this Graphics object, and resets fill and line style settings.
*
* @method clear
*/
PIXI.Graphics.prototype.clear = function()
{
this.lineWidth = 0;
this.filling = false;
this.dirty = true;
this.clearDirty = true;
this.graphicsData = [];
this.bounds = null; //new PIXI.Rectangle();
return this;
};
/**
* Useful function that returns a texture of the graphics object that can then be used to create sprites
* This can be quite useful if your geometry is complicated and needs to be reused multiple times.
*
* @method generateTexture
* @return {Texture} a texture of the graphics object
*/
PIXI.Graphics.prototype.generateTexture = function()
{
var bounds = this.getBounds();
var canvasBuffer = new PIXI.CanvasBuffer(bounds.width, bounds.height);
var texture = PIXI.Texture.fromCanvas(canvasBuffer.canvas);
canvasBuffer.context.translate(-bounds.x,-bounds.y);
PIXI.CanvasGraphics.renderGraphics(this, canvasBuffer.context);
return texture;
};
/**
* Renders the object using the WebGL renderer
*
* @method _renderWebGL
* @param renderSession {RenderSession}
* @private
*/
PIXI.Graphics.prototype._renderWebGL = function(renderSession)
{
// if the sprite is not visible or the alpha is 0 then no need to render this element
if(this.visible === false || this.alpha === 0 || this.isMask === true)return;
if(this._cacheAsBitmap)
{
if(this.dirty)
{
this._generateCachedSprite();
// we will also need to update the texture on the gpu too!
PIXI.updateWebGLTexture(this._cachedSprite.texture.baseTexture, renderSession.gl);
this.dirty = false;
}
PIXI.Sprite.prototype._renderWebGL.call(this._cachedSprite, renderSession);
return;
}
else
{
renderSession.spriteBatch.stop();
if(this._mask)renderSession.maskManager.pushMask(this.mask, renderSession);
if(this._filters)renderSession.filterManager.pushFilter(this._filterBlock);
// check blend mode
if(this.blendMode !== renderSession.spriteBatch.currentBlendMode)
{
renderSession.spriteBatch.currentBlendMode = this.blendMode;
var blendModeWebGL = PIXI.blendModesWebGL[renderSession.spriteBatch.currentBlendMode];
renderSession.spriteBatch.gl.blendFunc(blendModeWebGL[0], blendModeWebGL[1]);
}
PIXI.WebGLGraphics.renderGraphics(this, renderSession);
// only render if it has children!
if(this.children.length)
{
renderSession.spriteBatch.start();
// simple render children!
for(var i=0, j=this.children.length; i<j; i++)
{
this.children[i]._renderWebGL(renderSession);
}
renderSession.spriteBatch.stop();
}
if(this._filters)renderSession.filterManager.popFilter();
if(this._mask)renderSession.maskManager.popMask(renderSession);
renderSession.drawCount++;
renderSession.spriteBatch.start();
}
};
/**
* Renders the object using the Canvas renderer
*
* @method _renderCanvas
* @param renderSession {RenderSession}
* @private
*/
PIXI.Graphics.prototype._renderCanvas = function(renderSession)
{
// if the sprite is not visible or the alpha is 0 then no need to render this element
if(this.visible === false || this.alpha === 0 || this.isMask === true)return;
var context = renderSession.context;
var transform = this.worldTransform;
if(this.blendMode !== renderSession.currentBlendMode)
{
renderSession.currentBlendMode = this.blendMode;
context.globalCompositeOperation = PIXI.blendModesCanvas[renderSession.currentBlendMode];
}
context.setTransform(transform.a, transform.c, transform.b, transform.d, transform.tx, transform.ty);
PIXI.CanvasGraphics.renderGraphics(this, context);
// simple render children!
for(var i=0, j=this.children.length; i<j; i++)
{
this.children[i]._renderCanvas(renderSession);
}
};
/**
* Retrieves the bounds of the graphic shape as a rectangle object
*
* @method getBounds
* @return {Rectangle} the rectangular bounding area
*/
PIXI.Graphics.prototype.getBounds = function( matrix )
{
if(!this.bounds)this.updateBounds();
var w0 = this.bounds.x;
var w1 = this.bounds.width + this.bounds.x;
var h0 = this.bounds.y;
var h1 = this.bounds.height + this.bounds.y;
var worldTransform = matrix || this.worldTransform;
var a = worldTransform.a;
var b = worldTransform.c;
var c = worldTransform.b;
var d = worldTransform.d;
var tx = worldTransform.tx;
var ty = worldTransform.ty;
var x1 = a * w1 + c * h1 + tx;
var y1 = d * h1 + b * w1 + ty;
var x2 = a * w0 + c * h1 + tx;
var y2 = d * h1 + b * w0 + ty;
var x3 = a * w0 + c * h0 + tx;
var y3 = d * h0 + b * w0 + ty;
var x4 = a * w1 + c * h0 + tx;
var y4 = d * h0 + b * w1 + ty;
var maxX = -Infinity;
var maxY = -Infinity;
var minX = Infinity;
var minY = Infinity;
minX = x1 < minX ? x1 : minX;
minX = x2 < minX ? x2 : minX;
minX = x3 < minX ? x3 : minX;
minX = x4 < minX ? x4 : minX;
minY = y1 < minY ? y1 : minY;
minY = y2 < minY ? y2 : minY;
minY = y3 < minY ? y3 : minY;
minY = y4 < minY ? y4 : minY;
maxX = x1 > maxX ? x1 : maxX;
maxX = x2 > maxX ? x2 : maxX;
maxX = x3 > maxX ? x3 : maxX;
maxX = x4 > maxX ? x4 : maxX;
maxY = y1 > maxY ? y1 : maxY;
maxY = y2 > maxY ? y2 : maxY;
maxY = y3 > maxY ? y3 : maxY;
maxY = y4 > maxY ? y4 : maxY;
var bounds = this._bounds;
bounds.x = minX;
bounds.width = maxX - minX;
bounds.y = minY;
bounds.height = maxY - minY;
return bounds;
};
/**
* Update the bounds of the object
*
* @method updateBounds
*/
PIXI.Graphics.prototype.updateBounds = function()
{
var minX = Infinity;
var maxX = -Infinity;
var minY = Infinity;
var maxY = -Infinity;
var points, x, y, w, h;
for (var i = 0; i < this.graphicsData.length; i++) {
var data = this.graphicsData[i];
var type = data.type;
var lineWidth = data.lineWidth;
points = data.points;
if(type === PIXI.Graphics.RECT)
{
x = points[0] - lineWidth/2;
y = points[1] - lineWidth/2;
w = points[2] + lineWidth;
h = points[3] + lineWidth;
minX = x < minX ? x : minX;
maxX = x + w > maxX ? x + w : maxX;
minY = y < minY ? x : minY;
maxY = y + h > maxY ? y + h : maxY;
}
else if(type === PIXI.Graphics.CIRC || type === PIXI.Graphics.ELIP)
{
x = points[0];
y = points[1];
w = points[2] + lineWidth/2;
h = points[3] + lineWidth/2;
minX = x - w < minX ? x - w : minX;
maxX = x + w > maxX ? x + w : maxX;
minY = y - h < minY ? y - h : minY;
maxY = y + h > maxY ? y + h : maxY;
}
else
{
// POLY
for (var j = 0; j < points.length; j+=2)
{
x = points[j];
y = points[j+1];
minX = x-lineWidth < minX ? x-lineWidth : minX;
maxX = x+lineWidth > maxX ? x+lineWidth : maxX;
minY = y-lineWidth < minY ? y-lineWidth : minY;
maxY = y+lineWidth > maxY ? y+lineWidth : maxY;
}
}
}
var padding = this.boundsPadding;
this.bounds = new PIXI.Rectangle(minX - padding, minY - padding, (maxX - minX) + padding * 2, (maxY - minY) + padding * 2);
};
/**
* Generates the cached sprite when the sprite has cacheAsBitmap = true
*
* @method _generateCachedSprite
* @private
*/
PIXI.Graphics.prototype._generateCachedSprite = function()
{
var bounds = this.getLocalBounds();
if(!this._cachedSprite)
{
var canvasBuffer = new PIXI.CanvasBuffer(bounds.width, bounds.height);
var texture = PIXI.Texture.fromCanvas(canvasBuffer.canvas);
this._cachedSprite = new PIXI.Sprite(texture);
this._cachedSprite.buffer = canvasBuffer;
this._cachedSprite.worldTransform = this.worldTransform;
}
else
{
this._cachedSprite.buffer.resize(bounds.width, bounds.height);
}
// leverage the anchor to account for the offset of the element
this._cachedSprite.anchor.x = -( bounds.x / bounds.width );
this._cachedSprite.anchor.y = -( bounds.y / bounds.height );
// this._cachedSprite.buffer.context.save();
this._cachedSprite.buffer.context.translate(-bounds.x,-bounds.y);
PIXI.CanvasGraphics.renderGraphics(this, this._cachedSprite.buffer.context);
// this._cachedSprite.buffer.context.restore();
};
PIXI.Graphics.prototype.destroyCachedSprite = function()
{
this._cachedSprite.texture.destroy(true);
// let the gc collect the unused sprite
// TODO could be object pooled!
this._cachedSprite = null;
};
// SOME TYPES:
PIXI.Graphics.POLY = 0;
PIXI.Graphics.RECT = 1;
PIXI.Graphics.CIRC = 2;
PIXI.Graphics.ELIP = 3;
/**
* @author Mat Groves http://matgroves.com/
*/
/**
* A tiling sprite is a fast way of rendering a tiling image
*
* @class TilingSprite
* @extends Sprite
* @constructor
* @param texture {Texture} the texture of the tiling sprite
* @param width {Number} the width of the tiling sprite
* @param height {Number} the height of the tiling sprite
*/
PIXI.TilingSprite = function(texture, width, height)
{
PIXI.Sprite.call( this, texture);
/**
* The with of the tiling sprite
*
* @property width
* @type Number
*/
this.width = width || 100;
/**
* The height of the tiling sprite
*
* @property height
* @type Number
*/
this.height = height || 100;
/**
* The scaling of the image that is being tiled
*
* @property tileScale
* @type Point
*/
this.tileScale = new PIXI.Point(1,1);
/**
* A point that represents the scale of the texture object
*
* @property tileScaleOffset
* @type Point
*/
this.tileScaleOffset = new PIXI.Point(1,1);
/**
* The offset position of the image that is being tiled
*
* @property tilePosition
* @type Point
*/
this.tilePosition = new PIXI.Point(0,0);
/**
* Whether this sprite is renderable or not
*
* @property renderable
* @type Boolean
* @default true
*/
this.renderable = true;
/**
* The tint applied to the sprite. This is a hex value
*
* @property tint
* @type Number
* @default 0xFFFFFF
*/
this.tint = 0xFFFFFF;
/**
* The blend mode to be applied to the sprite
*
* @property blendMode
* @type Number
* @default PIXI.blendModes.NORMAL;
*/
this.blendMode = PIXI.blendModes.NORMAL;
};
// constructor
PIXI.TilingSprite.prototype = Object.create(PIXI.Sprite.prototype);
PIXI.TilingSprite.prototype.constructor = PIXI.TilingSprite;
/**
* The width of the sprite, setting this will actually modify the scale to achieve the value set
*
* @property width
* @type Number
*/
Object.defineProperty(PIXI.TilingSprite.prototype, 'width', {
get: function() {
return this._width;
},
set: function(value) {
this._width = value;
}
});
/**
* The height of the TilingSprite, setting this will actually modify the scale to achieve the value set
*
* @property height
* @type Number
*/
Object.defineProperty(PIXI.TilingSprite.prototype, 'height', {
get: function() {
return this._height;
},
set: function(value) {
this._height = value;
}
});
/**
* When the texture is updated, this event will be fired to update the scale and frame
*
* @method onTextureUpdate
* @param event
* @private
*/
PIXI.TilingSprite.prototype.onTextureUpdate = function()
{
this.updateFrame = true;
};
PIXI.TilingSprite.prototype.setTexture = function(texture)
{
if(this.texture === texture)return;
this.texture = texture;
this.refreshTexture = true;
/*
if(this.tilingTexture)
{
this.generateTilingTexture(true);
}
*/
/*
// stop current texture;
if(this.texture.baseTexture !== texture.baseTexture)
{
this.textureChange = true;
this.texture = texture;
}
else
{
this.texture = texture;
}
this.updateFrame = true;*/
this.cachedTint = 0xFFFFFF;
};
/**
* Renders the object using the WebGL renderer
*
* @method _renderWebGL
* @param renderSession {RenderSession}
* @private
*/
PIXI.TilingSprite.prototype._renderWebGL = function(renderSession)
{
if(this.visible === false || this.alpha === 0)return;
var i,j;
if(this.mask)
{
renderSession.spriteBatch.stop();
renderSession.maskManager.pushMask(this.mask, renderSession);
renderSession.spriteBatch.start();
}
if(this.filters)
{
renderSession.spriteBatch.flush();
renderSession.filterManager.pushFilter(this._filterBlock);
}
if(!this.tilingTexture || this.refreshTexture)
{
this.generateTilingTexture(true);
if(this.tilingTexture && this.tilingTexture.needsUpdate)
{
//TODO - tweaking
PIXI.updateWebGLTexture(this.tilingTexture.baseTexture, renderSession.gl);
this.tilingTexture.needsUpdate = false;
// this.tilingTexture._uvs = null;
}
}
else renderSession.spriteBatch.renderTilingSprite(this);
// simple render children!
for(i=0,j=this.children.length; i<j; i++)
{
this.children[i]._renderWebGL(renderSession);
}
renderSession.spriteBatch.stop();
if(this.filters)renderSession.filterManager.popFilter();
if(this.mask)renderSession.maskManager.popMask(renderSession);
renderSession.spriteBatch.start();
};
/**
* Renders the object using the Canvas renderer
*
* @method _renderCanvas
* @param renderSession {RenderSession}
* @private
*/
PIXI.TilingSprite.prototype._renderCanvas = function(renderSession)
{
if(this.visible === false || this.alpha === 0)return;
var context = renderSession.context;
if(this._mask)
{
renderSession.maskManager.pushMask(this._mask, context);
}
context.globalAlpha = this.worldAlpha;
var transform = this.worldTransform;
// allow for trimming
context.setTransform(transform.a, transform.c, transform.b, transform.d, transform.tx, transform.ty);
if(!this.__tilePattern || this.refreshTexture)
{
this.generateTilingTexture(false);
if(this.tilingTexture)
{
this.__tilePattern = context.createPattern(this.tilingTexture.baseTexture.source, 'repeat');
}
}
// check blend mode
if(this.blendMode !== renderSession.currentBlendMode)
{
renderSession.currentBlendMode = this.blendMode;
context.globalCompositeOperation = PIXI.blendModesCanvas[renderSession.currentBlendMode];
}
context.beginPath();
var tilePosition = this.tilePosition;
var tileScale = this.tileScale;
tilePosition.x %= this.tilingTexture.baseTexture.width;
tilePosition.y %= this.tilingTexture.baseTexture.height;
// offset
context.scale(tileScale.x,tileScale.y);
context.translate(tilePosition.x, tilePosition.y);
context.fillStyle = this.__tilePattern;
context.fillRect(-tilePosition.x,-tilePosition.y,this.width / tileScale.x, this.height / tileScale.y);
context.scale(1/tileScale.x, 1/tileScale.y);
context.translate(-tilePosition.x, -tilePosition.y);
context.closePath();
if(this._mask)
{
renderSession.maskManager.popMask(renderSession.context);
}
};
/**
* Returns the framing rectangle of the sprite as a PIXI.Rectangle object
*
* @method getBounds
* @return {Rectangle} the framing rectangle
*/
PIXI.TilingSprite.prototype.getBounds = function()
{
var width = this._width;
var height = this._height;
var w0 = width * (1-this.anchor.x);
var w1 = width * -this.anchor.x;
var h0 = height * (1-this.anchor.y);
var h1 = height * -this.anchor.y;
var worldTransform = this.worldTransform;
var a = worldTransform.a;
var b = worldTransform.c;
var c = worldTransform.b;
var d = worldTransform.d;
var tx = worldTransform.tx;
var ty = worldTransform.ty;
var x1 = a * w1 + c * h1 + tx;
var y1 = d * h1 + b * w1 + ty;
var x2 = a * w0 + c * h1 + tx;
var y2 = d * h1 + b * w0 + ty;
var x3 = a * w0 + c * h0 + tx;
var y3 = d * h0 + b * w0 + ty;
var x4 = a * w1 + c * h0 + tx;
var y4 = d * h0 + b * w1 + ty;
var maxX = -Infinity;
var maxY = -Infinity;
var minX = Infinity;
var minY = Infinity;
minX = x1 < minX ? x1 : minX;
minX = x2 < minX ? x2 : minX;
minX = x3 < minX ? x3 : minX;
minX = x4 < minX ? x4 : minX;
minY = y1 < minY ? y1 : minY;
minY = y2 < minY ? y2 : minY;
minY = y3 < minY ? y3 : minY;
minY = y4 < minY ? y4 : minY;
maxX = x1 > maxX ? x1 : maxX;
maxX = x2 > maxX ? x2 : maxX;
maxX = x3 > maxX ? x3 : maxX;
maxX = x4 > maxX ? x4 : maxX;
maxY = y1 > maxY ? y1 : maxY;
maxY = y2 > maxY ? y2 : maxY;
maxY = y3 > maxY ? y3 : maxY;
maxY = y4 > maxY ? y4 : maxY;
var bounds = this._bounds;
bounds.x = minX;
bounds.width = maxX - minX;
bounds.y = minY;
bounds.height = maxY - minY;
// store a reference so that if this function gets called again in the render cycle we do not have to recalculate
this._currentBounds = bounds;
return bounds;
};
/**
*
* @method generateTilingTexture
*
* @param forcePowerOfTwo {Boolean} Whether we want to force the texture to be a power of two
*/
PIXI.TilingSprite.prototype.generateTilingTexture = function(forcePowerOfTwo)
{
var texture = this.texture;
if(!texture.baseTexture.hasLoaded)return;
var baseTexture = texture.baseTexture;
var frame = texture.frame;
var targetWidth, targetHeight;
// check that the frame is the same size as the base texture.
var isFrame = frame.width !== baseTexture.width || frame.height !== baseTexture.height;
var newTextureRequired = false;
if(!forcePowerOfTwo)
{
if(isFrame)
{
targetWidth = frame.width;
targetHeight = frame.height;
newTextureRequired = true;
}
}
else
{
targetWidth = PIXI.getNextPowerOfTwo(frame.width);
targetHeight = PIXI.getNextPowerOfTwo(frame.height);
if(frame.width !== targetWidth && frame.height !== targetHeight)newTextureRequired = true;
}
if(newTextureRequired)
{
var canvasBuffer;
if(this.tilingTexture && this.tilingTexture.isTiling)
{
canvasBuffer = this.tilingTexture.canvasBuffer;
canvasBuffer.resize(targetWidth, targetHeight);
this.tilingTexture.baseTexture.width = targetWidth;
this.tilingTexture.baseTexture.height = targetHeight;
this.tilingTexture.needsUpdate = true;
}
else
{
canvasBuffer = new PIXI.CanvasBuffer(targetWidth, targetHeight);
this.tilingTexture = PIXI.Texture.fromCanvas(canvasBuffer.canvas);
this.tilingTexture.canvasBuffer = canvasBuffer;
this.tilingTexture.isTiling = true;
}
canvasBuffer.context.drawImage(texture.baseTexture.source,
frame.x,
frame.y,
frame.width,
frame.height,
0,
0,
targetWidth,
targetHeight);
this.tileScaleOffset.x = frame.width / targetWidth;
this.tileScaleOffset.y = frame.height / targetHeight;
}
else
{
//TODO - switching?
if(this.tilingTexture && this.tilingTexture.isTiling)
{
// destroy the tiling texture!
// TODO could store this somewhere?
this.tilingTexture.destroy(true);
}
this.tileScaleOffset.x = 1;
this.tileScaleOffset.y = 1;
this.tilingTexture = texture;
}
this.refreshTexture = false;
this.tilingTexture.baseTexture._powerOf2 = true;
};
/**
* @author Mat Groves http://matgroves.com/ @Doormat23
*/
PIXI.BaseTextureCache = {};
PIXI.texturesToUpdate = [];
PIXI.texturesToDestroy = [];
PIXI.BaseTextureCacheIdGenerator = 0;
/**
* A texture stores the information that represents an image. All textures have a base texture
*
* @class BaseTexture
* @uses EventTarget
* @constructor
* @param source {String} the source object (image or canvas)
* @param scaleMode {Number} Should be one of the PIXI.scaleMode consts
*/
PIXI.BaseTexture = function(source, scaleMode)
{
PIXI.EventTarget.call( this );
/**
* [read-only] The width of the base texture set when the image has loaded
*
* @property width
* @type Number
* @readOnly
*/
this.width = 100;
/**
* [read-only] The height of the base texture set when the image has loaded
*
* @property height
* @type Number
* @readOnly
*/
this.height = 100;
/**
* The scale mode to apply when scaling this texture
* @property scaleMode
* @type PIXI.scaleModes
* @default PIXI.scaleModes.LINEAR
*/
this.scaleMode = scaleMode || PIXI.scaleModes.DEFAULT;
/**
* [read-only] Describes if the base texture has loaded or not
*
* @property hasLoaded
* @type Boolean
* @readOnly
*/
this.hasLoaded = false;
/**
* The source that is loaded to create the texture
*
* @property source
* @type Image
*/
this.source = source;
//TODO will be used for futer pixi 1.5...
this.id = PIXI.BaseTextureCacheIdGenerator++;
// used for webGL
this._glTextures = [];
if(!source)return;
if(this.source.complete || this.source.getContext)
{
this.hasLoaded = true;
this.width = this.source.width;
this.height = this.source.height;
PIXI.texturesToUpdate.push(this);
}
else
{
var scope = this;
this.source.onload = function() {
scope.hasLoaded = true;
scope.width = scope.source.width;
scope.height = scope.source.height;
// add it to somewhere...
PIXI.texturesToUpdate.push(scope);
scope.dispatchEvent( { type: 'loaded', content: scope } );
};
}
this.imageUrl = null;
this._powerOf2 = false;
};
PIXI.BaseTexture.prototype.constructor = PIXI.BaseTexture;
/**
* Destroys this base texture
*
* @method destroy
*/
PIXI.BaseTexture.prototype.destroy = function()
{
if(this.imageUrl)
{
delete PIXI.BaseTextureCache[this.imageUrl];
this.imageUrl = null;
this.source.src = null;
}
this.source = null;
PIXI.texturesToDestroy.push(this);
};
/**
* Changes the source image of the texture
*
* @method updateSourceImage
* @param newSrc {String} the path of the image
*/
PIXI.BaseTexture.prototype.updateSourceImage = function(newSrc)
{
this.hasLoaded = false;
this.source.src = null;
this.source.src = newSrc;
};
/**
* Helper function that returns a base texture based on an image url
* If the image is not in the base texture cache it will be created and loaded
*
* @static
* @method fromImage
* @param imageUrl {String} The image url of the texture
* @param crossorigin {Boolean}
* @param scaleMode {Number} Should be one of the PIXI.scaleMode consts
* @return BaseTexture
*/
PIXI.BaseTexture.fromImage = function(imageUrl, crossorigin, scaleMode)
{
var baseTexture = PIXI.BaseTextureCache[imageUrl];
if(!baseTexture)
{
// new Image() breaks tex loading in some versions of Chrome.
// See https://code.google.com/p/chromium/issues/detail?id=238071
var image = new Image();//document.createElement('img');
if (crossorigin)
{
image.crossOrigin = '';
}
image.src = imageUrl;
baseTexture = new PIXI.BaseTexture(image, scaleMode);
baseTexture.imageUrl = imageUrl;
PIXI.BaseTextureCache[imageUrl] = baseTexture;
}
return baseTexture;
};
PIXI.BaseTexture.fromCanvas = function(canvas, scaleMode)
{
if(!canvas._pixiId)
{
canvas._pixiId = 'canvas_' + PIXI.TextureCacheIdGenerator++;
}
var baseTexture = PIXI.BaseTextureCache[canvas._pixiId];
if(!baseTexture)
{
baseTexture = new PIXI.BaseTexture(canvas, scaleMode);
PIXI.BaseTextureCache[canvas._pixiId] = baseTexture;
}
return baseTexture;
};
/**
* @author Mat Groves http://matgroves.com/ @Doormat23
*/
PIXI.TextureCache = {};
PIXI.FrameCache = {};
PIXI.TextureCacheIdGenerator = 0;
/**
* A texture stores the information that represents an image or part of an image. It cannot be added
* to the display list directly. To do this use PIXI.Sprite. If no frame is provided then the whole image is used
*
* @class Texture
* @uses EventTarget
* @constructor
* @param baseTexture {BaseTexture} The base texture source to create the texture from
* @param frame {Rectangle} The rectangle frame of the texture to show
*/
PIXI.Texture = function(baseTexture, frame)
{
PIXI.EventTarget.call( this );
if(!frame)
{
this.noFrame = true;
frame = new PIXI.Rectangle(0,0,1,1);
}
if(baseTexture instanceof PIXI.Texture)
baseTexture = baseTexture.baseTexture;
/**
* The base texture of that this texture uses
*
* @property baseTexture
* @type BaseTexture
*/
this.baseTexture = baseTexture;
/**
* The frame specifies the region of the base texture that this texture uses
*
* @property frame
* @type Rectangle
*/
this.frame = frame;
/**
* The trim point
*
* @property trim
* @type Rectangle
*/
this.trim = null;
this.scope = this;
this._uvs = null;
if(baseTexture.hasLoaded)
{
if(this.noFrame)frame = new PIXI.Rectangle(0,0, baseTexture.width, baseTexture.height);
this.setFrame(frame);
}
else
{
var scope = this;
baseTexture.addEventListener('loaded', function(){ scope.onBaseTextureLoaded(); });
}
};
PIXI.Texture.prototype.constructor = PIXI.Texture;
/**
* Called when the base texture is loaded
*
* @method onBaseTextureLoaded
* @param event
* @private
*/
PIXI.Texture.prototype.onBaseTextureLoaded = function()
{
var baseTexture = this.baseTexture;
baseTexture.removeEventListener( 'loaded', this.onLoaded );
if(this.noFrame)this.frame = new PIXI.Rectangle(0,0, baseTexture.width, baseTexture.height);
this.setFrame(this.frame);
this.scope.dispatchEvent( { type: 'update', content: this } );
};
/**
* Destroys this texture
*
* @method destroy
* @param destroyBase {Boolean} Whether to destroy the base texture as well
*/
PIXI.Texture.prototype.destroy = function(destroyBase)
{
if(destroyBase) this.baseTexture.destroy();
};
/**
* Specifies the rectangle region of the baseTexture
*
* @method setFrame
* @param frame {Rectangle} The frame of the texture to set it to
*/
PIXI.Texture.prototype.setFrame = function(frame)
{
this.frame = frame;
this.width = frame.width;
this.height = frame.height;
if(frame.x + frame.width > this.baseTexture.width || frame.y + frame.height > this.baseTexture.height)
{
throw new Error('Texture Error: frame does not fit inside the base Texture dimensions ' + this);
}
this.updateFrame = true;
PIXI.Texture.frameUpdates.push(this);
//this.dispatchEvent( { type: 'update', content: this } );
};
PIXI.Texture.prototype._updateWebGLuvs = function()
{
if(!this._uvs)this._uvs = new PIXI.TextureUvs();
var frame = this.frame;
var tw = this.baseTexture.width;
var th = this.baseTexture.height;
this._uvs.x0 = frame.x / tw;
this._uvs.y0 = frame.y / th;
this._uvs.x1 = (frame.x + frame.width) / tw;
this._uvs.y1 = frame.y / th;
this._uvs.x2 = (frame.x + frame.width) / tw;
this._uvs.y2 = (frame.y + frame.height) / th;
this._uvs.x3 = frame.x / tw;
this._uvs.y3 = (frame.y + frame.height) / th;
};
/**
* Helper function that returns a texture based on an image url
* If the image is not in the texture cache it will be created and loaded
*
* @static
* @method fromImage
* @param imageUrl {String} The image url of the texture
* @param crossorigin {Boolean} Whether requests should be treated as crossorigin
* @return Texture
*/
PIXI.Texture.fromImage = function(imageUrl, crossorigin, scaleMode)
{
var texture = PIXI.TextureCache[imageUrl];
if(!texture)
{
texture = new PIXI.Texture(PIXI.BaseTexture.fromImage(imageUrl, crossorigin, scaleMode));
PIXI.TextureCache[imageUrl] = texture;
}
return texture;
};
/**
* Helper function that returns a texture based on a frame id
* If the frame id is not in the texture cache an error will be thrown
*
* @static
* @method fromFrame
* @param frameId {String} The frame id of the texture
* @return Texture
*/
PIXI.Texture.fromFrame = function(frameId)
{
var texture = PIXI.TextureCache[frameId];
if(!texture) throw new Error('The frameId "' + frameId + '" does not exist in the texture cache ');
return texture;
};
/**
* Helper function that returns a texture based on a canvas element
* If the canvas is not in the texture cache it will be created and loaded
*
* @static
* @method fromCanvas
* @param canvas {Canvas} The canvas element source of the texture
* @return Texture
*/
PIXI.Texture.fromCanvas = function(canvas, scaleMode)
{
var baseTexture = PIXI.BaseTexture.fromCanvas(canvas, scaleMode);
return new PIXI.Texture( baseTexture );
};
/**
* Adds a texture to the textureCache.
*
* @static
* @method addTextureToCache
* @param texture {Texture}
* @param id {String} the id that the texture will be stored against.
*/
PIXI.Texture.addTextureToCache = function(texture, id)
{
PIXI.TextureCache[id] = texture;
};
/**
* Remove a texture from the textureCache.
*
* @static
* @method removeTextureFromCache
* @param id {String} the id of the texture to be removed
* @return {Texture} the texture that was removed
*/
PIXI.Texture.removeTextureFromCache = function(id)
{
var texture = PIXI.TextureCache[id];
delete PIXI.TextureCache[id];
delete PIXI.BaseTextureCache[id];
return texture;
};
// this is more for webGL.. it contains updated frames..
PIXI.Texture.frameUpdates = [];
PIXI.TextureUvs = function()
{
this.x0 = 0;
this.y0 = 0;
this.x1 = 0;
this.y1 = 0;
this.x2 = 0;
this.y2 = 0;
this.x3 = 0;
this.y4 = 0;
};
/**
* @author Mat Groves http://matgroves.com/ @Doormat23
*/
/**
A RenderTexture is a special texture that allows any pixi displayObject to be rendered to it.
__Hint__: All DisplayObjects (exmpl. Sprites) that render on RenderTexture should be preloaded.
Otherwise black rectangles will be drawn instead.
RenderTexture takes snapshot of DisplayObject passed to render method. If DisplayObject is passed to render method, position and rotation of it will be ignored. For example:
var renderTexture = new PIXI.RenderTexture(800, 600);
var sprite = PIXI.Sprite.fromImage("spinObj_01.png");
sprite.position.x = 800/2;
sprite.position.y = 600/2;
sprite.anchor.x = 0.5;
sprite.anchor.y = 0.5;
renderTexture.render(sprite);
Sprite in this case will be rendered to 0,0 position. To render this sprite at center DisplayObjectContainer should be used:
var doc = new PIXI.DisplayObjectContainer();
doc.addChild(sprite);
renderTexture.render(doc); // Renders to center of renderTexture
* @class RenderTexture
* @extends Texture
* @constructor
* @param width {Number} The width of the render texture
* @param height {Number} The height of the render texture
*/
PIXI.RenderTexture = function(width, height, renderer)
{
PIXI.EventTarget.call( this );
/**
* The with of the render texture
*
* @property width
* @type Number
*/
this.width = width || 100;
/**
* The height of the render texture
*
* @property height
* @type Number
*/
this.height = height || 100;
/**
* The framing rectangle of the render texture
*
* @property frame
* @type Rectangle
*/
this.frame = new PIXI.Rectangle(0, 0, this.width, this.height);
/**
* The base texture object that this texture uses
*
* @property baseTexture
* @type BaseTexture
*/
this.baseTexture = new PIXI.BaseTexture();
this.baseTexture.width = this.width;
this.baseTexture.height = this.height;
this.baseTexture._glTextures = [];
this.baseTexture.hasLoaded = true;
// each render texture can only belong to one renderer at the moment if its webGL
this.renderer = renderer || PIXI.defaultRenderer;
if(this.renderer.type === PIXI.WEBGL_RENDERER)
{
var gl = this.renderer.gl;
this.textureBuffer = new PIXI.FilterTexture(gl, this.width, this.height);
this.baseTexture._glTextures[gl.id] = this.textureBuffer.texture;
this.render = this.renderWebGL;
this.projection = new PIXI.Point(this.width/2 , -this.height/2);
}
else
{
this.render = this.renderCanvas;
this.textureBuffer = new PIXI.CanvasBuffer(this.width, this.height);
this.baseTexture.source = this.textureBuffer.canvas;
}
PIXI.Texture.frameUpdates.push(this);
};
PIXI.RenderTexture.prototype = Object.create(PIXI.Texture.prototype);
PIXI.RenderTexture.prototype.constructor = PIXI.RenderTexture;
PIXI.RenderTexture.prototype.resize = function(width, height)
{
this.width = width;
this.height = height;
this.frame.width = this.width;
this.frame.height = this.height;
if(this.renderer.type === PIXI.WEBGL_RENDERER)
{
this.projection.x = this.width / 2;
this.projection.y = -this.height / 2;
var gl = this.renderer.gl;
gl.bindTexture(gl.TEXTURE_2D, this.baseTexture._glTextures[gl.id]);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, this.width, this.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
}
else
{
this.textureBuffer.resize(this.width, this.height);
}
PIXI.Texture.frameUpdates.push(this);
};
/**
* This function will draw the display object to the texture.
*
* @method renderWebGL
* @param displayObject {DisplayObject} The display object to render this texture on
* @param clear {Boolean} If true the texture will be cleared before the displayObject is drawn
* @private
*/
PIXI.RenderTexture.prototype.renderWebGL = function(displayObject, position, clear)
{
//TOOD replace position with matrix..
var gl = this.renderer.gl;
gl.colorMask(true, true, true, true);
gl.viewport(0, 0, this.width, this.height);
gl.bindFramebuffer(gl.FRAMEBUFFER, this.textureBuffer.frameBuffer );
if(clear)this.textureBuffer.clear();
// THIS WILL MESS WITH HIT TESTING!
var children = displayObject.children;
//TODO -? create a new one??? dont think so!
var originalWorldTransform = displayObject.worldTransform;
displayObject.worldTransform = PIXI.RenderTexture.tempMatrix;
// modify to flip...
displayObject.worldTransform.d = -1;
displayObject.worldTransform.ty = this.projection.y * -2;
if(position)
{
displayObject.worldTransform.tx = position.x;
displayObject.worldTransform.ty -= position.y;
}
for(var i=0,j=children.length; i<j; i++)
{
children[i].updateTransform();
}
// update the textures!
PIXI.WebGLRenderer.updateTextures();
//
this.renderer.renderDisplayObject(displayObject, this.projection, this.textureBuffer.frameBuffer);
displayObject.worldTransform = originalWorldTransform;
};
/**
* This function will draw the display object to the texture.
*
* @method renderCanvas
* @param displayObject {DisplayObject} The display object to render this texture on
* @param clear {Boolean} If true the texture will be cleared before the displayObject is drawn
* @private
*/
PIXI.RenderTexture.prototype.renderCanvas = function(displayObject, position, clear)
{
var children = displayObject.children;
var originalWorldTransform = displayObject.worldTransform;
displayObject.worldTransform = PIXI.RenderTexture.tempMatrix;
if(position)
{
displayObject.worldTransform.tx = position.x;
displayObject.worldTransform.ty = position.y;
}
for(var i = 0, j = children.length; i < j; i++)
{
children[i].updateTransform();
}
if(clear)this.textureBuffer.clear();
var context = this.textureBuffer.context;
this.renderer.renderDisplayObject(displayObject, context);
context.setTransform(1,0,0,1,0,0);
displayObject.worldTransform = originalWorldTransform;
};
PIXI.RenderTexture.tempMatrix = new PIXI.Matrix();
/**
* @author Mat Groves http://matgroves.com/ @Doormat23
*/
if (typeof exports !== 'undefined') {
if (typeof module !== 'undefined' && module.exports) {
exports = module.exports = PIXI;
}
exports.PIXI = PIXI;
} else if (typeof define !== 'undefined' && define.amd) {
define('PIXI', (function() { return root.PIXI = PIXI; })() );
} else {
root.PIXI = PIXI;
}
}).call(this);
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2014 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*
* @overview
*
* Phaser - http://www.phaser.io
*
* v2.0.0 "Aes Sedai" - Built: Mon Mar 10 2014 11:07:14
*
* By Richard Davey http://www.photonstorm.com @photonstorm
*
* Phaser is a fun, free and fast 2D game framework for making HTML5 games
* for desktop and mobile web browsers, supporting Canvas and WebGL.
*
* Phaser uses Pixi.js for rendering, created by Mat Groves http://matgroves.com @Doormat23
* Phaser uses p2.js for full-body physics, created by Stefan Hedman https://github.com/schteppe/p2.js @schteppe
* Phaser contains a port of N+ Physics, converted by Richard Davey, original by http://www.metanetsoftware.com
*
* Many thanks to Adam Saltsman (@ADAMATOMIC) for releasing Flixel, from which both Phaser
* and my love of framework development can be traced.
*
* Follow development at http://phaser.io and on our forum
*
* "If you want your children to be intelligent, read them fairy tales."
* "If you want them to be more intelligent, read them more fairy tales."
* -- Albert Einstein
*/
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2014 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
(function(){
var root = this;
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2014 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @namespace Phaser
*/
var Phaser = Phaser || {
VERSION: '<%= version %>',
DEV_VERSION: '2.0',
GAMES: [],
AUTO: 0,
CANVAS: 1,
WEBGL: 2,
HEADLESS: 3,
SPRITE: 0,
BUTTON: 1,
IMAGE: 2,
GRAPHICS: 3,
TEXT: 4,
TILESPRITE: 5,
BITMAPTEXT: 6,
GROUP: 7,
RENDERTEXTURE: 8,
TILEMAP: 9,
TILEMAPLAYER: 10,
EMITTER: 11,
POLYGON: 12,
BITMAPDATA: 13,
CANVAS_FILTER: 14,
WEBGL_FILTER: 15,
ELLIPSE: 16,
SPRITEBATCH: 17,
BITMAPFONT: 18,
NONE: 0,
LEFT: 1,
RIGHT: 2,
UP: 3,
DOWN: 4,
DYNAMIC: 1,
STATIC: 2,
KINEMATIC: 4,
// the various blend modes supported by pixi / phaser
blendModes: {
NORMAL:0,
ADD:1,
MULTIPLY:2,
SCREEN:3,
OVERLAY:4,
DARKEN:5,
LIGHTEN:6,
COLOR_DODGE:7,
COLOR_BURN:8,
HARD_LIGHT:9,
SOFT_LIGHT:10,
DIFFERENCE:11,
EXCLUSION:12,
HUE:13,
SATURATION:14,
COLOR:15,
LUMINOSITY:16
},
// the scale modes
scaleModes: {
DEFAULT:0,
LINEAR:0,
NEAREST:1
}
};
PIXI.InteractionManager = function (dummy) {
// We don't need this in Pixi, so we've removed it to save space
// however the Stage object expects a reference to it, so here is a dummy entry.
};
/* jshint supernew: true */
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2014 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @class Phaser.Utils
* @static
*/
Phaser.Utils = {
/**
* Get a unit dimension from a string.
*
* @method Phaser.Utils.parseDimension
* @param {string|number} size - The size to parse.
* @param {number} dimension - The window dimension to check.
* @return {number} The parsed dimension.
*/
parseDimension: function (size, dimension) {
var f = 0;
var px = 0;
if (typeof size === 'string')
{
// %?
if (size.substr(-1) === '%')
{
f = parseInt(size, 10) / 100;
if (dimension === 0)
{
px = window.innerWidth * f;
}
else
{
px = window.innerHeight * f;
}
}
else
{
px = parseInt(size, 10);
}
}
else
{
px = size;
}
return px;
},
/**
* A standard Fisher-Yates Array shuffle implementation.
* @method Phaser.Utils.shuffle
* @param {array} array - The array to shuffle.
* @return {array} The shuffled array.
*/
shuffle: function (array) {
for (var i = array.length - 1; i > 0; i--)
{
var j = Math.floor(Math.random() * (i + 1));
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return array;
},
/**
* Javascript string pad http://www.webtoolkit.info/.
* pad = the string to pad it out with (defaults to a space)
* dir = 1 (left), 2 (right), 3 (both)
* @method Phaser.Utils.pad
* @param {string} str - The target string.
* @param {number} len - The number of characters to be added.
* @param {number} pad - The string to pad it out with (defaults to a space).
* @param {number} [dir=3] The direction dir = 1 (left), 2 (right), 3 (both).
* @return {string} The padded string
*/
pad: function (str, len, pad, dir) {
if (typeof(len) == "undefined") { var len = 0; }
if (typeof(pad) == "undefined") { var pad = ' '; }
if (typeof(dir) == "undefined") { var dir = 3; }
var padlen = 0;
if (len + 1 >= str.length)
{
switch (dir)
{
case 1:
str = Array(len + 1 - str.length).join(pad) + str;
break;
case 3:
var right = Math.ceil((padlen = len - str.length) / 2);
var left = padlen - right;
str = Array(left+1).join(pad) + str + Array(right+1).join(pad);
break;
default:
str = str + Array(len + 1 - str.length).join(pad);
break;
}
}
return str;
},
/**
* This is a slightly modified version of jQuery.isPlainObject. A plain object is an object whose internal class property is [object Object].
* @method Phaser.Utils.isPlainObject
* @param {object} obj - The object to inspect.
* @return {boolean} - true if the object is plain, otherwise false.
*/
isPlainObject: function (obj) {
// Not plain objects:
// - Any object or value whose internal [[Class]] property is not "[object Object]"
// - DOM nodes
// - window
if (typeof(obj) !== "object" || obj.nodeType || obj === obj.window)
{
return false;
}
// Support: Firefox <20
// The try/catch suppresses exceptions thrown when attempting to access
// the "constructor" property of certain host objects, ie. |window.location|
// https://bugzilla.mozilla.org/show_bug.cgi?id=814622
try {
if (obj.constructor && !hasOwn.call(obj.constructor.prototype, "isPrototypeOf"))
{
return false;
}
} catch (e) {
return false;
}
// If the function hasn't returned already, we're confident that
// |obj| is a plain object, created by {} or constructed with new Object
return true;
},
// deep, target, objects to copy to the target object
// This is a slightly modified version of {@link http://api.jquery.com/jQuery.extend/|jQuery.extend}
// deep (boolean)
// target (object to add to)
// objects ... (objects to recurse and copy from)
/**
* This is a slightly modified version of http://api.jquery.com/jQuery.extend/
* @method Phaser.Utils.extend
* @param {boolean} deep - Perform a deep copy?
* @param {object} target - The target object to copy to.
* @return {object} The extended object.
*/
extend: function () {
var options, name, src, copy, copyIsArray, clone,
target = arguments[0] || {},
i = 1,
length = arguments.length,
deep = false;
// Handle a deep copy situation
if (typeof target === "boolean")
{
deep = target;
target = arguments[1] || {};
// skip the boolean and the target
i = 2;
}
// extend Phaser if only one argument is passed
if (length === i)
{
target = this;
--i;
}
for ( ; i < length; i++ )
{
// Only deal with non-null/undefined values
if ((options = arguments[i]) != null)
{
// Extend the base object
for (name in options)
{
src = target[name];
copy = options[name];
// Prevent never-ending loop
if (target === copy)
{
continue;
}
// Recurse if we're merging plain objects or arrays
if (deep && copy && (Phaser.Utils.isPlainObject(copy) || (copyIsArray = Array.isArray(copy))))
{
if (copyIsArray)
{
copyIsArray = false;
clone = src && Array.isArray(src) ? src : [];
}
else
{
clone = src && Phaser.Utils.isPlainObject(src) ? src : {};
}
// Never move original objects, clone them
target[name] = Phaser.Utils.extend(deep, clone, copy);
// Don't bring in undefined values
}
else if (copy !== undefined)
{
target[name] = copy;
}
}
}
}
// Return the modified object
return target;
}
};
/**
* A polyfill for Function.prototype.bind
*/
if (typeof Function.prototype.bind != 'function') {
Function.prototype.bind = (function () {
var slice = Array.prototype.slice;
return function (thisArg) {
var target = this, boundArgs = slice.call(arguments, 1);
if (typeof target != 'function')
{
throw new TypeError();
}
function bound() {
var args = boundArgs.concat(slice.call(arguments));
target.apply(this instanceof bound ? this : thisArg, args);
}
bound.prototype = (function F(proto) {
proto && (F.prototype = proto);
if (!(this instanceof F))
{
return new F;
}
})(target.prototype);
return bound;
};
})();
}
/**
* A polyfill for Array.isArray
*/
if (!Array.isArray) {
Array.isArray = function (arg) {
return Object.prototype.toString.call(arg) == '[object Array]';
};
}
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2014 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* Creates a new Circle object with the center coordinate specified by the x and y parameters and the diameter specified by the diameter parameter. If you call this function without parameters, a circle with x, y, diameter and radius properties set to 0 is created.
* @class Circle
* @classdesc Phaser - Circle
* @constructor
* @param {number} [x=0] - The x coordinate of the center of the circle.
* @param {number} [y=0] - The y coordinate of the center of the circle.
* @param {number} [diameter=0] - The diameter of the circle.
* @return {Phaser.Circle} This circle object
*/
Phaser.Circle = function (x, y, diameter) {
x = x || 0;
y = y || 0;
diameter = diameter || 0;
/**
* @property {number} x - The x coordinate of the center of the circle.
*/
this.x = x;
/**
* @property {number} y - The y coordinate of the center of the circle.
*/
this.y = y;
/**
* @property {number} _diameter - The diameter of the circle.
* @private
*/
this._diameter = diameter;
if (diameter > 0)
{
/**
* @property {number} _radius - The radius of the circle.
* @private
*/
this._radius = diameter * 0.5;
}
else
{
this._radius = 0;
}
};
Phaser.Circle.prototype = {
/**
* The circumference of the circle.
* @method Phaser.Circle#circumference
* @return {number}
*/
circumference: function () {
return 2 * (Math.PI * this._radius);
},
/**
* Sets the members of Circle to the specified values.
* @method Phaser.Circle#setTo
* @param {number} x - The x coordinate of the center of the circle.
* @param {number} y - The y coordinate of the center of the circle.
* @param {number} diameter - The diameter of the circle in pixels.
* @return {Circle} This circle object.
*/
setTo: function (x, y, diameter) {
this.x = x;
this.y = y;
this._diameter = diameter;
this._radius = diameter * 0.5;
return this;
},
/**
* Copies the x, y and diameter properties from any given object to this Circle.
* @method Phaser.Circle#copyFrom
* @param {any} source - The object to copy from.
* @return {Circle} This Circle object.
*/
copyFrom: function (source) {
return this.setTo(source.x, source.y, source.diameter);
},
/**
* Copies the x, y and diameter properties from this Circle to any given object.
* @method Phaser.Circle#copyTo
* @param {any} dest - The object to copy to.
* @return {Object} This dest object.
*/
copyTo: function (dest) {
dest.x = this.x;
dest.y = this.y;
dest.diameter = this._diameter;
return dest;
},
/**
* Returns the distance from the center of the Circle object to the given object
* (can be Circle, Point or anything with x/y properties)
* @method Phaser.Circle#distance
* @param {object} dest - The target object. Must have visible x and y properties that represent the center of the object.
* @param {boolean} [round] - Round the distance to the nearest integer (default false).
* @return {number} The distance between this Point object and the destination Point object.
*/
distance: function (dest, round) {
if (typeof round === "undefined") { round = false }
if (round)
{
return Phaser.Math.distanceRound(this.x, this.y, dest.x, dest.y);
}
else
{
return Phaser.Math.distance(this.x, this.y, dest.x, dest.y);
}
},
/**
* Returns a new Circle object with the same values for the x, y, width, and height properties as this Circle object.
* @method Phaser.Circle#clone
* @param {Phaser.Circle} out - Optional Circle object. If given the values will be set into the object, otherwise a brand new Circle object will be created and returned.
* @return {Phaser.Circle} The cloned Circle object.
*/
clone: function (out) {
if (typeof out === "undefined")
{
out = new Phaser.Circle(this.x, this.y, this.diameter);
}
else
{
out.setTo(this.x, this.y, this.diameter);
}
return out;
},
/**
* Return true if the given x/y coordinates are within this Circle object.
* @method Phaser.Circle#contains
* @param {number} x - The X value of the coordinate to test.
* @param {number} y - The Y value of the coordinate to test.
* @return {boolean} True if the coordinates are within this circle, otherwise false.
*/
contains: function (x, y) {
return Phaser.Circle.contains(this, x, y);
},
/**
* Returns a Point object containing the coordinates of a point on the circumference of the Circle based on the given angle.
* @method Phaser.Circle#circumferencePoint
* @param {number} angle - The angle in radians (unless asDegrees is true) to return the point from.
* @param {boolean} asDegrees - Is the given angle in radians (false) or degrees (true)?
* @param {Phaser.Point} [out] - An optional Point object to put the result in to. If none specified a new Point object will be created.
* @return {Phaser.Point} The Point object holding the result.
*/
circumferencePoint: function (angle, asDegrees, out) {
return Phaser.Circle.circumferencePoint(this, angle, asDegrees, out);
},
/**
* Adjusts the location of the Circle object, as determined by its center coordinate, by the specified amounts.
* @method Phaser.Circle#offset
* @param {number} dx - Moves the x value of the Circle object by this amount.
* @param {number} dy - Moves the y value of the Circle object by this amount.
* @return {Circle} This Circle object.
*/
offset: function (dx, dy) {
this.x += dx;
this.y += dy;
return this;
},
/**
* Adjusts the location of the Circle object using a Point object as a parameter. This method is similar to the Circle.offset() method, except that it takes a Point object as a parameter.
* @method Phaser.Circle#offsetPoint
* @param {Point} point A Point object to use to offset this Circle object (or any valid object with exposed x and y properties).
* @return {Circle} This Circle object.
*/
offsetPoint: function (point) {
return this.offset(point.x, point.y);
},
/**
* Returns a string representation of this object.
* @method Phaser.Circle#toString
* @return {string} a string representation of the instance.
*/
toString: function () {
return "[{Phaser.Circle (x=" + this.x + " y=" + this.y + " diameter=" + this.diameter + " radius=" + this.radius + ")}]";
}
};
Phaser.Circle.prototype.constructor = Phaser.Circle;
/**
* The largest distance between any two points on the circle. The same as the radius * 2.
* @name Phaser.Circle#diameter
* @property {number} diameter - Gets or sets the diameter of the circle.
*/
Object.defineProperty(Phaser.Circle.prototype, "diameter", {
get: function () {
return this._diameter;
},
set: function (value) {
if (value > 0)
{
this._diameter = value;
this._radius = value * 0.5;
}
}
});
/**
* The length of a line extending from the center of the circle to any point on the circle itself. The same as half the diameter.
* @name Phaser.Circle#radius
* @property {number} radius - Gets or sets the radius of the circle.
*/
Object.defineProperty(Phaser.Circle.prototype, "radius", {
get: function () {
return this._radius;
},
set: function (value) {
if (value > 0)
{
this._radius = value;
this._diameter = value * 2;
}
}
});
/**
* The x coordinate of the leftmost point of the circle. Changing the left property of a Circle object has no effect on the x and y properties. However it does affect the diameter, whereas changing the x value does not affect the diameter property.
* @name Phaser.Circle#left
* @propety {number} left - Gets or sets the value of the leftmost point of the circle.
*/
Object.defineProperty(Phaser.Circle.prototype, "left", {
get: function () {
return this.x - this._radius;
},
set: function (value) {
if (value > this.x)
{
this._radius = 0;
this._diameter = 0;
}
else
{
this.radius = this.x - value;
}
}
});
/**
* The x coordinate of the rightmost point of the circle. Changing the right property of a Circle object has no effect on the x and y properties. However it does affect the diameter, whereas changing the x value does not affect the diameter property.
* @name Phaser.Circle#right
* @property {number} right - Gets or sets the value of the rightmost point of the circle.
*/
Object.defineProperty(Phaser.Circle.prototype, "right", {
get: function () {
return this.x + this._radius;
},
set: function (value) {
if (value < this.x)
{
this._radius = 0;
this._diameter = 0;
}
else
{
this.radius = value - this.x;
}
}
});
/**
* The sum of the y minus the radius property. Changing the top property of a Circle object has no effect on the x and y properties, but does change the diameter.
* @name Phaser.Circle#top
* @property {number} top - Gets or sets the top of the circle.
*/
Object.defineProperty(Phaser.Circle.prototype, "top", {
get: function () {
return this.y - this._radius;
},
set: function (value) {
if (value > this.y)
{
this._radius = 0;
this._diameter = 0;
}
else
{
this.radius = this.y - value;
}
}
});
/**
* The sum of the y and radius properties. Changing the bottom property of a Circle object has no effect on the x and y properties, but does change the diameter.
* @name Phaser.Circle#bottom
* @property {number} bottom - Gets or sets the bottom of the circle.
*/
Object.defineProperty(Phaser.Circle.prototype, "bottom", {
get: function () {
return this.y + this._radius;
},
set: function (value) {
if (value < this.y)
{
this._radius = 0;
this._diameter = 0;
}
else
{
this.radius = value - this.y;
}
}
});
/**
* The area of this Circle.
* @name Phaser.Circle#area
* @property {number} area - The area of this circle.
* @readonly
*/
Object.defineProperty(Phaser.Circle.prototype, "area", {
get: function () {
if (this._radius > 0)
{
return Math.PI * this._radius * this._radius;
}
else
{
return 0;
}
}
});
/**
* Determines whether or not this Circle object is empty. Will return a value of true if the Circle objects diameter is less than or equal to 0; otherwise false.
* If set to true it will reset all of the Circle objects properties to 0. A Circle object is empty if its diameter is less than or equal to 0.
* @name Phaser.Circle#empty
* @property {boolean} empty - Gets or sets the empty state of the circle.
*/
Object.defineProperty(Phaser.Circle.prototype, "empty", {
get: function () {
return (this._diameter === 0);
},
set: function (value) {
if (value === true)
{
this.setTo(0, 0, 0);
}
}
});
/**
* Return true if the given x/y coordinates are within the Circle object.
* @method Phaser.Circle.contains
* @param {Phaser.Circle} a - The Circle to be checked.
* @param {number} x - The X value of the coordinate to test.
* @param {number} y - The Y value of the coordinate to test.
* @return {boolean} True if the coordinates are within this circle, otherwise false.
*/
Phaser.Circle.contains = function (a, x, y) {
// Check if x/y are within the bounds first
if (a.radius > 0 && x >= a.left && x <= a.right && y >= a.top && y <= a.bottom)
{
var dx = (a.x - x) * (a.x - x);
var dy = (a.y - y) * (a.y - y);
return (dx + dy) <= (a.radius * a.radius);
}
else
{
return false;
}
};
/**
* Determines whether the two Circle objects match. This method compares the x, y and diameter properties.
* @method Phaser.Circle.equals
* @param {Phaser.Circle} a - The first Circle object.
* @param {Phaser.Circle} b - The second Circle object.
* @return {boolean} A value of true if the object has exactly the same values for the x, y and diameter properties as this Circle object; otherwise false.
*/
Phaser.Circle.equals = function (a, b) {
return (a.x == b.x && a.y == b.y && a.diameter == b.diameter);
};
/**
* Determines whether the two Circle objects intersect.
* This method checks the radius distances between the two Circle objects to see if they intersect.
* @method Phaser.Circle.intersects
* @param {Phaser.Circle} a - The first Circle object.
* @param {Phaser.Circle} b - The second Circle object.
* @return {boolean} A value of true if the specified object intersects with this Circle object; otherwise false.
*/
Phaser.Circle.intersects = function (a, b) {
return (Phaser.Math.distance(a.x, a.y, b.x, b.y) <= (a.radius + b.radius));
};
/**
* Returns a Point object containing the coordinates of a point on the circumference of the Circle based on the given angle.
* @method Phaser.Circle.circumferencePoint
* @param {Phaser.Circle} a - The first Circle object.
* @param {number} angle - The angle in radians (unless asDegrees is true) to return the point from.
* @param {boolean} asDegrees - Is the given angle in radians (false) or degrees (true)?
* @param {Phaser.Point} [out] - An optional Point object to put the result in to. If none specified a new Point object will be created.
* @return {Phaser.Point} The Point object holding the result.
*/
Phaser.Circle.circumferencePoint = function (a, angle, asDegrees, out) {
if (typeof asDegrees === "undefined") { asDegrees = false; }
if (typeof out === "undefined") { out = new Phaser.Point(); }
if (asDegrees === true)
{
angle = Phaser.Math.degToRad(angle);
}
out.x = a.x + a.radius * Math.cos(angle);
out.y = a.y + a.radius * Math.sin(angle);
return out;
};
/**
* Checks if the given Circle and Rectangle objects intersect.
* @method Phaser.Circle.intersectsRectangle
* @param {Phaser.Circle} c - The Circle object to test.
* @param {Phaser.Rectangle} r - The Rectangle object to test.
* @return {boolean} True if the two objects intersect, otherwise false.
*/
Phaser.Circle.intersectsRectangle = function (c, r) {
var cx = Math.abs(c.x - r.x - r.halfWidth);
var xDist = r.halfWidth + c.radius;
if (cx > xDist)
{
return false;
}
var cy = Math.abs(c.y - r.y - r.halfHeight);
var yDist = r.halfHeight + c.radius;
if (cy > yDist)
{
return false;
}
if (cx <= r.halfWidth || cy <= r.halfHeight)
{
return true;
}
var xCornerDist = cx - r.halfWidth;
var yCornerDist = cy - r.halfHeight;
var xCornerDistSq = xCornerDist * xCornerDist;
var yCornerDistSq = yCornerDist * yCornerDist;
var maxCornerDistSq = c.radius * c.radius;
return xCornerDistSq + yCornerDistSq <= maxCornerDistSq;
};
// Because PIXI uses its own Circle, we'll replace it with ours to avoid duplicating code or confusion.
PIXI.Circle = Phaser.Circle;
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2014 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* Creates a new Point. If you pass no parameters a Point is created set to (0,0).
* @class Phaser.Point
* @classdesc The Point object represents a location in a two-dimensional coordinate system, where x represents the horizontal axis and y represents the vertical axis.
* @constructor
* @param {number} x The horizontal position of this Point (default 0)
* @param {number} y The vertical position of this Point (default 0)
*/
Phaser.Point = function (x, y) {
x = x || 0;
y = y || 0;
/**
* @property {number} x - The x coordinate of the point.
*/
this.x = x;
/**
* @property {number} y - The y coordinate of the point.
*/
this.y = y;
};
Phaser.Point.prototype = {
/**
* Copies the x and y properties from any given object to this Point.
* @method Phaser.Point#copyFrom
* @param {any} source - The object to copy from.
* @return {Point} This Point object.
*/
copyFrom: function (source) {
return this.setTo(source.x, source.y);
},
/**
* Inverts the x and y values of this Point
* @method Phaser.Point#invert
* @return {Point} This Point object.
*/
invert: function () {
return this.setTo(this.y, this.x);
},
/**
* Sets the x and y values of this Point object to the given coordinates.
* @method Phaser.Point#setTo
* @param {number} x - The horizontal position of this point.
* @param {number} y - The vertical position of this point.
* @return {Point} This Point object. Useful for chaining method calls.
*/
setTo: function (x, y) {
this.x = x || 0;
this.y = y || ( (y !== 0) ? this.x : 0 );
return this;
},
/**
* Sets the x and y values of this Point object to the given coordinates.
* @method Phaser.Point#set
* @param {number} x - The horizontal position of this point.
* @param {number} y - The vertical position of this point.
* @return {Point} This Point object. Useful for chaining method calls.
*/
set: function (x, y) {
this.x = x || 0;
this.y = y || ( (y !== 0) ? this.x : 0 );
return this;
},
/**
* Adds the given x and y values to this Point.
* @method Phaser.Point#add
* @param {number} x - The value to add to Point.x.
* @param {number} y - The value to add to Point.y.
* @return {Phaser.Point} This Point object. Useful for chaining method calls.
*/
add: function (x, y) {
this.x += x;
this.y += y;
return this;
},
/**
* Subtracts the given x and y values from this Point.
* @method Phaser.Point#subtract
* @param {number} x - The value to subtract from Point.x.
* @param {number} y - The value to subtract from Point.y.
* @return {Phaser.Point} This Point object. Useful for chaining method calls.
*/
subtract: function (x, y) {
this.x -= x;
this.y -= y;
return this;
},
/**
* Multiplies Point.x and Point.y by the given x and y values.
* @method Phaser.Point#multiply
* @param {number} x - The value to multiply Point.x by.
* @param {number} y - The value to multiply Point.x by.
* @return {Phaser.Point} This Point object. Useful for chaining method calls.
*/
multiply: function (x, y) {
this.x *= x;
this.y *= y;
return this;
},
/**
* Divides Point.x and Point.y by the given x and y values.
* @method Phaser.Point#divide
* @param {number} x - The value to divide Point.x by.
* @param {number} y - The value to divide Point.x by.
* @return {Phaser.Point} This Point object. Useful for chaining method calls.
*/
divide: function (x, y) {
this.x /= x;
this.y /= y;
return this;
},
/**
* Clamps the x value of this Point to be between the given min and max.
* @method Phaser.Point#clampX
* @param {number} min - The minimum value to clamp this Point to.
* @param {number} max - The maximum value to clamp this Point to.
* @return {Phaser.Point} This Point object.
*/
clampX: function (min, max) {
this.x = Phaser.Math.clamp(this.x, min, max);
return this;
},
/**
* Clamps the y value of this Point to be between the given min and max
* @method Phaser.Point#clampY
* @param {number} min - The minimum value to clamp this Point to.
* @param {number} max - The maximum value to clamp this Point to.
* @return {Phaser.Point} This Point object.
*/
clampY: function (min, max) {
this.y = Phaser.Math.clamp(this.y, min, max);
return this;
},
/**
* Clamps this Point object values to be between the given min and max.
* @method Phaser.Point#clamp
* @param {number} min - The minimum value to clamp this Point to.
* @param {number} max - The maximum value to clamp this Point to.
* @return {Phaser.Point} This Point object.
*/
clamp: function (min, max) {
this.x = Phaser.Math.clamp(this.x, min, max);
this.y = Phaser.Math.clamp(this.y, min, max);
return this;
},
/**
* Creates a copy of the given Point.
* @method Phaser.Point#clone
* @param {Phaser.Point} [output] Optional Point object. If given the values will be set into this object, otherwise a brand new Point object will be created and returned.
* @return {Phaser.Point} The new Point object.
*/
clone: function (output) {
if (typeof output === "undefined")
{
output = new Phaser.Point(this.x, this.y);
}
else
{
output.setTo(this.x, this.y);
}
return output;
},
/**
* Copies the x and y properties from this Point to any given object.
* @method Phaser.Point#copyTo
* @param {any} dest - The object to copy to.
* @return {Object} The dest object.
*/
copyTo: function(dest) {
dest.x = this.x;
dest.y = this.y;
return dest;
},
/**
* Returns the distance of this Point object to the given object (can be a Circle, Point or anything with x/y properties)
* @method Phaser.Point#distance
* @param {object} dest - The target object. Must have visible x and y properties that represent the center of the object.
* @param {boolean} [round] - Round the distance to the nearest integer (default false).
* @return {number} The distance between this Point object and the destination Point object.
*/
distance: function (dest, round) {
return Phaser.Point.distance(this, dest, round);
},
/**
* Determines whether the given objects x/y values are equal to this Point object.
* @method Phaser.Point#equals
* @param {Phaser.Point} a - The first object to compare.
* @return {boolean} A value of true if the Points are equal, otherwise false.
*/
equals: function (a) {
return (a.x == this.x && a.y == this.y);
},
/**
* Rotates this Point around the x/y coordinates given to the desired angle.
* @method Phaser.Point#rotate
* @param {number} x - The x coordinate of the anchor point
* @param {number} y - The y coordinate of the anchor point
* @param {number} angle - The angle in radians (unless asDegrees is true) to rotate the Point to.
* @param {boolean} asDegrees - Is the given rotation in radians (false) or degrees (true)?
* @param {number} [distance] - An optional distance constraint between the Point and the anchor.
* @return {Phaser.Point} The modified point object.
*/
rotate: function (x, y, angle, asDegrees, distance) {
return Phaser.Point.rotate(this, x, y, angle, asDegrees, distance);
},
/**
* Calculates the length of the vector
* @method Phaser.Point#getMagnitude
* @return {number} the length of the vector
*/
getMagnitude: function() {
return Math.sqrt((this.x * this.x) + (this.y * this.y));
},
/**
* Alters the length of the vector without changing the direction
* @method Phaser.Point#setMagnitude
* @param {number} magnitude the desired magnitude of the resulting vector
* @return {Phaser.Point} the modified original vector
*/
setMagnitude: function(magnitude) {
return this.normalize().multiply(magnitude, magnitude);
},
/**
* Alters the vector so that its length is 1, but it retains the same direction
* @method Phaser.Point#normalize
* @return {Phaser.Point} the modified original vector
*/
normalize: function() {
if(!this.isZero()) {
var m = this.getMagnitude();
this.x /= m;
this.y /= m;
}
return this;
},
/**
* Determine if this point is at 0,0
* @method Phaser.Point#isZero
* @return {boolean} True if this Point is 0,0, otherwise false
*/
isZero: function() {
return (this.x === 0 && this.y === 0);
},
/**
* Returns a string representation of this object.
* @method Phaser.Point#toString
* @return {string} A string representation of the instance.
*/
toString: function () {
return '[{Point (x=' + this.x + ' y=' + this.y + ')}]';
}
};
Phaser.Point.prototype.constructor = Phaser.Point;
/**
* Adds the coordinates of two points together to create a new point.
* @method Phaser.Point.add
* @param {Phaser.Point} a - The first Point object.
* @param {Phaser.Point} b - The second Point object.
* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created.
* @return {Phaser.Point} The new Point object.
*/
Phaser.Point.add = function (a, b, out) {
if (typeof out === "undefined") { out = new Phaser.Point(); }
out.x = a.x + b.x;
out.y = a.y + b.y;
return out;
};
/**
* Subtracts the coordinates of two points to create a new point.
* @method Phaser.Point.subtract
* @param {Phaser.Point} a - The first Point object.
* @param {Phaser.Point} b - The second Point object.
* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created.
* @return {Phaser.Point} The new Point object.
*/
Phaser.Point.subtract = function (a, b, out) {
if (typeof out === "undefined") { out = new Phaser.Point(); }
out.x = a.x - b.x;
out.y = a.y - b.y;
return out;
};
/**
* Multiplies the coordinates of two points to create a new point.
* @method Phaser.Point.multiply
* @param {Phaser.Point} a - The first Point object.
* @param {Phaser.Point} b - The second Point object.
* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created.
* @return {Phaser.Point} The new Point object.
*/
Phaser.Point.multiply = function (a, b, out) {
if (typeof out === "undefined") { out = new Phaser.Point(); }
out.x = a.x * b.x;
out.y = a.y * b.y;
return out;
};
/**
* Divides the coordinates of two points to create a new point.
* @method Phaser.Point.divide
* @param {Phaser.Point} a - The first Point object.
* @param {Phaser.Point} b - The second Point object.
* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created.
* @return {Phaser.Point} The new Point object.
*/
Phaser.Point.divide = function (a, b, out) {
if (typeof out === "undefined") { out = new Phaser.Point(); }
out.x = a.x / b.x;
out.y = a.y / b.y;
return out;
};
/**
* Determines whether the two given Point objects are equal. They are considered equal if they have the same x and y values.
* @method Phaser.Point.equals
* @param {Phaser.Point} a - The first Point object.
* @param {Phaser.Point} b - The second Point object.
* @return {boolean} A value of true if the Points are equal, otherwise false.
*/
Phaser.Point.equals = function (a, b) {
return (a.x == b.x && a.y == b.y);
};
/**
* Returns the distance of this Point object to the given object (can be a Circle, Point or anything with x/y properties).
* @method Phaser.Point.distance
* @param {object} a - The target object. Must have visible x and y properties that represent the center of the object.
* @param {object} b - The target object. Must have visible x and y properties that represent the center of the object.
* @param {boolean} [round] - Round the distance to the nearest integer (default false).
* @return {number} The distance between this Point object and the destination Point object.
*/
Phaser.Point.distance = function (a, b, round) {
if (typeof round === "undefined") { round = false }
if (round)
{
return Phaser.Math.distanceRound(a.x, a.y, b.x, b.y);
}
else
{
return Phaser.Math.distance(a.x, a.y, b.x, b.y);
}
};
/**
* Rotates a Point around the x/y coordinates given to the desired angle.
* @method Phaser.Point.rotate
* @param {Phaser.Point} a - The Point object to rotate.
* @param {number} x - The x coordinate of the anchor point
* @param {number} y - The y coordinate of the anchor point
* @param {number} angle - The angle in radians (unless asDegrees is true) to rotate the Point to.
* @param {boolean} asDegrees - Is the given rotation in radians (false) or degrees (true)?
* @param {number} distance - An optional distance constraint between the Point and the anchor.
* @return {Phaser.Point} The modified point object.
*/
Phaser.Point.rotate = function (a, x, y, angle, asDegrees, distance) {
asDegrees = asDegrees || false;
distance = distance || null;
if (asDegrees)
{
angle = Phaser.Math.degToRad(angle);
}
// Get distance from origin (cx/cy) to this point
if (distance === null)
{
distance = Math.sqrt(((x - a.x) * (x - a.x)) + ((y - a.y) * (y - a.y)));
}
return a.setTo(x + distance * Math.cos(angle), y + distance * Math.sin(angle));
};
// Because PIXI uses its own Point, we'll replace it with ours to avoid duplicating code or confusion.
PIXI.Point = Phaser.Point;
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2014 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* Creates a new Rectangle object with the top-left corner specified by the x and y parameters and with the specified width and height parameters. If you call this function without parameters, a Rectangle with x, y, width, and height properties set to 0 is created.
*
* @class Phaser.Rectangle
* @constructor
* @param {number} x - The x coordinate of the top-left corner of the Rectangle.
* @param {number} y - The y coordinate of the top-left corner of the Rectangle.
* @param {number} width - The width of the Rectangle.
* @param {number} height - The height of the Rectangle.
* @return {Phaser.Rectangle} This Rectangle object.
*/
Phaser.Rectangle = function (x, y, width, height) {
x = x || 0;
y = y || 0;
width = width || 0;
height = height || 0;
/**
* @property {number} x - The x coordinate of the top-left corner of the Rectangle.
*/
this.x = x;
/**
* @property {number} y - The y coordinate of the top-left corner of the Rectangle.
*/
this.y = y;
/**
* @property {number} width - The width of the Rectangle.
*/
this.width = width;
/**
* @property {number} height - The height of the Rectangle.
*/
this.height = height;
};
Phaser.Rectangle.prototype = {
/**
* Adjusts the location of the Rectangle object, as determined by its top-left corner, by the specified amounts.
* @method Phaser.Rectangle#offset
* @param {number} dx - Moves the x value of the Rectangle object by this amount.
* @param {number} dy - Moves the y value of the Rectangle object by this amount.
* @return {Phaser.Rectangle} This Rectangle object.
*/
offset: function (dx, dy) {
this.x += dx;
this.y += dy;
return this;
},
/**
* Adjusts the location of the Rectangle object using a Point object as a parameter. This method is similar to the Rectangle.offset() method, except that it takes a Point object as a parameter.
* @method Phaser.Rectangle#offsetPoint
* @param {Phaser.Point} point - A Point object to use to offset this Rectangle object.
* @return {Phaser.Rectangle} This Rectangle object.
*/
offsetPoint: function (point) {
return this.offset(point.x, point.y);
},
/**
* Sets the members of Rectangle to the specified values.
* @method Phaser.Rectangle#setTo
* @param {number} x - The x coordinate of the top-left corner of the Rectangle.
* @param {number} y - The y coordinate of the top-left corner of the Rectangle.
* @param {number} width - The width of the Rectangle in pixels.
* @param {number} height - The height of the Rectangle in pixels.
* @return {Phaser.Rectangle} This Rectangle object
*/
setTo: function (x, y, width, height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
return this;
},
/**
* Runs Math.floor() on both the x and y values of this Rectangle.
* @method Phaser.Rectangle#floor
*/
floor: function () {
this.x = Math.floor(this.x);
this.y = Math.floor(this.y);
},
/**
* Runs Math.floor() on the x, y, width and height values of this Rectangle.
* @method Phaser.Rectangle#floorAll
*/
floorAll: function () {
this.x = Math.floor(this.x);
this.y = Math.floor(this.y);
this.width = Math.floor(this.width);
this.height = Math.floor(this.height);
},
/**
* Copies the x, y, width and height properties from any given object to this Rectangle.
* @method Phaser.Rectangle#copyFrom
* @param {any} source - The object to copy from.
* @return {Phaser.Rectangle} This Rectangle object.
*/
copyFrom: function (source) {
return this.setTo(source.x, source.y, source.width, source.height);
},
/**
* Copies the x, y, width and height properties from this Rectangle to any given object.
* @method Phaser.Rectangle#copyTo
* @param {any} source - The object to copy to.
* @return {object} This object.
*/
copyTo: function (dest) {
dest.x = this.x;
dest.y = this.y;
dest.width = this.width;
dest.height = this.height;
return dest;
},
/**
* Increases the size of the Rectangle object by the specified amounts. The center point of the Rectangle object stays the same, and its size increases to the left and right by the dx value, and to the top and the bottom by the dy value.
* @method Phaser.Rectangle#inflate
* @param {number} dx - The amount to be added to the left side of the Rectangle.
* @param {number} dy - The amount to be added to the bottom side of the Rectangle.
* @return {Phaser.Rectangle} This Rectangle object.
*/
inflate: function (dx, dy) {
return Phaser.Rectangle.inflate(this, dx, dy);
},
/**
* The size of the Rectangle object, expressed as a Point object with the values of the width and height properties.
* @method Phaser.Rectangle#size
* @param {Phaser.Point} [output] - Optional Point object. If given the values will be set into the object, otherwise a brand new Point object will be created and returned.
* @return {Phaser.Point} The size of the Rectangle object.
*/
size: function (output) {
return Phaser.Rectangle.size(this, output);
},
/**
* Returns a new Rectangle object with the same values for the x, y, width, and height properties as the original Rectangle object.
* @method Phaser.Rectangle#clone
* @param {Phaser.Rectangle} [output] - Optional Rectangle object. If given the values will be set into the object, otherwise a brand new Rectangle object will be created and returned.
* @return {Phaser.Rectangle}
*/
clone: function (output) {
return Phaser.Rectangle.clone(this, output);
},
/**
* Determines whether the specified coordinates are contained within the region defined by this Rectangle object.
* @method Phaser.Rectangle#contains
* @param {number} x - The x coordinate of the point to test.
* @param {number} y - The y coordinate of the point to test.
* @return {boolean} A value of true if the Rectangle object contains the specified point; otherwise false.
*/
contains: function (x, y) {
return Phaser.Rectangle.contains(this, x, y);
},
/**
* Determines whether the first Rectangle object is fully contained within the second Rectangle object.
* A Rectangle object is said to contain another if the second Rectangle object falls entirely within the boundaries of the first.
* @method Phaser.Rectangle#containsRect
* @param {Phaser.Rectangle} b - The second Rectangle object.
* @return {boolean} A value of true if the Rectangle object contains the specified point; otherwise false.
*/
containsRect: function (b) {
return Phaser.Rectangle.containsRect(this, b);
},
/**
* Determines whether the two Rectangles are equal.
* This method compares the x, y, width and height properties of each Rectangle.
* @method Phaser.Rectangle#equals
* @param {Phaser.Rectangle} b - The second Rectangle object.
* @return {boolean} A value of true if the two Rectangles have exactly the same values for the x, y, width and height properties; otherwise false.
*/
equals: function (b) {
return Phaser.Rectangle.equals(this, b);
},
/**
* If the Rectangle object specified in the toIntersect parameter intersects with this Rectangle object, returns the area of intersection as a Rectangle object. If the Rectangles do not intersect, this method returns an empty Rectangle object with its properties set to 0.
* @method Phaser.Rectangle#intersection
* @param {Phaser.Rectangle} b - The second Rectangle object.
* @param {Phaser.Rectangle} out - Optional Rectangle object. If given the intersection values will be set into this object, otherwise a brand new Rectangle object will be created and returned.
* @return {Phaser.Rectangle} A Rectangle object that equals the area of intersection. If the Rectangles do not intersect, this method returns an empty Rectangle object; that is, a Rectangle with its x, y, width, and height properties set to 0.
*/
intersection: function (b, out) {
return Phaser.Rectangle.intersection(this, b, out);
},
/**
* Determines whether the two Rectangles intersect with each other.
* This method checks the x, y, width, and height properties of the Rectangles.
* @method Phaser.Rectangle#intersects
* @param {Phaser.Rectangle} b - The second Rectangle object.
* @param {number} tolerance - A tolerance value to allow for an intersection test with padding, default to 0.
* @return {boolean} A value of true if the specified object intersects with this Rectangle object; otherwise false.
*/
intersects: function (b, tolerance) {
return Phaser.Rectangle.intersects(this, b, tolerance);
},
/**
* Determines whether the object specified intersects (overlaps) with the given values.
* @method Phaser.Rectangle#intersectsRaw
* @param {number} left - Description.
* @param {number} right - Description.
* @param {number} top - Description.
* @param {number} bottomt - Description.
* @param {number} tolerance - A tolerance value to allow for an intersection test with padding, default to 0
* @return {boolean} A value of true if the specified object intersects with the Rectangle; otherwise false.
*/
intersectsRaw: function (left, right, top, bottom, tolerance) {
return Phaser.Rectangle.intersectsRaw(this, left, right, top, bottom, tolerance);
},
/**
* Adds two Rectangles together to create a new Rectangle object, by filling in the horizontal and vertical space between the two Rectangles.
* @method Phaser.Rectangle#union
* @param {Phaser.Rectangle} b - The second Rectangle object.
* @param {Phaser.Rectangle} [out] - Optional Rectangle object. If given the new values will be set into this object, otherwise a brand new Rectangle object will be created and returned.
* @return {Phaser.Rectangle} A Rectangle object that is the union of the two Rectangles.
*/
union: function (b, out) {
return Phaser.Rectangle.union(this, b, out);
},
/**
* Returns a string representation of this object.
* @method Phaser.Rectangle#toString
* @return {string} A string representation of the instance.
*/
toString: function () {
return "[{Rectangle (x=" + this.x + " y=" + this.y + " width=" + this.width + " height=" + this.height + " empty=" + this.empty + ")}]";
},
/**
* @name Phaser.Rectangle#halfWidth
* @property {number} halfWidth - Half of the width of the Rectangle.
* @readonly
*/
get halfWidth() {
return Math.round(this.width / 2);
},
/**
* @name Phaser.Rectangle#halfHeight
* @property {number} halfHeight - Half of the height of the Rectangle.
* @readonly
*/
get halfHeight() {
return Math.round(this.height / 2);
},
/**
* The sum of the y and height properties. Changing the bottom property of a Rectangle object has no effect on the x, y and width properties, but does change the height property.
* @name Phaser.Rectangle#bottom
* @property {number} bottom - The sum of the y and height properties.
*/
get bottom() {
return this.y + this.height;
},
set bottom(value) {
if (value <= this.y)
{
this.height = 0;
}
else
{
this.height = (this.y - value);
}
},
/**
* The location of the Rectangles bottom right corner as a Point object.
* @name Phaser.Rectangle#bottomRight
* @property {Phaser.Point} bottomRight - Gets or sets the location of the Rectangles bottom right corner as a Point object.
*/
get bottomRight() {
return new Phaser.Point(this.right, this.bottom);
},
set bottomRight(value) {
this.right = value.x;
this.bottom = value.y;
},
/**
* The x coordinate of the left of the Rectangle. Changing the left property of a Rectangle object has no effect on the y and height properties. However it does affect the width property, whereas changing the x value does not affect the width property.
* @name Phaser.Rectangle#left
* @property {number} left - The x coordinate of the left of the Rectangle.
*/
get left() {
return this.x;
},
set left(value) {
if (value >= this.right)
{
this.width = 0;
}
else
{
this.width = this.right - value;
}
this.x = value;
},
/**
* The sum of the x and width properties. Changing the right property of a Rectangle object has no effect on the x, y and height properties, however it does affect the width property.
* @name Phaser.Rectangle#right
* @property {number} right - The sum of the x and width properties.
*/
get right() {
return this.x + this.width;
},
set right(value) {
if (value <= this.x)
{
this.width = 0;
}
else
{
this.width = this.x + value;
}
},
/**
* The volume of the Rectangle derived from width * height.
* @name Phaser.Rectangle#volume
* @property {number} volume - The volume of the Rectangle derived from width * height.
* @readonly
*/
get volume() {
return this.width * this.height;
},
/**
* The perimeter size of the Rectangle. This is the sum of all 4 sides.
* @name Phaser.Rectangle#perimeter
* @property {number} perimeter - The perimeter size of the Rectangle. This is the sum of all 4 sides.
* @readonly
*/
get perimeter() {
return (this.width * 2) + (this.height * 2);
},
/**
* The x coordinate of the center of the Rectangle.
* @name Phaser.Rectangle#centerX
* @property {number} centerX - The x coordinate of the center of the Rectangle.
*/
get centerX() {
return this.x + this.halfWidth;
},
set centerX(value) {
this.x = value - this.halfWidth;
},
/**
* The y coordinate of the center of the Rectangle.
* @name Phaser.Rectangle#centerY
* @property {number} centerY - The y coordinate of the center of the Rectangle.
*/
get centerY() {
return this.y + this.halfHeight;
},
set centerY(value) {
this.y = value - this.halfHeight;
},
/**
* The y coordinate of the top of the Rectangle. Changing the top property of a Rectangle object has no effect on the x and width properties.
* However it does affect the height property, whereas changing the y value does not affect the height property.
* @name Phaser.Rectangle#top
* @property {number} top - The y coordinate of the top of the Rectangle.
*/
get top() {
return this.y;
},
set top(value) {
if (value >= this.bottom)
{
this.height = 0;
this.y = value;
}
else
{
this.height = (this.bottom - value);
}
},
/**
* The location of the Rectangles top left corner as a Point object.
* @name Phaser.Rectangle#topLeft
* @property {Phaser.Point} topLeft - The location of the Rectangles top left corner as a Point object.
*/
get topLeft() {
return new Phaser.Point(this.x, this.y);
},
set topLeft(value) {
this.x = value.x;
this.y = value.y;
},
/**
* Determines whether or not this Rectangle object is empty. A Rectangle object is empty if its width or height is less than or equal to 0.
* If set to true then all of the Rectangle properties are set to 0.
* @name Phaser.Rectangle#empty
* @property {boolean} empty - Gets or sets the Rectangles empty state.
*/
get empty() {
return (!this.width || !this.height);
},
set empty(value) {
if (value === true)
{
this.setTo(0, 0, 0, 0);
}
}
};
Phaser.Rectangle.prototype.constructor = Phaser.Rectangle;
/**
* Increases the size of the Rectangle object by the specified amounts. The center point of the Rectangle object stays the same, and its size increases to the left and right by the dx value, and to the top and the bottom by the dy value.
* @method Phaser.Rectangle.inflate
* @param {Phaser.Rectangle} a - The Rectangle object.
* @param {number} dx - The amount to be added to the left side of the Rectangle.
* @param {number} dy - The amount to be added to the bottom side of the Rectangle.
* @return {Phaser.Rectangle} This Rectangle object.
*/
Phaser.Rectangle.inflate = function (a, dx, dy) {
a.x -= dx;
a.width += 2 * dx;
a.y -= dy;
a.height += 2 * dy;
return a;
};
/**
* Increases the size of the Rectangle object. This method is similar to the Rectangle.inflate() method except it takes a Point object as a parameter.
* @method Phaser.Rectangle.inflatePoint
* @param {Phaser.Rectangle} a - The Rectangle object.
* @param {Phaser.Point} point - The x property of this Point object is used to increase the horizontal dimension of the Rectangle object. The y property is used to increase the vertical dimension of the Rectangle object.
* @return {Phaser.Rectangle} The Rectangle object.
*/
Phaser.Rectangle.inflatePoint = function (a, point) {
return Phaser.Rectangle.inflate(a, point.x, point.y);
};
/**
* The size of the Rectangle object, expressed as a Point object with the values of the width and height properties.
* @method Phaser.Rectangle.size
* @param {Phaser.Rectangle} a - The Rectangle object.
* @param {Phaser.Point} [output] - Optional Point object. If given the values will be set into the object, otherwise a brand new Point object will be created and returned.
* @return {Phaser.Point} The size of the Rectangle object
*/
Phaser.Rectangle.size = function (a, output) {
if (typeof output === "undefined")
{
output = new Phaser.Point(a.width, a.height);
}
else
{
output.setTo(a.width, a.height);
}
return output;
};
/**
* Returns a new Rectangle object with the same values for the x, y, width, and height properties as the original Rectangle object.
* @method Phaser.Rectangle.clone
* @param {Phaser.Rectangle} a - The Rectangle object.
* @param {Phaser.Rectangle} [output] - Optional Rectangle object. If given the values will be set into the object, otherwise a brand new Rectangle object will be created and returned.
* @return {Phaser.Rectangle}
*/
Phaser.Rectangle.clone = function (a, output) {
if (typeof output === "undefined")
{
output = new Phaser.Rectangle(a.x, a.y, a.width, a.height);
}
else
{
output.setTo(a.x, a.y, a.width, a.height);
}
return output;
};
/**
* Determines whether the specified coordinates are contained within the region defined by this Rectangle object.
* @method Phaser.Rectangle.contains
* @param {Phaser.Rectangle} a - The Rectangle object.
* @param {number} x - The x coordinate of the point to test.
* @param {number} y - The y coordinate of the point to test.
* @return {boolean} A value of true if the Rectangle object contains the specified point; otherwise false.
*/
Phaser.Rectangle.contains = function (a, x, y) {
if (a.width <= 0 || a.height <= 0)
{
return false;
}
return (x >= a.x && x <= a.right && y >= a.y && y <= a.bottom);
};
/**
* Determines whether the specified coordinates are contained within the region defined by the given raw values.
* @method Phaser.Rectangle.containsRaw
* @param {number} rx - The x coordinate of the top left of the area.
* @param {number} ry - The y coordinate of the top left of the area.
* @param {number} rw - The width of the area.
* @param {number} rh - The height of the area.
* @param {number} x - The x coordinate of the point to test.
* @param {number} y - The y coordinate of the point to test.
* @return {boolean} A value of true if the Rectangle object contains the specified point; otherwise false.
*/
Phaser.Rectangle.containsRaw = function (rx, ry, rw, rh, x, y) {
return (x >= rx && x <= (rx + rw) && y >= ry && y <= (ry + rh));
};
/**
* Determines whether the specified point is contained within the rectangular region defined by this Rectangle object. This method is similar to the Rectangle.contains() method, except that it takes a Point object as a parameter.
* @method Phaser.Rectangle.containsPoint
* @param {Phaser.Rectangle} a - The Rectangle object.
* @param {Phaser.Point} point - The point object being checked. Can be Point or any object with .x and .y values.
* @return {boolean} A value of true if the Rectangle object contains the specified point; otherwise false.
*/
Phaser.Rectangle.containsPoint = function (a, point) {
return Phaser.Rectangle.contains(a, point.x, point.y);
};
/**
* Determines whether the first Rectangle object is fully contained within the second Rectangle object.
* A Rectangle object is said to contain another if the second Rectangle object falls entirely within the boundaries of the first.
* @method Phaser.Rectangle.containsRect
* @param {Phaser.Rectangle} a - The first Rectangle object.
* @param {Phaser.Rectangle} b - The second Rectangle object.
* @return {boolean} A value of true if the Rectangle object contains the specified point; otherwise false.
*/
Phaser.Rectangle.containsRect = function (a, b) {
// If the given rect has a larger volume than this one then it can never contain it
if (a.volume > b.volume)
{
return false;
}
return (a.x >= b.x && a.y >= b.y && a.right <= b.right && a.bottom <= b.bottom);
};
/**
* Determines whether the two Rectangles are equal.
* This method compares the x, y, width and height properties of each Rectangle.
* @method Phaser.Rectangle.equals
* @param {Phaser.Rectangle} a - The first Rectangle object.
* @param {Phaser.Rectangle} b - The second Rectangle object.
* @return {boolean} A value of true if the two Rectangles have exactly the same values for the x, y, width and height properties; otherwise false.
*/
Phaser.Rectangle.equals = function (a, b) {
return (a.x == b.x && a.y == b.y && a.width == b.width && a.height == b.height);
};
/**
* If the Rectangle object specified in the toIntersect parameter intersects with this Rectangle object, returns the area of intersection as a Rectangle object. If the Rectangles do not intersect, this method returns an empty Rectangle object with its properties set to 0.
* @method Phaser.Rectangle.intersection
* @param {Phaser.Rectangle} a - The first Rectangle object.
* @param {Phaser.Rectangle} b - The second Rectangle object.
* @param {Phaser.Rectangle} [output] - Optional Rectangle object. If given the intersection values will be set into this object, otherwise a brand new Rectangle object will be created and returned.
* @return {Phaser.Rectangle} A Rectangle object that equals the area of intersection. If the Rectangles do not intersect, this method returns an empty Rectangle object; that is, a Rectangle with its x, y, width, and height properties set to 0.
*/
Phaser.Rectangle.intersection = function (a, b, output) {
if (typeof output === "undefined")
{
output = new Phaser.Rectangle();
}
if (Phaser.Rectangle.intersects(a, b))
{
output.x = Math.max(a.x, b.x);
output.y = Math.max(a.y, b.y);
output.width = Math.min(a.right, b.right) - output.x;
output.height = Math.min(a.bottom, b.bottom) - output.y;
}
return output;
};
/**
* Determines whether the two Rectangles intersect with each other.
* This method checks the x, y, width, and height properties of the Rectangles.
* @method Phaser.Rectangle.intersects
* @param {Phaser.Rectangle} a - The first Rectangle object.
* @param {Phaser.Rectangle} b - The second Rectangle object.
* @return {boolean} A value of true if the specified object intersects with this Rectangle object; otherwise false.
*/
Phaser.Rectangle.intersects = function (a, b) {
if (a.width <= 0 || a.height <= 0 || b.width <= 0 || b.height <= 0)
{
return false;
}
return !(a.right < b.x || a.bottom < b.y || a.x > b.right || a.y > b.bottom);
};
/**
* Determines whether the object specified intersects (overlaps) with the given values.
* @method Phaser.Rectangle.intersectsRaw
* @param {number} left - Description.
* @param {number} right - Description.
* @param {number} top - Description.
* @param {number} bottom - Description.
* @param {number} tolerance - A tolerance value to allow for an intersection test with padding, default to 0
* @return {boolean} A value of true if the specified object intersects with the Rectangle; otherwise false.
*/
Phaser.Rectangle.intersectsRaw = function (a, left, right, top, bottom, tolerance) {
if (typeof tolerance === "undefined") { tolerance = 0; }
return !(left > a.right + tolerance || right < a.left - tolerance || top > a.bottom + tolerance || bottom < a.top - tolerance);
};
/**
* Adds two Rectangles together to create a new Rectangle object, by filling in the horizontal and vertical space between the two Rectangles.
* @method Phaser.Rectangle.union
* @param {Phaser.Rectangle} a - The first Rectangle object.
* @param {Phaser.Rectangle} b - The second Rectangle object.
* @param {Phaser.Rectangle} [output] - Optional Rectangle object. If given the new values will be set into this object, otherwise a brand new Rectangle object will be created and returned.
* @return {Phaser.Rectangle} A Rectangle object that is the union of the two Rectangles.
*/
Phaser.Rectangle.union = function (a, b, output) {
if (typeof output === "undefined")
{
output = new Phaser.Rectangle();
}
return output.setTo(Math.min(a.x, b.x), Math.min(a.y, b.y), Math.max(a.right, b.right) - Math.min(a.left, b.left), Math.max(a.bottom, b.bottom) - Math.min(a.top, b.top));
};
// Because PIXI uses its own Rectangle, we'll replace it with ours to avoid duplicating code or confusion.
PIXI.Rectangle = Phaser.Rectangle;
PIXI.EmptyRectangle = new Phaser.Rectangle(0, 0, 0, 0);
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2014 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* Creates a new Line object with a start and an end point.
* @class Line
* @classdesc Phaser - Line
* @constructor
* @param {number} [x1=0] - The x coordinate of the start of the line.
* @param {number} [y1=0] - The y coordinate of the start of the line.
* @param {number} [x2=0] - The x coordinate of the end of the line.
* @param {number} [y2=0] - The y coordinate of the end of the line.
* @return {Phaser.Line} This line object
*/
Phaser.Line = function (x1, y1, x2, y2) {
x1 = x1 || 0;
y1 = y1 || 0;
x2 = x2 || 0;
y2 = y2 || 0;
/**
* @property {Phaser.Point} start - The start point of the line.
*/
this.start = new Phaser.Point(x1, y1);
/**
* @property {Phaser.Point} end - The end point of the line.
*/
this.end = new Phaser.Point(x2, y2);
};
Phaser.Line.prototype = {
/**
* Sets the components of the Line to the specified values.
* @method Phaser.Line#setTo
* @param {number} [x1=0] - The x coordinate of the start of the line.
* @param {number} [y1=0] - The y coordinate of the start of the line.
* @param {number} [x2=0] - The x coordinate of the end of the line.
* @param {number} [y2=0] - The y coordinate of the end of the line.
* @return {Phaser.Line} This line object
*/
setTo: function (x1, y1, x2, y2) {
this.start.setTo(x1, y1);
this.end.setTo(x2, y2);
return this;
},
/**
* Sets the line to match the x/y coordinates of the two given sprites.
* Can optionally be calculated from their center coordinates.
* @method Phaser.Line#fromSprite
* @param {Phaser.Sprite} startSprite - The coordinates of this Sprite will be set to the Line.start point.
* @param {Phaser.Sprite} endSprite - The coordinates of this Sprite will be set to the Line.start point.
* @param {boolean} [useCenter=true] - If true it will use startSprite.center.x, if false startSprite.x.
* @return {Phaser.Line} This line object
*/
fromSprite: function (startSprite, endSprite, useCenter) {
if (typeof useCenter === 'undefined') { useCenter = true; }
if (useCenter)
{
return this.setTo(startSprite.center.x, startSprite.center.y, endSprite.center.x, endSprite.center.y);
}
else
{
return this.setTo(startSprite.x, startSprite.y, endSprite.x, endSprite.y);
}
},
/**
* Checks for intersection between this line and another Line.
* If asSegment is true it will check for segment intersection. If asSegment is false it will check for line intersection.
* Returns the intersection segment of AB and EF as a Point, or null if there is no intersection.
*
* @method Phaser.Line#intersects
* @param {Phaser.Line} line - The line to check against this one.
* @param {boolean} [asSegment=true] - If true it will check for segment intersection, otherwise full line intersection.
* @param {Phaser.Point} [result] - A Point object to store the result in, if not given a new one will be created.
* @return {Phaser.Point} The intersection segment of the two lines as a Point, or null if there is no intersection.
*/
intersects: function (line, asSegment, result) {
return Phaser.Line.intersectsPoints(this.start, this.end, line.start, line.end, asSegment, result);
},
/**
* Tests if the given coordinates fall on this line. See pointOnSegment to test against just the line segment.
* @method Phaser.Line#pointOnLine
* @param {number} x - The line to check against this one.
* @param {number} y - The line to check against this one.
* @return {boolean} True if the point is on the line, false if not.
*/
pointOnLine: function (x, y) {
return ((x - this.start.x) * (this.end.y - this.end.y) === (this.end.x - this.start.x) * (y - this.end.y));
},
/**
* Tests if the given coordinates fall on this line and within the segment. See pointOnLine to test against just the line.
* @method Phaser.Line#pointOnSegment
* @param {number} x - The line to check against this one.
* @param {number} y - The line to check against this one.
* @return {boolean} True if the point is on the line and segment, false if not.
*/
pointOnSegment: function (x, y) {
var xMin = Math.min(this.start.x, this.end.x);
var xMax = Math.max(this.start.x, this.end.x);
var yMin = Math.min(this.start.y, this.end.y);
var yMax = Math.max(this.start.y, this.end.y);
return (this.pointOnLine(x, y) && (x >= xMin && x <= xMax) && (y >= yMin && y <= yMax));
}
};
/**
* @name Phaser.Line#length
* @property {number} length - Gets the length of the line segment.
* @readonly
*/
Object.defineProperty(Phaser.Line.prototype, "length", {
get: function () {
return Math.sqrt((this.end.x - this.start.x) * (this.end.x - this.start.x) + (this.end.y - this.start.y) * (this.end.y - this.start.y));
}
});
/**
* @name Phaser.Line#angle
* @property {number} angle - Gets the angle of the line.
* @readonly
*/
Object.defineProperty(Phaser.Line.prototype, "angle", {
get: function () {
return Math.atan2(this.end.x - this.start.x, this.end.y - this.start.y);
}
});
/**
* @name Phaser.Line#slope
* @property {number} slope - Gets the slope of the line (y/x).
* @readonly
*/
Object.defineProperty(Phaser.Line.prototype, "slope", {
get: function () {
return (this.end.y - this.start.y) / (this.end.x - this.start.x);
}
});
/**
* @name Phaser.Line#perpSlope
* @property {number} perpSlope - Gets the perpendicular slope of the line (x/y).
* @readonly
*/
Object.defineProperty(Phaser.Line.prototype, "perpSlope", {
get: function () {
return -((this.end.x - this.start.x) / (this.end.y - this.start.y));
}
});
/**
* Checks for intersection between two lines as defined by the given start and end points.
* If asSegment is true it will check for line segment intersection. If asSegment is false it will check for line intersection.
* Returns the intersection segment of AB and EF as a Point, or null if there is no intersection.
* Adapted from code by Keith Hair
*
* @method Phaser.Line.intersectsPoints
* @param {Phaser.Point} a - The start of the first Line to be checked.
* @param {Phaser.Point} b - The end of the first line to be checked.
* @param {Phaser.Point} e - The start of the second Line to be checked.
* @param {Phaser.Point} f - The end of the second line to be checked.
* @param {boolean} [asSegment=true] - If true it will check for segment intersection, otherwise full line intersection.
* @param {Phaser.Point} [result] - A Point object to store the result in, if not given a new one will be created.
* @return {Phaser.Point} The intersection segment of the two lines as a Point, or null if there is no intersection.
*/
Phaser.Line.intersectsPoints = function (a, b, e, f, asSegment, result) {
if (typeof asSegment === 'undefined') { asSegment = true; }
if (typeof result === 'undefined') { result = new Phaser.Point(); }
var a1 = b.y - a.y;
var a2 = f.y - e.y;
var b1 = a.x - b.x;
var b2 = e.x - f.x;
var c1 = (b.x * a.y) - (a.x * b.y);
var c2 = (f.x * e.y) - (e.x * f.y);
var denom = (a1 * b2) - (a2 * b1);
if (denom === 0)
{
return null;
}
result.x = ((b1 * c2) - (b2 * c1)) / denom;
result.y = ((a2 * c1) - (a1 * c2)) / denom;
if (asSegment)
{
if (Math.pow((result.x - b.x) + (result.y - b.y), 2) > Math.pow((a.x - b.x) + (a.y - b.y), 2))
{
return null;
}
if (Math.pow((result.x - a.x) + (result.y - a.y), 2) > Math.pow((a.x - b.x) + (a.y - b.y), 2))
{
return null;
}
if (Math.pow((result.x - f.x) + (result.y - f.y), 2) > Math.pow((e.x - f.x) + (e.y - f.y), 2))
{
return null;
}
if (Math.pow((result.x - e.x) + (result.y - e.y), 2) > Math.pow((e.x - f.x) + (e.y - f.y), 2))
{
return null;
}
}
return result;
};
/**
* Checks for intersection between two lines.
* If asSegment is true it will check for segment intersection.
* If asSegment is false it will check for line intersection.
* Returns the intersection segment of AB and EF as a Point, or null if there is no intersection.
* Adapted from code by Keith Hair
*
* @method Phaser.Line.intersects
* @param {Phaser.Line} a - The first Line to be checked.
* @param {Phaser.Line} b - The second Line to be checked.
* @param {boolean} [asSegment=true] - If true it will check for segment intersection, otherwise full line intersection.
* @param {Phaser.Point} [result] - A Point object to store the result in, if not given a new one will be created.
* @return {Phaser.Point} The intersection segment of the two lines as a Point, or null if there is no intersection.
*/
Phaser.Line.intersects = function (a, b, asSegment, result) {
return Phaser.Line.intersectsPoints(a.start, a.end, b.start, b.end, asSegment, result);
};
/**
* @author Richard Davey <rich@photonstorm.com>
* @author Chad Engler <chad@pantherdev.com>
* @copyright 2014 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* Creates a Ellipse object. A curve on a plane surrounding two focal points.
* @class Ellipse
* @classdesc Phaser - Ellipse
* @constructor
* @param {number} [x=0] - The X coordinate of the upper-left corner of the framing rectangle of this ellipse.
* @param {number} [y=0] - The Y coordinate of the upper-left corner of the framing rectangle of this ellipse.
* @param {number} [width=0] - The overall width of this ellipse.
* @param {number} [height=0] - The overall height of this ellipse.
* @return {Phaser.Ellipse} This Ellipse object
*/
Phaser.Ellipse = function (x, y, width, height) {
this.type = Phaser.ELLIPSE;
x = x || 0;
y = y || 0;
width = width || 0;
height = height || 0;
/**
* @property {number} x - The X coordinate of the upper-left corner of the framing rectangle of this ellipse.
*/
this.x = x;
/**
* @property {number} y - The Y coordinate of the upper-left corner of the framing rectangle of this ellipse.
*/
this.y = y;
/**
* @property {number} width - The overall width of this ellipse.
*/
this.width = width;
/**
* @property {number} height - The overall height of this ellipse.
*/
this.height = height;
};
Phaser.Ellipse.prototype = {
/**
* Sets the members of the Ellipse to the specified values.
* @method Phaser.Ellipse#setTo
* @param {number} x - The X coordinate of the upper-left corner of the framing rectangle of this ellipse.
* @param {number} y - The Y coordinate of the upper-left corner of the framing rectangle of this ellipse.
* @param {number} width - The overall width of this ellipse.
* @param {number} height - The overall height of this ellipse.
* @return {Phaser.Ellipse} This Ellipse object.
*/
setTo: function (x, y, width, height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
return this;
},
/**
* Copies the x, y, width and height properties from any given object to this Ellipse.
* @method Phaser.Ellipse#copyFrom
* @param {any} source - The object to copy from.
* @return {Phaser.Ellipse} This Ellipse object.
*/
copyFrom: function (source) {
return this.setTo(source.x, source.y, source.width, source.height);
},
/**
* Copies the x, y and diameter properties from this Circle to any given object.
* @method Phaser.Ellipse#copyTo
* @param {any} dest - The object to copy to.
* @return {Object} This dest object.
*/
copyTo: function(dest) {
dest.x = this.x;
dest.y = this.y;
dest.width = this.width;
dest.height = this.height;
return dest;
},
/**
* Returns a new Ellipse object with the same values for the x, y, width, and height properties as this Ellipse object.
* @method Phaser.Ellipse#clone
* @param {Phaser.Ellipse} out - Optional Ellipse object. If given the values will be set into the object, otherwise a brand new Ellipse object will be created and returned.
* @return {Phaser.Ellipse} The cloned Ellipse object.
*/
clone: function(out) {
if (typeof out === "undefined")
{
out = new Phaser.Ellipse(this.x, this.y, this.width, this.height);
}
else
{
out.setTo(this.x, this.y, this.width, this.height);
}
return out;
},
/**
* Return true if the given x/y coordinates are within this Ellipse object.
* @method Phaser.Ellipse#contains
* @param {number} x - The X value of the coordinate to test.
* @param {number} y - The Y value of the coordinate to test.
* @return {boolean} True if the coordinates are within this ellipse, otherwise false.
*/
contains: function (x, y) {
return Phaser.Ellipse.contains(this, x, y);
},
/**
* Returns a string representation of this object.
* @method Phaser.Ellipse#toString
* @return {string} A string representation of the instance.
*/
toString: function () {
return "[{Phaser.Ellipse (x=" + this.x + " y=" + this.y + " width=" + this.width + " height=" + this.height + ")}]";
}
};
Phaser.Ellipse.prototype.constructor = Phaser.Ellipse;
/**
* The left coordinate of the Ellipse. The same as the X coordinate.
* @name Phaser.Ellipse#left
* @propety {number} left - Gets or sets the value of the leftmost point of the ellipse.
*/
Object.defineProperty(Phaser.Ellipse.prototype, "left", {
get: function () {
return this.x;
},
set: function (value) {
this.x = value;
}
});
/**
* The x coordinate of the rightmost point of the Ellipse. Changing the right property of an Ellipse object has no effect on the x property, but does adjust the width.
* @name Phaser.Ellipse#right
* @property {number} right - Gets or sets the value of the rightmost point of the ellipse.
*/
Object.defineProperty(Phaser.Ellipse.prototype, "right", {
get: function () {
return this.x + this.width;
},
set: function (value) {
if (value < this.x)
{
this.width = 0;
}
else
{
this.width = this.x + width;
}
}
});
/**
* The top of the Ellipse. The same as its y property.
* @name Phaser.Ellipse#top
* @property {number} top - Gets or sets the top of the ellipse.
*/
Object.defineProperty(Phaser.Ellipse.prototype, "top", {
get: function () {
return this.y;
},
set: function (value) {
this.y = value;
}
});
/**
* The sum of the y and height properties. Changing the bottom property of an Ellipse doesn't adjust the y property, but does change the height.
* @name Phaser.Ellipse#bottom
* @property {number} bottom - Gets or sets the bottom of the ellipse.
*/
Object.defineProperty(Phaser.Ellipse.prototype, "bottom", {
get: function () {
return this.y + this.height;
},
set: function (value) {
if (value < this.y)
{
this.height = 0;
}
else
{
this.height = this.y + value;
}
}
});
/**
* Determines whether or not this Ellipse object is empty. Will return a value of true if the Ellipse objects dimensions are less than or equal to 0; otherwise false.
* If set to true it will reset all of the Ellipse objects properties to 0. An Ellipse object is empty if its width or height is less than or equal to 0.
* @name Phaser.Ellipse#empty
* @property {boolean} empty - Gets or sets the empty state of the ellipse.
*/
Object.defineProperty(Phaser.Ellipse.prototype, "empty", {
get: function () {
return (this.width === 0 || this.height === 0);
},
set: function (value) {
if (value === true)
{
this.setTo(0, 0, 0, 0);
}
}
});
/**
* Return true if the given x/y coordinates are within the Ellipse object.
* @method Phaser.Ellipse.contains
* @param {Phaser.Ellipse} a - The Ellipse to be checked.
* @param {number} x - The X value of the coordinate to test.
* @param {number} y - The Y value of the coordinate to test.
* @return {boolean} True if the coordinates are within this ellipse, otherwise false.
*/
Phaser.Ellipse.contains = function (a, x, y) {
if (a.width <= 0 || a.height <= 0)
{
return false;
}
// Normalize the coords to an ellipse with center 0,0 and a radius of 0.5
var normx = ((x - a.x) / a.width) - 0.5;
var normy = ((y - a.y) / a.height) - 0.5;
normx *= normx;
normy *= normy;
return (normx + normy < 0.25);
};
/**
* Returns the framing rectangle of the ellipse as a Phaser.Rectangle object.
*
* @method getBounds
* @return {Phaser.Rectangle} The framing rectangle
*/
Phaser.Ellipse.prototype.getBounds = function() {
return new Phaser.Rectangle(this.x, this.y, this.width, this.height);
};
// Because PIXI uses its own Ellipse, we'll replace it with ours to avoid duplicating code or confusion.
PIXI.Ellipse = Phaser.Ellipse;
/**
* @author Richard Davey <rich@photonstorm.com>
* @author Adrien Brault <adrien.brault@gmail.com>
* @copyright 2014 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* Creates a new Polygon. You have to provide a list of points.
* This can be an array of Points that form the polygon, a flat array of numbers that will be interpreted as [x,y, x,y, ...],
* or the arguments passed can be all the points of the polygon e.g. `new Phaser.Polygon(new Phaser.Point(), new Phaser.Point(), ...)`, or the
* arguments passed can be flat x,y values e.g. `new Phaser.Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are numbers.
*
* @class Phaser.Polygon
* @classdesc The polygon represents a list of orderded points in space
* @constructor
* @param {Array<Phaser.Point>|Array<number>} points - The array of Points.
*/
Phaser.Polygon = function (points) {
/**
* @property {number} type - The base object type.
*/
this.type = Phaser.POLYGON;
//if points isn't an array, use arguments as the array
if (!(points instanceof Array))
{
points = Array.prototype.slice.call(arguments);
}
//if this is a flat array of numbers, convert it to points
if (typeof points[0] === 'number')
{
var p = [];
for (var i = 0, len = points.length; i < len; i += 2)
{
p.push(new Phaser.Point(points[i], points[i + 1]));
}
points = p;
}
/**
* @property {array<Phaser.Point>|array<number>} points - The array of Points.
*/
this.points = points;
};
Phaser.Polygon.prototype = {
/**
* Creates a clone of this polygon.
*
* @method Phaser.Polygon#clone
* @return {Phaser.Polygon} A copy of the polygon.
*/
clone: function () {
var points = [];
for (var i=0; i < this.points.length; i++)
{
points.push(this.points[i].clone());
}
return new Phaser.Polygon(points);
},
/**
* Checks whether the x and y coordinates are contained within this polygon.
*
* @method Phaser.Polygon#contains
* @param {number} x - The X value of the coordinate to test.
* @param {number} y - The Y value of the coordinate to test.
* @return {boolean} True if the coordinates are within this polygon, otherwise false.
*/
contains: function (x, y) {
var inside = false;
// use some raycasting to test hits https://github.com/substack/point-in-polygon/blob/master/index.js
for (var i = 0, j = this.points.length - 1; i < this.points.length; j = i++)
{
var xi = this.points[i].x;
var yi = this.points[i].y;
var xj = this.points[j].x;
var yj = this.points[j].y;
var intersect = ((yi > y) !== (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi);
if (intersect)
{
inside = true;
}
}
return inside;
}
};
Phaser.Polygon.prototype.constructor = Phaser.Polygon;
// Because PIXI uses its own Polygon, we'll replace it with ours to avoid duplicating code or confusion.
PIXI.Polygon = Phaser.Polygon;
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2014 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* A Camera is your view into the game world. It has a position and size and renders only those objects within its field of view.
* The game automatically creates a single Stage sized camera on boot. Move the camera around the world with Phaser.Camera.x/y
*
* @class Phaser.Camera
* @constructor
* @param {Phaser.Game} game - Game reference to the currently running game.
* @param {number} id - Not being used at the moment, will be when Phaser supports multiple camera
* @param {number} x - Position of the camera on the X axis
* @param {number} y - Position of the camera on the Y axis
* @param {number} width - The width of the view rectangle
* @param {number} height - The height of the view rectangle
*/
Phaser.Camera = function (game, id, x, y, width, height) {
/**
* @property {Phaser.Game} game - A reference to the currently running Game.
*/
this.game = game;
/**
* @property {Phaser.World} world - A reference to the game world.
*/
this.world = game.world;
/**
* @property {number} id - Reserved for future multiple camera set-ups.
* @default
*/
this.id = 0;
/**
* Camera view.
* The view into the world we wish to render (by default the game dimensions).
* The x/y values are in world coordinates, not screen coordinates, the width/height is how many pixels to render.
* Objects outside of this view are not rendered if set to camera cull.
* @property {Phaser.Rectangle} view
*/
this.view = new Phaser.Rectangle(x, y, width, height);
/**
* @property {Phaser.Rectangle} screenView - Used by Sprites to work out Camera culling.
*/
this.screenView = new Phaser.Rectangle(x, y, width, height);
/**
* The Camera is bound to this Rectangle and cannot move outside of it. By default it is enabled and set to the size of the World.
* The Rectangle can be located anywhere in the world and updated as often as you like. If you don't wish the Camera to be bound
* at all then set this to null. The values can be anything and are in World coordinates, with 0,0 being the center of the world.
* @property {Phaser.Rectangle} bounds - The Rectangle in which the Camera is bounded. Set to null to allow for movement anywhere.
*/
this.bounds = new Phaser.Rectangle(x, y, width, height);
/**
* @property {Phaser.Rectangle} deadzone - Moving inside this Rectangle will not cause camera moving.
*/
this.deadzone = null;
/**
* @property {boolean} visible - Whether this camera is visible or not.
* @default
*/
this.visible = true;
/**
* @property {boolean} atLimit - Whether this camera is flush with the World Bounds or not.
*/
this.atLimit = { x: false, y: false };
/**
* @property {Phaser.Sprite} target - If the camera is tracking a Sprite, this is a reference to it, otherwise null.
* @default
*/
this.target = null;
/**
* @property {number} edge - Edge property.
* @private
* @default
*/
this._edge = 0;
/**
* @property {PIXI.DisplayObject} displayObject - The display object to which all game objects are added. Set by World.boot
*/
this.displayObject = null;
/**
* @property {Phaser.Point} scale - The scale of the display object to which all game objects are added. Set by World.boot
*/
this.scale = null;
};
/**
* @constant
* @type {number}
*/
Phaser.Camera.FOLLOW_LOCKON = 0;
/**
* @constant
* @type {number}
*/
Phaser.Camera.FOLLOW_PLATFORMER = 1;
/**
* @constant
* @type {number}
*/
Phaser.Camera.FOLLOW_TOPDOWN = 2;
/**
* @constant
* @type {number}
*/
Phaser.Camera.FOLLOW_TOPDOWN_TIGHT = 3;
Phaser.Camera.prototype = {
/**
* Tells this camera which sprite to follow.
* @method Phaser.Camera#follow
* @param {Phaser.Sprite|Phaser.Image|Phaser.Text} target - The object you want the camera to track. Set to null to not follow anything.
* @param {number} [style] - Leverage one of the existing "deadzone" presets. If you use a custom deadzone, ignore this parameter and manually specify the deadzone after calling follow().
*/
follow: function (target, style) {
if (typeof style === "undefined") { style = Phaser.Camera.FOLLOW_LOCKON; }
this.target = target;
var helper;
switch (style) {
case Phaser.Camera.FOLLOW_PLATFORMER:
var w = this.width / 8;
var h = this.height / 3;
this.deadzone = new Phaser.Rectangle((this.width - w) / 2, (this.height - h) / 2 - h * 0.25, w, h);
break;
case Phaser.Camera.FOLLOW_TOPDOWN:
helper = Math.max(this.width, this.height) / 4;
this.deadzone = new Phaser.Rectangle((this.width - helper) / 2, (this.height - helper) / 2, helper, helper);
break;
case Phaser.Camera.FOLLOW_TOPDOWN_TIGHT:
helper = Math.max(this.width, this.height) / 8;
this.deadzone = new Phaser.Rectangle((this.width - helper) / 2, (this.height - helper) / 2, helper, helper);
break;
case Phaser.Camera.FOLLOW_LOCKON:
this.deadzone = null;
break;
default:
this.deadzone = null;
break;
}
},
/**
* Move the camera focus on a display object instantly.
* @method Phaser.Camera#focusOn
* @param {any} displayObject - The display object to focus the camera on. Must have visible x/y properties.
*/
focusOn: function (displayObject) {
this.setPosition(Math.round(displayObject.x - this.view.halfWidth), Math.round(displayObject.y - this.view.halfHeight));
},
/**
* Move the camera focus on a location instantly.
* @method Phaser.Camera#focusOnXY
* @param {number} x - X position.
* @param {number} y - Y position.
*/
focusOnXY: function (x, y) {
this.setPosition(Math.round(x - this.view.halfWidth), Math.round(y - this.view.halfHeight));
},
/**
* Update focusing and scrolling.
* @method Phaser.Camera#update
*/
update: function () {
if (this.target)
{
this.updateTarget();
}
if (this.bounds)
{
this.checkBounds();
}
this.displayObject.position.x = -this.view.x;
this.displayObject.position.y = -this.view.y;
},
/**
* Internal method
* @method Phaser.Camera#updateTarget
* @private
*/
updateTarget: function () {
if (this.deadzone)
{
this._edge = this.target.x - this.deadzone.x;
if (this.view.x > this._edge)
{
this.view.x = this._edge;
}
this._edge = this.target.x + this.target.width - this.deadzone.x - this.deadzone.width;
if (this.view.x < this._edge)
{
this.view.x = this._edge;
}
this._edge = this.target.y - this.deadzone.y;
if (this.view.y > this._edge)
{
this.view.y = this._edge;
}
this._edge = this.target.y + this.target.height - this.deadzone.y - this.deadzone.height;
if (this.view.y < this._edge)
{
this.view.y = this._edge;
}
}
else
{
this.focusOnXY(this.target.x, this.target.y);
}
},
/**
* Update the Camera bounds to match the game world.
* @method Phaser.Camera#setBoundsToWorld
*/
setBoundsToWorld: function () {
this.bounds.setTo(this.game.world.bounds.x, this.game.world.bounds.y, this.game.world.bounds.width, this.game.world.bounds.height);
},
/**
* Method called to ensure the camera doesn't venture outside of the game world.
* @method Phaser.Camera#checkWorldBounds
*/
checkBounds: function () {
this.atLimit.x = false;
this.atLimit.y = false;
// Make sure we didn't go outside the cameras bounds
if (this.view.x < this.bounds.x)
{
this.atLimit.x = true;
this.view.x = this.bounds.x;
}
if (this.view.right > this.bounds.right)
{
this.atLimit.x = true;
this.view.x = this.bounds.right - this.width;
}
if (this.view.y < this.bounds.top)
{
this.atLimit.y = true;
this.view.y = this.bounds.top;
}
if (this.view.bottom > this.bounds.bottom)
{
this.atLimit.y = true;
this.view.y = this.bounds.bottom - this.height;
}
this.view.floor();
},
/**
* A helper function to set both the X and Y properties of the camera at once
* without having to use game.camera.x and game.camera.y.
*
* @method Phaser.Camera#setPosition
* @param {number} x - X position.
* @param {number} y - Y position.
*/
setPosition: function (x, y) {
this.view.x = x;
this.view.y = y;
if (this.bounds)
{
this.checkBounds();
}
},
/**
* Sets the size of the view rectangle given the width and height in parameters.
*
* @method Phaser.Camera#setSize
* @param {number} width - The desired width.
* @param {number} height - The desired height.
*/
setSize: function (width, height) {
this.view.width = width;
this.view.height = height;
},
/**
* Resets the camera back to 0,0 and un-follows any object it may have been tracking.
*
* @method Phaser.Camera#reset
*/
reset: function () {
this.target = null;
this.view.x = 0;
this.view.y = 0;
}
};
Phaser.Camera.prototype.constructor = Phaser.Camera;
/**
* The Cameras x coordinate. This value is automatically clamped if it falls outside of the World bounds.
* @name Phaser.Camera#x
* @property {number} x - Gets or sets the cameras x position.
*/
Object.defineProperty(Phaser.Camera.prototype, "x", {
get: function () {
return this.view.x;
},
set: function (value) {
this.view.x = value;
if (this.bounds)
{
this.checkBounds();
}
}
});
/**
* The Cameras y coordinate. This value is automatically clamped if it falls outside of the World bounds.
* @name Phaser.Camera#y
* @property {number} y - Gets or sets the cameras y position.
*/
Object.defineProperty(Phaser.Camera.prototype, "y", {
get: function () {
return this.view.y;
},
set: function (value) {
this.view.y = value;
if (this.bounds)
{
this.checkBounds();
}
}
});
/**
* The Cameras width. By default this is the same as the Game size and should not be adjusted for now.
* @name Phaser.Camera#width
* @property {number} width - Gets or sets the cameras width.
*/
Object.defineProperty(Phaser.Camera.prototype, "width", {
get: function () {
return this.view.width;
},
set: function (value) {
this.view.width = value;
}
});
/**
* The Cameras height. By default this is the same as the Game size and should not be adjusted for now.
* @name Phaser.Camera#height
* @property {number} height - Gets or sets the cameras height.
*/
Object.defineProperty(Phaser.Camera.prototype, "height", {
get: function () {
return this.view.height;
},
set: function (value) {
this.view.height = value;
}
});
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2014 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* This is a base State class which can be extended if you are creating your own game.
* It provides quick access to common functions such as the camera, cache, input, match, sound and more.
*
* @class Phaser.State
* @constructor
*/
Phaser.State = function () {
/**
* @property {Phaser.Game} game - A reference to the currently running Game.
*/
this.game = null;
/**
* @property {Phaser.GameObjectFactory} add - Reference to the GameObjectFactory.
*/
this.add = null;
/**
* @property {Phaser.GameObjectCreator} make - Reference to the GameObjectCreator.
*/
this.make = null;
/**
* @property {Phaser.Camera} camera - A handy reference to world.camera.
*/
this.camera = null;
/**
* @property {Phaser.Cache} cache - Reference to the assets cache.
*/
this.cache = null;
/**
* @property {Phaser.Input} input - Reference to the input manager
*/
this.input = null;
/**
* @property {Phaser.Loader} load - Reference to the assets loader.
*/
this.load = null;
/**
* @property {Phaser.Math} math - Reference to the math helper.
*/
this.math = null;
/**
* @property {Phaser.SoundManager} sound - Reference to the sound manager.
*/
this.sound = null;
/**
* @property {Phaser.ScaleManager} scale - Reference to the game scale manager.
*/
this.scale = null;
/**
* @property {Phaser.Stage} stage - Reference to the stage.
*/
this.stage = null;
/**
* @property {Phaser.TimeManager} time - Reference to game clock.
*/
this.time = null;
/**
* @property {Phaser.TweenManager} tweens - Reference to the tween manager.
*/
this.tweens = null;
/**
* @property {Phaser.World} world - Reference to the world.
*/
this.world = null;
/**
* @property {Phaser.Particles} particles - The Particle Manager for the game. It is called during the game update loop and in turn updates any Emitters attached to it.
*/
this.particles = null;
/**
* @property {Phaser.Physics.World} physics - Reference to the physics manager.
*/
this.physics = null;
/**
* @property {Phaser.RandomDataGenerator} rnd - Reference to the random data generator.
*/
this.rnd = null;
};
Phaser.State.prototype = {
/**
* Override this method to add some load operations.
* If you need to use the loader, you may need to use them here.
*
* @method Phaser.State#preload
*/
preload: function () {
},
/**
* Put update logic here.
*
* @method Phaser.State#loadUpdate
*/
loadUpdate: function () {
},
/**
* Put render operations here.
*
* @method Phaser.State#loadRender
*/
loadRender: function () {
},
/**
* This method is called after the game engine successfully switches states.
* Feel free to add any setup code here (do not load anything here, override preload() instead).
*
* @method Phaser.State#create
*/
create: function () {
},
/**
* Put update logic here.
*
* @method Phaser.State#update
*/
update: function () {
},
/**
* Put render operations here.
*
* @method Phaser.State#render
*/
render: function () {
},
/**
* This method will be called when game paused.
*
* @method Phaser.State#paused
*/
paused: function () {
},
/**
* This method will be called when the state is destroyed.
* @method Phaser.State#destroy
*/
destroy: function () {
}
};
Phaser.State.prototype.constructor = Phaser.State;
/* jshint newcap: false */
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2014 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* The State Manager is responsible for loading, setting up and switching game states.
*
* @class Phaser.StateManager
* @constructor
* @param {Phaser.Game} game - A reference to the currently running game.
* @param {Phaser.State|Object} [pendingState=null] - A State object to seed the manager with.
*/
Phaser.StateManager = function (game, pendingState) {
/**
* @property {Phaser.Game} game - A reference to the currently running game.
*/
this.game = game;
/**
* @property {Object} states - The object containing Phaser.States.
*/
this.states = {};
/**
* @property {Phaser.State} _pendingState - The state to be switched to in the next frame.
* @private
*/
this._pendingState = null;
if (typeof pendingState !== 'undefined' && pendingState !== null)
{
this._pendingState = pendingState;
}
/**
* @property {boolean} _clearWorld - Clear the world when we switch state?
* @private
*/
this._clearWorld = false;
/**
* @property {boolean} _clearCache - Clear the cache when we switch state?
* @private
*/
this._clearCache = false;
/**
* @property {boolean} _created - Flag that sets if the State has been created or not.
* @private
*/
this._created = false;
/**
* @property {array} _args - Temporary container when you pass vars from one State to another.
* @private
*/
this._args = [];
/**
* @property {string} current - The current active State object (defaults to null).
*/
this.current = '';
/**
* @property {function} onInitCallback - This will be called when the state is started (i.e. set as the current active state).
*/
this.onInitCallback = null;
/**
* @property {function} onPreloadCallback - This will be called when init states (loading assets...).
*/
this.onPreloadCallback = null;
/**
* @property {function} onCreateCallback - This will be called when create states (setup states...).
*/
this.onCreateCallback = null;
/**
* @property {function} onUpdateCallback - This will be called when State is updated, this doesn't happen during load (@see onLoadUpdateCallback).
*/
this.onUpdateCallback = null;
/**
* @property {function} onRenderCallback - This will be called when the State is rendered, this doesn't happen during load (see onLoadRenderCallback).
*/
this.onRenderCallback = null;
/**
* @property {function} onPreRenderCallback - This will be called before the State is rendered and before the stage is cleared.
*/
this.onPreRenderCallback = null;
/**
* @property {function} onLoadUpdateCallback - This will be called when the State is updated but only during the load process.
*/
this.onLoadUpdateCallback = null;
/**
* @property {function} onLoadRenderCallback - This will be called when the State is rendered but only during the load process.
*/
this.onLoadRenderCallback = null;
/**
* @property {function} onPausedCallback - This will be called when the state is paused.
*/
this.onPausedCallback = null;
/**
* @property {function} onResumedCallback - This will be called when the state is resumed from a paused state.
*/
this.onResumedCallback = null;
/**
* @property {function} onShutDownCallback - This will be called when the state is shut down (i.e. swapped to another state).
*/
this.onShutDownCallback = null;
};
Phaser.StateManager.prototype = {
/**
* The Boot handler is called by Phaser.Game when it first starts up.
* @method Phaser.StateManager#boot
* @private
*/
boot: function () {
this.game.onPause.add(this.pause, this);
this.game.onResume.add(this.resume, this);
this.game.load.onLoadComplete.add(this.loadComplete, this);
if (this._pendingState !== null)
{
if (typeof this._pendingState === 'string')
{
// State was already added, so just start it
// this.start(this._pendingState, false, false);
}
else
{
this.add('default', this._pendingState, true);
}
}
},
/**
* Adds a new State into the StateManager. You must give each State a unique key by which you'll identify it.
* The State can be either a Phaser.State object (or an object that extends it), a plain JavaScript object or a function.
* If a function is given a new state object will be created by calling it.
*
* @method Phaser.StateManager#add
* @param {string} key - A unique key you use to reference this state, i.e. "MainMenu", "Level1".
* @param {Phaser.State|object|function} state - The state you want to switch to.
* @param {boolean} [autoStart=false] - If true the State will be started immediately after adding it.
*/
add: function (key, state, autoStart) {
if (typeof autoStart === "undefined") { autoStart = false; }
var newState;
if (state instanceof Phaser.State)
{
newState = state;
}
else if (typeof state === 'object')
{
newState = state;
newState.game = this.game;
}
else if (typeof state === 'function')
{
newState = new state(this.game);
}
this.states[key] = newState;
if (autoStart)
{
if (this.game.isBooted)
{
this.start(key);
}
else
{
this._pendingState = key;
}
}
return newState;
},
/**
* Delete the given state.
* @method Phaser.StateManager#remove
* @param {string} key - A unique key you use to reference this state, i.e. "MainMenu", "Level1".
*/
remove: function (key) {
if (this.current == key)
{
this.callbackContext = null;
this.onInitCallback = null;
this.onShutDownCallback = null;
this.onPreloadCallback = null;
this.onLoadRenderCallback = null;
this.onLoadUpdateCallback = null;
this.onCreateCallback = null;
this.onUpdateCallback = null;
this.onRenderCallback = null;
this.onPausedCallback = null;
this.onResumedCallback = null;
this.onDestroyCallback = null;
}
delete this.states[key];
},
/**
* Start the given State. If a State is already running then State.shutDown will be called (if it exists) before switching to the new State.
*
* @method Phaser.StateManager#start
* @param {string} key - The key of the state you want to start.
* @param {boolean} [clearWorld=true] - Clear everything in the world? This clears the World display list fully (but not the Stage, so if you've added your own objects to the Stage they will need managing directly)
* @param {boolean} [clearCache=false] - Clear the Game.Cache? This purges out all loaded assets. The default is false and you must have clearWorld=true if you want to clearCache as well.
* @param {...*} parameter - Additional parameters that will be passed to the State.init function (if it has one).
*/
start: function (key, clearWorld, clearCache) {
if (typeof clearWorld === "undefined") { clearWorld = true; }
if (typeof clearCache === "undefined") { clearCache = false; }
if (this.checkState(key))
{
// Place the state in the queue. It will be started the next time the game loop starts.
this._pendingState = key;
this._clearWorld = clearWorld;
this._clearCache = clearCache;
if (arguments.length > 3)
{
this._args = Array.prototype.splice.call(arguments, 3);
}
}
},
/**
* Used by onInit and onShutdown when those functions don't exist on the state
* @method Phaser.StateManager#dummy
* @private
*/
dummy: function () {
},
/**
* preUpdate is called right at the start of the game loop. It is responsible for changing to a new state that was requested previously.
*
* @method Phaser.StateManager#preUpdate
*/
preUpdate: function () {
if (this._pendingState && this.game.isBooted)
{
// Already got a state running?
if (this.current)
{
this.onShutDownCallback.call(this.callbackContext, this.game);
}
if (this._clearWorld)
{
this.game.tweens.removeAll();
this.game.world.destroy();
this.game.physics.clear();
if (this._clearCache === true)
{
this.game.cache.destroy();
}
}
this.setCurrentState(this._pendingState);
if (this.onPreloadCallback)
{
this.game.load.reset();
this.onPreloadCallback.call(this.callbackContext, this.game);
// Is the loader empty?
if (this.game.load.totalQueuedFiles() === 0)
{
this.loadComplete();
}
else
{
// Start the loader going as we have something in the queue
this.game.load.start();
}
}
else
{
// No init? Then there was nothing to load either
this.loadComplete();
}
if (this.current === this._pendingState)
{
this._pendingState = null;
}
}
},
/**
* Checks if a given phaser state is valid. A State is considered valid if it has at least one of the core functions: preload, create, update or render.
*
* @method Phaser.StateManager#checkState
* @param {string} key - The key of the state you want to check.
* @return {boolean} true if the State has the required functions, otherwise false.
*/
checkState: function (key) {
if (this.states[key])
{
var valid = false;
if (this.states[key]['preload']) { valid = true; }
if (this.states[key]['create']) { valid = true; }
if (this.states[key]['update']) { valid = true; }
if (this.states[key]['render']) { valid = true; }
if (valid === false)
{
console.warn("Invalid Phaser State object given. Must contain at least a one of the required functions: preload, create, update or render");
return false;
}
return true;
}
else
{
console.warn("Phaser.StateManager - No state found with the key: " + key);
return false;
}
},
/**
* Links game properties to the State given by the key.
* @method Phaser.StateManager#link
* @param {string} key - State key.
* @protected
*/
link: function (key) {
this.states[key].game = this.game;
this.states[key].add = this.game.add;
this.states[key].make = this.game.make;
this.states[key].camera = this.game.camera;
this.states[key].cache = this.game.cache;
this.states[key].input = this.game.input;
this.states[key].load = this.game.load;
this.states[key].math = this.game.math;
this.states[key].sound = this.game.sound;
this.states[key].scale = this.game.scale;
this.states[key].state = this;
this.states[key].stage = this.game.stage;
this.states[key].time = this.game.time;
this.states[key].tweens = this.game.tweens;
this.states[key].world = this.game.world;
this.states[key].particles = this.game.particles;
this.states[key].rnd = this.game.rnd;
this.states[key].physics = this.game.physics;
},
/**
* Sets the current State. Should not be called directly (use StateManager.start)
* @method Phaser.StateManager#setCurrentState
* @param {string} key - State key.
* @private
*/
setCurrentState: function (key) {
this.callbackContext = this.states[key];
this.link(key);
// Used when the state is set as being the current active state
this.onInitCallback = this.states[key]['init'] || this.dummy;
this.onPreloadCallback = this.states[key]['preload'] || null;
this.onLoadRenderCallback = this.states[key]['loadRender'] || null;
this.onLoadUpdateCallback = this.states[key]['loadUpdate'] || null;
this.onCreateCallback = this.states[key]['create'] || null;
this.onUpdateCallback = this.states[key]['update'] || null;
this.onPreRenderCallback = this.states[key]['preRender'] || null;
this.onRenderCallback = this.states[key]['render'] || null;
this.onPausedCallback = this.states[key]['paused'] || null;
this.onResumedCallback = this.states[key]['resumed'] || null;
// Used when the state is no longer the current active state
this.onShutDownCallback = this.states[key]['shutdown'] || this.dummy;
this.current = key;
this._created = false;
this.onInitCallback.apply(this.callbackContext, this._args);
this._args = [];
},
/**
* Gets the current State.
*
* @method Phaser.StateManager#getCurrentState
* @return Phaser.State
* @public
*/
getCurrentState: function() {
return this.states[this.current];
},
/**
* @method Phaser.StateManager#loadComplete
* @protected
*/
loadComplete: function () {
if (this._created === false && this.onCreateCallback)
{
this._created = true;
this.onCreateCallback.call(this.callbackContext, this.game);
}
else
{
this._created = true;
}
},
/**
* @method Phaser.StateManager#pause
* @protected
*/
pause: function () {
if (this._created && this.onPausedCallback)
{
this.onPausedCallback.call(this.callbackContext, this.game);
}
},
/**
* @method Phaser.StateManager#resume
* @protected
*/
resume: function () {
if (this._created && this.onResumedCallback)
{
this.onResumedCallback.call(this.callbackContext, this.game);
}
},
/**
* @method Phaser.StateManager#update
* @protected
*/
update: function () {
if (this._created && this.onUpdateCallback)
{
this.onUpdateCallback.call(this.callbackContext, this.game);
}
else
{
if (this.onLoadUpdateCallback)
{
this.onLoadUpdateCallback.call(this.callbackContext, this.game);
}
}
},
/**
* @method Phaser.StateManager#preRender
* @protected
*/
preRender: function () {
if (this.onPreRenderCallback)
{
this.onPreRenderCallback.call(this.callbackContext, this.game);
}
},
/**
* @method Phaser.StateManager#render
* @protected
*/
render: function () {
if (this._created && this.onRenderCallback)
{
if (this.game.renderType === Phaser.CANVAS)
{
this.game.context.save();
this.game.context.setTransform(1, 0, 0, 1, 0, 0);
}
this.onRenderCallback.call(this.callbackContext, this.game);
if (this.game.renderType === Phaser.CANVAS)
{
this.game.context.restore();
}
}
else
{
if (this.onLoadRenderCallback)
{
this.onLoadRenderCallback.call(this.callbackContext, this.game);
}
}
},
/**
* Nuke the entire game from orbit
* @method Phaser.StateManager#destroy
*/
destroy: function () {
this.callbackContext = null;
this.onInitCallback = null;
this.onShutDownCallback = null;
this.onPreloadCallback = null;
this.onLoadRenderCallback = null;
this.onLoadUpdateCallback = null;
this.onCreateCallback = null;
this.onUpdateCallback = null;
this.onRenderCallback = null;
this.onPausedCallback = null;
this.onResumedCallback = null;
this.onDestroyCallback = null;
this.game = null;
this.states = {};
this._pendingState = null;
}
};
Phaser.StateManager.prototype.constructor = Phaser.StateManager;
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2014 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* A basic linked list data structure.
*
* @class Phaser.LinkedList
* @constructor
*/
Phaser.LinkedList = function () {
/**
* @property {object} next - Next element in the list.
* @default
*/
this.next = null;
/**
* @property {object} prev - Previous element in the list.
* @default
*/
this.prev = null;
/**
* @property {object} first - First element in the list.
* @default
*/
this.first = null;
/**
* @property {object} last - Last element in the list.
* @default
*/
this.last = null;
/**
* @property {object} game - Number of elements in the list.
* @default
*/
this.total = 0;
};
Phaser.LinkedList.prototype = {
/**
* Adds a new element to this linked list.
*
* @method Phaser.LinkedList#add
* @param {object} child - The element to add to this list. Can be a Phaser.Sprite or any other object you need to quickly iterate through.
* @return {object} The child that was added.
*/
add: function (child) {
// If the list is empty
if (this.total === 0 && this.first == null && this.last == null)
{
this.first = child;
this.last = child;
this.next = child;
child.prev = this;
this.total++;
return child;
}
// Get gets appended to the end of the list, regardless of anything, and it won't have any children of its own (non-nested list)
this.last.next = child;
child.prev = this.last;
this.last = child;
this.total++;
return child;
},
/**
* Removes the given element from this linked list if it exists.
*
* @method Phaser.LinkedList#remove
* @param {object} child - The child to be removed from the list.
*/
remove: function (child) {
if (child == this.first)
{
// It was 'first', make 'first' point to first.next
this.first = this.first.next;
}
else if (child == this.last)
{
// It was 'last', make 'last' point to last.prev
this.last = this.last.prev;
}
if (child.prev)
{
// make child.prev.next point to childs.next instead of child
child.prev.next = child.next;
}
if (child.next)
{
// make child.next.prev point to child.prev instead of child
child.next.prev = child.prev;
}
child.next = child.prev = null;
if (this.first == null )
{
this.last = null;
}
this.total--;
},
/**
* Calls a function on all members of this list, using the member as the context for the callback.
* The function must exist on the member.
*
* @method Phaser.LinkedList#callAll
* @param {function} callback - The function to call.
*/
callAll: function (callback) {
if (!this.first || !this.last)
{
return;
}
var entity = this.first;
do
{
if (entity && entity[callback])
{
entity[callback].call(entity);
}
entity = entity.next;
}
while(entity != this.last.next)
}
};
Phaser.LinkedList.prototype.constructor = Phaser.LinkedList;
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2014 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @class Phaser.Signal
* @classdesc A Signal is used for object communication via a custom broadcaster instead of Events.
* @author Miller Medeiros http://millermedeiros.github.com/js-signals/
* @constructor
*/
Phaser.Signal = function () {
/**
* @property {Array.<Phaser.SignalBinding>} _bindings - Internal variable.
* @private
*/
this._bindings = [];
/**
* @property {any} _prevParams - Internal variable.
* @private
*/
this._prevParams = null;
// enforce dispatch to aways work on same context (#47)
var self = this;
/**
* @property {function} dispatch - The dispatch function is what sends the Signal out.
*/
this.dispatch = function(){
Phaser.Signal.prototype.dispatch.apply(self, arguments);
};
};
Phaser.Signal.prototype = {
/**
* If Signal should keep record of previously dispatched parameters and
* automatically execute listener during `add()`/`addOnce()` if Signal was
* already dispatched before.
* @property {boolean} memorize
*/
memorize: false,
/**
* @property {boolean} _shouldPropagate
* @private
*/
_shouldPropagate: true,
/**
* If Signal is active and should broadcast events.
* <p><strong>IMPORTANT:</strong> Setting this property during a dispatch will only affect the next dispatch, if you want to stop the propagation of a signal use `halt()` instead.</p>
* @property {boolean} active
* @default
*/
active: true,
/**
* @method Phaser.Signal#validateListener
* @param {function} listener - Signal handler function.
* @param {string} fnName - Function name.
* @private
*/
validateListener: function (listener, fnName) {
if (typeof listener !== 'function') {
throw new Error( 'listener is a required param of {fn}() and should be a Function.'.replace('{fn}', fnName) );
}
},
/**
* @method Phaser.Signal#_registerListener
* @param {function} listener - Signal handler function.
* @param {boolean} isOnce - Description.
* @param {object} [listenerContext] - Description.
* @param {number} [priority] - The priority level of the event listener. Listeners with higher priority will be executed before listeners with lower priority. Listeners with same priority level will be executed at the same order as they were added. (default = 0).
* @return {Phaser.SignalBinding} An Object representing the binding between the Signal and listener.
* @private
*/
_registerListener: function (listener, isOnce, listenerContext, priority) {
var prevIndex = this._indexOfListener(listener, listenerContext),
binding;
if (prevIndex !== -1) {
binding = this._bindings[prevIndex];
if (binding.isOnce() !== isOnce) {
throw new Error('You cannot add'+ (isOnce? '' : 'Once') +'() then add'+ (!isOnce? '' : 'Once') +'() the same listener without removing the relationship first.');
}
} else {
binding = new Phaser.SignalBinding(this, listener, isOnce, listenerContext, priority);
this._addBinding(binding);
}
if (this.memorize && this._prevParams){
binding.execute(this._prevParams);
}
return binding;
},
/**
* @method Phaser.Signal#_addBinding
* @param {Phaser.SignalBinding} binding - An Object representing the binding between the Signal and listener.
* @private
*/
_addBinding: function (binding) {
//simplified insertion sort
var n = this._bindings.length;
do { --n; } while (this._bindings[n] && binding._priority <= this._bindings[n]._priority);
this._bindings.splice(n + 1, 0, binding);
},
/**
* @method Phaser.Signal#_indexOfListener
* @param {function} listener - Signal handler function.
* @return {number} Description.
* @private
*/
_indexOfListener: function (listener, context) {
var n = this._bindings.length,
cur;
while (n--) {
cur = this._bindings[n];
if (cur._listener === listener && cur.context === context) {
return n;
}
}
return -1;
},
/**
* Check if listener was attached to Signal.
*
* @method Phaser.Signal#has
* @param {Function} listener - Signal handler function.
* @param {Object} [context] - Context on which listener will be executed (object that should represent the `this` variable inside listener function).
* @return {boolean} If Signal has the specified listener.
*/
has: function (listener, context) {
return this._indexOfListener(listener, context) !== -1;
},
/**
* Add a listener to the signal.
*
* @method Phaser.Signal#add
* @param {function} listener - Signal handler function.
* @param {object} [listenerContext] Context on which listener will be executed (object that should represent the `this` variable inside listener function).
* @param {number} [priority] The priority level of the event listener. Listeners with higher priority will be executed before listeners with lower priority. Listeners with same priority level will be executed at the same order as they were added. (default = 0).
* @return {Phaser.SignalBinding} An Object representing the binding between the Signal and listener.
*/
add: function (listener, listenerContext, priority) {
this.validateListener(listener, 'add');
return this._registerListener(listener, false, listenerContext, priority);
},
/**
* Add listener to the signal that should be removed after first execution (will be executed only once).
*
* @method Phaser.Signal#addOnce
* @param {function} listener Signal handler function.
* @param {object} [listenerContext] Context on which listener will be executed (object that should represent the `this` variable inside listener function).
* @param {number} [priority] The priority level of the event listener. Listeners with higher priority will be executed before listeners with lower priority. Listeners with same priority level will be executed at the same order as they were added. (default = 0)
* @return {Phaser.SignalBinding} An Object representing the binding between the Signal and listener.
*/
addOnce: function (listener, listenerContext, priority) {
this.validateListener(listener, 'addOnce');
return this._registerListener(listener, true, listenerContext, priority);
},
/**
* Remove a single listener from the dispatch queue.
*
* @method Phaser.Signal#remove
* @param {function} listener Handler function that should be removed.
* @param {object} [context] Execution context (since you can add the same handler multiple times if executing in a different context).
* @return {function} Listener handler function.
*/
remove: function (listener, context) {
this.validateListener(listener, 'remove');
var i = this._indexOfListener(listener, context);
if (i !== -1)
{
this._bindings[i]._destroy(); //no reason to a Phaser.SignalBinding exist if it isn't attached to a signal
this._bindings.splice(i, 1);
}
return listener;
},
/**
* Remove all listeners from the Signal.
*
* @method Phaser.Signal#removeAll
*/
removeAll: function () {
var n = this._bindings.length;
while (n--) {
this._bindings[n]._destroy();
}
this._bindings.length = 0;
},
/**
* Gets the total number of listeneres attached to ths Signal.
*
* @method Phaser.Signal#getNumListeners
* @return {number} Number of listeners attached to the Signal.
*/
getNumListeners: function () {
return this._bindings.length;
},
/**
* Stop propagation of the event, blocking the dispatch to next listeners on the queue.
* IMPORTANT: should be called only during signal dispatch, calling it before/after dispatch won't affect signal broadcast.
* @see Signal.prototype.disable
*
* @method Phaser.Signal#halt
*/
halt: function () {
this._shouldPropagate = false;
},
/**
* Dispatch/Broadcast Signal to all listeners added to the queue.
*
* @method Phaser.Signal#dispatch
* @param {any} [params] - Parameters that should be passed to each handler.
*/
dispatch: function () {
if (!this.active)
{
return;
}
var paramsArr = Array.prototype.slice.call(arguments);
var n = this._bindings.length;
var bindings;
if (this.memorize)
{
this._prevParams = paramsArr;
}
if (!n)
{
// Should come after memorize
return;
}
bindings = this._bindings.slice(); //clone array in case add/remove items during dispatch
this._shouldPropagate = true; //in case `halt` was called before dispatch or during the previous dispatch.
//execute all callbacks until end of the list or until a callback returns `false` or stops propagation
//reverse loop since listeners with higher priority will be added at the end of the list
do { n--; } while (bindings[n] && this._shouldPropagate && bindings[n].execute(paramsArr) !== false);
},
/**
* Forget memorized arguments.
* @see Signal.memorize
*
* @method Phaser.Signal#forget
*/
forget: function(){
this._prevParams = null;
},
/**
* Remove all bindings from signal and destroy any reference to external objects (destroy Signal object).
* IMPORTANT: calling any method on the signal instance after calling dispose will throw errors.
*
* @method Phaser.Signal#dispose
*/
dispose: function () {
this.removeAll();
delete this._bindings;
delete this._prevParams;
},
/**
*
* @method Phaser.Signal#toString
* @return {string} String representation of the object.
*/
toString: function () {
return '[Phaser.Signal active:'+ this.active +' numListeners:'+ this.getNumListeners() +']';
}
};
Phaser.Signal.prototype.constructor = Phaser.Signal;
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2014 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* Phaser.SignalBinding
*
* Object that represents a binding between a Signal and a listener function.
* This is an internal constructor and shouldn't be called by regular users.
* Inspired by Joa Ebert AS3 SignalBinding and Robert Penner's Slot classes.
*
* @class Phaser.SignalBinding
* @name SignalBinding
* @author Miller Medeiros http://millermedeiros.github.com/js-signals/
* @constructor
* @inner
* @param {Phaser.Signal} signal - Reference to Signal object that listener is currently bound to.
* @param {function} listener - Handler function bound to the signal.
* @param {boolean} isOnce - If binding should be executed just once.
* @param {object} [listenerContext] - Context on which listener will be executed (object that should represent the `this` variable inside listener function).
* @param {number} [priority] - The priority level of the event listener. (default = 0).
*/
Phaser.SignalBinding = function (signal, listener, isOnce, listenerContext, priority) {
/**
* @property {Phaser.Game} _listener - Handler function bound to the signal.
* @private
*/
this._listener = listener;
/**
* @property {boolean} _isOnce - If binding should be executed just once.
* @private
*/
this._isOnce = isOnce;
/**
* @property {object|undefined|null} context - Context on which listener will be executed (object that should represent the `this` variable inside listener function).
* @memberof SignalBinding.prototype
*/
this.context = listenerContext;
/**
* @property {Phaser.Signal} _signal - Reference to Signal object that listener is currently bound to.
* @private
*/
this._signal = signal;
/**
* @property {number} _priority - Listener priority.
* @private
*/
this._priority = priority || 0;
};
Phaser.SignalBinding.prototype = {
/**
* If binding is active and should be executed.
* @property {boolean} active
* @default
*/
active: true,
/**
* Default parameters passed to listener during `Signal.dispatch` and `SignalBinding.execute` (curried parameters).
* @property {array|null} params
* @default
*/
params: null,
/**
* Call listener passing arbitrary parameters.
* If binding was added using `Signal.addOnce()` it will be automatically removed from signal dispatch queue, this method is used internally for the signal dispatch.
* @method Phaser.SignalBinding#execute
* @param {array} [paramsArr] - Array of parameters that should be passed to the listener.
* @return {any} Value returned by the listener.
*/
execute: function (paramsArr) {
var handlerReturn, params;
if (this.active && !!this._listener)
{
params = this.params? this.params.concat(paramsArr) : paramsArr;
handlerReturn = this._listener.apply(this.context, params);
if (this._isOnce)
{
this.detach();
}
}
return handlerReturn;
},
/**
* Detach binding from signal.
* alias to: @see mySignal.remove(myBinding.getListener());
* @method Phaser.SignalBinding#detach
* @return {function|null} Handler function bound to the signal or `null` if binding was previously detached.
*/
detach: function () {
return this.isBound() ? this._signal.remove(this._listener, this.context) : null;
},
/**
* @method Phaser.SignalBinding#isBound
* @return {boolean} True if binding is still bound to the signal and has a listener.
*/
isBound: function () {
return (!!this._signal && !!this._listener);
},
/**
* @method Phaser.SignalBinding#isOnce
* @return {boolean} If SignalBinding will only be executed once.
*/
isOnce: function () {
return this._isOnce;
},
/**
* @method Phaser.SignalBinding#getListener
* @return {Function} Handler function bound to the signal.
*/
getListener: function () {
return this._listener;
},
/**
* @method Phaser.SignalBinding#getSignal
* @return {Signal} Signal that listener is currently bound to.
*/
getSignal: function () {
return this._signal;
},
/**
* @method Phaser.SignalBinding#_destroy
* Delete instance properties
* @private
*/
_destroy: function () {
delete this._signal;
delete this._listener;
delete this.context;
},
/**
* @method Phaser.SignalBinding#toString
* @return {string} String representation of the object.
*/
toString: function () {
return '[Phaser.SignalBinding isOnce:' + this._isOnce +', isBound:'+ this.isBound() +', active:' + this.active + ']';
}
};
Phaser.SignalBinding.prototype.constructor = Phaser.SignalBinding;
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2014 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* This is a base Filter template to use for any Phaser filter development.
*
* @class Phaser.Filter
* @classdesc Phaser - Filter
* @constructor
* @param {Phaser.Game} game - A reference to the currently running game.
* @param {Object} uniforms - Uniform mappings object
* @param {Array} fragmentSrc - The fragment shader code.
*/
Phaser.Filter = function (game, uniforms, fragmentSrc) {
/**
* @property {Phaser.Game} game - A reference to the currently running game.
*/
this.game = game;
/**
* @property {number} type - The const type of this object, either Phaser.WEBGL_FILTER or Phaser.CANVAS_FILTER.
* @default
*/
this.type = Phaser.WEBGL_FILTER;
/**
* An array of passes - some filters contain a few steps this array simply stores the steps in a linear fashion.
* For example the blur filter has two passes blurX and blurY.
* @property {array} passes - An array of filter objects.
* @private
*/
this.passes = [this];
/**
* @property {array} shaders - Array an array of shaders.
* @private
*/
this.shaders = [];
/**
* @property {boolean} dirty - Internal PIXI var.
* @default
*/
this.dirty = true;
/**
* @property {number} padding - Internal PIXI var.
* @default
*/
this.padding = 0;
/**
* @property {object} uniforms - Default uniform mappings.
*/
this.uniforms = {
time: { type: '1f', value: 0 },
resolution: { type: '2f', value: { x: 256, y: 256 }},
mouse: { type: '2f', value: { x: 0.0, y: 0.0 }}
};
/**
* @property {array} fragmentSrc - The fragment shader code.
*/
this.fragmentSrc = fragmentSrc || [];
};
Phaser.Filter.prototype = {
/**
* Should be over-ridden.
* @method Phaser.Filter#init
*/
init: function () {
// This should be over-ridden. Will receive a variable number of arguments.
},
/**
* Set the resolution uniforms on the filter.
* @method Phaser.Filter#setResolution
* @param {number} width - The width of the display.
* @param {number} height - The height of the display.
*/
setResolution: function (width, height) {
this.uniforms.resolution.value.x = width;
this.uniforms.resolution.value.y = height;
},
/**
* Updates the filter.
* @method Phaser.Filter#update
* @param {Phaser.Pointer} [pointer] - A Pointer object to use for the filter. The coordinates are mapped to the mouse uniform.
*/
update: function (pointer) {
if (typeof pointer !== 'undefined')
{
if (pointer.x > 0)
{
this.uniforms.mouse.x = pointer.x.toFixed(2);
}
if (pointer.y > 0)
{
this.uniforms.mouse.y = pointer.y.toFixed(2);
}
}
this.uniforms.time.value = this.game.time.totalElapsedSeconds();
},
/**
* Clear down this Filter and null out references
* @method Phaser.Filter#destroy
*/
destroy: function () {
this.game = null;
}
};
Phaser.Filter.prototype.constructor = Phaser.Filter;
/**
* @name Phaser.Filter#width
* @property {number} width - The width (resolution uniform)
*/
Object.defineProperty(Phaser.Filter.prototype, 'width', {
get: function() {
return this.uniforms.resolution.value.x;
},
set: function(value) {
this.uniforms.resolution.value.x = value;
}
});
/**
* @name Phaser.Filter#height
* @property {number} height - The height (resolution uniform)
*/
Object.defineProperty(Phaser.Filter.prototype, 'height', {
get: function() {
return this.uniforms.resolution.value.y;
},
set: function(value) {
this.uniforms.resolution.value.y = value;
}
});
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2014 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* This is a base Plugin template to use for any Phaser plugin development.
*
* @class Phaser.Plugin
* @classdesc Phaser - Plugin
* @constructor
* @param {Phaser.Game} game - A reference to the currently running game.
* @param {Any} parent - The object that owns this plugin, usually Phaser.PluginManager.
*/
Phaser.Plugin = function (game, parent) {
if (typeof parent === 'undefined') { parent = null; }
/**
* @property {Phaser.Game} game - A reference to the currently running game.
*/
this.game = game;
/**
* @property {Any} parent - The parent of this plugin. If added to the PluginManager the parent will be set to that, otherwise it will be null.
*/
this.parent = parent;
/**
* @property {boolean} active - A Plugin with active=true has its preUpdate and update methods called by the parent, otherwise they are skipped.
* @default
*/
this.active = false;
/**
* @property {boolean} visible - A Plugin with visible=true has its render and postRender methods called by the parent, otherwise they are skipped.
* @default
*/
this.visible = false;
/**
* @property {boolean} hasPreUpdate - A flag to indicate if this plugin has a preUpdate method.
* @default
*/
this.hasPreUpdate = false;
/**
* @property {boolean} hasUpdate - A flag to indicate if this plugin has an update method.
* @default
*/
this.hasUpdate = false;
/**
* @property {boolean} hasPostUpdate - A flag to indicate if this plugin has a postUpdate method.
* @default
*/
this.hasPostUpdate = false;
/**
* @property {boolean} hasRender - A flag to indicate if this plugin has a render method.
* @default
*/
this.hasRender = false;
/**
* @property {boolean} hasPostRender - A flag to indicate if this plugin has a postRender method.
* @default
*/
this.hasPostRender = false;
};
Phaser.Plugin.prototype = {
/**
* Pre-update is called at the very start of the update cycle, before any other subsystems have been updated (including Physics).
* It is only called if active is set to true.
* @method Phaser.Plugin#preUpdate
*/
preUpdate: function () {
},
/**
* Update is called after all the core subsystems (Input, Tweens, Sound, etc) and the State have updated, but before the render.
* It is only called if active is set to true.
* @method Phaser.Plugin#update
*/
update: function () {
},
/**
* Render is called right after the Game Renderer completes, but before the State.render.
* It is only called if visible is set to true.
* @method Phaser.Plugin#render
*/
render: function () {
},
/**
* Post-render is called after the Game Renderer and State.render have run.
* It is only called if visible is set to true.
* @method Phaser.Plugin#postRender
*/
postRender: function () {
},
/**
* Clear down this Plugin and null out references
* @method Phaser.Plugin#destroy
*/
destroy: function () {
this.game = null;
this.parent = null;
this.active = false;
this.visible = false;
}
};
Phaser.Plugin.prototype.constructor = Phaser.Plugin;
/* jshint newcap: false */
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2014 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* The Plugin Manager is responsible for the loading, running and unloading of Phaser Plugins.
*
* @class Phaser.PluginManager
* @classdesc Phaser - PluginManager
* @constructor
* @param {Phaser.Game} game - A reference to the currently running game.
* @param {Description} parent - Description.
*/
Phaser.PluginManager = function(game, parent) {
/**
* @property {Phaser.Game} game - A reference to the currently running game.
*/
this.game = game;
/**
* @property {Description} _parent - Description.
* @private
*/
this._parent = parent;
/**
* @property {array} plugins - Description.
*/
this.plugins = [];
/**
* @property {array} _pluginsLength - Description.
* @private
* @default
*/
this._pluginsLength = 0;
};
Phaser.PluginManager.prototype = {
/**
* Add a new Plugin to the PluginManager.
* The plugin's game and parent reference are set to this game and pluginmanager parent.
* @method Phaser.PluginManager#add
* @param {Phaser.Plugin} plugin - Description.
* @return {Phaser.Plugin} Description.
*/
add: function (plugin) {
var result = false;
// Prototype?
if (typeof plugin === 'function')
{
plugin = new plugin(this.game, this._parent);
}
else
{
plugin.game = this.game;
plugin.parent = this._parent;
}
// Check for methods now to avoid having to do this every loop
if (typeof plugin['preUpdate'] === 'function')
{
plugin.hasPreUpdate = true;
result = true;
}
if (typeof plugin['update'] === 'function')
{
plugin.hasUpdate = true;
result = true;
}
if (typeof plugin['postUpdate'] === 'function')
{
plugin.hasPostUpdate = true;
result = true;
}
if (typeof plugin['render'] === 'function')
{
plugin.hasRender = true;
result = true;
}
if (typeof plugin['postRender'] === 'function')
{
plugin.hasPostRender = true;
result = true;
}
// The plugin must have at least one of the above functions to be added to the PluginManager.
if (result)
{
if (plugin.hasPreUpdate || plugin.hasUpdate || plugin.hasPostUpdate)
{
plugin.active = true;
}
if (plugin.hasRender || plugin.hasPostRender)
{
plugin.visible = true;
}
this._pluginsLength = this.plugins.push(plugin);
// Allows plugins to run potentially destructive code outside of the constructor, and only if being added to the PluginManager
if (typeof plugin['init'] === 'function')
{
plugin.init();
}
return plugin;
}
else
{
return null;
}
},
/**
* Remove a Plugin from the PluginManager.
* @method Phaser.PluginManager#remove
* @param {Phaser.Plugin} plugin - The plugin to be removed.
*/
remove: function (plugin) {
if (this._pluginsLength === 0)
{
return;
}
for (this._p = 0; this._p < this._pluginsLength; this._p++)
{
if (this.plugins[this._p] === plugin)
{
plugin.destroy();
this.plugins.splice(this._p, 1);
this._pluginsLength--;
return;
}
}
},
/**
* Removes all Plugins from the PluginManager.
* @method Phaser.PluginManager#removeAll
*/
removeAll: function() {
for (this._p = 0; this._p < this._pluginsLength; this._p++)
{
this.plugins[this._p].destroy();
}
this.plugins.length = 0;
this._pluginsLength = 0;
},
/**
* Pre-update is called at the very start of the update cycle, before any other subsystems have been updated (including Physics).
* It only calls plugins who have active=true.
*
* @method Phaser.PluginManager#preUpdate
*/
preUpdate: function () {
if (this._pluginsLength === 0)
{
return;
}
for (this._p = 0; this._p < this._pluginsLength; this._p++)
{
if (this.plugins[this._p].active && this.plugins[this._p].hasPreUpdate)
{
this.plugins[this._p].preUpdate();
}
}
},
/**
* Update is called after all the core subsystems (Input, Tweens, Sound, etc) and the State have updated, but before the render.
* It only calls plugins who have active=true.
*
* @method Phaser.PluginManager#update
*/
update: function () {
if (this._pluginsLength === 0)
{
return;
}
for (this._p = 0; this._p < this._pluginsLength; this._p++)
{
if (this.plugins[this._p].active && this.plugins[this._p].hasUpdate)
{
this.plugins[this._p].update();
}
}
},
/**
* PostUpdate is the last thing to be called before the world render.
* In particular, it is called after the world postUpdate, which means the camera has been adjusted.
* It only calls plugins who have active=true.
*
* @method Phaser.PluginManager#postUpdate
*/
postUpdate: function () {
if (this._pluginsLength === 0)
{
return;
}
for (this._p = 0; this._p < this._pluginsLength; this._p++)
{
if (this.plugins[this._p].active && this.plugins[this._p].hasPostUpdate)
{
this.plugins[this._p].postUpdate();
}
}
},
/**
* Render is called right after the Game Renderer completes, but before the State.render.
* It only calls plugins who have visible=true.
*
* @method Phaser.PluginManager#render
*/
render: function () {
if (this._pluginsLength === 0)
{
return;
}
for (this._p = 0; this._p < this._pluginsLength; this._p++)
{
if (this.plugins[this._p].visible && this.plugins[this._p].hasRender)
{
this.plugins[this._p].render();
}
}
},
/**
* Post-render is called after the Game Renderer and State.render have run.
* It only calls plugins who have visible=true.
*
* @method Phaser.PluginManager#postRender
*/
postRender: function () {
if (this._pluginsLength === 0)
{
return;
}
for (this._p = 0; this._p < this._pluginsLength; this._p++)
{
if (this.plugins[this._p].visible && this.plugins[this._p].hasPostRender)
{
this.plugins[this._p].postRender();
}
}
},
/**
* Clear down this PluginManager and null out references
*
* @method Phaser.PluginManager#destroy
*/
destroy: function () {
this.plugins.length = 0;
this._pluginsLength = 0;
this.game = null;
this._parent = null;
}
};
Phaser.PluginManager.prototype.constructor = Phaser.PluginManager;
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2014 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* The Stage controls the canvas on which everything is displayed. It handles display within the browser,
* focus handling, game resizing, scaling and the pause, boot and orientation screens.
*
* @class Phaser.Stage
* @extends PIXI.Stage
* @constructor
* @param {Phaser.Game} game - Game reference to the currently running game.
* @param {number} width - Width of the canvas element.
* @param {number} height - Height of the canvas element.
*/
Phaser.Stage = function (game, width, height) {
/**
* @property {Phaser.Game} game - A reference to the currently running Game.
*/
this.game = game;
/**
* @property {Phaser.Point} offset - Holds the offset coordinates of the Game.canvas from the top-left of the browser window (used by Input and other classes)
*/
this.offset = new Phaser.Point();
PIXI.Stage.call(this, 0x000000, false);
/**
* @property {string} name - The name of this object.
* @default
*/
this.name = '_stage_root';
this.interactive = false;
/**
* @property {boolean} disableVisibilityChange - By default if the browser tab loses focus the game will pause. You can stop that behaviour by setting this property to true.
* @default
*/
this.disableVisibilityChange = false;
/**
* @property {number|false} checkOffsetInterval - The time (in ms) between which the stage should check to see if it has moved.
* @default
*/
this.checkOffsetInterval = 2500;
/**
* @property {boolean} exists - If exists is true the Stage and all children are updated, otherwise it is skipped.
* @default
*/
this.exists = true;
/**
* @property {number} currentRenderOrderID - Reset each frame, keeps a count of the total number of objects updated.
*/
this.currentRenderOrderID = 0;
/**
* @property {string} hiddenVar - The page visibility API event name.
* @private
*/
this._hiddenVar = 'hidden';
/**
* @property {number} _nextOffsetCheck - The time to run the next offset check.
* @private
*/
this._nextOffsetCheck = 0;
/**
* @property {number} _backgroundColor - Stage background color.
* @private
*/
this._backgroundColor;
if (game.config)
{
this.parseConfig(game.config);
}
else
{
this.game.canvas = Phaser.Canvas.create(width, height);
this.game.canvas.style['-webkit-full-screen'] = 'width: 100%; height: 100%';
}
};
Phaser.Stage.prototype = Object.create(PIXI.Stage.prototype);
Phaser.Stage.prototype.constructor = Phaser.Stage;
/**
* This is called automatically after the plugins preUpdate and before the State.update.
* Most objects have preUpdate methods and it's where initial movement and positioning is done.
*
* @method Phaser.Stage#preUpdate
*/
Phaser.Stage.prototype.preUpdate = function () {
this.currentRenderOrderID = 0;
// This can't loop in reverse, we need the orderID to be in sequence
var len = this.children.length;
for (var i = 0; i < len; i++)
{
this.children[i].preUpdate();
}
}
/**
* This is called automatically after the State.update, but before particles or plugins update.
*
* @method Phaser.Stage#update
*/
Phaser.Stage.prototype.update = function () {
var i = this.children.length;
while (i--)
{
this.children[i].update();
}
}
/**
* This is called automatically before the renderer runs and after the plugins have updated.
* In postUpdate this is where all the final physics calculatations and object positioning happens.
* The objects are processed in the order of the display list.
* The only exception to this is if the camera is following an object, in which case that is updated first.
*
* @method Phaser.Stage#postUpdate
*/
Phaser.Stage.prototype.postUpdate = function () {
if (this.game.world.camera.target)
{
this.game.world.camera.target.postUpdate();
this.game.world.camera.update();
var i = this.children.length;
while (i--)
{
if (this.children[i] !== this.game.world.camera.target)
{
this.children[i].postUpdate();
}
}
}
else
{
this.game.world.camera.update();
var i = this.children.length;
while (i--)
{
this.children[i].postUpdate();
}
}
if (this.checkOffsetInterval !== false)
{
if (this.game.time.now > this._nextOffsetCheck)
{
Phaser.Canvas.getOffset(this.game.canvas, this.offset);
this._nextOffsetCheck = this.game.time.now + this.checkOffsetInterval;
}
}
}
/**
* Parses a Game configuration object.
*
* @method Phaser.Stage#parseConfig
* @protected
*/
Phaser.Stage.prototype.parseConfig = function (config) {
if (config['canvasID'])
{
this.game.canvas = Phaser.Canvas.create(this.game.width, this.game.height, config['canvasID']);
}
else
{
this.game.canvas = Phaser.Canvas.create(this.game.width, this.game.height);
}
if (config['canvasStyle'])
{
this.game.canvas.stlye = config['canvasStyle'];
}
else
{
this.game.canvas.style['-webkit-full-screen'] = 'width: 100%; height: 100%';
}
if (config['checkOffsetInterval'])
{
this.checkOffsetInterval = config['checkOffsetInterval'];
}
if (config['disableVisibilityChange'])
{
this.disableVisibilityChange = config['disableVisibilityChange'];
}
if (config['fullScreenScaleMode'])
{
this.fullScreenScaleMode = config['fullScreenScaleMode'];
}
if (config['scaleMode'])
{
this.scaleMode = config['scaleMode'];
}
if (config['backgroundColor'])
{
this.backgroundColor = config['backgroundColor'];
}
}
/**
* Initialises the stage and adds the event listeners.
* @method Phaser.Stage#boot
* @private
*/
Phaser.Stage.prototype.boot = function () {
Phaser.Canvas.getOffset(this.game.canvas, this.offset);
this.bounds = new Phaser.Rectangle(this.offset.x, this.offset.y, this.game.width, this.game.height);
var _this = this;
this._onChange = function (event) {
return _this.visibilityChange(event);
}
Phaser.Canvas.setUserSelect(this.game.canvas, 'none');
Phaser.Canvas.setTouchAction(this.game.canvas, 'none');
this.checkVisibility();
}
/**
* Starts a page visibility event listener running, or window.blur/focus if not supported by the browser.
* @method Phaser.Stage#checkVisibility
*/
Phaser.Stage.prototype.checkVisibility = function () {
if (document.webkitHidden != undefined)
{
this._hiddenVar = 'webkitvisibilitychange';
}
else if (document.mozHidden != undefined)
{
this._hiddenVar = 'mozvisibilitychange';
}
else if (document.msHidden != undefined)
{
this._hiddenVar = 'msvisibilitychange';
}
else if (document.hidden != undefined)
{
this._hiddenVar = 'visibilitychange';
}
else
{
this._hiddenVar = null;
}
// Does browser support it? If not (like in IE9 or old Android) we need to fall back to blur/focus
if (this._hiddenVar)
{
document.addEventListener(this._hiddenVar, this._onChange, false);
}
if (window['onpagehide'])
{
window.onpagehide = this._onChange;
window.onpageshow = this._onChange;
}
window.onblur = this._onChange;
window.onfocus = this._onChange;
}
/**
* This method is called when the document visibility is changed.
* @method Phaser.Stage#visibilityChange
* @param {Event} event - Its type will be used to decide whether the game should be paused or not.
*/
Phaser.Stage.prototype.visibilityChange = function (event) {
if (this.disableVisibilityChange)
{
return;
}
if (event.type === 'pagehide' || event.type === 'blur' || event.type === 'pageshow' || event.type === 'focus')
{
if (event.type === 'pagehide' || event.type === 'blur')
{
this.game.gamePaused(event.timeStamp);
}
else if (event.type === 'pageshow' || event.type === 'focus')
{
this.game.gameResumed(event.timeStamp);
}
return;
}
if (document.hidden || document.mozHidden || document.msHidden || document.webkitHidden)
{
this.game.gamePaused(event.timeStamp);
}
else
{
this.game.gameResumed(event.timeStamp);
}
}
/**
* Sets the background color for the stage.
*
* @name Phaser.Stage#setBackgroundColor
* @param {number} backgroundColor - The color of the background, easiest way to pass this in is in hex format like: 0xFFFFFF for white.
*/
Phaser.Stage.prototype.setBackgroundColor = function(backgroundColor)
{
this._backgroundColor = backgroundColor || 0x000000;
this.backgroundColorSplit = PIXI.hex2rgb(this.backgroundColor);
var hex = this._backgroundColor.toString(16);
hex = '000000'.substr(0, 6 - hex.length) + hex;
this.backgroundColorString = '#' + hex;
}
/**
* @name Phaser.Stage#backgroundColor
* @property {number|string} backgroundColor - Gets and sets the background color of the stage. The color can be given as a number: 0xff0000 or a hex string: '#ff0000'
*/
Object.defineProperty(Phaser.Stage.prototype, "backgroundColor", {
get: function () {
return this._backgroundColor;
},
set: function (color) {
this._backgroundColor = color;
if (this.game.transparent === false)
{
if (typeof color === 'string')
{
color = Phaser.Color.hexToRGB(color);
}
this.setBackgroundColor(color);
}
}
});
/**
* Enable or disable texture smoothing for all objects on this Stage. Only works for bitmap/image textures. Smoothing is enabled by default.
*
* @name Phaser.Stage#smoothed
* @property {boolean} smoothed - Set to true to smooth all sprites rendered on this Stage, or false to disable smoothing (great for pixel art)
*/
Object.defineProperty(Phaser.Stage.prototype, "smoothed", {
get: function () {
return !PIXI.scaleModes.LINEAR;
},
set: function (value) {
if (value)
{
PIXI.scaleModes.LINEAR = 0;
}
else
{
PIXI.scaleModes.LINEAR = 1;
}
}
});
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2014 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* Phaser Group constructor.
* @class Phaser.Group
* @classdesc A Group is a container for display objects that allows for fast pooling and object recycling. Groups can be nested within other Groups and have their own local transforms.
* @constructor
* @param {Phaser.Game} game - A reference to the currently running game.
* @param {Phaser.Group|Phaser.Sprite|null} parent - The parent Group, DisplayObject or DisplayObjectContainer that this Group will be added to. If undefined it will use game.world. If null it won't be added to anything.
* @param {string} [name=group] - A name for this Group. Not used internally but useful for debugging.
* @param {boolean} [addToStage=false] - If set to true this Group will be added directly to the Game.Stage instead of Game.World.
*/
Phaser.Group = function (game, parent, name, addToStage) {
if (typeof addToStage === 'undefined') { addToStage = false; }
/**
* @property {Phaser.Game} game - A reference to the currently running Game.
*/
this.game = game;
if (typeof parent === 'undefined')
{
parent = game.world;
}
/**
* @property {string} name - A name for this Group. Not used internally but useful for debugging.
*/
this.name = name || 'group';
PIXI.DisplayObjectContainer.call(this);
if (addToStage)
{
this.game.stage.addChild(this);
}
else
{
if (parent)
{
parent.addChild(this);
}
}
/**
* @property {number} type - Internal Phaser Type value.
* @protected
*/
this.type = Phaser.GROUP;
/**
* @property {boolean} alive - The alive property is useful for Groups that are children of other Groups and need to be included/excluded in checks like forEachAlive.
* @default
*/
this.alive = true;
/**
* @property {boolean} exists - If exists is true the Group is updated, otherwise it is skipped.
* @default
*/
this.exists = true;
/**
* @property {Phaser.Group|Phaser.Sprite} parent - The parent of this Group.
*/
/**
* @property {Phaser.Point} scale - The scale of the Group container.
*/
this.scale = new Phaser.Point(1, 1);
/**
* @property {Phaser.Point} pivot - The pivot point of the Group container.
*/
/**
* The cursor is a simple way to iterate through the objects in a Group using the Group.next and Group.previous functions.
* The cursor is set to the first child added to the Group and doesn't change unless you call next, previous or set it directly with Group.cursor.
* @property {any} cursor - The current display object that the Group cursor is pointing to.
*/
this.cursor = null;
/**
* @property {Phaser.Point} cameraOffset - If this object is fixedToCamera then this stores the x/y offset that its drawn at, from the top-left of the camera view.
*/
this.cameraOffset = new Phaser.Point();
/**
* @property {boolean} enableBody - If true all Sprites created with `Group.create` or `Group.createMulitple` will have a physics body created on them. Change the body type with `Group.physicsBodyType`.
*/
this.enableBody = false;
/**
* @property {number} physicsBodyType - If Group.enableBody is true this is the type of physics body that is created on new Sprites. Phaser.Physics.ARCADE, Phaser.Physics.P2, Phaser.Physics.NINJA, etc.
*/
this.physicsBodyType = Phaser.Physics.ARCADE;
/**
* A small internal cache:
* 0 = previous position.x
* 1 = previous position.y
* 2 = previous rotation
* 3 = renderID
* 4 = fresh? (0 = no, 1 = yes)
* 5 = outOfBoundsFired (0 = no, 1 = yes)
* 6 = exists (0 = no, 1 = yes)
* 7 = fixed to camera (0 = no, 1 = yes)
* 8 = cursor index
* @property {Int16Array} _cache
* @private
*/
this._cache = new Int16Array([0, 0, 0, 0, 1, 0, 1, 0, 0]);
};
Phaser.Group.prototype = Object.create(PIXI.DisplayObjectContainer.prototype);
Phaser.Group.prototype.constructor = Phaser.Group;
/**
* @constant
* @type {number}
*/
Phaser.Group.RETURN_NONE = 0;
/**
* @constant
* @type {number}
*/
Phaser.Group.RETURN_TOTAL = 1;
/**
* @constant
* @type {number}
*/
Phaser.Group.RETURN_CHILD = 2;
/**
* @constant
* @type {number}
*/
Phaser.Group.SORT_ASCENDING = -1;
/**
* @constant
* @type {number}
*/
Phaser.Group.SORT_DESCENDING = 1;
/**
* Adds an existing object to this Group. The object can be an instance of Phaser.Sprite, Phaser.Button or any other display object.
* The child is automatically added to the top of the Group, so renders on-top of everything else within the Group. If you need to control
* that then see the addAt method.
*
* @see Phaser.Group#create
* @see Phaser.Group#addAt
* @method Phaser.Group#add
* @param {*} child - An instance of Phaser.Sprite, Phaser.Button or any other display object..
* @return {*} The child that was added to the Group.
*/
Phaser.Group.prototype.add = function (child) {
if (child.parent !== this)
{
this.addChild(child);
if (child.events)
{
child.events.onAddedToGroup.dispatch(child, this);
}
}
if (this.cursor === null)
{
this.cursor = child;
}
return child;
}
/**
* Adds an existing object to this Group. The object can be an instance of Phaser.Sprite, Phaser.Button or any other display object.
* The child is added to the Group at the location specified by the index value, this allows you to control child ordering.
*
* @method Phaser.Group#addAt
* @param {*} child - An instance of Phaser.Sprite, Phaser.Button or any other display object..
* @param {number} index - The index within the Group to insert the child to.
* @return {*} The child that was added to the Group.
*/
Phaser.Group.prototype.addAt = function (child, index) {
if (child.parent !== this)
{
this.addChildAt(child, index);
if (child.events)
{
child.events.onAddedToGroup.dispatch(child, this);
}
}
if (this.cursor === null)
{
this.cursor = child;
}
return child;
}
/**
* Returns the child found at the given index within this Group.
*
* @method Phaser.Group#getAt
* @param {number} index - The index to return the child from.
* @return {*} The child that was found at the given index. If the index was out of bounds then this will return -1.
*/
Phaser.Group.prototype.getAt = function (index) {
if (index < 0 || index > this.children.length)
{
return -1;
}
else
{
return this.getChildAt(index);
}
}
/**
* Automatically creates a new Phaser.Sprite object and adds it to the top of this Group.
* Useful if you don't need to create the Sprite instances before-hand.
*
* @method Phaser.Group#create
* @param {number} x - The x coordinate to display the newly created Sprite at. The value is in relation to the Group.x point.
* @param {number} y - The y coordinate to display the newly created Sprite at. The value is in relation to the Group.y point.
* @param {string} key - The Game.cache key of the image that this Sprite will use.
* @param {number|string} [frame] - If the Sprite image contains multiple frames you can specify which one to use here.
* @param {boolean} [exists=true] - The default exists state of the Sprite.
* @return {Phaser.Sprite} The child that was created.
*/
Phaser.Group.prototype.create = function (x, y, key, frame, exists) {
if (typeof exists === 'undefined') { exists = true; }
var child = new Phaser.Sprite(this.game, x, y, key, frame);
child.exists = exists;
child.visible = exists;
child.alive = exists;
this.addChild(child);
if (child.events)
{
child.events.onAddedToGroup.dispatch(child, this);
}
if (this.cursor === null)
{
this.cursor = child;
}
if (this.enableBody)
{
if (this.physicsBodyType === Phaser.Physics.ARCADE)
{
child.body = new Phaser.Physics.Arcade.Body(child);
}
else if (this.physicsBodyType === Phaser.Physics.NINJA && this.game.physics.ninja)
{
child.body = new Phaser.Physics.Ninja.Body(this.game.physics.ninja, child, 1);
}
else if (this.physicsBodyType === Phaser.Physics.P2 && this.game.physics.p2)
{
child.body = new Phaser.Physics.P2.Body(this.game, child, x, y, 1);
}
}
return child;
}
/**
* Automatically creates multiple Phaser.Sprite objects and adds them to the top of this Group.
* Useful if you need to quickly generate a pool of identical sprites, such as bullets. By default the sprites will be set to not exist
* and will be positioned at 0, 0 (relative to the Group.x/y)
*
* @method Phaser.Group#createMultiple
* @param {number} quantity - The number of Sprites to create.
* @param {string} key - The Game.cache key of the image that this Sprite will use.
* @param {number|string} [frame] - If the Sprite image contains multiple frames you can specify which one to use here.
* @param {boolean} [exists=false] - The default exists state of the Sprite.
*/
Phaser.Group.prototype.createMultiple = function (quantity, key, frame, exists) {
if (typeof exists === 'undefined') { exists = false; }
for (var i = 0; i < quantity; i++)
{
this.create(0, 0, key, frame, exists);
}
}
/**
* Advances the Group cursor to the next object in the Group. If it's at the end of the Group it wraps around to the first object.
*
* @method Phaser.Group#next
*/
Phaser.Group.prototype.next = function () {
if (this.cursor)
{
// Wrap the cursor?
if (this._cache[8] === this.children.length)
{
this._cache[8] = 0;
}
else
{
this._cache[8]++;
}
this.cursor = this.children[this._cache[8]];
}
}
/**
* Moves the Group cursor to the previous object in the Group. If it's at the start of the Group it wraps around to the last object.
*
* @method Phaser.Group#previous
*/
Phaser.Group.prototype.previous = function () {
if (this.cursor)
{
// Wrap the cursor?
if (this._cache[8] === 0)
{
this._cache[8] = this.children.length - 1;
}
else
{
this._cache[8]--;
}
this.cursor = this.children[this._cache[8]];
}
}
/**
* Swaps the position of two children in this Group. Both children must be in this Group.
* You cannot swap a child with itself, or swap un-parented children, doing so will return false.
*
* @method Phaser.Group#swap
* @param {*} child1 - The first child to swap.
* @param {*} child2 - The second child to swap.
*/
Phaser.Group.prototype.swap = function (child1, child2) {
return this.swapChildren(child1, child2);
}
/**
* Brings the given child to the top of this Group so it renders above all other children.
*
* @method Phaser.Group#bringToTop
* @param {*} child - The child to bring to the top of this Group.
* @return {*} The child that was moved.
*/
Phaser.Group.prototype.bringToTop = function (child) {
if (child.parent === this && this.getIndex(child) < this.children.length)
{
this.remove(child);
this.add(child);
}
return child;
}
/**
* Sends the given child to the bottom of this Group so it renders below all other children.
*
* @method Phaser.Group#sendToBack
* @param {*} child - The child to send to the bottom of this Group.
* @return {*} The child that was moved.
*/
Phaser.Group.prototype.sendToBack = function (child) {
if (child.parent === this && this.getIndex(child) > 0)
{
this.remove(child);
this.addAt(child, 0);
}
return child;
}
/**
* Moves the given child up one place in this Group unless it's already at the top.
*
* @method Phaser.Group#moveUp
* @param {*} child - The child to move up in the Group.
* @return {*} The child that was moved.
*/
Phaser.Group.prototype.moveUp = function (child) {
if (child.parent === this && this.getIndex(child) < this.children.length - 1)
{
var a = this.getIndex(child);
var b = this.getAt(a + 1);
if (b)
{
this.swap(a, b);
}
}
return child;
}
/**
* Moves the given child down one place in this Group unless it's already at the top.
*
* @method Phaser.Group#moveDown
* @param {*} child - The child to move down in the Group.
* @return {*} The child that was moved.
*/
Phaser.Group.prototype.moveDown = function (child) {
if (child.parent === this && this.getIndex(child) > 0)
{
var a = this.getIndex(child);
var b = this.getAt(a - 1);
if (b)
{
this.swap(a, b);
}
}
return child;
}
/**
* Positions the child found at the given index within this Group to the given x and y coordinates.
*
* @method Phaser.Group#xy
* @param {number} index - The index of the child in the Group to set the position of.
* @param {number} x - The new x position of the child.
* @param {number} y - The new y position of the child.
*/
Phaser.Group.prototype.xy = function (index, x, y) {
if (index < 0 || index > this.children.length)
{
return -1;
}
else
{
this.getChildAt(index).x = x;
this.getChildAt(index).y = y;
}
}
/**
* Reverses all children in this Group. Note that this does not propagate, only direct children are re-ordered.
*
* @method Phaser.Group#reverse
*/
Phaser.Group.prototype.reverse = function () {
this.children.reverse();
}
/**
* Get the index position of the given child in this Group.
*
* @method Phaser.Group#getIndex
* @param {*} child - The child to get the index for.
* @return {number} The index of the child or -1 if it's not a member of this Group.
*/
Phaser.Group.prototype.getIndex = function (child) {
return this.children.indexOf(child);
}
/**
* Replaces a child of this Group with the given newChild. The newChild cannot be a member of this Group.
*
* @method Phaser.Group#replace
* @param {*} oldChild - The child in this Group that will be replaced.
* @param {*} newChild - The child to be inserted into this group.
*/
Phaser.Group.prototype.replace = function (oldChild, newChild) {
var index = this.getIndex(oldChild);
if (index !== -1)
{
if (newChild.parent !== undefined)
{
newChild.events.onRemovedFromGroup.dispatch(newChild, this);
newChild.parent.removeChild(newChild);
}
this.removeChild(oldChild);
this.addChildAt(newChild, index);
newChild.events.onAddedToGroup.dispatch(newChild, this);
if (this.cursor === oldChild)
{
this.cursor = newChild;
}
}
}
/**
* Sets the given property to the given value on the child. The operation controls the assignment of the value.
*
* @method Phaser.Group#setProperty
* @param {*} child - The child to set the property value on.
* @param {array} key - An array of strings that make up the property that will be set.
* @param {*} value - The value that will be set.
* @param {number} [operation=0] - Controls how the value is assigned. A value of 0 replaces the value with the new one. A value of 1 adds it, 2 subtracts it, 3 multiplies it and 4 divides it.
*/
Phaser.Group.prototype.setProperty = function (child, key, value, operation) {
operation = operation || 0;
// As ugly as this approach looks, and although it's limited to a depth of only 4, it's extremely fast.
// Much faster than a for loop or object iteration. There are no checks, so if the key isn't valid then it'll fail
// but as you are likely to call this from inner loops that have to perform well, I'll take that trade off.
// 0 = Equals
// 1 = Add
// 2 = Subtract
// 3 = Multiply
// 4 = Divide
var len = key.length;
if (len == 1)
{
if (operation === 0) { child[key[0]] = value; }
else if (operation == 1) { child[key[0]] += value; }
else if (operation == 2) { child[key[0]] -= value; }
else if (operation == 3) { child[key[0]] *= value; }
else if (operation == 4) { child[key[0]] /= value; }
}
else if (len == 2)
{
if (operation === 0) { child[key[0]][key[1]] = value; }
else if (operation == 1) { child[key[0]][key[1]] += value; }
else if (operation == 2) { child[key[0]][key[1]] -= value; }
else if (operation == 3) { child[key[0]][key[1]] *= value; }
else if (operation == 4) { child[key[0]][key[1]] /= value; }
}
else if (len == 3)
{
if (operation === 0) { child[key[0]][key[1]][key[2]] = value; }
else if (operation == 1) { child[key[0]][key[1]][key[2]] += value; }
else if (operation == 2) { child[key[0]][key[1]][key[2]] -= value; }
else if (operation == 3) { child[key[0]][key[1]][key[2]] *= value; }
else if (operation == 4) { child[key[0]][key[1]][key[2]] /= value; }
}
else if (len == 4)
{
if (operation === 0) { child[key[0]][key[1]][key[2]][key[3]] = value; }
else if (operation == 1) { child[key[0]][key[1]][key[2]][key[3]] += value; }
else if (operation == 2) { child[key[0]][key[1]][key[2]][key[3]] -= value; }
else if (operation == 3) { child[key[0]][key[1]][key[2]][key[3]] *= value; }
else if (operation == 4) { child[key[0]][key[1]][key[2]][key[3]] /= value; }
}
}
/**
* This function allows you to quickly set a property on a single child of this Group to a new value.
* The operation parameter controls how the new value is assigned to the property, from simple replacement to addition and multiplication.
*
* @method Phaser.Group#set
* @param {Phaser.Sprite} child - The child to set the property on.
* @param {string} key - The property, as a string, to be set. For example: 'body.velocity.x'
* @param {*} value - The value that will be set.
* @param {boolean} [checkAlive=false] - If set then the child will only be updated if alive=true.
* @param {boolean} [checkVisible=false] - If set then the child will only be updated if visible=true.
* @param {number} [operation=0] - Controls how the value is assigned. A value of 0 replaces the value with the new one. A value of 1 adds it, 2 subtracts it, 3 multiplies it and 4 divides it.
*/
Phaser.Group.prototype.set = function (child, key, value, checkAlive, checkVisible, operation) {
key = key.split('.');
if (typeof checkAlive === 'undefined') { checkAlive = false; }
if (typeof checkVisible === 'undefined') { checkVisible = false; }
if ((checkAlive === false || (checkAlive && child.alive)) && (checkVisible === false || (checkVisible && child.visible)))
{
this.setProperty(child, key, value, operation);
}
}
/**
* This function allows you to quickly set the same property across all children of this Group to a new value.
* The operation parameter controls how the new value is assigned to the property, from simple replacement to addition and multiplication.
*
* @method Phaser.Group#setAll
* @param {string} key - The property, as a string, to be set. For example: 'body.velocity.x'
* @param {*} value - The value that will be set.
* @param {boolean} [checkAlive=false] - If set then only children with alive=true will be updated.
* @param {boolean} [checkVisible=false] - If set then only children with visible=true will be updated.
* @param {number} [operation=0] - Controls how the value is assigned. A value of 0 replaces the value with the new one. A value of 1 adds it, 2 subtracts it, 3 multiplies it and 4 divides it.
*/
Phaser.Group.prototype.setAll = function (key, value, checkAlive, checkVisible, operation) {
key = key.split('.');
if (typeof checkAlive === 'undefined') { checkAlive = false; }
if (typeof checkVisible === 'undefined') { checkVisible = false; }
operation = operation || 0;
for (var i = 0, len = this.children.length; i < len; i++)
{
if ((!checkAlive || (checkAlive && this.children[i].alive)) && (!checkVisible || (checkVisible && this.children[i].visible)))
{
this.setProperty(this.children[i], key, value, operation);
}
}
}
/**
* Adds the amount to the given property on all children in this Group.
* Group.addAll('x', 10) will add 10 to the child.x value.
*
* @method Phaser.Group#addAll
* @param {string} property - The property to increment, for example 'body.velocity.x' or 'angle'.
* @param {number} amount - The amount to increment the property by. If child.x = 10 then addAll('x', 40) would make child.x = 50.
* @param {boolean} checkAlive - If true the property will only be changed if the child is alive.
* @param {boolean} checkVisible - If true the property will only be changed if the child is visible.
*/
Phaser.Group.prototype.addAll = function (property, amount, checkAlive, checkVisible) {
this.setAll(property, amount, checkAlive, checkVisible, 1);
}
/**
* Subtracts the amount from the given property on all children in this Group.
* Group.subAll('x', 10) will minus 10 from the child.x value.
*
* @method Phaser.Group#subAll
* @param {string} property - The property to decrement, for example 'body.velocity.x' or 'angle'.
* @param {number} amount - The amount to subtract from the property. If child.x = 50 then subAll('x', 40) would make child.x = 10.
* @param {boolean} checkAlive - If true the property will only be changed if the child is alive.
* @param {boolean} checkVisible - If true the property will only be changed if the child is visible.
*/
Phaser.Group.prototype.subAll = function (property, amount, checkAlive, checkVisible) {
this.setAll(property, amount, checkAlive, checkVisible, 2);
}
/**
* Multiplies the given property by the amount on all children in this Group.
* Group.multiplyAll('x', 2) will x2 the child.x value.
*
* @method Phaser.Group#multiplyAll
* @param {string} property - The property to multiply, for example 'body.velocity.x' or 'angle'.
* @param {number} amount - The amount to multiply the property by. If child.x = 10 then multiplyAll('x', 2) would make child.x = 20.
* @param {boolean} checkAlive - If true the property will only be changed if the child is alive.
* @param {boolean} checkVisible - If true the property will only be changed if the child is visible.
*/
Phaser.Group.prototype.multiplyAll = function (property, amount, checkAlive, checkVisible) {
this.setAll(property, amount, checkAlive, checkVisible, 3);
}
/**
* Divides the given property by the amount on all children in this Group.
* Group.divideAll('x', 2) will half the child.x value.
*
* @method Phaser.Group#divideAll
* @param {string} property - The property to divide, for example 'body.velocity.x' or 'angle'.
* @param {number} amount - The amount to divide the property by. If child.x = 100 then divideAll('x', 2) would make child.x = 50.
* @param {boolean} checkAlive - If true the property will only be changed if the child is alive.
* @param {boolean} checkVisible - If true the property will only be changed if the child is visible.
*/
Phaser.Group.prototype.divideAll = function (property, amount, checkAlive, checkVisible) {
this.setAll(property, amount, checkAlive, checkVisible, 4);
}
/**
* Calls a function on all of the children that have exists=true in this Group.
* After the existsValue parameter you can add as many parameters as you like, which will all be passed to the child callback.
*
* @method Phaser.Group#callAllExists
* @param {function} callback - The function that exists on the children that will be called.
* @param {boolean} existsValue - Only children with exists=existsValue will be called.
* @param {...*} parameter - Additional parameters that will be passed to the callback.
*/
Phaser.Group.prototype.callAllExists = function (callback, existsValue) {
var args = Array.prototype.splice.call(arguments, 2);
for (var i = 0, len = this.children.length; i < len; i++)
{
if (this.children[i].exists === existsValue && this.children[i][callback])
{
this.children[i][callback].apply(this.children[i], args);
}
}
}
/**
* Returns a reference to a function that exists on a child of the Group based on the given callback array.
*
* @method Phaser.Group#callbackFromArray
* @param {object} child - The object to inspect.
* @param {array} callback - The array of function names.
* @param {number} length - The size of the array (pre-calculated in callAll).
* @protected
*/
Phaser.Group.prototype.callbackFromArray = function (child, callback, length) {
// Kinda looks like a Christmas tree
if (length == 1)
{
if (child[callback[0]])
{
return child[callback[0]];
}
}
else if (length == 2)
{
if (child[callback[0]][callback[1]])
{
return child[callback[0]][callback[1]];
}
}
else if (length == 3)
{
if (child[callback[0]][callback[1]][callback[2]])
{
return child[callback[0]][callback[1]][callback[2]];
}
}
else if (length == 4)
{
if (child[callback[0]][callback[1]][callback[2]][callback[3]])
{
return child[callback[0]][callback[1]][callback[2]][callback[3]];
}
}
else
{
if (child[callback])
{
return child[callback];
}
}
return false;
}
/**
* Calls a function on all of the children regardless if they are dead or alive (see callAllExists if you need control over that)
* After the method parameter and context you can add as many extra parameters as you like, which will all be passed to the child.
*
* @method Phaser.Group#callAll
* @param {string} method - A string containing the name of the function that will be called. The function must exist on the child.
* @param {string} [context=null] - A string containing the context under which the method will be executed. Set to null to default to the child.
* @param {...*} parameter - Additional parameters that will be passed to the method.
*/
Phaser.Group.prototype.callAll = function (method, context) {
if (typeof method === 'undefined')
{
return;
}
// Extract the method into an array
method = method.split('.');
var methodLength = method.length;
if (typeof context === 'undefined' || context === null || context === '')
{
context = null;
}
else
{
// Extract the context into an array
if (typeof context === 'string')
{
context = context.split('.');
var contextLength = context.length;
}
}
var args = Array.prototype.splice.call(arguments, 2);
var callback = null;
var callbackContext = null;
for (var i = 0, len = this.children.length; i < len; i++)
{
callback = this.callbackFromArray(this.children[i], method, methodLength);
if (context && callback)
{
callbackContext = this.callbackFromArray(this.children[i], context, contextLength);
if (callback)
{
callback.apply(callbackContext, args);
}
}
else if (callback)
{
callback.apply(this.children[i], args);
}
}
}
/**
* The core preUpdate - as called by World.
* @method Phaser.Group#preUpdate
* @protected
*/
Phaser.Group.prototype.preUpdate = function () {
if (!this.exists || !this.parent.exists)
{
this.renderOrderID = -1;
return false;
}
var i = this.children.length;
while (i--)
{
this.children[i].preUpdate();
}
return true;
}
/**
* The core update - as called by World.
* @method Phaser.Group#update
* @protected
*/
Phaser.Group.prototype.update = function () {
var i = this.children.length;
while (i--)
{
this.children[i].update();
}
}
/**
* The core postUpdate - as called by World.
* @method Phaser.Group#postUpdate
* @protected
*/
Phaser.Group.prototype.postUpdate = function () {
// Fixed to Camera?
if (this._cache[7] === 1)
{
this.x = this.game.camera.view.x + this.cameraOffset.x;
this.y = this.game.camera.view.y + this.cameraOffset.y;
}
var i = this.children.length;
while (i--)
{
this.children[i].postUpdate();
}
}
/**
* Allows you to call your own function on each member of this Group. You must pass the callback and context in which it will run.
* After the checkExists parameter you can add as many parameters as you like, which will all be passed to the callback along with the child.
* For example: Group.forEach(awardBonusGold, this, true, 100, 500)
* Note: Currently this will skip any children which are Groups themselves.
*
* @method Phaser.Group#forEach
* @param {function} callback - The function that will be called. Each child of the Group will be passed to it as its first parameter.
* @param {Object} callbackContext - The context in which the function should be called (usually 'this').
* @param {boolean} checkExists - If set only children with exists=true will be passed to the callback, otherwise all children will be passed.
*/
Phaser.Group.prototype.forEach = function (callback, callbackContext, checkExists) {
if (typeof checkExists === 'undefined')
{
checkExists = false;
}
var args = Array.prototype.splice.call(arguments, 3);
args.unshift(null);
for (var i = 0, len = this.children.length; i < len; i++)
{
if (!checkExists || (checkExists && this.children[i].exists))
{
args[0] = this.children[i];
callback.apply(callbackContext, args);
}
}
}
/**
* Allows you to call your own function on each member of this Group where child.exists=true. You must pass the callback and context in which it will run.
* You can add as many parameters as you like, which will all be passed to the callback along with the child.
* For example: Group.forEachExists(causeDamage, this, 500)
*
* @method Phaser.Group#forEachExists
* @param {function} callback - The function that will be called. Each child of the Group will be passed to it as its first parameter.
* @param {Object} callbackContext - The context in which the function should be called (usually 'this').
*/
Phaser.Group.prototype.forEachExists = function (callback, callbackContext) {
var args = Array.prototype.splice.call(arguments, 2);
args.unshift(null);
this.iterate('exists', true, Phaser.Group.RETURN_TOTAL, callback, callbackContext, args);
}
/**
* Allows you to call your own function on each alive member of this Group (where child.alive=true). You must pass the callback and context in which it will run.
* You can add as many parameters as you like, which will all be passed to the callback along with the child.
* For example: Group.forEachAlive(causeDamage, this, 500)
*
* @method Phaser.Group#forEachAlive
* @param {function} callback - The function that will be called. Each child of the Group will be passed to it as its first parameter.
* @param {Object} callbackContext - The context in which the function should be called (usually 'this').
*/
Phaser.Group.prototype.forEachAlive = function (callback, callbackContext) {
var args = Array.prototype.splice.call(arguments, 2);
args.unshift(null);
this.iterate('alive', true, Phaser.Group.RETURN_TOTAL, callback, callbackContext, args);
}
/**
* Allows you to call your own function on each dead member of this Group (where alive=false). You must pass the callback and context in which it will run.
* You can add as many parameters as you like, which will all be passed to the callback along with the child.
* For example: Group.forEachDead(bringToLife, this)
*
* @method Phaser.Group#forEachDead
* @param {function} callback - The function that will be called. Each child of the Group will be passed to it as its first parameter.
* @param {Object} callbackContext - The context in which the function should be called (usually 'this').
*/
Phaser.Group.prototype.forEachDead = function (callback, callbackContext) {
var args = Array.prototype.splice.call(arguments, 2);
args.unshift(null);
this.iterate('alive', false, Phaser.Group.RETURN_TOTAL, callback, callbackContext, args);
}
/**
* Call this function to sort the group according to a particular value and order.
* For example to depth sort Sprites for Zelda-style game you might call `group.sort('y', Phaser.Group.SORT_ASCENDING)` at the bottom of your `State.update()`.
*
* @method Phaser.Group#sort
* @param {string} [index='y'] - The `string` name of the property you want to sort on.
* @param {number} [order=Phaser.Group.SORT_ASCENDING] - The `Group` constant that defines the sort order. Possible values are Phaser.Group.SORT_ASCENDING and Phaser.Group.SORT_DESCENDING.
*/
Phaser.Group.prototype.sort = function (index, order) {
if (typeof index === 'undefined') { index = 'y'; }
if (typeof order === 'undefined') { order = Phaser.Group.SORT_ASCENDING; }
}
Phaser.Group.prototype.sortHandler = function (a, b) {
}
/**
* Iterates over the children of the Group. When a child has a property matching key that equals the given value, it is considered as a match.
* Matched children can be sent to the optional callback, or simply returned or counted.
* You can add as many callback parameters as you like, which will all be passed to the callback along with the child, after the callbackContext parameter.
*
* @method Phaser.Group#iterate
* @param {string} key - The child property to check, i.e. 'exists', 'alive', 'health'
* @param {any} value - If child.key === this value it will be considered a match. Note that a strict comparison is used.
* @param {number} returnType - How to return the data from this method. Either Phaser.Group.RETURN_NONE, Phaser.Group.RETURN_TOTAL or Phaser.Group.RETURN_CHILD.
* @param {function} [callback=null] - Optional function that will be called on each matching child. Each child of the Group will be passed to it as its first parameter.
* @param {Object} [callbackContext] - The context in which the function should be called (usually 'this').
* @return {any} Returns either a numeric total (if RETURN_TOTAL was specified) or the child object.
*/
Phaser.Group.prototype.iterate = function (key, value, returnType, callback, callbackContext, args) {
if (returnType === Phaser.Group.RETURN_TOTAL && this.children.length === 0)
{
return 0;
}
if (typeof callback === 'undefined')
{
callback = false;
}
var total = 0;
for (var i = 0, len = this.children.length; i < len; i++)
{
if (this.children[i][key] === value)
{
total++;
if (callback)
{
args[0] = this.children[i];
callback.apply(callbackContext, args);
}
if (returnType === Phaser.Group.RETURN_CHILD)
{
return this.children[i];
}
}
}
if (returnType === Phaser.Group.RETURN_TOTAL)
{
return total;
}
else if (returnType === Phaser.Group.RETURN_CHILD)
{
return null;
}
}
/**
* Call this function to retrieve the first object with exists == (the given state) in the Group.
*
* @method Phaser.Group#getFirstExists
* @param {boolean} state - True or false.
* @return {Any} The first child, or null if none found.
*/
Phaser.Group.prototype.getFirstExists = function (state) {
if (typeof state !== 'boolean')
{
state = true;
}
return this.iterate('exists', state, Phaser.Group.RETURN_CHILD);
}
/**
* Call this function to retrieve the first object with alive === true in the group.
* This is handy for checking if everything has been wiped out, or choosing a squad leader, etc.
*
* @method Phaser.Group#getFirstAlive
* @return {Any} The first alive child, or null if none found.
*/
Phaser.Group.prototype.getFirstAlive = function () {
return this.iterate('alive', true, Phaser.Group.RETURN_CHILD);
}
/**
* Call this function to retrieve the first object with alive === false in the group.
* This is handy for checking if everything has been wiped out, or choosing a squad leader, etc.
*
* @method Phaser.Group#getFirstDead
* @return {Any} The first dead child, or null if none found.
*/
Phaser.Group.prototype.getFirstDead = function () {
return this.iterate('alive', false, Phaser.Group.RETURN_CHILD);
}
/**
* Call this function to find out how many members of the group are alive.
*
* @method Phaser.Group#countLiving
* @return {number} The number of children flagged as alive.
*/
Phaser.Group.prototype.countLiving = function () {
return this.iterate('alive', true, Phaser.Group.RETURN_TOTAL);
}
/**
* Call this function to find out how many members of the group are dead.
*
* @method Phaser.Group#countDead
* @return {number} The number of children flagged as dead.
*/
Phaser.Group.prototype.countDead = function () {
return this.iterate('alive', false, Phaser.Group.RETURN_TOTAL);
}
/**
* Returns a member at random from the group.
*
* @method Phaser.Group#getRandom
* @param {number} startIndex - Optional offset off the front of the array. Default value is 0, or the beginning of the array.
* @param {number} length - Optional restriction on the number of values you want to randomly select from.
* @return {Any} A random child of this Group.
*/
Phaser.Group.prototype.getRandom = function (startIndex, length) {
if (this.children.length === 0)
{
return null;
}
startIndex = startIndex || 0;
length = length || this.children.length;
return this.game.math.getRandom(this.children, startIndex, length);
}
/**
* Removes the given child from this Group and sets its group property to null.
*
* @method Phaser.Group#remove
* @param {Any} child - The child to remove.
* @return {boolean} true if the child was removed from this Group, otherwise false.
*/
Phaser.Group.prototype.remove = function (child) {
if (this.children.length === 0)
{
return;
}
if (child.events)
{
child.events.onRemovedFromGroup.dispatch(child, this);
}
this.removeChild(child);
if (this.cursor === child)
{
this.next();
}
return true;
}
/**
* Removes all children from this Group, setting all group properties to null.
* The Group container remains on the display list.
*
* @method Phaser.Group#removeAll
*/
Phaser.Group.prototype.removeAll = function () {
if (this.children.length === 0)
{
return;
}
do
{
if (this.children[0].events)
{
this.children[0].events.onRemovedFromGroup.dispatch(this.children[0], this);
}
this.removeChild(this.children[0]);
}
while (this.children.length > 0);
this.cursor = null;
}
/**
* Removes all children from this Group whos index falls beteen the given startIndex and endIndex values.
*
* @method Phaser.Group#removeBetween
* @param {number} startIndex - The index to start removing children from.
* @param {number} endIndex - The index to stop removing children from. Must be higher than startIndex and less than the length of the Group.
*/
Phaser.Group.prototype.removeBetween = function (startIndex, endIndex) {
if (this.children.length === 0)
{
return;
}
if (startIndex > endIndex || startIndex < 0 || endIndex > this.children.length)
{
return false;
}
for (var i = startIndex; i < endIndex; i++)
{
if (this.children[i].events)
{
this.children[i].events.onRemovedFromGroup.dispatch(this.children[i], this);
}
this.removeChild(this.children[i]);
if (this.cursor === child)
{
this.cursor = null;
}
}
}
/**
* Destroys this Group. Removes all children, then removes the container from the display list and nulls references.
*
* @method Phaser.Group#destroy
* @param {boolean} [destroyChildren=true] - Should every child of this Group have its destroy method called?
*/
Phaser.Group.prototype.destroy = function (destroyChildren) {
if (this.game === null) { return; }
if (typeof destroyChildren === 'undefined') { destroyChildren = true; }
if (destroyChildren)
{
if (this.children.length > 0)
{
do
{
if (this.children[0].parent)
{
this.children[0].destroy(destroyChildren);
}
}
while (this.children.length > 0);
}
}
else
{
this.removeAll();
}
this.parent.removeChild(this);
this.game = null;
this.exists = false;
this.cursor = null;
}
/**
* @name Phaser.Group#total
* @property {number} total - The total number of children in this Group who have a state of exists = true.
* @readonly
*/
Object.defineProperty(Phaser.Group.prototype, "total", {
get: function () {
return this.iterate('exists', true, Phaser.Group.RETURN_TOTAL);
}
});
/**
* @name Phaser.Group#length
* @property {number} length - The total number of children in this Group, regardless of their exists/alive status.
* @readonly
*/
Object.defineProperty(Phaser.Group.prototype, "length", {
get: function () {
return this.children.length;
}
});
/**
* The angle of rotation of the Group container. This will adjust the Group container itself by modifying its rotation.
* This will have no impact on the rotation value of its children, but it will update their worldTransform and on-screen position.
* @name Phaser.Group#angle
* @property {number} angle - The angle of rotation given in degrees, where 0 degrees = to the right.
*/
Object.defineProperty(Phaser.Group.prototype, "angle", {
get: function() {
return Phaser.Math.radToDeg(this.rotation);
},
set: function(value) {
this.rotation = Phaser.Math.degToRad(value);
}
});
/**
* A Group that is fixed to the camera uses its x/y coordinates as offsets from the top left of the camera. These are stored in Group.cameraOffset.
* Note that the cameraOffset values are in addition to any parent in the display list.
* So if this Group was in a Group that has x: 200, then this will be added to the cameraOffset.x
*
* @name Phaser.Group#fixedToCamera
* @property {boolean} fixedToCamera - Set to true to fix this Group to the Camera at its current world coordinates.
*/
Object.defineProperty(Phaser.Group.prototype, "fixedToCamera", {
get: function () {
return !!this._cache[7];
},
set: function (value) {
if (value)
{
this._cache[7] = 1;
this.cameraOffset.set(this.x, this.y);
}
else
{
this._cache[7] = 0;
}
}
});
// Documentation stubs
/**
* The x coordinate of the Group container. You can adjust the Group container itself by modifying its coordinates.
* This will have no impact on the x/y coordinates of its children, but it will update their worldTransform and on-screen position.
* @name Phaser.Group#x
* @property {number} x - The x coordinate of the Group container.
*/
/**
* The y coordinate of the Group container. You can adjust the Group container itself by modifying its coordinates.
* This will have no impact on the x/y coordinates of its children, but it will update their worldTransform and on-screen position.
* @name Phaser.Group#y
* @property {number} y - The y coordinate of the Group container.
*/
/**
* The angle of rotation of the Group container. This will adjust the Group container itself by modifying its rotation.
* This will have no impact on the rotation value of its children, but it will update their worldTransform and on-screen position.
* @name Phaser.Group#rotation
* @property {number} rotation - The angle of rotation given in radians.
*/
/**
* @name Phaser.Group#visible
* @property {boolean} visible - The visible state of the Group. Non-visible Groups and all of their children are not rendered.
*/
/**
* @name Phaser.Group#alpha
* @property {number} alpha - The alpha value of the Group container.
*/
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2014 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* "This world is but a canvas to our imagination." - Henry David Thoreau
*
* A game has only one world. The world is an abstract place in which all game objects live. It is not bound
* by stage limits and can be any size. You look into the world via cameras. All game objects live within
* the world at world-based coordinates. By default a world is created the same size as your Stage.
*
* @class Phaser.World
* @extends Phaser.Group
* @constructor
* @param {Phaser.Game} game - Reference to the current game instance.
*/
Phaser.World = function (game) {
Phaser.Group.call(this, game, null, '__world', false);
/**
* The World has no fixed size, but it does have a bounds outside of which objects are no longer considered as being "in world" and you should use this to clean-up the display list and purge dead objects.
* By default we set the Bounds to be from 0,0 to Game.width,Game.height. I.e. it will match the size given to the game constructor with 0,0 representing the top-left of the display.
* However 0,0 is actually the center of the world, and if you rotate or scale the world all of that will happen from 0,0.
* So if you want to make a game in which the world itself will rotate you should adjust the bounds so that 0,0 is the center point, i.e. set them to -1000,-1000,2000,2000 for a 2000x2000 sized world centered around 0,0.
* @property {Phaser.Rectangle} bounds - Bound of this world that objects can not escape from.
*/
this.bounds = new Phaser.Rectangle(0, 0, game.width, game.height);
/**
* @property {Phaser.Camera} camera - Camera instance.
*/
this.camera = null;
}
Phaser.World.prototype = Object.create(Phaser.Group.prototype);
Phaser.World.prototype.constructor = Phaser.World;
/**
* Initialises the game world.
*
* @method Phaser.World#boot
* @protected
*/
Phaser.World.prototype.boot = function () {
this.camera = new Phaser.Camera(this.game, 0, 0, 0, this.game.width, this.game.height);
this.camera.displayObject = this;
this.camera.scale = this.scale;
this.game.camera = this.camera;
this.game.stage.addChild(this);
}
/**
* Updates the size of this world. Note that this doesn't modify the world x/y coordinates, just the width and height.
*
* @method Phaser.World#setBounds
* @param {number} x - Top left most corner of the world.
* @param {number} y - Top left most corner of the world.
* @param {number} width - New width of the world. Can never be smaller than the Game.width.
* @param {number} height - New height of the world. Can never be smaller than the Game.height.
*/
Phaser.World.prototype.setBounds = function (x, y, width, height) {
if (width < this.game.width)
{
width = this.game.width;
}
if (height < this.game.height)
{
height = this.game.height;
}
this.bounds.setTo(x, y, width, height);
if (this.camera.bounds)
{
// The Camera can never be smaller than the game size
this.camera.bounds.setTo(x, y, width, height);
}
if (this.game.physics)
{
this.game.physics.setBoundsToWorld();
}
}
/**
* Destroyer of worlds.
* @method Phaser.World#destroy
*/
Phaser.World.prototype.destroy = function () {
this.camera.reset();
this.game.input.reset(true);
this.removeAll();
}
/**
* @name Phaser.World#width
* @property {number} width - Gets or sets the current width of the game world.
*/
Object.defineProperty(Phaser.World.prototype, "width", {
get: function () {
return this.bounds.width;
},
set: function (value) {
this.bounds.width = value;
}
});
/**
* @name Phaser.World#height
* @property {number} height - Gets or sets the current height of the game world.
*/
Object.defineProperty(Phaser.World.prototype, "height", {
get: function () {
return this.bounds.height;
},
set: function (value) {
this.bounds.height = value;
}
});
/**
* @name Phaser.World#centerX
* @property {number} centerX - Gets the X position corresponding to the center point of the world.
* @readonly
*/
Object.defineProperty(Phaser.World.prototype, "centerX", {
get: function () {
return this.bounds.halfWidth;
}
});
/**
* @name Phaser.World#centerY
* @property {number} centerY - Gets the Y position corresponding to the center point of the world.
* @readonly
*/
Object.defineProperty(Phaser.World.prototype, "centerY", {
get: function () {
return this.bounds.halfHeight;
}
});
/**
* @name Phaser.World#randomX
* @property {number} randomX - Gets a random integer which is lesser than or equal to the current width of the game world.
* @readonly
*/
Object.defineProperty(Phaser.World.prototype, "randomX", {
get: function () {
if (this.bounds.x < 0)
{
return this.game.rnd.integerInRange(this.bounds.x, (this.bounds.width - Math.abs(this.bounds.x)));
}
else
{
return this.game.rnd.integerInRange(this.bounds.x, this.bounds.width);
}
}
});
/**
* @name Phaser.World#randomY
* @property {number} randomY - Gets a random integer which is lesser than or equal to the current height of the game world.
* @readonly
*/
Object.defineProperty(Phaser.World.prototype, "randomY", {
get: function () {
if (this.bounds.y < 0)
{
return this.game.rnd.integerInRange(this.bounds.y, (this.bounds.height - Math.abs(this.bounds.y)));
}
else
{
return this.game.rnd.integerInRange(this.bounds.y, this.bounds.height);
}
}
});
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2014 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* The ScaleManager object is responsible for helping you manage the scaling, resizing and alignment of your game within the browser.
*
* @class Phaser.ScaleManager
* @constructor
* @param {Phaser.Game} game - A reference to the currently running game.
* @param {number} width - The native width of the game.
* @param {number} height - The native height of the game.
*/
Phaser.ScaleManager = function (game, width, height) {
/**
* @property {Phaser.Game} game - A reference to the currently running game.
*/
this.game = game;
/**
* @property {number} width - Width of the stage after calculation.
*/
this.width = width;
/**
* @property {number} height - Height of the stage after calculation.
*/
this.height = height;
/**
* @property {number} minWidth - Minimum width the canvas should be scaled to (in pixels).
*/
this.minWidth = null;
/**
* @property {number} maxWidth - Maximum width the canvas should be scaled to (in pixels). If null it will scale to whatever width the browser can handle.
*/
this.maxWidth = null;
/**
* @property {number} minHeight - Minimum height the canvas should be scaled to (in pixels).
*/
this.minHeight = null;
/**
* @property {number} maxHeight - Maximum height the canvas should be scaled to (in pixels). If null it will scale to whatever height the browser can handle.
*/
this.maxHeight = null;
/**
* @property {boolean} forceLandscape - If the game should be forced to use Landscape mode, this is set to true by Game.Stage
* @default
*/
this.forceLandscape = false;
/**
* @property {boolean} forcePortrait - If the game should be forced to use Portrait mode, this is set to true by Game.Stage
* @default
*/
this.forcePortrait = false;
/**
* @property {boolean} incorrectOrientation - If the game should be forced to use a specific orientation and the device currently isn't in that orientation this is set to true.
* @default
*/
this.incorrectOrientation = false;
/**
* @property {boolean} pageAlignHorizontally - If you wish to align your game in the middle of the page then you can set this value to true.
* It will place a re-calculated margin-left pixel value onto the canvas element which is updated on orientation/resizing.
* It doesn't care about any other DOM element that may be on the page, it literally just sets the margin.
* @default
*/
this.pageAlignHorizontally = false;
/**
* @property {boolean} pageAlignVertically - If you wish to align your game in the middle of the page then you can set this value to true.
* It will place a re-calculated margin-left pixel value onto the canvas element which is updated on orientation/resizing.
* It doesn't care about any other DOM element that may be on the page, it literally just sets the margin.
* @default
*/
this.pageAlignVertically = false;
/**
* @property {number} maxIterations - The maximum number of times it will try to resize the canvas to fill the browser.
* @default
*/
this.maxIterations = 5;
/**
* @property {PIXI.Sprite} orientationSprite - The Sprite that is optionally displayed if the browser enters an unsupported orientation.
*/
this.orientationSprite = null;
/**
* @property {Phaser.Signal} enterLandscape - The event that is dispatched when the browser enters landscape orientation.
*/
this.enterLandscape = new Phaser.Signal();
/**
* @property {Phaser.Signal} enterPortrait - The event that is dispatched when the browser enters horizontal orientation.
*/
this.enterPortrait = new Phaser.Signal();
/**
* @property {Phaser.Signal} enterIncorrectOrientation - The event that is dispatched when the browser enters an incorrect orientation, as defined by forceOrientation.
*/
this.enterIncorrectOrientation = new Phaser.Signal();
/**
* @property {Phaser.Signal} leaveIncorrectOrientation - The event that is dispatched when the browser leaves an incorrect orientation, as defined by forceOrientation.
*/
this.leaveIncorrectOrientation = new Phaser.Signal();
/**
* @property {Phaser.Signal} hasResized - The event that is dispatched when the game scale changes.
*/
this.hasResized = new Phaser.Signal();
/**
* This is the DOM element that will have the Full Screen mode called on it. It defaults to the game canvas, but can be retargetted to any valid DOM element.
* If you adjust this property it's up to you to see it has the correct CSS applied, and that you have contained the game canvas correctly.
* Note that if you use a scale property of EXACT_FIT then fullScreenTarget will have its width and height style set to 100%.
* @property {any} fullScreenTarget
*/
this.fullScreenTarget = this.game.canvas;
/**
* @property {Phaser.Signal} enterFullScreen - The event that is dispatched when the browser enters full screen mode (if it supports the FullScreen API).
*/
this.enterFullScreen = new Phaser.Signal();
/**
* @property {Phaser.Signal} leaveFullScreen - The event that is dispatched when the browser leaves full screen mode (if it supports the FullScreen API).
*/
this.leaveFullScreen = new Phaser.Signal();
/**
* @property {number} orientation - The orientation value of the game (as defined by window.orientation if set). 90 = landscape. 0 = portrait.
*/
this.orientation = 0;
if (window['orientation'])
{
this.orientation = window['orientation'];
}
else
{
if (window.outerWidth > window.outerHeight)
{
this.orientation = 90;
}
}
/**
* @property {Phaser.Point} scaleFactor - The scale factor based on the game dimensions vs. the scaled dimensions.
* @readonly
*/
this.scaleFactor = new Phaser.Point(1, 1);
/**
* @property {Phaser.Point} scaleFactorInversed - The inversed scale factor. The displayed dimensions divided by the game dimensions.
* @readonly
*/
this.scaleFactorInversed = new Phaser.Point(1, 1);
/**
* @property {Phaser.Point} margin - If the game canvas is seto to align by adjusting the margin, the margin calculation values are stored in this Point.
* @readonly
*/
this.margin = new Phaser.Point(0, 0);
/**
* @property {number} aspectRatio - The aspect ratio of the scaled game.
* @readonly
*/
this.aspectRatio = 0;
/**
* @property {number} sourceAspectRatio - The aspect ratio (width / height) of the original game dimensions.
* @readonly
*/
this.sourceAspectRatio = width / height;
/**
* @property {any} event- The native browser events from full screen API changes.
*/
this.event = null;
/**
* @property {number} scaleMode - The current scaleMode.
*/
this.scaleMode = Phaser.ScaleManager.NO_SCALE;
/*
* @property {number} fullScreenScaleMode - Scale mode to be used in fullScreen
*/
this.fullScreenScaleMode = Phaser.ScaleManager.NO_SCALE;
/**
* @property {number} _startHeight - Internal cache var. Stage height when starting the game.
* @private
*/
this._startHeight = 0;
/**
* @property {number} _width - Cached stage width for full screen mode.
* @private
*/
this._width = 0;
/**
* @property {number} _height - Cached stage height for full screen mode.
* @private
*/
this._height = 0;
var _this = this;
window.addEventListener('orientationchange', function (event) {
return _this.checkOrientation(event);
}, false);
window.addEventListener('resize', function (event) {
return _this.checkResize(event);
}, false);
document.addEventListener('webkitfullscreenchange', function (event) {
return _this.fullScreenChange(event);
}, false);
document.addEventListener('mozfullscreenchange', function (event) {
return _this.fullScreenChange(event);
}, false);
document.addEventListener('fullscreenchange', function (event) {
return _this.fullScreenChange(event);
}, false);
};
/**
* @constant
* @type {number}
*/
Phaser.ScaleManager.EXACT_FIT = 0;
/**
* @constant
* @type {number}
*/
Phaser.ScaleManager.NO_SCALE = 1;
/**
* @constant
* @type {number}
*/
Phaser.ScaleManager.SHOW_ALL = 2;
Phaser.ScaleManager.prototype = {
/**
* Tries to enter the browser into full screen mode.
* Please note that this needs to be supported by the web browser and isn't the same thing as setting your game to fill the browser.
* @method Phaser.ScaleManager#startFullScreen
* @param {boolean} antialias - You can toggle the anti-alias feature of the canvas before jumping in to full screen (false = retain pixel art, true = smooth art)
*/
startFullScreen: function (antialias) {
if (this.isFullScreen || !this.game.device.fullscreen)
{
return;
}
if (typeof antialias !== 'undefined' && this.game.renderType === Phaser.CANVAS)
{
this.game.stage.smoothed = antialias;
}
this._width = this.width;
this._height = this.height;
if (this.game.device.fullscreenKeyboard)
{
this.fullScreenTarget[this.game.device.requestFullscreen](Element.ALLOW_KEYBOARD_INPUT);
}
else
{
this.fullScreenTarget[this.game.device.requestFullscreen]();
}
},
/**
* Stops full screen mode if the browser is in it.
* @method Phaser.ScaleManager#stopFullScreen
*/
stopFullScreen: function () {
this.fullScreenTarget[this.game.device.cancelFullscreen]();
},
/**
* Called automatically when the browser enters of leaves full screen mode.
* @method Phaser.ScaleManager#fullScreenChange
* @param {Event} event - The fullscreenchange event
* @protected
*/
fullScreenChange: function (event) {
this.event = event;
if (this.isFullScreen)
{
if (this.fullScreenScaleMode === Phaser.ScaleManager.EXACT_FIT)
{
this.fullScreenTarget.style['width'] = '100%';
this.fullScreenTarget.style['height'] = '100%';
this.width = window.outerWidth;
this.height = window.outerHeight;
this.game.input.scale.setTo(this.game.width / this.width, this.game.height / this.height);
this.aspectRatio = this.width / this.height;
this.scaleFactor.x = this.game.width / this.width;
this.scaleFactor.y = this.game.height / this.height;
this.checkResize();
}
else if (this.fullScreenScaleMode === Phaser.ScaleManager.SHOW_ALL)
{
this.setShowAll();
this.refresh();
}
this.enterFullScreen.dispatch(this.width, this.height);
}
else
{
this.fullScreenTarget.style['width'] = this.game.width + 'px';
this.fullScreenTarget.style['height'] = this.game.height + 'px';
this.width = this._width;
this.height = this._height;
this.game.input.scale.setTo(this.game.width / this.width, this.game.height / this.height);
this.aspectRatio = this.width / this.height;
this.scaleFactor.x = this.game.width / this.width;
this.scaleFactor.y = this.game.height / this.height;
this.leaveFullScreen.dispatch(this.width, this.height);
}
},
/**
* If you need your game to run in only one orientation you can force that to happen.
* The optional orientationImage is displayed when the game is in the incorrect orientation.
* @method Phaser.ScaleManager#forceOrientation
* @param {boolean} forceLandscape - true if the game should run in landscape mode only.
* @param {boolean} [forcePortrait=false] - true if the game should run in portrait mode only.
* @param {string} [orientationImage=''] - The string of an image in the Phaser.Cache to display when this game is in the incorrect orientation.
*/
forceOrientation: function (forceLandscape, forcePortrait, orientationImage) {
if (typeof forcePortrait === 'undefined') { forcePortrait = false; }
this.forceLandscape = forceLandscape;
this.forcePortrait = forcePortrait;
if (typeof orientationImage !== 'undefined')
{
if (orientationImage == null || this.game.cache.checkImageKey(orientationImage) === false)
{
orientationImage = '__default';
}
this.orientationSprite = new PIXI.Sprite(PIXI.TextureCache[orientationImage]);
this.orientationSprite.anchor.x = 0.5;
this.orientationSprite.anchor.y = 0.5;
this.orientationSprite.position.x = this.game.width / 2;
this.orientationSprite.position.y = this.game.height / 2;
this.checkOrientationState();
if (this.incorrectOrientation)
{
this.orientationSprite.visible = true;
this.game.world.visible = false;
}
else
{
this.orientationSprite.visible = false;
this.game.world.visible = true;
}
this.game.stage.addChild(this.orientationSprite);
}
},
/**
* Checks if the browser is in the correct orientation for your game (if forceLandscape or forcePortrait have been set)
* @method Phaser.ScaleManager#checkOrientationState
*/
checkOrientationState: function () {
// They are in the wrong orientation
if (this.incorrectOrientation)
{
if ((this.forceLandscape && window.innerWidth > window.innerHeight) || (this.forcePortrait && window.innerHeight > window.innerWidth))
{
// Back to normal
this.incorrectOrientation = false;
this.leaveIncorrectOrientation.dispatch();
if (this.orientationSprite)
{
this.orientationSprite.visible = false;
this.game.world.visible = true;
}
if (this.scaleMode !== Phaser.ScaleManager.NO_SCALE)
{
this.refresh();
}
}
}
else
{
if ((this.forceLandscape && window.innerWidth < window.innerHeight) || (this.forcePortrait && window.innerHeight < window.innerWidth))
{
// Show orientation screen
this.incorrectOrientation = true;
this.enterIncorrectOrientation.dispatch();
if (this.orientationSprite && this.orientationSprite.visible === false)
{
this.orientationSprite.visible = true;
this.game.world.visible = false;
}
if (this.scaleMode !== Phaser.ScaleManager.NO_SCALE)
{
this.refresh();
}
}
}
},
/**
* Handle window.orientationchange events
* @method Phaser.ScaleManager#checkOrientation
* @param {Event} event - The orientationchange event data.
*/
checkOrientation: function (event) {
this.event = event;
this.orientation = window['orientation'];
if (this.isLandscape)
{
this.enterLandscape.dispatch(this.orientation, true, false);
}
else
{
this.enterPortrait.dispatch(this.orientation, false, true);
}
if (this.scaleMode !== Phaser.ScaleManager.NO_SCALE)
{
this.refresh();
}
},
/**
* Handle window.resize events
* @method Phaser.ScaleManager#checkResize
* @param {Event} event - The resize event data.
*/
checkResize: function (event) {
this.event = event;
if (window.outerWidth > window.outerHeight)
{
this.orientation = 90;
}
else
{
this.orientation = 0;
}
if (this.isLandscape)
{
this.enterLandscape.dispatch(this.orientation, true, false);
}
else
{
this.enterPortrait.dispatch(this.orientation, false, true);
}
if (this.scaleMode !== Phaser.ScaleManager.NO_SCALE)
{
this.refresh();
}
this.checkOrientationState();
},
/**
* Re-calculate scale mode and update screen size.
* @method Phaser.ScaleManager#refresh
*/
refresh: function () {
// We can't do anything about the status bars in iPads, web apps or desktops
if (this.game.device.iPad === false && this.game.device.webApp === false && this.game.device.desktop === false)
{
if (this.game.device.android && this.game.device.chrome === false)
{
window.scrollTo(0, 1);
}
else
{
window.scrollTo(0, 0);
}
}
if (this._check == null && this.maxIterations > 0)
{
this._iterations = this.maxIterations;
var _this = this;
this._check = window.setInterval(function () {
return _this.setScreenSize();
}, 10);
this.setScreenSize();
}
},
/**
* Set screen size automatically based on the scaleMode.
* @param {boolean} force - If force is true it will try to resize the game regardless of the document dimensions.
*/
setScreenSize: function (force) {
if (typeof force == 'undefined')
{
force = false;
}
if (this.game.device.iPad === false && this.game.device.webApp === false && this.game.device.desktop === false)
{
if (this.game.device.android && this.game.device.chrome === false)
{
window.scrollTo(0, 1);
}
else
{
window.scrollTo(0, 0);
}
}
this._iterations--;
if (force || window.innerHeight > this._startHeight || this._iterations < 0)
{
// Set minimum height of content to new window height
document.documentElement['style'].minHeight = window.innerHeight + 'px';
if (this.incorrectOrientation === true)
{
this.setMaximum();
}
else if (!this.isFullScreen)
{
if (this.scaleMode == Phaser.ScaleManager.EXACT_FIT)
{
this.setExactFit();
}
else if (this.scaleMode == Phaser.ScaleManager.SHOW_ALL)
{
this.setShowAll();
}
}
else
{
if (this.fullScreenScaleMode == Phaser.ScaleManager.EXACT_FIT)
{
this.setExactFit();
}
else if (this.fullScreenScaleMode == Phaser.ScaleManager.SHOW_ALL)
{
this.setShowAll();
}
}
this.setSize();
clearInterval(this._check);
this._check = null;
}
},
/**
* Sets the canvas style width and height values based on minWidth/Height and maxWidth/Height.
* @method Phaser.ScaleManager#setSize
*/
setSize: function () {
if (this.incorrectOrientation === false)
{
if (this.maxWidth && this.width > this.maxWidth)
{
this.width = this.maxWidth;
}
if (this.maxHeight && this.height > this.maxHeight)
{
this.height = this.maxHeight;
}
if (this.minWidth && this.width < this.minWidth)
{
this.width = this.minWidth;
}
if (this.minHeight && this.height < this.minHeight)
{
this.height = this.minHeight;
}
}
this.game.canvas.style.width = this.width + 'px';
this.game.canvas.style.height = this.height + 'px';
this.game.input.scale.setTo(this.game.width / this.width, this.game.height / this.height);
if (this.pageAlignHorizontally)
{
if (this.width < window.innerWidth && this.incorrectOrientation === false)
{
this.margin.x = Math.round((window.innerWidth - this.width) / 2);
this.game.canvas.style.marginLeft = this.margin.x + 'px';
}
else
{
this.margin.x = 0;
this.game.canvas.style.marginLeft = '0px';
}
}
if (this.pageAlignVertically)
{
if (this.height < window.innerHeight && this.incorrectOrientation === false)
{
this.margin.y = Math.round((window.innerHeight - this.height) / 2);
this.game.canvas.style.marginTop = this.margin.y + 'px';
}
else
{
this.margin.y = 0;
this.game.canvas.style.marginTop = '0px';
}
}
Phaser.Canvas.getOffset(this.game.canvas, this.game.stage.offset);
this.aspectRatio = this.width / this.height;
this.scaleFactor.x = this.game.width / this.width;
this.scaleFactor.y = this.game.height / this.height;
this.scaleFactorInversed.x = this.width / this.game.width;
this.scaleFactorInversed.y = this.height / this.game.height;
this.hasResized.dispatch(this.width, this.height);
this.checkOrientationState();
},
/**
* Sets this.width equal to window.innerWidth and this.height equal to window.innerHeight
* @method Phaser.ScaleManager#setMaximum
*/
setMaximum: function () {
this.width = window.innerWidth;
this.height = window.innerHeight;
},
/**
* Calculates the multiplier needed to scale the game proportionally.
* @method Phaser.ScaleManager#setShowAll
*/
setShowAll: function () {
var multiplier = Math.min((window.innerHeight / this.game.height), (window.innerWidth / this.game.width));
this.width = Math.round(this.game.width * multiplier);
this.height = Math.round(this.game.height * multiplier);
},
/**
* Sets the width and height values of the canvas, no larger than the maxWidth/Height.
* @method Phaser.ScaleManager#setExactFit
*/
setExactFit: function () {
var availableWidth = window.innerWidth;
var availableHeight = window.innerHeight;
if (this.maxWidth && availableWidth > this.maxWidth)
{
this.width = this.maxWidth;
}
else
{
this.width = availableWidth;
}
if (this.maxHeight && availableHeight > this.maxHeight)
{
this.height = this.maxHeight;
}
else
{
this.height = availableHeight;
}
}
};
Phaser.ScaleManager.prototype.constructor = Phaser.ScaleManager;
/**
* @name Phaser.ScaleManager#isFullScreen
* @property {boolean} isFullScreen - Returns true if the browser is in full screen mode, otherwise false.
* @readonly
*/
Object.defineProperty(Phaser.ScaleManager.prototype, "isFullScreen", {
get: function () {
return (document['fullscreenElement'] || document['mozFullScreenElement'] || document['webkitFullscreenElement'])
}
});
/**
* @name Phaser.ScaleManager#isPortrait
* @property {boolean} isPortrait - Returns true if the browser dimensions match a portrait display.
* @readonly
*/
Object.defineProperty(Phaser.ScaleManager.prototype, "isPortrait", {
get: function () {
return this.orientation === 0 || this.orientation == 180;
}
});
/**
* @name Phaser.ScaleManager#isLandscape
* @property {boolean} isLandscape - Returns true if the browser dimensions match a landscape display.
* @readonly
*/
Object.defineProperty(Phaser.ScaleManager.prototype, "isLandscape", {
get: function () {
return this.orientation === 90 || this.orientation === -90;
}
});
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2014 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* Game constructor
*
* Instantiate a new <code>Phaser.Game</code> object.
* @class Phaser.Game
* @classdesc This is where the magic happens. The Game object is the heart of your game,
* providing quick access to common functions and handling the boot process.
* "Hell, there are no rules here - we're trying to accomplish something."
* Thomas A. Edison
* @constructor
* @param {number} [width=800] - The width of your game in game pixels.
* @param {number} [height=600] - The height of your game in game pixels.
* @param {number} [renderer=Phaser.AUTO] - Which renderer to use: Phaser.AUTO will auto-detect, Phaser.WEBGL, Phaser.CANVAS or Phaser.HEADLESS (no rendering at all).
* @param {string|HTMLElement} [parent=''] - The DOM element into which this games canvas will be injected. Either a DOM ID (string) or the element itself.
* @param {object} [state=null] - The default state object. A object consisting of Phaser.State functions (preload, create, update, render) or null.
* @param {boolean} [transparent=false] - Use a transparent canvas background or not.
* @param {boolean} [antialias=true] - Draw all image textures anti-aliased or not. The default is for smooth textures, but disable if your game features pixel art.
* @param {object} [physicsConfig=null] - A physics configuration object to pass to the Physics world on creation.
*/
Phaser.Game = function (width, height, renderer, parent, state, transparent, antialias, physicsConfig) {
/**
* @property {number} id - Phaser Game ID (for when Pixi supports multiple instances).
*/
this.id = Phaser.GAMES.push(this) - 1;
/**
* @property {object} config - The Phaser.Game configuration object.
*/
this.config = null;
/**
* @property {object} physicsConfig - The Phaser.Physics.World configuration object.
*/
this.physicsConfig = physicsConfig;
/**
* @property {HTMLElement} parent - The Games DOM parent.
* @default
*/
this.parent = '';
/**
* @property {number} width - The Game width (in pixels).
* @default
*/
this.width = 800;
/**
* @property {number} height - The Game height (in pixels).
* @default
*/
this.height = 600;
/**
* @property {boolean} transparent - Use a transparent canvas background or not.
* @default
*/
this.transparent = false;
/**
* @property {boolean} antialias - Anti-alias graphics. By default scaled images are smoothed in Canvas and WebGL, set anti-alias to false to disable this globally.
* @default
*/
this.antialias = true;
/**
* @property {number} renderer - The Pixi Renderer
* @default
*/
this.renderer = Phaser.AUTO;
/**
* @property {number} renderType - The Renderer this game will use. Either Phaser.AUTO, Phaser.CANVAS or Phaser.WEBGL.
*/
this.renderType = Phaser.AUTO;
/**
* @property {number} state - The StateManager.
*/
this.state = null;
/**
* @property {boolean} isBooted - Whether the game engine is booted, aka available.
* @default
*/
this.isBooted = false;
/**
* @property {boolean} id -Is game running or paused?
* @default
*/
this.isRunning = false;
/**
* @property {Phaser.RequestAnimationFrame} raf - Automatically handles the core game loop via requestAnimationFrame or setTimeout
*/
this.raf = null;
/**
* @property {Phaser.GameObjectFactory} add - Reference to the Phaser.GameObjectFactory.
*/
this.add = null;
/**
* @property {Phaser.GameObjectCreator} make - Reference to the GameObject Creator.
*/
this.make = null;
/**
* @property {Phaser.Cache} cache - Reference to the assets cache.
* @default
*/
this.cache = null;
/**
* @property {Phaser.Input} input - Reference to the input manager
* @default
*/
this.input = null;
/**
* @property {Phaser.Loader} load - Reference to the assets loader.
* @default
*/
this.load = null;
/**
* @property {Phaser.Math} math - Reference to the math helper.
*/
this.math = null;
/**
* @property {Phaser.Net} net - Reference to the network class.
*/
this.net = null;
/**
* @property {Phaser.ScaleManager} scale - The game scale manager.
*/
this.scale = null;
/**
* @property {Phaser.SoundManager} sound - Reference to the sound manager.
*/
this.sound = null;
/**
* @property {Phaser.Stage} stage - Reference to the stage.
*/
this.stage = null;
/**
* @property {Phaser.TimeManager} time - Reference to game clock.
*/
this.time = null;
/**
* @property {Phaser.TweenManager} tweens - Reference to the tween manager.
*/
this.tweens = null;
/**
* @property {Phaser.World} world - Reference to the world.
*/
this.world = null;
/**
* @property {Phaser.Physics} physics - Reference to the physics manager.
*/
this.physics = null;
/**
* @property {Phaser.RandomDataGenerator} rnd - Instance of repeatable random data generator helper.
*/
this.rnd = null;
/**
* @property {Phaser.Device} device - Contains device information and capabilities.
*/
this.device = null;
/**
* @property {Phaser.Physics.PhysicsManager} camera - A handy reference to world.camera.
*/
this.camera = null;
/**
* @property {HTMLCanvasElement} canvas - A handy reference to renderer.view, the canvas that the game is being rendered in to.
*/
this.canvas = null;
/**
* @property {CanvasRenderingContext2D} context - A handy reference to renderer.context (only set for CANVAS games, not WebGL)
*/
this.context = null;
/**
* @property {Phaser.Utils.Debug} debug - A set of useful debug utilitie.
*/
this.debug = null;
/**
* @property {Phaser.Particles} particles - The Particle Manager.
*/
this.particles = null;
/**
* @property {boolean} stepping - Enable core loop stepping with Game.enableStep().
* @default
* @readonly
*/
this.stepping = false;
/**
* @property {boolean} stepping - An internal property used by enableStep, but also useful to query from your own game objects.
* @default
* @readonly
*/
this.pendingStep = false;
/**
* @property {number} stepCount - When stepping is enabled this contains the current step cycle.
* @default
* @readonly
*/
this.stepCount = 0;
/**
* @property {boolean} _paused - Is game paused?
* @private
* @default
*/
this._paused = false;
/**
* @property {boolean} _codePaused - Was the game paused via code or a visibility change?
* @private
* @default
*/
this._codePaused = false;
// Parse the configuration object (if any)
if (arguments.length === 1 && typeof arguments[0] === 'object')
{
this.parseConfig(arguments[0]);
}
else
{
if (typeof width !== 'undefined')
{
this.width = width;
}
if (typeof height !== 'undefined')
{
this.height = height;
}
if (typeof renderer !== 'undefined')
{
this.renderer = renderer;
this.renderType = renderer;
}
if (typeof parent !== 'undefined')
{
this.parent = parent;
}
if (typeof transparent !== 'undefined')
{
this.transparent = transparent;
}
if (typeof antialias !== 'undefined')
{
this.antialias = antialias;
}
this.state = new Phaser.StateManager(this, state);
}
var _this = this;
this._onBoot = function () {
return _this.boot();
}
if (document.readyState === 'complete' || document.readyState === 'interactive')
{
window.setTimeout(this._onBoot, 0);
}
else
{
document.addEventListener('DOMContentLoaded', this._onBoot, false);
window.addEventListener('load', this._onBoot, false);
}
return this;
};
Phaser.Game.prototype = {
/**
* Parses a Game configuration object.
*
* @method Phaser.Game#parseConfig
* @protected
*/
parseConfig: function (config) {
this.config = config;
if (config['width'])
{
this.width = Phaser.Utils.parseDimension(config['width'], 0);
}
if (config['height'])
{
this.height = Phaser.Utils.parseDimension(config['height'], 1);
}
if (config['renderer'])
{
this.renderer = config['renderer'];
this.renderType = config['renderer'];
}
if (config['parent'])
{
this.parent = config['parent'];
}
if (config['transparent'])
{
this.transparent = config['transparent'];
}
if (config['antialias'])
{
this.antialias = config['antialias'];
}
if (config['physicsConfig'])
{
this.physicsConfig = config['physicsConfig'];
}
var state = null;
if (config['state'])
{
state = config['state'];
}
this.state = new Phaser.StateManager(this, state);
},
/**
* Initialize engine sub modules and start the game.
*
* @method Phaser.Game#boot
* @protected
*/
boot: function () {
if (this.isBooted)
{
return;
}
if (!document.body)
{
window.setTimeout(this._onBoot, 20);
}
else
{
document.removeEventListener('DOMContentLoaded', this._onBoot);
window.removeEventListener('load', this._onBoot);
this.onPause = new Phaser.Signal();
this.onResume = new Phaser.Signal();
this.isBooted = true;
this.device = new Phaser.Device(this);
this.math = Phaser.Math;
this.rnd = new Phaser.RandomDataGenerator([(Date.now() * Math.random()).toString()]);
this.stage = new Phaser.Stage(this, this.width, this.height);
this.scale = new Phaser.ScaleManager(this, this.width, this.height);
this.setUpRenderer();
this.device.checkFullScreenSupport();
this.world = new Phaser.World(this);
this.add = new Phaser.GameObjectFactory(this);
this.make = new Phaser.GameObjectCreator(this);
this.cache = new Phaser.Cache(this);
this.load = new Phaser.Loader(this);
this.time = new Phaser.Time(this);
this.tweens = new Phaser.TweenManager(this);
this.input = new Phaser.Input(this);
this.sound = new Phaser.SoundManager(this);
this.physics = new Phaser.Physics(this, this.physicsConfig);
this.particles = new Phaser.Particles(this);
this.plugins = new Phaser.PluginManager(this, this);
this.net = new Phaser.Net(this);
this.debug = new Phaser.Utils.Debug(this);
this.time.boot();
this.stage.boot();
this.world.boot();
this.input.boot();
this.sound.boot();
this.state.boot();
this.debug.boot();
this.showDebugHeader();
this.isRunning = true;
if (this.config && this.config['forceSetTimeOut'])
{
this.raf = new Phaser.RequestAnimationFrame(this, this.config['forceSetTimeOut']);
}
else
{
this.raf = new Phaser.RequestAnimationFrame(this, false);
}
this.raf.start();
}
},
/**
* Displays a Phaser version debug header in the console.
*
* @method Phaser.Game#showDebugHeader
* @protected
*/
showDebugHeader: function () {
var v = Phaser.DEV_VERSION;
var r = 'Canvas';
var a = 'HTML Audio';
if (this.renderType == Phaser.WEBGL)
{
r = 'WebGL';
}
else if (this.renderType == Phaser.HEADLESS)
{
r = 'Headless';
}
if (this.device.webAudio)
{
a = 'WebAudio';
}
if (this.device.chrome)
{
var args = [
'%c %c %c Phaser v' + v + ' - Renderer: ' + r + ' - Audio: ' + a + ' %c %c ',
'background: #00bff3',
'background: #0072bc',
'color: #ffffff; background: #003471',
'background: #0072bc',
'background: #00bff3'
];
console.log.apply(console, args);
}
else
{
console.log('Phaser v' + v + ' - Renderer: ' + r + ' - Audio: ' + a);
}
},
/**
* Checks if the device is capable of using the requested renderer and sets it up or an alternative if not.
*
* @method Phaser.Game#setUpRenderer
* @protected
*/
setUpRenderer: function () {
if (this.device.trident)
{
// Pixi WebGL renderer on IE11 doesn't work correctly at the moment, the pre-multiplied alpha gets all washed out.
// So we're forcing canvas for now until this is fixed, sorry. It's got to be better than no game appearing at all, right?
this.renderType = Phaser.CANVAS;
}
if (this.renderType === Phaser.HEADLESS || this.renderType === Phaser.CANVAS || (this.renderType === Phaser.AUTO && this.device.webGL === false))
{
if (this.device.canvas)
{
if (this.renderType === Phaser.AUTO)
{
this.renderType = Phaser.CANVAS;
}
this.renderer = new PIXI.CanvasRenderer(this.width, this.height, this.canvas, this.transparent);
this.context = this.renderer.context;
}
else
{
throw new Error('Phaser.Game - cannot create Canvas or WebGL context, aborting.');
}
}
else
{
// They requested WebGL, and their browser supports it
this.renderType = Phaser.WEBGL;
this.renderer = new PIXI.WebGLRenderer(this.width, this.height, this.canvas, this.transparent, this.antialias);
this.context = null;
}
this.stage.smoothed = this.antialias;
Phaser.Canvas.addToDOM(this.canvas, this.parent, true);
Phaser.Canvas.setTouchAction(this.canvas);
},
/**
* The core game loop.
*
* @method Phaser.Game#update
* @protected
* @param {number} time - The current time as provided by RequestAnimationFrame.
*/
update: function (time) {
this.time.update(time);
if (this._paused)
{
this.input.update();
if (this.renderType !== Phaser.HEADLESS)
{
this.renderer.render(this.stage);
this.plugins.render();
this.state.render();
this.plugins.postRender();
}
}
else
{
if (!this.pendingStep)
{
if (this.stepping)
{
this.pendingStep = true;
}
this.state.preUpdate();
this.plugins.preUpdate();
this.stage.preUpdate();
this.stage.update();
this.tweens.update();
this.sound.update();
this.input.update();
this.state.update();
this.physics.update();
this.particles.update();
this.plugins.update();
this.stage.postUpdate();
this.plugins.postUpdate();
}
if (this.renderType !== Phaser.HEADLESS)
{
this.renderer.render(this.stage);
this.plugins.render();
this.state.render();
this.plugins.postRender();
}
}
},
/**
* Enable core game loop stepping. When enabled you must call game.step() directly (perhaps via a DOM button?)
* Calling step will advance the game loop by one frame. This is extremely useful to hard to track down errors!
*
* @method Phaser.Game#enableStep
*/
enableStep: function () {
this.stepping = true;
this.pendingStep = false;
this.stepCount = 0;
},
/**
* Disables core game loop stepping.
*
* @method Phaser.Game#disableStep
*/
disableStep: function () {
this.stepping = false;
this.pendingStep = false;
},
/**
* When stepping is enabled you must call this function directly (perhaps via a DOM button?) to advance the game loop by one frame.
* This is extremely useful to hard to track down errors! Use the internal stepCount property to monitor progress.
*
* @method Phaser.Game#step
*/
step: function () {
this.pendingStep = false;
this.stepCount++;
},
/**
* Nuke the entire game from orbit
*
* @method Phaser.Game#destroy
*/
destroy: function () {
this.raf.stop();
this.input.destroy();
this.state.destroy();
this.state = null;
this.cache = null;
this.input = null;
this.load = null;
this.sound = null;
this.stage = null;
this.time = null;
this.world = null;
this.isBooted = false;
},
/**
* Called by the Stage visibility handler.
*
* @method Phaser.Game#gamePaused
*/
gamePaused: function (time) {
// If the game is already paused it was done via game code, so don't re-pause it
if (!this._paused)
{
this._paused = true;
this.time.gamePaused(time);
this.sound.setMute();
this.onPause.dispatch(this);
}
},
/**
* Called by the Stage visibility handler.
*
* @method Phaser.Game#gameResumed
*/
gameResumed: function (time) {
// Game is paused, but wasn't paused via code, so resume it
if (this._paused && !this._codePaused)
{
this._paused = false;
this.time.gameResumed(time);
this.input.reset();
this.sound.unsetMute();
this.onResume.dispatch(this);
}
}
};
Phaser.Game.prototype.constructor = Phaser.Game;
/**
* The paused state of the Game. A paused game doesn't update any of its subsystems.
* When a game is paused the onPause event is dispatched. When it is resumed the onResume event is dispatched.
* @name Phaser.Game#paused
* @property {boolean} paused - Gets and sets the paused state of the Game.
*/
Object.defineProperty(Phaser.Game.prototype, "paused", {
get: function () {
return this._paused;
},
set: function (value) {
if (value === true)
{
if (this._paused === false)
{
this._paused = true;
this._codePaused = true;
this.sound.mute = true;
this.time.gamePaused();
this.onPause.dispatch(this);
}
}
else
{
if (this._paused)
{
this._paused = false;
this._codePaused = false;
this.input.reset();
this.sound.mute = false;
this.time.gameResumed();
this.onResume.dispatch(this);
}
}
}
});
/**
* "Deleted code is debugged code." - Jeff Sickel
*/
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2014 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* Phaser.Input is the Input Manager for all types of Input across Phaser, including mouse, keyboard, touch and MSPointer.
* The Input manager is updated automatically by the core game loop.
*
* @class Phaser.Input
* @constructor
* @param {Phaser.Game} game - Current game instance.
*/
Phaser.Input = function (game) {
/**
* @property {Phaser.Game} game - A reference to the currently running game.
*/
this.game = game;
/**
* @property {HTMLCanvasElement} hitCanvas - The canvas to which single pixels are drawn in order to perform pixel-perfect hit detection.
* @default
*/
this.hitCanvas = null;
/**
* @property {CanvasRenderingContext2D} hitContext - The context of the pixel perfect hit canvas.
* @default
*/
this.hitContext = null;
/**
* @property {function} moveCallback - An optional callback that will be fired every time the activePointer receives a move event from the DOM. Set to null to disable.
*/
this.moveCallback = null;
/**
* @property {object} moveCallbackContext - The context in which the moveCallback will be sent. Defaults to Phaser.Input but can be set to any valid JS object.
*/
this.moveCallbackContext = this;
/**
* @property {number} pollRate - How often should the input pointers be checked for updates? A value of 0 means every single frame (60fps); a value of 1 means every other frame (30fps) and so on.
* @default
*/
this.pollRate = 0;
/**
* You can disable all Input by setting Input.disabled = true. While set all new input related events will be ignored.
* If you need to disable just one type of input; for example mouse; use Input.mouse.disabled = true instead
* @property {boolean} disabled
* @default
*/
this.disabled = false;
/**
* @property {number} multiInputOverride - Controls the expected behaviour when using a mouse and touch together on a multi-input device.
* @default
*/
this.multiInputOverride = Phaser.Input.MOUSE_TOUCH_COMBINE;
/**
* @property {Phaser.Point} position - A point object representing the current position of the Pointer.
* @default
*/
this.position = null;
/**
* @property {Phaser.Point} speed - A point object representing the speed of the Pointer. Only really useful in single Pointer games; otherwise see the Pointer objects directly.
*/
this.speed = null;
/**
* A Circle object centered on the x/y screen coordinates of the Input.
* Default size of 44px (Apples recommended "finger tip" size) but can be changed to anything.
* @property {Phaser.Circle} circle
*/
this.circle = null;
/**
* @property {Phaser.Point} scale - The scale by which all input coordinates are multiplied; calculated by the ScaleManager. In an un-scaled game the values will be x = 1 and y = 1.
*/
this.scale = null;
/**
* @property {number} maxPointers - The maximum number of Pointers allowed to be active at any one time. For lots of games it's useful to set this to 1.
* @default
*/
this.maxPointers = 10;
/**
* @property {number} currentPointers - The current number of active Pointers.
* @default
*/
this.currentPointers = 0;
/**
* @property {number} tapRate - The number of milliseconds that the Pointer has to be pressed down and then released to be considered a tap or click.
* @default
*/
this.tapRate = 200;
/**
* @property {number} doubleTapRate - The number of milliseconds between taps of the same Pointer for it to be considered a double tap / click.
* @default
*/
this.doubleTapRate = 300;
/**
* @property {number} holdRate - The number of milliseconds that the Pointer has to be pressed down for it to fire a onHold event.
* @default
*/
this.holdRate = 2000;
/**
* @property {number} justPressedRate - The number of milliseconds below which the Pointer is considered justPressed.
* @default
*/
this.justPressedRate = 200;
/**
* @property {number} justReleasedRate - The number of milliseconds below which the Pointer is considered justReleased .
* @default
*/
this.justReleasedRate = 200;
/**
* Sets if the Pointer objects should record a history of x/y coordinates they have passed through.
* The history is cleared each time the Pointer is pressed down.
* The history is updated at the rate specified in Input.pollRate
* @property {boolean} recordPointerHistory
* @default
*/
this.recordPointerHistory = false;
/**
* @property {number} recordRate - The rate in milliseconds at which the Pointer objects should update their tracking history.
* @default
*/
this.recordRate = 100;
/**
* The total number of entries that can be recorded into the Pointer objects tracking history.
* If the Pointer is tracking one event every 100ms; then a trackLimit of 100 would store the last 10 seconds worth of history.
* @property {number} recordLimit
* @default
*/
this.recordLimit = 100;
/**
* @property {Phaser.Pointer} pointer1 - A Pointer object.
*/
this.pointer1 = null;
/**
* @property {Phaser.Pointer} pointer2 - A Pointer object.
*/
this.pointer2 = null;
/**
* @property {Phaser.Pointer} pointer3 - A Pointer object.
*/
this.pointer3 = null;
/**
* @property {Phaser.Pointer} pointer4 - A Pointer object.
*/
this.pointer4 = null;
/**
* @property {Phaser.Pointer} pointer5 - A Pointer object.
*/
this.pointer5 = null;
/**
* @property {Phaser.Pointer} pointer6 - A Pointer object.
*/
this.pointer6 = null;
/**
* @property {Phaser.Pointer} pointer7 - A Pointer object.
*/
this.pointer7 = null;
/**
* @property {Phaser.Pointer} pointer8 - A Pointer object.
*/
this.pointer8 = null;
/**
* @property {Phaser.Pointer} pointer9 - A Pointer object.
*/
this.pointer9 = null;
/**
* @property {Phaser.Pointer} pointer10 - A Pointer object.
*/
this.pointer10 = null;
/**
* The most recently active Pointer object.
* When you've limited max pointers to 1 this will accurately be either the first finger touched or mouse.
* @property {Phaser.Pointer} activePointer
*/
this.activePointer = null;
/**
* @property {Pointer} mousePointer - The mouse has its own unique Phaser.Pointer object which you can use if making a desktop specific game.
*/
this.mousePointer = null;
/**
* @property {Phaser.Mouse} mouse - The Mouse Input manager.
*/
this.mouse = null;
/**
* @property {Phaser.Keyboard} keyboard - The Keyboard Input manager.
*/
this.keyboard = null;
/**
* @property {Phaser.Touch} touch - the Touch Input manager.
*/
this.touch = null;
/**
* @property {Phaser.MSPointer} mspointer - The MSPointer Input manager.
*/
this.mspointer = null;
/**
* @property {Phaser.Gamepad} gamepad - The Gamepad Input manager.
*/
this.gamepad = null;
/**
* @property {Phaser.Gestures} gestures - The Gestures manager.
*/
this.gestures = null;
/**
* @property {Phaser.Signal} onDown - A Signal that is dispatched each time a pointer is pressed down.
*/
this.onDown = null;
/**
* @property {Phaser.Signal} onUp - A Signal that is dispatched each time a pointer is released.
*/
this.onUp = null;
/**
* @property {Phaser.Signal} onTap - A Signal that is dispatched each time a pointer is tapped.
*/
this.onTap = null;
/**
* @property {Phaser.Signal} onHold - A Signal that is dispatched each time a pointer is held down.
*/
this.onHold = null;
/**
* A linked list of interactive objects; the InputHandler components (belonging to Sprites) register themselves with this.
* @property {Phaser.LinkedList} interactiveItems
*/
this.interactiveItems = new Phaser.LinkedList();
/**
* @property {Phaser.Point} _localPoint - Internal cache var.
* @private
*/
this._localPoint = new Phaser.Point();
/**
* @property {number} _pollCounter - Internal var holding the current poll counter.
* @private
*/
this._pollCounter = 0;
/**
* @property {Phaser.Point} _oldPosition - A point object representing the previous position of the Pointer.
* @private
*/
this._oldPosition = null;
/**
* @property {number} _x - x coordinate of the most recent Pointer event
* @private
*/
this._x = 0;
/**
* @property {number} _y - Y coordinate of the most recent Pointer event
* @private
*/
this._y = 0;
};
/**
* @constant
* @type {number}
*/
Phaser.Input.MOUSE_OVERRIDES_TOUCH = 0;
/**
* @constant
* @type {number}
*/
Phaser.Input.TOUCH_OVERRIDES_MOUSE = 1;
/**
* @constant
* @type {number}
*/
Phaser.Input.MOUSE_TOUCH_COMBINE = 2;
Phaser.Input.prototype = {
/**
* Starts the Input Manager running.
* @method Phaser.Input#boot
* @protected
*/
boot: function () {
this.mousePointer = new Phaser.Pointer(this.game, 0);
this.pointer1 = new Phaser.Pointer(this.game, 1);
this.pointer2 = new Phaser.Pointer(this.game, 2);
this.mouse = new Phaser.Mouse(this.game);
this.keyboard = new Phaser.Keyboard(this.game);
this.touch = new Phaser.Touch(this.game);
this.mspointer = new Phaser.MSPointer(this.game);
this.gamepad = new Phaser.Gamepad(this.game);
this.gestures = new Phaser.Gestures(this.game);
this.onDown = new Phaser.Signal();
this.onUp = new Phaser.Signal();
this.onTap = new Phaser.Signal();
this.onHold = new Phaser.Signal();
this.scale = new Phaser.Point(1, 1);
this.speed = new Phaser.Point();
this.position = new Phaser.Point();
this._oldPosition = new Phaser.Point();
this.circle = new Phaser.Circle(0, 0, 44);
this.activePointer = this.mousePointer;
this.currentPointers = 0;
this.hitCanvas = document.createElement('canvas');
this.hitCanvas.width = 1;
this.hitCanvas.height = 1;
this.hitContext = this.hitCanvas.getContext('2d');
this.mouse.start();
this.keyboard.start();
this.touch.start();
this.mspointer.start();
this.mousePointer.active = true;
},
/**
* Stops all of the Input Managers from running.
* @method Phaser.Input#destroy
*/
destroy: function () {
this.mouse.stop();
this.keyboard.stop();
this.touch.stop();
this.mspointer.stop();
this.gamepad.stop();
this.gestures.stop();
this.moveCallback = null;
},
/**
* Sets a callback that is fired every time the activePointer receives a DOM move event such as a mousemove or touchmove.
* It will be called every time the activePointer moves, which in a multi-touch game can be a lot of times, so this is best
* to only use if you've limited input to a single pointer (i.e. mouse or touch)
* @method Phaser.Input#setMoveCallback
* @param {function} callback - The callback that will be called each time the activePointer receives a DOM move event.
* @param {object} callbackContext - The context in which the callback will be called.
*/
setMoveCallback: function (callback, callbackContext) {
this.moveCallback = callback;
this.moveCallbackContext = callbackContext;
},
/**
* Add a new Pointer object to the Input Manager. By default Input creates 3 pointer objects: mousePointer, pointer1 and pointer2.
* If you need more then use this to create a new one, up to a maximum of 10.
* @method Phaser.Input#addPointer
* @return {Phaser.Pointer} A reference to the new Pointer object that was created.
*/
addPointer: function () {
var next = 0;
for (var i = 10; i > 0; i--)
{
if (this['pointer' + i] === null)
{
next = i;
}
}
if (next === 0)
{
console.warn("You can only have 10 Pointer objects");
return null;
}
else
{
this['pointer' + next] = new Phaser.Pointer(this.game, next);
return this['pointer' + next];
}
},
/**
* Updates the Input Manager. Called by the core Game loop.
* @method Phaser.Input#update
* @protected
*/
update: function () {
this.keyboard.update();
if (this.pollRate > 0 && this._pollCounter < this.pollRate)
{
this._pollCounter++;
return;
}
this.speed.x = this.position.x - this._oldPosition.x;
this.speed.y = this.position.y - this._oldPosition.y;
this._oldPosition.copyFrom(this.position);
this.mousePointer.update();
if (this.gamepad.active) { this.gamepad.update(); }
this.pointer1.update();
this.pointer2.update();
if (this.pointer3) { this.pointer3.update(); }
if (this.pointer4) { this.pointer4.update(); }
if (this.pointer5) { this.pointer5.update(); }
if (this.pointer6) { this.pointer6.update(); }
if (this.pointer7) { this.pointer7.update(); }
if (this.pointer8) { this.pointer8.update(); }
if (this.pointer9) { this.pointer9.update(); }
if (this.pointer10) { this.pointer10.update(); }
this._pollCounter = 0;
if (this.gestures.active) { this.gestures.update(); }
},
/**
* Reset all of the Pointers and Input states
* @method Phaser.Input#reset
* @param {boolean} hard - A soft reset (hard = false) won't reset any Signals that might be bound. A hard reset will.
*/
reset: function (hard) {
if (this.game.isBooted === false)
{
return;
}
if (typeof hard == 'undefined') { hard = false; }
this.keyboard.reset();
this.mousePointer.reset();
this.gamepad.reset();
for (var i = 1; i <= 10; i++)
{
if (this['pointer' + i])
{
this['pointer' + i].reset();
}
}
this.currentPointers = 0;
if (this.game.canvas.style.cursor !== 'none')
{
this.game.canvas.style.cursor = 'inherit';
}
if (hard === true)
{
this.onDown.dispose();
this.onUp.dispose();
this.onTap.dispose();
this.onHold.dispose();
this.onDown = new Phaser.Signal();
this.onUp = new Phaser.Signal();
this.onTap = new Phaser.Signal();
this.onHold = new Phaser.Signal();
this.interactiveItems.callAll('reset');
}
this._pollCounter = 0;
},
/**
* Resets the speed and old position properties.
* @method Phaser.Input#resetSpeed
* @param {number} x - Sets the oldPosition.x value.
* @param {number} y - Sets the oldPosition.y value.
*/
resetSpeed: function (x, y) {
this._oldPosition.setTo(x, y);
this.speed.setTo(0, 0);
},
/**
* Find the first free Pointer object and start it, passing in the event data. This is called automatically by Phaser.Touch and Phaser.MSPointer.
* @method Phaser.Input#startPointer
* @param {Any} event - The event data from the Touch event.
* @return {Phaser.Pointer} The Pointer object that was started or null if no Pointer object is available.
*/
startPointer: function (event) {
if (this.maxPointers < 10 && this.totalActivePointers == this.maxPointers)
{
return null;
}
if (this.pointer1.active === false)
{
return this.pointer1.start(event);
}
else if (this.pointer2.active === false)
{
return this.pointer2.start(event);
}
else
{
for (var i = 3; i <= 10; i++)
{
if (this['pointer' + i] && this['pointer' + i].active === false)
{
return this['pointer' + i].start(event);
}
}
}
return null;
},
/**
* Updates the matching Pointer object, passing in the event data. This is called automatically and should not normally need to be invoked.
* @method Phaser.Input#updatePointer
* @param {Any} event - The event data from the Touch event.
* @return {Phaser.Pointer} The Pointer object that was updated or null if no Pointer object is available.
*/
updatePointer: function (event) {
if (this.pointer1.active && this.pointer1.identifier == event.identifier)
{
return this.pointer1.move(event);
}
else if (this.pointer2.active && this.pointer2.identifier == event.identifier)
{
return this.pointer2.move(event);
}
else
{
for (var i = 3; i <= 10; i++)
{
if (this['pointer' + i] && this['pointer' + i].active && this['pointer' + i].identifier == event.identifier)
{
return this['pointer' + i].move(event);
}
}
}
return null;
},
/**
* Stops the matching Pointer object, passing in the event data.
* @method Phaser.Input#stopPointer
* @param {Any} event - The event data from the Touch event.
* @return {Phaser.Pointer} The Pointer object that was stopped or null if no Pointer object is available.
*/
stopPointer: function (event) {
if (this.pointer1.active && this.pointer1.identifier == event.identifier)
{
return this.pointer1.stop(event);
}
else if (this.pointer2.active && this.pointer2.identifier == event.identifier)
{
return this.pointer2.stop(event);
}
else
{
for (var i = 3; i <= 10; i++)
{
if (this['pointer' + i] && this['pointer' + i].active && this['pointer' + i].identifier == event.identifier)
{
return this['pointer' + i].stop(event);
}
}
}
return null;
},
/**
* Get the next Pointer object whos active property matches the given state
* @method Phaser.Input#getPointer
* @param {boolean} state - The state the Pointer should be in (false for inactive, true for active).
* @return {Phaser.Pointer} A Pointer object or null if no Pointer object matches the requested state.
*/
getPointer: function (state) {
state = state || false;
if (this.pointer1.active == state)
{
return this.pointer1;
}
else if (this.pointer2.active == state)
{
return this.pointer2;
}
else
{
for (var i = 3; i <= 10; i++)
{
if (this['pointer' + i] && this['pointer' + i].active == state)
{
return this['pointer' + i];
}
}
}
return null;
},
/**
* Get the Pointer object whos identified property matches the given identifier value.
* @method Phaser.Input#getPointerFromIdentifier
* @param {number} identifier - The Pointer.identifier value to search for.
* @return {Phaser.Pointer} A Pointer object or null if no Pointer object matches the requested identifier.
*/
getPointerFromIdentifier: function (identifier) {
if (this.pointer1.identifier == identifier)
{
return this.pointer1;
}
else if (this.pointer2.identifier == identifier)
{
return this.pointer2;
}
else
{
for (var i = 3; i <= 10; i++)
{
if (this['pointer' + i] && this['pointer' + i].identifier == identifier)
{
return this['pointer' + i];
}
}
}
return null;
},
/**
* This will return the local coordinates of the specified displayObject based on the given Pointer.
* @method Phaser.Input#getLocalPosition
* @param {Phaser.Sprite|Phaser.Image} displayObject - The DisplayObject to get the local coordinates for.
* @param {Phaser.Pointer} pointer - The Pointer to use in the check against the displayObject.
* @return {Phaser.Point} A point containing the coordinates of the Pointer position relative to the DisplayObject.
*/
getLocalPosition: function (displayObject, pointer, output) {
if (typeof output === 'undefined') { output = new Phaser.Point(); }
var wt = displayObject.worldTransform;
var id = 1 / (wt.a * wt.d + wt.b * -wt.c);
return output.setTo(
wt.d * id * pointer.x + -wt.b * id * pointer.y + (wt.ty * wt.b - wt.tx * wt.d) * id,
wt.a * id * pointer.y + -wt.c * id * pointer.x + (-wt.ty * wt.a + wt.tx * wt.c) * id
);
},
/**
* Tests if the current mouse coordinates hit a sprite
*
* @method hitTest
* @param displayObject {DisplayObject} The displayObject to test for a hit
*/
hitTest: function (displayObject, pointer, localPoint) {
if (!displayObject.worldVisible)
{
return false;
}
this.getLocalPosition(displayObject, pointer, this._localPoint);
localPoint.copyFrom(this._localPoint);
if (displayObject.hitArea && displayObject.hitArea.contains)
{
if (displayObject.hitArea.contains(this._localPoint.x, this._localPoint.y))
{
return true;
}
return false;
}
else if (displayObject instanceof Phaser.TileSprite)
{
var width = displayObject.width;
var height = displayObject.height;
var x1 = -width * displayObject.anchor.x;
if (this._localPoint.x > x1 && this._localPoint.x < x1 + width)
{
var y1 = -height * displayObject.anchor.y;
if (this._localPoint.y > y1 && this._localPoint.y < y1 + height)
{
return true;
}
}
}
else if (displayObject instanceof PIXI.Sprite)
{
var width = displayObject.texture.frame.width;
var height = displayObject.texture.frame.height;
var x1 = -width * displayObject.anchor.x;
if (this._localPoint.x > x1 && this._localPoint.x < x1 + width)
{
var y1 = -height * displayObject.anchor.y;
if (this._localPoint.y > y1 && this._localPoint.y < y1 + height)
{
return true;
}
}
}
for (var i = 0, len = displayObject.children.length; i < len; i++)
{
if (this.hitTest(displayObject.children[i], pointer, localPoint))
{
return true;
}
}
return false;
}
};
Phaser.Input.prototype.constructor = Phaser.Input;
/**
* The X coordinate of the most recently active pointer. This value takes game scaling into account automatically. See Pointer.screenX/clientX for source values.
* @name Phaser.Input#x
* @property {number} x - The X coordinate of the most recently active pointer.
*/
Object.defineProperty(Phaser.Input.prototype, "x", {
get: function () {
return this._x;
},
set: function (value) {
this._x = Math.floor(value);
}
});
/**
* The Y coordinate of the most recently active pointer. This value takes game scaling into account automatically. See Pointer.screenY/clientY for source values.
* @name Phaser.Input#y
* @property {number} y - The Y coordinate of the most recently active pointer.
*/
Object.defineProperty(Phaser.Input.prototype, "y", {
get: function () {
return this._y;
},
set: function (value) {
this._y = Math.floor(value);
}
});
/**
* @name Phaser.Input#pollLocked
* @property {boolean} pollLocked - True if the Input is currently poll rate locked.
* @readonly
*/
Object.defineProperty(Phaser.Input.prototype, "pollLocked", {
get: function () {
return (this.pollRate > 0 && this._pollCounter < this.pollRate);
}
});
/**
* The total number of inactive Pointers
* @name Phaser.Input#totalInactivePointers
* @property {number} totalInactivePointers - The total number of inactive Pointers.
* @readonly
*/
Object.defineProperty(Phaser.Input.prototype, "totalInactivePointers", {
get: function () {
return 10 - this.currentPointers;
}
});
/**
* The total number of active Pointers
* @name Phaser.Input#totalActivePointers
* @property {number} totalActivePointers - The total number of active Pointers.
* @readonly
*/
Object.defineProperty(Phaser.Input.prototype, "totalActivePointers", {
get: function () {
this.currentPointers = 0;
for (var i = 1; i <= 10; i++)
{
if (this['pointer' + i] && this['pointer' + i].active)
{
this.currentPointers++;
}
}
return this.currentPointers;
}
});
/**
* The world X coordinate of the most recently active pointer.
* @name Phaser.Input#worldX
* @property {number} worldX - The world X coordinate of the most recently active pointer.
*/
Object.defineProperty(Phaser.Input.prototype, "worldX", {
get: function () {
return this.game.camera.view.x + this.x;
}
});
/**
* The world Y coordinate of the most recently active pointer.
* @name Phaser.Input#worldY
* @property {number} worldY - The world Y coordinate of the most recently active pointer.
*/
Object.defineProperty(Phaser.Input.prototype, "worldY", {
get: function () {
return this.game.camera.view.y + this.y;
}
});
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2014 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @class Phaser.Key
* @classdesc If you need more fine-grained control over the handling of specific keys you can create and use Phaser.Key objects.
* @constructor
* @param {Phaser.Game} game - Current game instance.
* @param {number} keycode - The key code this Key is responsible for.
*/
Phaser.Key = function (game, keycode) {
/**
* @property {Phaser.Game} game - A reference to the currently running game.
*/
this.game = game;
/**
* @property {boolean} isDown - The "down" state of the key.
* @default
*/
this.isDown = false;
/**
* @property {boolean} isUp - The "up" state of the key.
* @default
*/
this.isUp = true;
/**
* @property {boolean} altKey - The down state of the ALT key, if pressed at the same time as this key.
* @default
*/
this.altKey = false;
/**
* @property {boolean} ctrlKey - The down state of the CTRL key, if pressed at the same time as this key.
* @default
*/
this.ctrlKey = false;
/**
* @property {boolean} shiftKey - The down state of the SHIFT key, if pressed at the same time as this key.
* @default
*/
this.shiftKey = false;
/**
* @property {number} timeDown - The timestamp when the key was last pressed down. This is based on Game.time.now.
*/
this.timeDown = 0;
/**
* If the key is down this value holds the duration of that key press and is constantly updated.
* If the key is up it holds the duration of the previous down session.
* @property {number} duration - The number of milliseconds this key has been held down for.
* @default
*/
this.duration = 0;
/**
* @property {number} timeUp - The timestamp when the key was last released. This is based on Game.time.now.
* @default
*/
this.timeUp = -2500;
/**
* @property {number} repeats - If a key is held down this holds down the number of times the key has 'repeated'.
* @default
*/
this.repeats = 0;
/**
* @property {number} keyCode - The keycode of this key.
*/
this.keyCode = keycode;
/**
* @property {Phaser.Signal} onDown - This Signal is dispatched every time this Key is pressed down. It is only dispatched once (until the key is released again).
*/
this.onDown = new Phaser.Signal();
/**
* @property {function} onHoldCallback - A callback that is called while this Key is held down. Warning: Depending on refresh rate that could be 60+ times per second.
*/
this.onHoldCallback = null;
/**
* @property {object} onHoldContext - The context under which the onHoldCallback will be called.
*/
this.onHoldContext = null;
/**
* @property {Phaser.Signal} onUp - This Signal is dispatched every time this Key is pressed down. It is only dispatched once (until the key is released again).
*/
this.onUp = new Phaser.Signal();
};
Phaser.Key.prototype = {
update: function () {
if (this.isDown)
{
this.duration = this.game.time.now - this.timeDown;
this.repeats++;
if (this.onHoldCallback)
{
this.onHoldCallback.call(this.onHoldContext, this);
}
}
},
/**
* Called automatically by Phaser.Keyboard.
* @method Phaser.Key#processKeyDown
* @param {KeyboardEvent} event.
* @protected
*/
processKeyDown: function (event) {
if (this.isDown)
{
return;
}
this.altKey = event.altKey;
this.ctrlKey = event.ctrlKey;
this.shiftKey = event.shiftKey;
this.isDown = true;
this.isUp = false;
this.timeDown = this.game.time.now;
this.duration = 0;
this.repeats = 0;
this.onDown.dispatch(this);
},
/**
* Called automatically by Phaser.Keyboard.
* @method Phaser.Key#processKeyUp
* @param {KeyboardEvent} event.
* @protected
*/
processKeyUp: function (event) {
if (this.isUp)
{
return;
}
this.isDown = false;
this.isUp = true;
this.timeUp = this.game.time.now;
this.duration = this.game.time.now - this.timeDown;
this.onUp.dispatch(this);
},
/**
* Resets the state of this Key.
*
* @method Phaser.Key#reset
*/
reset: function () {
this.isDown = false;
this.isUp = true;
this.timeUp = this.game.time.now;
this.duration = this.game.time.now - this.timeDown;
},
/**
* Returns the "just pressed" state of the Key. Just pressed is considered true if the key was pressed down within the duration given (default 250ms)
* @method Phaser.Key#justPressed
* @param {number} [duration=250] - The duration below which the key is considered as being just pressed.
* @return {boolean} True if the key is just pressed otherwise false.
*/
justPressed: function (duration) {
if (typeof duration === "undefined") { duration = 2500; }
return (this.isDown && this.duration < duration);
},
/**
* Returns the "just released" state of the Key. Just released is considered as being true if the key was released within the duration given (default 250ms)
* @method Phaser.Key#justReleased
* @param {number} [duration=250] - The duration below which the key is considered as being just released.
* @return {boolean} True if the key is just released otherwise false.
*/
justReleased: function (duration) {
if (typeof duration === "undefined") { duration = 2500; }
return (!this.isDown && ((this.game.time.now - this.timeUp) < duration));
}
};
Phaser.Key.prototype.constructor = Phaser.Key;
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2014 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* The Keyboard class handles looking after keyboard input for your game. It will recognise and respond to key presses and dispatch the required events.
*
* @class Phaser.Keyboard
* @constructor
* @param {Phaser.Game} game - A reference to the currently running game.
*/
Phaser.Keyboard = function (game) {
/**
* @property {Phaser.Game} game - Local reference to game.
*/
this.game = game;
/**
* You can disable all Keyboard Input by setting disabled to true. While true all new input related events will be ignored.
* @property {boolean} disabled - The disabled state of the Keyboard.
* @default
*/
this.disabled = false;
/**
* @property {Object} event - The most recent DOM event. This is updated every time a new key is pressed or released.
*/
this.event = null;
/**
* @property {Object} callbackContext - The context under which the callbacks are run.
*/
this.callbackContext = this;
/**
* @property {function} onDownCallback - This callback is invoked every time a key is pressed down.
*/
this.onDownCallback = null;
/**
* @property {function} onUpCallback - This callback is invoked every time a key is released.
*/
this.onUpCallback = null;
/**
* @property {array<Phaser.Key>} _keys - The array the Phaser.Key objects are stored in.
* @private
*/
this._keys = [];
/**
* @property {array} _capture - The array the key capture values are stored in.
* @private
*/
this._capture = [];
/**
* @property {function} _onKeyDown
* @private
* @default
*/
this._onKeyDown = null;
/**
* @property {function} _onKeyUp
* @private
* @default
*/
this._onKeyUp = null;
};
Phaser.Keyboard.prototype = {
/**
* Add callbacks to the Keyboard handler so that each time a key is pressed down or released the callbacks are activated.
*
* @method Phaser.Keyboard#addCallbacks
* @param {Object} context - The context under which the callbacks are run.
* @param {function} onDown - This callback is invoked every time a key is pressed down.
* @param {function} [onUp=null] - This callback is invoked every time a key is released.
*/
addCallbacks: function (context, onDown, onUp) {
this.callbackContext = context;
this.onDownCallback = onDown;
if (typeof onUp !== 'undefined')
{
this.onUpCallback = onUp;
}
},
/**
* If you need more fine-grained control over a Key you can create a new Phaser.Key object via this method.
* The Key object can then be polled, have events attached to it, etc.
*
* @method Phaser.Keyboard#addKey
* @param {number} keycode - The keycode of the key, i.e. Phaser.Keyboard.UP or Phaser.Keyboard.SPACEBAR
* @return {Phaser.Key} The Key object which you can store locally and reference directly.
*/
addKey: function (keycode) {
if (!this._keys[keycode])
{
this._keys[keycode] = new Phaser.Key(this.game, keycode);
this.addKeyCapture(keycode);
}
return this._keys[keycode];
},
/**
* Creates and returns an object containing 4 hotkeys for Up, Down, Left and Right.
*
* @method Phaser.Keyboard#createCursorKeys
* @return {object} An object containing properties: up, down, left and right. Which can be polled like any other Phaser.Key object.
*/
createCursorKeys: function () {
return {
up: this.addKey(Phaser.Keyboard.UP),
down: this.addKey(Phaser.Keyboard.DOWN),
left: this.addKey(Phaser.Keyboard.LEFT),
right: this.addKey(Phaser.Keyboard.RIGHT)
}
},
/**
* Starts the Keyboard event listeners running (keydown and keyup). They are attached to the document.body.
* This is called automatically by Phaser.Input and should not normally be invoked directly.
*
* @method Phaser.Keyboard#start
*/
start: function () {
var _this = this;
this._onKeyDown = function (event) {
return _this.processKeyDown(event);
};
this._onKeyUp = function (event) {
return _this.processKeyUp(event);
};
window.addEventListener('keydown', this._onKeyDown, false);
window.addEventListener('keyup', this._onKeyUp, false);
},
/**
* Stops the Keyboard event listeners from running (keydown and keyup). They are removed from the document.body.
*
* @method Phaser.Keyboard#stop
*/
stop: function () {
window.removeEventListener('keydown', this._onKeyDown);
window.removeEventListener('keyup', this._onKeyUp);
},
/**
* By default when a key is pressed Phaser will not stop the event from propagating up to the browser.
* There are some keys this can be annoying for, like the arrow keys or space bar, which make the browser window scroll.
* You can use addKeyCapture to consume the keyboard event for specific keys so it doesn't bubble up to the the browser.
* Pass in either a single keycode or an array/hash of keycodes.
*
* @method Phaser.Keyboard#addKeyCapture
* @param {Any} keycode - Either a single numeric keycode or an array/hash of keycodes: [65, 67, 68].
*/
addKeyCapture: function (keycode) {
if (typeof keycode === 'object')
{
for (var key in keycode)
{
this._capture[keycode[key]] = true;
}
}
else
{
this._capture[keycode] = true;
}
},
/**
* Removes an existing key capture.
*
* @method Phaser.Keyboard#removeKeyCapture
* @param {number} keycode
*/
removeKeyCapture: function (keycode) {
delete this._capture[keycode];
},
/**
* Clear all set key captures.
*
* @method Phaser.Keyboard#clearCaptures
*/
clearCaptures: function () {
this._capture = {};
},
/**
* Updates all currently defined keys.
*
* @method Phaser.Keyboard#update
*/
update: function () {
var i = this._keys.length;
while (i--)
{
if (this._keys[i])
{
this._keys[i].update();
}
}
},
/**
* Process the keydown event.
*
* @method Phaser.Keyboard#processKeyDown
* @param {KeyboardEvent} event
* @protected
*/
processKeyDown: function (event) {
this.event = event;
if (this.game.input.disabled || this.disabled)
{
return;
}
// The event is being captured but another hotkey may need it
if (this._capture[event.keyCode])
{
event.preventDefault();
}
if (this.onDownCallback)
{
this.onDownCallback.call(this.callbackContext, event);
}
if (!this._keys[event.keyCode])
{
this._keys[event.keyCode] = new Phaser.Key(this.game, event.keyCode);
}
this._keys[event.keyCode].processKeyDown(event);
},
/**
* Process the keyup event.
*
* @method Phaser.Keyboard#processKeyUp
* @param {KeyboardEvent} event
* @protected
*/
processKeyUp: function (event) {
this.event = event;
if (this.game.input.disabled || this.disabled)
{
return;
}
if (this._capture[event.keyCode])
{
event.preventDefault();
}
if (this.onUpCallback)
{
this.onUpCallback.call(this.callbackContext, event);
}
if (!this._keys[event.keyCode])
{
this._keys[event.keyCode] = new Phaser.Key(this.game, event.keyCode);
}
this._keys[event.keyCode].processKeyUp(event);
},
/**
* Resets all Keys.
*
* @method Phaser.Keyboard#reset
*/
reset: function () {
this.event = null;
var i = this._keys.length;
while (i--)
{
if (this._keys[i])
{
this._keys[i].reset();
}
}
},
/**
* Returns the "just pressed" state of the key. Just pressed is considered true if the key was pressed down within the duration given (default 250ms)
*
* @method Phaser.Keyboard#justPressed
* @param {number} keycode - The keycode of the key to remove, i.e. Phaser.Keyboard.UP or Phaser.Keyboard.SPACEBAR
* @param {number} [duration=250] - The duration below which the key is considered as being just pressed.
* @return {boolean} True if the key is just pressed otherwise false.
*/
justPressed: function (keycode, duration) {
if (this._keys[keycode])
{
return this._keys[keycode].justPressed(duration);
}
else
{
return false;
}
},
/**
* Returns the "just released" state of the Key. Just released is considered as being true if the key was released within the duration given (default 250ms)
*
* @method Phaser.Keyboard#justReleased
* @param {number} keycode - The keycode of the key to remove, i.e. Phaser.Keyboard.UP or Phaser.Keyboard.SPACEBAR
* @param {number} [duration=250] - The duration below which the key is considered as being just released.
* @return {boolean} True if the key is just released otherwise false.
*/
justReleased: function (keycode, duration) {
if (this._keys[keycode])
{
return this._keys[keycode].justReleased(duration);
}
else
{
return false;
}
},
/**
* Returns true of the key is currently pressed down. Note that it can only detect key presses on the web browser.
*
* @method Phaser.Keyboard#isDown
* @param {number} keycode - The keycode of the key to remove, i.e. Phaser.Keyboard.UP or Phaser.Keyboard.SPACEBAR
* @return {boolean} True if the key is currently down.
*/
isDown: function (keycode) {
if (this._keys[keycode])
{
return this._keys[keycode].isDown;
}
return false;
}
};
Phaser.Keyboard.prototype.constructor = Phaser.Keyboard;
Phaser.Keyboard.A = "A".charCodeAt(0);
Phaser.Keyboard.B = "B".charCodeAt(0);
Phaser.Keyboard.C = "C".charCodeAt(0);
Phaser.Keyboard.D = "D".charCodeAt(0);
Phaser.Keyboard.E = "E".charCodeAt(0);
Phaser.Keyboard.F = "F".charCodeAt(0);
Phaser.Keyboard.G = "G".charCodeAt(0);
Phaser.Keyboard.H = "H".charCodeAt(0);
Phaser.Keyboard.I = "I".charCodeAt(0);
Phaser.Keyboard.J = "J".charCodeAt(0);
Phaser.Keyboard.K = "K".charCodeAt(0);
Phaser.Keyboard.L = "L".charCodeAt(0);
Phaser.Keyboard.M = "M".charCodeAt(0);
Phaser.Keyboard.N = "N".charCodeAt(0);
Phaser.Keyboard.O = "O".charCodeAt(0);
Phaser.Keyboard.P = "P".charCodeAt(0);
Phaser.Keyboard.Q = "Q".charCodeAt(0);
Phaser.Keyboard.R = "R".charCodeAt(0);
Phaser.Keyboard.S = "S".charCodeAt(0);
Phaser.Keyboard.T = "T".charCodeAt(0);
Phaser.Keyboard.U = "U".charCodeAt(0);
Phaser.Keyboard.V = "V".charCodeAt(0);
Phaser.Keyboard.W = "W".charCodeAt(0);
Phaser.Keyboard.X = "X".charCodeAt(0);
Phaser.Keyboard.Y = "Y".charCodeAt(0);
Phaser.Keyboard.Z = "Z".charCodeAt(0);
Phaser.Keyboard.ZERO = "0".charCodeAt(0);
Phaser.Keyboard.ONE = "1".charCodeAt(0);
Phaser.Keyboard.TWO = "2".charCodeAt(0);
Phaser.Keyboard.THREE = "3".charCodeAt(0);
Phaser.Keyboard.FOUR = "4".charCodeAt(0);
Phaser.Keyboard.FIVE = "5".charCodeAt(0);
Phaser.Keyboard.SIX = "6".charCodeAt(0);
Phaser.Keyboard.SEVEN = "7".charCodeAt(0);
Phaser.Keyboard.EIGHT = "8".charCodeAt(0);
Phaser.Keyboard.NINE = "9".charCodeAt(0);
Phaser.Keyboard.NUMPAD_0 = 96;
Phaser.Keyboard.NUMPAD_1 = 97;
Phaser.Keyboard.NUMPAD_2 = 98;
Phaser.Keyboard.NUMPAD_3 = 99;
Phaser.Keyboard.NUMPAD_4 = 100;
Phaser.Keyboard.NUMPAD_5 = 101;
Phaser.Keyboard.NUMPAD_6 = 102;
Phaser.Keyboard.NUMPAD_7 = 103;
Phaser.Keyboard.NUMPAD_8 = 104;
Phaser.Keyboard.NUMPAD_9 = 105;
Phaser.Keyboard.NUMPAD_MULTIPLY = 106;
Phaser.Keyboard.NUMPAD_ADD = 107;
Phaser.Keyboard.NUMPAD_ENTER = 108;
Phaser.Keyboard.NUMPAD_SUBTRACT = 109;
Phaser.Keyboard.NUMPAD_DECIMAL = 110;
Phaser.Keyboard.NUMPAD_DIVIDE = 111;
Phaser.Keyboard.F1 = 112;
Phaser.Keyboard.F2 = 113;
Phaser.Keyboard.F3 = 114;
Phaser.Keyboard.F4 = 115;
Phaser.Keyboard.F5 = 116;
Phaser.Keyboard.F6 = 117;
Phaser.Keyboard.F7 = 118;
Phaser.Keyboard.F8 = 119;
Phaser.Keyboard.F9 = 120;
Phaser.Keyboard.F10 = 121;
Phaser.Keyboard.F11 = 122;
Phaser.Keyboard.F12 = 123;
Phaser.Keyboard.F13 = 124;
Phaser.Keyboard.F14 = 125;
Phaser.Keyboard.F15 = 126;
Phaser.Keyboard.COLON = 186;
Phaser.Keyboard.EQUALS = 187;
Phaser.Keyboard.UNDERSCORE = 189;
Phaser.Keyboard.QUESTION_MARK = 191;
Phaser.Keyboard.TILDE = 192;
Phaser.Keyboard.OPEN_BRACKET = 219;
Phaser.Keyboard.BACKWARD_SLASH = 220;
Phaser.Keyboard.CLOSED_BRACKET = 221;
Phaser.Keyboard.QUOTES = 222;
Phaser.Keyboard.BACKSPACE = 8;
Phaser.Keyboard.TAB = 9;
Phaser.Keyboard.CLEAR = 12;
Phaser.Keyboard.ENTER = 13;
Phaser.Keyboard.SHIFT = 16;
Phaser.Keyboard.CONTROL = 17;
Phaser.Keyboard.ALT = 18;
Phaser.Keyboard.CAPS_LOCK = 20;
Phaser.Keyboard.ESC = 27;
Phaser.Keyboard.SPACEBAR = 32;
Phaser.Keyboard.PAGE_UP = 33;
Phaser.Keyboard.PAGE_DOWN = 34;
Phaser.Keyboard.END = 35;
Phaser.Keyboard.HOME = 36;
Phaser.Keyboard.LEFT = 37;
Phaser.Keyboard.UP = 38;
Phaser.Keyboard.RIGHT = 39;
Phaser.Keyboard.DOWN = 40;
Phaser.Keyboard.INSERT = 45;
Phaser.Keyboard.DELETE = 46;
Phaser.Keyboard.HELP = 47;
Phaser.Keyboard.NUM_LOCK = 144;
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2014 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* Phaser.Mouse is responsible for handling all aspects of mouse interaction with the browser. It captures and processes mouse events.
*
* @class Phaser.Mouse
* @constructor
* @param {Phaser.Game} game - A reference to the currently running game.
*/
Phaser.Mouse = function (game) {
/**
* @property {Phaser.Game} game - A reference to the currently running game.
*/
this.game = game;
/**
* @property {Object} callbackContext - The context under which callbacks are called.
*/
this.callbackContext = this.game;
/**
* @property {function} mouseDownCallback - A callback that can be fired when the mouse is pressed down.
*/
this.mouseDownCallback = null;
/**
* @property {function} mouseMoveCallback - A callback that can be fired when the mouse is moved while pressed down.
*/
this.mouseMoveCallback = null;
/**
* @property {function} mouseUpCallback - A callback that can be fired when the mouse is released from a pressed down state.
*/
this.mouseUpCallback = null;
/**
* @property {boolean} capture - If true the DOM mouse events will have event.preventDefault applied to them, if false they will propogate fully.
*/
this.capture = false;
/**
* @property {number} button- The type of click, either: Phaser.Mouse.NO_BUTTON, Phaser.Mouse.LEFT_BUTTON, Phaser.Mouse.MIDDLE_BUTTON or Phaser.Mouse.RIGHT_BUTTON.
* @default
*/
this.button = -1;
/**
* @property {boolean} disabled - You can disable all Input by setting disabled = true. While set all new input related events will be ignored.
* @default
*/
this.disabled = false;
/**
* @property {boolean} locked - If the mouse has been Pointer Locked successfully this will be set to true.
* @default
*/
this.locked = false;
/**
* @property {Phaser.Signal} pointerLock - This event is dispatched when the browser enters or leaves pointer lock state.
* @default
*/
this.pointerLock = new Phaser.Signal();
/**
* @property {MouseEvent} event - The browser mouse DOM event. Will be set to null if no mouse event has ever been received.
* @default
*/
this.event = null;
/**
* @property {function} _onMouseDown - Internal event handler reference.
* @private
*/
this._onMouseDown = null;
/**
* @property {function} _onMouseMove - Internal event handler reference.
* @private
*/
this._onMouseMove = null;
/**
* @property {function} _onMouseUp - Internal event handler reference.
* @private
*/
this._onMouseUp = null;
};
/**
* @constant
* @type {number}
*/
Phaser.Mouse.NO_BUTTON = -1;
/**
* @constant
* @type {number}
*/
Phaser.Mouse.LEFT_BUTTON = 0;
/**
* @constant
* @type {number}
*/
Phaser.Mouse.MIDDLE_BUTTON = 1;
/**
* @constant
* @type {number}
*/
Phaser.Mouse.RIGHT_BUTTON = 2;
Phaser.Mouse.prototype = {
/**
* Starts the event listeners running.
* @method Phaser.Mouse#start
*/
start: function () {
var _this = this;
if (this.game.device.android && this.game.device.chrome === false)
{
// Android stock browser fires mouse events even if you preventDefault on the touchStart, so ...
return;
}
this._onMouseDown = function (event) {
return _this.onMouseDown(event);
};
this._onMouseMove = function (event) {
return _this.onMouseMove(event);
};
this._onMouseUp = function (event) {
return _this.onMouseUp(event);
};
this.game.canvas.addEventListener('mousedown', this._onMouseDown, true);
this.game.canvas.addEventListener('mousemove', this._onMouseMove, true);
this.game.canvas.addEventListener('mouseup', this._onMouseUp, true);
},
/**
* The internal method that handles the mouse down event from the browser.
* @method Phaser.Mouse#onMouseDown
* @param {MouseEvent} event - The native event from the browser. This gets stored in Mouse.event.
*/
onMouseDown: function (event) {
this.event = event;
if (this.capture)
{
event.preventDefault();
}
this.button = event.button;
if (this.mouseDownCallback)
{
this.mouseDownCallback.call(this.callbackContext, event);
}
if (this.game.input.disabled || this.disabled)
{
return;
}
event['identifier'] = 0;
this.game.input.mousePointer.start(event);
},
/**
* The internal method that handles the mouse move event from the browser.
* @method Phaser.Mouse#onMouseMove
* @param {MouseEvent} event - The native event from the browser. This gets stored in Mouse.event.
*/
onMouseMove: function (event) {
this.event = event;
if (this.capture)
{
event.preventDefault();
}
if (this.mouseMoveCallback)
{
this.mouseMoveCallback.call(this.callbackContext, event);
}
if (this.game.input.disabled || this.disabled)
{
return;
}
event['identifier'] = 0;
this.game.input.mousePointer.move(event);
},
/**
* The internal method that handles the mouse up event from the browser.
* @method Phaser.Mouse#onMouseUp
* @param {MouseEvent} event - The native event from the browser. This gets stored in Mouse.event.
*/
onMouseUp: function (event) {
this.event = event;
if (this.capture)
{
event.preventDefault();
}
this.button = Phaser.Mouse.NO_BUTTON;
if (this.mouseUpCallback)
{
this.mouseUpCallback.call(this.callbackContext, event);
}
if (this.game.input.disabled || this.disabled)
{
return;
}
event['identifier'] = 0;
this.game.input.mousePointer.stop(event);
},
/**
* If the browser supports it you can request that the pointer be locked to the browser window.
* This is classically known as 'FPS controls', where the pointer can't leave the browser until the user presses an exit key.
* If the browser successfully enters a locked state the event Phaser.Mouse.pointerLock will be dispatched and the first parameter will be 'true'.
* @method Phaser.Mouse#requestPointerLock
*/
requestPointerLock: function () {
if (this.game.device.pointerLock)
{
var element = this.game.canvas;
element.requestPointerLock = element.requestPointerLock || element.mozRequestPointerLock || element.webkitRequestPointerLock;
element.requestPointerLock();
var _this = this;
this._pointerLockChange = function (event) {
return _this.pointerLockChange(event);
};
document.addEventListener('pointerlockchange', this._pointerLockChange, true);
document.addEventListener('mozpointerlockchange', this._pointerLockChange, true);
document.addEventListener('webkitpointerlockchange', this._pointerLockChange, true);
}
},
/**
* Internal pointerLockChange handler.
* @method Phaser.Mouse#pointerLockChange
* @param {pointerlockchange} event - The native event from the browser. This gets stored in Mouse.event.
*/
pointerLockChange: function (event) {
var element = this.game.canvas;
if (document.pointerLockElement === element || document.mozPointerLockElement === element || document.webkitPointerLockElement === element)
{
// Pointer was successfully locked
this.locked = true;
this.pointerLock.dispatch(true, event);
}
else
{
// Pointer was unlocked
this.locked = false;
this.pointerLock.dispatch(false, event);
}
},
/**
* Internal release pointer lock handler.
* @method Phaser.Mouse#releasePointerLock
*/
releasePointerLock: function () {
document.exitPointerLock = document.exitPointerLock || document.mozExitPointerLock || document.webkitExitPointerLock;
document.exitPointerLock();
document.removeEventListener('pointerlockchange', this._pointerLockChange, true);
document.removeEventListener('mozpointerlockchange', this._pointerLockChange, true);
document.removeEventListener('webkitpointerlockchange', this._pointerLockChange, true);
},
/**
* Stop the event listeners.
* @method Phaser.Mouse#stop
*/
stop: function () {
this.game.canvas.removeEventListener('mousedown', this._onMouseDown, true);
this.game.canvas.removeEventListener('mousemove', this._onMouseMove, true);
this.game.canvas.removeEventListener('mouseup', this._onMouseUp, true);
}
};
Phaser.Mouse.prototype.constructor = Phaser.Mouse;
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2014 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* Phaser - MSPointer constructor.
*
* @class Phaser.MSPointer
* @classdesc The MSPointer class handles touch interactions with the game and the resulting Pointer objects.
* It will work only in Internet Explorer 10 and Windows Store or Windows Phone 8 apps using JavaScript.
* http://msdn.microsoft.com/en-us/library/ie/hh673557(v=vs.85).aspx
* @constructor
* @param {Phaser.Game} game - A reference to the currently running game.
*/
Phaser.MSPointer = function (game) {
/**
* @property {Phaser.Game} game - A reference to the currently running game.
*/
this.game = game;
/**
* @property {Object} callbackContext - The context under which callbacks are called (defaults to game).
*/
this.callbackContext = this.game;
/**
* You can disable all Input by setting disabled = true. While set all new input related events will be ignored.
* @property {boolean} disabled
*/
this.disabled = false;
/**
* @property {function} _onMSPointerDown - Internal function to handle MSPointer events.
* @private
*/
this._onMSPointerDown = null;
/**
* @property {function} _onMSPointerMove - Internal function to handle MSPointer events.
* @private
*/
this._onMSPointerMove = null;
/**
* @property {function} _onMSPointerUp - Internal function to handle MSPointer events.
* @private
*/
this._onMSPointerUp = null;
};
Phaser.MSPointer.prototype = {
/**
* Starts the event listeners running.
* @method Phaser.MSPointer#start
*/
start: function () {
var _this = this;
if (this.game.device.mspointer === true)
{
this._onMSPointerDown = function (event) {
return _this.onPointerDown(event);
};
this._onMSPointerMove = function (event) {
return _this.onPointerMove(event);
};
this._onMSPointerUp = function (event) {
return _this.onPointerUp(event);
};
this.game.renderer.view.addEventListener('MSPointerDown', this._onMSPointerDown, false);
this.game.renderer.view.addEventListener('MSPointerMove', this._onMSPointerMove, false);
this.game.renderer.view.addEventListener('MSPointerUp', this._onMSPointerUp, false);
// IE11+ uses non-prefix events
this.game.renderer.view.addEventListener('pointerDown', this._onMSPointerDown, false);
this.game.renderer.view.addEventListener('pointerMove', this._onMSPointerMove, false);
this.game.renderer.view.addEventListener('pointerUp', this._onMSPointerUp, false);
this.game.renderer.view.style['-ms-content-zooming'] = 'none';
this.game.renderer.view.style['-ms-touch-action'] = 'none';
}
},
/**
* The function that handles the PointerDown event.
* @method Phaser.MSPointer#onPointerDown
* @param {PointerEvent} event
*/
onPointerDown: function (event) {
if (this.game.input.disabled || this.disabled)
{
return;
}
event.preventDefault();
event.identifier = event.pointerId;
this.game.input.startPointer(event);
},
/**
* The function that handles the PointerMove event.
* @method Phaser.MSPointer#onPointerMove
* @param {PointerEvent } event
*/
onPointerMove: function (event) {
if (this.game.input.disabled || this.disabled)
{
return;
}
event.preventDefault();
event.identifier = event.pointerId;
this.game.input.updatePointer(event);
},
/**
* The function that handles the PointerUp event.
* @method Phaser.MSPointer#onPointerUp
* @param {PointerEvent} event
*/
onPointerUp: function (event) {
if (this.game.input.disabled || this.disabled)
{
return;
}
event.preventDefault();
event.identifier = event.pointerId;
this.game.input.stopPointer(event);
},
/**
* Stop the event listeners.
* @method Phaser.MSPointer#stop
*/
stop: function () {
this.game.canvas.removeEventListener('MSPointerDown', this._onMSPointerDown);
this.game.canvas.removeEventListener('MSPointerMove', this._onMSPointerMove);
this.game.canvas.removeEventListener('MSPointerUp', this._onMSPointerUp);
this.game.canvas.removeEventListener('pointerDown', this._onMSPointerDown);
this.game.canvas.removeEventListener('pointerMove', this._onMSPointerMove);
this.game.canvas.removeEventListener('pointerUp', this._onMSPointerUp);
}
};
Phaser.MSPointer.prototype.constructor = Phaser.MSPointer;
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2014 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* Phaser - Pointer constructor.
*
* @class Phaser.Pointer
* @classdesc A Pointer object is used by the Mouse, Touch and MSPoint managers and represents a single finger on the touch screen.
* @constructor
* @param {Phaser.Game} game - A reference to the currently running game.
* @param {number} id - The ID of the Pointer object within the game. Each game can have up to 10 active pointers.
*/
Phaser.Pointer = function (game, id) {
/**
* @property {Phaser.Game} game - A reference to the currently running game.
*/
this.game = game;
/**
* @property {number} id - The ID of the Pointer object within the game. Each game can have up to 10 active pointers.
*/
this.id = id;
/**
* @property {boolean} _holdSent - Local private variable to store the status of dispatching a hold event.
* @private
* @default
*/
this._holdSent = false;
/**
* @property {array} _history - Local private variable storing the short-term history of pointer movements.
* @private
*/
this._history = [];
/**
* @property {number} _lastDrop - Local private variable storing the time at which the next history drop should occur.
* @private
* @default
*/
this._nextDrop = 0;
/**
* @property {boolean} _stateReset - Monitor events outside of a state reset loop.
* @private
* @default
*/
this._stateReset = false;
/**
* @property {boolean} withinGame - true if the Pointer is within the game area, otherwise false.
*/
this.withinGame = false;
/**
* @property {number} clientX - The horizontal coordinate of point relative to the viewport in pixels, excluding any scroll offset.
* @default
*/
this.clientX = -1;
/**
* @property {number} clientY - The vertical coordinate of point relative to the viewport in pixels, excluding any scroll offset.
* @default
*/
this.clientY = -1;
/**
* @property {number} pageX - The horizontal coordinate of point relative to the viewport in pixels, including any scroll offset.
* @default
*/
this.pageX = -1;
/**
* @property {number} pageY - The vertical coordinate of point relative to the viewport in pixels, including any scroll offset.
* @default
*/
this.pageY = -1;
/**
* @property {number} screenX - The horizontal coordinate of point relative to the screen in pixels.
* @default
*/
this.screenX = -1;
/**
* @property {number} screenY - The vertical coordinate of point relative to the screen in pixels.
* @default
*/
this.screenY = -1;
/**
* @property {number} x - The horizontal coordinate of point relative to the game element. This value is automatically scaled based on game size.
* @default
*/
this.x = -1;
/**
* @property {number} y - The vertical coordinate of point relative to the game element. This value is automatically scaled based on game size.
* @default
*/
this.y = -1;
/**
* @property {boolean} isMouse - If the Pointer is a mouse this is true, otherwise false.
* @default
*/
this.isMouse = false;
/**
* @property {boolean} isDown - If the Pointer is touching the touchscreen, or the mouse button is held down, isDown is set to true.
* @default
*/
this.isDown = false;
/**
* @property {boolean} isUp - If the Pointer is not touching the touchscreen, or the mouse button is up, isUp is set to true.
* @default
*/
this.isUp = true;
/**
* @property {number} timeDown - A timestamp representing when the Pointer first touched the touchscreen.
* @default
*/
this.timeDown = 0;
/**
* @property {number} timeUp - A timestamp representing when the Pointer left the touchscreen.
* @default
*/
this.timeUp = 0;
/**
* @property {number} previousTapTime - A timestamp representing when the Pointer was last tapped or clicked.
* @default
*/
this.previousTapTime = 0;
/**
* @property {number} totalTouches - The total number of times this Pointer has been touched to the touchscreen.
* @default
*/
this.totalTouches = 0;
/**
* @property {number} msSinceLastClick - The number of miliseconds since the last click.
* @default
*/
this.msSinceLastClick = Number.MAX_VALUE;
/**
* @property {any} targetObject - The Game Object this Pointer is currently over / touching / dragging.
* @default
*/
this.targetObject = null;
/**
* @property {boolean} active - An active pointer is one that is currently pressed down on the display. A Mouse is always active.
* @default
*/
this.active = false;
/**
* @property {Phaser.Point} position - A Phaser.Point object containing the current x/y values of the pointer on the display.
*/
this.position = new Phaser.Point();
/**
* @property {Phaser.Point} positionDown - A Phaser.Point object containing the x/y values of the pointer when it was last in a down state on the display.
*/
this.positionDown = new Phaser.Point();
/**
* A Phaser.Circle that is centered on the x/y coordinates of this pointer, useful for hit detection.
* The Circle size is 44px (Apples recommended "finger tip" size).
* @property {Phaser.Circle} circle
*/
this.circle = new Phaser.Circle(0, 0, 44);
if (id === 0)
{
this.isMouse = true;
}
};
Phaser.Pointer.prototype = {
/**
* Called when the Pointer is pressed onto the touchscreen.
* @method Phaser.Pointer#start
* @param {Any} event
*/
start: function (event) {
this.identifier = event.identifier;
this.target = event.target;
if (typeof event.button !== 'undefined')
{
this.button = event.button;
}
this._history.length = 0;
this.active = true;
this.withinGame = true;
this.isDown = true;
this.isUp = false;
// Work out how long it has been since the last click
this.msSinceLastClick = this.game.time.now - this.timeDown;
this.timeDown = this.game.time.now;
this._holdSent = false;
// This sets the x/y and other local values
this.move(event, true);
// x and y are the old values here?
this.positionDown.setTo(this.x, this.y);
if (this.game.input.multiInputOverride === Phaser.Input.MOUSE_OVERRIDES_TOUCH || this.game.input.multiInputOverride === Phaser.Input.MOUSE_TOUCH_COMBINE || (this.game.input.multiInputOverride === Phaser.Input.TOUCH_OVERRIDES_MOUSE && this.game.input.currentPointers === 0))
{
this.game.input.x = this.x;
this.game.input.y = this.y;
this.game.input.position.setTo(this.x, this.y);
this.game.input.onDown.dispatch(this, event);
this.game.input.resetSpeed(this.x, this.y);
}
this._stateReset = false;
this.totalTouches++;
if (!this.isMouse)
{
this.game.input.currentPointers++;
}
if (this.targetObject !== null)
{
this.targetObject._touchedHandler(this);
}
return this;
},
/**
* Called by the Input Manager.
* @method Phaser.Pointer#update
*/
update: function () {
if (this.active)
{
if (this._holdSent === false && this.duration >= this.game.input.holdRate)
{
if (this.game.input.multiInputOverride == Phaser.Input.MOUSE_OVERRIDES_TOUCH || this.game.input.multiInputOverride == Phaser.Input.MOUSE_TOUCH_COMBINE || (this.game.input.multiInputOverride == Phaser.Input.TOUCH_OVERRIDES_MOUSE && this.game.input.currentPointers === 0))
{
this.game.input.onHold.dispatch(this);
}
this._holdSent = true;
}
// Update the droppings history
if (this.game.input.recordPointerHistory && this.game.time.now >= this._nextDrop)
{
this._nextDrop = this.game.time.now + this.game.input.recordRate;
this._history.push({
x: this.position.x,
y: this.position.y
});
if (this._history.length > this.game.input.recordLimit)
{
this._history.shift();
}
}
}
},
/**
* Called when the Pointer is moved.
* @method Phaser.Pointer#move
* @param {MouseEvent|PointerEvent|TouchEvent} event - The event passed up from the input handler.
* @param {boolean} [fromClick=false] - Was this called from the click event?
*/
move: function (event, fromClick) {
if (this.game.input.pollLocked)
{
return;
}
if (typeof fromClick === 'undefined') { fromClick = false; }
if (typeof event.button !== 'undefined')
{
this.button = event.button;
}
this.clientX = event.clientX;
this.clientY = event.clientY;
this.pageX = event.pageX;
this.pageY = event.pageY;
this.screenX = event.screenX;
this.screenY = event.screenY;
this.x = (this.pageX - this.game.stage.offset.x) * this.game.input.scale.x;
this.y = (this.pageY - this.game.stage.offset.y) * this.game.input.scale.y;
this.position.setTo(this.x, this.y);
this.circle.x = this.x;
this.circle.y = this.y;
if (this.game.input.multiInputOverride == Phaser.Input.MOUSE_OVERRIDES_TOUCH || this.game.input.multiInputOverride == Phaser.Input.MOUSE_TOUCH_COMBINE || (this.game.input.multiInputOverride == Phaser.Input.TOUCH_OVERRIDES_MOUSE && this.game.input.currentPointers === 0))
{
this.game.input.activePointer = this;
this.game.input.x = this.x;
this.game.input.y = this.y;
this.game.input.position.setTo(this.game.input.x, this.game.input.y);
this.game.input.circle.x = this.game.input.x;
this.game.input.circle.y = this.game.input.y;
}
// If the game is paused we don't process any target objects or callbacks
if (this.game.paused)
{
return this;
}
if (this.game.input.moveCallback)
{
this.game.input.moveCallback.call(this.game.input.moveCallbackContext, this, this.x, this.y);
}
// Easy out if we're dragging something and it still exists
if (this.targetObject !== null && this.targetObject.isDragged === true)
{
if (this.targetObject.update(this) === false)
{
this.targetObject = null;
}
return this;
}
// Work out which object is on the top
this._highestRenderOrderID = Number.MAX_SAFE_INTEGER;
this._highestRenderObject = null;
this._highestInputPriorityID = -1;
// Just run through the linked list
if (this.game.input.interactiveItems.total > 0)
{
var currentNode = this.game.input.interactiveItems.next;
do
{
// If the object is using pixelPerfect checks, or has a higher InputManager.PriorityID OR if the priority ID is the same as the current highest AND it has a higher renderOrderID, then set it to the top
if (currentNode.pixelPerfectClick || currentNode.pixelPerfectOver || currentNode.priorityID > this._highestInputPriorityID || (currentNode.priorityID === this._highestInputPriorityID && currentNode.sprite._cache[3] < this._highestRenderOrderID))
{
if ((!fromClick && currentNode.checkPointerOver(this)) || (fromClick && currentNode.checkPointerDown(this)))
{
this._highestRenderOrderID = currentNode.sprite._cache[3]; // renderOrderID
this._highestInputPriorityID = currentNode.priorityID;
this._highestRenderObject = currentNode;
}
}
currentNode = currentNode.next;
}
while (currentNode != null)
}
if (this._highestRenderObject === null)
{
// The pointer isn't currently over anything, check if we've got a lingering previous target
if (this.targetObject)
{
// console.log("The pointer isn't currently over anything, check if we've got a lingering previous target");
this.targetObject._pointerOutHandler(this);
this.targetObject = null;
}
}
else
{
if (this.targetObject === null)
{
// And now set the new one
// console.log('And now set the new one');
this.targetObject = this._highestRenderObject;
this._highestRenderObject._pointerOverHandler(this);
}
else
{
// We've got a target from the last update
// console.log("We've got a target from the last update");
if (this.targetObject === this._highestRenderObject)
{
// Same target as before, so update it
// console.log("Same target as before, so update it");
if (this._highestRenderObject.update(this) === false)
{
this.targetObject = null;
}
}
else
{
// The target has changed, so tell the old one we've left it
// console.log("The target has changed, so tell the old one we've left it");
this.targetObject._pointerOutHandler(this);
// And now set the new one
this.targetObject = this._highestRenderObject;
this.targetObject._pointerOverHandler(this);
}
}
}
return this;
},
/**
* Called when the Pointer leaves the target area.
* @method Phaser.Pointer#leave
* @param {MouseEvent|PointerEvent|TouchEvent} event - The event passed up from the input handler.
*/
leave: function (event) {
this.withinGame = false;
this.move(event, false);
},
/**
* Called when the Pointer leaves the touchscreen.
* @method Phaser.Pointer#stop
* @param {MouseEvent|PointerEvent|TouchEvent} event - The event passed up from the input handler.
*/
stop: function (event) {
if (this._stateReset)
{
event.preventDefault();
return;
}
this.timeUp = this.game.time.now;
if (this.game.input.multiInputOverride == Phaser.Input.MOUSE_OVERRIDES_TOUCH || this.game.input.multiInputOverride == Phaser.Input.MOUSE_TOUCH_COMBINE || (this.game.input.multiInputOverride == Phaser.Input.TOUCH_OVERRIDES_MOUSE && this.game.input.currentPointers === 0))
{
this.game.input.onUp.dispatch(this, event);
// Was it a tap?
if (this.duration >= 0 && this.duration <= this.game.input.tapRate)
{
// Was it a double-tap?
if (this.timeUp - this.previousTapTime < this.game.input.doubleTapRate)
{
// Yes, let's dispatch the signal then with the 2nd parameter set to true
this.game.input.onTap.dispatch(this, true);
}
else
{
// Wasn't a double-tap, so dispatch a single tap signal
this.game.input.onTap.dispatch(this, false);
}
this.previousTapTime = this.timeUp;
}
}
// Mouse is always active
if (this.id > 0)
{
this.active = false;
}
this.withinGame = false;
this.isDown = false;
this.isUp = true;
if (this.isMouse === false)
{
this.game.input.currentPointers--;
}
if (this.game.input.interactiveItems.total > 0)
{
var currentNode = this.game.input.interactiveItems.next;
do
{
if (currentNode)
{
currentNode._releasedHandler(this);
}
currentNode = currentNode.next;
}
while (currentNode != null)
}
if (this.targetObject)
{
this.targetObject._releasedHandler(this);
}
this.targetObject = null;
return this;
},
/**
* The Pointer is considered justPressed if the time it was pressed onto the touchscreen or clicked is less than justPressedRate.
* Note that calling justPressed doesn't reset the pressed status of the Pointer, it will return `true` for as long as the duration is valid.
* If you wish to check if the Pointer was pressed down just once then see the Sprite.events.onInputDown event.
* @method Phaser.Pointer#justPressed
* @param {number} [duration] - The time to check against. If none given it will use InputManager.justPressedRate.
* @return {boolean} true if the Pointer was pressed down within the duration given.
*/
justPressed: function (duration) {
duration = duration || this.game.input.justPressedRate;
return (this.isDown === true && (this.timeDown + duration) > this.game.time.now);
},
/**
* The Pointer is considered justReleased if the time it left the touchscreen is less than justReleasedRate.
* Note that calling justReleased doesn't reset the pressed status of the Pointer, it will return `true` for as long as the duration is valid.
* If you wish to check if the Pointer was released just once then see the Sprite.events.onInputUp event.
* @method Phaser.Pointer#justReleased
* @param {number} [duration] - The time to check against. If none given it will use InputManager.justReleasedRate.
* @return {boolean} true if the Pointer was released within the duration given.
*/
justReleased: function (duration) {
duration = duration || this.game.input.justReleasedRate;
return (this.isUp === true && (this.timeUp + duration) > this.game.time.now);
},
/**
* Resets the Pointer properties. Called by InputManager.reset when you perform a State change.
* @method Phaser.Pointer#reset
*/
reset: function () {
if (this.isMouse === false)
{
this.active = false;
}
this.identifier = null;
this.isDown = false;
this.isUp = true;
this.totalTouches = 0;
this._holdSent = false;
this._history.length = 0;
this._stateReset = true;
if (this.targetObject)
{
this.targetObject._releasedHandler(this);
}
this.targetObject = null;
}
};
Phaser.Pointer.prototype.constructor = Phaser.Pointer;
/**
* How long the Pointer has been depressed on the touchscreen. If not currently down it returns -1.
* @name Phaser.Pointer#duration
* @property {number} duration - How long the Pointer has been depressed on the touchscreen. If not currently down it returns -1.
* @readonly
*/
Object.defineProperty(Phaser.Pointer.prototype, "duration", {
get: function () {
if (this.isUp)
{
return -1;
}
return this.game.time.now - this.timeDown;
}
});
/**
* Gets the X value of this Pointer in world coordinates based on the world camera.
* @name Phaser.Pointer#worldX
* @property {number} duration - The X value of this Pointer in world coordinates based on the world camera.
* @readonly
*/
Object.defineProperty(Phaser.Pointer.prototype, "worldX", {
get: function () {
return this.game.world.camera.x + this.x;
}
});
/**
* Gets the Y value of this Pointer in world coordinates based on the world camera.
* @name Phaser.Pointer#worldY
* @property {number} duration - The Y value of this Pointer in world coordinates based on the world camera.
* @readonly
*/
Object.defineProperty(Phaser.Pointer.prototype, "worldY", {
get: function () {
return this.game.world.camera.y + this.y;
}
});
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2014 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* Phaser.Touch handles touch events with your game. Note: Android 2.x only supports 1 touch event at once, no multi-touch.
*
* @class Phaser.Touch
* @classdesc The Touch class handles touch interactions with the game and the resulting Pointer objects.
* @constructor
* @param {Phaser.Game} game - A reference to the currently running game.
*/
Phaser.Touch = function (game) {
/**
* @property {Phaser.Game} game - A reference to the currently running game.
*/
this.game = game;
/**
* @property {boolean} disabled - You can disable all Touch events by setting disabled = true. While set all new touch events will be ignored.
* @return {boolean}
*/
this.disabled = false;
/**
* @property {Object} callbackContext - The context under which callbacks are called.
*/
this.callbackContext = this.game;
/**
* @property {function} touchStartCallback - A callback that can be fired on a touchStart event.
*/
this.touchStartCallback = null;
/**
* @property {function} touchMoveCallback - A callback that can be fired on a touchMove event.
*/
this.touchMoveCallback = null;
/**
* @property {function} touchEndCallback - A callback that can be fired on a touchEnd event.
*/
this.touchEndCallback = null;
/**
* @property {function} touchEnterCallback - A callback that can be fired on a touchEnter event.
*/
this.touchEnterCallback = null;
/**
* @property {function} touchLeaveCallback - A callback that can be fired on a touchLeave event.
*/
this.touchLeaveCallback = null;
/**
* @property {function} touchCancelCallback - A callback that can be fired on a touchCancel event.
*/
this.touchCancelCallback = null;
/**
* @property {boolean} preventDefault - If true the TouchEvent will have prevent.default called on it.
* @default
*/
this.preventDefault = true;
/**
* @property {TouchEvent} event - The browser touch DOM event. Will be set to null if no touch event has ever been received.
* @default
*/
this.event = null;
/**
* @property {function} _onTouchStart - Internal event handler reference.
* @private
*/
this._onTouchStart = null;
/**
* @property {function} _onTouchMove - Internal event handler reference.
* @private
*/
this._onTouchMove = null;
/**
* @property {function} _onTouchEnd - Internal event handler reference.
* @private
*/
this._onTouchEnd = null;
/**
* @property {function} _onTouchEnter - Internal event handler reference.
* @private
*/
this._onTouchEnter = null;
/**
* @property {function} _onTouchLeave - Internal event handler reference.
* @private
*/
this._onTouchLeave = null;
/**
* @property {function} _onTouchCancel - Internal event handler reference.
* @private
*/
this._onTouchCancel = null;
/**
* @property {function} _onTouchMove - Internal event handler reference.
* @private
*/
this._onTouchMove = null;
};
Phaser.Touch.prototype = {
/**
* Starts the event listeners running.
* @method Phaser.Touch#start
*/
start: function () {
var _this = this;
if (this.game.device.touch)
{
this._onTouchStart = function (event) {
return _this.onTouchStart(event);
};
this._onTouchMove = function (event) {
return _this.onTouchMove(event);
};
this._onTouchEnd = function (event) {
return _this.onTouchEnd(event);
};
this._onTouchEnter = function (event) {
return _this.onTouchEnter(event);
};
this._onTouchLeave = function (event) {
return _this.onTouchLeave(event);
};
this._onTouchCancel = function (event) {
return _this.onTouchCancel(event);
};
this.game.canvas.addEventListener('touchstart', this._onTouchStart, false);
this.game.canvas.addEventListener('touchmove', this._onTouchMove, false);
this.game.canvas.addEventListener('touchend', this._onTouchEnd, false);
this.game.canvas.addEventListener('touchenter', this._onTouchEnter, false);
this.game.canvas.addEventListener('touchleave', this._onTouchLeave, false);
this.game.canvas.addEventListener('touchcancel', this._onTouchCancel, false);
}
},
/**
* Consumes all touchmove events on the document (only enable this if you know you need it!).
* @method Phaser.Touch#consumeTouchMove
*/
consumeDocumentTouches: function () {
this._documentTouchMove = function (event) {
event.preventDefault();
};
document.addEventListener('touchmove', this._documentTouchMove, false);
},
/**
* The internal method that handles the touchstart event from the browser.
* @method Phaser.Touch#onTouchStart
* @param {TouchEvent} event - The native event from the browser. This gets stored in Touch.event.
*/
onTouchStart: function (event) {
this.event = event;
if (this.touchStartCallback)
{
this.touchStartCallback.call(this.callbackContext, event);
}
if (this.game.input.disabled || this.disabled)
{
return;
}
if (this.preventDefault)
{
event.preventDefault();
}
// event.targetTouches = list of all touches on the TARGET ELEMENT (i.e. game dom element)
// event.touches = list of all touches on the ENTIRE DOCUMENT, not just the target element
// event.changedTouches = the touches that CHANGED in this event, not the total number of them
for (var i = 0; i < event.changedTouches.length; i++)
{
this.game.input.startPointer(event.changedTouches[i]);
}
},
/**
* Touch cancel - touches that were disrupted (perhaps by moving into a plugin or browser chrome).
* Occurs for example on iOS when you put down 4 fingers and the app selector UI appears.
* @method Phaser.Touch#onTouchCancel
* @param {TouchEvent} event - The native event from the browser. This gets stored in Touch.event.
*/
onTouchCancel: function (event) {
this.event = event;
if (this.touchCancelCallback)
{
this.touchCancelCallback.call(this.callbackContext, event);
}
if (this.game.input.disabled || this.disabled)
{
return;
}
if (this.preventDefault)
{
event.preventDefault();
}
// Touch cancel - touches that were disrupted (perhaps by moving into a plugin or browser chrome)
// http://www.w3.org/TR/touch-events/#dfn-touchcancel
for (var i = 0; i < event.changedTouches.length; i++)
{
this.game.input.stopPointer(event.changedTouches[i]);
}
},
/**
* For touch enter and leave its a list of the touch points that have entered or left the target.
* Doesn't appear to be supported by most browsers on a canvas element yet.
* @method Phaser.Touch#onTouchEnter
* @param {TouchEvent} event - The native event from the browser. This gets stored in Touch.event.
*/
onTouchEnter: function (event) {
this.event = event;
if (this.touchEnterCallback)
{
this.touchEnterCallback.call(this.callbackContext, event);
}
if (this.game.input.disabled || this.disabled)
{
return;
}
if (this.preventDefault)
{
event.preventDefault();
}
},
/**
* For touch enter and leave its a list of the touch points that have entered or left the target.
* Doesn't appear to be supported by most browsers on a canvas element yet.
* @method Phaser.Touch#onTouchLeave
* @param {TouchEvent} event - The native event from the browser. This gets stored in Touch.event.
*/
onTouchLeave: function (event) {
this.event = event;
if (this.touchLeaveCallback)
{
this.touchLeaveCallback.call(this.callbackContext, event);
}
if (this.preventDefault)
{
event.preventDefault();
}
},
/**
* The handler for the touchmove events.
* @method Phaser.Touch#onTouchMove
* @param {TouchEvent} event - The native event from the browser. This gets stored in Touch.event.
*/
onTouchMove: function (event) {
this.event = event;
if (this.touchMoveCallback)
{
this.touchMoveCallback.call(this.callbackContext, event);
}
if (this.preventDefault)
{
event.preventDefault();
}
for (var i = 0; i < event.changedTouches.length; i++)
{
this.game.input.updatePointer(event.changedTouches[i]);
}
},
/**
* The handler for the touchend events.
* @method Phaser.Touch#onTouchEnd
* @param {TouchEvent} event - The native event from the browser. This gets stored in Touch.event.
*/
onTouchEnd: function (event) {
this.event = event;
if (this.touchEndCallback)
{
this.touchEndCallback.call(this.callbackContext, event);
}
if (this.preventDefault)
{
event.preventDefault();
}
// For touch end its a list of the touch points that have been removed from the surface
// https://developer.mozilla.org/en-US/docs/DOM/TouchList
// event.changedTouches = the touches that CHANGED in this event, not the total number of them
for (var i = 0; i < event.changedTouches.length; i++)
{
this.game.input.stopPointer(event.changedTouches[i]);
}
},
/**
* Stop the event listeners.
* @method Phaser.Touch#stop
*/
stop: function () {
if (this.game.device.touch)
{
this.game.canvas.removeEventListener('touchstart', this._onTouchStart);
this.game.canvas.removeEventListener('touchmove', this._onTouchMove);
this.game.canvas.removeEventListener('touchend', this._onTouchEnd);
this.game.canvas.removeEventListener('touchenter', this._onTouchEnter);
this.game.canvas.removeEventListener('touchleave', this._onTouchLeave);
this.game.canvas.removeEventListener('touchcancel', this._onTouchCancel);
}
}
};
Phaser.Touch.prototype.constructor = Phaser.Touch;
/**
* @author @karlmacklin <tacklemcclean@gmail.com>
* @copyright 2014 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* The Gamepad class handles looking after gamepad input for your game.
* Remember to call gamepad.start(); expecting input!
*
* HTML5 GAMEPAD API SUPPORT IS AT AN EXPERIMENTAL STAGE!
* At moment of writing this (end of 2013) only Chrome supports parts of it out of the box. Firefox supports it
* via prefs flags (about:config, search gamepad). The browsers map the same controllers differently.
* This class has constans for Windows 7 Chrome mapping of
* XBOX 360 controller.
*
* @class Phaser.Gamepad
* @constructor
* @param {Phaser.Game} game - A reference to the currently running game.
*/
Phaser.Gamepad = function (game) {
/**
* @property {Phaser.Game} game - Local reference to game.
*/
this.game = game;
/**
* @property {Array<Phaser.SinglePad>} _gamepads - The four Phaser Gamepads.
* @private
*/
this._gamepads = [
new Phaser.SinglePad(game, this),
new Phaser.SinglePad(game, this),
new Phaser.SinglePad(game, this),
new Phaser.SinglePad(game, this)
];
/**
* @property {Object} _gamepadIndexMap - Maps the browsers gamepad indices to our Phaser Gamepads
* @private
*/
this._gamepadIndexMap = {};
/**
* @property {Array} _rawPads - The raw state of the gamepads from the browser
* @private
*/
this._rawPads = [];
/**
* @property {boolean} _active - Private flag for whether or not the API is polled
* @private
* @default
*/
this._active = false;
/**
* You can disable all Gamepad Input by setting disabled to true. While true all new input related events will be ignored.
* @property {boolean} disabled - The disabled state of the Gamepad.
* @default
*/
this.disabled = false;
/**
* Whether or not gamepads are supported in the current browser. Note that as of Dec. 2013 this check is actually not accurate at all due to poor implementation.
* @property {boolean} _gamepadSupportAvailable - Are gamepads supported in this browser or not?
* @private
*/
this._gamepadSupportAvailable = !!navigator.webkitGetGamepads || !!navigator.webkitGamepads || (navigator.userAgent.indexOf('Firefox/') != -1) || !!navigator.getGamepads;
/**
* Used to check for differences between earlier polls and current state of gamepads.
* @property {Array} _prevRawGamepadTypes
* @private
* @default
*/
this._prevRawGamepadTypes = [];
/**
* Used to check for differences between earlier polls and current state of gamepads.
* @property {Array} _prevTimestamps
* @private
* @default
*/
this._prevTimestamps = [];
/**
* @property {Object} callbackContext - The context under which the callbacks are run.
*/
this.callbackContext = this;
/**
* @property {function} onConnectCallback - This callback is invoked every time any gamepad is connected
*/
this.onConnectCallback = null;
/**
* @property {function} onDisconnectCallback - This callback is invoked every time any gamepad is disconnected
*/
this.onDisconnectCallback = null;
/**
* @property {function} onDownCallback - This callback is invoked every time any gamepad button is pressed down.
*/
this.onDownCallback = null;
/**
* @property {function} onUpCallback - This callback is invoked every time any gamepad button is released.
*/
this.onUpCallback = null;
/**
* @property {function} onAxisCallback - This callback is invoked every time any gamepad axis is changed.
*/
this.onAxisCallback = null;
/**
* @property {function} onFloatCallback - This callback is invoked every time any gamepad button is changed to a value where value > 0 and value < 1.
*/
this.onFloatCallback = null;
/**
* @property {function} _ongamepadconnected - Private callback for Firefox gamepad connection handling
* @private
*/
this._ongamepadconnected = null;
/**
* @property {function} _gamepaddisconnected - Private callback for Firefox gamepad connection handling
* @private
*/
this._gamepaddisconnected = null;
};
Phaser.Gamepad.prototype = {
/**
* Add callbacks to the main Gamepad handler to handle connect/disconnect/button down/button up/axis change/float value buttons
* @method Phaser.Gamepad#addCallbacks
* @param {Object} context - The context under which the callbacks are run.
* @param {Object} callbacks - Object that takes six different callback methods:
* onConnectCallback, onDisconnectCallback, onDownCallback, onUpCallback, onAxisCallback, onFloatCallback
*/
addCallbacks: function (context, callbacks) {
if (typeof callbacks !== 'undefined')
{
this.onConnectCallback = (typeof callbacks.onConnect === 'function') ? callbacks.onConnect : this.onConnectCallback;
this.onDisconnectCallback = (typeof callbacks.onDisconnect === 'function') ? callbacks.onDisconnect : this.onDisconnectCallback;
this.onDownCallback = (typeof callbacks.onDown === 'function') ? callbacks.onDown : this.onDownCallback;
this.onUpCallback = (typeof callbacks.onUp === 'function') ? callbacks.onUp : this.onUpCallback;
this.onAxisCallback = (typeof callbacks.onAxis === 'function') ? callbacks.onAxis : this.onAxisCallback;
this.onFloatCallback = (typeof callbacks.onFloat === 'function') ? callbacks.onFloat : this.onFloatCallback;
}
},
/**
* Starts the Gamepad event handling.
* This MUST be called manually before Phaser will start polling the Gamepad API.
*
* @method Phaser.Gamepad#start
*/
start: function () {
this._active = true;
var _this = this;
this._ongamepadconnected = function(event) {
var newPad = event.gamepad;
_this._rawPads.push(newPad);
_this._gamepads[newPad.index].connect(newPad);
};
window.addEventListener('gamepadconnected', this._ongamepadconnected, false);
this._ongamepaddisconnected = function(event) {
var removedPad = event.gamepad;
for (var i in _this._rawPads)
{
if (_this._rawPads[i].index === removedPad.index)
{
_this._rawPads.splice(i,1);
}
}
_this._gamepads[removedPad.index].disconnect();
};
window.addEventListener('gamepaddisconnected', this._ongamepaddisconnected, false);
},
/**
* Main gamepad update loop. Should not be called manually.
* @method Phaser.Gamepad#update
* @private
*/
update: function () {
this._pollGamepads();
for (var i = 0; i < this._gamepads.length; i++)
{
if (this._gamepads[i]._connected)
{
this._gamepads[i].pollStatus();
}
}
},
/**
* Updating connected gamepads (for Google Chrome).
* Should not be called manually.
* @method Phaser.Gamepad#_pollGamepads
* @private
*/
_pollGamepads: function () {
var rawGamepads = (navigator.webkitGetGamepads && navigator.webkitGetGamepads()) || navigator.webkitGamepads || navigator.getGamepads;
if (rawGamepads)
{
this._rawPads = [];
var gamepadsChanged = false;
for (var i = 0; i < rawGamepads.length; i++)
{
if (typeof rawGamepads[i] !== this._prevRawGamepadTypes[i])
{
gamepadsChanged = true;
this._prevRawGamepadTypes[i] = typeof rawGamepads[i];
}
if (rawGamepads[i])
{
this._rawPads.push(rawGamepads[i]);
}
// Support max 4 pads at the moment
if (i === 3)
{
break;
}
}
if (gamepadsChanged)
{
var validConnections = { rawIndices: {}, padIndices: {} };
var singlePad;
for (var j = 0; j < this._gamepads.length; j++)
{
singlePad = this._gamepads[j];
if (singlePad.connected)
{
for (var k = 0; k < this._rawPads.length; k++)
{
if (this._rawPads[k].index === singlePad.index)
{
validConnections.rawIndices[singlePad.index] = true;
validConnections.padIndices[j] = true;
}
}
}
}
for (var l = 0; l < this._gamepads.length; l++)
{
singlePad = this._gamepads[l];
if (validConnections.padIndices[l])
{
continue;
}
if (this._rawPads.length < 1)
{
singlePad.disconnect();
}
for (var m = 0; m < this._rawPads.length; m++)
{
if (validConnections.padIndices[l])
{
break;
}
var rawPad = this._rawPads[m];
if (rawPad)
{
if (validConnections.rawIndices[rawPad.index])
{
singlePad.disconnect();
continue;
}
else
{
singlePad.connect(rawPad);
validConnections.rawIndices[rawPad.index] = true;
validConnections.padIndices[l] = true;
}
}
else
{
singlePad.disconnect();
}
}
}
}
}
},
/**
* Sets the deadZone variable for all four gamepads
* @method Phaser.Gamepad#setDeadZones
*/
setDeadZones: function (value) {
for (var i = 0; i < this._gamepads.length; i++)
{
this._gamepads[i].deadZone = value;
}
},
/**
* Stops the Gamepad event handling.
*
* @method Phaser.Gamepad#stop
*/
stop: function () {
this._active = false;
window.removeEventListener('gamepadconnected', this._ongamepadconnected);
window.removeEventListener('gamepaddisconnected', this._ongamepaddisconnected);
},
/**
* Reset all buttons/axes of all gamepads
* @method Phaser.Gamepad#reset
*/
reset: function () {
this.update();
for (var i = 0; i < this._gamepads.length; i++)
{
this._gamepads[i].reset();
}
},
/**
* Returns the "just pressed" state of a button from ANY gamepad connected. Just pressed is considered true if the button was pressed down within the duration given (default 250ms).
* @method Phaser.Gamepad#justPressed
* @param {number} buttonCode - The buttonCode of the button to check for.
* @param {number} [duration=250] - The duration below which the button is considered as being just pressed.
* @return {boolean} True if the button is just pressed otherwise false.
*/
justPressed: function (buttonCode, duration) {
for (var i = 0; i < this._gamepads.length; i++)
{
if (this._gamepads[i].justPressed(buttonCode, duration) === true)
{
return true;
}
}
return false;
},
/**
* Returns the "just released" state of a button from ANY gamepad connected. Just released is considered as being true if the button was released within the duration given (default 250ms).
* @method Phaser.Gamepad#justPressed
* @param {number} buttonCode - The buttonCode of the button to check for.
* @param {number} [duration=250] - The duration below which the button is considered as being just released.
* @return {boolean} True if the button is just released otherwise false.
*/
justReleased: function (buttonCode, duration) {
for (var i = 0; i < this._gamepads.length; i++)
{
if (this._gamepads[i].justReleased(buttonCode, duration) === true)
{
return true;
}
}
return false;
},
/**
* Returns true if the button is currently pressed down, on ANY gamepad.
* @method Phaser.Gamepad#isDown
* @param {number} buttonCode - The buttonCode of the button to check for.
* @return {boolean} True if a button is currently down.
*/
isDown: function (buttonCode) {
for (var i = 0; i < this._gamepads.length; i++)
{
if (this._gamepads[i].isDown(buttonCode) === true)
{
return true;
}
}
return false;
}
};
Phaser.Gamepad.prototype.constructor = Phaser.Gamepad;
/**
* If the gamepad input is active or not - if not active it should not be updated from Input.js
* @name Phaser.Gamepad#active
* @property {boolean} active - If the gamepad input is active or not.
* @readonly
*/
Object.defineProperty(Phaser.Gamepad.prototype, "active", {
get: function () {
return this._active;
}
});
/**
* Whether or not gamepads are supported in current browser.
* @name Phaser.Gamepad#supported
* @property {boolean} supported - Whether or not gamepads are supported in current browser.
* @readonly
*/
Object.defineProperty(Phaser.Gamepad.prototype, "supported", {
get: function () {
return this._gamepadSupportAvailable;
}
});
/**
* How many live gamepads are currently connected.
* @name Phaser.Gamepad#padsConnected
* @property {boolean} padsConnected - How many live gamepads are currently connected.
* @readonly
*/
Object.defineProperty(Phaser.Gamepad.prototype, "padsConnected", {
get: function () {
return this._rawPads.length;
}
});
/**
* Gamepad #1
* @name Phaser.Gamepad#pad1
* @property {boolean} pad1 - Gamepad #1;
* @readonly
*/
Object.defineProperty(Phaser.Gamepad.prototype, "pad1", {
get: function () {
return this._gamepads[0];
}
});
/**
* Gamepad #2
* @name Phaser.Gamepad#pad2
* @property {boolean} pad2 - Gamepad #2
* @readonly
*/
Object.defineProperty(Phaser.Gamepad.prototype, "pad2", {
get: function () {
return this._gamepads[1];
}
});
/**
* Gamepad #3
* @name Phaser.Gamepad#pad3
* @property {boolean} pad3 - Gamepad #3
* @readonly
*/
Object.defineProperty(Phaser.Gamepad.prototype, "pad3", {
get: function () {
return this._gamepads[2];
}
});
/**
* Gamepad #4
* @name Phaser.Gamepad#pad4
* @property {boolean} pad4 - Gamepad #4
* @readonly
*/
Object.defineProperty(Phaser.Gamepad.prototype, "pad4", {
get: function () {
return this._gamepads[3];
}
});
Phaser.Gamepad.BUTTON_0 = 0;
Phaser.Gamepad.BUTTON_1 = 1;
Phaser.Gamepad.BUTTON_2 = 2;
Phaser.Gamepad.BUTTON_3 = 3;
Phaser.Gamepad.BUTTON_4 = 4;
Phaser.Gamepad.BUTTON_5 = 5;
Phaser.Gamepad.BUTTON_6 = 6;
Phaser.Gamepad.BUTTON_7 = 7;
Phaser.Gamepad.BUTTON_8 = 8;
Phaser.Gamepad.BUTTON_9 = 9;
Phaser.Gamepad.BUTTON_10 = 10;
Phaser.Gamepad.BUTTON_11 = 11;
Phaser.Gamepad.BUTTON_12 = 12;
Phaser.Gamepad.BUTTON_13 = 13;
Phaser.Gamepad.BUTTON_14 = 14;
Phaser.Gamepad.BUTTON_15 = 15;
Phaser.Gamepad.AXIS_0 = 0;
Phaser.Gamepad.AXIS_1 = 1;
Phaser.Gamepad.AXIS_2 = 2;
Phaser.Gamepad.AXIS_3 = 3;
Phaser.Gamepad.AXIS_4 = 4;
Phaser.Gamepad.AXIS_5 = 5;
Phaser.Gamepad.AXIS_6 = 6;
Phaser.Gamepad.AXIS_7 = 7;
Phaser.Gamepad.AXIS_8 = 8;
Phaser.Gamepad.AXIS_9 = 9;
// Below mapping applies to XBOX 360 Wired and Wireless controller on Google Chrome (tested on Windows 7).
// - Firefox uses different map! Separate amount of buttons and axes. DPAD = axis and not a button.
// In other words - discrepancies when using gamepads.
Phaser.Gamepad.XBOX360_A = 0;
Phaser.Gamepad.XBOX360_B = 1;
Phaser.Gamepad.XBOX360_X = 2;
Phaser.Gamepad.XBOX360_Y = 3;
Phaser.Gamepad.XBOX360_LEFT_BUMPER = 4;
Phaser.Gamepad.XBOX360_RIGHT_BUMPER = 5;
Phaser.Gamepad.XBOX360_LEFT_TRIGGER = 6;
Phaser.Gamepad.XBOX360_RIGHT_TRIGGER = 7;
Phaser.Gamepad.XBOX360_BACK = 8;
Phaser.Gamepad.XBOX360_START = 9;
Phaser.Gamepad.XBOX360_STICK_LEFT_BUTTON = 10;
Phaser.Gamepad.XBOX360_STICK_RIGHT_BUTTON = 11;
Phaser.Gamepad.XBOX360_DPAD_LEFT = 14;
Phaser.Gamepad.XBOX360_DPAD_RIGHT = 15;
Phaser.Gamepad.XBOX360_DPAD_UP = 12;
Phaser.Gamepad.XBOX360_DPAD_DOWN = 13;
Phaser.Gamepad.XBOX360_STICK_LEFT_X = 0;
Phaser.Gamepad.XBOX360_STICK_LEFT_Y = 1;
Phaser.Gamepad.XBOX360_STICK_RIGHT_X = 2;
Phaser.Gamepad.XBOX360_STICK_RIGHT_Y = 3;
/**
* @author @karlmacklin <tacklemcclean@gmail.com>
* @copyright 2014 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @class Phaser.SinglePad
* @classdesc A single Phaser Gamepad
* @constructor
* @param {Phaser.Game} game - Current game instance.
* @param {Object} padParent - The parent Phaser.Gamepad object (all gamepads reside under this)
*/
Phaser.SinglePad = function (game, padParent) {
/**
* @property {Phaser.Game} game - Local reference to game.
*/
this.game = game;
/**
* @property {Phaser.Gamepad} padParent - Main Phaser Gamepad object
*/
this._padParent = padParent;
/**
* @property {number} index - The gamepad index as per browsers data
* @default
*/
this._index = null;
/**
* @property {Object} _rawPad - The 'raw' gamepad data.
* @private
*/
this._rawPad = null;
/**
* @property {boolean} _connected - Is this pad connected or not.
* @private
*/
this._connected = false;
/**
* @property {number} _prevTimestamp - Used to check for differences between earlier polls and current state of gamepads.
* @private
*/
this._prevTimestamp = null;
/**
* @property {Array} _rawButtons - The 'raw' button state.
* @private
*/
this._rawButtons = [];
/**
* @property {Array} _buttons - Current Phaser state of the buttons.
* @private
*/
this._buttons = [];
/**
* @property {Array} _axes - Current axes state.
* @private
*/
this._axes = [];
/**
* @property {Array} _hotkeys - Hotkey buttons.
* @private
*/
this._hotkeys = [];
/**
* @property {Object} callbackContext - The context under which the callbacks are run.
*/
this.callbackContext = this;
/**
* @property {function} onConnectCallback - This callback is invoked every time this gamepad is connected
*/
this.onConnectCallback = null;
/**
* @property {function} onDisconnectCallback - This callback is invoked every time this gamepad is disconnected
*/
this.onDisconnectCallback = null;
/**
* @property {function} onDownCallback - This callback is invoked every time a button is pressed down.
*/
this.onDownCallback = null;
/**
* @property {function} onUpCallback - This callback is invoked every time a gamepad button is released.
*/
this.onUpCallback = null;
/**
* @property {function} onAxisCallback - This callback is invoked every time an axis is changed.
*/
this.onAxisCallback = null;
/**
* @property {function} onFloatCallback - This callback is invoked every time a button is changed to a value where value > 0 and value < 1.
*/
this.onFloatCallback = null;
/**
* @property {number} deadZone - Dead zone for axis feedback - within this value you won't trigger updates.
*/
this.deadZone = 0.26;
};
Phaser.SinglePad.prototype = {
/**
* Add callbacks to the this Gamepad to handle connect/disconnect/button down/button up/axis change/float value buttons
* @method Phaser.SinglePad#addCallbacks
* @param {Object} context - The context under which the callbacks are run.
* @param {Object} callbacks - Object that takes six different callbak methods:
* onConnectCallback, onDisconnectCallback, onDownCallback, onUpCallback, onAxisCallback, onFloatCallback
*/
addCallbacks: function (context, callbacks) {
if (typeof callbacks !== 'undefined')
{
this.onConnectCallback = (typeof callbacks.onConnect === 'function') ? callbacks.onConnect : this.onConnectCallback;
this.onDisconnectCallback = (typeof callbacks.onDisconnect === 'function') ? callbacks.onDisconnect : this.onDisconnectCallback;
this.onDownCallback = (typeof callbacks.onDown === 'function') ? callbacks.onDown : this.onDownCallback;
this.onUpCallback = (typeof callbacks.onUp === 'function') ? callbacks.onUp : this.onUpCallback;
this.onAxisCallback = (typeof callbacks.onAxis === 'function') ? callbacks.onAxis : this.onAxisCallback;
this.onFloatCallback = (typeof callbacks.onFloat === 'function') ? callbacks.onFloat : this.onFloatCallback;
}
},
/**
* If you need more fine-grained control over a Key you can create a new Phaser.Key object via this method.
* The Key object can then be polled, have events attached to it, etc.
*
* @method Phaser.SinglePad#addButton
* @param {number} buttonCode - The buttonCode of the button, i.e. Phaser.Gamepad.BUTTON_0 or Phaser.Gamepad.BUTTON_1
* @return {Phaser.GamepadButton} The GamepadButton object which you can store locally and reference directly.
*/
addButton: function (buttonCode) {
this._hotkeys[buttonCode] = new Phaser.GamepadButton(this.game, buttonCode);
return this._hotkeys[buttonCode];
},
/**
* Main update function, should be called by Phaser.Gamepad
* @method Phaser.SinglePad#pollStatus
*/
pollStatus: function () {
if (this._rawPad.timestamp && (this._rawPad.timestamp == this._prevTimestamp))
{
return;
}
for (var i = 0; i < this._rawPad.buttons.length; i += 1)
{
var buttonValue = this._rawPad.buttons[i];
if (this._rawButtons[i] !== buttonValue)
{
if (buttonValue === 1)
{
this.processButtonDown(i, buttonValue);
}
else if (buttonValue === 0)
{
this.processButtonUp(i, buttonValue);
}
else
{
this.processButtonFloat(i, buttonValue);
}
this._rawButtons[i] = buttonValue;
}
}
var axes = this._rawPad.axes;
for (var j = 0; j < axes.length; j += 1)
{
var axis = axes[j];
if (axis > 0 && axis > this.deadZone || axis < 0 && axis < -this.deadZone)
{
this.processAxisChange({axis: j, value: axis});
}
else
{
this.processAxisChange({axis: j, value: 0});
}
}
this._prevTimestamp = this._rawPad.timestamp;
},
/**
* Gamepad connect function, should be called by Phaser.Gamepad
* @method Phaser.SinglePad#connect
* @param {Object} rawPad - The raw gamepad object
*/
connect: function (rawPad) {
var triggerCallback = !this._connected;
this._index = rawPad.index;
this._connected = true;
this._rawPad = rawPad;
this._rawButtons = rawPad.buttons;
this._axes = rawPad.axes;
if (triggerCallback && this._padParent.onConnectCallback)
{
this._padParent.onConnectCallback.call(this._padParent.callbackContext, this._index);
}
if (triggerCallback && this.onConnectCallback)
{
this.onConnectCallback.call(this.callbackContext);
}
},
/**
* Gamepad disconnect function, should be called by Phaser.Gamepad
* @method Phaser.SinglePad#disconnect
*/
disconnect: function () {
var triggerCallback = this._connected;
this._connected = false;
this._rawPad = undefined;
this._rawButtons = [];
this._buttons = [];
var disconnectingIndex = this._index;
this._index = null;
if (triggerCallback && this._padParent.onDisconnectCallback)
{
this._padParent.onDisconnectCallback.call(this._padParent.callbackContext, disconnectingIndex);
}
if (triggerCallback && this.onDisconnectCallback)
{
this.onDisconnectCallback.call(this.callbackContext);
}
},
/**
* Handles changes in axis
* @method Phaser.SinglePad#processAxisChange
* @param {Object} axisState - State of the relevant axis
*/
processAxisChange: function (axisState) {
if (this.game.input.disabled || this.game.input.gamepad.disabled)
{
return;
}
if (this._axes[axisState.axis] === axisState.value)
{
return;
}
this._axes[axisState.axis] = axisState.value;
if (this._padParent.onAxisCallback)
{
this._padParent.onAxisCallback.call(this._padParent.callbackContext, axisState, this._index);
}
if (this.onAxisCallback)
{
this.onAxisCallback.call(this.callbackContext, axisState);
}
},
/**
* Handles button down press
* @method Phaser.SinglePad#processButtonDown
* @param {number} buttonCode - Which buttonCode of this button
* @param {Object} value - Button value
*/
processButtonDown: function (buttonCode, value) {
if (this.game.input.disabled || this.game.input.gamepad.disabled)
{
return;
}
if (this._padParent.onDownCallback)
{
this._padParent.onDownCallback.call(this._padParent.callbackContext, buttonCode, value, this._index);
}
if (this.onDownCallback)
{
this.onDownCallback.call(this.callbackContext, buttonCode, value);
}
if (this._buttons[buttonCode] && this._buttons[buttonCode].isDown)
{
// Key already down and still down, so update
this._buttons[buttonCode].duration = this.game.time.now - this._buttons[buttonCode].timeDown;
}
else
{
if (!this._buttons[buttonCode])
{
// Not used this button before, so register it
this._buttons[buttonCode] = {
isDown: true,
timeDown: this.game.time.now,
timeUp: 0,
duration: 0,
value: value
};
}
else
{
// Button used before but freshly down
this._buttons[buttonCode].isDown = true;
this._buttons[buttonCode].timeDown = this.game.time.now;
this._buttons[buttonCode].duration = 0;
this._buttons[buttonCode].value = value;
}
}
if (this._hotkeys[buttonCode])
{
this._hotkeys[buttonCode].processButtonDown(value);
}
},
/**
* Handles button release
* @method Phaser.SinglePad#processButtonUp
* @param {number} buttonCode - Which buttonCode of this button
* @param {Object} value - Button value
*/
processButtonUp: function (buttonCode, value) {
if (this.game.input.disabled || this.game.input.gamepad.disabled)
{
return;
}
if (this._padParent.onUpCallback)
{
this._padParent.onUpCallback.call(this._padParent.callbackContext, buttonCode, value, this._index);
}
if (this.onUpCallback)
{
this.onUpCallback.call(this.callbackContext, buttonCode, value);
}
if (this._hotkeys[buttonCode])
{
this._hotkeys[buttonCode].processButtonUp(value);
}
if (this._buttons[buttonCode])
{
this._buttons[buttonCode].isDown = false;
this._buttons[buttonCode].timeUp = this.game.time.now;
this._buttons[buttonCode].value = value;
}
else
{
// Not used this button before, so register it
this._buttons[buttonCode] = {
isDown: false,
timeDown: this.game.time.now,
timeUp: this.game.time.now,
duration: 0,
value: value
};
}
},
/**
* Handles buttons with floating values (like analog buttons that acts almost like an axis but still registers like a button)
* @method Phaser.SinglePad#processButtonFloat
* @param {number} buttonCode - Which buttonCode of this button
* @param {Object} value - Button value (will range somewhere between 0 and 1, but not specifically 0 or 1.
*/
processButtonFloat: function (buttonCode, value) {
if (this.game.input.disabled || this.game.input.gamepad.disabled)
{
return;
}
if (this._padParent.onFloatCallback)
{
this._padParent.onFloatCallback.call(this._padParent.callbackContext, buttonCode, value, this._index);
}
if (this.onFloatCallback)
{
this.onFloatCallback.call(this.callbackContext, buttonCode, value);
}
if (!this._buttons[buttonCode])
{
// Not used this button before, so register it
this._buttons[buttonCode] = { value: value };
}
else
{
// Button used before but freshly down
this._buttons[buttonCode].value = value;
}
if (this._hotkeys[buttonCode])
{
this._hotkeys[buttonCode].processButtonFloat(value);
}
},
/**
* Returns value of requested axis
* @method Phaser.SinglePad#axis
* @param {number} axisCode - The index of the axis to check
* @return {number} Axis value if available otherwise false
*/
axis: function (axisCode) {
if (this._axes[axisCode])
{
return this._axes[axisCode];
}
return false;
},
/**
* Returns true if the button is currently pressed down.
* @method Phaser.SinglePad#isDown
* @param {number} buttonCode - The buttonCode of the key to check.
* @return {boolean} True if the key is currently down.
*/
isDown: function (buttonCode) {
if (this._buttons[buttonCode])
{
return this._buttons[buttonCode].isDown;
}
return false;
},
/**
* Returns the "just released" state of a button from this gamepad. Just released is considered as being true if the button was released within the duration given (default 250ms).
* @method Phaser.SinglePad#justReleased
* @param {number} buttonCode - The buttonCode of the button to check for.
* @param {number} [duration=250] - The duration below which the button is considered as being just released.
* @return {boolean} True if the button is just released otherwise false.
*/
justReleased: function (buttonCode, duration) {
if (typeof duration === "undefined") { duration = 250; }
return (this._buttons[buttonCode] && this._buttons[buttonCode].isDown === false && (this.game.time.now - this._buttons[buttonCode].timeUp < duration));
},
/**
* Returns the "just pressed" state of a button from this gamepad. Just pressed is considered true if the button was pressed down within the duration given (default 250ms).
* @method Phaser.SinglePad#justPressed
* @param {number} buttonCode - The buttonCode of the button to check for.
* @param {number} [duration=250] - The duration below which the button is considered as being just pressed.
* @return {boolean} True if the button is just pressed otherwise false.
*/
justPressed: function (buttonCode, duration) {
if (typeof duration === "undefined") { duration = 250; }
return (this._buttons[buttonCode] && this._buttons[buttonCode].isDown && this._buttons[buttonCode].duration < duration);
},
/**
* Returns the value of a gamepad button. Intended mainly for cases when you have floating button values, for example
* analog trigger buttons on the XBOX 360 controller
* @method Phaser.SinglePad#buttonValue
* @param {number} buttonCode - The buttonCode of the button to check.
* @return {boolean} Button value if available otherwise false.
*/
buttonValue: function (buttonCode) {
if (this._buttons[buttonCode])
{
return this._buttons[buttonCode].value;
}
return false;
},
/**
* Reset all buttons/axes of this gamepad
* @method Phaser.SinglePad#reset
*/
reset: function () {
for (var i = 0; i < this._buttons.length; i++)
{
this._buttons[i] = 0;
}
for (var j = 0; j < this._axes.length; j++)
{
this._axes[j] = 0;
}
}
};
Phaser.SinglePad.prototype.constructor = Phaser.SinglePad;
/**
* Whether or not this particular gamepad is connected or not.
* @name Phaser.SinglePad#connected
* @property {boolean} connected - Whether or not this particular gamepad is connected or not.
* @readonly
*/
Object.defineProperty(Phaser.SinglePad.prototype, "connected", {
get: function () {
return this._connected;
}
});
/**
* Gamepad index as per browser data
* @name Phaser.SinglePad#index
* @property {number} index - The gamepad index, used to identify specific gamepads in the browser
* @readonly
*/
Object.defineProperty(Phaser.SinglePad.prototype, "index", {
get: function () {
return this._index;
}
});
/**
* @author @karlmacklin <tacklemcclean@gmail.com>
* @copyright 2014 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @class Phaser.GamepadButton
* @classdesc If you need more fine-grained control over the handling of specific buttons you can create and use Phaser.GamepadButton objects.
* @constructor
* @param {Phaser.Game} game - Current game instance.
* @param {number} buttoncode - The button code this GamepadButton is responsible for.
*/
Phaser.GamepadButton = function (game, buttoncode) {
/**
* @property {Phaser.Game} game - A reference to the currently running game.
*/
this.game = game;
/**
* @property {boolean} isDown - The "down" state of the button.
* @default
*/
this.isDown = false;
/**
* @property {boolean} isUp - The "up" state of the button.
* @default
*/
this.isUp = true;
/**
* @property {number} timeDown - The timestamp when the button was last pressed down.
* @default
*/
this.timeDown = 0;
/**
* If the button is down this value holds the duration of that button press and is constantly updated.
* If the button is up it holds the duration of the previous down session.
* @property {number} duration - The number of milliseconds this button has been held down for.
* @default
*/
this.duration = 0;
/**
* @property {number} timeUp - The timestamp when the button was last released.
* @default
*/
this.timeUp = 0;
/**
* @property {number} repeats - If a button is held down this holds down the number of times the button has 'repeated'.
* @default
*/
this.repeats = 0;
/**
* @property {number} value - Button value. Mainly useful for checking analog buttons (like shoulder triggers)
* @default
*/
this.value = 0;
/**
* @property {number} buttonCode - The buttoncode of this button.
*/
this.buttonCode = buttoncode;
/**
* @property {Phaser.Signal} onDown - This Signal is dispatched every time this GamepadButton is pressed down. It is only dispatched once (until the button is released again).
*/
this.onDown = new Phaser.Signal();
/**
* @property {Phaser.Signal} onUp - This Signal is dispatched every time this GamepadButton is pressed down. It is only dispatched once (until the button is released again).
*/
this.onUp = new Phaser.Signal();
/**
* @property {Phaser.Signal} onFloat - This Signal is dispatched every time this GamepadButton changes floating value (between (but not exactly) 0 and 1)
*/
this.onFloat = new Phaser.Signal();
};
Phaser.GamepadButton.prototype = {
/**
* Called automatically by Phaser.SinglePad.
* @method Phaser.GamepadButton#processButtonDown
* @param {Object} value - Button value
* @protected
*/
processButtonDown: function (value) {
if (this.isDown)
{
this.duration = this.game.time.now - this.timeDown;
this.repeats++;
}
else
{
this.isDown = true;
this.isUp = false;
this.timeDown = this.game.time.now;
this.duration = 0;
this.repeats = 0;
this.value = value;
this.onDown.dispatch(this, value);
}
},
/**
* Called automatically by Phaser.SinglePad.
* @method Phaser.GamepadButton#processButtonUp
* @param {Object} value - Button value
* @protected
*/
processButtonUp: function (value) {
this.isDown = false;
this.isUp = true;
this.timeUp = this.game.time.now;
this.value = value;
this.onUp.dispatch(this, value);
},
/**
* Called automatically by Phaser.Gamepad.
* @method Phaser.GamepadButton#processButtonFloat
* @param {Object} value - Button value
* @protected
*/
processButtonFloat: function (value) {
this.value = value;
this.onFloat.dispatch(this, value);
},
/**
* Returns the "just pressed" state of this button. Just pressed is considered true if the button was pressed down within the duration given (default 250ms).
* @method Phaser.GamepadButton#justPressed
* @param {number} [duration=250] - The duration below which the button is considered as being just pressed.
* @return {boolean} True if the button is just pressed otherwise false.
*/
justPressed: function (duration) {
if (typeof duration === "undefined") { duration = 250; }
return (this.isDown && this.duration < duration);
},
/**
* Returns the "just released" state of this button. Just released is considered as being true if the button was released within the duration given (default 250ms).
* @method Phaser.GamepadButton#justPressed
* @param {number} [duration=250] - The duration below which the button is considered as being just released.
* @return {boolean} True if the button is just pressed otherwise false.
*/
justReleased: function (duration) {
if (typeof duration === "undefined") { duration = 250; }
return (this.isDown === false && (this.game.time.now - this.timeUp < duration));
}
};
Phaser.GamepadButton.prototype.constructor = Phaser.GamepadButton;
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2014 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* The Input Handler is bound to a specific Sprite and is responsible for managing all Input events on that Sprite.
* @class Phaser.InputHandler
* @constructor
* @param {Phaser.Sprite} sprite - The Sprite object to which this Input Handler belongs.
*/
Phaser.InputHandler = function (sprite) {
/**
* @property {Phaser.Sprite} sprite - The Sprite object to which this Input Handler belongs.
*/
this.sprite = sprite;
/**
* @property {Phaser.Game} game - A reference to the currently running game.
*/
this.game = sprite.game;
/**
* @property {boolean} enabled - If enabled the Input Handler will process input requests and monitor pointer activity.
* @default
*/
this.enabled = false;
/**
* @property {number} priorityID - The PriorityID controls which Sprite receives an Input event first if they should overlap.
* @default
*/
this.priorityID = 0;
/**
* @property {boolean} useHandCursor - On a desktop browser you can set the 'hand' cursor to appear when moving over the Sprite.
* @default
*/
this.useHandCursor = false;
/**
* @property {boolean} isDragged - true if the Sprite is being currently dragged.
* @default
*/
this.isDragged = false;
/**
* @property {boolean} allowHorizontalDrag - Controls if the Sprite is allowed to be dragged horizontally.
* @default
*/
this.allowHorizontalDrag = true;
/**
* @property {boolean} allowVerticalDrag - Controls if the Sprite is allowed to be dragged vertically.
* @default
*/
this.allowVerticalDrag = true;
/**
* @property {boolean} bringToTop - If true when this Sprite is clicked or dragged it will automatically be bought to the top of the Group it is within.
* @default
*/
this.bringToTop = false;
/**
* @property {Phaser.Point} snapOffset - A Point object that contains by how far the Sprite snap is offset.
* @default
*/
this.snapOffset = null;
/**
* @property {boolean} snapOnDrag - When the Sprite is dragged this controls if the center of the Sprite will snap to the pointer on drag or not.
* @default
*/
this.snapOnDrag = false;
/**
* @property {boolean} snapOnRelease - When the Sprite is dragged this controls if the Sprite will be snapped on release.
* @default
*/
this.snapOnRelease = false;
/**
* @property {number} snapX - When a Sprite has snapping enabled this holds the width of the snap grid.
* @default
*/
this.snapX = 0;
/**
* @property {number} snapY - When a Sprite has snapping enabled this holds the height of the snap grid.
* @default
*/
this.snapY = 0;
/**
* @property {number} snapOffsetX - This defines the top-left X coordinate of the snap grid.
* @default
*/
this.snapOffsetX = 0;
/**
* @property {number} snapOffsetY - This defines the top-left Y coordinate of the snap grid..
* @default
*/
this.snapOffsetY = 0;
/**
* Set to true to use pixel perfect hit detection when checking if the pointer is over this Sprite.
* The x/y coordinates of the pointer are tested against the image in combination with the InputHandler.pixelPerfectAlpha value.
* Warning: This is expensive, especially on mobile (where it's not even needed!) so only enable if required. Also see the less-expensive InputHandler.pixelPerfectClick.
* @property {number} pixelPerfectOver - Use a pixel perfect check when testing for pointer over.
* @default
*/
this.pixelPerfectOver = false;
/**
* Set to true to use pixel perfect hit detection when checking if the pointer is over this Sprite when it's clicked or touched.
* The x/y coordinates of the pointer are tested against the image in combination with the InputHandler.pixelPerfectAlpha value.
* Warning: This is expensive so only enable if you really need it.
* @property {number} pixelPerfectClick - Use a pixel perfect check when testing for clicks or touches on the Sprite.
* @default
*/
this.pixelPerfectClick = false;
/**
* @property {number} pixelPerfectAlpha - The alpha tolerance threshold. If the alpha value of the pixel matches or is above this value, it's considered a hit.
* @default
*/
this.pixelPerfectAlpha = 255;
/**
* @property {boolean} draggable - Is this sprite allowed to be dragged by the mouse? true = yes, false = no
* @default
*/
this.draggable = false;
/**
* @property {Phaser.Rectangle} boundsRect - A region of the game world within which the sprite is restricted during drag.
* @default
*/
this.boundsRect = null;
/**
* @property {Phaser.Sprite} boundsSprite - A Sprite the bounds of which this sprite is restricted during drag.
* @default
*/
this.boundsSprite = null;
/**
* If this object is set to consume the pointer event then it will stop all propogation from this object on.
* For example if you had a stack of 6 sprites with the same priority IDs and one consumed the event, none of the others would receive it.
* @property {boolean} consumePointerEvent
* @default
*/
this.consumePointerEvent = false;
/**
* @property {Phaser.Point} _tempPoint - Internal cache var.
* @private
*/
this._tempPoint = new Phaser.Point();
/**
* @property {array} _pointerData - Internal cache var.
* @private
*/
this._pointerData = [];
this._pointerData.push({
id: 0,
x: 0,
y: 0,
isDown: false,
isUp: false,
isOver: false,
isOut: false,
timeOver: 0,
timeOut: 0,
timeDown: 0,
timeUp: 0,
downDuration: 0,
isDragged: false
});
};
Phaser.InputHandler.prototype = {
/**
* Starts the Input Handler running. This is called automatically when you enable input on a Sprite, or can be called directly if you need to set a specific priority.
* @method Phaser.InputHandler#start
* @param {number} priority - Higher priority sprites take click priority over low-priority sprites when they are stacked on-top of each other.
* @param {boolean} useHandCursor - If true the Sprite will show the hand cursor on mouse-over (doesn't apply to mobile browsers)
* @return {Phaser.Sprite} The Sprite object to which the Input Handler is bound.
*/
start: function (priority, useHandCursor) {
priority = priority || 0;
if (typeof useHandCursor == 'undefined') { useHandCursor = false; }
// Turning on
if (this.enabled === false)
{
// Register, etc
this.game.input.interactiveItems.add(this);
this.useHandCursor = useHandCursor;
this.priorityID = priority;
for (var i = 0; i < 10; i++)
{
this._pointerData[i] = {
id: i,
x: 0,
y: 0,
isDown: false,
isUp: false,
isOver: false,
isOut: false,
timeOver: 0,
timeOut: 0,
timeDown: 0,
timeUp: 0,
downDuration: 0,
isDragged: false
};
}
this.snapOffset = new Phaser.Point();
this.enabled = true;
// Create the signals the Input component will emit
if (this.sprite.events && this.sprite.events.onInputOver === null)
{
this.sprite.events.onInputOver = new Phaser.Signal();
this.sprite.events.onInputOut = new Phaser.Signal();
this.sprite.events.onInputDown = new Phaser.Signal();
this.sprite.events.onInputUp = new Phaser.Signal();
this.sprite.events.onDragStart = new Phaser.Signal();
this.sprite.events.onDragStop = new Phaser.Signal();
}
}
return this.sprite;
},
/**
* Resets the Input Handler and disables it.
* @method Phaser.InputHandler#reset
*/
reset: function () {
this.enabled = false;
for (var i = 0; i < 10; i++)
{
this._pointerData[i] = {
id: i,
x: 0,
y: 0,
isDown: false,
isUp: false,
isOver: false,
isOut: false,
timeOver: 0,
timeOut: 0,
timeDown: 0,
timeUp: 0,
downDuration: 0,
isDragged: false
};
}
},
/**
* Stops the Input Handler from running.
* @method Phaser.InputHandler#stop
*/
stop: function () {
// Turning off
if (this.enabled === false)
{
return;
}
else
{
// De-register, etc
this.enabled = false;
this.game.input.interactiveItems.remove(this);
}
},
/**
* Clean up memory.
* @method Phaser.InputHandler#destroy
*/
destroy: function () {
if (this.enabled)
{
this.enabled = false;
this.game.input.interactiveItems.remove(this);
this._pointerData.length = 0;
this.boundsRect = null;
this.boundsSprite = null;
this.sprite = null;
}
},
/**
* The x coordinate of the Input pointer, relative to the top-left of the parent Sprite.
* This value is only set when the pointer is over this Sprite.
* @method Phaser.InputHandler#pointerX
* @param {Phaser.Pointer} pointer
* @return {number} The x coordinate of the Input pointer.
*/
pointerX: function (pointer) {
pointer = pointer || 0;
return this._pointerData[pointer].x;
},
/**
* The y coordinate of the Input pointer, relative to the top-left of the parent Sprite
* This value is only set when the pointer is over this Sprite.
* @method Phaser.InputHandler#pointerY
* @param {Phaser.Pointer} pointer
* @return {number} The y coordinate of the Input pointer.
*/
pointerY: function (pointer) {
pointer = pointer || 0;
return this._pointerData[pointer].y;
},
/**
* If the Pointer is touching the touchscreen, or the mouse button is held down, isDown is set to true.
* @method Phaser.InputHandler#pointerDown
* @param {Phaser.Pointer} pointer
* @return {boolean}
*/
pointerDown: function (pointer) {
pointer = pointer || 0;
return this._pointerData[pointer].isDown;
},
/**
* If the Pointer is not touching the touchscreen, or the mouse button is up, isUp is set to true
* @method Phaser.InputHandler#pointerUp
* @param {Phaser.Pointer} pointer
* @return {boolean}
*/
pointerUp: function (pointer) {
pointer = pointer || 0;
return this._pointerData[pointer].isUp;
},
/**
* A timestamp representing when the Pointer first touched the touchscreen.
* @method Phaser.InputHandler#pointerTimeDown
* @param {Phaser.Pointer} pointer
* @return {number}
*/
pointerTimeDown: function (pointer) {
pointer = pointer || 0;
return this._pointerData[pointer].timeDown;
},
/**
* A timestamp representing when the Pointer left the touchscreen.
* @method Phaser.InputHandler#pointerTimeUp
* @param {Phaser.Pointer} pointer
* @return {number}
*/
pointerTimeUp: function (pointer) {
pointer = pointer || 0;
return this._pointerData[pointer].timeUp;
},
/**
* Is the Pointer over this Sprite?
* @method Phaser.InputHandler#pointerOver
* @param {number} [index] - The ID number of a Pointer to check. If you don't provide a number it will check all Pointers.
* @return {boolean} True if the given pointer (if a index was given, or any pointer if not) is over this object.
*/
pointerOver: function (index) {
if (this.enabled)
{
if (typeof index === 'undefined')
{
for (var i = 0; i < 10; i++)
{
if (this._pointerData[i].isOver)
{
return true;
}
}
}
else
{
return this._pointerData[index].isOver;
}
}
return false;
},
/**
* Is the Pointer outside of this Sprite?
* @method Phaser.InputHandler#pointerOut
* @param {number} [index] - The ID number of a Pointer to check. If you don't provide a number it will check all Pointers.
* @return {boolean} True if the given pointer (if a index was given, or any pointer if not) is out of this object.
*/
pointerOut: function (index) {
if (this.enabled)
{
if (typeof index === 'undefined')
{
for (var i = 0; i < 10; i++)
{
if (this._pointerData[i].isOut)
{
return true;
}
}
}
else
{
return this._pointerData[index].isOut;
}
}
return false;
},
/**
* A timestamp representing when the Pointer first touched the touchscreen.
* @method Phaser.InputHandler#pointerTimeOver
* @param {Phaser.Pointer} pointer
* @return {number}
*/
pointerTimeOver: function (pointer) {
pointer = pointer || 0;
return this._pointerData[pointer].timeOver;
},
/**
* A timestamp representing when the Pointer left the touchscreen.
* @method Phaser.InputHandler#pointerTimeOut
* @param {Phaser.Pointer} pointer
* @return {number}
*/
pointerTimeOut: function (pointer) {
pointer = pointer || 0;
return this._pointerData[pointer].timeOut;
},
/**
* Is this sprite being dragged by the mouse or not?
* @method Phaser.InputHandler#pointerDragged
* @param {Phaser.Pointer} pointer
* @return {boolean} True if the pointer is dragging an object, otherwise false.
*/
pointerDragged: function (pointer) {
pointer = pointer || 0;
return this._pointerData[pointer].isDragged;
},
/**
* Checks if the given pointer is over this Sprite and can click it.
* @method Phaser.InputHandler#checkPointerDown
* @param {Phaser.Pointer} pointer
* @return {boolean} True if the pointer is down, otherwise false.
*/
checkPointerDown: function (pointer) {
if (this.enabled === false || this.sprite.visible === false || this.sprite.parent.visible === false)
{
return false;
}
// Need to pass it a temp point, in case we need it again for the pixel check
if (this.game.input.hitTest(this.sprite, pointer, this._tempPoint))
{
if (this.pixelPerfectClick)
{
return this.checkPixel(this._tempPoint.x, this._tempPoint.y);
}
else
{
return true;
}
}
return false;
},
/**
* Checks if the given pointer is over this Sprite.
* @method Phaser.InputHandler#checkPointerOver
* @param {Phaser.Pointer} pointer
* @return {boolean}
*/
checkPointerOver: function (pointer) {
if (this.enabled === false || this.sprite.visible === false || this.sprite.parent.visible === false)
{
return false;
}
// Need to pass it a temp point, in case we need it again for the pixel check
if (this.game.input.hitTest(this.sprite, pointer, this._tempPoint))
{
if (this.pixelPerfectOver)
{
return this.checkPixel(this._tempPoint.x, this._tempPoint.y);
}
else
{
return true;
}
}
return false;
},
/**
* Runs a pixel perfect check against the given x/y coordinates of the Sprite this InputHandler is bound to.
* It compares the alpha value of the pixel and if >= InputHandler.pixelPerfectAlpha it returns true.
* @method Phaser.InputHandler#checkPixel
* @param {number} x - The x coordinate to check.
* @param {number} y - The y coordinate to check.
* @param {Phaser.Pointer} [pointer] - The pointer to get the x/y coordinate from if not passed as the first two parameters.
* @return {boolean} true if there is the alpha of the pixel is >= InputHandler.pixelPerfectAlpha
*/
checkPixel: function (x, y, pointer) {
// Grab a pixel from our image into the hitCanvas and then test it
if (this.sprite.texture.baseTexture.source)
{
this.game.input.hitContext.clearRect(0, 0, 1, 1);
if (x === null && y === null)
{
// Use the pointer parameter
this.game.input.getLocalPosition(this.sprite, pointer, this._tempPoint);
var x = this._tempPoint.x;
var y = this._tempPoint.y;
}
if (this.sprite.anchor.x !== 0)
{
x -= -this.sprite.texture.frame.width * this.sprite.anchor.x;
}
if (this.sprite.anchor.y !== 0)
{
y -= -this.sprite.texture.frame.height * this.sprite.anchor.y;
}
x += this.sprite.texture.frame.x;
y += this.sprite.texture.frame.y;
this.game.input.hitContext.drawImage(this.sprite.texture.baseTexture.source, x, y, 1, 1, 0, 0, 1, 1);
var rgb = this.game.input.hitContext.getImageData(0, 0, 1, 1);
if (rgb.data[3] >= this.pixelPerfectAlpha)
{
return true;
}
}
return false;
},
/**
* Update.
* @method Phaser.InputHandler#update
* @protected
* @param {Phaser.Pointer} pointer
*/
update: function (pointer) {
if (this.sprite === null)
{
// Abort. We've been destroyed.
return;
}
if (!this.enabled || !this.sprite.visible || !this.sprite.parent.visible)
{
this._pointerOutHandler(pointer);
return false;
}
if (this.draggable && this._draggedPointerID == pointer.id)
{
return this.updateDrag(pointer);
}
else if (this._pointerData[pointer.id].isOver === true)
{
if (this.checkPointerOver(pointer))
{
this._pointerData[pointer.id].x = pointer.x - this.sprite.x;
this._pointerData[pointer.id].y = pointer.y - this.sprite.y;
return true;
}
else
{
this._pointerOutHandler(pointer);
return false;
}
}
},
/**
* Internal method handling the pointer over event.
* @method Phaser.InputHandler#_pointerOverHandler
* @private
* @param {Phaser.Pointer} pointer
*/
_pointerOverHandler: function (pointer) {
if (this.sprite === null)
{
// Abort. We've been destroyed.
return;
}
if (this._pointerData[pointer.id].isOver === false)
{
this._pointerData[pointer.id].isOver = true;
this._pointerData[pointer.id].isOut = false;
this._pointerData[pointer.id].timeOver = this.game.time.now;
this._pointerData[pointer.id].x = pointer.x - this.sprite.x;
this._pointerData[pointer.id].y = pointer.y - this.sprite.y;
if (this.useHandCursor && this._pointerData[pointer.id].isDragged === false)
{
this.game.canvas.style.cursor = "pointer";
}
this.sprite.events.onInputOver.dispatch(this.sprite, pointer);
}
},
/**
* Internal method handling the pointer out event.
* @method Phaser.InputHandler#_pointerOutHandler
* @private
* @param {Phaser.Pointer} pointer
*/
_pointerOutHandler: function (pointer) {
if (this.sprite === null)
{
// Abort. We've been destroyed.
return;
}
this._pointerData[pointer.id].isOver = false;
this._pointerData[pointer.id].isOut = true;
this._pointerData[pointer.id].timeOut = this.game.time.now;
if (this.useHandCursor && this._pointerData[pointer.id].isDragged === false)
{
this.game.canvas.style.cursor = "default";
}
if (this.sprite && this.sprite.events)
{
this.sprite.events.onInputOut.dispatch(this.sprite, pointer);
}
},
/**
* Internal method handling the touched event.
* @method Phaser.InputHandler#_touchedHandler
* @private
* @param {Phaser.Pointer} pointer
*/
_touchedHandler: function (pointer) {
if (this.sprite === null)
{
// Abort. We've been destroyed.
return;
}
if (this._pointerData[pointer.id].isDown === false && this._pointerData[pointer.id].isOver === true)
{
if (this.pixelPerfectClick && !this.checkPixel(null, null, pointer))
{
return;
}
this._pointerData[pointer.id].isDown = true;
this._pointerData[pointer.id].isUp = false;
this._pointerData[pointer.id].timeDown = this.game.time.now;
this.sprite.events.onInputDown.dispatch(this.sprite, pointer);
// Start drag
if (this.draggable && this.isDragged === false)
{
this.startDrag(pointer);
}
if (this.bringToTop)
{
this.sprite.bringToTop();
}
}
// Consume the event?
return this.consumePointerEvent;
},
/**
* Internal method handling the pointer released event.
* @method Phaser.InputHandler#_releasedHandler
* @private
* @param {Phaser.Pointer} pointer
*/
_releasedHandler: function (pointer) {
if (this.sprite === null)
{
// Abort. We've been destroyed.
return;
}
// If was previously touched by this Pointer, check if still is AND still over this item
if (this._pointerData[pointer.id].isDown && pointer.isUp)
{
this._pointerData[pointer.id].isDown = false;
this._pointerData[pointer.id].isUp = true;
this._pointerData[pointer.id].timeUp = this.game.time.now;
this._pointerData[pointer.id].downDuration = this._pointerData[pointer.id].timeUp - this._pointerData[pointer.id].timeDown;
// Only release the InputUp signal if the pointer is still over this sprite
if (this.checkPointerOver(pointer))
{
// Release the inputUp signal and provide optional parameter if pointer is still over the sprite or not
this.sprite.events.onInputUp.dispatch(this.sprite, pointer, true);
}
else
{
// Release the inputUp signal and provide optional parameter if pointer is still over the sprite or not
this.sprite.events.onInputUp.dispatch(this.sprite, pointer, false);
// Pointer outside the sprite? Reset the cursor
if (this.useHandCursor)
{
this.game.canvas.style.cursor = "default";
}
}
// Stop drag
if (this.draggable && this.isDragged && this._draggedPointerID == pointer.id)
{
this.stopDrag(pointer);
}
}
},
/**
* Updates the Pointer drag on this Sprite.
* @method Phaser.InputHandler#updateDrag
* @param {Phaser.Pointer} pointer
* @return {boolean}
*/
updateDrag: function (pointer) {
if (pointer.isUp)
{
this.stopDrag(pointer);
return false;
}
if (this.sprite.fixedToCamera)
{
if (this.allowHorizontalDrag)
{
this.sprite.cameraOffset.x = pointer.x + this._dragPoint.x + this.dragOffset.x;
}
if (this.allowVerticalDrag)
{
this.sprite.cameraOffset.y = pointer.y + this._dragPoint.y + this.dragOffset.y;
}
if (this.boundsRect)
{
this.checkBoundsRect();
}
if (this.boundsSprite)
{
this.checkBoundsSprite();
}
if (this.snapOnDrag)
{
this.sprite.cameraOffset.x = Math.round((this.sprite.cameraOffset.x - (this.snapOffsetX % this.snapX)) / this.snapX) * this.snapX + (this.snapOffsetX % this.snapX);
this.sprite.cameraOffset.y = Math.round((this.sprite.cameraOffset.y - (this.snapOffsetY % this.snapY)) / this.snapY) * this.snapY + (this.snapOffsetY % this.snapY);
}
}
else
{
if (this.allowHorizontalDrag)
{
this.sprite.x = pointer.x + this._dragPoint.x + this.dragOffset.x;
}
if (this.allowVerticalDrag)
{
this.sprite.y = pointer.y + this._dragPoint.y + this.dragOffset.y;
}
if (this.boundsRect)
{
this.checkBoundsRect();
}
if (this.boundsSprite)
{
this.checkBoundsSprite();
}
if (this.snapOnDrag)
{
this.sprite.x = Math.round((this.sprite.x - (this.snapOffsetX % this.snapX)) / this.snapX) * this.snapX + (this.snapOffsetX % this.snapX);
this.sprite.y = Math.round((this.sprite.y - (this.snapOffsetY % this.snapY)) / this.snapY) * this.snapY + (this.snapOffsetY % this.snapY);
}
}
return true;
},
/**
* Returns true if the pointer has entered the Sprite within the specified delay time (defaults to 500ms, half a second)
* @method Phaser.InputHandler#justOver
* @param {Phaser.Pointer} pointer
* @param {number} delay - The time below which the pointer is considered as just over.
* @return {boolean}
*/
justOver: function (pointer, delay) {
pointer = pointer || 0;
delay = delay || 500;
return (this._pointerData[pointer].isOver && this.overDuration(pointer) < delay);
},
/**
* Returns true if the pointer has left the Sprite within the specified delay time (defaults to 500ms, half a second)
* @method Phaser.InputHandler#justOut
* @param {Phaser.Pointer} pointer
* @param {number} delay - The time below which the pointer is considered as just out.
* @return {boolean}
*/
justOut: function (pointer, delay) {
pointer = pointer || 0;
delay = delay || 500;
return (this._pointerData[pointer].isOut && (this.game.time.now - this._pointerData[pointer].timeOut < delay));
},
/**
* Returns true if the pointer has touched or clicked on the Sprite within the specified delay time (defaults to 500ms, half a second)
* @method Phaser.InputHandler#justPressed
* @param {Phaser.Pointer} pointer
* @param {number} delay - The time below which the pointer is considered as just over.
* @return {boolean}
*/
justPressed: function (pointer, delay) {
pointer = pointer || 0;
delay = delay || 500;
return (this._pointerData[pointer].isDown && this.downDuration(pointer) < delay);
},
/**
* Returns true if the pointer was touching this Sprite, but has been released within the specified delay time (defaults to 500ms, half a second)
* @method Phaser.InputHandler#justReleased
* @param {Phaser.Pointer} pointer
* @param {number} delay - The time below which the pointer is considered as just out.
* @return {boolean}
*/
justReleased: function (pointer, delay) {
pointer = pointer || 0;
delay = delay || 500;
return (this._pointerData[pointer].isUp && (this.game.time.now - this._pointerData[pointer].timeUp < delay));
},
/**
* If the pointer is currently over this Sprite this returns how long it has been there for in milliseconds.
* @method Phaser.InputHandler#overDuration
* @param {Phaser.Pointer} pointer
* @return {number} The number of milliseconds the pointer has been over the Sprite, or -1 if not over.
*/
overDuration: function (pointer) {
pointer = pointer || 0;
if (this._pointerData[pointer].isOver)
{
return this.game.time.now - this._pointerData[pointer].timeOver;
}
return -1;
},
/**
* If the pointer is currently over this Sprite this returns how long it has been there for in milliseconds.
* @method Phaser.InputHandler#downDuration
* @param {Phaser.Pointer} pointer
* @return {number} The number of milliseconds the pointer has been pressed down on the Sprite, or -1 if not over.
*/
downDuration: function (pointer) {
pointer = pointer || 0;
if (this._pointerData[pointer].isDown)
{
return this.game.time.now - this._pointerData[pointer].timeDown;
}
return -1;
},
/**
* Make this Sprite draggable by the mouse. You can also optionally set mouseStartDragCallback and mouseStopDragCallback
* @method Phaser.InputHandler#enableDrag
* @param {boolean} [lockCenter=false] - If false the Sprite will drag from where you click it minus the dragOffset. If true it will center itself to the tip of the mouse pointer.
* @param {boolean} [bringToTop=false] - If true the Sprite will be bought to the top of the rendering list in its current Group.
* @param {boolean} [pixelPerfect=false] - If true it will use a pixel perfect test to see if you clicked the Sprite. False uses the bounding box.
* @param {boolean} [alphaThreshold=255] - If using pixel perfect collision this specifies the alpha level from 0 to 255 above which a collision is processed.
* @param {Phaser.Rectangle} [boundsRect=null] - If you want to restrict the drag of this sprite to a specific Rectangle, pass the Phaser.Rectangle here, otherwise it's free to drag anywhere.
* @param {Phaser.Sprite} [boundsSprite=null] - If you want to restrict the drag of this sprite to within the bounding box of another sprite, pass it here.
*/
enableDrag: function (lockCenter, bringToTop, pixelPerfect, alphaThreshold, boundsRect, boundsSprite) {
if (typeof lockCenter == 'undefined') { lockCenter = false; }
if (typeof bringToTop == 'undefined') { bringToTop = false; }
if (typeof pixelPerfect == 'undefined') { pixelPerfect = false; }
if (typeof alphaThreshold == 'undefined') { alphaThreshold = 255; }
if (typeof boundsRect == 'undefined') { boundsRect = null; }
if (typeof boundsSprite == 'undefined') { boundsSprite = null; }
this._dragPoint = new Phaser.Point();
this.draggable = true;
this.bringToTop = bringToTop;
this.dragOffset = new Phaser.Point();
this.dragFromCenter = lockCenter;
this.pixelPerfect = pixelPerfect;
this.pixelPerfectAlpha = alphaThreshold;
if (boundsRect)
{
this.boundsRect = boundsRect;
}
if (boundsSprite)
{
this.boundsSprite = boundsSprite;
}
},
/**
* Stops this sprite from being able to be dragged. If it is currently the target of an active drag it will be stopped immediately. Also disables any set callbacks.
* @method Phaser.InputHandler#disableDrag
*/
disableDrag: function () {
if (this._pointerData)
{
for (var i = 0; i < 10; i++)
{
this._pointerData[i].isDragged = false;
}
}
this.draggable = false;
this.isDragged = false;
this._draggedPointerID = -1;
},
/**
* Called by Pointer when drag starts on this Sprite. Should not usually be called directly.
* @method Phaser.InputHandler#startDrag
* @param {Phaser.Pointer} pointer
*/
startDrag: function (pointer) {
this.isDragged = true;
this._draggedPointerID = pointer.id;
this._pointerData[pointer.id].isDragged = true;
if (this.sprite.fixedToCamera)
{
if (this.dragFromCenter)
{
this.sprite.centerOn(pointer.x, pointer.y);
this._dragPoint.setTo(this.sprite.cameraOffset.x - pointer.x, this.sprite.cameraOffset.y - pointer.y);
}
else
{
this._dragPoint.setTo(this.sprite.cameraOffset.x - pointer.x, this.sprite.cameraOffset.y - pointer.y);
}
}
else
{
if (this.dragFromCenter)
{
this.sprite.centerOn(pointer.x, pointer.y);
this._dragPoint.setTo(this.sprite.x - pointer.x, this.sprite.y - pointer.y);
}
else
{
this._dragPoint.setTo(this.sprite.x - pointer.x, this.sprite.y - pointer.y);
}
}
this.updateDrag(pointer);
if (this.bringToTop)
{
this.sprite.bringToTop();
}
this.sprite.events.onDragStart.dispatch(this.sprite, pointer);
},
/**
* Called by Pointer when drag is stopped on this Sprite. Should not usually be called directly.
* @method Phaser.InputHandler#stopDrag
* @param {Phaser.Pointer} pointer
*/
stopDrag: function (pointer) {
this.isDragged = false;
this._draggedPointerID = -1;
this._pointerData[pointer.id].isDragged = false;
if (this.snapOnRelease)
{
if (this.sprite.fixedToCamera)
{
this.sprite.cameraOffset.x = Math.round((this.sprite.cameraOffset.x - (this.snapOffsetX % this.snapX)) / this.snapX) * this.snapX + (this.snapOffsetX % this.snapX);
this.sprite.cameraOffset.y = Math.round((this.sprite.cameraOffset.y - (this.snapOffsetY % this.snapY)) / this.snapY) * this.snapY + (this.snapOffsetY % this.snapY);
}
else
{
this.sprite.x = Math.round((this.sprite.x - (this.snapOffsetX % this.snapX)) / this.snapX) * this.snapX + (this.snapOffsetX % this.snapX);
this.sprite.y = Math.round((this.sprite.y - (this.snapOffsetY % this.snapY)) / this.snapY) * this.snapY + (this.snapOffsetY % this.snapY);
}
}
this.sprite.events.onDragStop.dispatch(this.sprite, pointer);
if (this.checkPointerOver(pointer) === false)
{
this._pointerOutHandler(pointer);
}
},
/**
* Restricts this sprite to drag movement only on the given axis. Note: If both are set to false the sprite will never move!
* @method Phaser.InputHandler#setDragLock
* @param {boolean} [allowHorizontal=true] - To enable the sprite to be dragged horizontally set to true, otherwise false.
* @param {boolean} [allowVertical=true] - To enable the sprite to be dragged vertically set to true, otherwise false.
*/
setDragLock: function (allowHorizontal, allowVertical) {
if (typeof allowHorizontal == 'undefined') { allowHorizontal = true; }
if (typeof allowVertical == 'undefined') { allowVertical = true; }
this.allowHorizontalDrag = allowHorizontal;
this.allowVerticalDrag = allowVertical;
},
/**
* Make this Sprite snap to the given grid either during drag or when it's released.
* For example 16x16 as the snapX and snapY would make the sprite snap to every 16 pixels.
* @method Phaser.InputHandler#enableSnap
* @param {number} snapX - The width of the grid cell to snap to.
* @param {number} snapY - The height of the grid cell to snap to.
* @param {boolean} [onDrag=true] - If true the sprite will snap to the grid while being dragged.
* @param {boolean} [onRelease=false] - If true the sprite will snap to the grid when released.
* @param {number} [snapOffsetX=0] - Used to offset the top-left starting point of the snap grid.
* @param {number} [snapOffsetX=0] - Used to offset the top-left starting point of the snap grid.
*/
enableSnap: function (snapX, snapY, onDrag, onRelease, snapOffsetX, snapOffsetY) {
if (typeof onDrag == 'undefined') { onDrag = true; }
if (typeof onRelease == 'undefined') { onRelease = false; }
if (typeof snapOffsetX == 'undefined') { snapOffsetX = 0; }
if (typeof snapOffsetY == 'undefined') { snapOffsetY = 0; }
this.snapX = snapX;
this.snapY = snapY;
this.snapOffsetX = snapOffsetX;
this.snapOffsetY = snapOffsetY;
this.snapOnDrag = onDrag;
this.snapOnRelease = onRelease;
},
/**
* Stops the sprite from snapping to a grid during drag or release.
* @method Phaser.InputHandler#disableSnap
*/
disableSnap: function () {
this.snapOnDrag = false;
this.snapOnRelease = false;
},
/**
* Bounds Rect check for the sprite drag
* @method Phaser.InputHandler#checkBoundsRect
*/
checkBoundsRect: function () {
if (this.sprite.fixedToCamera)
{
if (this.sprite.cameraOffset.x < this.boundsRect.left)
{
this.sprite.cameraOffset.x = this.boundsRect.cameraOffset.x;
}
else if ((this.sprite.cameraOffset.x + this.sprite.width) > this.boundsRect.right)
{
this.sprite.cameraOffset.x = this.boundsRect.right - this.sprite.width;
}
if (this.sprite.cameraOffset.y < this.boundsRect.top)
{
this.sprite.cameraOffset.y = this.boundsRect.top;
}
else if ((this.sprite.cameraOffset.y + this.sprite.height) > this.boundsRect.bottom)
{
this.sprite.cameraOffset.y = this.boundsRect.bottom - this.sprite.height;
}
}
else
{
if (this.sprite.x < this.boundsRect.left)
{
this.sprite.x = this.boundsRect.x;
}
else if ((this.sprite.x + this.sprite.width) > this.boundsRect.right)
{
this.sprite.x = this.boundsRect.right - this.sprite.width;
}
if (this.sprite.y < this.boundsRect.top)
{
this.sprite.y = this.boundsRect.top;
}
else if ((this.sprite.y + this.sprite.height) > this.boundsRect.bottom)
{
this.sprite.y = this.boundsRect.bottom - this.sprite.height;
}
}
},
/**
* Parent Sprite Bounds check for the sprite drag.
* @method Phaser.InputHandler#checkBoundsSprite
*/
checkBoundsSprite: function () {
if (this.sprite.fixedToCamera && this.boundsSprite.fixedToCamera)
{
if (this.sprite.cameraOffset.x < this.boundsSprite.camerOffset.x)
{
this.sprite.cameraOffset.x = this.boundsSprite.camerOffset.x;
}
else if ((this.sprite.cameraOffset.x + this.sprite.width) > (this.boundsSprite.camerOffset.x + this.boundsSprite.width))
{
this.sprite.cameraOffset.x = (this.boundsSprite.camerOffset.x + this.boundsSprite.width) - this.sprite.width;
}
if (this.sprite.cameraOffset.y < this.boundsSprite.camerOffset.y)
{
this.sprite.cameraOffset.y = this.boundsSprite.camerOffset.y;
}
else if ((this.sprite.cameraOffset.y + this.sprite.height) > (this.boundsSprite.camerOffset.y + this.boundsSprite.height))
{
this.sprite.cameraOffset.y = (this.boundsSprite.camerOffset.y + this.boundsSprite.height) - this.sprite.height;
}
}
else
{
if (this.sprite.x < this.boundsSprite.x)
{
this.sprite.x = this.boundsSprite.x;
}
else if ((this.sprite.x + this.sprite.width) > (this.boundsSprite.x + this.boundsSprite.width))
{
this.sprite.x = (this.boundsSprite.x + this.boundsSprite.width) - this.sprite.width;
}
if (this.sprite.y < this.boundsSprite.y)
{
this.sprite.y = this.boundsSprite.y;
}
else if ((this.sprite.y + this.sprite.height) > (this.boundsSprite.y + this.boundsSprite.height))
{
this.sprite.y = (this.boundsSprite.y + this.boundsSprite.height) - this.sprite.height;
}
}
}
};
Phaser.InputHandler.prototype.constructor = Phaser.InputHandler;
/**
* @author Antony Woods <antony@teamwoods.org>
* @copyright 2014 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* Phaser - Gestures constructor.
*
* @class Phaser.Gestures
* @classdesc An object for controlling the detection of global gestures.
* @constructor
* @param {Phaser.Game} game - A reference to the currently running game.
*/
Phaser.Gestures = function (game) {
/**
* @property {Phaser.Game} game - A reference to the currently running game.
*/
this.game = game;
/**
* @property {boolean} active - If true, the Gestures class will attempt to detect gestures
* @default
*/
this.active = false;
/**
* @property {Array} _gestures - A list of gestures that we're currently tracking.
* @default
*/
this._gestures = [];
/**
* @property {Array} _pointers - A list of of pointers that are in the process of being detected
* @default
*/
this._pointers = [];
/**
* Update pointer state
*/
this.game.input.setMoveCallback(function (pointer) {
if (this.active)
{
this._updatePointerState(pointer);
}
}, this);
};
Phaser.Gestures.prototype = {
/**
* Add a new pointer and gesture type to the detection system
* @method Phaser.Gestures#add
* @param {Phaser.Gestures} gesture - a gesture that we wish to detect (i.e. Phaser.Gesture.SwipeLeft)
* @param {function} onGestureUpdated - a callback for when the gesture updates (returns with valid data)
*/
add: function (gesture, onGestureUpdated) {
this.add(gesture, onGestureUpdated, null, null);
},
/**
* Add a new pointer and gesture type to the detection system
* @method Phaser.Gestures#add
* @param {Phaser.Gestures} gesture - a gesture that we wish to detect (i.e. Phaser.Gesture.SwipeLeft)
* @param {function} onGestureUpdated - a callback for when the gesture updates (returns with valid data)
* @param {function} onGestureStarted - a callback for when the gesture starts (begins detection)
* @param {function} onGestureStopped - a callback for when the gesture stops (ends detection)
*/
add: function (gesture, onGestureUpdated, onGestureStarted, onGestureStopped) {
var gestureObject = {
gesture: new gesture(),
hasStarted: false,
onGestureStarted: onGestureStarted,
onGestureUpdated: onGestureUpdated,
onGestureStopped: onGestureStopped,
}
this._gestures.push(gestureObject);
},
/**
* Remove a pointer and gesture combination from the detection system
* @method Phaser.Gestures#remove
* @param {Phaser.Gestures} gesture - a gesture that we no longer wish to detect (i.e. Phaser.Gesture.SwipeLeft)
*/
remove: function (gesture) {
for (var i = this._gestures.length - 1; i >= 0; --i)
{
if (this._gestures[i].gesture.name == new gesture().name)
{
delete this._gestures[i];
}
}
this._gestures = this._gestures.filter(function(a){return typeof a !== 'undefined';});
},
/**
* Update function, called whenever a pointer triggers an event.
* @method Phaser.Gestures#update
*/
update: function () {
if (this.active && this._pointers.length > 0)
{
var hasPointers = this._pointers.filter(function(p){return p.isDown;}).length > 0;
for (var i = this._gestures.length - 1; i >= 0; --i)
{
if (!this._gestures[i].hasStarted)
{
this._gestures[i].hasStarted = true;
this._gestures[i].gesture.start(this._pointers);
if (this._gestures[i].onGestureStarted != null)
{
this._gestures[i].onGestureStarted();
}
}
else
{
var result = this._gestures[i].gesture.update(this._pointers);
if (result)
{
var data = this._gestures[i].gesture.getData();
if (this._gestures[i].onGestureUpdated != null)
{
this._gestures[i].onGestureUpdated(data);
}
}
if (!hasPointers)
{
this._gestures[i].gesture.stop(this._pointers);
this._gestures[i].hasStarted = false;
if (this._gestures[i].onGestureStopped != null)
{
this._gestures[i].onGestureStopped();
}
}
}
}
this._pointers = this._pointers.filter(function(p){return p.isDown;});
}
},
/**
* Updates internal pointer state
* @method Phaser.Gestures#update
* @param {Phaser.Pointer} pointer - the pointer that triggered this update
*/
_updatePointerState: function (pointer) {
var pointerObject = null;
for (var i = this._pointers.length - 1; i >= 0; --i)
{
if (this._pointers[i].pointer == pointer)
{
pointerObject = this._pointers[i];
break;
}
}
if (pointerObject == null && pointer.isDown)
{
pointerObject = {
pointer: pointer,
justPressed: true,
isUp: false,
isDown: true
}
this._pointers.push(pointerObject);
}
else if (pointerObject != null)
{
pointerObject.justPressed = false;
pointerObject.isDown = pointer.isDown;
pointerObject.isUp = pointer.isUp;
}
}
};
Phaser.Gestures.prototype.constructor = Phaser.Gestures;
/* ---------------------------------------- */
Phaser.Gestures.Helpers = {
/**
* Finds or creates a local 'pointer' object from a given array
*
* @method Phaser.Gestures.Helpers#createOrFindPointerData
* @param {Array} - an array of objects that expose 'pointer' as a field.
* @param {Phaser.Point} - the pointer object we're attempting to find.
*/
createOrFindPointerData: function(pointerArray, pointer) {
var pointerObject = null;
for (var i = pointerArray.length - 1; i >= 0; --i)
{
if (pointerArray[i].pointer == pointer)
{
pointerObject = pointerArray[i];
break;
}
}
if (pointerObject == null)
{
pointerObject = {
pointer:pointer,
isNew: true
}
pointerArray.push(pointerObject);
}
return pointerObject;
}
};
Phaser.Gesture = {};
/**
* Swipe-Left detection
*
* @class Phaser.Gesture.SwipeLeft
*/
Phaser.Gesture.SwipeLeft = function (game) {
/**
* @property {Phaser.Game} game - A reference to the currently running game.
*/
this.game = game;
/**
* @property {String} - the name of the gesture
* @default
*/
this.name = "SwipeLeft";
/**
* @property {Array} _deltaXPerPointer - A list of delta X value for each pointer.
* @default
*/
this._pointerData = [];
};
Phaser.Gesture.SwipeLeft.prototype = {
/**
* Find a pointer data object using the helper
*
* @method Phaser.Gesture.SwipeLeft#_createOrFindPointerData
* @param {Phaser.Pointer} - the pointer for which we want to retrieve data
*/
_createOrFindPointerData: function (pointer) {
var ptrObject = Phaser.Gestures.Helpers.createOrFindPointerData(this._pointerData, pointer);
if (ptrObject.isNew)
{
ptrObject.isNew = false;
ptrObject.lastX = pointer.pointer.x;
ptrObject.lastY = pointer.pointer.y;
ptrObject.hasTriggered = false;
}
return ptrObject;
},
/**
* Start detection process for gesture, called when a pointer touches the screen
*
* @method Phaser.Gesture.SwipeLeft#update
* @param {Array} - an array to all the current pointers
*/
start: function (pointers) {
for (var i = pointers.length - 1; i >=0; --i)
{
this._createOrFindPointerData(pointers[i]);
}
},
/**
* Update during the detection of a gesture, called when a pointer moves
*
* @method Phaser.Gesture.SwipeLeft#update
* @param {Array} - an array to all the current pointers
* @returns {boolean} True, if the gesture has been detected and can return some tangible information.
*/
update: function (pointers) {
for (var i = pointers.length - 1; i >=0; --i)
{
var ptrObject = this._createOrFindPointerData(pointers[i]);
if (ptrObject.pointer.isDown && !ptrObject.hasTriggered)
{
var currentX = pointers[i].pointer.x;
var deltaX = ptrObject.lastX - currentX;
ptrObject.lastX = currentX;
if (deltaX > 100)
{
ptrObject.hasTriggered = true;
return true;
}
}
}
return false
},
/**
* Stop detection process for gesture, called when a pointer leaves the screen
*
* @method Phaser.Gesture.SwipeLeft#update
* @param {Array} - an array to all the current pointers
*/
stop: function (pointers) {
this._pointerData = [];
},
/**
* Fetches the current relevant data for this gesture
*
* @method Phaser.Gesture.SwipeLeft#getData
* @returns {object} an object with data relating to the current state of this gesture
*/
getData: function () {
return { didSwipe: true };
}
}
Phaser.Gesture.SwipeLeft.prototype.constructor = Phaser.Gesture.SwipeLeft;
/**
* Swipe-Right detection
*
* @class Phaser.Gesture.SwipeRight
*/
Phaser.Gesture.SwipeRight = function (game) {
/**
* @property {Phaser.Game} game - A reference to the currently running game.
*/
this.game = game;
/**
* @property {String} - the name of the gesture
* @default
*/
this.name = "SwipeRight";
/**
* @property {Array} _pointerData - A pointer data array.
* @default
*/
this._pointerData = [];
};
Phaser.Gesture.SwipeRight.prototype = {
/**
* Find a pointer data object using the helper
*
* @method Phaser.Gesture.SwipeRight#_createOrFindPointerData
* @private
* @param {Phaser.Pointer} - the pointer for which we want to retrieve data
*/
_createOrFindPointerData: function(pointer) {
var ptrObject = Phaser.Gestures.Helpers.createOrFindPointerData(this._pointerData, pointer);
if (ptrObject.isNew)
{
ptrObject.isNew = false;
ptrObject.lastX = pointer.pointer.x;
ptrObject.lastY = pointer.pointer.y;
ptrObject.hasTriggered = false;
}
return ptrObject;
},
/**
* Start detection process for gesture, called when a pointer touches the screen
*
* @method Phaser.Gesture.SwipeRight#update
* @param {Array} - an array to all the current pointers
*/
start: function (pointers) {
for (var i = pointers.length - 1; i >=0; --i)
{
this._createOrFindPointerData(pointers[i]);
}
},
/**
* Update during the detection of a gesture, called when a pointer moves
*
* @method Phaser.Gesture.SwipeRight#update
* @param {Array} - an array to all the current pointers
* @returns {boolean} True, if the gesture has been detected and can return some tangible information.
*/
update: function (pointers) {
for (var i = pointers.length - 1; i >=0; --i)
{
var ptrObject = this._createOrFindPointerData(pointers[i]);
if (ptrObject.pointer.isDown && !ptrObject.hasTriggered)
{
var currentX = pointers[i].pointer.x;
var deltaX = ptrObject.lastX - currentX;
ptrObject.lastX = currentX;
if (deltaX < -100)
{
ptrObject.hasTriggered = true;
return true;
}
}
}
return false
},
/**
* Stop detection process for gesture, called when a pointer leaves the screen
*
* @method Phaser.Gesture.SwipeRight#update
* @param {Array} - an array to all the current pointers
*/
stop: function (pointers) {
this._pointerData = [];
},
/**
* Fetches the current relevant data for this gesture
*
* @method Phaser.Gesture.SwipeRight#getData
* @returns {object} an object with data relating to the current state of this gesture
*/
getData: function () {
return { didSwipe: true };
}
}
Phaser.Gesture.SwipeRight.prototype.constructor = Phaser.Gesture.SwipeRight;
/**
* Swipe-Down detection
*
* @class Phaser.Gesture.SwipeDown
*/
Phaser.Gesture.SwipeDown = function (game) {
/**
* @property {Phaser.Game} game - A reference to the currently running game.
*/
this.game = game;
/**
* @property {String} - the name of the gesture
* @default
*/
this.name = "SwipeDown";
/**
* @property {Array} _pointerData - Array of pointer data.
* @default
*/
this._pointerData = [];
};
Phaser.Gesture.SwipeDown.prototype = {
/**
* Find a pointer data object using the helper
*
* @method Phaser.Gesture.SwipeDown#_createOrFindPointerData
* @private
* @param {Phaser.Pointer} - the pointer for which we want to retrieve data
*/
_createOrFindPointerData: function (pointer) {
var ptrObject = Phaser.Gestures.Helpers.createOrFindPointerData(this._pointerData, pointer);
if (ptrObject.isNew)
{
ptrObject.isNew = false;
ptrObject.lastX = pointer.pointer.x;
ptrObject.lastY = pointer.pointer.y;
ptrObject.hasTriggered = false;
}
return ptrObject;
},
/**
* Start detection process for gesture, called when a pointer touches the screen
*
* @method Phaser.Gesture.SwipeDown#update
* @param {Array} - an array to all the current pointers
*/
start: function (pointers) {
for (var i = pointers.length - 1; i >=0; --i)
{
this._createOrFindPointerData(pointers[i]);
}
},
/**
* Update during the detection of a gesture, called when a pointer moves
*
* @method Phaser.Gesture.SwipeDown#update
* @param {Array} - an array to all the current pointers
* @returns {boolean} True, if the gesture has been detected and can return some tangible information.
*/
update: function (pointers) {
for (var i = pointers.length - 1; i >=0; --i)
{
var ptrObject = this._createOrFindPointerData(pointers[i]);
if (ptrObject.pointer.isDown && !ptrObject.hasTriggered)
{
var currentY = pointers[i].pointer.y;
var deltaY = ptrObject.lastY - currentY;
ptrObject.lastY = currentY;
if (deltaY < -100)
{
ptrObject.hasTriggered = true;
return true;
}
}
}
return false
},
/**
* Stop detection process for gesture, called when a pointer leaves the screen
*
* @method Phaser.Gesture.SwipeDown#update
* @param {Array} pointers - an array to all the current pointers
*/
stop: function (pointers) {
this._pointerData = [];
},
/**
* Fetches the current relevant data for this gesture
*
* @method Phaser.Gesture.SwipeDown#getData
* @returns {object} an object with data relating to the current state of this gesture
*/
getData: function ( ) {
return { didSwipe: true };
}
}
Phaser.Gesture.SwipeDown.prototype.constructor = Phaser.Gesture.SwipeDown;
/**
* Swipe-Up detection
*
* @class Phaser.Gesture.SwipeUp
*/
Phaser.Gesture.SwipeUp = function (game) {
/**
* @property {Phaser.Game} game - A reference to the currently running game.
*/
this.game = game;
/**
* @property {String} - the name of the gesture
* @default
*/
this.name = "SwipeUp";
/**
* @property {Array} _pointerData - Array of pointer data.
* @default
*/
this._pointerData = [];
};
Phaser.Gesture.SwipeUp.prototype = {
/**
* Find a pointer data object using the helper
*
* @method Phaser.Gesture.SwipeUp#_createOrFindPointerData
* @private
* @param {Phaser.Pointer} - the pointer for which we want to retrieve data
*/
_createOrFindPointerData: function (pointer) {
var ptrObject = Phaser.Gestures.Helpers.createOrFindPointerData(this._pointerData, pointer);
if (ptrObject.isNew)
{
ptrObject.isNew = false;
ptrObject.lastX = pointer.pointer.x;
ptrObject.lastY = pointer.pointer.y;
ptrObject.hasTriggered = false;
}
return ptrObject;
},
/**
* Start detection process for gesture, called when a pointer touches the screen
*
* @method Phaser.Gesture.SwipeUp#update
* @param {Array} - an array to all the current pointers
*/
start: function (pointers) {
for (var i = pointers.length - 1; i >=0; --i)
{
this._createOrFindPointerData(pointers[i]);
}
},
/**
* Update during the detection of a gesture, called when a pointer moves
*
* @method Phaser.Gesture.SwipeUp#update
* @param {Array} - an array to all the current pointers
* @returns {boolean} True, if the gesture has been detected and can return some tangible information.
*/
update: function ( pointers ) {
for (var i = pointers.length - 1; i >=0; --i)
{
var ptrObject = this._createOrFindPointerData(pointers[i]);
if (ptrObject.pointer.isDown && !ptrObject.hasTriggered)
{
var currentY = pointers[i].pointer.y;
var deltaY = ptrObject.lastY - currentY;
ptrObject.lastY = currentY;
if (deltaY > 100)
{
ptrObject.hasTriggered = true;
return true;
}
}
}
return false
},
/**
* Stop detection process for gesture, called when a pointer leaves the screen
*
* @method Phaser.Gesture.SwipeUp#update
* @param {Array} - an array to all the current pointers
*/
stop: function (pointers) {
this._pointerData = [];
},
/**
* Fetches the current relevant data for this gesture
*
* @method Phaser.Gesture.SwipeUp#getData
* @returns {object} an object with data relating to the current state of this gesture
*/
getData: function () {
return { didSwipe: true };
}
}
Phaser.Gesture.SwipeUp.prototype.constructor = Phaser.Gesture.SwipeUp;
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2014 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @class Phaser.Events
*
* @classdesc The Events component is a collection of events fired by the parent game object.
*
* For example to tell when a Sprite has been added to a new group:
*
* `sprite.events.onAddedToGroup.add(yourFunction, this);`
*
* Where `yourFunction` is the function you want called when this event occurs.
*
* Note that the Input related events only exist if the Sprite has had `inputEnabled` set to `true`.
*
* @constructor
*
* @param {Phaser.Sprite} sprite - A reference to Description.
*/
Phaser.Events = function (sprite) {
this.parent = sprite;
this.onAddedToGroup = new Phaser.Signal();
this.onRemovedFromGroup = new Phaser.Signal();
this.onKilled = new Phaser.Signal();
this.onRevived = new Phaser.Signal();
this.onOutOfBounds = new Phaser.Signal();
this.onInputOver = null;
this.onInputOut = null;
this.onInputDown = null;
this.onInputUp = null;
this.onDragStart = null;
this.onDragStop = null;
this.onAnimationStart = null;
this.onAnimationComplete = null;
this.onAnimationLoop = null;
};
Phaser.Events.prototype = {
destroy: function () {
this.parent = null;
this.onAddedToGroup.dispose();
this.onRemovedFromGroup.dispose();
this.onKilled.dispose();
this.onRevived.dispose();
this.onOutOfBounds.dispose();
if (this.onInputOver)
{
this.onInputOver.dispose();
this.onInputOut.dispose();
this.onInputDown.dispose();
this.onInputUp.dispose();
this.onDragStart.dispose();
this.onDragStop.dispose();
}
if (this.onAnimationStart)
{
this.onAnimationStart.dispose();
this.onAnimationComplete.dispose();
this.onAnimationLoop.dispose();
}
}
};
Phaser.Events.prototype.constructor = Phaser.Events;
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2014 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* The Game Object Factory is a quick way to create all of the different sorts of core objects that Phaser uses.
*
* @class Phaser.GameObjectFactory
* @constructor
* @param {Phaser.Game} game - A reference to the currently running game.
*/
Phaser.GameObjectFactory = function (game) {
/**
* @property {Phaser.Game} game - A reference to the currently running Game.
*/
this.game = game;
/**
* @property {Phaser.World} world - A reference to the game world.
*/
this.world = this.game.world;
};
Phaser.GameObjectFactory.prototype = {
/**
* Adds an existing object to the game world.
* @method Phaser.GameObjectFactory#existing
* @param {*} object - An instance of Phaser.Sprite, Phaser.Button or any other display object..
* @return {*} The child that was added to the Group.
*/
existing: function (object) {
return this.world.add(object);
},
/**
* Create a new `Image` object. An Image is a light-weight object you can use to display anything that doesn't need physics or animation.
* It can still rotate, scale, crop and receive input events. This makes it perfect for logos, backgrounds, simple buttons and other non-Sprite graphics.
*
* @method Phaser.GameObjectFactory#image
* @param {number} x - X position of the image.
* @param {number} y - Y position of the image.
* @param {string|Phaser.RenderTexture|PIXI.Texture} key - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture.
* @param {string|number} [frame] - If the sprite uses an image from a texture atlas or sprite sheet you can pass the frame here. Either a number for a frame ID or a string for a frame name.
* @param {Phaser.Group} [group] - Optional Group to add the object to. If not specified it will be added to the World group.
* @returns {Phaser.Sprite} the newly created sprite object.
*/
image: function (x, y, key, frame, group) {
if (typeof group === 'undefined') { group = this.world; }
return group.add(new Phaser.Image(this.game, x, y, key, frame));
},
/**
* Create a new Sprite with specific position and sprite sheet key.
*
* @method Phaser.GameObjectFactory#sprite
* @param {number} x - X position of the new sprite.
* @param {number} y - Y position of the new sprite.
* @param {string|Phaser.RenderTexture|PIXI.Texture} key - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture.
* @param {string|number} [frame] - If the sprite uses an image from a texture atlas or sprite sheet you can pass the frame here. Either a number for a frame ID or a string for a frame name.
* @param {Phaser.Group} [group] - Optional Group to add the object to. If not specified it will be added to the World group.
* @returns {Phaser.Sprite} the newly created sprite object.
*/
sprite: function (x, y, key, frame, group) {
if (typeof group === 'undefined') { group = this.world; }
return group.create(x, y, key, frame);
},
/**
* Create a tween object for a specific object. The object can be any JavaScript object or Phaser object such as Sprite.
*
* @method Phaser.GameObjectFactory#tween
* @param {object} obj - Object the tween will be run on.
* @return {Phaser.Tween} The newly created Phaser.Tween object.
*/
tween: function (obj) {
return this.game.tweens.create(obj);
},
/**
* A Group is a container for display objects that allows for fast pooling, recycling and collision checks.
*
* @method Phaser.GameObjectFactory#group
* @param {any} [parent] - The parent Group or DisplayObjectContainer that will hold this group, if any. If set to null the Group won't be added to the display list. If undefined it will be added to World by default.
* @param {string} [name='group'] - A name for this Group. Not used internally but useful for debugging.
* @param {boolean} [addToStage=false] - If set to true this Group will be added directly to the Game.Stage instead of Game.World.
* @return {Phaser.Group} The newly created group.
*/
group: function (parent, name, addToStage) {
if (typeof name === 'undefined') { name = 'group'; }
if (typeof addToStage === 'undefined') { addToStage = false; }
return new Phaser.Group(this.game, parent, name, addToStage);
},
/**
* A Group is a container for display objects that allows for fast pooling, recycling and collision checks.
*
* @method Phaser.GameObjectFactory#spriteBatch
* @param {any} parent - The parent Group or DisplayObjectContainer that will hold this group, if any.
* @param {string} [name='group'] - A name for this Group. Not used internally but useful for debugging.
* @param {boolean} [addToStage=false] - If set to true this Group will be added directly to the Game.Stage instead of Game.World.
* @return {Phaser.Group} The newly created group.
*/
spriteBatch: function (parent, name, addToStage) {
if (typeof name === 'undefined') { name = 'group'; }
if (typeof addToStage === 'undefined') { addToStage = false; }
return new Phaser.SpriteBatch(this.game, parent, name, addToStage);
},
/**
* Creates a new Sound object.
*
* @method Phaser.GameObjectFactory#audio
* @param {string} key - The Game.cache key of the sound that this object will use.
* @param {number} [volume=1] - The volume at which the sound will be played.
* @param {boolean} [loop=false] - Whether or not the sound will loop.
* @param {boolean} [connect=true] - Controls if the created Sound object will connect to the master gainNode of the SoundManager when running under WebAudio.
* @return {Phaser.Sound} The newly created text object.
*/
audio: function (key, volume, loop, connect) {
return this.game.sound.add(key, volume, loop, connect);
},
/**
* Creates a new Sound object.
*
* @method Phaser.GameObjectFactory#sound
* @param {string} key - The Game.cache key of the sound that this object will use.
* @param {number} [volume=1] - The volume at which the sound will be played.
* @param {boolean} [loop=false] - Whether or not the sound will loop.
* @param {boolean} [connect=true] - Controls if the created Sound object will connect to the master gainNode of the SoundManager when running under WebAudio.
* @return {Phaser.Sound} The newly created text object.
*/
sound: function (key, volume, loop, connect) {
return this.game.sound.add(key, volume, loop, connect);
},
/**
* Creates a new TileSprite object.
*
* @method Phaser.GameObjectFactory#tileSprite
* @param {number} x - The x coordinate (in world space) to position the TileSprite at.
* @param {number} y - The y coordinate (in world space) to position the TileSprite at.
* @param {number} width - The width of the TileSprite.
* @param {number} height - The height of the TileSprite.
* @param {string|Phaser.RenderTexture|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the TileSprite during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture.
* @param {string|number} frame - If this TileSprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index.
* @param {Phaser.Group} [group] - Optional Group to add the object to. If not specified it will be added to the World group.
* @return {Phaser.TileSprite} The newly created tileSprite object.
*/
tileSprite: function (x, y, width, height, key, frame, group) {
if (typeof group === 'undefined') { group = this.world; }
return group.add(new Phaser.TileSprite(this.game, x, y, width, height, key, frame));
},
/**
* Creates a new Text object.
*
* @method Phaser.GameObjectFactory#text
* @param {number} x - X position of the new text object.
* @param {number} y - Y position of the new text object.
* @param {string} text - The actual text that will be written.
* @param {object} style - The style object containing style attributes like font, font size , etc.
* @param {Phaser.Group} [group] - Optional Group to add the object to. If not specified it will be added to the World group.
* @return {Phaser.Text} The newly created text object.
*/
text: function (x, y, text, style, group) {
if (typeof group === 'undefined') { group = this.world; }
return group.add(new Phaser.Text(this.game, x, y, text, style));
},
/**
* Creates a new Button object.
*
* @method Phaser.GameObjectFactory#button
* @param {number} [x] X position of the new button object.
* @param {number} [y] Y position of the new button object.
* @param {string} [key] The image key as defined in the Game.Cache to use as the texture for this button.
* @param {function} [callback] The function to call when this button is pressed
* @param {object} [callbackContext] The context in which the callback will be called (usually 'this')
* @param {string|number} [overFrame] This is the frame or frameName that will be set when this button is in an over state. Give either a number to use a frame ID or a string for a frame name.
* @param {string|number} [outFrame] This is the frame or frameName that will be set when this button is in an out state. Give either a number to use a frame ID or a string for a frame name.
* @param {string|number} [downFrame] This is the frame or frameName that will be set when this button is in a down state. Give either a number to use a frame ID or a string for a frame name.
* @param {string|number} [upFrame] This is the frame or frameName that will be set when this button is in an up state. Give either a number to use a frame ID or a string for a frame name.
* @param {Phaser.Group} [group] - Optional Group to add the object to. If not specified it will be added to the World group.
* @return {Phaser.Button} The newly created button object.
*/
button: function (x, y, key, callback, callbackContext, overFrame, outFrame, downFrame, upFrame, group) {
if (typeof group === 'undefined') { group = this.world; }
return group.add(new Phaser.Button(this.game, x, y, key, callback, callbackContext, overFrame, outFrame, downFrame, upFrame));
},
/**
* Creates a new Graphics object.
*
* @method Phaser.GameObjectFactory#graphics
* @param {number} x - X position of the new graphics object.
* @param {number} y - Y position of the new graphics object.
* @param {Phaser.Group} [group] - Optional Group to add the object to. If not specified it will be added to the World group.
* @return {Phaser.Graphics} The newly created graphics object.
*/
graphics: function (x, y, group) {
if (typeof group === 'undefined') { group = this.world; }
return group.add(new Phaser.Graphics(this.game, x, y));
},
/**
* Emitter is a lightweight particle emitter. It can be used for one-time explosions or for
* continuous effects like rain and fire. All it really does is launch Particle objects out
* at set intervals, and fixes their positions and velocities accorindgly.
*
* @method Phaser.GameObjectFactory#emitter
* @param {number} [x=0] - The x coordinate within the Emitter that the particles are emitted from.
* @param {number} [y=0] - The y coordinate within the Emitter that the particles are emitted from.
* @param {number} [maxParticles=50] - The total number of particles in this emitter.
* @return {Phaser.Emitter} The newly created emitter object.
*/
emitter: function (x, y, maxParticles) {
return this.game.particles.add(new Phaser.Particles.Arcade.Emitter(this.game, x, y, maxParticles));
},
/**
* Create a new RetroFont object to be used as a texture for an Image or Sprite and optionally add it to the Cache.
* A RetroFont uses a bitmap which contains fixed with characters for the font set. You use character spacing to define the set.
* If you need variable width character support then use a BitmapText object instead. The main difference between a RetroFont and a BitmapText
* is that a RetroFont creates a single texture that you can apply to a game object, where-as a BitmapText creates one Sprite object per letter of text.
* The texture can be asssigned or one or multiple images/sprites, but note that the text the RetroFont uses will be shared across them all,
* i.e. if you need each Image to have different text in it, then you need to create multiple RetroFont objects.
*
* @method Phaser.GameObjectFactory#retroFont
* @param {string} font - The key of the image in the Game.Cache that the RetroFont will use.
* @param {number} characterWidth - The width of each character in the font set.
* @param {number} characterHeight - The height of each character in the font set.
* @param {string} chars - The characters used in the font set, in display order. You can use the TEXT_SET consts for common font set arrangements.
* @param {number} charsPerRow - The number of characters per row in the font set.
* @param {number} [xSpacing=0] - If the characters in the font set have horizontal spacing between them set the required amount here.
* @param {number} [ySpacing=0] - If the characters in the font set have vertical spacing between them set the required amount here.
* @param {number} [xOffset=0] - If the font set doesn't start at the top left of the given image, specify the X coordinate offset here.
* @param {number} [yOffset=0] - If the font set doesn't start at the top left of the given image, specify the Y coordinate offset here.
* @return {Phaser.RetroFont} The newly created RetroFont texture which can be applied to an Image or Sprite.
*/
retroFont: function (font, characterWidth, characterHeight, chars, charsPerRow, xSpacing, ySpacing, xOffset, yOffset) {
return new Phaser.RetroFont(this.game, font, characterWidth, characterHeight, chars, charsPerRow, xSpacing, ySpacing, xOffset, yOffset);
},
/**
* Create a new BitmapText object.
*
* @method Phaser.GameObjectFactory#bitmapText
* @param {number} x - X position of the new bitmapText object.
* @param {number} y - Y position of the new bitmapText object.
* @param {string} font - The key of the BitmapText font as stored in Game.Cache.
* @param {string} [text] - The actual text that will be rendered. Can be set later via BitmapText.text.
* @param {number} [size] - The size the font will be rendered in, in pixels.
* @param {Phaser.Group} [group] - Optional Group to add the object to. If not specified it will be added to the World group.
* @return {Phaser.BitmapText} The newly created bitmapText object.
*/
bitmapText: function (x, y, font, text, size, group) {
if (typeof group === 'undefined') { group = this.world; }
return group.add(new Phaser.BitmapText(this.game, x, y, font, text, size));
},
/**
* Creates a new Phaser.Tilemap object. The map can either be populated with data from a Tiled JSON file or from a CSV file.
* To do this pass the Cache key as the first parameter. When using Tiled data you need only provide the key.
* When using CSV data you must provide the key and the tileWidth and tileHeight parameters.
* If creating a blank tilemap to be populated later, you can either specify no parameters at all and then use `Tilemap.create` or pass the map and tile dimensions here.
* Note that all Tilemaps use a base tile size to calculate dimensions from, but that a TilemapLayer may have its own unique tile size that overrides it.
*
* @method Phaser.GameObjectFactory#tilemap
* @param {string} [key] - The key of the tilemap data as stored in the Cache. If you're creating a blank map either leave this parameter out or pass `null`.
* @param {number} [tileWidth=32] - The pixel width of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data.
* @param {number} [tileHeight=32] - The pixel height of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data.
* @param {number} [width=10] - The width of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this.
* @param {number} [height=10] - The height of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this.
* @return {Phaser.Tilemap} The newly created tilemap object.
*/
tilemap: function (key, tileWidth, tileHeight, width, height) {
return new Phaser.Tilemap(this.game, key, tileWidth, tileHeight, width, height);
},
/**
* A dynamic initially blank canvas to which images can be drawn.
*
* @method Phaser.GameObjectFactory#renderTexture
* @param {number} [width=100] - the width of the RenderTexture.
* @param {number} [height=100] - the height of the RenderTexture.
* @param {string} [key=''] - Asset key for the RenderTexture when stored in the Cache (see addToCache parameter).
* @param {boolean} [addToCache=false] - Should this RenderTexture be added to the Game.Cache? If so you can retrieve it with Cache.getTexture(key)
* @return {Phaser.RenderTexture} The newly created RenderTexture object.
*/
renderTexture: function (width, height, key, addToCache) {
if (typeof key === 'undefined' || key === '') { key = this.game.rnd.uuid(); }
if (typeof addToCache === 'undefined') { addToCache = false; }
var texture = new Phaser.RenderTexture(this.game, width, height, key);
if (addToCache)
{
this.game.cache.addRenderTexture(key, texture);
}
return texture;
},
/**
* A BitmapData object which can be manipulated and drawn to like a traditional Canvas object and used to texture Sprites.
*
* @method Phaser.GameObjectFactory#bitmapData
* @param {number} [width=100] - The width of the BitmapData in pixels.
* @param {number} [height=100] - The height of the BitmapData in pixels.
* @param {string} [key=''] - Asset key for the BitmapData when stored in the Cache (see addToCache parameter).
* @param {boolean} [addToCache=false] - Should this BitmapData be added to the Game.Cache? If so you can retrieve it with Cache.getBitmapData(key)
* @return {Phaser.BitmapData} The newly created BitmapData object.
*/
bitmapData: function (width, height, addToCache) {
if (typeof addToCache === 'undefined') { addToCache = false; }
if (typeof key === 'undefined' || key === '') { key = this.game.rnd.uuid(); }
var texture = new Phaser.BitmapData(this.game, key, width, height);
if (addToCache)
{
this.game.cache.addBitmapData(key, texture);
}
return texture;
},
/**
* A WebGL shader/filter that can be applied to Sprites.
*
* @method Phaser.GameObjectFactory#filter
* @param {string} filter - The name of the filter you wish to create, for example HueRotate or SineWave.
* @param {any} - Whatever parameters are needed to be passed to the filter init function.
* @return {Phaser.Filter} The newly created Phaser.Filter object.
*/
filter: function (filter) {
var args = Array.prototype.splice.call(arguments, 1);
var filter = new Phaser.Filter[filter](this.game);
filter.init.apply(filter, args);
return filter;
}
};
Phaser.GameObjectFactory.prototype.constructor = Phaser.GameObjectFactory;
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2014 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* The Game Object Creator is a quick way to create all of the different sorts of core objects that Phaser uses, but not add them to the game world.
* Use the GameObjectFactory to create and add the objects into the world.
*
* @class Phaser.GameObjectCreator
* @constructor
* @param {Phaser.Game} game - A reference to the currently running game.
*/
Phaser.GameObjectCreator = function (game) {
/**
* @property {Phaser.Game} game - A reference to the currently running Game.
*/
this.game = game;
/**
* @property {Phaser.World} world - A reference to the game world.
*/
this.world = this.game.world;
};
Phaser.GameObjectCreator.prototype = {
/**
* Create a new `Image` object. An Image is a light-weight object you can use to display anything that doesn't need physics or animation.
* It can still rotate, scale, crop and receive input events. This makes it perfect for logos, backgrounds, simple buttons and other non-Sprite graphics.
*
* @method Phaser.GameObjectCreator#image
* @param {number} x - X position of the image.
* @param {number} y - Y position of the image.
* @param {string|Phaser.RenderTexture|PIXI.Texture} key - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture.
* @param {string|number} [frame] - If the sprite uses an image from a texture atlas or sprite sheet you can pass the frame here. Either a number for a frame ID or a string for a frame name.
* @returns {Phaser.Sprite} the newly created sprite object.
*/
image: function (x, y, key, frame) {
return new Phaser.Image(this.game, x, y, key, frame);
},
/**
* Create a new Sprite with specific position and sprite sheet key.
*
* @method Phaser.GameObjectCreator#sprite
* @param {number} x - X position of the new sprite.
* @param {number} y - Y position of the new sprite.
* @param {string|Phaser.RenderTexture|PIXI.Texture} key - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture.
* @param {string|number} [frame] - If the sprite uses an image from a texture atlas or sprite sheet you can pass the frame here. Either a number for a frame ID or a string for a frame name.
* @returns {Phaser.Sprite} the newly created sprite object.
*/
sprite: function (x, y, key, frame) {
return new Phaser.Sprite(this.game, x, y, key, frame);
},
/**
* Create a tween object for a specific object. The object can be any JavaScript object or Phaser object such as Sprite.
*
* @method Phaser.GameObjectCreator#tween
* @param {object} obj - Object the tween will be run on.
* @return {Phaser.Tween} The Tween object.
*/
tween: function (obj) {
return new Phaser.Tween(obj, this.game);
},
/**
* A Group is a container for display objects that allows for fast pooling, recycling and collision checks.
*
* @method Phaser.GameObjectCreator#group
* @param {any} [parent] - The parent Group or DisplayObjectContainer that will hold this group, if any. If set to null the Group won't be added to the display list. If undefined it will be added to World by default.
* @param {string} [name='group'] - A name for this Group. Not used internally but useful for debugging.
* @param {boolean} [addToStage=false] - If set to true this Group will be added directly to the Game.Stage instead of Game.World.
* @return {Phaser.Group} The newly created group.
*/
group: function (parent, name, addToStage) {
if (typeof name === 'undefined') { name = 'group'; }
if (typeof addToStage === 'undefined') { addToStage = false; }
return new Phaser.Group(this.game, parent, name, addToStage);
},
/**
* A Group is a container for display objects that allows for fast pooling, recycling and collision checks.
*
* @method Phaser.GameObjectCreator#spriteBatch
* @param {any} parent - The parent Group or DisplayObjectContainer that will hold this group, if any.
* @param {string} [name='group'] - A name for this Group. Not used internally but useful for debugging.
* @param {boolean} [addToStage=false] - If set to true this Group will be added directly to the Game.Stage instead of Game.World.
* @return {Phaser.Group} The newly created group.
*/
spriteBatch: function (parent, name, addToStage) {
if (typeof name === 'undefined') { name = 'group'; }
if (typeof addToStage === 'undefined') { addToStage = false; }
return new Phaser.SpriteBatch(this.game, parent, name, addToStage);
},
/**
* Creates a new Sound object.
*
* @method Phaser.GameObjectCreator#audio
* @param {string} key - The Game.cache key of the sound that this object will use.
* @param {number} [volume=1] - The volume at which the sound will be played.
* @param {boolean} [loop=false] - Whether or not the sound will loop.
* @param {boolean} [connect=true] - Controls if the created Sound object will connect to the master gainNode of the SoundManager when running under WebAudio.
* @return {Phaser.Sound} The newly created text object.
*/
audio: function (key, volume, loop, connect) {
return this.game.sound.add(key, volume, loop, connect);
},
/**
* Creates a new Sound object.
*
* @method Phaser.GameObjectCreator#sound
* @param {string} key - The Game.cache key of the sound that this object will use.
* @param {number} [volume=1] - The volume at which the sound will be played.
* @param {boolean} [loop=false] - Whether or not the sound will loop.
* @param {boolean} [connect=true] - Controls if the created Sound object will connect to the master gainNode of the SoundManager when running under WebAudio.
* @return {Phaser.Sound} The newly created text object.
*/
sound: function (key, volume, loop, connect) {
return this.game.sound.add(key, volume, loop, connect);
},
/**
* Creates a new TileSprite object.
*
* @method Phaser.GameObjectCreator#tileSprite
* @param {number} x - The x coordinate (in world space) to position the TileSprite at.
* @param {number} y - The y coordinate (in world space) to position the TileSprite at.
* @param {number} width - The width of the TileSprite.
* @param {number} height - The height of the TileSprite.
* @param {string|Phaser.RenderTexture|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the TileSprite during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture.
* @param {string|number} frame - If this TileSprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index.
* @return {Phaser.TileSprite} The newly created tileSprite object.
*/
tileSprite: function (x, y, width, height, key, frame) {
return new Phaser.TileSprite(this.game, x, y, width, height, key, frame);
},
/**
* Creates a new Text object.
*
* @method Phaser.GameObjectCreator#text
* @param {number} x - X position of the new text object.
* @param {number} y - Y position of the new text object.
* @param {string} text - The actual text that will be written.
* @param {object} style - The style object containing style attributes like font, font size , etc.
* @return {Phaser.Text} The newly created text object.
*/
text: function (x, y, text, style, group) {
return new Phaser.Text(this.game, x, y, text, style);
},
/**
* Creates a new Button object.
*
* @method Phaser.GameObjectCreator#button
* @param {number} [x] X position of the new button object.
* @param {number} [y] Y position of the new button object.
* @param {string} [key] The image key as defined in the Game.Cache to use as the texture for this button.
* @param {function} [callback] The function to call when this button is pressed
* @param {object} [callbackContext] The context in which the callback will be called (usually 'this')
* @param {string|number} [overFrame] This is the frame or frameName that will be set when this button is in an over state. Give either a number to use a frame ID or a string for a frame name.
* @param {string|number} [outFrame] This is the frame or frameName that will be set when this button is in an out state. Give either a number to use a frame ID or a string for a frame name.
* @param {string|number} [downFrame] This is the frame or frameName that will be set when this button is in a down state. Give either a number to use a frame ID or a string for a frame name.
* @param {string|number} [upFrame] This is the frame or frameName that will be set when this button is in an up state. Give either a number to use a frame ID or a string for a frame name.
* @return {Phaser.Button} The newly created button object.
*/
button: function (x, y, key, callback, callbackContext, overFrame, outFrame, downFrame, upFrame, group) {
return new Phaser.Button(this.game, x, y, key, callback, callbackContext, overFrame, outFrame, downFrame, upFrame);
},
/**
* Creates a new Graphics object.
*
* @method Phaser.GameObjectCreator#graphics
* @param {number} x - X position of the new graphics object.
* @param {number} y - Y position of the new graphics object.
* @param {Phaser.Group} [group] - Optional Group to add the object to. If not specified it will be added to the World group.
* @return {Phaser.Graphics} The newly created graphics object.
*/
graphics: function (x, y, group) {
return new Phaser.Graphics(this.game, x, y);
},
/**
* Emitter is a lightweight particle emitter. It can be used for one-time explosions or for
* continuous effects like rain and fire. All it really does is launch Particle objects out
* at set intervals, and fixes their positions and velocities accorindgly.
*
* @method Phaser.GameObjectCreator#emitter
* @param {number} [x=0] - The x coordinate within the Emitter that the particles are emitted from.
* @param {number} [y=0] - The y coordinate within the Emitter that the particles are emitted from.
* @param {number} [maxParticles=50] - The total number of particles in this emitter.
* @return {Phaser.Emitter} The newly created emitter object.
*/
emitter: function (x, y, maxParticles) {
return new Phaser.Particles.Arcade.Emitter(this.game, x, y, maxParticles);
},
/**
* Create a new RetroFont object to be used as a texture for an Image or Sprite and optionally add it to the Cache.
* A RetroFont uses a bitmap which contains fixed with characters for the font set. You use character spacing to define the set.
* If you need variable width character support then use a BitmapText object instead. The main difference between a RetroFont and a BitmapText
* is that a RetroFont creates a single texture that you can apply to a game object, where-as a BitmapText creates one Sprite object per letter of text.
* The texture can be asssigned or one or multiple images/sprites, but note that the text the RetroFont uses will be shared across them all,
* i.e. if you need each Image to have different text in it, then you need to create multiple RetroFont objects.
*
* @method Phaser.GameObjectCreator#retroFont
* @param {string} font - The key of the image in the Game.Cache that the RetroFont will use.
* @param {number} characterWidth - The width of each character in the font set.
* @param {number} characterHeight - The height of each character in the font set.
* @param {string} chars - The characters used in the font set, in display order. You can use the TEXT_SET consts for common font set arrangements.
* @param {number} charsPerRow - The number of characters per row in the font set.
* @param {number} [xSpacing=0] - If the characters in the font set have horizontal spacing between them set the required amount here.
* @param {number} [ySpacing=0] - If the characters in the font set have vertical spacing between them set the required amount here.
* @param {number} [xOffset=0] - If the font set doesn't start at the top left of the given image, specify the X coordinate offset here.
* @param {number} [yOffset=0] - If the font set doesn't start at the top left of the given image, specify the Y coordinate offset here.
* @return {Phaser.RetroFont} The newly created RetroFont texture which can be applied to an Image or Sprite.
*/
retroFont: function (font, characterWidth, characterHeight, chars, charsPerRow, xSpacing, ySpacing, xOffset, yOffset) {
return new Phaser.RetroFont(this.game, font, characterWidth, characterHeight, chars, charsPerRow, xSpacing, ySpacing, xOffset, yOffset);
},
/**
* Create a new BitmapText object.
*
* @method Phaser.GameObjectCreator#bitmapText
* @param {number} x - X position of the new bitmapText object.
* @param {number} y - Y position of the new bitmapText object.
* @param {string} font - The key of the BitmapText font as stored in Game.Cache.
* @param {string} [text] - The actual text that will be rendered. Can be set later via BitmapText.text.
* @param {number} [size] - The size the font will be rendered in, in pixels.
* @return {Phaser.BitmapText} The newly created bitmapText object.
*/
bitmapText: function (x, y, font, text, size, group) {
return new Phaser.BitmapText(this.game, x, y, font, text, size);
},
/**
* Creates a new Phaser.Tilemap object. The map can either be populated with data from a Tiled JSON file or from a CSV file.
* To do this pass the Cache key as the first parameter. When using Tiled data you need only provide the key.
* When using CSV data you must provide the key and the tileWidth and tileHeight parameters.
* If creating a blank tilemap to be populated later, you can either specify no parameters at all and then use `Tilemap.create` or pass the map and tile dimensions here.
* Note that all Tilemaps use a base tile size to calculate dimensions from, but that a TilemapLayer may have its own unique tile size that overrides it.
*
* @method Phaser.GameObjectCreator#tilemap
* @param {string} [key] - The key of the tilemap data as stored in the Cache. If you're creating a blank map either leave this parameter out or pass `null`.
* @param {number} [tileWidth=32] - The pixel width of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data.
* @param {number} [tileHeight=32] - The pixel height of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data.
* @param {number} [width=10] - The width of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this.
* @param {number} [height=10] - The height of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this.
*/
tilemap: function (key, tileWidth, tileHeight, width, height) {
return new Phaser.Tilemap(this.game, key, tileWidth, tileHeight, width, height);
},
/**
* A dynamic initially blank canvas to which images can be drawn.
*
* @method Phaser.GameObjectCreator#renderTexture
* @param {number} [width=100] - the width of the RenderTexture.
* @param {number} [height=100] - the height of the RenderTexture.
* @param {string} [key=''] - Asset key for the RenderTexture when stored in the Cache (see addToCache parameter).
* @param {boolean} [addToCache=false] - Should this RenderTexture be added to the Game.Cache? If so you can retrieve it with Cache.getTexture(key)
* @return {Phaser.RenderTexture} The newly created RenderTexture object.
*/
renderTexture: function (width, height, key, addToCache) {
if (typeof key === 'undefined' || key === '') { key = this.game.rnd.uuid(); }
if (typeof addToCache === 'undefined') { addToCache = false; }
var texture = new Phaser.RenderTexture(this.game, width, height, key);
if (addToCache)
{
this.game.cache.addRenderTexture(key, texture);
}
return texture;
},
/**
* A BitmapData object which can be manipulated and drawn to like a traditional Canvas object and used to texture Sprites.
*
* @method Phaser.GameObjectCreator#bitmapData
* @param {number} [width=100] - The width of the BitmapData in pixels.
* @param {number} [height=100] - The height of the BitmapData in pixels.
* @param {string} [key=''] - Asset key for the BitmapData when stored in the Cache (see addToCache parameter).
* @param {boolean} [addToCache=false] - Should this BitmapData be added to the Game.Cache? If so you can retrieve it with Cache.getBitmapData(key)
* @return {Phaser.BitmapData} The newly created BitmapData object.
*/
bitmapData: function (width, height, addToCache) {
if (typeof addToCache === 'undefined') { addToCache = false; }
if (typeof key === 'undefined' || key === '') { key = this.game.rnd.uuid(); }
var texture = new Phaser.BitmapData(this.game, key, width, height);
if (addToCache)
{
this.game.cache.addBitmapData(key, texture);
}
return texture;
},
/**
* A WebGL shader/filter that can be applied to Sprites.
*
* @method Phaser.GameObjectCreator#filter
* @param {string} filter - The name of the filter you wish to create, for example HueRotate or SineWave.
* @param {any} - Whatever parameters are needed to be passed to the filter init function.
* @return {Phaser.Filter} The newly created Phaser.Filter object.
*/
filter: function (filter) {
var args = Array.prototype.splice.call(arguments, 1);
var filter = new Phaser.Filter[filter](this.game);
filter.init.apply(filter, args);
return filter;
}
};
Phaser.GameObjectCreator.prototype.constructor = Phaser.GameObjectCreator;
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2014 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* Creates a new BitmapData object.
*
* @class Phaser.BitmapData
*
* @classdesc A BitmapData object contains a Canvas element to which you can draw anything you like via normal Canvas context operations.
* A single BitmapData can be used as the texture one or many Images/Sprites. So if you need to dynamically create a Sprite texture then they are a good choice.
*
* @constructor
* @param {Phaser.Game} game - A reference to the currently running game.
* @param {string} key - Internal Phaser reference key for the render texture.
* @param {number} [width=100] - The width of the BitmapData in pixels.
* @param {number} [height=100] - The height of the BitmapData in pixels.
*/
Phaser.BitmapData = function (game, key, width, height) {
if (typeof width === 'undefined') { width = 100; }
if (typeof height === 'undefined') { height = 100; }
/**
* @property {Phaser.Game} game - A reference to the currently running game.
*/
this.game = game;
/**
* @property {string} key - The key of the BitmapData in the Cache, if stored there.
*/
this.key = key;
/**
* @property {number} width - The width of the BitmapData in pixels.
*/
this.width = width;
/**
* @property {number} height - The height of the BitmapData in pixels.
*/
this.height = height;
/**
* @property {HTMLCanvasElement} canvas - The canvas to which this BitmapData draws.
* @default
*/
this.canvas = Phaser.Canvas.create(width, height, '', true);
/**
* @property {CanvasRenderingContext2D} context - The 2d context of the canvas.
* @default
*/
this.context = this.canvas.getContext('2d');
/**
* @property {CanvasRenderingContext2D} ctx - A reference to BitmapData.context.
*/
this.ctx = this.context;
/**
* @property {array} imageData - The canvas image data.
*/
this.imageData = this.context.getImageData(0, 0, width, height);
/**
* @property {UInt8Clamped} pixels - A reference to the context imageData buffer.
*/
if (this.imageData.data.buffer)
{
this.pixels = this.imageData.data.buffer;
}
else
{
this.pixels = this.imageData.data;
}
/**
* @property {PIXI.BaseTexture} baseTexture - The PIXI.BaseTexture.
* @default
*/
this.baseTexture = new PIXI.BaseTexture(this.canvas);
/**
* @property {PIXI.Texture} texture - The PIXI.Texture.
* @default
*/
this.texture = new PIXI.Texture(this.baseTexture);
/**
* @property {Phaser.Frame} textureFrame - The Frame this BitmapData uses for rendering.
* @default
*/
this.textureFrame = new Phaser.Frame(0, 0, 0, width, height, 'bitmapData', game.rnd.uuid());
/**
* @property {number} type - The const type of this object.
* @default
*/
this.type = Phaser.BITMAPDATA;
this._dirty = false;
}
Phaser.BitmapData.prototype = {
/**
* Updates the given objects so that they use this BitmapData as their texture. This will replace any texture they will currently have set.
*
* @method Phaser.BitmapData#add
* @param {Phaser.Sprite|Phaser.Sprite[]|Phaser.Image|Phaser.Image[]} object - Either a single Sprite/Image or an Array of Sprites/Images.
*/
add: function (object) {
if (Array.isArray(object))
{
for (var i = 0; i < object.length; i++)
{
if (object[i]['loadTexture'])
{
object[i].loadTexture(this);
}
}
}
else
{
object.loadTexture(this);
}
},
/**
* Clears the BitmapData.
* @method Phaser.BitmapData#clear
*/
clear: function () {
this.context.clearRect(0, 0, this.width, this.height);
this._dirty = true;
},
/**
* Resizes the BitmapData.
* @method Phaser.BitmapData#resize
*/
resize: function (width, height) {
if (width !== this.width || height !== this.height)
{
this.width = width;
this.height = height;
this.canvas.width = width;
this.canvas.height = height;
this.textureFrame.width = width;
this.textureFrame.height = height;
this.imageData = this.context.getImageData(0, 0, width, height);
}
this._dirty = true;
},
/**
* @method Phaser.BitmapData#refreshBuffer
*/
refreshBuffer: function () {
this.imageData = this.context.getImageData(0, 0, this.width, this.height);
this.pixels = new Int32Array(this.imageData.data.buffer);
// this.data8 = new Uint8ClampedArray(this.imageData.buffer);
// this.data32 = new Uint32Array(this.imageData.buffer);
},
/**
* Sets the color of the given pixel to the specified red, green, blue and alpha values.
* @method Phaser.BitmapData#setPixel32
* @param {number} x - The X coordinate of the pixel to be set.
* @param {number} y - The Y coordinate of the pixel to be set.
* @param {number} red - The red color value, between 0 and 0xFF (255).
* @param {number} green - The green color value, between 0 and 0xFF (255).
* @param {number} blue - The blue color value, between 0 and 0xFF (255).
* @param {number} alpha - The alpha color value, between 0 and 0xFF (255).
*/
setPixel32: function (x, y, red, green, blue, alpha) {
if (x >= 0 && x <= this.width && y >= 0 && y <= this.height)
{
this.pixels[y * this.width + x] = (alpha << 24) | (blue << 16) | (green << 8) | red;
/*
if (this.isLittleEndian)
{
this.data32[y * this.width + x] = (alpha << 24) | (blue << 16) | (green << 8) | red;
}
else
{
this.data32[y * this.width + x] = (red << 24) | (green << 16) | (blue << 8) | alpha;
}
*/
// this.imageData.data.set(this.data8);
this.context.putImageData(this.imageData, 0, 0);
this._dirty = true;
}
},
/**
* Sets the color of the given pixel to the specified red, green and blue values.
*
* @method Phaser.BitmapData#setPixel
* @param {number} x - The X coordinate of the pixel to be set.
* @param {number} y - The Y coordinate of the pixel to be set.
* @param {number} red - The red color value (between 0 and 255)
* @param {number} green - The green color value (between 0 and 255)
* @param {number} blue - The blue color value (between 0 and 255)
*/
setPixel: function (x, y, red, green, blue) {
this.setPixel32(x, y, red, green, blue, 255);
},
/**
* Get the color of a specific pixel.
*
* @param {number} x - The X coordinate of the pixel to get.
* @param {number} y - The Y coordinate of the pixel to get.
* @return {number} A native color value integer (format: 0xRRGGBB)
*/
getPixel: function (x, y) {
if (x >= 0 && x <= this.width && y >= 0 && y <= this.height)
{
return this.data32[y * this.width + x];
}
},
/**
* Get the color of a specific pixel including its alpha value.
*
* @param {number} x - The X coordinate of the pixel to get.
* @param {number} y - The Y coordinate of the pixel to get.
* @return {number} A native color value integer (format: 0xAARRGGBB)
*/
getPixel32: function (x, y) {
if (x >= 0 && x <= this.width && y >= 0 && y <= this.height)
{
return this.data32[y * this.width + x];
}
},
/**
* Gets all the pixels from the region specified by the given Rectangle object.
*
* @param {Phaser.Rectangle} rect - The Rectangle region to get.
* @return {array} CanvasPixelArray.
*/
getPixels: function (rect) {
return this.context.getImageData(rect.x, rect.y, rect.width, rect.height);
},
/**
* Copies the pixels from the source image to this BitmapData based on the given area and destination.
*
* @param {HTMLImage|string} source - The Image to draw. If you give a key it will try and find the Image in the Game.Cache.
* @param {Phaser.Rectangle} area - The Rectangle region to copy from the source image.
* @param {number} destX - The destination x coordinate to copy the image to.
* @param {number} destY - The destination y coordinate to copy the image to.
*/
copyPixels: function (source, area, destX, destY) {
if (typeof source === 'string')
{
source = this.game.cache.getImage(source);
}
if (source)
{
this.context.drawImage(source, area.x, area.y, area.width, area.height, destX, destY, area.width, area.height);
}
},
/**
* Draws the given image to this BitmapData at the coordinates specified. If you need to only draw a part of the image use BitmapData.copyPixels instead.
*
* @param {HTMLImage|string} source - The Image to draw. If you give a key it will try and find the Image in the Game.Cache.
* @param {number} destX - The destination x coordinate to draw the image to.
* @param {number} destY - The destination y coordinate to draw the image to.
*/
draw: function (source, destX, destY) {
if (typeof source === 'string')
{
source = this.game.cache.getImage(source);
}
if (source)
{
this.context.drawImage(source, 0, 0, source.width, source.height, destX, destY, source.width, source.height);
}
},
/**
* Draws the given image onto this BitmapData using an image as an alpha mask.
*
* @param {HTMLImage|string} source - The Image to draw. If you give a key it will try and find the Image in the Game.Cache.
* @param {HTMLImage|string} mask - The Image to use as the alpha mask. If you give a key it will try and find the Image in the Game.Cache.
*/
alphaMask: function (source, mask) {
var temp = this.context.globalCompositeOperation;
if (typeof mask === 'string')
{
mask = this.game.cache.getImage(mask);
}
if (mask)
{
this.context.drawImage(mask, 0, 0);
}
this.context.globalCompositeOperation = 'source-atop';
if (typeof source === 'string')
{
source = this.game.cache.getImage(source);
}
if (source)
{
this.context.drawImage(source, 0, 0);
}
this.context.globalCompositeOperation = temp;
},
/**
* If the game is running in WebGL this will push the texture up to the GPU if it's dirty.
* This is called automatically if the BitmapData is being used by a Sprite, otherwise you need to remember to call it in your render function.
*
* @method Phaser.BitmapData#render
*/
render: function () {
if (this._dirty)
{
// Only needed if running in WebGL, otherwise this array will never get cleared down
if (this.game.renderType === Phaser.WEBGL)
{
// should use the rendersession
PIXI.updateWebGLTexture(this.baseTexture, this.game.renderer.gl);
}
this._dirty = false;
}
}
};
Phaser.BitmapData.prototype.constructor = Phaser.BitmapData;
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2014 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @class Phaser.Sprite
*
* @classdesc Create a new `Sprite` object. Sprites are the lifeblood of your game, used for nearly everything visual.
*
* At its most basic a Sprite consists of a set of coordinates and a texture that is rendered to the canvas.
* They also contain additional properties allowing for physics motion (via Sprite.body), input handling (via Sprite.input),
* events (via Sprite.events), animation (via Sprite.animations), camera culling and more. Please see the Examples for use cases.
*
* @constructor
* @extends PIXI.Sprite
* @param {Phaser.Game} game - A reference to the currently running game.
* @param {number} x - The x coordinate (in world space) to position the Sprite at.
* @param {number} y - The y coordinate (in world space) to position the Sprite at.
* @param {string|Phaser.RenderTexture|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture.
* @param {string|number} frame - If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index.
*/
Phaser.Sprite = function (game, x, y, key, frame) {
x = x || 0;
y = y || 0;
key = key || null;
frame = frame || null;
/**
* @property {Phaser.Game} game - A reference to the currently running Game.
*/
this.game = game;
/**
* @property {string} name - The user defined name given to this Sprite.
* @default
*/
this.name = '';
/**
* @property {number} type - The const type of this object.
* @readonly
*/
this.type = Phaser.SPRITE;
/**
* @property {Phaser.Events} events - The Events you can subscribe to that are dispatched when certain things happen on this Sprite or its components.
*/
this.events = new Phaser.Events(this);
/**
* @property {Phaser.AnimationManager} animations - This manages animations of the sprite. You can modify animations through it (see Phaser.AnimationManager)
*/
this.animations = new Phaser.AnimationManager(this);
/**
* @property {string|Phaser.RenderTexture|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture, BitmapData or PIXI.Texture.
*/
this.key = key;
/**
* @property {number} _frame - Internal cache var.
* @private
*/
this._frame = 0;
/**
* @property {string} _frameName - Internal cache var.
* @private
*/
this._frameName = '';
PIXI.Sprite.call(this, PIXI.TextureCache['__default']);
this.loadTexture(key, frame);
this.position.set(x, y);
/**
* @property {Phaser.Point} world - The world coordinates of this Sprite. This differs from the x/y coordinates which are relative to the Sprites container.
*/
this.world = new Phaser.Point(x, y);
/**
* Should this Sprite be automatically culled if out of range of the camera?
* A culled sprite has its renderable property set to 'false'.
* Be advised this is quite an expensive operation, as it has to calculate the bounds of the object every frame, so only enable it if you really need it.
*
* @property {boolean} autoCull - A flag indicating if the Sprite should be automatically camera culled or not.
* @default
*/
this.autoCull = false;
/**
* @property {Phaser.InputHandler|null} input - The Input Handler for this object. Needs to be enabled with image.inputEnabled = true before you can use it.
*/
this.input = null;
/**
* By default Sprites won't add themselves to any physics system and their physics body will be `null`.
* To enable them for physics you need to call `game.physics.enable(sprite, system)` where `sprite` is this object
* and `system` is the Physics system you want to use to manage this body. Once enabled you can access all physics related properties via `Sprite.body`.
*
* Important: Enabling a Sprite for P2 or Ninja physics will automatically set `Sprite.anchor` to 0.5 so the physics body is centered on the Sprite.
* If you need a different result then adjust or re-create the Body shape offsets manually, and/or reset the anchor after enabling physics.
*
* @property {Phaser.Physics.Arcade.Body|Phaser.Physics.P2.Body|Phaser.Physics.Ninja.Body|null} body
* @default
*/
this.body = null;
/**
* @property {number} health - Health value. Used in combination with damage() to allow for quick killing of Sprites.
*/
this.health = 1;
/**
* If you would like the Sprite to have a lifespan once 'born' you can set this to a positive value. Handy for particles, bullets, etc.
* The lifespan is decremented by game.time.elapsed each update, once it reaches zero the kill() function is called.
* @property {number} lifespan - The lifespan of the Sprite (in ms) before it will be killed.
* @default
*/
this.lifespan = 0;
/**
* If true the Sprite checks if it is still within the world each frame, when it leaves the world it dispatches Sprite.events.onOutOfBounds
* and optionally kills the sprite (if Sprite.outOfBoundsKill is true). By default this is disabled because the Sprite has to calculate its
* bounds every frame to support it, and not all games need it. Enable it by setting the value to true.
* @property {boolean} checkWorldBounds
* @default
*/
this.checkWorldBounds = false;
/**
* @property {boolean} outOfBoundsKill - If true Sprite.kill is called as soon as Sprite.inWorld returns false, as long as Sprite.checkWorldBounds is true.
* @default
*/
this.outOfBoundsKill = false;
/**
* @property {boolean} debug - Handy flag to use with Game.enableStep
* @default
*/
this.debug = false;
/**
* @property {Phaser.Point} cameraOffset - If this object is fixedToCamera then this stores the x/y offset that its drawn at, from the top-left of the camera view.
*/
this.cameraOffset = new Phaser.Point();
/**
* A small internal cache:
* 0 = previous position.x
* 1 = previous position.y
* 2 = previous rotation
* 3 = renderID
* 4 = fresh? (0 = no, 1 = yes)
* 5 = outOfBoundsFired (0 = no, 1 = yes)
* 6 = exists (0 = no, 1 = yes)
* 7 = fixed to camera (0 = no, 1 = yes)
* @property {Int16Array} _cache
* @private
*/
this._cache = new Int16Array([0, 0, 0, 0, 1, 0, 1, 0]);
/**
* @property {Phaser.Rectangle} _bounds - Internal cache var.
* @private
*/
this._bounds = new Phaser.Rectangle();
};
Phaser.Sprite.prototype = Object.create(PIXI.Sprite.prototype);
Phaser.Sprite.prototype.constructor = Phaser.Sprite;
/**
* Automatically called by World.preUpdate.
*
* @method Phaser.Sprite#preUpdate
* @memberof Phaser.Sprite
* @return {boolean} True if the Sprite was rendered, otherwise false.
*/
Phaser.Sprite.prototype.preUpdate = function() {
if (this._cache[4] === 1)
{
this.world.setTo(this.parent.position.x + this.position.x, this.parent.position.y + this.position.y);
this.worldTransform.tx = this.world.x;
this.worldTransform.ty = this.world.y;
this._cache[0] = this.world.x;
this._cache[1] = this.world.y;
this._cache[2] = this.rotation;
this._cache[4] = 0;
return false;
}
this._cache[0] = this.world.x;
this._cache[1] = this.world.y;
this._cache[2] = this.rotation;
if (!this.exists || !this.parent.exists)
{
// Reset the renderOrderID
this._cache[3] = -1;
return false;
}
if (this.lifespan > 0)
{
this.lifespan -= this.game.time.elapsed;
if (this.lifespan <= 0)
{
this.kill();
return false;
}
}
// Cache the bounds if we need it
if (this.autoCull || this.checkWorldBounds)
{
this._bounds.copyFrom(this.getBounds());
}
if (this.autoCull)
{
// Won't get rendered but will still get its transform updated
this.renderable = this.game.world.camera.screenView.intersects(this._bounds);
}
if (this.checkWorldBounds)
{
// The Sprite is already out of the world bounds, so let's check to see if it has come back again
if (this._cache[5] === 1 && this.game.world.bounds.intersects(this._bounds))
{
this._cache[5] = 0;
}
else if (this._cache[5] === 0 && !this.game.world.bounds.intersects(this._bounds))
{
// The Sprite WAS in the screen, but has now left.
this._cache[5] = 1;
this.events.onOutOfBounds.dispatch(this);
if (this.outOfBoundsKill)
{
this.kill();
return false;
}
}
}
this.world.setTo(this.game.camera.x + this.worldTransform.tx, this.game.camera.y + this.worldTransform.ty);
if (this.visible)
{
this._cache[3] = this.game.stage.currentRenderOrderID++;
}
this.animations.update();
if (this.exists && this.body)
{
this.body.preUpdate();
}
// Update any Children
for (var i = 0, len = this.children.length; i < len; i++)
{
this.children[i].preUpdate();
}
return true;
};
/**
* Override and use this function in your own custom objects to handle any update requirements you may have.
* Remember if this Sprite has any children you should call update on them too.
*
* @method Phaser.Sprite#update
* @memberof Phaser.Sprite
*/
Phaser.Sprite.prototype.update = function() {
};
/**
* Internal function called by the World postUpdate cycle.
*
* @method Phaser.Sprite#postUpdate
* @memberof Phaser.Sprite
*/
Phaser.Sprite.prototype.postUpdate = function() {
if (this.key instanceof Phaser.BitmapData && this.key._dirty)
{
this.key.render();
}
if (this.exists && this.body)
{
this.body.postUpdate();
}
// Fixed to Camera?
if (this._cache[7] === 1)
{
this.position.x = (this.game.camera.view.x + this.cameraOffset.x) / this.game.camera.scale.x;
this.position.y = (this.game.camera.view.y + this.cameraOffset.y) / this.game.camera.scale.y;
}
// Update any Children
for (var i = 0, len = this.children.length; i < len; i++)
{
this.children[i].postUpdate();
}
};
/**
* Changes the Texture the Sprite is using entirely. The old texture is removed and the new one is referenced or fetched from the Cache.
* This causes a WebGL texture update, so use sparingly or in low-intensity portions of your game.
*
* @method Phaser.Sprite#loadTexture
* @memberof Phaser.Sprite
* @param {string|Phaser.RenderTexture|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture, BitmapData or PIXI.Texture.
* @param {string|number} frame - If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index.
*/
Phaser.Sprite.prototype.loadTexture = function (key, frame) {
frame = frame || 0;
if (key instanceof Phaser.RenderTexture)
{
this.key = key.key;
this.setTexture(key);
return;
}
else if (key instanceof Phaser.BitmapData)
{
this.key = key.key;
this.setTexture(key.texture);
return;
}
else if (key instanceof PIXI.Texture)
{
this.key = key;
this.setTexture(key);
return;
}
else
{
if (key === null || typeof key === 'undefined')
{
this.key = '__default';
this.setTexture(PIXI.TextureCache[this.key]);
return;
}
else if (typeof key === 'string' && !this.game.cache.checkImageKey(key))
{
this.key = '__missing';
this.setTexture(PIXI.TextureCache[this.key]);
return;
}
if (this.game.cache.isSpriteSheet(key))
{
this.key = key;
// var frameData = this.game.cache.getFrameData(key);
this.animations.loadFrameData(this.game.cache.getFrameData(key));
if (typeof frame === 'string')
{
this.frameName = frame;
}
else
{
this.frame = frame;
}
}
else
{
this.key = key;
this.setTexture(PIXI.TextureCache[key]);
return;
}
}
};
/**
* Crop allows you to crop the texture used to display this Sprite.
* Cropping takes place from the top-left of the Sprite and can be modified in real-time by providing an updated rectangle object.
*
* @method Phaser.Sprite#crop
* @memberof Phaser.Sprite
* @param {Phaser.Rectangle} rect - The Rectangle to crop the Sprite to. Pass null or no parameters to clear a previously set crop rectangle.
*/
Phaser.Sprite.prototype.crop = function(rect) {
if (typeof rect === 'undefined' || rect === null)
{
// Clear any crop that may be set
if (this.texture.hasOwnProperty('sourceWidth'))
{
this.texture.setFrame(new Phaser.Rectangle(0, 0, this.texture.sourceWidth, this.texture.sourceHeight));
}
}
else
{
// Do we need to clone the PIXI.Texture object?
if (this.texture instanceof PIXI.Texture)
{
// Yup, let's rock it ...
var local = {};
Phaser.Utils.extend(true, local, this.texture);
local.sourceWidth = local.width;
local.sourceHeight = local.height;
local.frame = rect;
local.width = rect.width;
local.height = rect.height;
this.texture = local;
this.texture.updateFrame = true;
PIXI.Texture.frameUpdates.push(this.texture);
}
else
{
this.texture.setFrame(rect);
}
}
};
/**
* Brings a 'dead' Sprite back to life, optionally giving it the health value specified.
* A resurrected Sprite has its alive, exists and visible properties all set to true.
* It will dispatch the onRevived event, you can listen to Sprite.events.onRevived for the signal.
*
* @method Phaser.Sprite#revive
* @memberof Phaser.Sprite
* @param {number} [health=1] - The health to give the Sprite.
* @return (Phaser.Sprite) This instance.
*/
Phaser.Sprite.prototype.revive = function(health) {
if (typeof health === 'undefined') { health = 1; }
this.alive = true;
this.exists = true;
this.visible = true;
this.health = health;
if (this.events)
{
this.events.onRevived.dispatch(this);
}
return this;
};
/**
* Kills a Sprite. A killed Sprite has its alive, exists and visible properties all set to false.
* It will dispatch the onKilled event, you can listen to Sprite.events.onKilled for the signal.
* Note that killing a Sprite is a way for you to quickly recycle it in a Sprite pool, it doesn't free it up from memory.
* If you don't need this Sprite any more you should call Sprite.destroy instead.
*
* @method Phaser.Sprite#kill
* @memberof Phaser.Sprite
* @return (Phaser.Sprite) This instance.
*/
Phaser.Sprite.prototype.kill = function() {
this.alive = false;
this.exists = false;
this.visible = false;
if (this.events)
{
this.events.onKilled.dispatch(this);
}
return this;
};
/**
* Destroys the Sprite. This removes it from its parent group, destroys the input, event and animation handlers if present
* and nulls its reference to game, freeing it up for garbage collection.
*
* @method Phaser.Sprite#destroy
* @memberof Phaser.Sprite
* @param {boolean} [destroyChildren=true] - Should every child of this object have its destroy method called?
*/
Phaser.Sprite.prototype.destroy = function(destroyChildren) {
if (this.game === null) { return; }
if (typeof destroyChildren === 'undefined') { destroyChildren = true; }
if (this.parent)
{
if (this.parent instanceof Phaser.Group)
{
this.parent.remove(this);
}
else
{
this.parent.removeChild(this);
}
}
if (this.input)
{
this.input.destroy();
}
if (this.animations)
{
this.animations.destroy();
}
if (this.body)
{
this.body.destroy();
}
if (this.events)
{
this.events.destroy();
}
var i = this.children.length;
if (destroyChildren)
{
while (i--)
{
this.children[i].destroy(destroyChildren);
}
}
else
{
while (i--)
{
this.removeChild(this.children[i]);
}
}
this.alive = false;
this.exists = false;
this.visible = false;
this.filters = null;
this.mask = null;
this.game = null;
};
/**
* Damages the Sprite, this removes the given amount from the Sprites health property.
* If health is then taken below or is equal to zero `Sprite.kill` is called.
*
* @method Phaser.Sprite#damage
* @memberof Phaser.Sprite
* @param {number} amount - The amount to subtract from the Sprite.health value.
* @return (Phaser.Sprite) This instance.
*/
Phaser.Sprite.prototype.damage = function(amount) {
if (this.alive)
{
this.health -= amount;
if (this.health <= 0)
{
this.kill();
}
}
return this;
};
/**
* Resets the Sprite. This places the Sprite at the given x/y world coordinates and then
* sets alive, exists, visible and renderable all to true. Also resets the outOfBounds state and health values.
* If the Sprite has a physics body that too is reset.
*
* @method Phaser.Sprite#reset
* @memberof Phaser.Sprite
* @param {number} x - The x coordinate (in world space) to position the Sprite at.
* @param {number} y - The y coordinate (in world space) to position the Sprite at.
* @param {number} [health=1] - The health to give the Sprite.
* @return (Phaser.Sprite) This instance.
*/
Phaser.Sprite.prototype.reset = function(x, y, health) {
if (typeof health === 'undefined') { health = 1; }
this.world.setTo(x, y);
this.position.x = x;
this.position.y = y;
this.alive = true;
this.exists = true;
this.visible = true;
this.renderable = true;
this._outOfBoundsFired = false;
this.health = health;
if (this.body)
{
this.body.reset(x, y, false, false);
}
return this;
};
/**
* Brings the Sprite to the top of the display list it is a child of. Sprites that are members of a Phaser.Group are only
* bought to the top of that Group, not the entire display list.
*
* @method Phaser.Sprite#bringToTop
* @memberof Phaser.Sprite
* @return (Phaser.Sprite) This instance.
*/
Phaser.Sprite.prototype.bringToTop = function() {
if (this.parent)
{
this.parent.bringToTop(this);
}
return this;
};
/**
* Play an animation based on the given key. The animation should previously have been added via sprite.animations.add()
* If the requested animation is already playing this request will be ignored. If you need to reset an already running animation do so directly on the Animation object itself.
*
* @method Phaser.Sprite#play
* @memberof Phaser.Sprite
* @param {string} name - The name of the animation to be played, e.g. "fire", "walk", "jump".
* @param {number} [frameRate=null] - The framerate to play the animation at. The speed is given in frames per second. If not provided the previously set frameRate of the Animation is used.
* @param {boolean} [loop=false] - Should the animation be looped after playback. If not provided the previously set loop value of the Animation is used.
* @param {boolean} [killOnComplete=false] - If set to true when the animation completes (only happens if loop=false) the parent Sprite will be killed.
* @return {Phaser.Animation} A reference to playing Animation instance.
*/
Phaser.Sprite.prototype.play = function (name, frameRate, loop, killOnComplete) {
if (this.animations)
{
return this.animations.play(name, frameRate, loop, killOnComplete);
}
};
/**
* Indicates the rotation of the Sprite, in degrees, from its original orientation. Values from 0 to 180 represent clockwise rotation; values from 0 to -180 represent counterclockwise rotation.
* Values outside this range are added to or subtracted from 360 to obtain a value within the range. For example, the statement player.angle = 450 is the same as player.angle = 90.
* If you wish to work in radians instead of degrees use the property Sprite.rotation instead. Working in radians is also a little faster as it doesn't have to convert the angle.
*
* @name Phaser.Sprite#angle
* @property {number} angle - The angle of this Sprite in degrees.
*/
Object.defineProperty(Phaser.Sprite.prototype, "angle", {
get: function() {
return Phaser.Math.wrapAngle(Phaser.Math.radToDeg(this.rotation));
},
set: function(value) {
this.rotation = Phaser.Math.degToRad(Phaser.Math.wrapAngle(value));
}
});
/**
* Returns the delta x value. The difference between world.x now and in the previous step.
*
* @name Phaser.Sprite#deltaX
* @property {number} deltaX - The delta value. Positive if the motion was to the right, negative if to the left.
* @readonly
*/
Object.defineProperty(Phaser.Sprite.prototype, "deltaX", {
get: function() {
return this.world.x - this._cache[0];
}
});
/**
* Returns the delta y value. The difference between world.y now and in the previous step.
*
* @name Phaser.Sprite#deltaY
* @property {number} deltaY - The delta value. Positive if the motion was downwards, negative if upwards.
* @readonly
*/
Object.defineProperty(Phaser.Sprite.prototype, "deltaY", {
get: function() {
return this.world.y - this._cache[1];
}
});
/**
* Returns the delta z value. The difference between rotation now and in the previous step.
*
* @name Phaser.Sprite#deltaZ
* @property {number} deltaZ - The delta value.
* @readonly
*/
Object.defineProperty(Phaser.Sprite.prototype, "deltaZ", {
get: function() {
return this.rotation - this._cache[2];
}
});
/**
* Checks if the Sprite bounds are within the game world, otherwise false if fully outside of it.
*
* @name Phaser.Sprite#inWorld
* @property {boolean} inWorld - True if the Sprite bounds is within the game world, even if only partially. Otherwise false if fully outside of it.
* @readonly
*/
Object.defineProperty(Phaser.Sprite.prototype, "inWorld", {
get: function() {
return this.game.world.bounds.intersects(this.getBounds());
}
});
/**
* Checks if the Sprite bounds are within the game camera, otherwise false if fully outside of it.
*
* @name Phaser.Sprite#inCamera
* @property {boolean} inCamera - True if the Sprite bounds is within the game camera, even if only partially. Otherwise false if fully outside of it.
* @readonly
*/
Object.defineProperty(Phaser.Sprite.prototype, "inCamera", {
get: function() {
return this.game.world.camera.screenView.intersects(this.getBounds());
}
});
/**
* @name Phaser.Sprite#frame
* @property {number} frame - Gets or sets the current frame index and updates the Texture Cache for display.
*/
Object.defineProperty(Phaser.Sprite.prototype, "frame", {
get: function () {
return this.animations.frame;
},
set: function (value) {
this.animations.frame = value;
}
});
/**
* @name Phaser.Sprite#frameName
* @property {string} frameName - Gets or sets the current frame name and updates the Texture Cache for display.
*/
Object.defineProperty(Phaser.Sprite.prototype, "frameName", {
get: function () {
return this.animations.frameName;
},
set: function (value) {
this.animations.frameName = value;
}
});
/**
* @name Phaser.Sprite#renderOrderID
* @property {number} renderOrderID - The render order ID, reset every frame.
* @readonly
*/
Object.defineProperty(Phaser.Sprite.prototype, "renderOrderID", {
get: function() {
return this._cache[3];
}
});
/**
* By default a Sprite won't process any input events at all. By setting inputEnabled to true the Phaser.InputHandler is
* activated for this object and it will then start to process click/touch events and more.
*
* @name Phaser.Sprite#inputEnabled
* @property {boolean} inputEnabled - Set to true to allow this object to receive input events.
*/
Object.defineProperty(Phaser.Sprite.prototype, "inputEnabled", {
get: function () {
return (this.input && this.input.enabled);
},
set: function (value) {
if (value)
{
if (this.input === null)
{
this.input = new Phaser.InputHandler(this);
this.input.start();
}
}
else
{
if (this.input && this.input.enabled)
{
this.input.stop();
}
}
}
});
/**
* Sprite.exists controls if the core game loop and physics update this Sprite or not.
* When you set Sprite.exists to false it will remove its Body from the physics world (if it has one) and also set Sprite.visible to false.
* Setting Sprite.exists to true will re-add the Body to the physics world (if it has a body) and set Sprite.visible to true.
*
* @name Phaser.Sprite#exists
* @property {boolean} exists - If the Sprite is processed by the core game update and physics.
*/
Object.defineProperty(Phaser.Sprite.prototype, "exists", {
get: function () {
return !!this._cache[6];
},
set: function (value) {
if (value)
{
// exists = true
this._cache[6] = 1;
if (this.body && this.body.type === Phaser.Physics.P2)
{
this.body.addToWorld();
}
this.visible = true;
}
else
{
// exists = false
this._cache[6] = 0;
if (this.body && this.body.type === Phaser.Physics.P2)
{
this.body.removeFromWorld();
}
this.visible = false;
}
}
});
/**
* An Sprite that is fixed to the camera uses its x/y coordinates as offsets from the top left of the camera. These are stored in Sprite.cameraOffset.
* Note that the cameraOffset values are in addition to any parent in the display list.
* So if this Sprite was in a Group that has x: 200, then this will be added to the cameraOffset.x
*
* @name Phaser.Sprite#fixedToCamera
* @property {boolean} fixedToCamera - Set to true to fix this Sprite to the Camera at its current world coordinates.
*/
Object.defineProperty(Phaser.Sprite.prototype, "fixedToCamera", {
get: function () {
return !!this._cache[7];
},
set: function (value) {
if (value)
{
this._cache[7] = 1;
this.cameraOffset.set(this.x, this.y);
}
else
{
this._cache[7] = 0;
}
}
});
/**
* Enable or disable texture smoothing for this Sprite. Only works for bitmap/image textures. Smoothing is enabled by default.
*
* @name Phaser.Sprite#smoothed
* @property {boolean} smoothed - Set to true to smooth the texture of this Sprite, or false to disable smoothing (great for pixel art)
*/
Object.defineProperty(Phaser.Sprite.prototype, "smoothed", {
get: function () {
return !this.texture.baseTexture.scaleMode;
},
set: function (value) {
if (value)
{
if (this.texture)
{
this.texture.baseTexture.scaleMode = 0;
}
}
else
{
if (this.texture)
{
this.texture.baseTexture.scaleMode = 1;
}
}
}
});
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2014 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @class Phaser.Image
*
* @classdesc Create a new `Image` object. An Image is a light-weight object you can use to display anything that doesn't need physics or animation.
* It can still rotate, scale, crop and receive input events. This makes it perfect for logos, backgrounds, simple buttons and other non-Sprite graphics.
*
* @constructor
* @param {Phaser.Game} game - A reference to the currently running game.
* @param {number} x - The x coordinate of the Imaget. The coordinate is relative to any parent container this Image may be in.
* @param {number} y - The y coordinate of the Image. The coordinate is relative to any parent container this Image may be in.
* @param {string|Phaser.RenderTexture|Phaser.BitmapData|PIXI.Texture} key - The texture used by the Image during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture, BitmapData or PIXI.Texture.
* @param {string|number} frame - If this Image is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index.
*/
Phaser.Image = function (game, x, y, key, frame) {
x = x || 0;
y = y || 0;
key = key || null;
frame = frame || null;
/**
* @property {Phaser.Game} game - A reference to the currently running Game.
*/
this.game = game;
/**
* @property {boolean} exists - If exists = false then the Image isn't updated by the core game loop.
* @default
*/
this.exists = true;
/**
* @property {string} name - The user defined name given to this Image.
* @default
*/
this.name = '';
/**
* @property {number} type - The const type of this object.
* @readonly
*/
this.type = Phaser.IMAGE;
/**
* @property {Phaser.Events} events - The Events you can subscribe to that are dispatched when certain things happen on this Image or its components.
*/
this.events = new Phaser.Events(this);
/**
* @property {string|Phaser.RenderTexture|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the Image during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture, BitmapData or PIXI.Texture.
*/
this.key = key;
/**
* @property {number} _frame - Internal cache var.
* @private
*/
this._frame = 0;
/**
* @property {string} _frameName - Internal cache var.
* @private
*/
this._frameName = '';
PIXI.Sprite.call(this, PIXI.TextureCache['__default']);
this.loadTexture(key, frame);
this.position.set(x, y);
/**
* @property {Phaser.Point} world - The world coordinates of this Image. This differs from the x/y coordinates which are relative to the Images container.
*/
this.world = new Phaser.Point(x, y);
/**
* Should this Image be automatically culled if out of range of the camera?
* A culled sprite has its renderable property set to 'false'.
* Be advised this is quite an expensive operation, as it has to calculate the bounds of the object every frame, so only enable it if you really need it.
*
* @property {boolean} autoCull - A flag indicating if the Image should be automatically camera culled or not.
* @default
*/
this.autoCull = false;
/**
* @property {Phaser.InputHandler|null} input - The Input Handler for this object. Needs to be enabled with image.inputEnabled = true before you can use it.
*/
this.input = null;
/**
* @property {Phaser.Point} cameraOffset - If this object is fixedToCamera then this stores the x/y offset that its drawn at, from the top-left of the camera view.
*/
this.cameraOffset = new Phaser.Point();
/**
* A small internal cache:
* 0 = previous position.x
* 1 = previous position.y
* 2 = previous rotation
* 3 = renderID
* 4 = fresh? (0 = no, 1 = yes)
* 5 = outOfBoundsFired (0 = no, 1 = yes)
* 6 = exists (0 = no, 1 = yes)
* 7 = fixed to camera (0 = no, 1 = yes)
* @property {Int16Array} _cache
* @private
*/
this._cache = new Int16Array([0, 0, 0, 0, 1, 0, 1, 0]);
};
Phaser.Image.prototype = Object.create(PIXI.Sprite.prototype);
Phaser.Image.prototype.constructor = Phaser.Image;
/**
* Automatically called by World.preUpdate.
*
* @method Phaser.Image#preUpdate
* @memberof Phaser.Image
*/
Phaser.Image.prototype.preUpdate = function() {
this._cache[0] = this.world.x;
this._cache[1] = this.world.y;
this._cache[2] = this.rotation;
if (!this.exists || !this.parent.exists)
{
this._cache[3] = -1;
return false;
}
if (this.autoCull)
{
// Won't get rendered but will still get its transform updated
this.renderable = this.game.world.camera.screenView.intersects(this.getBounds());
}
this.world.setTo(this.game.camera.x + this.worldTransform[2], this.game.camera.y + this.worldTransform[5]);
if (this.visible)
{
this._cache[3] = this.game.stage.currentRenderOrderID++;
}
// Update any Children
for (var i = 0, len = this.children.length; i < len; i++)
{
this.children[i].preUpdate();
}
return true;
}
/**
* Override and use this function in your own custom objects to handle any update requirements you may have.
*
* @method Phaser.Image#update
* @memberof Phaser.Image
*/
Phaser.Image.prototype.update = function() {
}
/**
* Internal function called by the World postUpdate cycle.
*
* @method Phaser.Image#postUpdate
* @memberof Phaser.Image
*/
Phaser.Image.prototype.postUpdate = function() {
if (this.key instanceof Phaser.BitmapData && this.key._dirty)
{
this.key.render();
}
// Fixed to Camera?
if (this._cache[7] === 1)
{
this.position.x = (this.game.camera.view.x + this.cameraOffset.x) / this.game.camera.scale.x;
this.position.y = (this.game.camera.view.y + this.cameraOffset.y) / this.game.camera.scale.y;
}
// Update any Children
for (var i = 0, len = this.children.length; i < len; i++)
{
this.children[i].postUpdate();
}
}
/**
* Changes the Texture the Image is using entirely. The old texture is removed and the new one is referenced or fetched from the Cache.
* This causes a WebGL texture update, so use sparingly or in low-intensity portions of your game.
*
* @method Phaser.Image#loadTexture
* @memberof Phaser.Image
* @param {string|Phaser.RenderTexture|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the Image during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture, BitmapData or PIXI.Texture.
* @param {string|number} frame - If this Image is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index.
*/
Phaser.Image.prototype.loadTexture = function (key, frame) {
frame = frame || 0;
if (key instanceof Phaser.RenderTexture)
{
this.key = key.key;
this.setTexture(key);
return;
}
else if (key instanceof Phaser.BitmapData)
{
this.key = key.key;
this.setTexture(key.texture);
return;
}
else if (key instanceof PIXI.Texture)
{
this.key = key;
this.setTexture(key);
return;
}
else
{
if (key === null || typeof key === 'undefined')
{
this.key = '__default';
this.setTexture(PIXI.TextureCache[this.key]);
return;
}
else if (typeof key === 'string' && !this.game.cache.checkImageKey(key))
{
this.key = '__missing';
this.setTexture(PIXI.TextureCache[this.key]);
return;
}
if (this.game.cache.isSpriteSheet(key))
{
this.key = key;
var frameData = this.game.cache.getFrameData(key);
if (typeof frame === 'string')
{
this._frame = 0;
this._frameName = frame;
this.setTexture(PIXI.TextureCache[frameData.getFrameByName(frame).uuid]);
return;
}
else
{
this._frame = frame;
this._frameName = '';
this.setTexture(PIXI.TextureCache[frameData.getFrame(frame).uuid]);
return;
}
}
else
{
this.key = key;
this.setTexture(PIXI.TextureCache[key]);
return;
}
}
}
/**
* Crop allows you to crop the texture used to display this Image.
* Cropping takes place from the top-left of the Image and can be modified in real-time by providing an updated rectangle object.
*
* @method Phaser.Image#crop
* @memberof Phaser.Image
* @param {Phaser.Rectangle} rect - The Rectangle to crop the Image to. Pass null or no parameters to clear a previously set crop rectangle.
*/
Phaser.Image.prototype.crop = function(rect) {
if (typeof rect === 'undefined' || rect === null)
{
// Clear any crop that may be set
if (this.texture.hasOwnProperty('sourceWidth'))
{
this.texture.setFrame(new Phaser.Rectangle(0, 0, this.texture.sourceWidth, this.texture.sourceHeight));
}
}
else
{
// Do we need to clone the PIXI.Texture object?
if (this.texture instanceof PIXI.Texture)
{
// Yup, let's rock it ...
var local = {};
Phaser.Utils.extend(true, local, this.texture);
local.sourceWidth = local.width;
local.sourceHeight = local.height;
local.frame = rect;
local.width = rect.width;
local.height = rect.height;
this.texture = local;
this.texture.updateFrame = true;
PIXI.Texture.frameUpdates.push(this.texture);
}
else
{
this.texture.setFrame(rect);
}
}
}
/**
* Brings a 'dead' Image back to life, optionally giving it the health value specified.
* A resurrected Image has its alive, exists and visible properties all set to true.
* It will dispatch the onRevived event, you can listen to Image.events.onRevived for the signal.
*
* @method Phaser.Image#revive
* @memberof Phaser.Image
* @return {Phaser.Image} This instance.
*/
Phaser.Image.prototype.revive = function() {
this.alive = true;
this.exists = true;
this.visible = true;
if (this.events)
{
this.events.onRevived.dispatch(this);
}
return this;
}
/**
* Kills a Image. A killed Image has its alive, exists and visible properties all set to false.
* It will dispatch the onKilled event, you can listen to Image.events.onKilled for the signal.
* Note that killing a Image is a way for you to quickly recycle it in a Image pool, it doesn't free it up from memory.
* If you don't need this Image any more you should call Image.destroy instead.
*
* @method Phaser.Image#kill
* @memberof Phaser.Image
* @return {Phaser.Image} This instance.
*/
Phaser.Image.prototype.kill = function() {
this.alive = false;
this.exists = false;
this.visible = false;
if (this.events)
{
this.events.onKilled.dispatch(this);
}
return this;
}
/**
* Destroys the Image. This removes it from its parent group, destroys the input, event and animation handlers if present
* and nulls its reference to game, freeing it up for garbage collection.
*
* @method Phaser.Image#destroy
* @memberof Phaser.Image
* @param {boolean} [destroyChildren=true] - Should every child of this object have its destroy method called?
*/
Phaser.Image.prototype.destroy = function(destroyChildren) {
if (this.game === null) { return; }
if (typeof destroyChildren === 'undefined') { destroyChildren = true; }
if (this.parent)
{
if (this.parent instanceof Phaser.Group)
{
this.parent.remove(this);
}
else
{
this.parent.removeChild(this);
}
}
if (this.events)
{
this.events.destroy();
}
if (this.input)
{
this.input.destroy();
}
var i = this.children.length;
if (destroyChildren)
{
while (i--)
{
this.children[i].destroy(destroyChildren);
}
}
else
{
while (i--)
{
this.removeChild(this.children[i]);
}
}
this.alive = false;
this.exists = false;
this.visible = false;
this.filters = null;
this.mask = null;
this.game = null;
}
/**
* Resets the Image. This places the Image at the given x/y world coordinates and then sets alive, exists, visible and renderable all to true.
*
* @method Phaser.Image#reset
* @memberof Phaser.Image
* @param {number} x - The x coordinate (in world space) to position the Image at.
* @param {number} y - The y coordinate (in world space) to position the Image at.
* @return {Phaser.Image} This instance.
*/
Phaser.Image.prototype.reset = function(x, y) {
this.world.setTo(x, y);
this.position.x = x;
this.position.y = y;
this.alive = true;
this.exists = true;
this.visible = true;
this.renderable = true;
return this;
}
/**
* Brings the Image to the top of the display list it is a child of. Images that are members of a Phaser.Group are only
* bought to the top of that Group, not the entire display list.
*
* @method Phaser.Image#bringToTop
* @memberof Phaser.Image
* @return {Phaser.Image} This instance.
*/
Phaser.Image.prototype.bringToTop = function() {
if (this.parent)
{
this.parent.bringToTop(this);
}
return this;
}
/**
* Indicates the rotation of the Image, in degrees, from its original orientation. Values from 0 to 180 represent clockwise rotation; values from 0 to -180 represent counterclockwise rotation.
* Values outside this range are added to or subtracted from 360 to obtain a value within the range. For example, the statement player.angle = 450 is the same as player.angle = 90.
* If you wish to work in radians instead of degrees use the property Image.rotation instead. Working in radians is also a little faster as it doesn't have to convert the angle.
*
* @name Phaser.Image#angle
* @property {number} angle - The angle of this Image in degrees.
*/
Object.defineProperty(Phaser.Image.prototype, "angle", {
get: function() {
return Phaser.Math.wrapAngle(Phaser.Math.radToDeg(this.rotation));
},
set: function(value) {
this.rotation = Phaser.Math.degToRad(Phaser.Math.wrapAngle(value));
}
});
/**
* Returns the delta x value. The difference between world.x now and in the previous step.
*
* @name Phaser.Image#deltaX
* @property {number} deltaX - The delta value. Positive if the motion was to the right, negative if to the left.
* @readonly
*/
Object.defineProperty(Phaser.Image.prototype, "deltaX", {
get: function() {
return this.world.x - this._cache[0];
}
});
/**
* Returns the delta y value. The difference between world.y now and in the previous step.
*
* @name Phaser.Image#deltaY
* @property {number} deltaY - The delta value. Positive if the motion was downwards, negative if upwards.
* @readonly
*/
Object.defineProperty(Phaser.Image.prototype, "deltaY", {
get: function() {
return this.world.y - this._cache[1];
}
});
/**
* Returns the delta z value. The difference between rotation now and in the previous step.
*
* @name Phaser.Image#deltaZ
* @property {number} deltaZ - The delta value.
* @readonly
*/
Object.defineProperty(Phaser.Image.prototype, "deltaZ", {
get: function() {
return this.rotation - this._cache[2];
}
});
/**
* Checks if the Image bounds are within the game world, otherwise false if fully outside of it.
*
* @name Phaser.Image#inWorld
* @property {boolean} inWorld - True if the Image bounds is within the game world, even if only partially. Otherwise false if fully outside of it.
* @readonly
*/
Object.defineProperty(Phaser.Image.prototype, "inWorld", {
get: function() {
return this.game.world.bounds.intersects(this.getBounds());
}
});
/**
* Checks if the Image bounds are within the game camera, otherwise false if fully outside of it.
*
* @name Phaser.Image#inCamera
* @property {boolean} inCamera - True if the Image bounds is within the game camera, even if only partially. Otherwise false if fully outside of it.
* @readonly
*/
Object.defineProperty(Phaser.Image.prototype, "inCamera", {
get: function() {
return this.game.world.camera.screenView.intersects(this.getBounds());
}
});
/**
* @name Phaser.Image#frame
* @property {number} frame - Gets or sets the current frame index and updates the Texture for display.
*/
Object.defineProperty(Phaser.Image.prototype, "frame", {
get: function() {
return this._frame;
},
set: function(value) {
if (value !== this.frame && this.game.cache.isSpriteSheet(this.key))
{
var frameData = this.game.cache.getFrameData(this.key);
if (frameData && value < frameData.total && frameData.getFrame(value))
{
this.setTexture(PIXI.TextureCache[frameData.getFrame(value).uuid]);
this._frame = value;
}
}
}
});
/**
* @name Phaser.Image#frameName
* @property {string} frameName - Gets or sets the current frame by name and updates the Texture for display.
*/
Object.defineProperty(Phaser.Image.prototype, "frameName", {
get: function() {
return this._frameName;
},
set: function(value) {
if (value !== this.frameName && this.game.cache.isSpriteSheet(this.key))
{
var frameData = this.game.cache.getFrameData(this.key);
if (frameData && frameData.getFrameByName(value))
{
this.setTexture(PIXI.TextureCache[frameData.getFrameByName(value).uuid]);
this._frameName = value;
}
}
}
});
/**
* @name Phaser.Image#renderOrderID
* @property {number} renderOrderID - The render order ID, reset every frame.
* @readonly
*/
Object.defineProperty(Phaser.Image.prototype, "renderOrderID", {
get: function() {
return this._cache[3];
}
});
/**
* By default an Image won't process any input events at all. By setting inputEnabled to true the Phaser.InputHandler is
* activated for this object and it will then start to process click/touch events and more.
*
* @name Phaser.Image#inputEnabled
* @property {boolean} inputEnabled - Set to true to allow this object to receive input events.
*/
Object.defineProperty(Phaser.Image.prototype, "inputEnabled", {
get: function () {
return (this.input && this.input.enabled);
},
set: function (value) {
if (value)
{
if (this.input === null)
{
this.input = new Phaser.InputHandler(this);
this.input.start();
}
}
else
{
if (this.input && this.input.enabled)
{
this.input.stop();
}
}
}
});
/**
* An Image that is fixed to the camera uses its x/y coordinates as offsets from the top left of the camera. These are stored in Image.cameraOffset.
* Note that the cameraOffset values are in addition to any parent in the display list.
* So if this Image was in a Group that has x: 200, then this will be added to the cameraOffset.x
*
* @name Phaser.Image#fixedToCamera
* @property {boolean} fixedToCamera - Set to true to fix this Image to the Camera at its current world coordinates.
*/
Object.defineProperty(Phaser.Image.prototype, "fixedToCamera", {
get: function () {
return !!this._cache[7];
},
set: function (value) {
if (value)
{
this._cache[7] = 1;
this.cameraOffset.set(this.x, this.y);
}
else
{
this._cache[7] = 0;
}
}
});
/**
* Enable or disable texture smoothing for this Image. Only works for bitmap/image textures. Smoothing is enabled by default.
*
* @name Phaser.Image#smoothed
* @property {boolean} smoothed - Set to true to smooth the texture of this Image, or false to disable smoothing (great for pixel art)
*/
Object.defineProperty(Phaser.Image.prototype, "smoothed", {
get: function () {
return !this.texture.baseTexture.scaleMode;
},
set: function (value) {
if (value)
{
if (this.texture)
{
this.texture.baseTexture.scaleMode = 0;
}
}
else
{
if (this.texture)
{
this.texture.baseTexture.scaleMode = 1;
}
}
}
});
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2014 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* A TileSprite is a Sprite that has a repeating texture. The texture can be scrolled and scaled and will automatically wrap on the edges as it does so.
* Please note that TileSprites have no input handler or physics bodies.
*
* @class Phaser.TileSprite
* @constructor
* @param {Phaser.Game} game - A reference to the currently running game.
* @param {number} x - The x coordinate (in world space) to position the TileSprite at.
* @param {number} y - The y coordinate (in world space) to position the TileSprite at.
* @param {number} width - The width of the TileSprite.
* @param {number} height - The height of the TileSprite.
* @param {string|Phaser.RenderTexture|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the TileSprite during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture.
* @param {string|number} frame - If this TileSprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index.
*/
Phaser.TileSprite = function (game, x, y, width, height, key, frame) {
x = x || 0;
y = y || 0;
width = width || 256;
height = height || 256;
key = key || null;
frame = frame || null;
/**
* @property {Phaser.Game} game - A reference to the currently running Game.
*/
this.game = game;
/**
* @property {string} name - The user defined name given to this Sprite.
* @default
*/
this.name = '';
/**
* @property {number} type - The const type of this object.
* @readonly
*/
this.type = Phaser.TILESPRITE;
/**
* @property {Phaser.Events} events - The Events you can subscribe to that are dispatched when certain things happen on this Sprite or its components.
*/
this.events = new Phaser.Events(this);
/**
* @property {Phaser.AnimationManager} animations - This manages animations of the sprite. You can modify animations through it (see Phaser.AnimationManager)
*/
this.animations = new Phaser.AnimationManager(this);
/**
* @property {string|Phaser.RenderTexture|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture, BitmapData or PIXI.Texture.
*/
this.key = key;
/**
* @property {number} _frame - Internal cache var.
* @private
*/
this._frame = 0;
/**
* @property {string} _frameName - Internal cache var.
* @private
*/
this._frameName = '';
/**
* @property {Phaser.Point} _scroll - Internal cache var.
* @private
*/
this._scroll = new Phaser.Point();
PIXI.TilingSprite.call(this, PIXI.TextureCache['__default'], width, height);
this.loadTexture(key, frame);
this.position.set(x, y);
/**
* @property {Phaser.InputHandler|null} input - The Input Handler for this object. Needs to be enabled with image.inputEnabled = true before you can use it.
*/
this.input = null;
/**
* @property {Phaser.Point} world - The world coordinates of this Sprite. This differs from the x/y coordinates which are relative to the Sprites container.
*/
this.world = new Phaser.Point(x, y);
/**
* @property {Phaser.Point} cameraOffset - If this object is fixedToCamera then this stores the x/y offset that its drawn at, from the top-left of the camera view.
*/
this.cameraOffset = new Phaser.Point();
/**
* By default Sprites won't add themselves to any physics system and their physics body will be `null`.
* To enable them for physics you need to call `game.physics.enable(sprite, system)` where `sprite` is this object
* and `system` is the Physics system you want to use to manage this body. Once enabled you can access all physics related properties via `Sprite.body`.
*
* Important: Enabling a Sprite for P2 or Ninja physics will automatically set `Sprite.anchor` to 0.5 so the physics body is centered on the Sprite.
* If you need a different result then adjust or re-create the Body shape offsets manually, and/or reset the anchor after enabling physics.
*
* @property {Phaser.Physics.Arcade.Body|Phaser.Physics.P2.Body|Phaser.Physics.Ninja.Body|null} body
* @default
*/
this.body = null;
/**
* A small internal cache:
* 0 = previous position.x
* 1 = previous position.y
* 2 = previous rotation
* 3 = renderID
* 4 = fresh? (0 = no, 1 = yes)
* 5 = outOfBoundsFired (0 = no, 1 = yes)
* 6 = exists (0 = no, 1 = yes)
* 7 = fixed to camera (0 = no, 1 = yes)
* @property {Int16Array} _cache
* @private
*/
this._cache = new Int16Array([0, 0, 0, 0, 1, 0, 1, 0]);
};
Phaser.TileSprite.prototype = Object.create(PIXI.TilingSprite.prototype);
Phaser.TileSprite.prototype.constructor = Phaser.TileSprite;
/**
* Automatically called by World.preUpdate.
*
* @method Phaser.TileSprite#preUpdate
* @memberof Phaser.TileSprite
*/
Phaser.TileSprite.prototype.preUpdate = function() {
this.world.setTo(this.game.camera.x + this.worldTransform[2], this.game.camera.y + this.worldTransform[5]);
this.animations.update();
if (this._scroll.x !== 0)
{
this.tilePosition.x += this._scroll.x * this.game.time.physicsElapsed;
}
if (this._scroll.y !== 0)
{
this.tilePosition.y += this._scroll.y * this.game.time.physicsElapsed;
}
if (this.visible)
{
this._cache[3] = this.game.stage.currentRenderOrderID++;
}
if (this.exists && this.body)
{
this.body.preUpdate();
}
// Update any Children
for (var i = 0, len = this.children.length; i < len; i++)
{
this.children[i].preUpdate();
}
return true;
}
/**
* Override and use this function in your own custom objects to handle any update requirements you may have.
*
* @method Phaser.TileSprite#update
* @memberof Phaser.TileSprite
*/
Phaser.TileSprite.prototype.update = function() {
}
/**
* Internal function called by the World postUpdate cycle.
*
* @method Phaser.TileSprite#postUpdate
* @memberof Phaser.TileSprite
*/
Phaser.TileSprite.prototype.postUpdate = function() {
if (this.exists && this.body)
{
this.body.postUpdate();
}
// Fixed to Camera?
if (this._cache[7] === 1)
{
this.position.x = this.game.camera.view.x + this.cameraOffset.x;
this.position.y = this.game.camera.view.y + this.cameraOffset.y;
}
// Update any Children
for (var i = 0, len = this.children.length; i < len; i++)
{
this.children[i].postUpdate();
}
}
/**
* Sets this TileSprite to automatically scroll in the given direction until stopped via TileSprite.stopScroll().
* The scroll speed is specified in pixels per second.
* A negative x value will scroll to the left. A positive x value will scroll to the right.
* A negative y value will scroll up. A positive y value will scroll down.
*
* @method Phaser.TileSprite#autoScroll
* @memberof Phaser.TileSprite
*/
Phaser.TileSprite.prototype.autoScroll = function(x, y) {
this._scroll.set(x, y);
}
/**
* Stops an automatically scrolling TileSprite.
*
* @method Phaser.TileSprite#stopScroll
* @memberof Phaser.TileSprite
*/
Phaser.TileSprite.prototype.stopScroll = function() {
this._scroll.set(0, 0);
}
/**
* Changes the Texture the TileSprite is using entirely. The old texture is removed and the new one is referenced or fetched from the Cache.
* This causes a WebGL texture update, so use sparingly or in low-intensity portions of your game.
*
* @method Phaser.TileSprite#loadTexture
* @memberof Phaser.TileSprite
* @param {string|Phaser.RenderTexture|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture, BitmapData or PIXI.Texture.
* @param {string|number} frame - If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index.
*/
Phaser.TileSprite.prototype.loadTexture = function (key, frame) {
frame = frame || 0;
if (key instanceof Phaser.RenderTexture)
{
this.key = key.key;
this.setTexture(key);
return;
}
else if (key instanceof Phaser.BitmapData)
{
this.key = key.key;
this.setTexture(key.texture);
return;
}
else if (key instanceof PIXI.Texture)
{
this.key = key;
this.setTexture(key);
return;
}
else
{
if (key === null || typeof key === 'undefined')
{
this.key = '__default';
this.setTexture(PIXI.TextureCache[this.key]);
return;
}
else if (typeof key === 'string' && !this.game.cache.checkImageKey(key))
{
this.key = '__missing';
this.setTexture(PIXI.TextureCache[this.key]);
return;
}
if (this.game.cache.isSpriteSheet(key))
{
this.key = key;
// var frameData = this.game.cache.getFrameData(key);
this.animations.loadFrameData(this.game.cache.getFrameData(key));
if (typeof frame === 'string')
{
this.frameName = frame;
}
else
{
this.frame = frame;
}
}
else
{
this.key = key;
this.setTexture(PIXI.TextureCache[key]);
return;
}
}
}
/**
* Destroys the TileSprite. This removes it from its parent group, destroys the event and animation handlers if present
* and nulls its reference to game, freeing it up for garbage collection.
*
* @method Phaser.TileSprite#destroy
* @memberof Phaser.TileSprite
* @param {boolean} [destroyChildren=true] - Should every child of this object have its destroy method called?
*/
Phaser.TileSprite.prototype.destroy = function(destroyChildren) {
if (this.game === null) { return; }
if (typeof destroyChildren === 'undefined') { destroyChildren = true; }
if (this.filters)
{
this.filters = null;
}
if (this.parent)
{
if (this.parent instanceof Phaser.Group)
{
this.parent.remove(this);
}
else
{
this.parent.removeChild(this);
}
}
this.animations.destroy();
this.events.destroy();
var i = this.children.length;
if (destroyChildren)
{
while (i--)
{
this.children[i].destroy(destroyChildren);
}
}
else
{
while (i--)
{
this.removeChild(this.children[i]);
}
}
this.exists = false;
this.visible = false;
this.filters = null;
this.mask = null;
this.game = null;
}
/**
* Play an animation based on the given key. The animation should previously have been added via sprite.animations.add()
* If the requested animation is already playing this request will be ignored. If you need to reset an already running animation do so directly on the Animation object itself.
*
* @method Phaser.TileSprite#play
* @memberof Phaser.TileSprite
* @param {string} name - The name of the animation to be played, e.g. "fire", "walk", "jump".
* @param {number} [frameRate=null] - The framerate to play the animation at. The speed is given in frames per second. If not provided the previously set frameRate of the Animation is used.
* @param {boolean} [loop=false] - Should the animation be looped after playback. If not provided the previously set loop value of the Animation is used.
* @param {boolean} [killOnComplete=false] - If set to true when the animation completes (only happens if loop=false) the parent Sprite will be killed.
* @return {Phaser.Animation} A reference to playing Animation instance.
*/
Phaser.TileSprite.prototype.play = function (name, frameRate, loop, killOnComplete) {
return this.animations.play(name, frameRate, loop, killOnComplete);
}
/**
* Indicates the rotation of the Sprite, in degrees, from its original orientation. Values from 0 to 180 represent clockwise rotation; values from 0 to -180 represent counterclockwise rotation.
* Values outside this range are added to or subtracted from 360 to obtain a value within the range. For example, the statement player.angle = 450 is the same as player.angle = 90.
* If you wish to work in radians instead of degrees use the property Sprite.rotation instead. Working in radians is also a little faster as it doesn't have to convert the angle.
*
* @name Phaser.TileSprite#angle
* @property {number} angle - The angle of this Sprite in degrees.
*/
Object.defineProperty(Phaser.TileSprite.prototype, "angle", {
get: function() {
return Phaser.Math.wrapAngle(Phaser.Math.radToDeg(this.rotation));
},
set: function(value) {
this.rotation = Phaser.Math.degToRad(Phaser.Math.wrapAngle(value));
}
});
/**
* @name Phaser.TileSprite#frame
* @property {number} frame - Gets or sets the current frame index and updates the Texture Cache for display.
*/
Object.defineProperty(Phaser.TileSprite.prototype, "frame", {
get: function () {
return this.animations.frame;
},
set: function (value) {
if (value !== this.animations.frame)
{
this.animations.frame = value;
}
}
});
/**
* @name Phaser.TileSprite#frameName
* @property {string} frameName - Gets or sets the current frame name and updates the Texture Cache for display.
*/
Object.defineProperty(Phaser.TileSprite.prototype, "frameName", {
get: function () {
return this.animations.frameName;
},
set: function (value) {
if (value !== this.animations.frameName)
{
this.animations.frameName = value;
}
}
});
/**
* An TileSprite that is fixed to the camera uses its x/y coordinates as offsets from the top left of the camera. These are stored in TileSprite.cameraOffset.
* Note that the cameraOffset values are in addition to any parent in the display list.
* So if this TileSprite was in a Group that has x: 200, then this will be added to the cameraOffset.x
*
* @name Phaser.TileSprite#fixedToCamera
* @property {boolean} fixedToCamera - Set to true to fix this TileSprite to the Camera at its current world coordinates.
*/
Object.defineProperty(Phaser.TileSprite.prototype, "fixedToCamera", {
get: function () {
return !!this._cache[7];
},
set: function (value) {
if (value)
{
this._cache[7] = 1;
this.cameraOffset.set(this.x, this.y);
}
else
{
this._cache[7] = 0;
}
}
});
/**
* TileSprite.exists controls if the core game loop and physics update this TileSprite or not.
* When you set TileSprite.exists to false it will remove its Body from the physics world (if it has one) and also set TileSprite.visible to false.
* Setting TileSprite.exists to true will re-add the Body to the physics world (if it has a body) and set TileSprite.visible to true.
*
* @name Phaser.TileSprite#exists
* @property {boolean} exists - If the TileSprite is processed by the core game update and physics.
*/
Object.defineProperty(Phaser.TileSprite.prototype, "exists", {
get: function () {
return !!this._cache[6];
},
set: function (value) {
if (value)
{
// exists = true
this._cache[6] = 1;
if (this.body && this.body.type === Phaser.Physics.P2)
{
this.body.addToWorld();
}
this.visible = true;
}
else
{
// exists = false
this._cache[6] = 0;
if (this.body && this.body.type === Phaser.Physics.P2)
{
this.body.removeFromWorld();
}
this.visible = false;
}
}
});
/**
* By default a TileSprite won't process any input events at all. By setting inputEnabled to true the Phaser.InputHandler is
* activated for this object and it will then start to process click/touch events and more.
*
* @name Phaser.TileSprite#inputEnabled
* @property {boolean} inputEnabled - Set to true to allow this object to receive input events.
*/
Object.defineProperty(Phaser.TileSprite.prototype, "inputEnabled", {
get: function () {
return (this.input && this.input.enabled);
},
set: function (value) {
if (value)
{
if (this.input === null)
{
this.input = new Phaser.InputHandler(this);
this.input.start();
}
}
else
{
if (this.input && this.input.enabled)
{
this.input.stop();
}
}
}
});
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2014 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* Create a new `Text` object. This uses a local hidden Canvas object and renders the type into it. It then makes a texture from this for renderning to the view.
* Because of this you can only display fonts that are currently loaded and available to the browser. It won't load the fonts for you.
* Here is a compatibility table showing the available default fonts across different mobile browsers: http://www.jordanm.co.uk/tinytype
*
* @class Phaser.Text
* @extends PIXI.Text
* @constructor
* @param {Phaser.Game} game - Current game instance.
* @param {number} x - X position of the new text object.
* @param {number} y - Y position of the new text object.
* @param {string} text - The actual text that will be written.
* @param {object} style - The style object containing style attributes like font, font size ,
*/
Phaser.Text = function (game, x, y, text, style) {
x = x || 0;
y = y || 0;
text = text || '';
style = style || '';
/**
* @property {Phaser.Game} game - A reference to the currently running Game.
*/
this.game = game;
/**
* @property {boolean} exists - If exists = false then the Text isn't updated by the core game loop.
* @default
*/
this.exists = true;
/**
* @property {string} name - The user defined name given to this object.
* @default
*/
this.name = '';
/**
* @property {number} type - The const type of this object.
* @default
*/
this.type = Phaser.TEXT;
/**
* @property {Phaser.Point} world - The world coordinates of this Sprite. This differs from the x/y coordinates which are relative to the Sprites container.
*/
this.world = new Phaser.Point(x, y);
/**
* @property {string} _text - Internal cache var.
* @private
*/
this._text = text;
/**
* @property {string} _font - Internal cache var.
* @private
*/
this._font = '';
/**
* @property {number} _fontSize - Internal cache var.
* @private
*/
this._fontSize = 32;
/**
* @property {string} _fontWeight - Internal cache var.
* @private
*/
this._fontWeight = 'normal';
/**
* @property {number} lineSpacing - Additional spacing (in pixels) between each line of text if multi-line.
* @private
*/
this._lineSpacing = 0;
/**
* @property {Phaser.Events} events - The Events you can subscribe to that are dispatched when certain things happen on this Sprite or its components.
*/
this.events = new Phaser.Events(this);
/**
* @property {Phaser.InputHandler|null} input - The Input Handler for this object. Needs to be enabled with image.inputEnabled = true before you can use it.
*/
this.input = null;
/**
* @property {Phaser.Point} cameraOffset - If this object is fixedToCamera then this stores the x/y offset that its drawn at, from the top-left of the camera view.
*/
this.cameraOffset = new Phaser.Point();
PIXI.Text.call(this, text, style);
this.position.set(x, y);
/**
* A small internal cache:
* 0 = previous position.x
* 1 = previous position.y
* 2 = previous rotation
* 3 = renderID
* 4 = fresh? (0 = no, 1 = yes)
* 5 = outOfBoundsFired (0 = no, 1 = yes)
* 6 = exists (0 = no, 1 = yes)
* 7 = fixed to camera (0 = no, 1 = yes)
* @property {Int16Array} _cache
* @private
*/
this._cache = new Int16Array([0, 0, 0, 0, 1, 0, 1, 0]);
};
Phaser.Text.prototype = Object.create(PIXI.Text.prototype);
Phaser.Text.prototype.constructor = Phaser.Text;
/**
* Automatically called by World.preUpdate.
* @method Phaser.Text.prototype.preUpdate
*/
Phaser.Text.prototype.preUpdate = function () {
this._cache[0] = this.world.x;
this._cache[1] = this.world.y;
this._cache[2] = this.rotation;
if (!this.exists || !this.parent.exists)
{
this.renderOrderID = -1;
return false;
}
if (this.autoCull)
{
// Won't get rendered but will still get its transform updated
this.renderable = this.game.world.camera.screenView.intersects(this.getBounds());
}
this.world.setTo(this.game.camera.x + this.worldTransform[2], this.game.camera.y + this.worldTransform[5]);
if (this.visible)
{
this._cache[3] = this.game.stage.currentRenderOrderID++;
}
// Update any Children
for (var i = 0, len = this.children.length; i < len; i++)
{
this.children[i].preUpdate();
}
return true;
}
/**
* Override and use this function in your own custom objects to handle any update requirements you may have.
*
* @method Phaser.Text#update
* @memberof Phaser.Text
*/
Phaser.Text.prototype.update = function() {
}
/**
* Automatically called by World.postUpdate.
* @method Phaser.Text.prototype.postUpdate
*/
Phaser.Text.prototype.postUpdate = function () {
if (this._cache[7] === 1)
{
this.position.x = (this.game.camera.view.x + this.cameraOffset.x) / this.game.camera.scale.x;
this.position.y = (this.game.camera.view.y + this.cameraOffset.y) / this.game.camera.scale.y;
}
// Update any Children
for (var i = 0, len = this.children.length; i < len; i++)
{
this.children[i].postUpdate();
}
}
/**
* @method Phaser.Text.prototype.destroy
* @param {boolean} [destroyChildren=true] - Should every child of this object have its destroy method called?
*/
Phaser.Text.prototype.destroy = function (destroyChildren) {
if (this.game === null) { return; }
if (typeof destroyChildren === 'undefined') { destroyChildren = true; }
if (this.parent)
{
if (this.parent instanceof Phaser.Group)
{
this.parent.remove(this);
}
else
{
this.parent.removeChild(this);
}
}
this.texture.destroy();
if (this.canvas.parentNode)
{
this.canvas.parentNode.removeChild(this.canvas);
}
else
{
this.canvas = null;
this.context = null;
}
var i = this.children.length;
if (destroyChildren)
{
while (i--)
{
this.children[i].destroy(destroyChildren);
}
}
else
{
while (i--)
{
this.removeChild(this.children[i]);
}
}
this.exists = false;
this.visible = false;
this.filters = null;
this.mask = null;
this.game = null;
}
/**
* @method Phaser.Text.prototype.setShadow
* @param {number} [x=0] - The shadowOffsetX value in pixels. This is how far offset horizontally the shadow effect will be.
* @param {number} [y=0] - The shadowOffsetY value in pixels. This is how far offset vertically the shadow effect will be.
* @param {string} [color='rgba(0,0,0,0)'] - The color of the shadow, as given in CSS rgba format. Set the alpha component to 0 to disable the shadow.
* @param {number} [blur=0] - The shadowBlur value. Make the shadow softer by applying a Gaussian blur to it. A number from 0 (no blur) up to approx. 10 (depending on scene).
*/
Phaser.Text.prototype.setShadow = function (x, y, color, blur) {
this.style.shadowOffsetX = x || 0;
this.style.shadowOffsetY = y || 0;
this.style.shadowColor = color || 'rgba(0,0,0,0)';
this.style.shadowBlur = blur || 0;
this.dirty = true;
}
/**
* Set the style of the text by passing a single style object to it.
*
* @method Phaser.Text.prototype.setStyle
* @param [style] {Object} The style parameters
* @param [style.font='bold 20pt Arial'] {String} The style and size of the font
* @param [style.fill='black'] {Object} A canvas fillstyle that will be used on the text eg 'red', '#00FF00'
* @param [style.align='left'] {String} Alignment for multiline text ('left', 'center' or 'right'), does not affect single line text
* @param [style.stroke='black'] {String} A canvas fillstyle that will be used on the text stroke eg 'blue', '#FCFF00'
* @param [style.strokeThickness=0] {Number} A number that represents the thickness of the stroke. Default is 0 (no stroke)
* @param [style.wordWrap=false] {Boolean} Indicates if word wrap should be used
* @param [style.wordWrapWidth=100] {Number} The width at which text will wrap
*/
Phaser.Text.prototype.setStyle = function (style) {
style = style || {};
style.font = style.font || 'bold 20pt Arial';
style.fill = style.fill || 'black';
style.align = style.align || 'left';
style.stroke = style.stroke || 'black'; //provide a default, see: https://github.com/GoodBoyDigital/pixi.js/issues/136
style.strokeThickness = style.strokeThickness || 0;
style.wordWrap = style.wordWrap || false;
style.wordWrapWidth = style.wordWrapWidth || 100;
style.shadowOffsetX = style.shadowOffsetX || 0;
style.shadowOffsetY = style.shadowOffsetY || 0;
style.shadowColor = style.shadowColor || 'rgba(0,0,0,0)';
style.shadowBlur = style.shadowBlur || 0;
this.style = style;
this.dirty = true;
}
/**
* Renders text. This replaces the Pixi.Text.updateText function as we need a few extra bits in here.
*
* @method Phaser.Text.prototype.updateText
* @private
*/
Phaser.Text.prototype.updateText = function () {
this.context.font = this.style.font;
var outputText = this.text;
// word wrap
// preserve original text
if(this.style.wordWrap)outputText = this.runWordWrap(this.text);
//split text into lines
var lines = outputText.split(/(?:\r\n|\r|\n)/);
//calculate text width
var lineWidths = [];
var maxLineWidth = 0;
for (var i = 0; i < lines.length; i++)
{
var lineWidth = this.context.measureText(lines[i]).width;
lineWidths[i] = lineWidth;
maxLineWidth = Math.max(maxLineWidth, lineWidth);
}
this.canvas.width = maxLineWidth + this.style.strokeThickness;
//calculate text height
var lineHeight = this.determineFontHeight('font: ' + this.style.font + ';') + this.style.strokeThickness + this._lineSpacing + this.style.shadowOffsetY;
this.canvas.height = lineHeight * lines.length;
if(navigator.isCocoonJS) this.context.clearRect(0,0,this.canvas.width,this.canvas.height);
//set canvas text styles
this.context.fillStyle = this.style.fill;
this.context.font = this.style.font;
this.context.strokeStyle = this.style.stroke;
this.context.lineWidth = this.style.strokeThickness;
this.context.shadowOffsetX = this.style.shadowOffsetX;
this.context.shadowOffsetY = this.style.shadowOffsetY;
this.context.shadowColor = this.style.shadowColor;
this.context.shadowBlur = this.style.shadowBlur;
this.context.textBaseline = 'top';
//draw lines line by line
for (i = 0; i < lines.length; i++)
{
var linePosition = new PIXI.Point(this.style.strokeThickness / 2, this.style.strokeThickness / 2 + i * lineHeight);
if(this.style.align === 'right')
{
linePosition.x += maxLineWidth - lineWidths[i];
}
else if(this.style.align === 'center')
{
linePosition.x += (maxLineWidth - lineWidths[i]) / 2;
}
linePosition.y += this._lineSpacing;
if(this.style.stroke && this.style.strokeThickness)
{
this.context.strokeText(lines[i], linePosition.x, linePosition.y);
}
if(this.style.fill)
{
this.context.fillText(lines[i], linePosition.x, linePosition.y);
}
}
this.updateTexture();
}
/**
* Greedy wrapping algorithm that will wrap words as the line grows longer than its horizontal bounds.
*
* @method Phaser.Text.prototype.runWordWrap
* @private
*/
Phaser.Text.prototype.runWordWrap = function (text) {
var result = '';
var lines = text.split('\n');
for (var i = 0; i < lines.length; i++)
{
var spaceLeft = this.style.wordWrapWidth;
var words = lines[i].split(' ');
for (var j = 0; j < words.length; j++)
{
var wordWidth = this.context.measureText(words[j]).width;
var wordWidthWithSpace = wordWidth + this.context.measureText(' ').width;
if (wordWidthWithSpace > spaceLeft)
{
// Skip printing the newline if it's the first word of the line that is greater than the word wrap width.
if (j > 0)
{
result += '\n';
}
result += words[j] + ' ';
spaceLeft = this.style.wordWrapWidth - wordWidth;
}
else
{
spaceLeft -= wordWidthWithSpace;
result += words[j] + ' ';
}
}
if (i < lines.length-1)
{
result += '\n';
}
}
return result;
}
/**
* Indicates the rotation of the Text, in degrees, from its original orientation. Values from 0 to 180 represent clockwise rotation; values from 0 to -180 represent counterclockwise rotation.
* Values outside this range are added to or subtracted from 360 to obtain a value within the range. For example, the statement player.angle = 450 is the same as player.angle = 90.
* If you wish to work in radians instead of degrees use the property Sprite.rotation instead.
* @name Phaser.Text#angle
* @property {number} angle - Gets or sets the angle of rotation in degrees.
*/
Object.defineProperty(Phaser.Text.prototype, 'angle', {
get: function() {
return Phaser.Math.radToDeg(this.rotation);
},
set: function(value) {
this.rotation = Phaser.Math.degToRad(value);
}
});
/**
* The text string to be displayed by this Text object, taking into account the style settings.
* @name Phaser.Text#text
* @property {string} text - The text string to be displayed by this Text object, taking into account the style settings.
*/
Object.defineProperty(Phaser.Text.prototype, 'text', {
get: function() {
return this._text;
},
set: function(value) {
if (value !== this._text)
{
this._text = value.toString() || ' ';
this.dirty = true;
}
}
});
/**
* @name Phaser.Text#font
* @property {string} font - The font the text will be rendered in, i.e. 'Arial'. Must be loaded in the browser before use.
*/
Object.defineProperty(Phaser.Text.prototype, 'font', {
get: function() {
return this._font;
},
set: function(value) {
if (value !== this._font)
{
this._font = value.trim();
this.style.font = this._fontWeight + ' ' + this._fontSize + "px '" + this._font + "'";
this.dirty = true;
}
}
});
/**
* @name Phaser.Text#fontSize
* @property {number} fontSize - The size of the font in pixels.
*/
Object.defineProperty(Phaser.Text.prototype, 'fontSize', {
get: function() {
return this._fontSize;
},
set: function(value) {
value = parseInt(value);
if (value !== this._fontSize)
{
this._fontSize = value;
this.style.font = this._fontWeight + ' ' + this._fontSize + "px '" + this._font + "'";
this.dirty = true;
}
}
});
/**
* @name Phaser.Text#fontWeight
* @property {number} fontWeight - The weight of the font: 'normal', 'bold', 'italic'. You can combine settings too, such as 'bold italic'.
*/
Object.defineProperty(Phaser.Text.prototype, 'fontWeight', {
get: function() {
return this._fontWeight;
},
set: function(value) {
if (value !== this._fontWeight)
{
this._fontWeight = value;
this.style.font = this._fontWeight + ' ' + this._fontSize + "px '" + this._font + "'";
this.dirty = true;
}
}
});
/**
* @name Phaser.Text#fill
* @property {object} fill - A canvas fillstyle that will be used on the text eg 'red', '#00FF00'.
*/
Object.defineProperty(Phaser.Text.prototype, 'fill', {
get: function() {
return this.style.fill;
},
set: function(value) {
if (value !== this.style.fill)
{
this.style.fill = value;
this.dirty = true;
}
}
});
/**
* @name Phaser.Text#align
* @property {string} align - Alignment for multiline text ('left', 'center' or 'right'), does not affect single line text.
*/
Object.defineProperty(Phaser.Text.prototype, 'align', {
get: function() {
return this.style.align;
},
set: function(value) {
if (value !== this.style.align)
{
this.style.align = value;
this.dirty = true;
}
}
});
/**
* @name Phaser.Text#stroke
* @property {string} stroke - A canvas fillstyle that will be used on the text stroke eg 'blue', '#FCFF00'.
*/
Object.defineProperty(Phaser.Text.prototype, 'stroke', {
get: function() {
return this.style.stroke;
},
set: function(value) {
if (value !== this.style.stroke)
{
this.style.stroke = value;
this.dirty = true;
}
}
});
/**
* @name Phaser.Text#strokeThickness
* @property {number} strokeThickness - A number that represents the thickness of the stroke. Default is 0 (no stroke)
*/
Object.defineProperty(Phaser.Text.prototype, 'strokeThickness', {
get: function() {
return this.style.strokeThickness;
},
set: function(value) {
if (value !== this.style.strokeThickness)
{
this.style.strokeThickness = value;
this.dirty = true;
}
}
});
/**
* @name Phaser.Text#wordWrap
* @property {boolean} wordWrap - Indicates if word wrap should be used.
*/
Object.defineProperty(Phaser.Text.prototype, 'wordWrap', {
get: function() {
return this.style.wordWrap;
},
set: function(value) {
if (value !== this.style.wordWrap)
{
this.style.wordWrap = value;
this.dirty = true;
}
}
});
/**
* @name Phaser.Text#wordWrapWidth
* @property {number} wordWrapWidth - The width at which text will wrap.
*/
Object.defineProperty(Phaser.Text.prototype, 'wordWrapWidth', {
get: function() {
return this.style.wordWrapWidth;
},
set: function(value) {
if (value !== this.style.wordWrapWidth)
{
this.style.wordWrapWidth = value;
this.dirty = true;
}
}
});
/**
* @name Phaser.Text#lineSpacing
* @property {number} lineSpacing - Additional spacing (in pixels) between each line of text if multi-line.
*/
Object.defineProperty(Phaser.Text.prototype, 'lineSpacing', {
get: function() {
return this._lineSpacing;
},
set: function(value) {
if (value !== this._lineSpacing)
{
this._lineSpacing = parseFloat(value);
this.dirty = true;
}
}
});
/**
* @name Phaser.Text#shadowOffsetX
* @property {number} shadowOffsetX - The shadowOffsetX value in pixels. This is how far offset horizontally the shadow effect will be.
*/
Object.defineProperty(Phaser.Text.prototype, 'shadowOffsetX', {
get: function() {
return this.style.shadowOffsetX;
},
set: function(value) {
if (value !== this.style.shadowOffsetX)
{
this.style.shadowOffsetX = value;
this.dirty = true;
}
}
});
/**
* @name Phaser.Text#shadowOffsetY
* @property {number} shadowOffsetY - The shadowOffsetY value in pixels. This is how far offset vertically the shadow effect will be.
*/
Object.defineProperty(Phaser.Text.prototype, 'shadowOffsetY', {
get: function() {
return this.style.shadowOffsetY;
},
set: function(value) {
if (value !== this.style.shadowOffsetY)
{
this.style.shadowOffsetY = value;
this.dirty = true;
}
}
});
/**
* @name Phaser.Text#shadowColor
* @property {string} shadowColor - The color of the shadow, as given in CSS rgba format. Set the alpha component to 0 to disable the shadow.
*/
Object.defineProperty(Phaser.Text.prototype, 'shadowColor', {
get: function() {
return this.style.shadowColor;
},
set: function(value) {
if (value !== this.style.shadowColor)
{
this.style.shadowColor = value;
this.dirty = true;
}
}
});
/**
* @name Phaser.Text#shadowBlur
* @property {number} shadowBlur - The shadowBlur value. Make the shadow softer by applying a Gaussian blur to it. A number from 0 (no blur) up to approx. 10 (depending on scene).
*/
Object.defineProperty(Phaser.Text.prototype, 'shadowBlur', {
get: function() {
return this.style.shadowBlur;
},
set: function(value) {
if (value !== this.style.shadowBlur)
{
this.style.shadowBlur = value;
this.dirty = true;
}
}
});
/**
* By default a Text object won't process any input events at all. By setting inputEnabled to true the Phaser.InputHandler is
* activated for this object and it will then start to process click/touch events and more.
*
* @name Phaser.Text#inputEnabled
* @property {boolean} inputEnabled - Set to true to allow this object to receive input events.
*/
Object.defineProperty(Phaser.Text.prototype, "inputEnabled", {
get: function () {
return (this.input && this.input.enabled);
},
set: function (value) {
if (value)
{
if (this.input === null)
{
this.input = new Phaser.InputHandler(this);
this.input.start();
}
}
else
{
if (this.input && this.input.enabled)
{
this.input.stop();
}
}
}
});
/**
* An Text that is fixed to the camera uses its x/y coordinates as offsets from the top left of the camera. These are stored in Text.cameraOffset.
* Note that the cameraOffset values are in addition to any parent in the display list.
* So if this Text was in a Group that has x: 200, then this will be added to the cameraOffset.x
*
* @name Phaser.Text#fixedToCamera
* @property {boolean} fixedToCamera - Set to true to fix this Text to the Camera at its current world coordinates.
*/
Object.defineProperty(Phaser.Text.prototype, "fixedToCamera", {
get: function () {
return !!this._cache[7];
},
set: function (value) {
if (value)
{
this._cache[7] = 1;
this.cameraOffset.set(this.x, this.y);
}
else
{
this._cache[7] = 0;
}
}
});
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2014 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* Creates a new BitmapText object.
*
* @class Phaser.BitmapText
*
* @classdesc BitmapText objects work by taking a texture file and an XML file that describes the font layout.
*
* On Windows you can use the free app BMFont: http://www.angelcode.com/products/bmfont/
* On OS X we recommend Glyph Designer: http://www.71squared.com/en/glyphdesigner
* For Web there is the great Littera: http://kvazars.com/littera/
*
* @constructor
* @param {Phaser.Game} game - A reference to the currently running game.
* @param {number} x - X position of the new bitmapText object.
* @param {number} y - Y position of the new bitmapText object.
* @param {string} font - The key of the BitmapFont as stored in Game.Cache.
* @param {string} [text=''] - The actual text that will be rendered. Can be set later via BitmapText.text.
* @param {number} [size=32] - The size the font will be rendered in, in pixels.
*/
Phaser.BitmapText = function (game, x, y, font, text, size) {
x = x || 0;
y = y || 0;
font = font || '';
text = text || '';
size = size || 32;
/**
* @property {Phaser.Game} game - A reference to the currently running Game.
*/
this.game = game;
/**
* @property {boolean} exists - If exists = false then the Sprite isn't updated by the core game loop or physics subsystem at all.
* @default
*/
this.exists = true;
/**
* @property {string} name - The user defined name given to this BitmapText.
* @default
*/
this.name = '';
/**
* @property {number} type - The const type of this object.
* @readonly
*/
this.type = Phaser.BITMAPTEXT;
/**
* @property {Phaser.Point} world - The world coordinates of this Sprite. This differs from the x/y coordinates which are relative to the Sprites container.
*/
this.world = new Phaser.Point(x, y);
/**
* @property {string} _text - Internal cache var.
* @private
*/
this._text = text;
/**
* @property {string} _font - Internal cache var.
* @private
*/
this._font = font;
/**
* @property {number} _fontSize - Internal cache var.
* @private
*/
this._fontSize = size;
/**
* @property {string} _align - Internal cache var.
* @private
*/
this._align = 'left';
/**
* @property {number} _tint - Internal cache var.
* @private
*/
this._tint = 0xFFFFFF;
/**
* @property {Phaser.Events} events - The Events you can subscribe to that are dispatched when certain things happen on this Sprite or its components.
*/
this.events = new Phaser.Events(this);
/**
* @property {Phaser.InputHandler|null} input - The Input Handler for this object. Needs to be enabled with image.inputEnabled = true before you can use it.
*/
this.input = null;
/**
* @property {Phaser.Point} cameraOffset - If this object is fixedToCamera then this stores the x/y offset that its drawn at, from the top-left of the camera view.
*/
this.cameraOffset = new Phaser.Point();
PIXI.BitmapText.call(this, text);
this.position.set(x, y);
/**
* A small internal cache:
* 0 = previous position.x
* 1 = previous position.y
* 2 = previous rotation
* 3 = renderID
* 4 = fresh? (0 = no, 1 = yes)
* 5 = outOfBoundsFired (0 = no, 1 = yes)
* 6 = exists (0 = no, 1 = yes)
* 7 = fixed to camera (0 = no, 1 = yes)
* @property {Int16Array} _cache
* @private
*/
this._cache = new Int16Array([0, 0, 0, 0, 1, 0, 1, 0]);
};
Phaser.BitmapText.prototype = Object.create(PIXI.BitmapText.prototype);
Phaser.BitmapText.prototype.constructor = Phaser.BitmapText;
/**
* @method Phaser.BitmapText.prototype.setStyle
* @private
*/
Phaser.BitmapText.prototype.setStyle = function() {
this.style = { align: this._align };
this.fontName = this._font;
this.fontSize = this._fontSize;
this.dirty = true;
};
/**
* Automatically called by World.preUpdate.
* @method Phaser.BitmapText.prototype.preUpdate
*/
Phaser.BitmapText.prototype.preUpdate = function () {
this._cache[0] = this.world.x;
this._cache[1] = this.world.y;
this._cache[2] = this.rotation;
if (!this.exists || !this.parent.exists)
{
this.renderOrderID = -1;
return false;
}
if (this.autoCull)
{
// Won't get rendered but will still get its transform updated
this.renderable = this.game.world.camera.screenView.intersects(this.getBounds());
}
this.world.setTo(this.game.camera.x + this.worldTransform[2], this.game.camera.y + this.worldTransform[5]);
if (this.visible)
{
this._cache[3] = this.game.stage.currentRenderOrderID++;
}
return true;
}
/**
* Override and use this function in your own custom objects to handle any update requirements you may have.
*
* @method Phaser.BitmapText.prototype.update
*/
Phaser.BitmapText.prototype.update = function() {
}
/**
* Automatically called by World.postUpdate.
* @method Phaser.BitmapText.prototype.postUpdate
*/
Phaser.BitmapText.prototype.postUpdate = function () {
// Fixed to Camera?
if (this._cache[7] === 1)
{
this.position.x = (this.game.camera.view.x + this.cameraOffset.x) / this.game.camera.scale.x;
this.position.y = (this.game.camera.view.y + this.cameraOffset.y) / this.game.camera.scale.y;
}
}
/**
* Destroy this BitmapText instance. This will remove any filters and un-parent any children.
* @method Phaser.BitmapText.prototype.destroy
* @param {boolean} [destroyChildren=true] - Should every child of this object have its destroy method called?
*/
Phaser.BitmapText.prototype.destroy = function(destroyChildren) {
if (this.game === null) { return; }
if (typeof destroyChildren === 'undefined') { destroyChildren = true; }
if (this.parent)
{
if (this.parent instanceof Phaser.Group)
{
this.parent.remove(this);
}
else
{
this.parent.removeChild(this);
}
}
var i = this.children.length;
if (destroyChildren)
{
while (i--)
{
if (this.children[i].destroy)
{
this.children[i].destroy(destroyChildren);
}
else
{
this.removeChild(this.children[i]);
}
}
}
else
{
while (i--)
{
this.removeChild(this.children[i]);
}
}
this.exists = false;
this.visible = false;
this.filters = null;
this.mask = null;
this.game = null;
}
/**
* @name Phaser.BitmapText#align
* @property {string} align - Alignment for multiline text ('left', 'center' or 'right'), does not affect single line text.
*/
Object.defineProperty(Phaser.BitmapText.prototype, 'align', {
get: function() {
return this._align;
},
set: function(value) {
if (value !== this._align)
{
this._align = value;
this.setStyle();
}
}
});
/**
* @name Phaser.BitmapText#tint
* @property {number} tint - The tint applied to the BitmapText. This is a hex value. Set to white to disable (0xFFFFFF)
*/
Object.defineProperty(Phaser.BitmapText.prototype, 'tint', {
get: function() {
return this._tint;
},
set: function(value) {
if (value !== this._tint)
{
this._tint = value;
this.dirty = true;
}
}
});
/**
* Indicates the rotation of the Text, in degrees, from its original orientation. Values from 0 to 180 represent clockwise rotation; values from 0 to -180 represent counterclockwise rotation.
* Values outside this range are added to or subtracted from 360 to obtain a value within the range. For example, the statement player.angle = 450 is the same as player.angle = 90.
* If you wish to work in radians instead of degrees use the property Sprite.rotation instead.
* @name Phaser.BitmapText#angle
* @property {number} angle - Gets or sets the angle of rotation in degrees.
*/
Object.defineProperty(Phaser.BitmapText.prototype, 'angle', {
get: function() {
return Phaser.Math.radToDeg(this.rotation);
},
set: function(value) {
this.rotation = Phaser.Math.degToRad(value);
}
});
/**
* @name Phaser.BitmapText#font
* @property {string} font - The font the text will be rendered in, i.e. 'Arial'. Must be loaded in the browser before use.
*/
Object.defineProperty(Phaser.BitmapText.prototype, 'font', {
get: function() {
return this._font;
},
set: function(value) {
if (value !== this._font)
{
this._font = value.trim();
this.style.font = this._fontSize + "px '" + this._font + "'";
this.dirty = true;
}
}
});
/**
* @name Phaser.BitmapText#fontSize
* @property {number} fontSize - The size of the font in pixels.
*/
Object.defineProperty(Phaser.BitmapText.prototype, 'fontSize', {
get: function() {
return this._fontSize;
},
set: function(value) {
value = parseInt(value);
if (value !== this._fontSize)
{
this._fontSize = value;
this.style.font = this._fontSize + "px '" + this._font + "'";
this.dirty = true;
}
}
});
/**
* The text string to be displayed by this Text object, taking into account the style settings.
* @name Phaser.BitmapText#text
* @property {string} text - The text string to be displayed by this Text object, taking into account the style settings.
*/
Object.defineProperty(Phaser.BitmapText.prototype, 'text', {
get: function() {
return this._text;
},
set: function(value) {
if (value !== this._text)
{
this._text = value.toString() || ' ';
this.dirty = true;
}
}
});
/**
* By default a Text object won't process any input events at all. By setting inputEnabled to true the Phaser.InputHandler is
* activated for this object and it will then start to process click/touch events and more.
*
* @name Phaser.BitmapText#inputEnabled
* @property {boolean} inputEnabled - Set to true to allow this object to receive input events.
*/
Object.defineProperty(Phaser.BitmapText.prototype, "inputEnabled", {
get: function () {
return (this.input && this.input.enabled);
},
set: function (value) {
if (value)
{
if (this.input === null)
{
this.input = new Phaser.InputHandler(this);
this.input.start();
}
}
else
{
if (this.input && this.input.enabled)
{
this.input.stop();
}
}
}
});
/**
* An BitmapText that is fixed to the camera uses its x/y coordinates as offsets from the top left of the camera. These are stored in BitmapText.cameraOffset.
* Note that the cameraOffset values are in addition to any parent in the display list.
* So if this BitmapText was in a Group that has x: 200, then this will be added to the cameraOffset.x
*
* @name Phaser.BitmapText#fixedToCamera
* @property {boolean} fixedToCamera - Set to true to fix this BitmapText to the Camera at its current world coordinates.
*/
Object.defineProperty(Phaser.BitmapText.prototype, "fixedToCamera", {
get: function () {
return !!this._cache[7];
},
set: function (value) {
if (value)
{
this._cache[7] = 1;
this.cameraOffset.set(this.x, this.y);
}
else
{
this._cache[7] = 0;
}
}
});
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2014 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @class Phaser.Button
*
* @classdesc Create a new `Button` object. A Button is a special type of Sprite that is set-up to handle Pointer events automatically. The four states a Button responds to are:
*
* * 'Over' - when the Pointer moves over the Button. This is also commonly known as 'hover'.
* * 'Out' - when the Pointer that was previously over the Button moves out of it.
* * 'Down' - when the Pointer is pressed down on the Button. I.e. touched on a touch enabled device or clicked with the mouse.
* * 'Up' - when the Pointer that was pressed down on the Button is released again.
*
* You can set a unique texture frame and Sound for any of these states.
*
* @constructor
* @extends Phaser.Image
*
* @param {Phaser.Game} game Current game instance.
* @param {number} [x=0] - X position of the Button.
* @param {number} [y=0] - Y position of the Button.
* @param {string} [key] - The image key as defined in the Game.Cache to use as the texture for this Button.
* @param {function} [callback] - The function to call when this Button is pressed.
* @param {object} [callbackContext] - The context in which the callback will be called (usually 'this').
* @param {string|number} [overFrame] - This is the frame or frameName that will be set when this button is in an over state. Give either a number to use a frame ID or a string for a frame name.
* @param {string|number} [outFrame] - This is the frame or frameName that will be set when this button is in an out state. Give either a number to use a frame ID or a string for a frame name.
* @param {string|number} [downFrame] - This is the frame or frameName that will be set when this button is in a down state. Give either a number to use a frame ID or a string for a frame name.
* @param {string|number} [upFrame] - This is the frame or frameName that will be set when this button is in an up state. Give either a number to use a frame ID or a string for a frame name.
*/
Phaser.Button = function (game, x, y, key, callback, callbackContext, overFrame, outFrame, downFrame, upFrame) {
x = x || 0;
y = y || 0;
key = key || null;
callback = callback || null;
callbackContext = callbackContext || this;
Phaser.Image.call(this, game, x, y, key, outFrame);
/**
* @property {number} type - The Phaser Object Type.
*/
this.type = Phaser.BUTTON;
/**
* @property {string} _onOverFrameName - Internal variable.
* @private
* @default
*/
this._onOverFrameName = null;
/**
* @property {string} _onOutFrameName - Internal variable.
* @private
* @default
*/
this._onOutFrameName = null;
/**
* @property {string} _onDownFrameName - Internal variable.
* @private
* @default
*/
this._onDownFrameName = null;
/**
* @property {string} _onUpFrameName - Internal variable.
* @private
* @default
*/
this._onUpFrameName = null;
/**
* @property {number} _onOverFrameID - Internal variable.
* @private
* @default
*/
this._onOverFrameID = null;
/**
* @property {number} _onOutFrameID - Internal variable.
* @private
* @default
*/
this._onOutFrameID = null;
/**
* @property {number} _onDownFrameID - Internal variable.
* @private
* @default
*/
this._onDownFrameID = null;
/**
* @property {number} _onUpFrameID - Internal variable.
* @private
* @default
*/
this._onUpFrameID = null;
/**
* @property {Phaser.Sound} onOverSound - The Sound to be played when this Buttons Over state is activated.
* @default
*/
this.onOverSound = null;
/**
* @property {Phaser.Sound} onOutSound - The Sound to be played when this Buttons Out state is activated.
* @default
*/
this.onOutSound = null;
/**
* @property {Phaser.Sound} onDownSound - The Sound to be played when this Buttons Down state is activated.
* @default
*/
this.onDownSound = null;
/**
* @property {Phaser.Sound} onUpSound - The Sound to be played when this Buttons Up state is activated.
* @default
*/
this.onUpSound = null;
/**
* @property {string} onOverSoundMarker - The Sound Marker used in conjunction with the onOverSound.
* @default
*/
this.onOverSoundMarker = '';
/**
* @property {string} onOutSoundMarker - The Sound Marker used in conjunction with the onOutSound.
* @default
*/
this.onOutSoundMarker = '';
/**
* @property {string} onDownSoundMarker - The Sound Marker used in conjunction with the onDownSound.
* @default
*/
this.onDownSoundMarker = '';
/**
* @property {string} onUpSoundMarker - The Sound Marker used in conjunction with the onUpSound.
* @default
*/
this.onUpSoundMarker = '';
/**
* @property {Phaser.Signal} onInputOver - The Signal (or event) dispatched when this Button is in an Over state.
*/
this.onInputOver = new Phaser.Signal();
/**
* @property {Phaser.Signal} onInputOut - The Signal (or event) dispatched when this Button is in an Out state.
*/
this.onInputOut = new Phaser.Signal();
/**
* @property {Phaser.Signal} onInputDown - The Signal (or event) dispatched when this Button is in an Down state.
*/
this.onInputDown = new Phaser.Signal();
/**
* @property {Phaser.Signal} onInputUp - The Signal (or event) dispatched when this Button is in an Up state.
*/
this.onInputUp = new Phaser.Signal();
/**
* @property {boolean} freezeFrames - When true the Button will cease to change texture frame on all events (over, out, up, down).
*/
this.freezeFrames = false;
/**
* When the Button is touched / clicked and then released you can force it to enter a state of "out" instead of "up".
* @property {boolean} forceOut
* @default
*/
this.forceOut = false;
this.inputEnabled = true;
this.input.start(0, true);
this.setFrames(overFrame, outFrame, downFrame, upFrame);
if (callback !== null)
{
this.onInputUp.add(callback, callbackContext);
}
// Redirect the input events to here so we can handle animation updates, etc
this.events.onInputOver.add(this.onInputOverHandler, this);
this.events.onInputOut.add(this.onInputOutHandler, this);
this.events.onInputDown.add(this.onInputDownHandler, this);
this.events.onInputUp.add(this.onInputUpHandler, this);
};
Phaser.Button.prototype = Object.create(Phaser.Image.prototype);
Phaser.Button.prototype.constructor = Phaser.Button;
/**
* Clears all of the frames set on this Button.
*
* @method Phaser.Button.prototype.clearFrames
*/
Phaser.Button.prototype.clearFrames = function () {
this._onOverFrameName = null;
this._onOverFrameID = null;
this._onOutFrameName = null;
this._onOutFrameID = null;
this._onDownFrameName = null;
this._onDownFrameID = null;
this._onUpFrameName = null;
this._onUpFrameID = null;
}
/**
* Used to manually set the frames that will be used for the different states of the Button.
*
* @method Phaser.Button.prototype.setFrames
* @param {string|number} [overFrame] - This is the frame or frameName that will be set when this button is in an over state. Give either a number to use a frame ID or a string for a frame name.
* @param {string|number} [outFrame] - This is the frame or frameName that will be set when this button is in an out state. Give either a number to use a frame ID or a string for a frame name.
* @param {string|number} [downFrame] - This is the frame or frameName that will be set when this button is in a down state. Give either a number to use a frame ID or a string for a frame name.
* @param {string|number} [upFrame] - This is the frame or frameName that will be set when this button is in an up state. Give either a number to use a frame ID or a string for a frame name.
*/
Phaser.Button.prototype.setFrames = function (overFrame, outFrame, downFrame, upFrame) {
this.clearFrames();
if (overFrame !== null)
{
if (typeof overFrame === 'string')
{
this._onOverFrameName = overFrame;
if (this.input.pointerOver())
{
this.frameName = overFrame;
}
}
else
{
this._onOverFrameID = overFrame;
if (this.input.pointerOver())
{
this.frame = overFrame;
}
}
}
if (outFrame !== null)
{
if (typeof outFrame === 'string')
{
this._onOutFrameName = outFrame;
if (this.input.pointerOver() === false)
{
this.frameName = outFrame;
}
}
else
{
this._onOutFrameID = outFrame;
if (this.input.pointerOver() === false)
{
this.frame = outFrame;
}
}
}
if (downFrame !== null)
{
if (typeof downFrame === 'string')
{
this._onDownFrameName = downFrame;
if (this.input.pointerDown())
{
this.frameName = downFrame;
}
}
else
{
this._onDownFrameID = downFrame;
if (this.input.pointerDown())
{
this.frame = downFrame;
}
}
}
if (upFrame !== null)
{
if (typeof upFrame === 'string')
{
this._onUpFrameName = upFrame;
if (this.input.pointerUp())
{
this.frameName = upFrame;
}
}
else
{
this._onUpFrameID = upFrame;
if (this.input.pointerUp())
{
this.frame = upFrame;
}
}
}
};
/**
* Sets the sounds to be played whenever this Button is interacted with. Sounds can be either full Sound objects, or markers pointing to a section of a Sound object.
* The most common forms of sounds are 'hover' effects and 'click' effects, which is why the order of the parameters is overSound then downSound.
* Call this function with no parameters at all to reset all sounds on this Button.
*
* @method Phaser.Button.prototype.setSounds
* @param {Phaser.Sound} [overSound] - Over Button Sound.
* @param {string} [overMarker] - Over Button Sound Marker.
* @param {Phaser.Sound} [downSound] - Down Button Sound.
* @param {string} [downMarker] - Down Button Sound Marker.
* @param {Phaser.Sound} [outSound] - Out Button Sound.
* @param {string} [outMarker] - Out Button Sound Marker.
* @param {Phaser.Sound} [upSound] - Up Button Sound.
* @param {string} [upMarker] - Up Button Sound Marker.
*/
Phaser.Button.prototype.setSounds = function (overSound, overMarker, downSound, downMarker, outSound, outMarker, upSound, upMarker) {
this.setOverSound(overSound, overMarker);
this.setOutSound(outSound, outMarker);
this.setDownSound(downSound, downMarker);
this.setUpSound(upSound, upMarker);
}
/**
* The Sound to be played when a Pointer moves over this Button.
*
* @method Phaser.Button.prototype.setOverSound
* @param {Phaser.Sound} sound - The Sound that will be played.
* @param {string} [marker] - A Sound Marker that will be used in the playback.
*/
Phaser.Button.prototype.setOverSound = function (sound, marker) {
this.onOverSound = null;
this.onOverSoundMarker = '';
if (sound instanceof Phaser.Sound)
{
this.onOverSound = sound;
}
if (typeof marker === 'string')
{
this.onOverSoundMarker = marker;
}
}
/**
* The Sound to be played when a Pointer moves out of this Button.
*
* @method Phaser.Button.prototype.setOutSound
* @param {Phaser.Sound} sound - The Sound that will be played.
* @param {string} [marker] - A Sound Marker that will be used in the playback.
*/
Phaser.Button.prototype.setOutSound = function (sound, marker) {
this.onOutSound = null;
this.onOutSoundMarker = '';
if (sound instanceof Phaser.Sound)
{
this.onOutSound = sound;
}
if (typeof marker === 'string')
{
this.onOutSoundMarker = marker;
}
}
/**
* The Sound to be played when a Pointer presses down on this Button.
*
* @method Phaser.Button.prototype.setDownSound
* @param {Phaser.Sound} sound - The Sound that will be played.
* @param {string} [marker] - A Sound Marker that will be used in the playback.
*/
Phaser.Button.prototype.setDownSound = function (sound, marker) {
this.onDownSound = null;
this.onDownSoundMarker = '';
if (sound instanceof Phaser.Sound)
{
this.onDownSound = sound;
}
if (typeof marker === 'string')
{
this.onDownSoundMarker = marker;
}
}
/**
* The Sound to be played when a Pointer has pressed down and is released from this Button.
*
* @method Phaser.Button.prototype.setUpSound
* @param {Phaser.Sound} sound - The Sound that will be played.
* @param {string} [marker] - A Sound Marker that will be used in the playback.
*/
Phaser.Button.prototype.setUpSound = function (sound, marker) {
this.onUpSound = null;
this.onUpSoundMarker = '';
if (sound instanceof Phaser.Sound)
{
this.onUpSound = sound;
}
if (typeof marker === 'string')
{
this.onUpSoundMarker = marker;
}
}
/**
* Internal function that handles input events.
*
* @protected
* @method Phaser.Button.prototype.onInputOverHandler
* @param {Phaser.Button} sprite - The Button that the event occured on.
* @param {Phaser.Pointer} pointer - The Pointer that activated the Button.
*/
Phaser.Button.prototype.onInputOverHandler = function (sprite, pointer) {
if (this.freezeFrames === false)
{
this.setState(1);
}
if (this.onOverSound)
{
this.onOverSound.play(this.onOverSoundMarker);
}
if (this.onInputOver)
{
this.onInputOver.dispatch(this, pointer);
}
};
/**
* Internal function that handles input events.
*
* @protected
* @method Phaser.Button.prototype.onInputOutHandler
* @param {Phaser.Button} sprite - The Button that the event occured on.
* @param {Phaser.Pointer} pointer - The Pointer that activated the Button.
*/
Phaser.Button.prototype.onInputOutHandler = function (sprite, pointer) {
if (this.freezeFrames === false)
{
this.setState(2);
}
if (this.onOutSound)
{
this.onOutSound.play(this.onOutSoundMarker);
}
if (this.onInputOut)
{
this.onInputOut.dispatch(this, pointer);
}
};
/**
* Internal function that handles input events.
*
* @protected
* @method Phaser.Button.prototype.onInputDownHandler
* @param {Phaser.Button} sprite - The Button that the event occured on.
* @param {Phaser.Pointer} pointer - The Pointer that activated the Button.
*/
Phaser.Button.prototype.onInputDownHandler = function (sprite, pointer) {
if (this.freezeFrames === false)
{
this.setState(3);
}
if (this.onDownSound)
{
this.onDownSound.play(this.onDownSoundMarker);
}
if (this.onInputDown)
{
this.onInputDown.dispatch(this, pointer);
}
};
/**
* Internal function that handles input events.
*
* @protected
* @method Phaser.Button.prototype.onInputUpHandler
* @param {Phaser.Button} sprite - The Button that the event occured on.
* @param {Phaser.Pointer} pointer - The Pointer that activated the Button.
*/
Phaser.Button.prototype.onInputUpHandler = function (sprite, pointer, isOver) {
if (this.onUpSound)
{
this.onUpSound.play(this.onUpSoundMarker);
}
if (this.onInputUp)
{
this.onInputUp.dispatch(this, pointer, isOver);
}
if (this.freezeFrames)
{
return;
}
if (this.forceOut)
{
// Button should be forced to the Out frame when released.
this.setState(2);
}
else
{
if (this._onUpFrameName || this._onUpFrameID)
{
this.setState(4);
}
else
{
if (isOver)
{
this.setState(1);
}
else
{
this.setState(2);
}
}
}
};
/**
* Internal function that handles Button state changes.
*
* @protected
* @method Phaser.Button.prototype.setState
* @param {number} newState - The new State of the Button.
*/
Phaser.Button.prototype.setState = function (newState) {
if (newState === 1)
{
// Over
if (this._onOverFrameName != null)
{
this.frameName = this._onOverFrameName;
}
else if (this._onOverFrameID != null)
{
this.frame = this._onOverFrameID;
}
}
else if (newState === 2)
{
// Out
if (this._onOutFrameName != null)
{
this.frameName = this._onOutFrameName;
}
else if (this._onOutFrameID != null)
{
this.frame = this._onOutFrameID;
}
}
else if (newState === 3)
{
// Down
if (this._onDownFrameName != null)
{
this.frameName = this._onDownFrameName;
}
else if (this._onDownFrameID != null)
{
this.frame = this._onDownFrameID;
}
}
else if (newState === 4)
{
// Up
if (this._onUpFrameName != null)
{
this.frameName = this._onUpFrameName;
}
else if (this._onUpFrameID != null)
{
this.frame = this._onUpFrameID;
}
}
};
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2014 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* Creates a new `Graphics` object.
*
* @class Phaser.Graphics
* @constructor
*
* @param {Phaser.Game} game Current game instance.
* @param {number} x - X position of the new graphics object.
* @param {number} y - Y position of the new graphics object.
*/
Phaser.Graphics = function (game, x, y) {
x = x || 0;
y = y || 0;
/**
* @property {Phaser.Game} game - A reference to the currently running Game.
*/
this.game = game;
/**
* @property {boolean} exists - If exists = false then the Text isn't updated by the core game loop.
* @default
*/
this.exists = true;
/**
* @property {string} name - The user defined name given to this object.
* @default
*/
this.name = '';
/**
* @property {number} type - The const type of this object.
* @default
*/
this.type = Phaser.GRAPHICS;
/**
* @property {Phaser.Point} world - The world coordinates of this Sprite. This differs from the x/y coordinates which are relative to the Sprites container.
*/
this.world = new Phaser.Point(x, y);
/**
* @property {Phaser.Point} cameraOffset - If this object is fixedToCamera then this stores the x/y offset that its drawn at, from the top-left of the camera view.
*/
this.cameraOffset = new Phaser.Point();
PIXI.Graphics.call(this);
this.position.set(x, y);
/**
* A small internal cache:
* 0 = previous position.x
* 1 = previous position.y
* 2 = previous rotation
* 3 = renderID
* 4 = fresh? (0 = no, 1 = yes)
* 5 = outOfBoundsFired (0 = no, 1 = yes)
* 6 = exists (0 = no, 1 = yes)
* 7 = fixed to camera (0 = no, 1 = yes)
* @property {Int16Array} _cache
* @private
*/
this._cache = new Int16Array([0, 0, 0, 0, 1, 0, 1, 0]);
};
Phaser.Graphics.prototype = Object.create(PIXI.Graphics.prototype);
Phaser.Graphics.prototype.constructor = Phaser.Graphics;
/**
* Automatically called by World.preUpdate.
* @method Phaser.Graphics.prototype.preUpdate
*/
Phaser.Graphics.prototype.preUpdate = function () {
this._cache[0] = this.world.x;
this._cache[1] = this.world.y;
this._cache[2] = this.rotation;
if (!this.exists || !this.parent.exists)
{
this.renderOrderID = -1;
return false;
}
if (this.autoCull)
{
// Won't get rendered but will still get its transform updated
this.renderable = this.game.world.camera.screenView.intersects(this.getBounds());
}
this.world.setTo(this.game.camera.x + this.worldTransform[2], this.game.camera.y + this.worldTransform[5]);
if (this.visible)
{
this._cache[3] = this.game.stage.currentRenderOrderID++;
}
return true;
}
/**
* Override and use this function in your own custom objects to handle any update requirements you may have.
*
* @method Phaser.Graphics#update
* @memberof Phaser.Graphics
*/
Phaser.Graphics.prototype.update = function() {
}
/**
* Automatically called by World.postUpdate.
* @method Phaser.Graphics.prototype.postUpdate
*/
Phaser.Graphics.prototype.postUpdate = function () {
// Fixed to Camera?
if (this._cache[7] === 1)
{
this.position.x = (this.game.camera.view.x + this.cameraOffset.x) / this.game.camera.scale.x;
this.position.y = (this.game.camera.view.y + this.cameraOffset.y) / this.game.camera.scale.y;
}
}
/**
* Destroy this Graphics instance.
*
* @method Phaser.Graphics.prototype.destroy
* @param {boolean} [destroyChildren=true] - Should every child of this object have its destroy method called?
*/
Phaser.Graphics.prototype.destroy = function(destroyChildren) {
if (typeof destroyChildren === 'undefined') { destroyChildren = true; }
this.clear();
if (this.parent)
{
if (this.parent instanceof Phaser.Group)
{
this.parent.remove(this);
}
else
{
this.parent.removeChild(this);
}
}
var i = this.children.length;
if (destroyChildren)
{
while (i--)
{
this.children[i].destroy(destroyChildren);
}
}
else
{
while (i--)
{
this.removeChild(this.children[i]);
}
}
this.exists = false;
this.visible = false;
this.game = null;
}
/*
* Draws a {Phaser.Polygon} or a {PIXI.Polygon} filled
*
* @method Phaser.Graphics.prototype.drawPolygon
*/
Phaser.Graphics.prototype.drawPolygon = function (poly) {
this.moveTo(poly.points[0].x, poly.points[0].y);
for (var i = 1; i < poly.points.length; i += 1)
{
this.lineTo(poly.points[i].x, poly.points[i].y);
}
this.lineTo(poly.points[0].x, poly.points[0].y);
}
/**
* Indicates the rotation of the Graphics, in degrees, from its original orientation. Values from 0 to 180 represent clockwise rotation; values from 0 to -180 represent counterclockwise rotation.
* Values outside this range are added to or subtracted from 360 to obtain a value within the range. For example, the statement player.angle = 450 is the same as player.angle = 90.
* If you wish to work in radians instead of degrees use the property Sprite.rotation instead.
* @name Phaser.Graphics#angle
* @property {number} angle - Gets or sets the angle of rotation in degrees.
*/
Object.defineProperty(Phaser.Graphics.prototype, 'angle', {
get: function() {
return Phaser.Math.radToDeg(this.rotation);
},
set: function(value) {
this.rotation = Phaser.Math.degToRad(value);
}
});
/**
* An Graphics that is fixed to the camera uses its x/y coordinates as offsets from the top left of the camera. These are stored in Graphics.cameraOffset.
* Note that the cameraOffset values are in addition to any parent in the display list.
* So if this Graphics was in a Group that has x: 200, then this will be added to the cameraOffset.x
*
* @name Phaser.Graphics#fixedToCamera
* @property {boolean} fixedToCamera - Set to true to fix this Graphics to the Camera at its current world coordinates.
*/
Object.defineProperty(Phaser.Graphics.prototype, "fixedToCamera", {
get: function () {
return !!this._cache[7];
},
set: function (value) {
if (value)
{
this._cache[7] = 1;
this.cameraOffset.set(this.x, this.y);
}
else
{
this._cache[7] = 0;
}
}
});
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2014 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* A RenderTexture is a special texture that allows any displayObject to be rendered to it.
* @class Phaser.RenderTexture
* @constructor
* @param {Phaser.Game} game - Current game instance.
* @param {string} key - Internal Phaser reference key for the render texture.
* @param {number} [width=100] - The width of the render texture.
* @param {number} [height=100] - The height of the render texture.
*/
Phaser.RenderTexture = function (game, width, height, key) {
/**
* @property {Phaser.Game} game - A reference to the currently running game.
*/
this.game = game;
/**
* @property {string} key - The key of the RenderTexture in the Cache, if stored there.
*/
this.key = key;
/**
* @property {number} type - Base Phaser object type.
*/
this.type = Phaser.RENDERTEXTURE;
/**
* @property {Phaser.Point} _temp - Internal var.
* @private
*/
this._temp = new Phaser.Point();
PIXI.RenderTexture.call(this, width, height);
};
Phaser.RenderTexture.prototype = Object.create(PIXI.RenderTexture.prototype);
Phaser.RenderTexture.prototype.constructor = Phaser.RenderTexture;
/**
* This function will draw the display object to the texture.
*
* @method Phaser.RenderTexture.prototype.renderXY
* @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapText|Phaser.Group} displayObject The display object to render to this texture.
* @param {number} x - The x position to render the object at.
* @param {number} y - The y position to render the object at.
* @param {boolean} clear - If true the texture will be cleared before the display object is drawn.
*/
Phaser.RenderTexture.prototype.renderXY = function (displayObject, x, y, clear) {
this._temp.set(x, y);
this.render(displayObject, this._temp, clear);
}
// Documentation stubs
/**
* This function will draw the display object to the texture.
*
* @method Phaser.RenderTexture.prototype.render
* @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapText|Phaser.Group} displayObject The display object to render to this texture.
* @param {Phaser.Point} position - A Point object containing the position to render the display object at.
* @param {boolean} clear - If true the texture will be cleared before the display object is drawn.
*/
/**
* Resize this RenderTexture to the given width and height.
*
* @method Phaser.RenderTexture.prototype.resize
* @param {number} width - The new width of the RenderTexture.
* @param {number} height - The new height of the RenderTexture.
*/
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2014 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* Phaser SpriteBatch constructor.
*
* @classdesc The SpriteBatch class is a really fast version of the DisplayObjectContainer built solely for speed, so use when you need a lot of sprites or particles.
* @class Phaser.SpriteBatch
* @extends Phaser.Group
* @constructor
* @param {Phaser.Game} game - A reference to the currently running game.
* @param {Phaser.Group|Phaser.Sprite} parent - The parent Group, DisplayObject or DisplayObjectContainer that this Group will be added to. If undefined or null it will use game.world.
* @param {string} [name=group] - A name for this Group. Not used internally but useful for debugging.
* @param {boolean} [addToStage=false] - If set to true this Group will be added directly to the Game.Stage instead of Game.World.
*/
Phaser.SpriteBatch = function (game, parent, name, addToStage) {
PIXI.SpriteBatch.call(this);
Phaser.Group.call(this, game, parent, name, addToStage);
/**
* @property {number} type - Internal Phaser Type value.
* @protected
*/
this.type = Phaser.SPRITEBATCH;
};
Phaser.SpriteBatch.prototype = Phaser.Utils.extend(true, Phaser.SpriteBatch.prototype, Phaser.Group.prototype, PIXI.SpriteBatch.prototype);
Phaser.SpriteBatch.prototype.constructor = Phaser.SpriteBatch;
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2014 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @class Phaser.RetroFont
* @extends Phaser.RenderTexture
* @constructor
* @param {Phaser.Game} game - Current game instance.
* @param {string} key - The font set graphic set as stored in the Game.Cache.
* @param {number} characterWidth - The width of each character in the font set.
* @param {number} characterHeight - The height of each character in the font set.
* @param {string} chars - The characters used in the font set, in display order. You can use the TEXT_SET consts for common font set arrangements.
* @param {number} charsPerRow - The number of characters per row in the font set.
* @param {number} [xSpacing=0] - If the characters in the font set have horizontal spacing between them set the required amount here.
* @param {number} [ySpacing=0] - If the characters in the font set have vertical spacing between them set the required amount here.
* @param {number} [xOffset=0] - If the font set doesn't start at the top left of the given image, specify the X coordinate offset here.
* @param {number} [yOffset=0] - If the font set doesn't start at the top left of the given image, specify the Y coordinate offset here.
*/
Phaser.RetroFont = function (game, key, characterWidth, characterHeight, chars, charsPerRow, xSpacing, ySpacing, xOffset, yOffset) {
/**
* @property {number} characterWidth - The width of each character in the font set.
*/
this.characterWidth = characterWidth;
/**
* @property {number} characterHeight - The height of each character in the font set.
*/
this.characterHeight = characterHeight;
/**
* @property {number} characterSpacingX - If the characters in the font set have horizontal spacing between them set the required amount here.
*/
this.characterSpacingX = xSpacing || 0;
/**
* @property {number} characterSpacingY - If the characters in the font set have vertical spacing between them set the required amount here.
*/
this.characterSpacingY = ySpacing || 0;
/**
* @property {number} characterPerRow - The number of characters per row in the font set.
*/
this.characterPerRow = charsPerRow;
/**
* @property {number} offsetX - If the font set doesn't start at the top left of the given image, specify the X coordinate offset here.
*/
this.offsetX = xOffset || 0;
/**
* @property {number} offsetY - If the font set doesn't start at the top left of the given image, specify the Y coordinate offset here.
*/
this.offsetY = yOffset || 0;
/**
* @property {string} align - Alignment of the text when multiLine = true or a fixedWidth is set. Set to RetroFont.ALIGN_LEFT (default), RetroFont.ALIGN_RIGHT or RetroFont.ALIGN_CENTER.
*/
this.align = "left";
/**
* @property {boolean} multiLine - If set to true all carriage-returns in text will form new lines (see align). If false the font will only contain one single line of text (the default)
* @default
*/
this.multiLine = false;
/**
* @property {boolean} autoUpperCase - Automatically convert any text to upper case. Lots of old bitmap fonts only contain upper-case characters, so the default is true.
* @default
*/
this.autoUpperCase = true;
/**
* @property {number} customSpacingX - Adds horizontal spacing between each character of the font, in pixels.
* @default
*/
this.customSpacingX = 0;
/**
* @property {number} customSpacingY - Adds vertical spacing between each line of multi-line text, set in pixels.
* @default
*/
this.customSpacingY = 0;
/**
* If you need this RetroFont image to have a fixed width you can set the width in this value.
* If text is wider than the width specified it will be cropped off.
* @property {number} fixedWidth
*/
this.fixedWidth = 0;
/**
* @property {HTMLImage} fontSet - A reference to the image stored in the Game.Cache that contains the font.
*/
this.fontSet = game.cache.getImage(key);
/**
* @property {string} _text - The text of the font image.
* @private
*/
this._text = '';
/**
* @property {array} grabData - An array of rects for faster character pasting.
* @private
*/
this.grabData = [];
// Now generate our rects for faster copying later on
var currentX = this.offsetX;
var currentY = this.offsetY;
var r = 0;
var data = new Phaser.FrameData();
for (var c = 0; c < chars.length; c++)
{
var uuid = game.rnd.uuid();
var frame = data.addFrame(new Phaser.Frame(c, currentX, currentY, this.characterWidth, this.characterHeight, '', uuid));
this.grabData[chars.charCodeAt(c)] = frame.index;
PIXI.TextureCache[uuid] = new PIXI.Texture(PIXI.BaseTextureCache[key], {
x: currentX,
y: currentY,
width: this.characterWidth,
height: this.characterHeight
});
r++;
if (r == this.characterPerRow)
{
r = 0;
currentX = this.offsetX;
currentY += this.characterHeight + this.characterSpacingY;
}
else
{
currentX += this.characterWidth + this.characterSpacingX;
}
}
game.cache.updateFrameData(key, data);
this.stamp = new Phaser.Image(game, 0, 0, key, 0);
Phaser.RenderTexture.call(this, game);
/**
* @property {number} type - Base Phaser object type.
*/
this.type = Phaser.BITMAPFONT;
};
Phaser.RetroFont.prototype = Object.create(Phaser.RenderTexture.prototype);
Phaser.RetroFont.prototype.constructor = Phaser.RetroFont;
/**
* Align each line of multi-line text to the left.
* @constant
* @type {string}
*/
Phaser.RetroFont.ALIGN_LEFT = "left";
/**
* Align each line of multi-line text to the right.
* @constant
* @type {string}
*/
Phaser.RetroFont.ALIGN_RIGHT = "right";
/**
* Align each line of multi-line text in the center.
* @constant
* @type {string}
*/
Phaser.RetroFont.ALIGN_CENTER = "center";
/**
* Text Set 1 = !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~
* @constant
* @type {string}
*/
Phaser.RetroFont.TEXT_SET1 = " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~";
/**
* Text Set 2 = !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ
* @constant
* @type {string}
*/
Phaser.RetroFont.TEXT_SET2 = " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ";
/**
* Text Set 3 = ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789
* @constant
* @type {string}
*/
Phaser.RetroFont.TEXT_SET3 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 ";
/**
* Text Set 4 = ABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789
* @constant
* @type {string}
*/
Phaser.RetroFont.TEXT_SET4 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789";
/**
* Text Set 5 = ABCDEFGHIJKLMNOPQRSTUVWXYZ.,/() '!?-*:0123456789
* @constant
* @type {string}
*/
Phaser.RetroFont.TEXT_SET5 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ.,/() '!?-*:0123456789";
/**
* Text Set 6 = ABCDEFGHIJKLMNOPQRSTUVWXYZ!?:;0123456789\"(),-.'
* @constant
* @type {string}
*/
Phaser.RetroFont.TEXT_SET6 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ!?:;0123456789\"(),-.' ";
/**
* Text Set 7 = AGMSY+:4BHNTZ!;5CIOU.?06DJPV,(17EKQW\")28FLRX-'39
* @constant
* @type {string}
*/
Phaser.RetroFont.TEXT_SET7 = "AGMSY+:4BHNTZ!;5CIOU.?06DJPV,(17EKQW\")28FLRX-'39";
/**
* Text Set 8 = 0123456789 .ABCDEFGHIJKLMNOPQRSTUVWXYZ
* @constant
* @type {string}
*/
Phaser.RetroFont.TEXT_SET8 = "0123456789 .ABCDEFGHIJKLMNOPQRSTUVWXYZ";
/**
* Text Set 9 = ABCDEFGHIJKLMNOPQRSTUVWXYZ()-0123456789.:,'\"?!
* @constant
* @type {string}
*/
Phaser.RetroFont.TEXT_SET9 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ()-0123456789.:,'\"?!";
/**
* Text Set 10 = ABCDEFGHIJKLMNOPQRSTUVWXYZ
* @constant
* @type {string}
*/
Phaser.RetroFont.TEXT_SET10 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
/**
* Text Set 11 = ABCDEFGHIJKLMNOPQRSTUVWXYZ.,\"-+!?()':;0123456789
* @constant
* @type {string}
*/
Phaser.RetroFont.TEXT_SET11 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ.,\"-+!?()':;0123456789";
/**
* If you need this FlxSprite to have a fixed width and custom alignment you can set the width here.<br>
* If text is wider than the width specified it will be cropped off.
*
* @method Phaser.RetroFont#setFixedWidth
* @memberof Phaser.RetroFont
* @param {number} width - Width in pixels of this RetroFont. Set to zero to disable and re-enable automatic resizing.
* @param {string} [lineAlignment='left'] - Align the text within this width. Set to RetroFont.ALIGN_LEFT (default), RetroFont.ALIGN_RIGHT or RetroFont.ALIGN_CENTER.
*/
Phaser.RetroFont.prototype.setFixedWidth = function (width, lineAlignment) {
if (typeof lineAlignment === 'undefined') { lineAlignment = 'left'; }
this.fixedWidth = width;
this.align = lineAlignment;
}
/**
* A helper function that quickly sets lots of variables at once, and then updates the text.
*
* @method Phaser.RetroFont#setText
* @memberof Phaser.RetroFont
* @param {string} content - The text of this sprite.
* @param {boolean} [multiLine=false] - Set to true if you want to support carriage-returns in the text and create a multi-line sprite instead of a single line.
* @param {number} [characterSpacing=0] - To add horizontal spacing between each character specify the amount in pixels.
* @param {number} [lineSpacing=0] - To add vertical spacing between each line of text, set the amount in pixels.
* @param {string} [lineAlignment='left'] - Align each line of multi-line text. Set to RetroFont.ALIGN_LEFT, RetroFont.ALIGN_RIGHT or RetroFont.ALIGN_CENTER.
* @param {boolean} [allowLowerCase=false] - Lots of bitmap font sets only include upper-case characters, if yours needs to support lower case then set this to true.
*/
Phaser.RetroFont.prototype.setText = function (content, multiLine, characterSpacing, lineSpacing, lineAlignment, allowLowerCase) {
this.multiLine = multiLine || false;
this.customSpacingX = characterSpacing || 0;
this.customSpacingY = lineSpacing || 0;
this.align = lineAlignment || 'left';
if (allowLowerCase)
{
this.autoUpperCase = false;
}
else
{
this.autoUpperCase = true;
}
if (content.length > 0)
{
this.text = content;
}
}
/**
* Over rides the default PIXI.RenderTexture resize event as we need our baseTexture resized as well.
*
* @method Phaser.RetroFont#resize
* @memberof Phaser.RetroFont
*/
Phaser.RetroFont.prototype.resize = function (width, height) {
this.width = width;
this.height = height;
this.frame.width = this.width;
this.frame.height = this.height;
this.baseTexture.width = this.width;
this.baseTexture.height = this.height;
if (this.renderer.type === PIXI.WEBGL_RENDERER)
{
this.projection.x = this.width / 2;
this.projection.y = -this.height / 2;
var gl = this.renderer.gl;
gl.bindTexture(gl.TEXTURE_2D, this.baseTexture._glTextures[gl.id]);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, this.width, this.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
}
else
{
this.textureBuffer.resize(this.width, this.height);
}
PIXI.Texture.frameUpdates.push(this);
}
/**
* Updates the BitmapData of the Sprite with the text
*
* @method Phaser.RetroFont#buildRetroFontText
* @memberof Phaser.RetroFont
*/
Phaser.RetroFont.prototype.buildRetroFontText = function () {
var cx = 0;
var cy = 0;
if (this.multiLine)
{
var lines = this._text.split("\n");
if (this.fixedWidth > 0)
{
this.resize(fixedWidth, (lines.length * (this.characterHeight + this.customSpacingY)) - this.customSpacingY);
}
else
{
this.resize(this.getLongestLine() * (this.characterWidth + this.customSpacingX), (lines.length * (this.characterHeight + this.customSpacingY)) - this.customSpacingY);
}
this.textureBuffer.clear();
// Loop through each line of text
for (var i = 0; i < lines.length; i++)
{
// This line of text is held in lines[i] - need to work out the alignment
switch (this.align)
{
case Phaser.RetroFont.ALIGN_LEFT:
cx = 0;
break;
case Phaser.RetroFont.ALIGN_RIGHT:
cx = this.width - (lines[i].length * (this.characterWidth + this.customSpacingX));
break;
case Phaser.RetroFont.ALIGN_CENTER:
cx = (this.width / 2) - ((lines[i].length * (this.characterWidth + this.customSpacingX)) / 2);
cx += this.customSpacingX / 2;
break;
}
// Sanity checks
if (cx < 0)
{
cx = 0;
}
this.pasteLine(lines[i], cx, cy, this.customSpacingX);
cy += this.characterHeight + this.customSpacingY;
}
}
else
{
if (this.fixedWidth > 0)
{
this.resize(fixedWidth, this.characterHeight);
}
else
{
this.resize(this._text.length * (this.characterWidth + this.customSpacingX), this.characterHeight);
}
this.textureBuffer.clear();
switch (this.align)
{
case Phaser.RetroFont.ALIGN_LEFT:
cx = 0;
break;
case Phaser.RetroFont.ALIGN_RIGHT:
cx = this.width - (this._text.length * (this.characterWidth + this.customSpacingX));
break;
case Phaser.RetroFont.ALIGN_CENTER:
cx = (this.width / 2) - ((this._text.length * (this.characterWidth + this.customSpacingX)) / 2);
cx += this.customSpacingX / 2;
break;
}
this.pasteLine(this._text, cx, 0, this.customSpacingX);
}
}
/**
* Internal function that takes a single line of text (2nd parameter) and pastes it into the BitmapData at the given coordinates.
* Used by getLine and getMultiLine
*
* @method Phaser.RetroFont#buildRetroFontText
* @memberof Phaser.RetroFont
* @param {string} line - The single line of text to paste.
* @param {number} x - The x coordinate.
* @param {number} y - The y coordinate.
* @param {number} customSpacingX - Custom X spacing.
*/
Phaser.RetroFont.prototype.pasteLine = function (line, x, y, customSpacingX) {
var p = new Phaser.Point();
for (var c = 0; c < line.length; c++)
{
// If it's a space then there is no point copying, so leave a blank space
if (line.charAt(c) == " ")
{
x += this.characterWidth + this.customSpacingX;
}
else
{
// If the character doesn't exist in the font then we don't want a blank space, we just want to skip it
if (this.grabData[line.charCodeAt(c)] >= 0)
{
this.stamp.frame = this.grabData[line.charCodeAt(c)];
p.set(x, y);
this.render(this.stamp, p, false);
x += this.characterWidth + this.customSpacingX;
if (x > this.width)
{
break;
}
}
}
}
}
/**
* Works out the longest line of text in _text and returns its length
*
* @method Phaser.RetroFont#getLongestLine
* @memberof Phaser.RetroFont
* @return {number} The length of the longest line of text.
*/
Phaser.RetroFont.prototype.getLongestLine = function () {
var longestLine = 0;
if (this._text.length > 0)
{
var lines = this._text.split("\n");
for (var i = 0; i < lines.length; i++)
{
if (lines[i].length > longestLine)
{
longestLine = lines[i].length;
}
}
}
return longestLine;
}
/**
* Internal helper function that removes all unsupported characters from the _text String, leaving only characters contained in the font set.
*
* @method Phaser.RetroFont#removeUnsupportedCharacters
* @memberof Phaser.RetroFont
* @protected
* @param {boolean} [stripCR=true] - Should it strip carriage returns as well?
* @return {string} A clean version of the string.
*/
Phaser.RetroFont.prototype.removeUnsupportedCharacters = function (stripCR) {
var newString = "";
for (var c = 0; c < this._text.length; c++)
{
var char = this._text[c];
var code = char.charCodeAt(0);
if (this.grabData[code] >= 0 || (!stripCR && char === "\n"))
{
newString = newString.concat(char);
}
}
return newString;
}
/**
* @name Phaser.BitmapText#text
* @property {string} text - Set this value to update the text in this sprite. Carriage returns are automatically stripped out if multiLine is false. Text is converted to upper case if autoUpperCase is true.
*/
Object.defineProperty(Phaser.RetroFont.prototype, "text", {
get: function () {
return this._text;
},
set: function (value) {
var newText;
if (this.autoUpperCase)
{
newText = value.toUpperCase();
}
else
{
newText = value;
}
if (newText !== this._text)
{
this._text = newText;
this.removeUnsupportedCharacters(this.multiLine);
this.buildRetroFontText();
}
}
});
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2014 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* The Canvas class handles everything related to creating the `canvas` DOM tag that Phaser will use, including styles, offset and aspect ratio.
*
* @class Phaser.Canvas
* @static
*/
Phaser.Canvas = {
/**
* Creates a `canvas` DOM element. The element is not automatically added to the document.
*
* @method Phaser.Canvas.create
* @param {number} [width=256] - The width of the canvas element.
* @param {number} [height=256] - The height of the canvas element..
* @param {string} [id=''] - If given this will be set as the ID of the canvas element, otherwise no ID will be set.
* @param {boolean} [noCocoon=false] - CocoonJS only allows 1 screencanvas object, which should be your game. If you need to create another canvas (i.e. for a texture) set this to 'true'.
* @return {HTMLCanvasElement} The newly created canvas element.
*/
create: function (width, height, id, noCocoon) {
if (typeof noCocoon === 'undefined') { noCocoon = false; }
width = width || 256;
height = height || 256;
if (noCocoon)
{
var canvas = document.createElement('canvas');
}
else
{
var canvas = document.createElement(navigator.isCocoonJS ? 'screencanvas' : 'canvas');
}
if (typeof id === 'string' && id !== '')
{
canvas.id = id;
}
canvas.width = width;
canvas.height = height;
canvas.style.display = 'block';
return canvas;
},
/**
* Get the DOM offset values of any given element
* @method Phaser.Canvas.getOffset
* @param {HTMLElement} element - The targeted element that we want to retrieve the offset.
* @param {Phaser.Point} [point] - The point we want to take the x/y values of the offset.
* @return {Phaser.Point} - A point objet with the offsetX and Y as its properties.
*/
getOffset: function (element, point) {
point = point || new Phaser.Point();
var box = element.getBoundingClientRect();
var clientTop = element.clientTop || document.body.clientTop || 0;
var clientLeft = element.clientLeft || document.body.clientLeft || 0;
// Without this check Chrome is now throwing console warnings about strict vs. quirks :(
var scrollTop = 0;
var scrollLeft = 0;
if (document.compatMode === 'CSS1Compat')
{
scrollTop = window.pageYOffset || document.documentElement.scrollTop || element.scrollTop || 0;
scrollLeft = window.pageXOffset || document.documentElement.scrollLeft || element.scrollLeft || 0;
}
else
{
scrollTop = window.pageYOffset || document.body.scrollTop || element.scrollTop || 0;
scrollLeft = window.pageXOffset || document.body.scrollLeft || element.scrollLeft || 0;
}
point.x = box.left + scrollLeft - clientLeft;
point.y = box.top + scrollTop - clientTop;
return point;
},
/**
* Returns the aspect ratio of the given canvas.
*
* @method Phaser.Canvas.getAspectRatio
* @param {HTMLCanvasElement} canvas - The canvas to get the aspect ratio from.
* @return {number} The ratio between canvas' width and height.
*/
getAspectRatio: function (canvas) {
return canvas.width / canvas.height;
},
/**
* Sets the background color behind the canvas. This changes the canvas style property.
*
* @method Phaser.Canvas.setBackgroundColor
* @param {HTMLCanvasElement} canvas - The canvas to set the background color on.
* @param {string} [color] - The color to set. Can be in the format 'rgb(r,g,b)', or '#RRGGBB' or any valid CSS color.
* @return {HTMLCanvasElement} Returns the source canvas.
*/
setBackgroundColor: function (canvas, color) {
color = color || 'rgb(0,0,0)';
canvas.style.backgroundColor = color;
return canvas;
},
/**
* Sets the touch-action property on the canvas style. Can be used to disable default browser touch actions.
*
* @method Phaser.Canvas.setTouchAction
* @param {HTMLCanvasElement} canvas - The canvas to set the touch action on.
* @param {String} [value] - The touch action to set. Defaults to 'none'.
* @return {HTMLCanvasElement} The source canvas.
*/
setTouchAction: function (canvas, value) {
value = value || 'none';
canvas.style.msTouchAction = value;
canvas.style['ms-touch-action'] = value;
canvas.style['touch-action'] = value;
return canvas;
},
/**
* Sets the user-select property on the canvas style. Can be used to disable default browser selection actions.
*
* @method Phaser.Canvas.setUserSelect
* @param {HTMLCanvasElement} canvas - The canvas to set the touch action on.
* @param {String} [value] - The touch action to set. Defaults to 'none'.
* @return {HTMLCanvasElement} The source canvas.
*/
setUserSelect: function (canvas, value) {
value = value || 'none';
canvas.style['-webkit-touch-callout'] = value;
canvas.style['-webkit-user-select'] = value;
canvas.style['-khtml-user-select'] = value;
canvas.style['-moz-user-select'] = value;
canvas.style['-ms-user-select'] = value;
canvas.style['user-select'] = value;
canvas.style['-webkit-tap-highlight-color'] = 'rgba(0, 0, 0, 0)';
return canvas;
},
/**
* Adds the given canvas element to the DOM. The canvas will be added as a child of the given parent.
* If no parent is given it will be added as a child of the document.body.
*
* @method Phaser.Canvas.addToDOM
* @param {HTMLCanvasElement} canvas - The canvas to set the touch action on.
* @param {string|HTMLElement} parent - The DOM element to add the canvas to.
* @param {boolean} [overflowHidden=true] - If set to true it will add the overflow='hidden' style to the parent DOM element.
* @return {HTMLCanvasElement} Returns the source canvas.
*/
addToDOM: function (canvas, parent, overflowHidden) {
var target;
if (typeof overflowHidden === 'undefined') { overflowHidden = true; }
if (parent)
{
if (typeof parent === 'string')
{
// hopefully an element ID
target = document.getElementById(parent);
}
else if (typeof parent === 'object' && parent.nodeType === 1)
{
// quick test for a HTMLelement
target = parent;
}
}
// Fallback, covers an invalid ID and a non HTMLelement object
if (!target)
{
target = document.body;
}
if (overflowHidden && target.style)
{
target.style.overflow = 'hidden';
}
target.appendChild(canvas);
return canvas;
},
/**
* Sets the transform of the given canvas to the matrix values provided.
*
* @method Phaser.Canvas.setTransform
* @param {CanvasRenderingContext2D} context - The context to set the transform on.
* @param {number} translateX - The value to translate horizontally by.
* @param {number} translateY - The value to translate vertically by.
* @param {number} scaleX - The value to scale horizontally by.
* @param {number} scaleY - The value to scale vertically by.
* @param {number} skewX - The value to skew horizontaly by.
* @param {number} skewY - The value to skew vertically by.
* @return {CanvasRenderingContext2D} Returns the source context.
*/
setTransform: function (context, translateX, translateY, scaleX, scaleY, skewX, skewY) {
context.setTransform(scaleX, skewX, skewY, scaleY, translateX, translateY);
return context;
},
/**
* Sets the Image Smoothing property on the given context. Set to false to disable image smoothing.
* By default browsers have image smoothing enabled, which isn't always what you visually want, especially
* when using pixel art in a game. Note that this sets the property on the context itself, so that any image
* drawn to the context will be affected. This sets the property across all current browsers but support is
* patchy on earlier browsers, especially on mobile.
*
* @method Phaser.Canvas.setSmoothingEnabled
* @param {CanvasRenderingContext2D} context - The context to enable or disable the image smoothing on.
* @param {boolean} value - If set to true it will enable image smoothing, false will disable it.
* @return {CanvasRenderingContext2D} Returns the source context.
*/
setSmoothingEnabled: function (context, value) {
context['imageSmoothingEnabled'] = value;
context['mozImageSmoothingEnabled'] = value;
context['oImageSmoothingEnabled'] = value;
context['webkitImageSmoothingEnabled'] = value;
context['msImageSmoothingEnabled'] = value;
return context;
},
/**
* Sets the CSS image-rendering property on the given canvas to be 'crisp' (aka 'optimize contrast on webkit').
* Note that if this doesn't given the desired result then see the setSmoothingEnabled.
*
* @method Phaser.Canvas.setImageRenderingCrisp
* @param {HTMLCanvasElement} canvas - The canvas to set image-rendering crisp on.
* @return {HTMLCanvasElement} Returns the source canvas.
*/
setImageRenderingCrisp: function (canvas) {
canvas.style['image-rendering'] = 'optimizeSpeed';
canvas.style['image-rendering'] = 'crisp-edges';
canvas.style['image-rendering'] = '-moz-crisp-edges';
canvas.style['image-rendering'] = '-webkit-optimize-contrast';
canvas.style['image-rendering'] = 'optimize-contrast';
canvas.style.msInterpolationMode = 'nearest-neighbor';
return canvas;
},
/**
* Sets the CSS image-rendering property on the given canvas to be 'bicubic' (aka 'auto').
* Note that if this doesn't given the desired result then see the CanvasUtils.setSmoothingEnabled method.
*
* @method Phaser.Canvas.setImageRenderingBicubic
* @param {HTMLCanvasElement} canvas The canvas to set image-rendering bicubic on.
* @return {HTMLCanvasElement} Returns the source canvas.
*/
setImageRenderingBicubic: function (canvas) {
canvas.style['image-rendering'] = 'auto';
canvas.style.msInterpolationMode = 'bicubic';
return canvas;
}
};
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2014 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* Detects device support capabilities. Using some elements from System.js by MrDoob and Modernizr
*
* @class Phaser.Device
* @constructor
*/
Phaser.Device = function (game) {
/**
* @property {Phaser.Game} game - A reference to the currently running game.
*/
this.game = game;
/**
* An optional 'fix' for the horrendous Android stock browser bug https://code.google.com/p/android/issues/detail?id=39247
* @property {boolean} patchAndroidClearRectBug - Description.
* @default
*/
this.patchAndroidClearRectBug = false;
// Operating System
/**
* @property {boolean} desktop - Is running desktop?
* @default
*/
this.desktop = false;
/**
* @property {boolean} iOS - Is running on iOS?
* @default
*/
this.iOS = false;
/**
* @property {boolean} cocoonJS - Is the game running under CocoonJS?
* @default
*/
this.cocoonJS = false;
/**
* @property {boolean} ejecta - Is the game running under Ejecta?
* @default
*/
this.ejecta = false;
/**
* @property {boolean} android - Is running on android?
* @default
*/
this.android = false;
/**
* @property {boolean} chromeOS - Is running on chromeOS?
* @default
*/
this.chromeOS = false;
/**
* @property {boolean} linux - Is running on linux?
* @default
*/
this.linux = false;
/**
* @property {boolean} macOS - Is running on macOS?
* @default
*/
this.macOS = false;
/**
* @property {boolean} windows - Is running on windows?
* @default
*/
this.windows = false;
/**
* @property {boolean} windowsPhone - Is running on a Windows Phone?
* @default
*/
this.windowsPhone = false;
// Features
/**
* @property {boolean} canvas - Is canvas available?
* @default
*/
this.canvas = false;
/**
* @property {boolean} file - Is file available?
* @default
*/
this.file = false;
/**
* @property {boolean} fileSystem - Is fileSystem available?
* @default
*/
this.fileSystem = false;
/**
* @property {boolean} localStorage - Is localStorage available?
* @default
*/
this.localStorage = false;
/**
* @property {boolean} webGL - Is webGL available?
* @default
*/
this.webGL = false;
/**
* @property {boolean} worker - Is worker available?
* @default
*/
this.worker = false;
/**
* @property {boolean} touch - Is touch available?
* @default
*/
this.touch = false;
/**
* @property {boolean} mspointer - Is mspointer available?
* @default
*/
this.mspointer = false;
/**
* @property {boolean} css3D - Is css3D available?
* @default
*/
this.css3D = false;
/**
* @property {boolean} pointerLock - Is Pointer Lock available?
* @default
*/
this.pointerLock = false;
/**
* @property {boolean} typedArray - Does the browser support TypedArrays?
* @default
*/
this.typedArray = false;
/**
* @property {boolean} vibration - Does the device support the Vibration API?
* @default
*/
this.vibration = false;
/**
* @property {boolean} quirksMode - Is the browser running in strict mode (false) or quirks mode? (true)
* @default
*/
this.quirksMode = false;
// Browser
/**
* @property {boolean} arora - Set to true if running in Arora.
* @default
*/
this.arora = false;
/**
* @property {boolean} chrome - Set to true if running in Chrome.
* @default
*/
this.chrome = false;
/**
* @property {boolean} epiphany - Set to true if running in Epiphany.
* @default
*/
this.epiphany = false;
/**
* @property {boolean} firefox - Set to true if running in Firefox.
* @default
*/
this.firefox = false;
/**
* @property {boolean} ie - Set to true if running in Internet Explorer.
* @default
*/
this.ie = false;
/**
* @property {number} ieVersion - If running in Internet Explorer this will contain the major version number. Beyond IE10 you should use Device.trident and Device.tridentVersion.
* @default
*/
this.ieVersion = 0;
/**
* @property {boolean} trident - Set to true if running a Trident version of Internet Explorer (IE11+)
* @default
*/
this.trident = false;
/**
* @property {number} tridentVersion - If running in Internet Explorer 11 this will contain the major version number. See http://msdn.microsoft.com/en-us/library/ie/ms537503(v=vs.85).aspx
* @default
*/
this.tridentVersion = 0;
/**
* @property {boolean} mobileSafari - Set to true if running in Mobile Safari.
* @default
*/
this.mobileSafari = false;
/**
* @property {boolean} midori - Set to true if running in Midori.
* @default
*/
this.midori = false;
/**
* @property {boolean} opera - Set to true if running in Opera.
* @default
*/
this.opera = false;
/**
* @property {boolean} safari - Set to true if running in Safari.
* @default
*/
this.safari = false;
/**
* @property {boolean} webApp - Set to true if running as a WebApp, i.e. within a WebView
* @default
*/
this.webApp = false;
/**
* @property {boolean} silk - Set to true if running in the Silk browser (as used on the Amazon Kindle)
* @default
*/
this.silk = false;
// Audio
/**
* @property {boolean} audioData - Are Audio tags available?
* @default
*/
this.audioData = false;
/**
* @property {boolean} webAudio - Is the WebAudio API available?
* @default
*/
this.webAudio = false;
/**
* @property {boolean} ogg - Can this device play ogg files?
* @default
*/
this.ogg = false;
/**
* @property {boolean} opus - Can this device play opus files?
* @default
*/
this.opus = false;
/**
* @property {boolean} mp3 - Can this device play mp3 files?
* @default
*/
this.mp3 = false;
/**
* @property {boolean} wav - Can this device play wav files?
* @default
*/
this.wav = false;
/**
* Can this device play m4a files?
* @property {boolean} m4a - True if this device can play m4a files.
* @default
*/
this.m4a = false;
/**
* @property {boolean} webm - Can this device play webm files?
* @default
*/
this.webm = false;
// Device
/**
* @property {boolean} iPhone - Is running on iPhone?
* @default
*/
this.iPhone = false;
/**
* @property {boolean} iPhone4 - Is running on iPhone4?
* @default
*/
this.iPhone4 = false;
/**
* @property {boolean} iPad - Is running on iPad?
* @default
*/
this.iPad = false;
/**
* @property {number} pixelRatio - PixelRatio of the host device?
* @default
*/
this.pixelRatio = 0;
/**
* @property {boolean} littleEndian - Is the device big or little endian? (only detected if the browser supports TypedArrays)
* @default
*/
this.littleEndian = false;
/**
* @property {boolean} fullscreen - Does the browser support the Full Screen API?
* @default
*/
this.fullscreen = false;
/**
* @property {string} requestFullscreen - If the browser supports the Full Screen API this holds the call you need to use to activate it.
* @default
*/
this.requestFullscreen = '';
/**
* @property {string} cancelFullscreen - If the browser supports the Full Screen API this holds the call you need to use to cancel it.
* @default
*/
this.cancelFullscreen = '';
/**
* @property {boolean} fullscreenKeyboard - Does the browser support access to the Keyboard during Full Screen mode?
* @default
*/
this.fullscreenKeyboard = false;
// Run the checks
this._checkAudio();
this._checkBrowser();
this._checkCSS3D();
this._checkDevice();
this._checkFeatures();
this._checkOS();
};
Phaser.Device.prototype = {
/**
* Check which OS is game running on.
* @method Phaser.Device#_checkOS
* @private
*/
_checkOS: function () {
var ua = navigator.userAgent;
if (/Android/.test(ua))
{
this.android = true;
}
else if (/CrOS/.test(ua))
{
this.chromeOS = true;
}
else if (/iP[ao]d|iPhone/i.test(ua))
{
this.iOS = true;
}
else if (/Linux/.test(ua))
{
this.linux = true;
}
else if (/Mac OS/.test(ua))
{
this.macOS = true;
}
else if (/Windows/.test(ua))
{
this.windows = true;
if (/Windows Phone/i.test(ua))
{
this.windowsPhone = true;
}
}
if (this.windows || this.macOS || (this.linux && this.silk === false))
{
this.desktop = true;
}
// Windows Phone / Table reset
if (this.windowsPhone || ((/Windows NT/i.test(ua)) && (/Touch/i.test(ua))))
{
this.desktop = false;
}
},
/**
* Check HTML5 features of the host environment.
* @method Phaser.Device#_checkFeatures
* @private
*/
_checkFeatures: function () {
this.canvas = !!window['CanvasRenderingContext2D'] || this.cocoonJS;
try {
this.localStorage = !!localStorage.getItem;
} catch (error) {
this.localStorage = false;
}
this.file = !!window['File'] && !!window['FileReader'] && !!window['FileList'] && !!window['Blob'];
this.fileSystem = !!window['requestFileSystem'];
this.webGL = ( function () { try { var canvas = document.createElement( 'canvas' ); return !! window.WebGLRenderingContext && ( canvas.getContext( 'webgl' ) || canvas.getContext( 'experimental-webgl' ) ); } catch( e ) { return false; } } )();
if (this.webGL === null || this.webGL === false)
{
this.webGL = false;
}
else
{
this.webGL = true;
}
this.worker = !!window['Worker'];
if ('ontouchstart' in document.documentElement || (window.navigator.maxTouchPoints && window.navigator.maxTouchPoints > 1))
{
this.touch = true;
}
if (window.navigator.msPointerEnabled || window.navigator.pointerEnabled)
{
this.mspointer = true;
}
this.pointerLock = 'pointerLockElement' in document || 'mozPointerLockElement' in document || 'webkitPointerLockElement' in document;
this.quirksMode = (document.compatMode === 'CSS1Compat') ? false : true;
},
/**
* Checks for support of the Full Screen API.
*
* @method Phaser.Device#checkFullScreenSupport
*/
checkFullScreenSupport: function () {
var fs = [
'requestFullscreen',
'requestFullScreen',
'webkitRequestFullscreen',
'webkitRequestFullScreen',
'msRequestFullscreen',
'msRequestFullScreen',
'mozRequestFullScreen',
'mozRequestFullscreen'
];
for (var i = 0; i < fs.length; i++)
{
if (this.game.canvas[fs[i]])
{
this.fullscreen = true;
this.requestFullscreen = fs[i];
}
}
var cfs = [
'cancelFullScreen',
'exitFullscreen',
'webkitCancelFullScreen',
'webkitExitFullscreen',
'msCancelFullScreen',
'msExitFullscreen',
'mozCancelFullScreen',
'mozExitFullscreen'
];
if (this.fullscreen)
{
for (var i = 0; i < cfs.length; i++)
{
if (this.game.canvas[cfs[i]])
{
this.cancelFullscreen = cfs[i];
}
}
}
// Keyboard Input?
if (window['Element'] && Element['ALLOW_KEYBOARD_INPUT'])
{
this.fullscreenKeyboard = true;
}
},
/**
* Check what browser is game running in.
* @method Phaser.Device#_checkBrowser
* @private
*/
_checkBrowser: function () {
var ua = navigator.userAgent;
if (/Arora/.test(ua))
{
this.arora = true;
}
else if (/Chrome/.test(ua))
{
this.chrome = true;
}
else if (/Epiphany/.test(ua))
{
this.epiphany = true;
}
else if (/Firefox/.test(ua))
{
this.firefox = true;
}
else if (/Mobile Safari/.test(ua))
{
this.mobileSafari = true;
}
else if (/MSIE (\d+\.\d+);/.test(ua))
{
this.ie = true;
this.ieVersion = parseInt(RegExp.$1, 10);
}
else if (/Midori/.test(ua))
{
this.midori = true;
}
else if (/Opera/.test(ua))
{
this.opera = true;
}
else if (/Safari/.test(ua))
{
this.safari = true;
}
else if (/Silk/.test(ua))
{
this.silk = true;
}
else if (/Trident\/(\d+\.\d+); rv:(\d+\.\d+)/.test(ua))
{
this.ie = true;
this.trident = true;
this.tridentVersion = parseInt(RegExp.$1, 10);
this.ieVersion = parseInt(RegExp.$2, 10);
}
// WebApp mode in iOS
if (navigator['standalone'])
{
this.webApp = true;
}
if (navigator['isCocoonJS'])
{
this.cocoonJS = true;
}
if (typeof window.ejecta !== "undefined")
{
this.ejecta = true;
}
},
/**
* Check audio support.
* @method Phaser.Device#_checkAudio
* @private
*/
_checkAudio: function () {
this.audioData = !!(window['Audio']);
this.webAudio = !!(window['webkitAudioContext'] || window['AudioContext']);
var audioElement = document.createElement('audio');
var result = false;
try {
if (result = !!audioElement.canPlayType) {
if (audioElement.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
this.ogg = true;
}
if (audioElement.canPlayType('audio/ogg; codecs="opus"').replace(/^no$/, '')) {
this.opus = true;
}
if (audioElement.canPlayType('audio/mpeg;').replace(/^no$/, '')) {
this.mp3 = true;
}
// Mimetypes accepted:
// developer.mozilla.org/En/Media_formats_supported_by_the_audio_and_video_elements
// bit.ly/iphoneoscodecs
if (audioElement.canPlayType('audio/wav; codecs="1"').replace(/^no$/, '')) {
this.wav = true;
}
if (audioElement.canPlayType('audio/x-m4a;') || audioElement.canPlayType('audio/aac;').replace(/^no$/, '')) {
this.m4a = true;
}
if (audioElement.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/, '')) {
this.webm = true;
}
}
} catch (e) {
}
},
/**
* Check PixelRatio of devices.
* @method Phaser.Device#_checkDevice
* @private
*/
_checkDevice: function () {
this.pixelRatio = window['devicePixelRatio'] || 1;
this.iPhone = navigator.userAgent.toLowerCase().indexOf('iphone') != -1;
this.iPhone4 = (this.pixelRatio == 2 && this.iPhone);
this.iPad = navigator.userAgent.toLowerCase().indexOf('ipad') != -1;
if (typeof Int8Array !== 'undefined')
{
this.littleEndian = new Int8Array(new Int16Array([1]).buffer)[0] > 0;
this.typedArray = true;
}
else
{
this.littleEndian = false;
this.typedArray = false;
}
navigator.vibrate = navigator.vibrate || navigator.webkitVibrate || navigator.mozVibrate || navigator.msVibrate;
if (navigator.vibrate)
{
this.vibration = true;
}
},
/**
* Check whether the host environment support 3D CSS.
* @method Phaser.Device#_checkCSS3D
* @private
*/
_checkCSS3D: function () {
var el = document.createElement('p');
var has3d;
var transforms = {
'webkitTransform': '-webkit-transform',
'OTransform': '-o-transform',
'msTransform': '-ms-transform',
'MozTransform': '-moz-transform',
'transform': 'transform'
};
// Add it to the body to get the computed style.
document.body.insertBefore(el, null);
for (var t in transforms)
{
if (el.style[t] !== undefined)
{
el.style[t] = "translate3d(1px,1px,1px)";
has3d = window.getComputedStyle(el).getPropertyValue(transforms[t]);
}
}
document.body.removeChild(el);
this.css3D = (has3d !== undefined && has3d.length > 0 && has3d !== "none");
},
/**
* Check whether the host environment can play audio.
* @method Phaser.Device#canPlayAudio
* @param {string} type - One of 'mp3, 'ogg', 'm4a', 'wav', 'webm'.
* @return {boolean} True if the given file type is supported by the browser, otherwise false.
*/
canPlayAudio: function (type) {
if (type == 'mp3' && this.mp3)
{
return true;
}
else if (type == 'ogg' && (this.ogg || this.opus))
{
return true;
}
else if (type == 'm4a' && this.m4a)
{
return true;
}
else if (type == 'wav' && this.wav)
{
return true;
}
else if (type == 'webm' && this.webm)
{
return true;
}
return false;
},
/**
* Check whether the console is open.
* @method Phaser.Device#isConsoleOpen
* @return {boolean} True if the browser dev console is open.
*/
isConsoleOpen: function () {
if (window.console && window.console['firebug'])
{
return true;
}
if (window.console)
{
console.profile();
console.profileEnd();
if (console.clear)
{
console.clear();
}
return console['profiles'].length > 0;
}
return false;
}
};
Phaser.Device.prototype.constructor = Phaser.Device;
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2014 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* Abstracts away the use of RAF or setTimeOut for the core game update loop.
*
* @class Phaser.RequestAnimationFrame
* @constructor
* @param {Phaser.Game} game - A reference to the currently running game.
* @param {boolean} [forceSetTimeOut=false] - Tell Phaser to use setTimeOut even if raf is available.
*/
Phaser.RequestAnimationFrame = function(game, forceSetTimeOut) {
if (typeof forceSetTimeOut === 'undefined') { forceSetTimeOut = false; }
/**
* @property {Phaser.Game} game - The currently running game.
*/
this.game = game;
/**
* @property {boolean} isRunning - true if RequestAnimationFrame is running, otherwise false.
* @default
*/
this.isRunning = false;
/**
* @property {boolean} forceSetTimeOut - Tell Phaser to use setTimeOut even if raf is available.
*/
this.forceSetTimeOut = forceSetTimeOut;
var vendors = [
'ms',
'moz',
'webkit',
'o'
];
for (var x = 0; x < vendors.length && !window.requestAnimationFrame; x++)
{
window.requestAnimationFrame = window[vendors[x] + 'RequestAnimationFrame'];
window.cancelAnimationFrame = window[vendors[x] + 'CancelAnimationFrame'];
}
/**
* @property {boolean} _isSetTimeOut - true if the browser is using setTimeout instead of raf.
* @private
*/
this._isSetTimeOut = false;
/**
* @property {function} _onLoop - The function called by the update.
* @private
*/
this._onLoop = null;
/**
* @property {number} _timeOutID - The callback ID used when calling cancel.
* @private
*/
this._timeOutID = null;
};
Phaser.RequestAnimationFrame.prototype = {
/**
* Starts the requestAnimationFrame running or setTimeout if unavailable in browser
* @method Phaser.RequestAnimationFrame#start
*/
start: function () {
this.isRunning = true;
var _this = this;
if (!window.requestAnimationFrame || this.forceSetTimeOut)
{
this._isSetTimeOut = true;
this._onLoop = function () {
return _this.updateSetTimeout();
};
this._timeOutID = window.setTimeout(this._onLoop, 0);
}
else
{
this._isSetTimeOut = false;
this._onLoop = function (time) {
return _this.updateRAF(time);
};
this._timeOutID = window.requestAnimationFrame(this._onLoop);
}
},
/**
* The update method for the requestAnimationFrame
* @method Phaser.RequestAnimationFrame#updateRAF
* @param {number} time - A timestamp, either from RAF or setTimeOut
*/
updateRAF: function (time) {
this.game.update(Date.now());
this._timeOutID = window.requestAnimationFrame(this._onLoop);
},
/**
* The update method for the setTimeout.
* @method Phaser.RequestAnimationFrame#updateSetTimeout
*/
updateSetTimeout: function () {
this.game.update(Date.now());
this._timeOutID = window.setTimeout(this._onLoop, this.game.time.timeToCall);
},
/**
* Stops the requestAnimationFrame from running.
* @method Phaser.RequestAnimationFrame#stop
*/
stop: function () {
if (this._isSetTimeOut)
{
clearTimeout(this._timeOutID);
}
else
{
window.cancelAnimationFrame(this._timeOutID);
}
this.isRunning = false;
},
/**
* Is the browser using setTimeout?
* @method Phaser.RequestAnimationFrame#isSetTimeOut
* @return {boolean}
*/
isSetTimeOut: function () {
return this._isSetTimeOut;
},
/**
* Is the browser using requestAnimationFrame?
* @method Phaser.RequestAnimationFrame#isRAF
* @return {boolean}
*/
isRAF: function () {
return (this._isSetTimeOut === false);
}
};
Phaser.RequestAnimationFrame.prototype.constructor = Phaser.RequestAnimationFrame;
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2014 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* A collection of mathematical methods.
*
* @class Phaser.Math
*/
Phaser.Math = {
/**
* = 2 &pi;
* @method Phaser.Math#PI2
*/
PI2: Math.PI * 2,
/**
* Two number are fuzzyEqual if their difference is less than &epsilon;.
* @method Phaser.Math#fuzzyEqual
* @param {number} a
* @param {number} b
* @param {number} epsilon
* @return {boolean} True if |a-b|<&epsilon;
*/
fuzzyEqual: function (a, b, epsilon) {
if (typeof epsilon === "undefined") { epsilon = 0.0001; }
return Math.abs(a - b) < epsilon;
},
/**
* a is fuzzyLessThan b if it is less than b + &epsilon;.
* @method Phaser.Math#fuzzyLessThan
* @param {number} a
* @param {number} b
* @param {number} epsilon
* @return {boolean} True if a<b+&epsilon;
*/
fuzzyLessThan: function (a, b, epsilon) {
if (typeof epsilon === "undefined") { epsilon = 0.0001; }
return a < b + epsilon;
},
/**
* a is fuzzyGreaterThan b if it is more than b - &epsilon;.
* @method Phaser.Math#fuzzyGreaterThan
* @param {number} a
* @param {number} b
* @param {number} epsilon
* @return {boolean} True if a>b+&epsilon;
*/
fuzzyGreaterThan: function (a, b, epsilon) {
if (typeof epsilon === "undefined") { epsilon = 0.0001; }
return a > b - epsilon;
},
/**
* @method Phaser.Math#fuzzyCeil
* @param {number} val
* @param {number} epsilon
* @return {boolean} ceiling(val-&epsilon;)
*/
fuzzyCeil: function (val, epsilon) {
if (typeof epsilon === "undefined") { epsilon = 0.0001; }
return Math.ceil(val - epsilon);
},
/**
* @method Phaser.Math#fuzzyFloor
* @param {number} val
* @param {number} epsilon
* @return {boolean} floor(val-&epsilon;)
*/
fuzzyFloor: function (val, epsilon) {
if (typeof epsilon === "undefined") { epsilon = 0.0001; }
return Math.floor(val + epsilon);
},
/**
* Averages all values passed to the function and returns the result. You can pass as many parameters as you like.
* @method Phaser.Math#average
* @return {number} The average of all given values.
*/
average: function () {
var args = [];
for (var _i = 0; _i < (arguments.length - 0); _i++) {
args[_i] = arguments[_i + 0];
}
var avg = 0;
for (var i = 0; i < args.length; i++) {
avg += args[i];
}
return avg / args.length;
},
/**
* @method Phaser.Math#truncate
* @param {number} n
* @return {number}
*/
truncate: function (n) {
return (n > 0) ? Math.floor(n) : Math.ceil(n);
},
/**
* @method Phaser.Math#shear
* @param {number} n
* @return {number} n mod 1
*/
shear: function (n) {
return n % 1;
},
/**
* Snap a value to nearest grid slice, using rounding.
*
* Example: if you have an interval gap of 5 and a position of 12... you will snap to 10 whereas 14 will snap to 15.
*
* @method Phaser.Math#snapTo
* @param {number} input - The value to snap.
* @param {number} gap - The interval gap of the grid.
* @param {number} [start] - Optional starting offset for gap.
* @return {number}
*/
snapTo: function (input, gap, start) {
if (typeof start === "undefined") { start = 0; }
if (gap === 0) {
return input;
}
input -= start;
input = gap * Math.round(input / gap);
return start + input;
},
/**
* Snap a value to nearest grid slice, using floor.
*
* Example: if you have an interval gap of 5 and a position of 12... you will snap to 10. As will 14 snap to 10... but 16 will snap to 15
*
* @method Phaser.Math#snapToFloor
* @param {number} input - The value to snap.
* @param {number} gap - The interval gap of the grid.
* @param {number} [start] - Optional starting offset for gap.
* @return {number}
*/
snapToFloor: function (input, gap, start) {
if (typeof start === "undefined") { start = 0; }
if (gap === 0) {
return input;
}
input -= start;
input = gap * Math.floor(input / gap);
return start + input;
},
/**
* Snap a value to nearest grid slice, using ceil.
*
* Example: if you have an interval gap of 5 and a position of 12... you will snap to 15. As will 14 will snap to 15... but 16 will snap to 20.
*
* @method Phaser.Math#snapToCeil
* @param {number} input - The value to snap.
* @param {number} gap - The interval gap of the grid.
* @param {number} [start] - Optional starting offset for gap.
* @return {number}
*/
snapToCeil: function (input, gap, start) {
if (typeof start === "undefined") { start = 0; }
if (gap === 0) {
return input;
}
input -= start;
input = gap * Math.ceil(input / gap);
return start + input;
},
/**
* Snaps a value to the nearest value in an array.
* @method Phaser.Math#snapToInArray
* @param {number} input
* @param {array} arr
* @param {boolean} sort - True if the array needs to be sorted.
* @return {number}
*/
snapToInArray: function (input, arr, sort) {
if (typeof sort === "undefined") { sort = true; }
if (sort) {
arr.sort();
}
if (input < arr[0]) {
return arr[0];
}
var i = 1;
while (arr[i] < input) {
i++;
}
var low = arr[i - 1];
var high = (i < arr.length) ? arr[i] : Number.POSITIVE_INFINITY;
return ((high - input) <= (input - low)) ? high : low;
},
/**
* Round to some place comparative to a 'base', default is 10 for decimal place.
*
* 'place' is represented by the power applied to 'base' to get that place
* e.g.
* 2000/7 ~= 285.714285714285714285714 ~= (bin)100011101.1011011011011011
*
* roundTo(2000/7,3) === 0
* roundTo(2000/7,2) == 300
* roundTo(2000/7,1) == 290
* roundTo(2000/7,0) == 286
* roundTo(2000/7,-1) == 285.7
* roundTo(2000/7,-2) == 285.71
* roundTo(2000/7,-3) == 285.714
* roundTo(2000/7,-4) == 285.7143
* roundTo(2000/7,-5) == 285.71429
*
* roundTo(2000/7,3,2) == 288 -- 100100000
* roundTo(2000/7,2,2) == 284 -- 100011100
* roundTo(2000/7,1,2) == 286 -- 100011110
* roundTo(2000/7,0,2) == 286 -- 100011110
* roundTo(2000/7,-1,2) == 285.5 -- 100011101.1
* roundTo(2000/7,-2,2) == 285.75 -- 100011101.11
* roundTo(2000/7,-3,2) == 285.75 -- 100011101.11
* roundTo(2000/7,-4,2) == 285.6875 -- 100011101.1011
* roundTo(2000/7,-5,2) == 285.71875 -- 100011101.10111
*
* Note what occurs when we round to the 3rd space (8ths place), 100100000, this is to be assumed
* because we are rounding 100011.1011011011011011 which rounds up.
*
* @method Phaser.Math#roundTo
* @param {number} value - The value to round.
* @param {number} place - The place to round to.
* @param {number} base - The base to round in... default is 10 for decimal.
* @return {number}
*/
roundTo: function (value, place, base) {
if (typeof place === "undefined") { place = 0; }
if (typeof base === "undefined") { base = 10; }
var p = Math.pow(base, -place);
return Math.round(value * p) / p;
},
/**
* @method Phaser.Math#floorTo
* @param {number} value - The value to round.
* @param {number} place - The place to round to.
* @param {number} base - The base to round in... default is 10 for decimal.
* @return {number}
*/
floorTo: function (value, place, base) {
if (typeof place === "undefined") { place = 0; }
if (typeof base === "undefined") { base = 10; }
var p = Math.pow(base, -place);
return Math.floor(value * p) / p;
},
/**
* @method Phaser.Math#ceilTo
* @param {number} value - The value to round.
* @param {number} place - The place to round to.
* @param {number} base - The base to round in... default is 10 for decimal.
* @return {number}
*/
ceilTo: function (value, place, base) {
if (typeof place === "undefined") { place = 0; }
if (typeof base === "undefined") { base = 10; }
var p = Math.pow(base, -place);
return Math.ceil(value * p) / p;
},
/**
* A one dimensional linear interpolation of a value.
* @method Phaser.Math#interpolateFloat
* @param {number} a
* @param {number} b
* @param {number} weight
* @return {number}
*/
interpolateFloat: function (a, b, weight) {
return (b - a) * weight + a;
},
/**
* Find the angle of a segment from (x1, y1) -> (x2, y2).
* @method Phaser.Math#angleBetween
* @param {number} x1
* @param {number} y1
* @param {number} x2
* @param {number} y2
* @return {number}
*/
angleBetween: function (x1, y1, x2, y2) {
return Math.atan2(x2 - x1, y2 - y1);
},
/**
* Find the angle of a segment from (point1.x, point1.y) -> (point2.x, point2.y).
* @method Phaser.Math#angleBetweenPoints
* @param {Phaser.Point} point1
* @param {Phaser.Point} point2
* @return {number}
*/
angleBetweenPoints: function (point1, point2) {
return Math.atan2(point2.x - point1.x, point2.y - point1.y);
},
/**
* Reverses an angle.
* @method Phaser.Math#reverseAngle
* @param {number} angleRad - The angle to reverse, in radians.
* @return {number} Returns the reverse angle, in radians.
*/
reverseAngle: function (angleRad) {
return this.normalizeAngle(angleRad + Math.PI, true);
},
/**
* Normalizes an angle to the [0,2pi) range.
* @method Phaser.Math#normalizeAngle
* @param {number} angleRad - The angle to normalize, in radians.
* @return {number} Returns the angle, fit within the [0,2pi] range, in radians.
*/
normalizeAngle: function (angleRad) {
angleRad = angleRad % (2 * Math.PI);
return angleRad >= 0 ? angleRad : angleRad + 2 * Math.PI;
},
/**
* Normalizes a latitude to the [-90,90] range. Latitudes above 90 or below -90 are capped, not wrapped.
* @method Phaser.Math#normalizeLatitude
* @param {number} lat - The latitude to normalize, in degrees.
* @return {number} Returns the latitude, fit within the [-90,90] range.
*/
normalizeLatitude: function (lat) {
return Math.max(-90, Math.min(90, lat));
},
/**
* Normalizes a longitude to the [-180,180] range. Longitudes above 180 or below -180 are wrapped.
* @method Phaser.Math#normalizeLongitude
* @param {number} lng - The longitude to normalize, in degrees.
* @return {number} Returns the longitude, fit within the [-180,180] range.
*/
normalizeLongitude: function (lng) {
if (lng % 360 == 180)
{
return 180;
}
lng = lng % 360;
return lng < -180 ? lng + 360 : lng > 180 ? lng - 360 : lng;
},
/**
* Closest angle between two angles from a1 to a2 absolute value the return for exact angle
* @method Phaser.Math#nearestAngleBetween
* @param {number} a1
* @param {number} a2
* @param {boolean} radians - True if angle sizes are expressed in radians.
* @return {number}
*/
nearestAngleBetween: function (a1, a2, radians) {
if (typeof radians === "undefined") { radians = true; }
var rd = (radians) ? Math.PI : 180;
a1 = this.normalizeAngle(a1, radians);
a2 = this.normalizeAngle(a2, radians);
if (a1 < -rd / 2 && a2 > rd / 2)
{
a1 += rd * 2;
}
if (a2 < -rd / 2 && a1 > rd / 2)
{
a2 += rd * 2;
}
return a2 - a1;
},
/**
* Interpolate across the shortest arc between two angles.
* @method Phaser.Math#interpolateAngles
* @param {number} a1 - Description.
* @param {number} a2 - Description.
* @param {number} weight - Description.
* @param {boolean} radians - True if angle sizes are expressed in radians.
* @param {Description} ease - Description.
* @return {number}
*/
interpolateAngles: function (a1, a2, weight, radians, ease) {
if (typeof radians === "undefined") { radians = true; }
if (typeof ease === "undefined") { ease = null; }
a1 = this.normalizeAngle(a1, radians);
a2 = this.normalizeAngleToAnother(a2, a1, radians);
return (typeof ease === 'function') ? ease(weight, a1, a2 - a1, 1) : this.interpolateFloat(a1, a2, weight);
},
/**
* Generate a random bool result based on the chance value.
* <p>
* Returns true or false based on the chance value (default 50%). For example if you wanted a player to have a 30% chance
* of getting a bonus, call chanceRoll(30) - true means the chance passed, false means it failed.
* </p>
* @method Phaser.Math#chanceRoll
* @param {number} chance - The chance of receiving the value. A number between 0 and 100 (effectively 0% to 100%).
* @return {boolean} True if the roll passed, or false otherwise.
*/
chanceRoll: function (chance) {
if (typeof chance === "undefined") { chance = 50; }
if (chance <= 0)
{
return false;
}
else if (chance >= 100)
{
return true;
}
else
{
if (Math.random() * 100 >= chance)
{
return false;
}
else
{
return true;
}
}
},
/**
* Returns an Array containing the numbers from min to max (inclusive).
*
* @method Phaser.Math#numberArray
* @param {number} min - The minimum value the array starts with.
* @param {number} max - The maximum value the array contains.
* @return {array} The array of number values.
*/
numberArray: function (min, max) {
var result = [];
for (var i = min; i <= max; i++)
{
result.push(i);
}
return result;
},
/**
* Adds the given amount to the value, but never lets the value go over the specified maximum.
*
* @method Phaser.Math#maxAdd
* @param {number} value - The value to add the amount to.
* @param {number} amount - The amount to add to the value.
* @param {number} max- The maximum the value is allowed to be.
* @return {number}
*/
maxAdd: function (value, amount, max) {
value += amount;
if (value > max)
{
value = max;
}
return value;
},
/**
* Subtracts the given amount from the value, but never lets the value go below the specified minimum.
*
* @method Phaser.Math#minSub
* @param {number} value - The base value.
* @param {number} amount - The amount to subtract from the base value.
* @param {number} min - The minimum the value is allowed to be.
* @return {number} The new value.
*/
minSub: function (value, amount, min) {
value -= amount;
if (value < min)
{
value = min;
}
return value;
},
/**
* Ensures that the value always stays between min and max, by wrapping the value around.
* max should be larger than min, or the function will return 0.
*
* @method Phaser.Math#wrap
* @param {number} value - The value to wrap.
* @param {number} min - The minimum the value is allowed to be.
* @param {number} max - The maximum the value is allowed to be.
* @return {number} The wrapped value.
*/
wrap: function (value, min, max) {
var range = max - min;
if (range <= 0)
{
return 0;
}
var result = (value - min) % range;
if (result < 0)
{
result += range;
}
return result + min;
},
/**
* Adds value to amount and ensures that the result always stays between 0 and max, by wrapping the value around.
* Values must be positive integers, and are passed through Math.abs.
*
* @method Phaser.Math#wrapValue
* @param {number} value - The value to add the amount to.
* @param {number} amount - The amount to add to the value.
* @param {number} max - The maximum the value is allowed to be.
* @return {number} The wrapped value.
*/
wrapValue: function (value, amount, max) {
var diff;
value = Math.abs(value);
amount = Math.abs(amount);
max = Math.abs(max);
diff = (value + amount) % max;
return diff;
},
/**
* Randomly returns either a 1 or -1.
*
* @method Phaser.Math#randomSign
* @return {number} 1 or -1
*/
randomSign: function () {
return (Math.random() > 0.5) ? 1 : -1;
},
/**
* Returns true if the number given is odd.
*
* @method Phaser.Math#isOdd
* @param {number} n - The number to check.
* @return {boolean} True if the given number is odd. False if the given number is even.
*/
isOdd: function (n) {
return (n & 1);
},
/**
* Returns true if the number given is even.
*
* @method Phaser.Math#isEven
* @param {number} n - The number to check.
* @return {boolean} True if the given number is even. False if the given number is odd.
*/
isEven: function (n) {
if (n & 1)
{
return false;
}
else
{
return true;
}
},
/**
* Significantly faster version of Math.max
* See http://jsperf.com/math-s-min-max-vs-homemade/5
*
* @method Phaser.Math#max
* @return {number} The highest value from those given.
*/
max: function () {
for (var i = 1, max = 0, len = arguments.length; i < len; i++)
{
if (arguments[max] < arguments[i])
{
max = i;
}
}
return arguments[max];
},
/**
* Updated version of Math.min that can be passed either an array of numbers or the numbers as parameters.
* See http://jsperf.com/math-s-min-max-vs-homemade/5
*
* @method Phaser.Math#min
* @return {number} The lowest value from those given.
*/
min: function () {
if (arguments.length === 1 && typeof arguments[0] === 'object')
{
var data = arguments[0];
}
else
{
var data = arguments;
}
for (var i = 1, min = 0, len = data.length; i < len; i++)
{
if (data[i] < data[min])
{
min = i;
}
}
return data[min];
},
/**
* Updated version of Math.max that can be passed either an array of numbers or the numbers as parameters.
*
* @method Phaser.Math#max
* @return {number} The largest value from those given.
*/
max: function () {
if (arguments.length === 1 && typeof arguments[0] === 'object')
{
var data = arguments[0];
}
else
{
var data = arguments;
}
for (var i = 1, max = 0, len = data.length; i < len; i++)
{
if (data[i] > data[max])
{
max = i;
}
}
return data[max];
},
/**
* Updated version of Math.min that can be passed a property and either an array of objects or the objects as parameters.
* It will find the lowest matching property value from the given objects.
*
* @method Phaser.Math#minProperty
* @return {number} The lowest value from those given.
*/
minProperty: function (property) {
if (arguments.length === 2 && typeof arguments[1] === 'object')
{
var data = arguments[1];
}
else
{
var data = arguments.slice(1);
}
for (var i = 1, min = 0, len = data.length; i < len; i++)
{
if (data[i][property] < data[min][property])
{
min = i;
}
}
return data[min][property];
},
/**
* Updated version of Math.max that can be passed a property and either an array of objects or the objects as parameters.
* It will find the largest matching property value from the given objects.
*
* @method Phaser.Math#maxProperty
* @return {number} The largest value from those given.
*/
maxProperty: function (property) {
if (arguments.length === 2 && typeof arguments[1] === 'object')
{
var data = arguments[1];
}
else
{
var data = arguments.slice(1);
}
for (var i = 1, max = 0, len = data.length; i < len; i++)
{
if (data[i][property] > data[max][property])
{
max = i;
}
}
return data[max][property];
},
/**
* Keeps an angle value between -180 and +180<br>
* Should be called whenever the angle is updated on the Sprite to stop it from going insane.
*
* @method Phaser.Math#wrapAngle
* @param {number} angle - The angle value to check
* @return {number} The new angle value, returns the same as the input angle if it was within bounds.
*/
wrapAngle: function (angle) {
return this.wrap(angle, -180, 180);
},
/**
* Keeps an angle value between the given min and max values.
*
* @method Phaser.Math#angleLimit
* @param {number} angle - The angle value to check. Must be between -180 and +180.
* @param {number} min - The minimum angle that is allowed (must be -180 or greater).
* @param {number} max - The maximum angle that is allowed (must be 180 or less).
* @return {number} The new angle value, returns the same as the input angle if it was within bounds
*/
angleLimit: function (angle, min, max) {
var result = angle;
if (angle > max)
{
result = max;
}
else if (angle < min)
{
result = min;
}
return result;
},
/**
* A Linear Interpolation Method, mostly used by Phaser.Tween.
* @method Phaser.Math#linearInterpolation
* @param {number} v
* @param {number} k
* @return {number}
*/
linearInterpolation: function (v, k) {
var m = v.length - 1;
var f = m * k;
var i = Math.floor(f);
if (k < 0)
{
return this.linear(v[0], v[1], f);
}
if (k > 1)
{
return this.linear(v[m], v[m - 1], m - f);
}
return this.linear(v[i], v[i + 1 > m ? m : i + 1], f - i);
},
/**
* A Bezier Interpolation Method, mostly used by Phaser.Tween.
* @method Phaser.Math#bezierInterpolation
* @param {number} v
* @param {number} k
* @return {number}
*/
bezierInterpolation: function (v, k) {
var b = 0;
var n = v.length - 1;
for (var i = 0; i <= n; i++)
{
b += Math.pow(1 - k, n - i) * Math.pow(k, i) * v[i] * this.bernstein(n, i);
}
return b;
},
/**
* A Catmull Rom Interpolation Method, mostly used by Phaser.Tween.
* @method Phaser.Math#catmullRomInterpolation
* @param {number} v
* @param {number} k
* @return {number}
*/
catmullRomInterpolation: function (v, k) {
var m = v.length - 1;
var f = m * k;
var i = Math.floor(f);
if (v[0] === v[m])
{
if (k < 0)
{
i = Math.floor(f = m * (1 + k));
}
return this.catmullRom(v[(i - 1 + m) % m], v[i], v[(i + 1) % m], v[(i + 2) % m], f - i);
}
else
{
if (k < 0)
{
return v[0] - (this.catmullRom(v[0], v[0], v[1], v[1], -f) - v[0]);
}
if (k > 1)
{
return v[m] - (this.catmullRom(v[m], v[m], v[m - 1], v[m - 1], f - m) - v[m]);
}
return this.catmullRom(v[i ? i - 1 : 0], v[i], v[m < i + 1 ? m : i + 1], v[m < i + 2 ? m : i + 2], f - i);
}
},
/**
* Description.
* @method Phaser.Math#Linear
* @param {number} p0
* @param {number} p1
* @param {number} t
* @return {number}
*/
linear: function (p0, p1, t) {
return (p1 - p0) * t + p0;
},
/**
* @method Phaser.Math#bernstein
* @param {number} n
* @param {number} i
* @return {number}
*/
bernstein: function (n, i) {
return this.factorial(n) / this.factorial(i) / this.factorial(n - i);
},
/**
* Description.
* @method Phaser.Math#catmullRom
* @param {number} p0
* @param {number} p1
* @param {number} p2
* @param {number} p3
* @param {number} t
* @return {number}
*/
catmullRom: function (p0, p1, p2, p3, t) {
var v0 = (p2 - p0) * 0.5, v1 = (p3 - p1) * 0.5, t2 = t * t, t3 = t * t2;
return (2 * p1 - 2 * p2 + v0 + v1) * t3 + (-3 * p1 + 3 * p2 - 2 * v0 - v1) * t2 + v0 * t + p1;
},
/**
* @method Phaser.Math#difference
* @param {number} a
* @param {number} b
* @return {number}
*/
difference: function (a, b) {
return Math.abs(a - b);
},
/**
* Fetch a random entry from the given array.
* Will return null if random selection is missing, or array has no entries.
*
* @method Phaser.Math#getRandom
* @param {array} objects - An array of objects.
* @param {number} startIndex - Optional offset off the front of the array. Default value is 0, or the beginning of the array.
* @param {number} length - Optional restriction on the number of values you want to randomly select from.
* @return {object} The random object that was selected.
*/
getRandom: function (objects, startIndex, length) {
if (typeof startIndex === "undefined") { startIndex = 0; }
if (typeof length === "undefined") { length = 0; }
if (objects != null) {
var l = length;
if ((l === 0) || (l > objects.length - startIndex))
{
l = objects.length - startIndex;
}
if (l > 0)
{
return objects[startIndex + Math.floor(Math.random() * l)];
}
}
return null;
},
/**
* Round down to the next whole number. E.g. floor(1.7) == 1, and floor(-2.7) == -2.
*
* @method Phaser.Math#floor
* @param {number} Value Any number.
* @return {number} The rounded value of that number.
*/
floor: function (value) {
var n = value | 0;
return (value > 0) ? (n) : ((n != value) ? (n - 1) : (n));
},
/**
* Round up to the next whole number. E.g. ceil(1.3) == 2, and ceil(-2.3) == -3.
*
* @method Phaser.Math#ceil
* @param {number} value - Any number.
* @return {number} The rounded value of that number.
*/
ceil: function (value) {
var n = value | 0;
return (value > 0) ? ((n != value) ? (n + 1) : (n)) : (n);
},
/**
* Generate a sine and cosine table simultaneously and extremely quickly. Based on research by Franky of scene.at
* <p>
* The parameters allow you to specify the length, amplitude and frequency of the wave. Once you have called this function
* you should get the results via getSinTable() and getCosTable(). This generator is fast enough to be used in real-time.
* </p>
* @method Phaser.Math#sinCosGenerator
* @param {number} length - The length of the wave
* @param {number} sinAmplitude - The amplitude to apply to the sine table (default 1.0) if you need values between say -+ 125 then give 125 as the value
* @param {number} cosAmplitude - The amplitude to apply to the cosine table (default 1.0) if you need values between say -+ 125 then give 125 as the value
* @param {number} frequency - The frequency of the sine and cosine table data
* @return {Array} Returns the sine table
*/
sinCosGenerator: function (length, sinAmplitude, cosAmplitude, frequency) {
if (typeof sinAmplitude === "undefined") { sinAmplitude = 1.0; }
if (typeof cosAmplitude === "undefined") { cosAmplitude = 1.0; }
if (typeof frequency === "undefined") { frequency = 1.0; }
var sin = sinAmplitude;
var cos = cosAmplitude;
var frq = frequency * Math.PI / length;
var cosTable = [];
var sinTable = [];
for (var c = 0; c < length; c++) {
cos -= sin * frq;
sin += cos * frq;
cosTable[c] = cos;
sinTable[c] = sin;
}
return { sin: sinTable, cos: cosTable, length: length };
},
/**
* Removes the top element from the stack and re-inserts it onto the bottom, then returns it.
* The original stack is modified in the process. This effectively moves the position of the data from the start to the end of the table.
*
* @method Phaser.Math#shift
* @param {array} stack - The array to shift.
* @return {any} The shifted value.
*/
shift: function (stack) {
var s = stack.shift();
stack.push(s);
return s;
},
/**
* Shuffles the data in the given array into a new order
* @method Phaser.Math#shuffleArray
* @param {array} array - The array to shuffle
* @return {array} The array
*/
shuffleArray: function (array) {
for (var i = array.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return array;
},
/**
* Returns the distance between the two given set of coordinates.
*
* @method Phaser.Math#distance
* @param {number} x1
* @param {number} y1
* @param {number} x2
* @param {number} y2
* @return {number} The distance between the two sets of coordinates.
*/
distance: function (x1, y1, x2, y2) {
var dx = x1 - x2;
var dy = y1 - y2;
return Math.sqrt(dx * dx + dy * dy);
},
/**
* Returns the distance between the two given set of coordinates at the power given.
*
* @method Phaser.Math#distancePow
* @param {number} x1
* @param {number} y1
* @param {number} x2
* @param {number} y2
* @param {number} [pow=2]
* @return {number} The distance between the two sets of coordinates.
*/
distancePow: function (x1, y1, x2, y2, pow) {
if (typeof pow === 'undefined') { pow = 2; }
return Math.sqrt(Math.pow(x2 - x1, pow) + Math.pow(y2 - y1, pow));
},
/**
* Returns the rounded distance between the two given set of coordinates.
*
* @method Phaser.Math#distanceRounded
* @param {number} x1
* @param {number} y1
* @param {number} x2
* @param {number} y2
* @return {number} The distance between this Point object and the destination Point object.
*/
distanceRounded: function (x1, y1, x2, y2) {
return Math.round(Phaser.Math.distance(x1, y1, x2, y2));
},
/**
* Force a value within the boundaries of two values.
* Clamp value to range <a, b>
*
* @method Phaser.Math#clamp
* @param {number} x
* @param {number} a
* @param {number} b
* @return {number}
*/
clamp: function ( x, a, b ) {
return ( x < a ) ? a : ( ( x > b ) ? b : x );
},
/**
* Clamp value to range <a, inf).
*
* @method Phaser.Math#clampBottom
* @param {number} x
* @param {number} a
* @return {number}
*/
clampBottom: function ( x, a ) {
return x < a ? a : x;
},
/**
* Checks if two values are within the given tolerance of each other.
*
* @method Phaser.Math#within
* @param {number} a - The first number to check
* @param {number} b - The second number to check
* @param {number} tolerance - The tolerance. Anything equal to or less than this is considered within the range.
* @return {boolean} True if a is <= tolerance of b.
*/
within: function ( a, b, tolerance ) {
return (Math.abs(a - b) <= tolerance);
},
/**
* Linear mapping from range <a1, a2> to range <b1, b2>
*
* @method Phaser.Math#mapLinear
* @param {number} x
* @param {number} a1
* @param {number} a1
* @param {number} a2
* @param {number} b1
* @param {number} b2
* @return {number}
*/
mapLinear: function ( x, a1, a2, b1, b2 ) {
return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
},
/**
* Smoothstep function as detailed at http://en.wikipedia.org/wiki/Smoothstep
*
* @method Phaser.Math#smoothstep
* @param {number} x
* @param {number} min
* @param {number} max
* @return {number}
*/
smoothstep: function ( x, min, max ) {
if (x <= min)
{
return 0;
}
if (x >= max)
{
return 1;
}
x = (x - min) / (max - min);
return x * x * (3 - 2 * x);
},
/**
* Smootherstep function as detailed at http://en.wikipedia.org/wiki/Smoothstep
*
* @method Phaser.Math#smootherstep
* @param {number} x
* @param {number} min
* @param {number} max
* @return {number}
*/
smootherstep: function ( x, min, max ) {
if (x <= min)
{
return 0;
}
if (x >= max)
{
return 1;
}
x = (x - min) / (max - min);
return x * x * x * (x * (x * 6 - 15) + 10);
},
/**
* A value representing the sign of the value.
* -1 for negative, +1 for positive, 0 if value is 0
*
* @method Phaser.Math#sign
* @param {number} x
* @return {number}
*/
sign: function ( x ) {
return ( x < 0 ) ? -1 : ( ( x > 0 ) ? 1 : 0 );
},
/**
* Convert p2 physics value (meters) to pixel scale.
*
* @method Phaser.Math#p2px
* @param {number} v - The value to convert.
* @return {number} The scaled value.
*/
p2px: function (v) {
return v *= 20;
},
/**
* Convert pixel value to p2 physics scale (meters).
*
* @method Phaser.Math#px2p
* @param {number} v - The value to convert.
* @return {number} The scaled value.
*/
px2p: function (v) {
return v * 0.05;
},
/**
* Convert p2 physics value (meters) to pixel scale and inverses it.
*
* @method Phaser.Math#p2pxi
* @param {number} v - The value to convert.
* @return {number} The scaled value.
*/
p2pxi: function (v) {
return v *= -20;
},
/**
* Convert pixel value to p2 physics scale (meters) and inverses it.
*
* @method Phaser.Math#px2pi
* @param {number} v - The value to convert.
* @return {number} The scaled value.
*/
px2pi: function (v) {
return v * -0.05;
},
/**
* Convert degrees to radians.
*
* @method Phaser.Math#degToRad
* @return {function}
*/
degToRad: function() {
var degreeToRadiansFactor = Math.PI / 180;
return function ( degrees ) {
return degrees * degreeToRadiansFactor;
};
}(),
/**
* Convert degrees to radians.
*
* @method Phaser.Math#radToDeg
* @return {function}
*/
radToDeg: function() {
var radianToDegreesFactor = 180 / Math.PI;
return function ( radians ) {
return radians * radianToDegreesFactor;
};
}()
};
/* jshint noempty: false */
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2014 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* Phaser.RandomDataGenerator constructor.
*
* @class Phaser.RandomDataGenerator
* @classdesc An extremely useful repeatable random data generator. Access it via Phaser.Game.rnd
* Based on Nonsense by Josh Faul https://github.com/jocafa/Nonsense.
* Random number generator from http://baagoe.org/en/wiki/Better_random_numbers_for_javascript
*
* @constructor
* @param {array} seeds
*/
Phaser.RandomDataGenerator = function (seeds) {
if (typeof seeds === "undefined") { seeds = []; }
/**
* @property {number} c - Internal var.
* @private
*/
this.c = 1;
/**
* @property {number} s0 - Internal var.
* @private
*/
this.s0 = 0;
/**
* @property {number} s1 - Internal var.
* @private
*/
this.s1 = 0;
/**
* @property {number} s2 - Internal var.
* @private
*/
this.s2 = 0;
this.sow(seeds);
};
Phaser.RandomDataGenerator.prototype = {
/**
* Private random helper.
* @method Phaser.RandomDataGenerator#rnd
* @private
* @return {number}
*/
rnd: function () {
var t = 2091639 * this.s0 + this.c * 2.3283064365386963e-10; // 2^-32
this.c = t | 0;
this.s0 = this.s1;
this.s1 = this.s2;
this.s2 = t - this.c;
return this.s2;
},
/**
* Reset the seed of the random data generator.
*
* @method Phaser.RandomDataGenerator#sow
* @param {array} seeds
*/
sow: function (seeds) {
if (typeof seeds === "undefined") { seeds = []; }
this.s0 = this.hash(' ');
this.s1 = this.hash(this.s0);
this.s2 = this.hash(this.s1);
this.c = 1;
var seed;
for (var i = 0; seed = seeds[i++]; )
{
this.s0 -= this.hash(seed);
this.s0 += ~~(this.s0 < 0);
this.s1 -= this.hash(seed);
this.s1 += ~~(this.s1 < 0);
this.s2 -= this.hash(seed);
this.s2 += ~~(this.s2 < 0);
}
},
/**
* Internal method that creates a seed hash.
* @method Phaser.RandomDataGenerator#hash
* @param {Any} data
* @private
* @return {number} hashed value.
*/
hash: function (data) {
var h, i, n;
n = 0xefc8249d;
data = data.toString();
for (i = 0; i < data.length; i++) {
n += data.charCodeAt(i);
h = 0.02519603282416938 * n;
n = h >>> 0;
h -= n;
h *= n;
n = h >>> 0;
h -= n;
n += h * 0x100000000;// 2^32
}
return (n >>> 0) * 2.3283064365386963e-10;// 2^-32
},
/**
* Returns a random integer between 0 and 2^32.
* @method Phaser.RandomDataGenerator#integer
* @return {number} A random integer between 0 and 2^32.
*/
integer: function() {
return this.rnd.apply(this) * 0x100000000;// 2^32
},
/**
* Returns a random real number between 0 and 1.
* @method Phaser.RandomDataGenerator#frac
* @return {number} A random real number between 0 and 1.
*/
frac: function() {
return this.rnd.apply(this) + (this.rnd.apply(this) * 0x200000 | 0) * 1.1102230246251565e-16;// 2^-53
},
/**
* Returns a random real number between 0 and 2^32.
* @method Phaser.RandomDataGenerator#real
* @return {number} A random real number between 0 and 2^32.
*/
real: function() {
return this.integer() + this.frac();
},
/**
* Returns a random integer between and including min and max.
*
* @method Phaser.RandomDataGenerator#integerInRange
* @param {number} min - The minimum value in the range.
* @param {number} max - The maximum value in the range.
* @return {number} A random number between min and max.
*/
integerInRange: function (min, max) {
return Math.round(this.realInRange(min, max));
},
/**
* Returns a random real number between min and max.
* @method Phaser.RandomDataGenerator#realInRange
* @param {number} min - The minimum value in the range.
* @param {number} max - The maximum value in the range.
* @return {number} A random number between min and max.
*/
realInRange: function (min, max) {
return this.frac() * (max - min) + min;
},
/**
* Returns a random real number between -1 and 1.
* @method Phaser.RandomDataGenerator#normal
* @return {number} A random real number between -1 and 1.
*/
normal: function () {
return 1 - 2 * this.frac();
},
/**
* Returns a valid RFC4122 version4 ID hex string from https://gist.github.com/1308368
* @method Phaser.RandomDataGenerator#uuid
* @return {string} A valid RFC4122 version4 ID hex string
*/
uuid: function () {
var a = '';
var b = '';
for (b = a = ''; a++ < 36; b +=~a % 5 | a * 3&4 ? (a^15 ? 8^this.frac() * (a^20 ? 16 : 4) : 4).toString(16) : '-')
{
}
return b;
},
/**
* Returns a random member of `array`.
* @method Phaser.RandomDataGenerator#pick
* @param {Array} ary - An Array to pick a random member of.
* @return {any} A random member of the array.
*/
pick: function (ary) {
return ary[this.integerInRange(0, ary.length)];
},
/**
* Returns a random member of `array`, favoring the earlier entries.
* @method Phaser.RandomDataGenerator#weightedPick
* @param {Array} ary - An Array to pick a random member of.
* @return {any} A random member of the array.
*/
weightedPick: function (ary) {
return ary[~~(Math.pow(this.frac(), 2) * ary.length)];
},
/**
* Returns a random timestamp between min and max, or between the beginning of 2000 and the end of 2020 if min and max aren't specified.
* @method Phaser.RandomDataGenerator#timestamp
* @param {number} min - The minimum value in the range.
* @param {number} max - The maximum value in the range.
* @return {number} A random timestamp between min and max.
*/
timestamp: function (min, max) {
return this.realInRange(min || 946684800000, max || 1577862000000);
},
/**
* Returns a random angle between -180 and 180.
* @method Phaser.RandomDataGenerator#angle
* @return {number} A random number between -180 and 180.
*/
angle: function() {
return this.integerInRange(-180, 180);
}
};
Phaser.RandomDataGenerator.prototype.constructor = Phaser.RandomDataGenerator;
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2014 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* Javascript QuadTree
* @version 1.0
* @author Timo Hausmann
*
* @version 1.2, September 4th 2013
* @author Richard Davey
* The original code was a conversion of the Java code posted to GameDevTuts. However I've tweaked
* it massively to add node indexing, removed lots of temp. var creation and significantly
* increased performance as a result.
*
* Original version at https://github.com/timohausmann/quadtree-js/
*/
/**
* @copyright © 2012 Timo Hausmann
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/**
* QuadTree Constructor
*
* @class Phaser.QuadTree
* @classdesc A QuadTree implementation. The original code was a conversion of the Java code posted to GameDevTuts.
* However I've tweaked it massively to add node indexing, removed lots of temp. var creation and significantly increased performance as a result.
* Original version at https://github.com/timohausmann/quadtree-js/
* @constructor
* @param {number} x - The top left coordinate of the quadtree.
* @param {number} y - The top left coordinate of the quadtree.
* @param {number} width - The width of the quadtree in pixels.
* @param {number} height - The height of the quadtree in pixels.
* @param {number} [maxObjects=10] - The maximum number of objects per node.
* @param {number} [maxLevels=4] - The maximum number of levels to iterate to.
* @param {number} [level=0] - Which level is this?
*/
Phaser.QuadTree = function(x, y, width, height, maxObjects, maxLevels, level) {
/**
* @property {number} maxObjects - The maximum number of objects per node.
* @default
*/
this.maxObjects = 10;
/**
* @property {number} maxLevels - The maximum number of levels to break down to.
* @default
*/
this.maxLevels = 4;
/**
* @property {number} level - The current level.
*/
this.level = 0;
/**
* @property {object} bounds - Object that contains the quadtree bounds.
*/
this.bounds;
/**
* @property {array} objects - Array of quadtree children.
*/
this.objects;
/**
* @property {array} nodes - Array of associated child nodes.
*/
this.nodes;
this.reset(x, y, width, height, maxObjects, maxLevels, level);
};
Phaser.QuadTree.prototype = {
/**
* Resets the QuadTree.
*
* @method Phaser.QuadTree#reset
* @param {number} x - The top left coordinate of the quadtree.
* @param {number} y - The top left coordinate of the quadtree.
* @param {number} width - The width of the quadtree in pixels.
* @param {number} height - The height of the quadtree in pixels.
* @param {number} [maxObjects=10] - The maximum number of objects per node.
* @param {number} [maxLevels=4] - The maximum number of levels to iterate to.
* @param {number} [level=0] - Which level is this?
*/
reset: function (x, y, width, height, maxObjects, maxLevels, level) {
this.maxObjects = maxObjects || 10;
this.maxLevels = maxLevels || 4;
this.level = level || 0;
this.bounds = {
x: Math.round(x),
y: Math.round(y),
width: width,
height: height,
subWidth: Math.floor(width / 2),
subHeight: Math.floor(height / 2),
right: Math.round(x) + Math.floor(width / 2),
bottom: Math.round(y) + Math.floor(height / 2)
};
this.objects = [];
this.nodes = [];
},
/**
* Populates this quadtree with the children of the given Group. In order to be added the child must exist and have a body property.
*
* @method Phaser.QuadTree#populate
* @param {Phaser.Group} group - The Group to add to the quadtree.
*/
populate: function (group) {
group.forEach(this.populateHandler, this, true);
},
/**
* Handler for the populate method.
*
* @method Phaser.QuadTree#populateHandler
* @param {Phaser.Sprite|object} sprite - The Sprite to check.
*/
populateHandler: function (sprite) {
if (sprite.body && sprite.exists)
{
this.insert(sprite.body);
}
},
/**
* Split the node into 4 subnodes
*
* @method Phaser.QuadTree#split
*/
split: function () {
this.level++;
// top right node
this.nodes[0] = new Phaser.QuadTree(this.bounds.right, this.bounds.y, this.bounds.subWidth, this.bounds.subHeight, this.maxObjects, this.maxLevels, this.level);
// top left node
this.nodes[1] = new Phaser.QuadTree(this.bounds.x, this.bounds.y, this.bounds.subWidth, this.bounds.subHeight, this.maxObjects, this.maxLevels, this.level);
// bottom left node
this.nodes[2] = new Phaser.QuadTree(this.bounds.x, this.bounds.bottom, this.bounds.subWidth, this.bounds.subHeight, this.maxObjects, this.maxLevels, this.level);
// bottom right node
this.nodes[3] = new Phaser.QuadTree(this.bounds.right, this.bounds.bottom, this.bounds.subWidth, this.bounds.subHeight, this.maxObjects, this.maxLevels, this.level);
},
/**
* Insert the object into the node. If the node exceeds the capacity, it will split and add all objects to their corresponding subnodes.
*
* @method Phaser.QuadTree#insert
* @param {Phaser.Physics.Arcade.Body|object} body - The Body object to insert into the quadtree. Can be any object so long as it exposes x, y, right and bottom properties.
*/
insert: function (body) {
var i = 0;
var index;
// if we have subnodes ...
if (this.nodes[0] != null)
{
index = this.getIndex(body);
if (index !== -1)
{
this.nodes[index].insert(body);
return;
}
}
this.objects.push(body);
if (this.objects.length > this.maxObjects && this.level < this.maxLevels)
{
// Split if we don't already have subnodes
if (this.nodes[0] == null)
{
this.split();
}
// Add objects to subnodes
while (i < this.objects.length)
{
index = this.getIndex(this.objects[i]);
if (index !== -1)
{
// this is expensive - see what we can do about it
this.nodes[index].insert(this.objects.splice(i, 1)[0]);
}
else
{
i++;
}
}
}
},
/**
* Determine which node the object belongs to.
*
* @method Phaser.QuadTree#getIndex
* @param {Phaser.Rectangle|object} rect - The bounds in which to check.
* @return {number} index - Index of the subnode (0-3), or -1 if rect cannot completely fit within a subnode and is part of the parent node.
*/
getIndex: function (rect) {
// default is that rect doesn't fit, i.e. it straddles the internal quadrants
var index = -1;
if (rect.x < this.bounds.right && rect.right < this.bounds.right)
{
if (rect.y < this.bounds.bottom && rect.bottom < this.bounds.bottom)
{
// rect fits within the top-left quadrant of this quadtree
index = 1;
}
else if (rect.y > this.bounds.bottom)
{
// rect fits within the bottom-left quadrant of this quadtree
index = 2;
}
}
else if (rect.x > this.bounds.right)
{
// rect can completely fit within the right quadrants
if (rect.y < this.bounds.bottom && rect.bottom < this.bounds.bottom)
{
// rect fits within the top-right quadrant of this quadtree
index = 0;
}
else if (rect.y > this.bounds.bottom)
{
// rect fits within the bottom-right quadrant of this quadtree
index = 3;
}
}
return index;
},
/**
* Return all objects that could collide with the given Sprite.
*
* @method Phaser.QuadTree#retrieve
* @param {Phaser.Sprite} sprite - The sprite to check against.
* @return {array} - Array with all detected objects.
*/
retrieve: function (sprite) {
var returnObjects = this.objects;
// sprite.body.quadTreeIndex = this.getIndex(sprite.body);
var index = this.getIndex(sprite.body);
if (this.nodes[0])
{
// If rect fits into a subnode ..
if (index !== -1)
{
returnObjects = returnObjects.concat(this.nodes[index].retrieve(sprite));
}
else
{
// If rect does not fit into a subnode, check it against all subnodes (unrolled for speed)
returnObjects = returnObjects.concat(this.nodes[0].retrieve(sprite));
returnObjects = returnObjects.concat(this.nodes[1].retrieve(sprite));
returnObjects = returnObjects.concat(this.nodes[2].retrieve(sprite));
returnObjects = returnObjects.concat(this.nodes[3].retrieve(sprite));
}
}
return returnObjects;
},
/**
* Clear the quadtree.
* @method Phaser.QuadTree#clear
*/
clear: function () {
this.objects.length = 0;
var i = this.nodes.length;
while (i--)
{
this.nodes[i].clear();
this.nodes.splice(i, 1);
}
this.nodes.length = 0;
}
};
Phaser.QuadTree.prototype.constructor = Phaser.QuadTree;
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2014 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* Phaser.Net handles browser URL related tasks such as checking host names, domain names and query string manipulation.
*
* @class Phaser.Net
* @constructor
* @param {Phaser.Game} game - A reference to the currently running game.
*/
Phaser.Net = function (game) {
this.game = game;
};
Phaser.Net.prototype = {
/**
* Returns the hostname given by the browser.
*
* @method Phaser.Net#getHostName
* @return {string}
*/
getHostName: function () {
if (window.location && window.location.hostname) {
return window.location.hostname;
}
return null;
},
/**
* Compares the given domain name against the hostname of the browser containing the game.
* If the domain name is found it returns true.
* You can specify a part of a domain, for example 'google' would match 'google.com', 'google.co.uk', etc.
* Do not include 'http://' at the start.
*
* @method Phaser.Net#checkDomainName
* @param {string} domain
* @return {boolean} true if the given domain fragment can be found in the window.location.hostname
*/
checkDomainName: function (domain) {
return window.location.hostname.indexOf(domain) !== -1;
},
/**
* Updates a value on the Query String and returns it in full.
* If the value doesn't already exist it is set.
* If the value exists it is replaced with the new value given. If you don't provide a new value it is removed from the query string.
* Optionally you can redirect to the new url, or just return it as a string.
*
* @method Phaser.Net#updateQueryString
* @param {string} key - The querystring key to update.
* @param {string} value - The new value to be set. If it already exists it will be replaced.
* @param {boolean} redirect - If true the browser will issue a redirect to the url with the new querystring.
* @param {string} url - The URL to modify. If none is given it uses window.location.href.
* @return {string} If redirect is false then the modified url and query string is returned.
*/
updateQueryString: function (key, value, redirect, url) {
if (typeof redirect === "undefined") { redirect = false; }
if (typeof url === "undefined" || url === '') { url = window.location.href; }
var output = '';
var re = new RegExp("([?|&])" + key + "=.*?(&|#|$)(.*)", "gi");
if (re.test(url))
{
if (typeof value !== 'undefined' && value !== null)
{
output = url.replace(re, '$1' + key + "=" + value + '$2$3');
}
else
{
output = url.replace(re, '$1$3').replace(/(&|\?)$/, '');
}
}
else
{
if (typeof value !== 'undefined' && value !== null)
{
var separator = url.indexOf('?') !== -1 ? '&' : '?';
var hash = url.split('#');
url = hash[0] + separator + key + '=' + value;
if (hash[1]) {
url += '#' + hash[1];
}
output = url;
}
else
{
output = url;
}
}
if (redirect)
{
window.location.href = output;
}
else
{
return output;
}
},
/**
* Returns the Query String as an object.
* If you specify a parameter it will return just the value of that parameter, should it exist.
*
* @method Phaser.Net#getQueryString
* @param {string} [parameter=''] - If specified this will return just the value for that key.
* @return {string|object} An object containing the key value pairs found in the query string or just the value if a parameter was given.
*/
getQueryString: function (parameter) {
if (typeof parameter === "undefined") { parameter = ''; }
var output = {};
var keyValues = location.search.substring(1).split('&');
for (var i in keyValues)
{
var key = keyValues[i].split('=');
if (key.length > 1)
{
if (parameter && parameter == this.decodeURI(key[0]))
{
return this.decodeURI(key[1]);
}
else
{
output[this.decodeURI(key[0])] = this.decodeURI(key[1]);
}
}
}
return output;
},
/**
* Returns the Query String as an object.
* If you specify a parameter it will return just the value of that parameter, should it exist.
*
* @method Phaser.Net#decodeURI
* @param {string} value - The URI component to be decoded.
* @return {string} The decoded value.
*/
decodeURI: function (value) {
return decodeURIComponent(value.replace(/\+/g, " "));
}
};
Phaser.Net.prototype.constructor = Phaser.Net;
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2014 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* Phaser - TweenManager
*
* @class Phaser.TweenManager
* @classdesc
* Phaser.Game has a single instance of the TweenManager through which all Tween objects are created and updated.
* Tweens are hooked into the game clock and pause system, adjusting based on the game state.
*
* TweenManager is based heavily on tween.js by http://soledadpenades.com.
* The difference being that tweens belong to a games instance of TweenManager, rather than to a global TWEEN object.
* It also has callbacks swapped for Signals and a few issues patched with regard to properties and completion errors.
* Please see https://github.com/sole/tween.js for a full list of contributors.
* @constructor
*
* @param {Phaser.Game} game - A reference to the currently running game.
*/
Phaser.TweenManager = function (game) {
/**
* @property {Phaser.Game} game - Local reference to game.
*/
this.game = game;
/**
* @property {array<Phaser.Tween>} _tweens - All of the currently running tweens.
* @private
*/
this._tweens = [];
/**
* @property {array<Phaser.Tween>} _add - All of the tweens queued to be added in the next update.
* @private
*/
this._add = [];
this.game.onPause.add(this._pauseAll, this);
this.game.onResume.add(this._resumeAll, this);
};
Phaser.TweenManager.prototype = {
/**
* Get all the tween objects in an array.
* @method Phaser.TweenManager#getAll
* @returns {Phaser.Tween[]} Array with all tween objects.
*/
getAll: function () {
return this._tweens;
},
/**
* Remove all tweens running and in the queue. Doesn't call any of the tween onComplete events.
* @method Phaser.TweenManager#removeAll
*/
removeAll: function () {
for (var i = 0; i < this._tweens.length; i++)
{
this._tweens[i].pendingDelete = true;
}
this._add = [];
},
/**
* Add a new tween into the TweenManager.
*
* @method Phaser.TweenManager#add
* @param {Phaser.Tween} tween - The tween object you want to add.
* @returns {Phaser.Tween} The tween object you added to the manager.
*/
add: function (tween) {
tween._manager = this;
this._add.push(tween);
},
/**
* Create a tween object for a specific object. The object can be any JavaScript object or Phaser object such as Sprite.
*
* @method Phaser.TweenManager#create
* @param {Object} object - Object the tween will be run on.
* @returns {Phaser.Tween} The newly created tween object.
*/
create: function (object) {
return new Phaser.Tween(object, this.game, this);
},
/**
* Remove a tween from this manager.
*
* @method Phaser.TweenManager#remove
* @param {Phaser.Tween} tween - The tween object you want to remove.
*/
remove: function (tween) {
var i = this._tweens.indexOf(tween);
if (i !== -1)
{
this._tweens[i].pendingDelete = true;
}
},
/**
* Update all the tween objects you added to this manager.
*
* @method Phaser.TweenManager#update
* @returns {boolean} Return false if there's no tween to update, otherwise return true.
*/
update: function () {
if (this._tweens.length === 0 && this._add.length === 0)
{
return false;
}
var i = 0;
var numTweens = this._tweens.length;
while (i < numTweens)
{
if (this._tweens[i].update(this.game.time.now))
{
i++;
}
else
{
this._tweens.splice(i, 1);
numTweens--;
}
}
// If there are any new tweens to be added, do so now - otherwise they can be spliced out of the array before ever running
if (this._add.length > 0)
{
this._tweens = this._tweens.concat(this._add);
this._add.length = 0;
}
return true;
},
/**
* Checks to see if a particular Sprite is currently being tweened.
*
* @method Phaser.TweenManager#isTweening
* @param {object} object - The object to check for tweens against.
* @returns {boolean} Returns true if the object is currently being tweened, false if not.
*/
isTweening: function(object) {
return this._tweens.some(function(tween) {
return tween._object === object;
});
},
/**
* Private. Called by game focus loss. Pauses all currently running tweens.
*
* @method Phaser.TweenManager#_pauseAll
* @private
*/
_pauseAll: function () {
for (var i = this._tweens.length - 1; i >= 0; i--)
{
this._tweens[i]._pause();
}
},
/**
* Private. Called by game focus loss. Resumes all currently paused tweens.
*
* @method Phaser.TweenManager#_resumeAll
* @private
*/
_resumeAll: function () {
for (var i = this._tweens.length - 1; i >= 0; i--)
{
this._tweens[i]._resume();
}
},
/**
* Pauses all currently running tweens.
*
* @method Phaser.TweenManager#pauseAll
*/
pauseAll: function () {
for (var i = this._tweens.length - 1; i >= 0; i--)
{
this._tweens[i].pause();
}
},
/**
* Resumes all currently paused tweens.
*
* @method Phaser.TweenManager#resumeAll
*/
resumeAll: function () {
for (var i = this._tweens.length - 1; i >= 0; i--)
{
this._tweens[i].resume(true);
}
}
};
Phaser.TweenManager.prototype.constructor = Phaser.TweenManager;
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2014 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* Tween constructor
* Create a new <code>Tween</code>.
*
* @class Phaser.Tween
* @constructor
* @param {object} object - Target object will be affected by this tween.
* @param {Phaser.Game} game - Current game instance.
* @param {Phaser.TweenManager} manager - The TweenManager responsible for looking after this Tween.
*/
Phaser.Tween = function (object, game, manager) {
/**
* Reference to the target object.
* @property {object} _object
* @private
*/
this._object = object;
/**
* @property {Phaser.Game} game - A reference to the currently running Game.
*/
this.game = game;
/**
* @property {Phaser.TweenManager} _manager - Reference to the TweenManager.
* @private
*/
this._manager = manager;
/**
* @property {object} _valuesStart - Private value object.
* @private
*/
this._valuesStart = {};
/**
* @property {object} _valuesEnd - Private value object.
* @private
*/
this._valuesEnd = {};
/**
* @property {object} _valuesStartRepeat - Private value object.
* @private
*/
this._valuesStartRepeat = {};
/**
* @property {number} _duration - Private duration counter.
* @private
* @default
*/
this._duration = 1000;
/**
* @property {number} _repeat - Private repeat counter.
* @private
* @default
*/
this._repeat = 0;
/**
* @property {boolean} _yoyo - Private yoyo flag.
* @private
* @default
*/
this._yoyo = false;
/**
* @property {boolean} _reversed - Private reversed flag.
* @private
* @default
*/
this._reversed = false;
/**
* @property {number} _delayTime - Private delay counter.
* @private
* @default
*/
this._delayTime = 0;
/**
* @property {number} _startTime - Private start time counter.
* @private
* @default null
*/
this._startTime = null;
/**
* @property {function} _easingFunction - The easing function used for the tween.
* @private
*/
this._easingFunction = Phaser.Easing.Linear.None;
/**
* @property {function} _interpolationFunction - The interpolation function used for the tween.
* @private
*/
this._interpolationFunction = Phaser.Math.linearInterpolation;
/**
* @property {array} _chainedTweens - A private array of chained tweens.
* @private
*/
this._chainedTweens = [];
/**
* @property {boolean} _onStartCallbackFired - Private flag.
* @private
* @default
*/
this._onStartCallbackFired = false;
/**
* @property {function} _onUpdateCallback - An onUpdate callback.
* @private
* @default null
*/
this._onUpdateCallback = null;
/**
* @property {object} _onUpdateCallbackContext - The context in which to call the onUpdate callback.
* @private
* @default null
*/
this._onUpdateCallbackContext = null;
/**
* @property {boolean} _paused - Is this Tween paused or not?
* @private
* @default
*/
this._paused = false;
/**
* @property {number} _pausedTime - Private pause timer.
* @private
* @default
*/
this._pausedTime = 0;
/**
* @property {boolean} _codePaused - Was the Tween paused by code or by Game focus loss?
* @private
*/
this._codePaused = false;
/**
* @property {boolean} pendingDelete - If this tween is ready to be deleted by the TweenManager.
* @default
*/
this.pendingDelete = false;
// Set all starting values present on the target object - why? this will copy loads of properties we don't need - commenting out for now
// for (var field in object)
// {
// this._valuesStart[field] = parseFloat(object[field], 10);
// }
/**
* @property {Phaser.Signal} onStart - The onStart event is fired when the Tween begins.
*/
this.onStart = new Phaser.Signal();
/**
* @property {Phaser.Signal} onLoop - The onLoop event is fired if the Tween loops.
*/
this.onLoop = new Phaser.Signal();
/**
* @property {Phaser.Signal} onComplete - The onComplete event is fired when the Tween completes. Does not fire if the Tween is set to loop.
*/
this.onComplete = new Phaser.Signal();
/**
* @property {boolean} isRunning - If the tween is running this is set to true, otherwise false. Tweens that are in a delayed state, waiting to start, are considered as being running.
* @default
*/
this.isRunning = false;
};
Phaser.Tween.prototype = {
/**
* Configure the Tween
*
* @method Phaser.Tween#to
* @param {object} properties - Properties you want to tween.
* @param {number} [duration=1000] - Duration of this tween in ms.
* @param {function} [ease=null] - Easing function. If not set it will default to Phaser.Easing.Linear.None.
* @param {boolean} [autoStart=false] - Whether this tween will start automatically or not.
* @param {number} [delay=0] - Delay before this tween will start, defaults to 0 (no delay). Value given is in ms.
* @param {boolean} [repeat=0] - Should the tween automatically restart once complete? (ignores any chained tweens).
* @param {boolean} [yoyo=false] - A tween that yoyos will reverse itself when it completes.
* @return {Phaser.Tween} This Tween object.
*/
to: function (properties, duration, ease, autoStart, delay, repeat, yoyo) {
duration = duration || 1000;
ease = ease || null;
autoStart = autoStart || false;
delay = delay || 0;
repeat = repeat || 0;
yoyo = yoyo || false;
var self;
if (this._parent)
{
self = this._manager.create(this._object);
this._lastChild.chain(self);
this._lastChild = self;
}
else
{
self = this;
this._parent = this;
this._lastChild = this;
}
self._repeat = repeat;
self._duration = duration;
self._valuesEnd = properties;
if (ease !== null)
{
self._easingFunction = ease;
}
if (delay > 0)
{
self._delayTime = delay;
}
self._yoyo = yoyo;
if (autoStart)
{
return this.start();
}
else
{
return this;
}
},
/**
* Starts the tween running. Can also be called by the autoStart parameter of Tween.to.
*
* @method Phaser.Tween#start
* @return {Phaser.Tween} Itself.
*/
start: function () {
if (this.game === null || this._object === null)
{
return;
}
this._manager.add(this);
this.isRunning = true;
this._onStartCallbackFired = false;
this._startTime = this.game.time.now + this._delayTime;
for (var property in this._valuesEnd)
{
// check if an Array was provided as property value
if (Array.isArray(this._valuesEnd[property]))
{
if (this._valuesEnd[property].length === 0)
{
continue;
}
// create a local copy of the Array with the start value at the front
this._valuesEnd[property] = [this._object[property]].concat(this._valuesEnd[property]);
}
this._valuesStart[property] = this._object[property];
if (!Array.isArray(this._valuesStart[property]))
{
this._valuesStart[property] *= 1.0; // Ensures we're using numbers, not strings
}
this._valuesStartRepeat[property] = this._valuesStart[property] || 0;
}
return this;
},
/**
* This will generate an array populated with the tweened object values from start to end.
* It works by running the tween simulation at the given frame rate based on the values set-up in Tween.to and similar functions.
* It ignores delay and repeat counts and any chained tweens. Just one play through of tween data is returned, including yoyo if set.
*
* @method Phaser.Tween#generateData
* @param {number} [frameRate=60] - The speed in frames per second that the data should be generated at. The higher the value, the larger the array it creates.
* @param {array} [data] - If given the generated data will be appended to this array, otherwise a new array will be returned.
* @return {array} An array of tweened values.
*/
generateData: function (frameRate, data) {
if (this.game === null || this._object === null)
{
return null;
}
this._startTime = 0;
for (var property in this._valuesEnd)
{
// Check if an Array was provided as property value
if (Array.isArray(this._valuesEnd[property]))
{
if (this._valuesEnd[property].length === 0)
{
continue;
}
// create a local copy of the Array with the start value at the front
this._valuesEnd[property] = [this._object[property]].concat(this._valuesEnd[property]);
}
this._valuesStart[property] = this._object[property];
if (!Array.isArray(this._valuesStart[property]))
{
this._valuesStart[property] *= 1.0; // Ensures we're using numbers, not strings
}
this._valuesStartRepeat[property] = this._valuesStart[property] || 0;
}
// Simulate the tween. We will run for frameRate * (this._duration / 1000) (ms)
var time = 0;
var total = frameRate * (this._duration / 1000);
var tick = this._duration / total;
var output = [];
while (total--)
{
var property;
var elapsed = (time - this._startTime) / this._duration;
elapsed = elapsed > 1 ? 1 : elapsed;
var value = this._easingFunction(elapsed);
var blob = {};
for (property in this._valuesEnd)
{
var start = this._valuesStart[property] || 0;
var end = this._valuesEnd[property];
if (end instanceof Array)
{
blob[property] = this._interpolationFunction(end, value);
}
else
{
// Parses relative end values with start as base (e.g.: +10, -3)
if (typeof(end) === 'string')
{
end = start + parseFloat(end, 10);
}
// protect against non numeric properties.
if (typeof(end) === 'number')
{
blob[property] = start + ( end - start ) * value;
}
}
}
output.push(blob);
time += tick;
}
if (this._yoyo)
{
var reversed = output.slice();
reversed.reverse();
output = output.concat(reversed);
}
if (typeof data !== 'undefined')
{
data = data.concat(output);
return data;
}
else
{
return output;
}
},
/**
* Stops the tween if running and removes it from the TweenManager. If there are any onComplete callbacks or events they are not dispatched.
*
* @method Phaser.Tween#stop
* @return {Phaser.Tween} Itself.
*/
stop: function () {
this.isRunning = false;
this._onUpdateCallback = null;
this._manager.remove(this);
return this;
},
/**
* Sets a delay time before this tween will start.
*
* @method Phaser.Tween#delay
* @param {number} amount - The amount of the delay in ms.
* @return {Phaser.Tween} Itself.
*/
delay: function (amount) {
this._delayTime = amount;
return this;
},
/**
* Sets the number of times this tween will repeat.
*
* @method Phaser.Tween#repeat
* @param {number} times - How many times to repeat.
* @return {Phaser.Tween} Itself.
*/
repeat: function (times) {
this._repeat = times;
return this;
},
/**
* A tween that has yoyo set to true will run through from start to finish, then reverse from finish to start.
* Used in combination with repeat you can create endless loops.
*
* @method Phaser.Tween#yoyo
* @param {boolean} yoyo - Set to true to yoyo this tween.
* @return {Phaser.Tween} Itself.
*/
yoyo: function(yoyo) {
this._yoyo = yoyo;
return this;
},
/**
* Set easing function this tween will use, i.e. Phaser.Easing.Linear.None.
*
* @method Phaser.Tween#easing
* @param {function} easing - The easing function this tween will use, i.e. Phaser.Easing.Linear.None.
* @return {Phaser.Tween} Itself.
*/
easing: function (easing) {
this._easingFunction = easing;
return this;
},
/**
* Set interpolation function the tween will use, by default it uses Phaser.Math.linearInterpolation.
* Also available: Phaser.Math.bezierInterpolation and Phaser.Math.catmullRomInterpolation.
*
* @method Phaser.Tween#interpolation
* @param {function} interpolation - The interpolation function to use (Phaser.Math.linearInterpolation by default)
* @return {Phaser.Tween} Itself.
*/
interpolation: function (interpolation) {
this._interpolationFunction = interpolation;
return this;
},
/**
* You can chain tweens together by passing a reference to the chain function. This enables one tween to call another on completion.
* You can pass as many tweens as you like to this function, they will each be chained in sequence.
*
* @method Phaser.Tween#chain
* @return {Phaser.Tween} Itself.
*/
chain: function () {
this._chainedTweens = arguments;
return this;
},
/**
* Loop a chain of tweens
*
* Usage:
* game.add.tween(p).to({ x: 700 }, 1000, Phaser.Easing.Linear.None, true)
* .to({ y: 300 }, 1000, Phaser.Easing.Linear.None)
* .to({ x: 0 }, 1000, Phaser.Easing.Linear.None)
* .to({ y: 0 }, 1000, Phaser.Easing.Linear.None)
* .loop();
* @method Phaser.Tween#loop
* @return {Phaser.Tween} Itself.
*/
loop: function() {
this._lastChild.chain(this);
return this;
},
/**
* Sets a callback to be fired each time this tween updates. Note: callback will be called in the context of the global scope.
*
* @method Phaser.Tween#onUpdateCallback
* @param {function} callback - The callback to invoke each time this tween is updated.
* @return {Phaser.Tween} Itself.
*/
onUpdateCallback: function (callback, callbackContext) {
this._onUpdateCallback = callback;
this._onUpdateCallbackContext = callbackContext;
return this;
},
/**
* Pauses the tween.
*
* @method Phaser.Tween#pause
*/
pause: function () {
this._codePaused = true;
this._paused = true;
this._pausedTime = this.game.time.now;
},
/**
* This is called by the core Game loop. Do not call it directly, instead use Tween.pause.
* @method Phaser.Tween#_pause
* @private
*/
_pause: function () {
if (!this._codePaused)
{
this._paused = true;
this._pausedTime = this.game.time.now;
}
},
/**
* Resumes a paused tween.
*
* @method Phaser.Tween#resume
*/
resume: function () {
if (this._paused)
{
this._paused = false;
this._codePaused = false;
this._startTime += (this.game.time.now - this._pausedTime);
}
},
/**
* This is called by the core Game loop. Do not call it directly, instead use Tween.pause.
* @method Phaser.Tween#_resume
* @private
*/
_resume: function () {
if (this._codePaused)
{
return;
}
else
{
this._startTime += this.game.time.pauseDuration;
this._paused = false;
}
},
/**
* Core tween update function called by the TweenManager. Does not need to be invoked directly.
*
* @method Phaser.Tween#update
* @param {number} time - A timestamp passed in by the TweenManager.
* @return {boolean} false if the tween has completed and should be deleted from the manager, otherwise true (still active).
*/
update: function (time) {
if (this.pendingDelete)
{
return false;
}
if (this._paused || time < this._startTime)
{
return true;
}
var property;
if (time < this._startTime)
{
return true;
}
if (this._onStartCallbackFired === false)
{
this.onStart.dispatch(this._object);
this._onStartCallbackFired = true;
}
var elapsed = (time - this._startTime) / this._duration;
elapsed = elapsed > 1 ? 1 : elapsed;
var value = this._easingFunction(elapsed);
for (property in this._valuesEnd)
{
var start = this._valuesStart[property] || 0;
var end = this._valuesEnd[property];
if (end instanceof Array)
{
this._object[property] = this._interpolationFunction(end, value);
}
else
{
// Parses relative end values with start as base (e.g.: +10, -3)
if (typeof(end) === 'string')
{
end = start + parseFloat(end, 10);
}
// protect against non numeric properties.
if (typeof(end) === 'number')
{
this._object[property] = start + ( end - start ) * value;
}
}
}
if (this._onUpdateCallback !== null)
{
this._onUpdateCallback.call(this._onUpdateCallbackContext, this, value);
}
if (elapsed == 1)
{
if (this._repeat > 0)
{
if (isFinite(this._repeat))
{
this._repeat--;
}
// reassign starting values, restart by making startTime = now
for (property in this._valuesStartRepeat)
{
if (typeof(this._valuesEnd[property]) === 'string')
{
this._valuesStartRepeat[property] = this._valuesStartRepeat[property] + parseFloat(this._valuesEnd[property], 10);
}
if (this._yoyo)
{
var tmp = this._valuesStartRepeat[property];
this._valuesStartRepeat[property] = this._valuesEnd[property];
this._valuesEnd[property] = tmp;
this._reversed = !this._reversed;
}
this._valuesStart[property] = this._valuesStartRepeat[property];
}
this._startTime = time + this._delayTime;
this.onLoop.dispatch(this._object);
return true;
}
else
{
this.isRunning = false;
this.onComplete.dispatch(this._object);
for (var i = 0, numChainedTweens = this._chainedTweens.length; i < numChainedTweens; i ++)
{
this._chainedTweens[i].start(time);
}
return false;
}
}
return true;
}
};
Phaser.Tween.prototype.constructor = Phaser.Tween;
/* jshint curly: false */
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2014 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* A collection of easing methods defining ease-in ease-out curves.
*
* @class Phaser.Easing
*/
Phaser.Easing = {
/**
* Linear easing.
*
* @class Phaser.Easing.Linear
*/
Linear: {
/**
* Ease-in.
*
* @method Phaser.Easing.Linear#In
* @param {number} k - The value to be tweened.
* @returns {number} k^2.
*/
None: function ( k ) {
return k;
}
},
/**
* Quadratic easing.
*
* @class Phaser.Easing.Quadratic
*/
Quadratic: {
/**
* Ease-in.
*
* @method Phaser.Easing.Quadratic#In
* @param {number} k - The value to be tweened.
* @returns {number} k^2.
*/
In: function ( k ) {
return k * k;
},
/**
* Ease-out.
*
* @method Phaser.Easing.Quadratic#Out
* @param {number} k - The value to be tweened.
* @returns {number} k* (2-k).
*/
Out: function ( k ) {
return k * ( 2 - k );
},
/**
* Ease-in/out.
*
* @method Phaser.Easing.Quadratic#InOut
* @param {number} k - The value to be tweened.
* @returns {number} The tweened value.
*/
InOut: function ( k ) {
if ( ( k *= 2 ) < 1 ) return 0.5 * k * k;
return - 0.5 * ( --k * ( k - 2 ) - 1 );
}
},
/**
* Cubic easing.
*
* @class Phaser.Easing.Cubic
*/
Cubic: {
/**
* Cubic ease-in.
*
* @method Phaser.Easing.Cubic#In
* @param {number} k - The value to be tweened.
* @returns {number} The tweened value.
*/
In: function ( k ) {
return k * k * k;
},
/**
* Cubic ease-out.
*
* @method Phaser.Easing.Cubic#Out
* @param {number} k - The value to be tweened.
* @returns {number} The tweened value.
*/
Out: function ( k ) {
return --k * k * k + 1;
},
/**
* Cubic ease-in/out.
*
* @method Phaser.Easing.Cubic#InOut
* @param {number} k - The value to be tweened.
* @returns {number} The tweened value.
*/
InOut: function ( k ) {
if ( ( k *= 2 ) < 1 ) return 0.5 * k * k * k;
return 0.5 * ( ( k -= 2 ) * k * k + 2 );
}
},
/**
* Quartic easing.
*
* @class Phaser.Easing.Quartic
*/
Quartic: {
/**
* Quartic ease-in.
*
* @method Phaser.Easing.Quartic#In
* @param {number} k - The value to be tweened.
* @returns {number} The tweened value.
*/
In: function ( k ) {
return k * k * k * k;
},
/**
* Quartic ease-out.
*
* @method Phaser.Easing.Quartic#Out
* @param {number} k - The value to be tweened.
* @returns {number} The tweened value.
*/
Out: function ( k ) {
return 1 - ( --k * k * k * k );
},
/**
* Quartic ease-in/out.
*
* @method Phaser.Easing.Quartic#InOut
* @param {number} k - The value to be tweened.
* @returns {number} The tweened value.
*/
InOut: function ( k ) {
if ( ( k *= 2 ) < 1) return 0.5 * k * k * k * k;
return - 0.5 * ( ( k -= 2 ) * k * k * k - 2 );
}
},
/**
* Quintic easing.
*
* @class Phaser.Easing.Quintic
*/
Quintic: {
/**
* Quintic ease-in.
*
* @method Phaser.Easing.Quintic#In
* @param {number} k - The value to be tweened.
* @returns {number} The tweened value.
*/
In: function ( k ) {
return k * k * k * k * k;
},
/**
* Quintic ease-out.
*
* @method Phaser.Easing.Quintic#Out
* @param {number} k - The value to be tweened.
* @returns {number} The tweened value.
*/
Out: function ( k ) {
return --k * k * k * k * k + 1;
},
/**
* Quintic ease-in/out.
*
* @method Phaser.Easing.Quintic#InOut
* @param {number} k - The value to be tweened.
* @returns {number} The tweened value.
*/
InOut: function ( k ) {
if ( ( k *= 2 ) < 1 ) return 0.5 * k * k * k * k * k;
return 0.5 * ( ( k -= 2 ) * k * k * k * k + 2 );
}
},
/**
* Sinusoidal easing.
*
* @class Phaser.Easing.Sinusoidal
*/
Sinusoidal: {
/**
* Sinusoidal ease-in.
*
* @method Phaser.Easing.Sinusoidal#In
* @param {number} k - The value to be tweened.
* @returns {number} The tweened value.
*/
In: function ( k ) {
return 1 - Math.cos( k * Math.PI / 2 );
},
/**
* Sinusoidal ease-out.
*
* @method Phaser.Easing.Sinusoidal#Out
* @param {number} k - The value to be tweened.
* @returns {number} The tweened value.
*/
Out: function ( k ) {
return Math.sin( k * Math.PI / 2 );
},
/**
* Sinusoidal ease-in/out.
*
* @method Phaser.Easing.Sinusoidal#InOut
* @param {number} k - The value to be tweened.
* @returns {number} The tweened value.
*/
InOut: function ( k ) {
return 0.5 * ( 1 - Math.cos( Math.PI * k ) );
}
},
/**
* Exponential easing.
*
* @class Phaser.Easing.Exponential
*/
Exponential: {
/**
* Exponential ease-in.
*
* @method Phaser.Easing.Exponential#In
* @param {number} k - The value to be tweened.
* @returns {number} The tweened value.
*/
In: function ( k ) {
return k === 0 ? 0 : Math.pow( 1024, k - 1 );
},
/**
* Exponential ease-out.
*
* @method Phaser.Easing.Exponential#Out
* @param {number} k - The value to be tweened.
* @returns {number} The tweened value.
*/
Out: function ( k ) {
return k === 1 ? 1 : 1 - Math.pow( 2, - 10 * k );
},
/**
* Exponential ease-in/out.
*
* @method Phaser.Easing.Exponential#InOut
* @param {number} k - The value to be tweened.
* @returns {number} The tweened value.
*/
InOut: function ( k ) {
if ( k === 0 ) return 0;
if ( k === 1 ) return 1;
if ( ( k *= 2 ) < 1 ) return 0.5 * Math.pow( 1024, k - 1 );
return 0.5 * ( - Math.pow( 2, - 10 * ( k - 1 ) ) + 2 );
}
},
/**
* Circular easing.
*
* @class Phaser.Easing.Circular
*/
Circular: {
/**
* Circular ease-in.
*
* @method Phaser.Easing.Circular#In
* @param {number} k - The value to be tweened.
* @returns {number} The tweened value.
*/
In: function ( k ) {
return 1 - Math.sqrt( 1 - k * k );
},
/**
* Circular ease-out.
*
* @method Phaser.Easing.Circular#Out
* @param {number} k - The value to be tweened.
* @returns {number} The tweened value.
*/
Out: function ( k ) {
return Math.sqrt( 1 - ( --k * k ) );
},
/**
* Circular ease-in/out.
*
* @method Phaser.Easing.Circular#InOut
* @param {number} k - The value to be tweened.
* @returns {number} The tweened value.
*/
InOut: function ( k ) {
if ( ( k *= 2 ) < 1) return - 0.5 * ( Math.sqrt( 1 - k * k) - 1);
return 0.5 * ( Math.sqrt( 1 - ( k -= 2) * k) + 1);
}
},
/**
* Elastic easing.
*
* @class Phaser.Easing.Elastic
*/
Elastic: {
/**
* Elastic ease-in.
*
* @method Phaser.Easing.Elastic#In
* @param {number} k - The value to be tweened.
* @returns {number} The tweened value.
*/
In: function ( k ) {
var s, a = 0.1, p = 0.4;
if ( k === 0 ) return 0;
if ( k === 1 ) return 1;
if ( !a || a < 1 ) { a = 1; s = p / 4; }
else s = p * Math.asin( 1 / a ) / ( 2 * Math.PI );
return - ( a * Math.pow( 2, 10 * ( k -= 1 ) ) * Math.sin( ( k - s ) * ( 2 * Math.PI ) / p ) );
},
/**
* Elastic ease-out.
*
* @method Phaser.Easing.Elastic#Out
* @param {number} k - The value to be tweened.
* @returns {number} The tweened value.
*/
Out: function ( k ) {
var s, a = 0.1, p = 0.4;
if ( k === 0 ) return 0;
if ( k === 1 ) return 1;
if ( !a || a < 1 ) { a = 1; s = p / 4; }
else s = p * Math.asin( 1 / a ) / ( 2 * Math.PI );
return ( a * Math.pow( 2, - 10 * k) * Math.sin( ( k - s ) * ( 2 * Math.PI ) / p ) + 1 );
},
/**
* Elastic ease-in/out.
*
* @method Phaser.Easing.Elastic#InOut
* @param {number} k - The value to be tweened.
* @returns {number} The tweened value.
*/
InOut: function ( k ) {
var s, a = 0.1, p = 0.4;
if ( k === 0 ) return 0;
if ( k === 1 ) return 1;
if ( !a || a < 1 ) { a = 1; s = p / 4; }
else s = p * Math.asin( 1 / a ) / ( 2 * Math.PI );
if ( ( k *= 2 ) < 1 ) return - 0.5 * ( a * Math.pow( 2, 10 * ( k -= 1 ) ) * Math.sin( ( k - s ) * ( 2 * Math.PI ) / p ) );
return a * Math.pow( 2, -10 * ( k -= 1 ) ) * Math.sin( ( k - s ) * ( 2 * Math.PI ) / p ) * 0.5 + 1;
}
},
/**
* Back easing.
*
* @class Phaser.Easing.Back
*/
Back: {
/**
* Back ease-in.
*
* @method Phaser.Easing.Back#In
* @param {number} k - The value to be tweened.
* @returns {number} The tweened value.
*/
In: function ( k ) {
var s = 1.70158;
return k * k * ( ( s + 1 ) * k - s );
},
/**
* Back ease-out.
*
* @method Phaser.Easing.Back#Out
* @param {number} k - The value to be tweened.
* @returns {number} The tweened value.
*/
Out: function ( k ) {
var s = 1.70158;
return --k * k * ( ( s + 1 ) * k + s ) + 1;
},
/**
* Back ease-in/out.
*
* @method Phaser.Easing.Back#InOut
* @param {number} k - The value to be tweened.
* @returns {number} The tweened value.
*/
InOut: function ( k ) {
var s = 1.70158 * 1.525;
if ( ( k *= 2 ) < 1 ) return 0.5 * ( k * k * ( ( s + 1 ) * k - s ) );
return 0.5 * ( ( k -= 2 ) * k * ( ( s + 1 ) * k + s ) + 2 );
}
},
/**
* Bounce easing.
*
* @class Phaser.Easing.Bounce
*/
Bounce: {
/**
* Bounce ease-in.
*
* @method Phaser.Easing.Bounce#In
* @param {number} k - The value to be tweened.
* @returns {number} The tweened value.
*/
In: function ( k ) {
return 1 - Phaser.Easing.Bounce.Out( 1 - k );
},
/**
* Bounce ease-out.
*
* @method Phaser.Easing.Bounce#Out
* @param {number} k - The value to be tweened.
* @returns {number} The tweened value.
*/
Out: function ( k ) {
if ( k < ( 1 / 2.75 ) ) {
return 7.5625 * k * k;
} else if ( k < ( 2 / 2.75 ) ) {
return 7.5625 * ( k -= ( 1.5 / 2.75 ) ) * k + 0.75;
} else if ( k < ( 2.5 / 2.75 ) ) {
return 7.5625 * ( k -= ( 2.25 / 2.75 ) ) * k + 0.9375;
} else {
return 7.5625 * ( k -= ( 2.625 / 2.75 ) ) * k + 0.984375;
}
},
/**
* Bounce ease-in/out.
*
* @method Phaser.Easing.Bounce#InOut
* @param {number} k - The value to be tweened.
* @returns {number} The tweened value.
*/
InOut: function ( k ) {
if ( k < 0.5 ) return Phaser.Easing.Bounce.In( k * 2 ) * 0.5;
return Phaser.Easing.Bounce.Out( k * 2 - 1 ) * 0.5 + 0.5;
}
}
};
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2014 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* Time constructor.
*
* @class Phaser.Time
* @classdesc This is the core internal game clock. It manages the elapsed time and calculation of elapsed values, used for game object motion and tweens.
* @constructor
* @param {Phaser.Game} game A reference to the currently running game.
*/
Phaser.Time = function (game) {
/**
* @property {Phaser.Game} game - Local reference to game.
*/
this.game = game;
/**
* @property {number} time - Game time counter. If you need a value for in-game calculation please use Phaser.Time.now instead.
* @protected
*/
this.time = 0;
/**
* @property {number} now - The time right now.
* @protected
*/
this.now = 0;
/**
* @property {number} elapsed - Elapsed time since the last frame (in ms).
* @protected
*/
this.elapsed = 0;
/**
* @property {number} pausedTime - Records how long the game has been paused for. Is reset each time the game pauses.
* @protected
*/
this.pausedTime = 0;
/**
* @property {boolean} advancedTiming - If true Phaser.Time will perform advanced profiling including the fps rate, fps min/max and msMin and msMax.
* @default
*/
this.advancedTiming = false;
/**
* @property {number} fps - Frames per second. Only calculated if Time.advancedTiming is true.
* @protected
*/
this.fps = 0;
/**
* @property {number} fpsMin - The lowest rate the fps has dropped to. Only calculated if Time.advancedTiming is true.
*/
this.fpsMin = 1000;
/**
* @property {number} fpsMax - The highest rate the fps has reached (usually no higher than 60fps). Only calculated if Time.advancedTiming is true.
*/
this.fpsMax = 0;
/**
* @property {number} msMin - The minimum amount of time the game has taken between two frames. Only calculated if Time.advancedTiming is true.
* @default
*/
this.msMin = 1000;
/**
* @property {number} msMax - The maximum amount of time the game has taken between two frames. Only calculated if Time.advancedTiming is true.
*/
this.msMax = 0;
/**
* @property {number} physicsElapsed - The elapsed time calculated for the physics motion updates.
*/
this.physicsElapsed = 0;
/**
* @property {number} frames - The number of frames record in the last second. Only calculated if Time.advancedTiming is true.
*/
this.frames = 0;
/**
* @property {number} pauseDuration - Records how long the game was paused for in miliseconds.
*/
this.pauseDuration = 0;
/**
* @property {number} timeToCall - The value that setTimeout needs to work out when to next update
*/
this.timeToCall = 0;
/**
* @property {number} lastTime - Internal value used by timeToCall as part of the setTimeout loop
*/
this.lastTime = 0;
/**
* @property {Phaser.Timer} events - This is a Phaser.Timer object bound to the master clock to which you can add timed events.
*/
this.events = new Phaser.Timer(this.game, false);
/**
* @property {number} _started - The time at which the Game instance started.
* @private
*/
this._started = 0;
/**
* @property {number} _timeLastSecond - The time (in ms) that the last second counter ticked over.
* @private
*/
this._timeLastSecond = 0;
/**
* @property {number} _pauseStarted - The time the game started being paused.
* @private
*/
this._pauseStarted = 0;
/**
* @property {boolean} _justResumed - Internal value used to recover from the game pause state.
* @private
*/
this._justResumed = false;
/**
* @property {array} _timers - Internal store of Phaser.Timer objects.
* @private
*/
this._timers = [];
/**
* @property {number} _len - Temp. array length variable.
* @private
*/
this._len = 0;
/**
* @property {number} _i - Temp. array counter variable.
* @private
*/
this._i = 0;
};
Phaser.Time.prototype = {
/**
* Called automatically by Phaser.Game after boot. Should not be called directly.
*
* @method Phaser.Time#boot
* @protected
*/
boot: function () {
this._started = Date.now();
this.events.start();
},
/**
* Creates a new stand-alone Phaser.Timer object.
*
* @method Phaser.Time#create
* @param {boolean} [autoDestroy=true] - A Timer that is set to automatically destroy itself will do so after all of its events have been dispatched (assuming no looping events).
* @return {Phaser.Timer} The Timer object that was created.
*/
create: function (autoDestroy) {
if (typeof autoDestroy === 'undefined') { autoDestroy = true; }
var timer = new Phaser.Timer(this.game, autoDestroy);
this._timers.push(timer);
return timer;
},
/**
* Remove all Timer objects, regardless of their state.
*
* @method Phaser.Time#removeAll
*/
removeAll: function () {
for (var i = 0; i < this._timers.length; i++)
{
this._timers[i].destroy();
}
this._timers = [];
},
/**
* Updates the game clock and if enabled the advanced timing data. This is called automatically by Phaser.Game.
*
* @method Phaser.Time#update
* @protected
* @param {number} time - The current timestamp, either performance.now or Date.now depending on the browser.
*/
update: function (time) {
this.now = time;
if (this._justResumed)
{
this.time = this.now;
this._justResumed = false;
this.events.resume();
for (var i = 0; i < this._timers.length; i++)
{
this._timers[i]._resume();
}
}
this.timeToCall = this.game.math.max(0, 16 - (time - this.lastTime));
this.elapsed = this.now - this.time;
this.physicsElapsed = this.elapsed / 1000;
if (this.advancedTiming)
{
this.msMin = this.game.math.min(this.msMin, this.elapsed);
this.msMax = this.game.math.max(this.msMax, this.elapsed);
this.frames++;
if (this.now > this._timeLastSecond + 1000)
{
this.fps = Math.round((this.frames * 1000) / (this.now - this._timeLastSecond));
this.fpsMin = this.game.math.min(this.fpsMin, this.fps);
this.fpsMax = this.game.math.max(this.fpsMax, this.fps);
this._timeLastSecond = this.now;
this.frames = 0;
}
}
this.time = this.now;
this.lastTime = time + this.timeToCall;
// Paused but still running?
if (!this.game.paused)
{
// Our internal Phaser.Timer
this.events.update(this.now);
// Any game level timers
this._i = 0;
this._len = this._timers.length;
while (this._i < this._len)
{
if (this._timers[this._i].update(this.now))
{
this._i++;
}
else
{
this._timers.splice(this._i, 1);
this._len--;
}
}
}
},
/**
* Called when the game enters a paused state.
*
* @method Phaser.Time#gamePaused
* @private
*/
gamePaused: function (time) {
if (typeof time === 'undefined')
{
this._pauseStarted = this.now;
}
else
{
this._pauseStarted = time;
}
this.events.pause();
var i = this._timers.length;
while (i--)
{
this._timers[i]._pause();
}
},
/**
* Called when the game resumes from a paused state.
*
* @method Phaser.Time#gameResumed
* @private
*/
gameResumed: function (time) {
if (typeof time === 'undefined')
{
this.pauseDuration = this.now - this._pauseStarted;
}
else
{
this.pauseDuration = time - this._pauseStarted;
}
// Level out the elapsed timer to avoid spikes
this.time = Date.now();
this._justResumed = true;
},
/**
* The number of seconds that have elapsed since the game was started.
*
* @method Phaser.Time#totalElapsedSeconds
* @return {number} The number of seconds that have elapsed since the game was started.
*/
totalElapsedSeconds: function() {
return (this.now - this._started) * 0.001;
},
/**
* How long has passed since the given time.
*
* @method Phaser.Time#elapsedSince
* @param {number} since - The time you want to measure against.
* @return {number} The difference between the given time and now.
*/
elapsedSince: function (since) {
return this.now - since;
},
/**
* How long has passed since the given time (in seconds).
*
* @method Phaser.Time#elapsedSecondsSince
* @param {number} since - The time you want to measure (in seconds).
* @return {number} Duration between given time and now (in seconds).
*/
elapsedSecondsSince: function (since) {
return (this.now - since) * 0.001;
},
/**
* Resets the private _started value to now and removes all currently running Timers.
*
* @method Phaser.Time#reset
*/
reset: function () {
this._started = this.now;
this.removeAll();
}
};
Phaser.Time.prototype.constructor = Phaser.Time;
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2014 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* A Timer is a way to create small re-usable or disposable objects that do nothing but wait for a specific moment in time, and then dispatch an event.
* You can add as many events to a Timer as you like, each with their own delays. A Timer uses milliseconds as its unit of time. There are 1000 ms in 1 second.
* So if you want to fire an event every quarter of a second you'd need to set the delay to 250.
*
* @class Phaser.Timer
* @classdesc A Timer is a way to create small re-usable or disposable objects that do nothing but wait for a specific moment in time, and then dispatch an event.
* @constructor
* @param {Phaser.Game} game A reference to the currently running game.
* @param {boolean} [autoDestroy=true] - A Timer that is set to automatically destroy itself will do so after all of its events have been dispatched (assuming no looping events).
*/
Phaser.Timer = function (game, autoDestroy) {
if (typeof autoDestroy === 'undefined') { autoDestroy = true; }
/**
* @property {Phaser.Game} game - Local reference to game.
*/
this.game = game;
/**
* @property {boolean} running - True if the Timer is actively running. Do not switch this boolean, if you wish to pause the timer then use Timer.pause() instead.
* @default
*/
this.running = false;
/**
* @property {boolean} autoDestroy - A Timer that is set to automatically destroy itself will do so after all of its events have been dispatched (assuming no looping events).
*/
this.autoDestroy = autoDestroy;
/**
* @property {boolean} expired - An expired Timer is one in which all of its events have been dispatched and none are pending.
* @readonly
* @default
*/
this.expired = false;
/**
* @property {array<Phaser.TimerEvent>} events - An array holding all of this timers Phaser.TimerEvent objects. Use the methods add, repeat and loop to populate it.
*/
this.events = [];
/**
* @property {Phaser.Signal} onComplete - This signal will be dispatched when this Timer has completed, meaning there are no more events in the queue.
*/
this.onComplete = new Phaser.Signal();
/**
* @property {number} nextTick - The time the next tick will occur.
* @readonly
* @protected
*/
this.nextTick = 0;
/**
* @property {boolean} paused - The paused state of the Timer. You can pause the timer by calling Timer.pause() and Timer.resume() or by the game pausing.
* @readonly
* @default
*/
this.paused = false;
/**
* @property {boolean} _codePaused - Was the Timer paused by code or by Game focus loss?
* @private
*/
this._codePaused = false;
/**
* @property {number} _started - The time at which this Timer instance started running.
* @private
* @default
*/
this._started = 0;
/**
* @property {number} _pauseStarted - The time the game started being paused.
* @private
*/
this._pauseStarted = 0;
/**
* @property {number} _now - The current start-time adjusted time.
* @private
*/
this._now = 0;
/**
* @property {number} _len - Temp. array length variable.
* @private
*/
this._len = 0;
/**
* @property {number} _i - Temp. array counter variable.
* @private
*/
this._i = 0;
};
/**
* @constant
* @type {number}
*/
Phaser.Timer.MINUTE = 60000;
/**
* @constant
* @type {number}
*/
Phaser.Timer.SECOND = 1000;
/**
* @constant
* @type {number}
*/
Phaser.Timer.HALF = 500;
/**
* @constant
* @type {number}
*/
Phaser.Timer.QUARTER = 250;
Phaser.Timer.prototype = {
/**
* Creates a new TimerEvent on this Timer. Use the methods add, repeat or loop instead of this.
* @method Phaser.Timer#create
* @private
* @param {number} delay - The number of milliseconds that should elapse before the Timer will call the given callback.
* @param {boolean} loop - Should the event loop or not?
* @param {number} repeatCount - The number of times the event will repeat.
* @param {function} callback - The callback that will be called when the Timer event occurs.
* @param {object} callbackContext - The context in which the callback will be called.
* @param {array} arguments - The values to be sent to your callback function when it is called.
* @return {Phaser.TimerEvent} The Phaser.TimerEvent object that was created.
*/
create: function (delay, loop, repeatCount, callback, callbackContext, args) {
var tick = delay;
if (this.running)
{
if (this._now === 0)
{
tick += this.game.time.now;
}
else
{
tick += this._now;
}
}
var event = new Phaser.TimerEvent(this, delay, tick, repeatCount, loop, callback, callbackContext, args);
this.events.push(event);
this.order();
this.expired = false;
return event;
},
/**
* Adds a new Event to this Timer. The event will fire after the given amount of 'delay' in milliseconds has passed, once the Timer has started running.
* Call Timer.start() once you have added all of the Events you require for this Timer. The delay is in relation to when the Timer starts, not the time it was added.
* If the Timer is already running the delay will be calculated based on the timers current time.
* @method Phaser.Timer#add
* @param {number} delay - The number of milliseconds that should elapse before the Timer will call the given callback.
* @param {function} callback - The callback that will be called when the Timer event occurs.
* @param {object} callbackContext - The context in which the callback will be called.
* @param {...*} arguments - The values to be sent to your callback function when it is called.
* @return {Phaser.TimerEvent} The Phaser.TimerEvent object that was created.
*/
add: function (delay, callback, callbackContext) {
return this.create(delay, false, 0, callback, callbackContext, Array.prototype.splice.call(arguments, 3));
},
/**
* Adds a new Event to this Timer that will repeat for the given number of iterations.
* The event will fire after the given amount of 'delay' milliseconds has passed once the Timer has started running.
* Call Timer.start() once you have added all of the Events you require for this Timer. The delay is in relation to when the Timer starts, not the time it was added.
* If the Timer is already running the delay will be calculated based on the timers current time.
* @method Phaser.Timer#repeat
* @param {number} delay - The number of milliseconds that should elapse before the Timer will call the given callback.
* @param {number} repeatCount - The number of times the event will repeat.
* @param {function} callback - The callback that will be called when the Timer event occurs.
* @param {object} callbackContext - The context in which the callback will be called.
* @param {...*} arguments - The values to be sent to your callback function when it is called.
* @return {Phaser.TimerEvent} The Phaser.TimerEvent object that was created.
*/
repeat: function (delay, repeatCount, callback, callbackContext) {
return this.create(delay, false, repeatCount, callback, callbackContext, Array.prototype.splice.call(arguments, 4));
},
/**
* Adds a new looped Event to this Timer that will repeat forever or until the Timer is stopped.
* The event will fire after the given amount of 'delay' milliseconds has passed once the Timer has started running.
* Call Timer.start() once you have added all of the Events you require for this Timer. The delay is in relation to when the Timer starts, not the time it was added.
* If the Timer is already running the delay will be calculated based on the timers current time.
* @method Phaser.Timer#loop
* @param {number} delay - The number of milliseconds that should elapse before the Timer will call the given callback.
* @param {function} callback - The callback that will be called when the Timer event occurs.
* @param {object} callbackContext - The context in which the callback will be called.
* @param {...*} arguments - The values to be sent to your callback function when it is called.
* @return {Phaser.TimerEvent} The Phaser.TimerEvent object that was created.
*/
loop: function (delay, callback, callbackContext) {
return this.create(delay, true, 0, callback, callbackContext, Array.prototype.splice.call(arguments, 3));
},
/**
* Starts this Timer running.
* @method Phaser.Timer#start
*/
start: function () {
this._started = this.game.time.now;
this.running = true;
},
/**
* Stops this Timer from running. Does not cause it to be destroyed if autoDestroy is set to true.
* @method Phaser.Timer#stop
* @param {boolean} [clearEvents=true] - If true all the events in Timer will be cleared, otherwise they will remain.
*/
stop: function (clearEvents) {
this.running = false;
if (typeof clearEvents === 'undefined') { clearEvents = true; }
if (clearEvents)
{
this.events.length = 0;
}
},
/**
* Removes a pending TimerEvent from the queue.
* @param {Phaser.TimerEvent} event - The event to remove from the queue.
* @method Phaser.Timer#remove
*/
remove: function (event) {
for (var i = 0; i < this.events.length; i++)
{
if (this.events[i] === event)
{
this.events[i].pendingDelete = true;
return true;
}
}
return false;
},
/**
* Orders the events on this Timer so they are in tick order. This is called automatically when new events are created.
* @method Phaser.Timer#order
*/
order: function () {
if (this.events.length > 0)
{
// Sort the events so the one with the lowest tick is first
this.events.sort(this.sortHandler);
this.nextTick = this.events[0].tick;
}
},
/**
* Sort handler used by Phaser.Timer.order.
* @method Phaser.Timer#sortHandler
* @protected
*/
sortHandler: function (a, b) {
if (a.tick < b.tick)
{
return -1;
}
else if (a.tick > b.tick)
{
return 1;
}
return 0;
},
/**
* The main Timer update event, called automatically by the Game clock.
* @method Phaser.Timer#update
* @protected
* @param {number} time - The time from the core game clock.
* @return {boolean} True if there are still events waiting to be dispatched, otherwise false if this Timer can be destroyed.
*/
update: function (time) {
if (this.paused)
{
return true;
}
this._now = time;
this._len = this.events.length;
this._i = 0;
while (this._i < this._len)
{
if (this.events[this._i].pendingDelete)
{
this.events.splice(this._i, 1);
this._len--;
}
this._i++;
}
this._len = this.events.length;
if (this.running && this._now >= this.nextTick && this._len > 0)
{
this._i = 0;
while (this._i < this._len && this.running)
{
if (this._now >= this.events[this._i].tick)
{
var diff = this._now - this.events[this._i].tick;
var newTick = (this._now + this.events[this._i].delay) - diff;
if (newTick < 0)
{
newTick = this._now + this.events[this._i].delay;
}
if (this.events[this._i].loop === true)
{
this.events[this._i].tick = newTick;
this.events[this._i].callback.apply(this.events[this._i].callbackContext, this.events[this._i].args);
}
else if (this.events[this._i].repeatCount > 0)
{
this.events[this._i].repeatCount--;
this.events[this._i].tick = newTick;
this.events[this._i].callback.apply(this.events[this._i].callbackContext, this.events[this._i].args);
}
else
{
this.events[this._i].callback.apply(this.events[this._i].callbackContext, this.events[this._i].args);
this.events.splice(this._i, 1);
this._len--;
}
this._i++;
}
else
{
break;
}
}
// Are there any events left?
if (this.events.length > 0)
{
this.order();
}
else
{
this.expired = true;
this.onComplete.dispatch(this);
}
}
if (this.expired && this.autoDestroy)
{
return false;
}
else
{
return true;
}
},
/**
* Pauses the Timer and all events in the queue.
* @method Phaser.Timer#pause
*/
pause: function () {
if (this.running && !this.expired)
{
this._pauseStarted = this.game.time.now;
this.paused = true;
this._codePaused = true;
}
},
/**
* This is called by the core Game loop. Do not call it directly, instead use Timer.pause.
* @method Phaser.Timer#_pause
* @private
*/
_pause: function () {
if (this.running && !this.expired)
{
this._pauseStarted = this.game.time.now;
this.paused = true;
}
},
/**
* Resumes the Timer and updates all pending events.
* @method Phaser.Timer#resume
*/
resume: function () {
if (this.running && !this.expired)
{
var pauseDuration = this.game.time.now - this._pauseStarted;
for (var i = 0; i < this.events.length; i++)
{
this.events[i].tick += pauseDuration;
}
this.nextTick += pauseDuration;
this.paused = false;
this._codePaused = false;
}
},
/**
* This is called by the core Game loop. Do not call it directly, instead use Timer.pause.
* @method Phaser.Timer#_resume
* @private
*/
_resume: function () {
if (this._codePaused)
{
return;
}
else
{
this.resume();
}
},
/**
* Destroys this Timer. Any pending Events are not dispatched.
* @method Phaser.Timer#destroy
*/
destroy: function () {
this.onComplete.removeAll();
this.running = false;
this.events = [];
this._i = this._len;
}
};
/**
* @name Phaser.Timer#next
* @property {number} next - The time at which the next event will occur.
* @readonly
*/
Object.defineProperty(Phaser.Timer.prototype, "next", {
get: function () {
return this.nextTick;
}
});
/**
* @name Phaser.Timer#duration
* @property {number} duration - The duration in ms remaining until the next event will occur.
* @readonly
*/
Object.defineProperty(Phaser.Timer.prototype, "duration", {
get: function () {
if (this.running && this.nextTick > this._now)
{
return this.nextTick - this._now;
}
else
{
return 0;
}
}
});
/**
* @name Phaser.Timer#length
* @property {number} length - The number of pending events in the queue.
* @readonly
*/
Object.defineProperty(Phaser.Timer.prototype, "length", {
get: function () {
return this.events.length;
}
});
/**
* @name Phaser.Timer#ms
* @property {number} ms - The duration in milliseconds that this Timer has been running for.
* @readonly
*/
Object.defineProperty(Phaser.Timer.prototype, "ms", {
get: function () {
return this._now - this._started;
}
});
/**
* @name Phaser.Timer#seconds
* @property {number} seconds - The duration in seconds that this Timer has been running for.
* @readonly
*/
Object.defineProperty(Phaser.Timer.prototype, "seconds", {
get: function () {
return this.ms * 0.001;
}
});
Phaser.Timer.prototype.constructor = Phaser.Timer;
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2014 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* A TimerEvent is a single event that is processed by a Phaser.Timer. It consists of a delay, which is a value in milliseconds after which the event will fire.
* It can call a specific callback, passing in optional parameters.
*
* @class Phaser.TimerEvent
* @classdesc A TimerEvent is a single event that is processed by a Phaser.Timer. It consists of a delay, which is a value in milliseconds after which the event will fire.
* @constructor
* @param {Phaser.Timer} timer - The Timer object that this TimerEvent belongs to.
* @param {number} delay - The delay in ms at which this TimerEvent fires.
* @param {number} tick - The tick is the next game clock time that this event will fire at.
* @param {number} repeatCount - If this TimerEvent repeats it will do so this many times.
* @param {boolean} loop - True if this TimerEvent loops, otherwise false.
* @param {function} callback - The callback that will be called when the TimerEvent occurs.
* @param {object} callbackContext - The context in which the callback will be called.
* @param {array} arguments - The values to be passed to the callback.
*/
Phaser.TimerEvent = function (timer, delay, tick, repeatCount, loop, callback, callbackContext, args) {
/**
* @property {Phaser.Timer} timer - The Timer object that this TimerEvent belongs to.
*/
this.timer = timer;
/**
* @property {number} delay - The delay in ms at which this TimerEvent fires.
*/
this.delay = delay;
/**
* @property {number} tick - The tick is the next game clock time that this event will fire at.
*/
this.tick = tick;
/**
* @property {number} repeatCount - If this TimerEvent repeats it will do so this many times.
*/
this.repeatCount = repeatCount - 1;
/**
* @property {boolean} loop - True if this TimerEvent loops, otherwise false.
*/
this.loop = loop;
/**
* @property {function} callback - The callback that will be called when the TimerEvent occurs.
*/
this.callback = callback;
/**
* @property {object} callbackContext - The context in which the callback will be called.
*/
this.callbackContext = callbackContext;
/**
* @property {array} arguments - The values to be passed to the callback.
*/
this.args = args;
/**
* @property {boolean} pendingDelete - A flag that controls if the TimerEvent is pending deletion.
* @protected
*/
this.pendingDelete = false;
};
Phaser.TimerEvent.prototype.constructor = Phaser.TimerEvent;
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2014 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* The Animation Manager is used to add, play and update Phaser Animations.
* Any Game Object such as Phaser.Sprite that supports animation contains a single AnimationManager instance.
*
* @class Phaser.AnimationManager
* @constructor
* @param {Phaser.Sprite} sprite - A reference to the Game Object that owns this AnimationManager.
*/
Phaser.AnimationManager = function (sprite) {
/**
* @property {Phaser.Sprite} sprite - A reference to the parent Sprite that owns this AnimationManager.
*/
this.sprite = sprite;
/**
* @property {Phaser.Game} game - A reference to the currently running Game.
*/
this.game = sprite.game;
/**
* @property {Phaser.Frame} currentFrame - The currently displayed Frame of animation, if any.
* @default
*/
this.currentFrame = null;
/**
* @property {boolean} updateIfVisible - Should the animation data continue to update even if the Sprite.visible is set to false.
* @default
*/
this.updateIfVisible = true;
/**
* @property {boolean} isLoaded - Set to true once animation data has been loaded.
* @default
*/
this.isLoaded = false;
/**
* @property {Phaser.FrameData} _frameData - A temp. var for holding the currently playing Animations FrameData.
* @private
* @default
*/
this._frameData = null;
/**
* @property {object} _anims - An internal object that stores all of the Animation instances.
* @private
*/
this._anims = {};
/**
* @property {object} _outputFrames - An internal object to help avoid gc.
* @private
*/
this._outputFrames = [];
};
Phaser.AnimationManager.prototype = {
/**
* Loads FrameData into the internal temporary vars and resets the frame index to zero.
* This is called automatically when a new Sprite is created.
*
* @method Phaser.AnimationManager#loadFrameData
* @private
* @param {Phaser.FrameData} frameData - The FrameData set to load.
*/
loadFrameData: function (frameData) {
this._frameData = frameData;
this.frame = 0;
this.isLoaded = true;
},
/**
* Adds a new animation under the given key. Optionally set the frames, frame rate and loop.
* Animations added in this way are played back with the play function.
*
* @method Phaser.AnimationManager#add
* @param {string} name - The unique (within this Sprite) name for the animation, i.e. "run", "fire", "walk".
* @param {Array} [frames=null] - An array of numbers/strings that correspond to the frames to add to this animation and in which order. e.g. [1, 2, 3] or ['run0', 'run1', run2]). If null then all frames will be used.
* @param {number} [frameRate=60] - The speed at which the animation should play. The speed is given in frames per second.
* @param {boolean} [loop=false] - Whether or not the animation is looped or just plays once.
* @param {boolean} [useNumericIndex=true] - Are the given frames using numeric indexes (default) or strings?
* @return {Phaser.Animation} The Animation object that was created.
*/
add: function (name, frames, frameRate, loop, useNumericIndex) {
if (this._frameData == null)
{
console.warn('No FrameData available for Phaser.Animation ' + name);
return;
}
frames = frames || [];
frameRate = frameRate || 60;
if (typeof loop === 'undefined') { loop = false; }
// If they didn't set the useNumericIndex then let's at least try and guess it
if (typeof useNumericIndex === 'undefined')
{
if (frames && typeof frames[0] === 'number')
{
useNumericIndex = true;
}
else
{
useNumericIndex = false;
}
}
// Create the signals the AnimationManager will emit
if (this.sprite.events.onAnimationStart == null)
{
this.sprite.events.onAnimationStart = new Phaser.Signal();
this.sprite.events.onAnimationComplete = new Phaser.Signal();
this.sprite.events.onAnimationLoop = new Phaser.Signal();
}
this._outputFrames.length = 0;
this._frameData.getFrameIndexes(frames, useNumericIndex, this._outputFrames);
this._anims[name] = new Phaser.Animation(this.game, this.sprite, name, this._frameData, this._outputFrames, frameRate, loop);
this.currentAnim = this._anims[name];
this.currentFrame = this.currentAnim.currentFrame;
this.sprite.setTexture(PIXI.TextureCache[this.currentFrame.uuid]);
if (this.sprite.__tilePattern)
{
this.__tilePattern = false;
this.tilingTexture = false;
}
return this._anims[name];
},
/**
* Check whether the frames in the given array are valid and exist.
*
* @method Phaser.AnimationManager#validateFrames
* @param {Array} frames - An array of frames to be validated.
* @param {boolean} [useNumericIndex=true] - Validate the frames based on their numeric index (true) or string index (false)
* @return {boolean} True if all given Frames are valid, otherwise false.
*/
validateFrames: function (frames, useNumericIndex) {
if (typeof useNumericIndex == 'undefined') { useNumericIndex = true; }
for (var i = 0; i < frames.length; i++)
{
if (useNumericIndex === true)
{
if (frames[i] > this._frameData.total)
{
return false;
}
}
else
{
if (this._frameData.checkFrameName(frames[i]) === false)
{
return false;
}
}
}
return true;
},
/**
* Play an animation based on the given key. The animation should previously have been added via sprite.animations.add()
* If the requested animation is already playing this request will be ignored. If you need to reset an already running animation do so directly on the Animation object itself.
*
* @method Phaser.AnimationManager#play
* @param {string} name - The name of the animation to be played, e.g. "fire", "walk", "jump".
* @param {number} [frameRate=null] - The framerate to play the animation at. The speed is given in frames per second. If not provided the previously set frameRate of the Animation is used.
* @param {boolean} [loop=false] - Should the animation be looped after playback. If not provided the previously set loop value of the Animation is used.
* @param {boolean} [killOnComplete=false] - If set to true when the animation completes (only happens if loop=false) the parent Sprite will be killed.
* @return {Phaser.Animation} A reference to playing Animation instance.
*/
play: function (name, frameRate, loop, killOnComplete) {
if (this._anims[name])
{
if (this.currentAnim == this._anims[name])
{
if (this.currentAnim.isPlaying === false)
{
this.currentAnim.paused = false;
return this.currentAnim.play(frameRate, loop, killOnComplete);
}
}
else
{
this.currentAnim = this._anims[name];
this.currentAnim.paused = false;
return this.currentAnim.play(frameRate, loop, killOnComplete);
}
}
},
/**
* Stop playback of an animation. If a name is given that specific animation is stopped, otherwise the current animation is stopped.
* The currentAnim property of the AnimationManager is automatically set to the animation given.
*
* @method Phaser.AnimationManager#stop
* @param {string} [name=null] - The name of the animation to be stopped, e.g. "fire". If none is given the currently running animation is stopped.
* @param {boolean} [resetFrame=false] - When the animation is stopped should the currentFrame be set to the first frame of the animation (true) or paused on the last frame displayed (false)
*/
stop: function (name, resetFrame) {
if (typeof resetFrame == 'undefined') { resetFrame = false; }
if (typeof name == 'string')
{
if (this._anims[name])
{
this.currentAnim = this._anims[name];
this.currentAnim.stop(resetFrame);
}
}
else
{
if (this.currentAnim)
{
this.currentAnim.stop(resetFrame);
}
}
},
/**
* The main update function is called by the Sprites update loop. It's responsible for updating animation frames and firing related events.
*
* @method Phaser.AnimationManager#update
* @protected
* @return {boolean} True if a new animation frame has been set, otherwise false.
*/
update: function () {
if (this.updateIfVisible && !this.sprite.visible)
{
return false;
}
if (this.currentAnim && this.currentAnim.update() === true)
{
this.currentFrame = this.currentAnim.currentFrame;
return true;
}
return false;
},
/**
* Returns an animation that was previously added by name.
*
* @method Phaser.AnimationManager#getAnimation
* @param {string} name - The name of the animation to be returned, e.g. "fire".
* @return {Phaser.Animation} The Animation instance, if found, otherwise null.
*/
getAnimation: function (name) {
if (typeof name === 'string')
{
if (this._anims[name])
{
return this._anims[name];
}
}
return null;
},
/**
* Refreshes the current frame data back to the parent Sprite and also resets the texture data.
*
* @method Phaser.AnimationManager#refreshFrame
*/
refreshFrame: function () {
this.sprite.setTexture(PIXI.TextureCache[this.currentFrame.uuid]);
if (this.sprite.__tilePattern)
{
this.__tilePattern = false;
this.tilingTexture = false;
}
},
/**
* Destroys all references this AnimationManager contains. Sets the _anims to a new object and nulls the current animation.
*
* @method Phaser.AnimationManager#destroy
*/
destroy: function () {
this._anims = {};
this._frameData = null;
this._frameIndex = 0;
this.currentAnim = null;
this.currentFrame = null;
}
};
Phaser.AnimationManager.prototype.constructor = Phaser.AnimationManager;
/**
* @name Phaser.AnimationManager#frameData
* @property {Phaser.FrameData} frameData - The current animations FrameData.
* @readonly
*/
Object.defineProperty(Phaser.AnimationManager.prototype, 'frameData', {
get: function () {
return this._frameData;
}
});
/**
* @name Phaser.AnimationManager#frameTotal
* @property {number} frameTotal - The total number of frames in the currently loaded FrameData, or -1 if no FrameData is loaded.
* @readonly
*/
Object.defineProperty(Phaser.AnimationManager.prototype, 'frameTotal', {
get: function () {
if (this._frameData)
{
return this._frameData.total;
}
else
{
return -1;
}
}
});
/**
* @name Phaser.AnimationManager#paused
* @property {boolean} paused - Gets and sets the paused state of the current animation.
*/
Object.defineProperty(Phaser.AnimationManager.prototype, 'paused', {
get: function () {
return this.currentAnim.isPaused;
},
set: function (value) {
this.currentAnim.paused = value;
}
});
/**
* @name Phaser.AnimationManager#frame
* @property {number} frame - Gets or sets the current frame index and updates the Texture Cache for display.
*/
Object.defineProperty(Phaser.AnimationManager.prototype, 'frame', {
get: function () {
if (this.currentFrame)
{
return this._frameIndex;
}
},
set: function (value) {
if (typeof value === 'number' && this._frameData && this._frameData.getFrame(value) !== null)
{
this.currentFrame = this._frameData.getFrame(value);
this._frameIndex = value;
this.sprite.setTexture(PIXI.TextureCache[this.currentFrame.uuid]);
if (this.sprite.__tilePattern)
{
this.__tilePattern = false;
this.tilingTexture = false;
}
}
}
});
/**
* @name Phaser.AnimationManager#frameName
* @property {string} frameName - Gets or sets the current frame name and updates the Texture Cache for display.
*/
Object.defineProperty(Phaser.AnimationManager.prototype, 'frameName', {
get: function () {
if (this.currentFrame)
{
return this.currentFrame.name;
}
},
set: function (value) {
if (typeof value === 'string' && this._frameData && this._frameData.getFrameByName(value) !== null)
{
this.currentFrame = this._frameData.getFrameByName(value);
this._frameIndex = this.currentFrame.index;
this.sprite.setTexture(PIXI.TextureCache[this.currentFrame.uuid]);
if (this.sprite.__tilePattern)
{
this.__tilePattern = false;
this.tilingTexture = false;
}
}
else
{
console.warn('Cannot set frameName: ' + value);
}
}
});
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2014 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* An Animation instance contains a single animation and the controls to play it.
* It is created by the AnimationManager, consists of Animation.Frame objects and belongs to a single Game Object such as a Sprite.
*
* @class Phaser.Animation
* @constructor
* @param {Phaser.Game} game - A reference to the currently running game.
* @param {Phaser.Sprite} parent - A reference to the owner of this Animation.
* @param {string} name - The unique name for this animation, used in playback commands.
* @param {Phaser.FrameData} frameData - The FrameData object that contains all frames used by this Animation.
* @param {(Array.<number>|Array.<string>)} frames - An array of numbers or strings indicating which frames to play in which order.
* @param {number} delay - The time between each frame of the animation, given in ms.
* @param {boolean} loop - Should this animation loop when it reaches the end or play through once.
*/
Phaser.Animation = function (game, parent, name, frameData, frames, delay, loop) {
/**
* @property {Phaser.Game} game - A reference to the currently running Game.
*/
this.game = game;
/**
* @property {Phaser.Sprite} _parent - A reference to the parent Sprite that owns this Animation.
* @private
*/
this._parent = parent;
/**
* @property {Phaser.FrameData} _frameData - The FrameData the Animation uses.
* @private
*/
this._frameData = frameData;
/**
* @property {string} name - The user defined name given to this Animation.
*/
this.name = name;
/**
* @property {array} _frames
* @private
*/
this._frames = [];
this._frames = this._frames.concat(frames);
/**
* @property {number} delay - The delay in ms between each frame of the Animation.
*/
this.delay = 1000 / delay;
/**
* @property {boolean} loop - The loop state of the Animation.
*/
this.loop = loop;
/**
* @property {number} loopCount - The number of times the animation has looped since it was last started.
*/
this.loopCount = 0;
/**
* @property {boolean} killOnComplete - Should the parent of this Animation be killed when the animation completes?
* @default
*/
this.killOnComplete = false;
/**
* @property {boolean} isFinished - The finished state of the Animation. Set to true once playback completes, false during playback.
* @default
*/
this.isFinished = false;
/**
* @property {boolean} isPlaying - The playing state of the Animation. Set to false once playback completes, true during playback.
* @default
*/
this.isPlaying = false;
/**
* @property {boolean} isPaused - The paused state of the Animation.
* @default
*/
this.isPaused = false;
/**
* @property {boolean} _pauseStartTime - The time the animation paused.
* @private
* @default
*/
this._pauseStartTime = 0;
/**
* @property {number} _frameIndex
* @private
* @default
*/
this._frameIndex = 0;
/**
* @property {number} _frameDiff
* @private
* @default
*/
this._frameDiff = 0;
/**
* @property {number} _frameSkip
* @private
* @default
*/
this._frameSkip = 1;
/**
* @property {Phaser.Frame} currentFrame - The currently displayed frame of the Animation.
*/
this.currentFrame = this._frameData.getFrame(this._frames[this._frameIndex]);
/**
* @property {Phaser.Signal} onStart - This event is dispatched when this Animation starts playback.
*/
this.onStart = new Phaser.Signal();
/**
* @property {Phaser.Signal} onComplete - This event is dispatched when this Animation completes playback. If the animation is set to loop this is never fired, listen for onAnimationLoop instead.
*/
this.onComplete = new Phaser.Signal();
/**
* @property {Phaser.Signal} onLoop - This event is dispatched when this Animation loops.
*/
this.onLoop = new Phaser.Signal();
// Set-up some event listeners
this.game.onPause.add(this.onPause, this);
this.game.onResume.add(this.onResume, this);
};
Phaser.Animation.prototype = {
/**
* Plays this animation.
*
* @method Phaser.Animation#play
* @memberof Phaser.Animation
* @param {number} [frameRate=null] - The framerate to play the animation at. The speed is given in frames per second. If not provided the previously set frameRate of the Animation is used.
* @param {boolean} [loop=false] - Should the animation be looped after playback. If not provided the previously set loop value of the Animation is used.
* @param {boolean} [killOnComplete=false] - If set to true when the animation completes (only happens if loop=false) the parent Sprite will be killed.
* @return {Phaser.Animation} - A reference to this Animation instance.
*/
play: function (frameRate, loop, killOnComplete) {
if (typeof frameRate === 'number')
{
// If they set a new frame rate then use it, otherwise use the one set on creation
this.delay = 1000 / frameRate;
}
if (typeof loop === 'boolean')
{
// If they set a new loop value then use it, otherwise use the one set on creation
this.loop = loop;
}
if (typeof killOnComplete !== 'undefined')
{
// Remove the parent sprite once the animation has finished?
this.killOnComplete = killOnComplete;
}
this.isPlaying = true;
this.isFinished = false;
this.paused = false;
this.loopCount = 0;
this._timeLastFrame = this.game.time.now;
this._timeNextFrame = this.game.time.now + this.delay;
this._frameIndex = 0;
this.currentFrame = this._frameData.getFrame(this._frames[this._frameIndex]);
this._parent.setTexture(PIXI.TextureCache[this.currentFrame.uuid]);
// TODO: Double check if required
if (this._parent.__tilePattern)
{
this._parent.__tilePattern = false;
this._parent.tilingTexture = false;
}
this._parent.events.onAnimationStart.dispatch(this._parent, this);
this.onStart.dispatch(this._parent, this);
return this;
},
/**
* Sets this animation back to the first frame and restarts the animation.
*
* @method Phaser.Animation#restart
* @memberof Phaser.Animation
*/
restart: function () {
this.isPlaying = true;
this.isFinished = false;
this.paused = false;
this.loopCount = 0;
this._timeLastFrame = this.game.time.now;
this._timeNextFrame = this.game.time.now + this.delay;
this._frameIndex = 0;
this.currentFrame = this._frameData.getFrame(this._frames[this._frameIndex]);
this.onStart.dispatch(this._parent, this);
},
/**
* Stops playback of this animation and set it to a finished state. If a resetFrame is provided it will stop playback and set frame to the first in the animation.
* If `dispatchComplete` is true it will dispatch the complete events, otherwise they'll be ignored.
*
* @method Phaser.Animation#stop
* @memberof Phaser.Animation
* @param {boolean} [resetFrame=false] - If true after the animation stops the currentFrame value will be set to the first frame in this animation.
* @param {boolean} [dispatchComplete=false] - Dispatch the Animation.onComplete and parent.onAnimationComplete events?
*/
stop: function (resetFrame, dispatchComplete) {
if (typeof resetFrame === 'undefined') { resetFrame = false; }
if (typeof dispatchComplete === 'undefined') { dispatchComplete = false; }
this.isPlaying = false;
this.isFinished = true;
this.paused = false;
if (resetFrame)
{
this.currentFrame = this._frameData.getFrame(this._frames[0]);
}
if (dispatchComplete)
{
this._parent.events.onAnimationComplete.dispatch(this._parent, this);
this.onComplete.dispatch(this._parent, this);
}
},
/**
* Called when the Game enters a paused state.
*
* @method Phaser.Animation#onPause
* @memberof Phaser.Animation
*/
onPause: function () {
if (this.isPlaying)
{
this._frameDiff = this._timeNextFrame - this.game.time.now;
}
},
/**
* Called when the Game resumes from a paused state.
*
* @method Phaser.Animation#onResume
* @memberof Phaser.Animation
*/
onResume: function () {
if (this.isPlaying)
{
this._timeNextFrame = this.game.time.now + this._frameDiff;
}
},
/**
* Updates this animation. Called automatically by the AnimationManager.
*
* @method Phaser.Animation#update
* @memberof Phaser.Animation
*/
update: function () {
if (this.isPaused)
{
return false;
}
if (this.isPlaying === true && this.game.time.now >= this._timeNextFrame)
{
this._frameSkip = 1;
// Lagging?
this._frameDiff = this.game.time.now - this._timeNextFrame;
this._timeLastFrame = this.game.time.now;
if (this._frameDiff > this.delay)
{
// We need to skip a frame, work out how many
this._frameSkip = Math.floor(this._frameDiff / this.delay);
this._frameDiff -= (this._frameSkip * this.delay);
}
// And what's left now?
this._timeNextFrame = this.game.time.now + (this.delay - this._frameDiff);
this._frameIndex += this._frameSkip;
if (this._frameIndex >= this._frames.length)
{
if (this.loop)
{
this._frameIndex %= this._frames.length;
this.currentFrame = this._frameData.getFrame(this._frames[this._frameIndex]);
if (this.currentFrame)
{
this._parent.setTexture(PIXI.TextureCache[this.currentFrame.uuid]);
if (this._parent.__tilePattern)
{
this._parent.__tilePattern = false;
this._parent.tilingTexture = false;
}
}
this.loopCount++;
this._parent.events.onAnimationLoop.dispatch(this._parent, this);
this.onLoop.dispatch(this._parent, this);
}
else
{
this.complete();
}
}
else
{
this.currentFrame = this._frameData.getFrame(this._frames[this._frameIndex]);
if (this.currentFrame)
{
this._parent.setTexture(PIXI.TextureCache[this.currentFrame.uuid]);
if (this._parent.__tilePattern)
{
this._parent.__tilePattern = false;
this._parent.tilingTexture = false;
}
}
}
return true;
}
return false;
},
/**
* Cleans up this animation ready for deletion. Nulls all values and references.
*
* @method Phaser.Animation#destroy
* @memberof Phaser.Animation
*/
destroy: function () {
this.game = null;
this._parent = null;
this._frames = null;
this._frameData = null;
this.currentFrame = null;
this.isPlaying = false;
this.onStart.destroy();
this.onLoop.destroy();
this.onComplete.destroy();
this.game.onPause.remove(this.onPause, this);
this.game.onResume.remove(this.onResume, this);
},
/**
* Called internally when the animation finishes playback.
* Sets the isPlaying and isFinished states and dispatches the onAnimationComplete event if it exists on the parent and local onComplete event.
*
* @method Phaser.Animation#complete
* @memberof Phaser.Animation
*/
complete: function () {
this.isPlaying = false;
this.isFinished = true;
this.paused = false;
this._parent.events.onAnimationComplete.dispatch(this._parent, this);
this.onComplete.dispatch(this._parent, this);
if (this.killOnComplete)
{
this._parent.kill();
}
}
};
Phaser.Animation.prototype.constructor = Phaser.Animation;
/**
* @name Phaser.Animation#paused
* @property {boolean} paused - Gets and sets the paused state of this Animation.
*/
Object.defineProperty(Phaser.Animation.prototype, 'paused', {
get: function () {
return this.isPaused;
},
set: function (value) {
this.isPaused = value;
if (value)
{
// Paused
this._pauseStartTime = this.game.time.now;
}
else
{
// Un-paused
if (this.isPlaying)
{
this._timeNextFrame = this.game.time.now + this.delay;
}
}
}
});
/**
* @name Phaser.Animation#frameTotal
* @property {number} frameTotal - The total number of frames in the currently loaded FrameData, or -1 if no FrameData is loaded.
* @readonly
*/
Object.defineProperty(Phaser.Animation.prototype, 'frameTotal', {
get: function () {
return this._frames.length;
}
});
/**
* @name Phaser.Animation#frame
* @property {number} frame - Gets or sets the current frame index and updates the Texture Cache for display.
*/
Object.defineProperty(Phaser.Animation.prototype, 'frame', {
get: function () {
if (this.currentFrame !== null)
{
return this.currentFrame.index;
}
else
{
return this._frameIndex;
}
},
set: function (value) {
this.currentFrame = this._frameData.getFrame(this._frames[value]);
if (this.currentFrame !== null)
{
this._frameIndex = value;
this._parent.setTexture(PIXI.TextureCache[this.currentFrame.uuid]);
}
}
});
/**
* @name Phaser.Animation#speed
* @property {number} speed - Gets or sets the current speed of the animation, the time between each frame of the animation, given in ms. Takes effect from the NEXT frame. Minimum value is 1.
*/
Object.defineProperty(Phaser.Animation.prototype, 'speed', {
get: function () {
return Math.round(1000 / this.delay);
},
set: function (value) {
if (value >= 1)
{
this.delay = 1000 / value;
}
}
});
/**
* Really handy function for when you are creating arrays of animation data but it's using frame names and not numbers.
* For example imagine you've got 30 frames named: 'explosion_0001-large' to 'explosion_0030-large'
* You could use this function to generate those by doing: Phaser.Animation.generateFrameNames('explosion_', 1, 30, '-large', 4);
*
* @method Phaser.Animation.generateFrameNames
* @param {string} prefix - The start of the filename. If the filename was 'explosion_0001-large' the prefix would be 'explosion_'.
* @param {number} start - The number to start sequentially counting from. If your frames are named 'explosion_0001' to 'explosion_0034' the start is 1.
* @param {number} stop - The number to count to. If your frames are named 'explosion_0001' to 'explosion_0034' the stop value is 34.
* @param {string} [suffix=''] - The end of the filename. If the filename was 'explosion_0001-large' the prefix would be '-large'.
* @param {number} [zeroPad=0] - The number of zeroes to pad the min and max values with. If your frames are named 'explosion_0001' to 'explosion_0034' then the zeroPad is 4.
*/
Phaser.Animation.generateFrameNames = function (prefix, start, stop, suffix, zeroPad) {
if (typeof suffix == 'undefined') { suffix = ''; }
var output = [];
var frame = '';
if (start < stop)
{
for (var i = start; i <= stop; i++)
{
if (typeof zeroPad == 'number')
{
// str, len, pad, dir
frame = Phaser.Utils.pad(i.toString(), zeroPad, '0', 1);
}
else
{
frame = i.toString();
}
frame = prefix + frame + suffix;
output.push(frame);
}
}
else
{
for (var i = start; i >= stop; i--)
{
if (typeof zeroPad == 'number')
{
// str, len, pad, dir
frame = Phaser.Utils.pad(i.toString(), zeroPad, '0', 1);
}
else
{
frame = i.toString();
}
frame = prefix + frame + suffix;
output.push(frame);
}
}
return output;
}
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2014 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* A Frame is a single frame of an animation and is part of a FrameData collection.
*
* @class Phaser.Frame
* @constructor
* @param {number} index - The index of this Frame within the FrameData set it is being added to.
* @param {number} x - X position of the frame within the texture image.
* @param {number} y - Y position of the frame within the texture image.
* @param {number} width - Width of the frame within the texture image.
* @param {number} height - Height of the frame within the texture image.
* @param {string} name - The name of the frame. In Texture Atlas data this is usually set to the filename.
* @param {string} uuid - Internal UUID key.
*/
Phaser.Frame = function (index, x, y, width, height, name, uuid) {
/**
* @property {number} index - The index of this Frame within the FrameData set it is being added to.
*/
this.index = index;
/**
* @property {number} x - X position within the image to cut from.
*/
this.x = x;
/**
* @property {number} y - Y position within the image to cut from.
*/
this.y = y;
/**
* @property {number} width - Width of the frame.
*/
this.width = width;
/**
* @property {number} height - Height of the frame.
*/
this.height = height;
/**
* @property {string} name - Useful for Texture Atlas files (is set to the filename value).
*/
this.name = name;
/**
* @property {string} uuid - A link to the PIXI.TextureCache entry.
*/
this.uuid = uuid;
/**
* @property {number} centerX - Center X position within the image to cut from.
*/
this.centerX = Math.floor(width / 2);
/**
* @property {number} centerY - Center Y position within the image to cut from.
*/
this.centerY = Math.floor(height / 2);
/**
* @property {number} distance - The distance from the top left to the bottom-right of this Frame.
*/
this.distance = Phaser.Math.distance(0, 0, width, height);
/**
* @property {boolean} rotated - Rotated? (not yet implemented)
* @default
*/
this.rotated = false;
/**
* @property {string} rotationDirection - Either 'cw' or 'ccw', rotation is always 90 degrees.
* @default 'cw'
*/
this.rotationDirection = 'cw';
/**
* @property {boolean} trimmed - Was it trimmed when packed?
* @default
*/
this.trimmed = false;
/**
* @property {number} sourceSizeW - Width of the original sprite.
*/
this.sourceSizeW = width;
/**
* @property {number} sourceSizeH - Height of the original sprite.
*/
this.sourceSizeH = height;
/**
* @property {number} spriteSourceSizeX - X position of the trimmed sprite inside original sprite.
* @default
*/
this.spriteSourceSizeX = 0;
/**
* @property {number} spriteSourceSizeY - Y position of the trimmed sprite inside original sprite.
* @default
*/
this.spriteSourceSizeY = 0;
/**
* @property {number} spriteSourceSizeW - Width of the trimmed sprite.
* @default
*/
this.spriteSourceSizeW = 0;
/**
* @property {number} spriteSourceSizeH - Height of the trimmed sprite.
* @default
*/
this.spriteSourceSizeH = 0;
};
Phaser.Frame.prototype = {
/**
* If the frame was trimmed when added to the Texture Atlas this records the trim and source data.
*
* @method Phaser.Frame#setTrim
* @param {boolean} trimmed - If this frame was trimmed or not.
* @param {number} actualWidth - The width of the frame before being trimmed.
* @param {number} actualHeight - The height of the frame before being trimmed.
* @param {number} destX - The destination X position of the trimmed frame for display.
* @param {number} destY - The destination Y position of the trimmed frame for display.
* @param {number} destWidth - The destination width of the trimmed frame for display.
* @param {number} destHeight - The destination height of the trimmed frame for display.
*/
setTrim: function (trimmed, actualWidth, actualHeight, destX, destY, destWidth, destHeight) {
this.trimmed = trimmed;
if (trimmed)
{
this.width = actualWidth;
this.height = actualHeight;
this.sourceSizeW = actualWidth;
this.sourceSizeH = actualHeight;
this.centerX = Math.floor(actualWidth / 2);
this.centerY = Math.floor(actualHeight / 2);
this.spriteSourceSizeX = destX;
this.spriteSourceSizeY = destY;
this.spriteSourceSizeW = destWidth;
this.spriteSourceSizeH = destHeight;
}
},
/**
* Returns a Rectangle set to the dimensions of this Frame.
*
* @method Phaser.Frame#getRect
* @param {Phaser.Rectangle} [out] - A rectangle to copy the frame dimensions to.
* @return {Phaser.Rectangle} A rectangle.
*/
getRect: function (out) {
if (typeof out === 'undefined')
{
out = new Phaser.Rectangle(this.x, this.y, this.width, this.height);
}
else
{
out.setTo(this.x, this.y, this.width, this.height);
}
return out;
}
};
Phaser.Frame.prototype.constructor = Phaser.Frame;
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2014 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* FrameData is a container for Frame objects, which are the internal representation of animation data in Phaser.
*
* @class Phaser.FrameData
* @constructor
*/
Phaser.FrameData = function () {
/**
* @property {Array} _frames - Local array of frames.
* @private
*/
this._frames = [];
/**
* @property {Array} _frameNames - Local array of frame names for name to index conversions.
* @private
*/
this._frameNames = [];
};
Phaser.FrameData.prototype = {
/**
* Adds a new Frame to this FrameData collection. Typically called by the Animation.Parser and not directly.
*
* @method Phaser.FrameData#addFrame
* @param {Phaser.Frame} frame - The frame to add to this FrameData set.
* @return {Phaser.Frame} The frame that was just added.
*/
addFrame: function (frame) {
frame.index = this._frames.length;
this._frames.push(frame);
if (frame.name !== '')
{
this._frameNames[frame.name] = frame.index;
}
return frame;
},
/**
* Get a Frame by its numerical index.
*
* @method Phaser.FrameData#getFrame
* @param {number} index - The index of the frame you want to get.
* @return {Phaser.Frame} The frame, if found.
*/
getFrame: function (index) {
if (index > this._frames.length)
{
index = 0;
}
return this._frames[index];
},
/**
* Get a Frame by its frame name.
*
* @method Phaser.FrameData#getFrameByName
* @param {string} name - The name of the frame you want to get.
* @return {Phaser.Frame} The frame, if found.
*/
getFrameByName: function (name) {
if (typeof this._frameNames[name] === 'number')
{
return this._frames[this._frameNames[name]];
}
return null;
},
/**
* Check if there is a Frame with the given name.
*
* @method Phaser.FrameData#checkFrameName
* @param {string} name - The name of the frame you want to check.
* @return {boolean} True if the frame is found, otherwise false.
*/
checkFrameName: function (name) {
if (this._frameNames[name] == null)
{
return false;
}
return true;
},
/**
* Returns a range of frames based on the given start and end frame indexes and returns them in an Array.
*
* @method Phaser.FrameData#getFrameRange
* @param {number} start - The starting frame index.
* @param {number} end - The ending frame index.
* @param {Array} [output] - If given the results will be appended to the end of this array otherwise a new array will be created.
* @return {Array} An array of Frames between the start and end index values, or an empty array if none were found.
*/
getFrameRange: function (start, end, output) {
if (typeof output === "undefined") { output = []; }
for (var i = start; i <= end; i++)
{
output.push(this._frames[i]);
}
return output;
},
/**
* Returns all of the Frames in this FrameData set where the frame index is found in the input array.
* The frames are returned in the output array, or if none is provided in a new Array object.
*
* @method Phaser.FrameData#getFrames
* @param {Array} frames - An Array containing the indexes of the frames to retrieve. If the array is empty then all frames in the FrameData are returned.
* @param {boolean} [useNumericIndex=true] - Are the given frames using numeric indexes (default) or strings? (false)
* @param {Array} [output] - If given the results will be appended to the end of this array otherwise a new array will be created.
* @return {Array} An array of all Frames in this FrameData set matching the given names or IDs.
*/
getFrames: function (frames, useNumericIndex, output) {
if (typeof useNumericIndex === "undefined") { useNumericIndex = true; }
if (typeof output === "undefined") { output = []; }
if (typeof frames === "undefined" || frames.length === 0)
{
// No input array, so we loop through all frames
for (var i = 0; i < this._frames.length; i++)
{
// We only need the indexes
output.push(this._frames[i]);
}
}
else
{
// Input array given, loop through that instead
for (var i = 0, len = frames.length; i < len; i++)
{
// Does the input array contain names or indexes?
if (useNumericIndex)
{
// The actual frame
output.push(this.getFrame(frames[i]));
}
else
{
// The actual frame
output.push(this.getFrameByName(frames[i]));
}
}
}
return output;
},
/**
* Returns all of the Frame indexes in this FrameData set.
* The frames indexes are returned in the output array, or if none is provided in a new Array object.
*
* @method Phaser.FrameData#getFrameIndexes
* @param {Array} frames - An Array containing the indexes of the frames to retrieve. If the array is empty then all frames in the FrameData are returned.
* @param {boolean} [useNumericIndex=true] - Are the given frames using numeric indexes (default) or strings? (false)
* @param {Array} [output] - If given the results will be appended to the end of this array otherwise a new array will be created.
* @return {Array} An array of all Frame indexes matching the given names or IDs.
*/
getFrameIndexes: function (frames, useNumericIndex, output) {
if (typeof useNumericIndex === "undefined") { useNumericIndex = true; }
if (typeof output === "undefined") { output = []; }
if (typeof frames === "undefined" || frames.length === 0)
{
// No frames array, so we loop through all frames
for (var i = 0, len = this._frames.length; i < len; i++)
{
output.push(this._frames[i].index);
}
}
else
{
// Input array given, loop through that instead
for (var i = 0, len = frames.length; i < len; i++)
{
// Does the frames array contain names or indexes?
if (useNumericIndex)
{
output.push(frames[i]);
}
else
{
if (this.getFrameByName(frames[i]))
{
output.push(this.getFrameByName(frames[i]).index);
}
}
}
}
return output;
}
};
Phaser.FrameData.prototype.constructor = Phaser.FrameData;
/**
* @name Phaser.FrameData#total
* @property {number} total - The total number of frames in this FrameData set.
* @readonly
*/
Object.defineProperty(Phaser.FrameData.prototype, "total", {
get: function () {
return this._frames.length;
}
});
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2014 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* Responsible for parsing sprite sheet and JSON data into the internal FrameData format that Phaser uses for animations.
*
* @class Phaser.AnimationParser
*/
Phaser.AnimationParser = {
/**
* Parse a Sprite Sheet and extract the animation frame data from it.
*
* @method Phaser.AnimationParser.spriteSheet
* @param {Phaser.Game} game - A reference to the currently running game.
* @param {string} key - The Game.Cache asset key of the Sprite Sheet image.
* @param {number} frameWidth - The fixed width of each frame of the animation.
* @param {number} frameHeight - The fixed height of each frame of the animation.
* @param {number} [frameMax=-1] - The total number of animation frames to extact from the Sprite Sheet. The default value of -1 means "extract all frames".
* @param {number} [margin=0] - If the frames have been drawn with a margin, specify the amount here.
* @param {number} [spacing=0] - If the frames have been drawn with spacing between them, specify the amount here.
* @return {Phaser.FrameData} A FrameData object containing the parsed frames.
*/
spriteSheet: function (game, key, frameWidth, frameHeight, frameMax, margin, spacing) {
// How big is our image?
var img = game.cache.getImage(key);
if (img == null)
{
return null;
}
var width = img.width;
var height = img.height;
if (frameWidth <= 0)
{
frameWidth = Math.floor(-width / Math.min(-1, frameWidth));
}
if (frameHeight <= 0)
{
frameHeight = Math.floor(-height / Math.min(-1, frameHeight));
}
var row = Math.floor((width - margin) / (frameWidth + spacing));
var column = Math.floor((height - margin) / (frameHeight + spacing));
var total = row * column;
if (frameMax !== -1)
{
total = frameMax;
}
// Zero or smaller than frame sizes?
if (width === 0 || height === 0 || width < frameWidth || height < frameHeight || total === 0)
{
console.warn("Phaser.AnimationParser.spriteSheet: width/height zero or width/height < given frameWidth/frameHeight");
return null;
}
// Let's create some frames then
var data = new Phaser.FrameData();
var x = margin;
var y = margin;
for (var i = 0; i < total; i++)
{
var uuid = game.rnd.uuid();
data.addFrame(new Phaser.Frame(i, x, y, frameWidth, frameHeight, '', uuid));
PIXI.TextureCache[uuid] = new PIXI.Texture(PIXI.BaseTextureCache[key], {
x: x,
y: y,
width: frameWidth,
height: frameHeight
});
x += frameWidth + spacing;
if (x + frameWidth > width)
{
x = margin;
y += frameHeight + spacing;
}
}
return data;
},
/**
* Parse the JSON data and extract the animation frame data from it.
*
* @method Phaser.AnimationParser.JSONData
* @param {Phaser.Game} game - A reference to the currently running game.
* @param {Object} json - The JSON data from the Texture Atlas. Must be in Array format.
* @param {string} cacheKey - The Game.Cache asset key of the texture image.
* @return {Phaser.FrameData} A FrameData object containing the parsed frames.
*/
JSONData: function (game, json, cacheKey) {
// Malformed?
if (!json['frames'])
{
console.warn("Phaser.AnimationParser.JSONData: Invalid Texture Atlas JSON given, missing 'frames' array");
console.log(json);
return;
}
// Let's create some frames then
var data = new Phaser.FrameData();
// By this stage frames is a fully parsed array
var frames = json['frames'];
var newFrame;
for (var i = 0; i < frames.length; i++)
{
var uuid = game.rnd.uuid();
newFrame = data.addFrame(new Phaser.Frame(
i,
frames[i].frame.x,
frames[i].frame.y,
frames[i].frame.w,
frames[i].frame.h,
frames[i].filename,
uuid
));
PIXI.TextureCache[uuid] = new PIXI.Texture(PIXI.BaseTextureCache[cacheKey], {
x: frames[i].frame.x,
y: frames[i].frame.y,
width: frames[i].frame.w,
height: frames[i].frame.h
});
if (frames[i].trimmed)
{
newFrame.setTrim(
frames[i].trimmed,
frames[i].sourceSize.w,
frames[i].sourceSize.h,
frames[i].spriteSourceSize.x,
frames[i].spriteSourceSize.y,
frames[i].spriteSourceSize.w,
frames[i].spriteSourceSize.h
);
PIXI.TextureCache[uuid].trim = new Phaser.Rectangle(frames[i].spriteSourceSize.x, frames[i].spriteSourceSize.y, frames[i].sourceSize.w, frames[i].sourceSize.h);
}
}
return data;
},
/**
* Parse the JSON data and extract the animation frame data from it.
*
* @method Phaser.AnimationParser.JSONDataHash
* @param {Phaser.Game} game - A reference to the currently running game.
* @param {Object} json - The JSON data from the Texture Atlas. Must be in JSON Hash format.
* @param {string} cacheKey - The Game.Cache asset key of the texture image.
* @return {Phaser.FrameData} A FrameData object containing the parsed frames.
*/
JSONDataHash: function (game, json, cacheKey) {
// Malformed?
if (!json['frames'])
{
console.warn("Phaser.AnimationParser.JSONDataHash: Invalid Texture Atlas JSON given, missing 'frames' object");
console.log(json);
return;
}
// Let's create some frames then
var data = new Phaser.FrameData();
// By this stage frames is a fully parsed array
var frames = json['frames'];
var newFrame;
var i = 0;
for (var key in frames)
{
var uuid = game.rnd.uuid();
newFrame = data.addFrame(new Phaser.Frame(
i,
frames[key].frame.x,
frames[key].frame.y,
frames[key].frame.w,
frames[key].frame.h,
key,
uuid
));
PIXI.TextureCache[uuid] = new PIXI.Texture(PIXI.BaseTextureCache[cacheKey], {
x: frames[key].frame.x,
y: frames[key].frame.y,
width: frames[key].frame.w,
height: frames[key].frame.h
});
if (frames[key].trimmed)
{
newFrame.setTrim(
frames[key].trimmed,
frames[key].sourceSize.w,
frames[key].sourceSize.h,
frames[key].spriteSourceSize.x,
frames[key].spriteSourceSize.y,
frames[key].spriteSourceSize.w,
frames[key].spriteSourceSize.h
);
PIXI.TextureCache[uuid].trim = new Phaser.Rectangle(frames[key].spriteSourceSize.x, frames[key].spriteSourceSize.y, frames[key].sourceSize.w, frames[key].sourceSize.h);
}
i++;
}
return data;
},
/**
* Parse the XML data and extract the animation frame data from it.
*
* @method Phaser.AnimationParser.XMLData
* @param {Phaser.Game} game - A reference to the currently running game.
* @param {Object} xml - The XML data from the Texture Atlas. Must be in Starling XML format.
* @param {string} cacheKey - The Game.Cache asset key of the texture image.
* @return {Phaser.FrameData} A FrameData object containing the parsed frames.
*/
XMLData: function (game, xml, cacheKey) {
// Malformed?
if (!xml.getElementsByTagName('TextureAtlas'))
{
console.warn("Phaser.AnimationParser.XMLData: Invalid Texture Atlas XML given, missing <TextureAtlas> tag");
return;
}
// Let's create some frames then
var data = new Phaser.FrameData();
var frames = xml.getElementsByTagName('SubTexture');
var newFrame;
var uuid;
var name;
var frame;
var x;
var y;
var width;
var height;
var frameX;
var frameY;
var frameWidth;
var frameHeight;
for (var i = 0; i < frames.length; i++)
{
uuid = game.rnd.uuid();
frame = frames[i].attributes;
name = frame.name.nodeValue;
x = parseInt(frame.x.nodeValue, 10);
y = parseInt(frame.y.nodeValue, 10);
width = parseInt(frame.width.nodeValue, 10);
height = parseInt(frame.height.nodeValue, 10);
frameX = null;
frameY = null;
if (frame.frameX)
{
frameX = Math.abs(parseInt(frame.frameX.nodeValue, 10));
frameY = Math.abs(parseInt(frame.frameY.nodeValue, 10));
frameWidth = parseInt(frame.frameWidth.nodeValue, 10);
frameHeight = parseInt(frame.frameHeight.nodeValue, 10);
}
newFrame = data.addFrame(new Phaser.Frame(i, x, y, width, height, name, uuid));
PIXI.TextureCache[uuid] = new PIXI.Texture(PIXI.BaseTextureCache[cacheKey], {
x: x,
y: y,
width: width,
height: height
});
// Trimmed?
if (frameX !== null || frameY !== null)
{
newFrame.setTrim(true, width, height, frameX, frameY, frameWidth, frameHeight);
PIXI.TextureCache[uuid].trim = new Phaser.Rectangle(frameX, frameY, width, height);
}
}
return data;
}
};
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2014 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* Phaser.Cache constructor.
*
* @class Phaser.Cache
* @classdesc A game only has one instance of a Cache and it is used to store all externally loaded assets such as images, sounds and data files as a result of Loader calls. Cached items use string based keys for look-up.
* @constructor
* @param {Phaser.Game} game - A reference to the currently running game.
*/
Phaser.Cache = function (game) {
/**
* @property {Phaser.Game} game - Local reference to game.
*/
this.game = game;
/**
* @property {object} game - Canvas key-value container.
* @private
*/
this._canvases = {};
/**
* @property {object} _images - Image key-value container.
* @private
*/
this._images = {};
/**
* @property {object} _textures - RenderTexture key-value container.
* @private
*/
this._textures = {};
/**
* @property {object} _sounds - Sound key-value container.
* @private
*/
this._sounds = {};
/**
* @property {object} _text - Text key-value container.
* @private
*/
this._text = {};
/**
* @property {object} _text - Text key-value container.
* @private
*/
this._json = {};
/**
* @property {object} _physics - Physics data key-value container.
* @private
*/
this._physics = {};
/**
* @property {object} _tilemaps - Tilemap key-value container.
* @private
*/
this._tilemaps = {};
/**
* @property {object} _binary - Binary file key-value container.
* @private
*/
this._binary = {};
/**
* @property {object} _bitmapDatas - BitmapData key-value container.
* @private
*/
this._bitmapDatas = {};
/**
* @property {object} _bitmapFont - BitmapFont key-value container.
* @private
*/
this._bitmapFont = {};
this.addDefaultImage();
this.addMissingImage();
/**
* @property {Phaser.Signal} onSoundUnlock - This event is dispatched when the sound system is unlocked via a touch event on cellular devices.
*/
this.onSoundUnlock = new Phaser.Signal();
};
/**
* @constant
* @type {number}
*/
Phaser.Cache.CANVAS = 1;
/**
* @constant
* @type {number}
*/
Phaser.Cache.IMAGE = 2;
/**
* @constant
* @type {number}
*/
Phaser.Cache.TEXTURE = 3;
/**
* @constant
* @type {number}
*/
Phaser.Cache.SOUND = 4;
/**
* @constant
* @type {number}
*/
Phaser.Cache.TEXT = 5;
/**
* @constant
* @type {number}
*/
Phaser.Cache.PHYSICS = 6;
/**
* @constant
* @type {number}
*/
Phaser.Cache.TILEMAP = 7;
/**
* @constant
* @type {number}
*/
Phaser.Cache.BINARY = 8;
/**
* @constant
* @type {number}
*/
Phaser.Cache.BITMAPDATA = 9;
/**
* @constant
* @type {number}
*/
Phaser.Cache.BITMAPFONT = 10;
/**
* @constant
* @type {number}
*/
Phaser.Cache.JSON = 11;
Phaser.Cache.prototype = {
/**
* Add a new canvas object in to the cache.
*
* @method Phaser.Cache#addCanvas
* @param {string} key - Asset key for this canvas.
* @param {HTMLCanvasElement} canvas - Canvas DOM element.
* @param {CanvasRenderingContext2D} context - Render context of this canvas.
*/
addCanvas: function (key, canvas, context) {
this._canvases[key] = { canvas: canvas, context: context };
},
/**
* Add a binary object in to the cache.
*
* @method Phaser.Cache#addBinary
* @param {string} key - Asset key for this binary data.
* @param {object} binaryData - The binary object to be addded to the cache.
*/
addBinary: function (key, binaryData) {
this._binary[key] = binaryData;
},
/**
* Add a BitmapData object in to the cache.
*
* @method Phaser.Cache#addBitmapData
* @param {string} key - Asset key for this BitmapData.
* @param {Phaser.BitmapData} bitmapData - The BitmapData object to be addded to the cache.
* @return {Phaser.BitmapData} The BitmapData object to be addded to the cache.
*/
addBitmapData: function (key, bitmapData) {
this._bitmapDatas[key] = bitmapData;
return bitmapData;
},
/**
* Add a new Phaser.RenderTexture in to the cache.
*
* @method Phaser.Cache#addRenderTexture
* @param {string} key - The unique key by which you will reference this object.
* @param {Phaser.Texture} texture - The texture to use as the base of the RenderTexture.
*/
addRenderTexture: function (key, texture) {
var frame = new Phaser.Frame(0, 0, 0, texture.width, texture.height, '', '');
this._textures[key] = { texture: texture, frame: frame };
},
/**
* Add a Phaser.BitmapFont in to the cache.
*
* @method Phaser.Cache#addBitmapFont
* @param {string} key - The unique key by which you will reference this object.
* @param {Phaser.BitmapFont} texture - The BitmapFont object to be stored. This can be applied to any Image/Sprite as a texture.
*/
addBitmapFont: function (key, texture) {
this._bitmapFont[key] = texture;
},
/**
* Add a new sprite sheet in to the cache.
*
* @method Phaser.Cache#addSpriteSheet
* @param {string} key - The unique key by which you will reference this object.
* @param {string} url - URL of this sprite sheet file.
* @param {object} data - Extra sprite sheet data.
* @param {number} frameWidth - Width of the sprite sheet.
* @param {number} frameHeight - Height of the sprite sheet.
* @param {number} [frameMax=-1] - How many frames stored in the sprite sheet. If -1 then it divides the whole sheet evenly.
* @param {number} [margin=0] - If the frames have been drawn with a margin, specify the amount here.
* @param {number} [spacing=0] - If the frames have been drawn with spacing between them, specify the amount here.
*/
addSpriteSheet: function (key, url, data, frameWidth, frameHeight, frameMax, margin, spacing) {
this._images[key] = { url: url, data: data, spriteSheet: true, frameWidth: frameWidth, frameHeight: frameHeight, margin: margin, spacing: spacing };
PIXI.BaseTextureCache[key] = new PIXI.BaseTexture(data);
PIXI.TextureCache[key] = new PIXI.Texture(PIXI.BaseTextureCache[key]);
this._images[key].frameData = Phaser.AnimationParser.spriteSheet(this.game, key, frameWidth, frameHeight, frameMax, margin, spacing);
},
/**
* Add a new tilemap to the Cache.
*
* @method Phaser.Cache#addTilemap
* @param {string} key - The unique key by which you will reference this object.
* @param {string} url - URL of the tilemap image.
* @param {object} mapData - The tilemap data object (either a CSV or JSON file).
* @param {number} format - The format of the tilemap data.
*/
addTilemap: function (key, url, mapData, format) {
this._tilemaps[key] = { url: url, data: mapData, format: format };
},
/**
* Add a new texture atlas to the Cache.
*
* @method Phaser.Cache#addTextureAtlas
* @param {string} key - The unique key by which you will reference this object.
* @param {string} url - URL of this texture atlas file.
* @param {object} data - Extra texture atlas data.
* @param {object} atlasData - Texture atlas frames data.
* @param {number} format - The format of the texture atlas.
*/
addTextureAtlas: function (key, url, data, atlasData, format) {
this._images[key] = { url: url, data: data, spriteSheet: true };
PIXI.BaseTextureCache[key] = new PIXI.BaseTexture(data);
PIXI.TextureCache[key] = new PIXI.Texture(PIXI.BaseTextureCache[key]);
if (format == Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY)
{
this._images[key].frameData = Phaser.AnimationParser.JSONData(this.game, atlasData, key);
}
else if (format == Phaser.Loader.TEXTURE_ATLAS_JSON_HASH)
{
this._images[key].frameData = Phaser.AnimationParser.JSONDataHash(this.game, atlasData, key);
}
else if (format == Phaser.Loader.TEXTURE_ATLAS_XML_STARLING)
{
this._images[key].frameData = Phaser.AnimationParser.XMLData(this.game, atlasData, key);
}
},
/**
* Add a new Bitmap Font to the Cache.
*
* @method Phaser.Cache#addBitmapFont
* @param {string} key - The unique key by which you will reference this object.
* @param {string} url - URL of this font xml file.
* @param {object} data - Extra font data.
* @param {object} xmlData - Texture atlas frames data.
* @param {number} [xSpacing=0] - If you'd like to add additional horizontal spacing between the characters then set the pixel value here.
* @param {number} [ySpacing=0] - If you'd like to add additional vertical spacing between the lines then set the pixel value here.
*/
addBitmapFont: function (key, url, data, xmlData, xSpacing, ySpacing) {
this._images[key] = { url: url, data: data, spriteSheet: true };
PIXI.BaseTextureCache[key] = new PIXI.BaseTexture(data);
PIXI.TextureCache[key] = new PIXI.Texture(PIXI.BaseTextureCache[key]);
Phaser.LoaderParser.bitmapFont(this.game, xmlData, key, xSpacing, ySpacing);
},
/**
* Add a new physics data object to the Cache.
*
* @method Phaser.Cache#addTilemap
* @param {string} key - The unique key by which you will reference this object.
* @param {string} url - URL of the physics json data.
* @param {object} JSONData - The physics data object (a JSON file).
* @param {number} format - The format of the physics data.
*/
addPhysicsData: function (key, url, JSONData, format) {
this._physics[key] = { url: url, data: JSONData, format: format };
},
/**
* Adds a default image to be used in special cases such as WebGL Filters. Is mapped to the key __default.
*
* @method Phaser.Cache#addDefaultImage
* @protected
*/
addDefaultImage: function () {
var img = new Image();
img.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgAQMAAABJtOi3AAAAA1BMVEX///+nxBvIAAAAAXRSTlMAQObYZgAAABVJREFUeF7NwIEAAAAAgKD9qdeocAMAoAABm3DkcAAAAABJRU5ErkJggg==";
this._images['__default'] = { url: null, data: img, spriteSheet: false };
this._images['__default'].frame = new Phaser.Frame(0, 0, 0, 32, 32, '', '');
PIXI.BaseTextureCache['__default'] = new PIXI.BaseTexture(img);
PIXI.TextureCache['__default'] = new PIXI.Texture(PIXI.BaseTextureCache['__default']);
},
/**
* Adds an image to be used when a key is wrong / missing. Is mapped to the key __missing.
*
* @method Phaser.Cache#addMissingImage
* @protected
*/
addMissingImage: function () {
var img = new Image();
img.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAIAAAD8GO2jAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAJ9JREFUeNq01ssOwyAMRFG46v//Mt1ESmgh+DFmE2GPOBARKb2NVjo+17PXLD8a1+pl5+A+wSgFygymWYHBb0FtsKhJDdZlncG2IzJ4ayoMDv20wTmSMzClEgbWYNTAkQ0Z+OJ+A/eWnAaR9+oxCF4Os0H8htsMUp+pwcgBBiMNnAwF8GqIgL2hAzaGFFgZauDPKABmowZ4GL369/0rwACp2yA/ttmvsQAAAABJRU5ErkJggg==";
this._images['__missing'] = { url: null, data: img, spriteSheet: false };
this._images['__missing'].frame = new Phaser.Frame(0, 0, 0, 32, 32, '', '');
PIXI.BaseTextureCache['__missing'] = new PIXI.BaseTexture(img);
PIXI.TextureCache['__missing'] = new PIXI.Texture(PIXI.BaseTextureCache['__missing']);
},
/**
* Add a new text data.
*
* @method Phaser.Cache#addText
* @param {string} key - Asset key for the text data.
* @param {string} url - URL of this text data file.
* @param {object} data - Extra text data.
*/
addText: function (key, url, data) {
this._text[key] = { url: url, data: data };
},
/**
* Add a new json object into the cache.
*
* @method Phaser.Cache#addJSON
* @param {string} key - Asset key for the text data.
* @param {string} url - URL of this text data file.
* @param {object} data - Extra text data.
*/
addJSON: function (key, url, data) {
this._json[key] = { url: url, data: data };
},
/**
* Add a new image.
*
* @method Phaser.Cache#addImage
* @param {string} key - The unique key by which you will reference this object.
* @param {string} url - URL of this image file.
* @param {object} data - Extra image data.
*/
addImage: function (key, url, data) {
this._images[key] = { url: url, data: data, spriteSheet: false };
this._images[key].frame = new Phaser.Frame(0, 0, 0, data.width, data.height, key, this.game.rnd.uuid());
PIXI.BaseTextureCache[key] = new PIXI.BaseTexture(data);
PIXI.TextureCache[key] = new PIXI.Texture(PIXI.BaseTextureCache[key]);
},
/**
* Add a new sound.
*
* @method Phaser.Cache#addSound
* @param {string} key - Asset key for the sound.
* @param {string} url - URL of this sound file.
* @param {object} data - Extra sound data.
* @param {boolean} webAudio - True if the file is using web audio.
* @param {boolean} audioTag - True if the file is using legacy HTML audio.
*/
addSound: function (key, url, data, webAudio, audioTag) {
webAudio = webAudio || true;
audioTag = audioTag || false;
var decoded = false;
if (audioTag)
{
decoded = true;
}
this._sounds[key] = { url: url, data: data, isDecoding: false, decoded: decoded, webAudio: webAudio, audioTag: audioTag, locked: this.game.sound.touchLocked };
},
/**
* Reload a sound.
*
* @method Phaser.Cache#reloadSound
* @param {string} key - Asset key for the sound.
*/
reloadSound: function (key) {
var _this = this;
if (this._sounds[key])
{
this._sounds[key].data.src = this._sounds[key].url;
this._sounds[key].data.addEventListener('canplaythrough', function () {
return _this.reloadSoundComplete(key);
}, false);
this._sounds[key].data.load();
}
},
/**
* Fires the onSoundUnlock event when the sound has completed reloading.
*
* @method Phaser.Cache#reloadSoundComplete
* @param {string} key - Asset key for the sound.
*/
reloadSoundComplete: function (key) {
if (this._sounds[key])
{
this._sounds[key].locked = false;
this.onSoundUnlock.dispatch(key);
}
},
/**
* Updates the sound object in the cache.
*
* @method Phaser.Cache#updateSound
* @param {string} key - Asset key for the sound.
*/
updateSound: function (key, property, value) {
if (this._sounds[key])
{
this._sounds[key][property] = value;
}
},
/**
* Add a new decoded sound.
*
* @method Phaser.Cache#decodedSound
* @param {string} key - Asset key for the sound.
* @param {object} data - Extra sound data.
*/
decodedSound: function (key, data) {
this._sounds[key].data = data;
this._sounds[key].decoded = true;
this._sounds[key].isDecoding = false;
},
/**
* Get a canvas object from the cache by its key.
*
* @method Phaser.Cache#getCanvas
* @param {string} key - Asset key of the canvas to retrieve from the Cache.
* @return {object} The canvas object.
*/
getCanvas: function (key) {
if (this._canvases[key])
{
return this._canvases[key].canvas;
}
else
{
console.warn('Phaser.Cache.getCanvas: Invalid key: "' + key + '"');
}
},
/**
* Get a BitmapData object from the cache by its key.
*
* @method Phaser.Cache#getBitmapData
* @param {string} key - Asset key of the BitmapData object to retrieve from the Cache.
* @return {Phaser.BitmapData} The requested BitmapData object if found, or null if not.
*/
getBitmapData: function (key) {
if (this._bitmapDatas[key])
{
return this._bitmapDatas[key];
}
else
{
console.warn('Phaser.Cache.getBitmapData: Invalid key: "' + key + '"');
}
},
/**
* Get a BitmapFont object from the cache by its key.
*
* @method Phaser.Cache#getBitmapFont
* @param {string} key - Asset key of the BitmapFont object to retrieve from the Cache.
* @return {Phaser.BitmapFont} The requested BitmapFont object if found, or null if not.
*/
getBitmapFont: function (key) {
if (this._bitmapFont[key])
{
return this._bitmapFont[key];
}
else
{
console.warn('Phaser.Cache.getBitmapFont: Invalid key: "' + key + '"');
}
},
/**
* Get a physics data object from the cache by its key. You can get either the entire data set or just a single object from it.
*
* @method Phaser.Cache#getPhysicsData
* @param {string} key - Asset key of the physics data object to retrieve from the Cache.
* @param {string} [object=null] - If specified it will return just the physics object that is part of the given key, if null it will return them all.
* @return {object} The requested physics object data if found.
*/
getPhysicsData: function (key, object) {
if (typeof object === 'undefined' || object === null)
{
// Get 'em all
if (this._physics[key])
{
return this._physics[key].data;
}
else
{
console.warn('Phaser.Cache.getPhysicsData: Invalid key: "' + key + '"');
}
}
else
{
if (this._physics[key] && this._physics[key].data[object])
{
return this._physics[key].data[object];
}
else
{
console.warn('Phaser.Cache.getPhysicsData: Invalid key/object: "' + key + ' / ' + object + '"');
}
}
return null;
},
/**
* Checks if an image key exists.
*
* @method Phaser.Cache#checkImageKey
* @param {string} key - Asset key of the image to check is in the Cache.
* @return {boolean} True if the key exists, otherwise false.
*/
checkImageKey: function (key) {
if (this._images[key])
{
return true;
}
return false;
},
/**
* Get image data by key.
*
* @method Phaser.Cache#getImage
* @param {string} key - Asset key of the image to retrieve from the Cache.
* @return {object} The image data.
*/
getImage: function (key) {
if (this._images[key])
{
return this._images[key].data;
}
else
{
console.warn('Phaser.Cache.getImage: Invalid key: "' + key + '"');
}
},
/**
* Get tilemap data by key.
*
* @method Phaser.Cache#getTilemap
* @param {string} key - Asset key of the tilemap data to retrieve from the Cache.
* @return {Object} The raw tilemap data in CSV or JSON format.
*/
getTilemapData: function (key) {
if (this._tilemaps[key])
{
return this._tilemaps[key];
}
else
{
console.warn('Phaser.Cache.getTilemapData: Invalid key: "' + key + '"');
}
},
/**
* Get frame data by key.
*
* @method Phaser.Cache#getFrameData
* @param {string} key - Asset key of the frame data to retrieve from the Cache.
* @return {Phaser.FrameData} The frame data.
*/
getFrameData: function (key) {
if (this._images[key] && this._images[key].frameData)
{
return this._images[key].frameData;
}
return null;
},
/**
* Replaces a set of frameData with a new Phaser.FrameData object.
*
* @method Phaser.Cache#updateFrameData
* @param {string} key - The unique key by which you will reference this object.
* @param {number} frameData - The new FrameData.
*/
updateFrameData: function (key, frameData) {
if (this._images[key])
{
this._images[key].spriteSheet = true;
this._images[key].frameData = frameData;
}
},
/**
* Get a single frame out of a frameData set by key.
*
* @method Phaser.Cache#getFrameByIndex
* @param {string} key - Asset key of the frame data to retrieve from the Cache.
* @return {Phaser.Frame} The frame object.
*/
getFrameByIndex: function (key, frame) {
if (this._images[key] && this._images[key].frameData)
{
return this._images[key].frameData.getFrame(frame);
}
return null;
},
/**
* Get a single frame out of a frameData set by key.
*
* @method Phaser.Cache#getFrameByName
* @param {string} key - Asset key of the frame data to retrieve from the Cache.
* @return {Phaser.Frame} The frame object.
*/
getFrameByName: function (key, frame) {
if (this._images[key] && this._images[key].frameData)
{
return this._images[key].frameData.getFrameByName(frame);
}
return null;
},
/**
* Get a single frame by key. You'd only do this to get the default Frame created for a non-atlas/spritesheet image.
*
* @method Phaser.Cache#getFrame
* @param {string} key - Asset key of the frame data to retrieve from the Cache.
* @return {Phaser.Frame} The frame data.
*/
getFrame: function (key) {
if (this._images[key] && this._images[key].spriteSheet === false)
{
return this._images[key].frame;
}
return null;
},
/**
* Get a single texture frame by key. You'd only do this to get the default Frame created for a non-atlas/spritesheet image.
*
* @method Phaser.Cache#getTextureFrame
* @param {string} key - Asset key of the frame to retrieve from the Cache.
* @return {Phaser.Frame} The frame data.
*/
getTextureFrame: function (key) {
if (this._textures[key])
{
return this._textures[key].frame;
}
return null;
},
/**
* Get a RenderTexture by key.
*
* @method Phaser.Cache#getTexture
* @param {string} key - Asset key of the RenderTexture to retrieve from the Cache.
* @return {Phaser.RenderTexture} The RenderTexture object.
*/
getTexture: function (key) {
if (this._textures[key])
{
return this._textures[key];
}
else
{
console.warn('Phaser.Cache.getTexture: Invalid key: "' + key + '"');
}
},
/**
* Get sound by key.
*
* @method Phaser.Cache#getSound
* @param {string} key - Asset key of the sound to retrieve from the Cache.
* @return {Phaser.Sound} The sound object.
*/
getSound: function (key) {
if (this._sounds[key])
{
return this._sounds[key];
}
else
{
console.warn('Phaser.Cache.getSound: Invalid key: "' + key + '"');
}
},
/**
* Get sound data by key.
*
* @method Phaser.Cache#getSoundData
* @param {string} key - Asset key of the sound to retrieve from the Cache.
* @return {object} The sound data.
*/
getSoundData: function (key) {
if (this._sounds[key])
{
return this._sounds[key].data;
}
else
{
console.warn('Phaser.Cache.getSoundData: Invalid key: "' + key + '"');
}
},
/**
* Check if the given sound has finished decoding.
*
* @method Phaser.Cache#isSoundDecoded
* @param {string} key - Asset key of the sound in the Cache.
* @return {boolean} The decoded state of the Sound object.
*/
isSoundDecoded: function (key) {
if (this._sounds[key])
{
return this._sounds[key].decoded;
}
},
/**
* Check if the given sound is ready for playback. A sound is considered ready when it has finished decoding and the device is no longer touch locked.
*
* @method Phaser.Cache#isSoundReady
* @param {string} key - Asset key of the sound in the Cache.
* @return {boolean} True if the sound is decoded and the device is not touch locked.
*/
isSoundReady: function (key) {
return (this._sounds[key] && this._sounds[key].decoded && this.game.sound.touchLocked === false);
},
/**
* Check whether an image asset is sprite sheet or not.
*
* @method Phaser.Cache#isSpriteSheet
* @param {string} key - Asset key of the sprite sheet you want.
* @return {boolean} True if the image is a sprite sheet.
*/
isSpriteSheet: function (key) {
if (this._images[key])
{
return this._images[key].spriteSheet;
}
return false;
},
/**
* Get text data by key.
*
* @method Phaser.Cache#getText
* @param {string} key - Asset key of the text data to retrieve from the Cache.
* @return {object} The text data.
*/
getText: function (key) {
if (this._text[key])
{
return this._text[key].data;
}
else
{
console.warn('Phaser.Cache.getText: Invalid key: "' + key + '"');
}
},
/**
* Get a JSON object by key from the cache.
*
* @method Phaser.Cache#getJSON
* @param {string} key - Asset key of the json object to retrieve from the Cache.
* @return {object} The JSON object.
*/
getJSON: function (key) {
if (this._json[key])
{
return this._json[key].data;
}
else
{
console.warn('Phaser.Cache.getJSON: Invalid key: "' + key + '"');
}
},
/**
* Get binary data by key.
*
* @method Phaser.Cache#getBinary
* @param {string} key - Asset key of the binary data object to retrieve from the Cache.
* @return {object} The binary data object.
*/
getBinary: function (key) {
if (this._binary[key])
{
return this._binary[key];
}
else
{
console.warn('Phaser.Cache.getBinary: Invalid key: "' + key + '"');
}
},
/**
* Gets all keys used by the Cache for the given data type.
*
* @method Phaser.Cache#getKeys
* @param {number} [type=Phaser.Cache.IMAGE] - The type of Cache keys you wish to get. Can be Cache.CANVAS, Cache.IMAGE, Cache.SOUND, etc.
* @return {Array} The array of item keys.
*/
getKeys: function (type) {
var array = null;
switch (type)
{
case Phaser.Cache.CANVAS:
array = this._canvases;
break;
case Phaser.Cache.IMAGE:
array = this._images;
break;
case Phaser.Cache.TEXTURE:
array = this._textures;
break;
case Phaser.Cache.SOUND:
array = this._sounds;
break;
case Phaser.Cache.TEXT:
array = this._text;
break;
case Phaser.Cache.PHYSICS:
array = this._physics;
break;
case Phaser.Cache.TILEMAP:
array = this._tilemaps;
break;
case Phaser.Cache.BINARY:
array = this._binary;
break;
case Phaser.Cache.BITMAPDATA:
array = this._bitmapDatas;
break;
case Phaser.Cache.BITMAPFONT:
array = this._bitmapFont;
break;
case Phaser.Cache.JSON:
array = this._json;
break;
}
if (!array)
{
return;
}
var output = [];
for (var item in array)
{
if (item !== '__default' && item !== '__missing')
{
output.push(item);
}
}
return output;
},
/**
* Removes a canvas from the cache.
*
* @method Phaser.Cache#removeCanvas
* @param {string} key - Key of the asset you want to remove.
*/
removeCanvas: function (key) {
delete this._canvases[key];
},
/**
* Removes an image from the cache.
*
* @method Phaser.Cache#removeImage
* @param {string} key - Key of the asset you want to remove.
*/
removeImage: function (key) {
delete this._images[key];
},
/**
* Removes a sound from the cache.
*
* @method Phaser.Cache#removeSound
* @param {string} key - Key of the asset you want to remove.
*/
removeSound: function (key) {
delete this._sounds[key];
},
/**
* Removes a text from the cache.
*
* @method Phaser.Cache#removeText
* @param {string} key - Key of the asset you want to remove.
*/
removeText: function (key) {
delete this._text[key];
},
/**
* Removes a json object from the cache.
*
* @method Phaser.Cache#removeJSON
* @param {string} key - Key of the asset you want to remove.
*/
removeJSON: function (key) {
delete this._json[key];
},
/**
* Removes a physics data file from the cache.
*
* @method Phaser.Cache#removePhysics
* @param {string} key - Key of the asset you want to remove.
*/
removePhysics: function (key) {
delete this._text[key];
},
/**
* Removes a tilemap from the cache.
*
* @method Phaser.Cache#removeTilemap
* @param {string} key - Key of the asset you want to remove.
*/
removeTilemap: function (key) {
delete this._text[key];
},
/**
* Removes a binary file from the cache.
*
* @method Phaser.Cache#removeBinary
* @param {string} key - Key of the asset you want to remove.
*/
removeBinary: function (key) {
delete this._text[key];
},
/**
* Removes a bitmap data from the cache.
*
* @method Phaser.Cache#removeBitmapData
* @param {string} key - Key of the asset you want to remove.
*/
removeBitmapData: function (key) {
delete this._text[key];
},
/**
* Removes a bitmap font from the cache.
*
* @method Phaser.Cache#removeBitmapFont
* @param {string} key - Key of the asset you want to remove.
*/
removeBitmapFont: function (key) {
delete this._text[key];
},
/**
* Clears the cache. Removes every local cache object reference.
*
* @method Phaser.Cache#destroy
*/
destroy: function () {
for (var item in this._canvases)
{
delete this._canvases[item['key']];
}
for (var item in this._images)
{
delete this._images[item['key']];
}
for (var item in this._sounds)
{
delete this._sounds[item['key']];
}
for (var item in this._text)
{
delete this._text[item['key']];
}
for (var item in this._json)
{
delete this._json[item['key']];
}
for (var item in this._textures)
{
delete this._textures[item['key']];
}
for (var item in this._physics)
{
delete this._physics[item['key']];
}
for (var item in this._tilemaps)
{
delete this._tilemaps[item['key']];
}
for (var item in this._binary)
{
delete this._binary[item['key']];
}
for (var item in this._bitmapDatas)
{
delete this._bitmapDatas[item['key']];
}
for (var item in this._bitmapFont)
{
delete this._bitmapFont[item['key']];
}
}
};
Phaser.Cache.prototype.constructor = Phaser.Cache;
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2014 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* Phaser loader constructor.
* The Loader handles loading all external content such as Images, Sounds, Texture Atlases and data files.
* It uses a combination of Image() loading and xhr and provides progress and completion callbacks.
* @class Phaser.Loader
* @classdesc The Loader handles loading all external content such as Images, Sounds, Texture Atlases and data files.
* It uses a combination of Image() loading and xhr and provides progress and completion callbacks.
* @constructor
* @param {Phaser.Game} game - A reference to the currently running game.
*/
Phaser.Loader = function (game) {
/**
* @property {Phaser.Game} game - Local reference to game.
*/
this.game = game;
/**
* @property {array} _fileList - Contains all the assets file infos.
* @private
*/
this._fileList = [];
/**
* @property {number} _fileIndex - The index of the current file being loaded.
* @private
*/
this._fileIndex = 0;
/**
* @property {number} _progressChunk - Indicates the size of 1 file in terms of a percentage out of 100.
* @private
* @default
*/
this._progressChunk = 0;
/**
* @property {XMLHttpRequest} - An XMLHttpRequest object used for loading text and audio data.
* @private
*/
this._xhr = new XMLHttpRequest();
/**
* @property {boolean} isLoading - True if the Loader is in the process of loading the queue.
* @default
*/
this.isLoading = false;
/**
* @property {boolean} hasLoaded - True if all assets in the queue have finished loading.
* @default
*/
this.hasLoaded = false;
/**
* @property {number} progress - The rounded load progress percentage value (from 0 to 100)
* @default
*/
this.progress = 0;
/**
* @property {number} progressFloat - The non-rounded load progress value (from 0.0 to 100.0)
* @default
*/
this.progressFloat = 0;
/**
* You can optionally link a sprite to the preloader.
* If you do so the Sprites width or height will be cropped based on the percentage loaded.
* @property {Phaser.Sprite|Phaser.Image} preloadSprite
* @default
*/
this.preloadSprite = null;
/**
* @property {boolean|string} crossOrigin - The crossOrigin value applied to loaded images.
* @default
*/
this.crossOrigin = false;
/**
* If you want to append a URL before the path of any asset you can set this here.
* Useful if you need to allow an asset url to be configured outside of the game code.
* MUST have / on the end of it!
* @property {string} baseURL
* @default
*/
this.baseURL = '';
/**
* @property {Phaser.Signal} onFileComplete - Event signal.
*/
this.onFileComplete = new Phaser.Signal();
/**
* @property {Phaser.Signal} onFileError - Event signal.
*/
this.onFileError = new Phaser.Signal();
/**
* @property {Phaser.Signal} onLoadStart - Event signal.
*/
this.onLoadStart = new Phaser.Signal();
/**
* @property {Phaser.Signal} onLoadComplete - Event signal.
*/
this.onLoadComplete = new Phaser.Signal();
};
/**
* @constant
* @type {number}
*/
Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY = 0;
/**
* @constant
* @type {number}
*/
Phaser.Loader.TEXTURE_ATLAS_JSON_HASH = 1;
/**
* @constant
* @type {number}
*/
Phaser.Loader.TEXTURE_ATLAS_XML_STARLING = 2;
/**
* @constant
* @type {number}
*/
Phaser.Loader.PHYSICS_LIME_CORONA = 3;
Phaser.Loader.prototype = {
/**
* You can set a Sprite to be a "preload" sprite by passing it to this method.
* A "preload" sprite will have its width or height crop adjusted based on the percentage of the loader in real-time.
* This allows you to easily make loading bars for games. Note that Sprite.visible = true will be set when calling this.
*
* @method Phaser.Loader#setPreloadSprite
* @param {Phaser.Sprite|Phaser.Image} sprite - The sprite that will be cropped during the load.
* @param {number} [direction=0] - A value of zero means the sprite width will be cropped, a value of 1 means its height will be cropped.
*/
setPreloadSprite: function (sprite, direction) {
direction = direction || 0;
this.preloadSprite = { sprite: sprite, direction: direction, width: sprite.width, height: sprite.height, crop: null };
if (direction === 0)
{
// Horizontal crop
this.preloadSprite.crop = new Phaser.Rectangle(0, 0, 1, sprite.height);
}
else
{
// Vertical crop
this.preloadSprite.crop = new Phaser.Rectangle(0, 0, sprite.width, 1);
}
sprite.crop(this.preloadSprite.crop);
sprite.visible = true;
},
/**
* Check whether asset exists with a specific key.
*
* @method Phaser.Loader#checkKeyExists
* @param {string} type - The type asset you want to check.
* @param {string} key - Key of the asset you want to check.
* @return {boolean} Return true if exists, otherwise return false.
*/
checkKeyExists: function (type, key) {
if (this._fileList.length > 0)
{
for (var i = 0; i < this._fileList.length; i++)
{
if (this._fileList[i].type === type && this._fileList[i].key === key)
{
return true;
}
}
}
return false;
},
/**
* Gets the fileList index for the given key.
*
* @method Phaser.Loader#getAssetIndex
* @param {string} type - The type asset you want to check.
* @param {string} key - Key of the asset you want to check.
* @return {number} The index of this key in the filelist, or -1 if not found.
*/
getAssetIndex: function (type, key) {
if (this._fileList.length > 0)
{
for (var i = 0; i < this._fileList.length; i++)
{
if (this._fileList[i].type === type && this._fileList[i].key === key)
{
return i;
}
}
}
return -1;
},
/**
* Gets the asset that is queued for load.
*
* @method Phaser.Loader#getAsset
* @param {string} type - The type asset you want to check.
* @param {string} key - Key of the asset you want to check.
* @return {any} Returns an object if found that has 2 properties: index and file. Otherwise false.
*/
getAsset: function (type, key) {
if (this._fileList.length > 0)
{
for (var i = 0; i < this._fileList.length; i++)
{
if (this._fileList[i].type === type && this._fileList[i].key === key)
{
return { index: i, file: this._fileList[i] };
}
}
}
return false;
},
/**
* Reset loader, this will remove the load queue.
*
* @method Phaser.Loader#reset
*/
reset: function () {
this.preloadSprite = null;
this.isLoading = false;
this._fileList.length = 0;
this._fileIndex = 0;
},
/**
* Internal function that adds a new entry to the file list. Do not call directly.
*
* @method Phaser.Loader#addToFileList
* @param {string} type - The type of resource to add to the list (image, audio, xml, etc).
* @param {string} key - The unique Cache ID key of this resource.
* @param {string} url - The URL the asset will be loaded from.
* @param {object} properties - Any additional properties needed to load the file.
* @protected
*/
addToFileList: function (type, key, url, properties) {
var entry = {
type: type,
key: key,
url: url,
data: null,
error: false,
loaded: false
};
if (typeof properties !== "undefined")
{
for (var prop in properties)
{
entry[prop] = properties[prop];
}
}
if (this.checkKeyExists(type, key) === false)
{
this._fileList.push(entry);
}
},
/**
* Internal function that replaces an existing entry in the file list with a new one. Do not call directly.
*
* @method Phaser.Loader#replaceInFileList
* @param {string} type - The type of resource to add to the list (image, audio, xml, etc).
* @param {string} key - The unique Cache ID key of this resource.
* @param {string} url - The URL the asset will be loaded from.
* @param {object} properties - Any additional properties needed to load the file.
* @protected
*/
replaceInFileList: function (type, key, url, properties) {
var entry = {
type: type,
key: key,
url: url,
data: null,
error: false,
loaded: false
};
if (typeof properties !== "undefined")
{
for (var prop in properties)
{
entry[prop] = properties[prop];
}
}
var index = this.getAssetIndex(type, key);
if (index === -1)
{
this._fileList.push(entry);
}
else
{
this._fileList[index] = entry;
}
},
/**
* Add an image to the Loader.
*
* @method Phaser.Loader#image
* @param {string} key - Unique asset key of this image file.
* @param {string} url - URL of image file.
* @param {boolean} [overwrite=false] - If an unloaded file with a matching key already exists in the queue, this entry will overwrite it.
* @return {Phaser.Loader} This Loader instance.
*/
image: function (key, url, overwrite) {
if (typeof overwrite === "undefined") { overwrite = false; }
if (overwrite)
{
this.replaceInFileList('image', key, url);
}
else
{
this.addToFileList('image', key, url);
}
return this;
},
/**
* Add a text file to the Loader.
*
* @method Phaser.Loader#text
* @param {string} key - Unique asset key of the text file.
* @param {string} url - URL of the text file.
* @param {boolean} [overwrite=false] - If an unloaded file with a matching key already exists in the queue, this entry will overwrite it.
* @return {Phaser.Loader} This Loader instance.
*/
text: function (key, url, overwrite) {
if (typeof overwrite === "undefined") { overwrite = false; }
if (overwrite)
{
this.replaceInFileList('text', key, url);
}
else
{
this.addToFileList('text', key, url);
}
return this;
},
/**
* Add a json file to the Loader.
*
* @method Phaser.Loader#json
* @param {string} key - Unique asset key of the json file.
* @param {string} url - URL of the json file.
* @param {boolean} [overwrite=false] - If an unloaded file with a matching key already exists in the queue, this entry will overwrite it.
* @return {Phaser.Loader} This Loader instance.
*/
json: function (key, url, overwrite) {
if (typeof overwrite === "undefined") { overwrite = false; }
if (overwrite)
{
this.replaceInFileList('json', key, url);
}
else
{
this.addToFileList('json', key, url);
}
return this;
},
/**
* Add a JavaScript file to the Loader. Once loaded the JavaScript file will be automatically turned into a script tag (and executed), so be careful what you load!
* You can also specify a callback. This will be executed as soon as the script tag has been created.
*
* @method Phaser.Loader#script
* @param {string} key - Unique asset key of the script file.
* @param {string} url - URL of the JavaScript file.
* @param {function} [callback] - Optional callback that will be called after the script tag has loaded, so you can perform additional processing.
* @param {function} [callbackContext] - The context under which the callback will be applied. If not specified it will use the callback itself as the context.
* @return {Phaser.Loader} This Loader instance.
*/
script: function (key, url, callback, callbackContext) {
if (typeof callback === 'undefined') { callback = false; }
if (callback !== false && typeof callbackContext === 'undefined') { callbackContext = callback; }
this.addToFileList('script', key, url, { callback: callback, callbackContext: callbackContext });
return this;
},
/**
* Add a binary file to the Loader. It will be loaded via xhr with a responseType of "arraybuffer". You can specify an optional callback to process the file after load.
* When the callback is called it will be passed 2 parameters: the key of the file and the file data.
* WARNING: If you specify a callback, the file data will be set to whatever your callback returns. So always return the data object, even if you didn't modify it.
*
* @method Phaser.Loader#binary
* @param {string} key - Unique asset key of the binary file.
* @param {string} url - URL of the binary file.
* @param {function} [callback] - Optional callback that will be passed the file after loading, so you can perform additional processing on it.
* @param {function} [callbackContext] - The context under which the callback will be applied. If not specified it will use the callback itself as the context.
* @return {Phaser.Loader} This Loader instance.
*/
binary: function (key, url, callback, callbackContext) {
if (typeof callback === 'undefined') { callback = false; }
if (callback !== false && typeof callbackContext === 'undefined') { callbackContext = callback; }
this.addToFileList('binary', key, url, { callback: callback, callbackContext: callbackContext });
return this;
},
/**
* Add a new sprite sheet to the loader.
*
* @method Phaser.Loader#spritesheet
* @param {string} key - Unique asset key of the sheet file.
* @param {string} url - URL of the sheet file.
* @param {number} frameWidth - Width of each single frame.
* @param {number} frameHeight - Height of each single frame.
* @param {number} [frameMax=-1] - How many frames in this sprite sheet. If not specified it will divide the whole image into frames.
* @param {number} [margin=0] - If the frames have been drawn with a margin, specify the amount here.
* @param {number} [spacing=0] - If the frames have been drawn with spacing between them, specify the amount here.
* @return {Phaser.Loader} This Loader instance.
*/
spritesheet: function (key, url, frameWidth, frameHeight, frameMax, margin, spacing) {
if (typeof frameMax === "undefined") { frameMax = -1; }
if (typeof margin === "undefined") { margin = 0; }
if (typeof spacing === "undefined") { spacing = 0; }
this.addToFileList('spritesheet', key, url, { frameWidth: frameWidth, frameHeight: frameHeight, frameMax: frameMax, margin: margin, spacing: spacing });
return this;
},
/**
* Add a new audio file to the loader.
*
* @method Phaser.Loader#audio
* @param {string} key - Unique asset key of the audio file.
* @param {Array|string} urls - An array containing the URLs of the audio files, i.e.: [ 'jump.mp3', 'jump.ogg', 'jump.m4a' ] or a single string containing just one URL.
* @param {boolean} autoDecode - When using Web Audio the audio files can either be decoded at load time or run-time. They can't be played until they are decoded, but this let's you control when that happens. Decoding is a non-blocking async process.
* @return {Phaser.Loader} This Loader instance.
*/
audio: function (key, urls, autoDecode) {
if (typeof autoDecode === "undefined") { autoDecode = true; }
this.addToFileList('audio', key, urls, { buffer: null, autoDecode: autoDecode });
return this;
},
/**
* Add a new tilemap loading request.
*
* @method Phaser.Loader#tilemap
* @param {string} key - Unique asset key of the tilemap data.
* @param {string} [mapDataURL] - The url of the map data file (csv/json)
* @param {object} [mapData] - An optional JSON data object. If given then the mapDataURL is ignored and this JSON object is used for map data instead.
* @param {number} [format=Phaser.Tilemap.CSV] - The format of the map data. Either Phaser.Tilemap.CSV or Phaser.Tilemap.TILED_JSON.
* @return {Phaser.Loader} This Loader instance.
*/
tilemap: function (key, mapDataURL, mapData, format) {
if (typeof mapDataURL === "undefined") { mapDataURL = null; }
if (typeof mapData === "undefined") { mapData = null; }
if (typeof format === "undefined") { format = Phaser.Tilemap.CSV; }
if (mapDataURL == null && mapData == null)
{
console.warn('Phaser.Loader.tilemap - Both mapDataURL and mapData are null. One must be set.');
return this;
}
// A map data object has been given
if (mapData)
{
switch (format)
{
// A csv string or object has been given
case Phaser.Tilemap.CSV:
break;
// An xml string or object has been given
case Phaser.Tilemap.TILED_JSON:
if (typeof mapData === 'string')
{
mapData = JSON.parse(mapData);
}
break;
}
this.game.cache.addTilemap(key, null, mapData, format);
}
else
{
this.addToFileList('tilemap', key, mapDataURL, { format: format });
}
return this;
},
/**
* Add a new physics data object loading request.
* The data must be in Lime + Corona JSON format. Physics Editor by code'n'web exports in this format natively.
*
* @method Phaser.Loader#physics
* @param {string} key - Unique asset key of the physics json data.
* @param {string} [dataURL] - The url of the map data file (csv/json)
* @param {object} [jsonData] - An optional JSON data object. If given then the dataURL is ignored and this JSON object is used for physics data instead.
* @param {string} [format=Phaser.Physics.LIME_CORONA_JSON] - The format of the physics data.
* @return {Phaser.Loader} This Loader instance.
*/
physics: function (key, dataURL, jsonData, format) {
if (typeof dataURL === "undefined") { dataURL = null; }
if (typeof jsonData === "undefined") { jsonData = null; }
if (typeof format === "undefined") { format = Phaser.Physics.LIME_CORONA_JSON; }
if (dataURL == null && jsonData == null)
{
console.warn('Phaser.Loader.physics - Both dataURL and jsonData are null. One must be set.');
return this;
}
// A map data object has been given
if (jsonData)
{
if (typeof jsonData === 'string')
{
jsonData = JSON.parse(jsonData);
}
this.game.cache.addPhysicsData(key, null, jsonData, format);
}
else
{
this.addToFileList('physics', key, dataURL, { format: format });
}
return this;
},
/**
* Add a new bitmap font loading request.
*
* @method Phaser.Loader#bitmapFont
* @param {string} key - Unique asset key of the bitmap font.
* @param {string} textureURL - The url of the font image file.
* @param {string} [xmlURL] - The url of the font data file (xml/fnt)
* @param {object} [xmlData] - An optional XML data object.
* @param {number} [xSpacing=0] - If you'd like to add additional horizontal spacing between the characters then set the pixel value here.
* @param {number} [ySpacing=0] - If you'd like to add additional vertical spacing between the lines then set the pixel value here.
* @return {Phaser.Loader} This Loader instance.
*/
bitmapFont: function (key, textureURL, xmlURL, xmlData, xSpacing, ySpacing) {
if (typeof xmlURL === "undefined") { xmlURL = null; }
if (typeof xmlData === "undefined") { xmlData = null; }
if (typeof xSpacing === "undefined") { xSpacing = 0; }
if (typeof ySpacing === "undefined") { ySpacing = 0; }
// A URL to a json/xml file has been given
if (xmlURL)
{
this.addToFileList('bitmapfont', key, textureURL, { xmlURL: xmlURL, xSpacing: xSpacing, ySpacing: ySpacing });
}
else
{
// An xml string or object has been given
if (typeof xmlData === 'string')
{
var xml;
try {
if (window['DOMParser'])
{
var domparser = new DOMParser();
xml = domparser.parseFromString(xmlData, "text/xml");
}
else
{
xml = new ActiveXObject("Microsoft.XMLDOM");
xml.async = 'false';
xml.loadXML(xmlData);
}
}
catch (e)
{
xml = undefined;
}
if (!xml || !xml.documentElement || xml.getElementsByTagName("parsererror").length)
{
throw new Error("Phaser.Loader. Invalid Bitmap Font XML given");
}
else
{
this.addToFileList('bitmapfont', key, textureURL, { xmlURL: null, xmlData: xml, xSpacing: xSpacing, ySpacing: ySpacing });
}
}
}
return this;
},
/**
* Add a new texture atlas to the loader. This atlas uses the JSON Array data format.
*
* @method Phaser.Loader#atlasJSONArray
* @param {string} key - Unique asset key of the texture atlas file.
* @param {string} textureURL - The url of the texture atlas image file.
* @param {string} [atlasURL] - The url of the texture atlas data file (json/xml). You don't need this if you are passing an atlasData object instead.
* @param {object} [atlasData] - A JSON or XML data object. You don't need this if the data is being loaded from a URL.
* @return {Phaser.Loader} This Loader instance.
*/
atlasJSONArray: function (key, textureURL, atlasURL, atlasData) {
return this.atlas(key, textureURL, atlasURL, atlasData, Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY);
},
/**
* Add a new texture atlas to the loader. This atlas uses the JSON Hash data format.
*
* @method Phaser.Loader#atlasJSONHash
* @param {string} key - Unique asset key of the texture atlas file.
* @param {string} textureURL - The url of the texture atlas image file.
* @param {string} [atlasURL] - The url of the texture atlas data file (json/xml). You don't need this if you are passing an atlasData object instead.
* @param {object} [atlasData] - A JSON or XML data object. You don't need this if the data is being loaded from a URL.
* @return {Phaser.Loader} This Loader instance.
*/
atlasJSONHash: function (key, textureURL, atlasURL, atlasData) {
return this.atlas(key, textureURL, atlasURL, atlasData, Phaser.Loader.TEXTURE_ATLAS_JSON_HASH);
},
/**
* Add a new texture atlas to the loader. This atlas uses the Starling XML data format.
*
* @method Phaser.Loader#atlasXML
* @param {string} key - Unique asset key of the texture atlas file.
* @param {string} textureURL - The url of the texture atlas image file.
* @param {string} [atlasURL] - The url of the texture atlas data file (json/xml). You don't need this if you are passing an atlasData object instead.
* @param {object} [atlasData] - A JSON or XML data object. You don't need this if the data is being loaded from a URL.
* @return {Phaser.Loader} This Loader instance.
*/
atlasXML: function (key, textureURL, atlasURL, atlasData) {
return this.atlas(key, textureURL, atlasURL, atlasData, Phaser.Loader.TEXTURE_ATLAS_XML_STARLING);
},
/**
* Add a new texture atlas to the loader.
*
* @method Phaser.Loader#atlas
* @param {string} key - Unique asset key of the texture atlas file.
* @param {string} textureURL - The url of the texture atlas image file.
* @param {string} [atlasURL] - The url of the texture atlas data file (json/xml). You don't need this if you are passing an atlasData object instead.
* @param {object} [atlasData] - A JSON or XML data object. You don't need this if the data is being loaded from a URL.
* @param {number} [format] - A value describing the format of the data, the default is Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY.
* @return {Phaser.Loader} This Loader instance.
*/
atlas: function (key, textureURL, atlasURL, atlasData, format) {
if (typeof atlasURL === "undefined") { atlasURL = null; }
if (typeof atlasData === "undefined") { atlasData = null; }
if (typeof format === "undefined") { format = Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY; }
// A URL to a json/xml file has been given
if (atlasURL)
{
this.addToFileList('textureatlas', key, textureURL, { atlasURL: atlasURL, format: format });
}
else
{
switch (format)
{
// A json string or object has been given
case Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY:
if (typeof atlasData === 'string')
{
atlasData = JSON.parse(atlasData);
}
break;
// An xml string or object has been given
case Phaser.Loader.TEXTURE_ATLAS_XML_STARLING:
if (typeof atlasData === 'string')
{
var xml;
try {
if (window['DOMParser'])
{
var domparser = new DOMParser();
xml = domparser.parseFromString(atlasData, "text/xml");
}
else
{
xml = new ActiveXObject("Microsoft.XMLDOM");
xml.async = 'false';
xml.loadXML(atlasData);
}
}
catch (e)
{
xml = undefined;
}
if (!xml || !xml.documentElement || xml.getElementsByTagName("parsererror").length)
{
throw new Error("Phaser.Loader. Invalid Texture Atlas XML given");
}
else
{
atlasData = xml;
}
}
break;
}
this.addToFileList('textureatlas', key, textureURL, { atlasURL: null, atlasData: atlasData, format: format });
}
return this;
},
/**
* Remove loading request of a file.
*
* @method Phaser.Loader#removeFile
* @param {string} type - The type of resource to add to the list (image, audio, xml, etc).
* @param {string} key - Key of the file you want to remove.
*/
removeFile: function (type, key) {
var file = this.getAsset(type, key);
if (file !== false)
{
this._fileList.splice(file.index, 1);
}
},
/**
* Remove all file loading requests.
*
* @method Phaser.Loader#removeAll
*/
removeAll: function () {
this._fileList.length = 0;
},
/**
* Start loading the assets. Normally you don't need to call this yourself as the StateManager will do so.
*
* @method Phaser.Loader#start
*/
start: function () {
if (this.isLoading)
{
return;
}
this.progress = 0;
this.progressFloat = 0;
this.hasLoaded = false;
this.isLoading = true;
this.onLoadStart.dispatch(this._fileList.length);
if (this._fileList.length > 0)
{
this._fileIndex = 0;
this._progressChunk = 100 / this._fileList.length;
this.loadFile();
}
else
{
this.progress = 100;
this.progressFloat = 100;
this.hasLoaded = true;
this.onLoadComplete.dispatch();
}
},
/**
* Load files. Private method ONLY used by loader.
*
* @method Phaser.Loader#loadFile
* @private
*/
loadFile: function () {
if (!this._fileList[this._fileIndex])
{
console.warn('Phaser.Loader loadFile invalid index ' + this._fileIndex);
return;
}
var file = this._fileList[this._fileIndex];
var _this = this;
// Image or Data?
switch (file.type)
{
case 'image':
case 'spritesheet':
case 'textureatlas':
case 'bitmapfont':
file.data = new Image();
file.data.name = file.key;
file.data.onload = function () {
return _this.fileComplete(_this._fileIndex);
};
file.data.onerror = function () {
return _this.fileError(_this._fileIndex);
};
if (this.crossOrigin)
{
file.data.crossOrigin = this.crossOrigin;
}
file.data.src = this.baseURL + file.url;
break;
case 'audio':
file.url = this.getAudioURL(file.url);
if (file.url !== null)
{
// WebAudio or Audio Tag?
if (this.game.sound.usingWebAudio)
{
this._xhr.open("GET", this.baseURL + file.url, true);
this._xhr.responseType = "arraybuffer";
this._xhr.onload = function () {
return _this.fileComplete(_this._fileIndex);
};
this._xhr.onerror = function () {
return _this.fileError(_this._fileIndex);
};
this._xhr.send();
}
else if (this.game.sound.usingAudioTag)
{
if (this.game.sound.touchLocked)
{
// If audio is locked we can't do this yet, so need to queue this load request. Bum.
file.data = new Audio();
file.data.name = file.key;
file.data.preload = 'auto';
file.data.src = this.baseURL + file.url;
this.fileComplete(this._fileIndex);
}
else
{
file.data = new Audio();
file.data.name = file.key;
file.data.onerror = function () {
return _this.fileError(_this._fileIndex);
};
file.data.preload = 'auto';
file.data.src = this.baseURL + file.url;
file.data.addEventListener('canplaythrough', Phaser.GAMES[this.game.id].load.fileComplete(this._fileIndex), false);
file.data.load();
}
}
}
else
{
this.fileError(this._fileIndex);
}
break;
case 'json':
this._xhr.open("GET", this.baseURL + file.url, true);
this._xhr.responseType = "text";
this._xhr.onload = function () {
return _this.jsonLoadComplete(_this._fileIndex);
};
this._xhr.send();
break;
case 'tilemap':
this._xhr.open("GET", this.baseURL + file.url, true);
this._xhr.responseType = "text";
if (file.format === Phaser.Tilemap.TILED_JSON)
{
this._xhr.onload = function () {
return _this.jsonLoadComplete(_this._fileIndex);
};
}
else if (file.format === Phaser.Tilemap.CSV)
{
this._xhr.onload = function () {
return _this.csvLoadComplete(_this._fileIndex);
};
}
else
{
throw new Error("Phaser.Loader. Invalid Tilemap format: " + file.format);
}
this._xhr.onerror = function () {
return _this.dataLoadError(_this._fileIndex);
};
this._xhr.send();
break;
case 'text':
case 'script':
case 'physics':
this._xhr.open("GET", this.baseURL + file.url, true);
this._xhr.responseType = "text";
this._xhr.onload = function () {
return _this.fileComplete(_this._fileIndex);
};
this._xhr.onerror = function () {
return _this.fileError(_this._fileIndex);
};
this._xhr.send();
break;
case 'binary':
this._xhr.open("GET", this.baseURL + file.url, true);
this._xhr.responseType = "arraybuffer";
this._xhr.onload = function () {
return _this.fileComplete(_this._fileIndex);
};
this._xhr.onerror = function () {
return _this.fileError(_this._fileIndex);
};
this._xhr.send();
break;
}
},
/**
* Private method ONLY used by loader.
* @method Phaser.Loader#getAudioURL
* @param {array|string} urls - Either an array of audio file URLs or a string containing a single URL path.
* @private
*/
getAudioURL: function (urls) {
var extension;
if (typeof urls === 'string') { urls = [urls]; }
for (var i = 0; i < urls.length; i++)
{
extension = urls[i].toLowerCase();
extension = extension.substr((Math.max(0, extension.lastIndexOf(".")) || Infinity) + 1);
if (this.game.device.canPlayAudio(extension))
{
return urls[i];
}
}
return null;
},
/**
* Error occured when loading a file.
*
* @method Phaser.Loader#fileError
* @param {number} index - The index of the file in the file queue that errored.
*/
fileError: function (index) {
this._fileList[index].loaded = true;
this._fileList[index].error = true;
this.onFileError.dispatch(this._fileList[index].key, this._fileList[index]);
console.warn("Phaser.Loader error loading file: " + this._fileList[index].key + ' from URL ' + this._fileList[index].url);
this.nextFile(index, false);
},
/**
* Called when a file is successfully loaded.
*
* @method Phaser.Loader#fileComplete
* @param {number} index - The index of the file in the file queue that loaded.
*/
fileComplete: function (index) {
if (!this._fileList[index])
{
console.warn('Phaser.Loader fileComplete invalid index ' + index);
return;
}
var file = this._fileList[index];
file.loaded = true;
var loadNext = true;
var _this = this;
switch (file.type)
{
case 'image':
this.game.cache.addImage(file.key, file.url, file.data);
break;
case 'spritesheet':
this.game.cache.addSpriteSheet(file.key, file.url, file.data, file.frameWidth, file.frameHeight, file.frameMax, file.margin, file.spacing);
break;
case 'textureatlas':
if (file.atlasURL == null)
{
this.game.cache.addTextureAtlas(file.key, file.url, file.data, file.atlasData, file.format);
}
else
{
// Load the JSON or XML before carrying on with the next file
loadNext = false;
this._xhr.open("GET", this.baseURL + file.atlasURL, true);
this._xhr.responseType = "text";
if (file.format == Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY || file.format == Phaser.Loader.TEXTURE_ATLAS_JSON_HASH)
{
this._xhr.onload = function () {
return _this.jsonLoadComplete(index);
};
}
else if (file.format == Phaser.Loader.TEXTURE_ATLAS_XML_STARLING)
{
this._xhr.onload = function () {
return _this.xmlLoadComplete(index);
};
}
else
{
throw new Error("Phaser.Loader. Invalid Texture Atlas format: " + file.format);
}
this._xhr.onerror = function () {
return _this.dataLoadError(index);
};
this._xhr.send();
}
break;
case 'bitmapfont':
if (file.xmlURL == null)
{
this.game.cache.addBitmapFont(file.key, file.url, file.data, file.xmlData, file.xSpacing, file.ySpacing);
}
else
{
// Load the XML before carrying on with the next file
loadNext = false;
this._xhr.open("GET", this.baseURL + file.xmlURL, true);
this._xhr.responseType = "text";
this._xhr.onload = function () {
return _this.xmlLoadComplete(index);
};
this._xhr.onerror = function () {
return _this.dataLoadError(index);
};
this._xhr.send();
}
break;
case 'audio':
if (this.game.sound.usingWebAudio)
{
file.data = this._xhr.response;
this.game.cache.addSound(file.key, file.url, file.data, true, false);
if (file.autoDecode)
{
this.game.cache.updateSound(key, 'isDecoding', true);
var that = this;
var key = file.key;
this.game.sound.context.decodeAudioData(file.data, function (buffer) {
if (buffer)
{
that.game.cache.decodedSound(key, buffer);
that.game.sound.onSoundDecode.dispatch(key, that.game.cache.getSound(key));
}
});
}
}
else
{
file.data.removeEventListener('canplaythrough', Phaser.GAMES[this.game.id].load.fileComplete);
this.game.cache.addSound(file.key, file.url, file.data, false, true);
}
break;
case 'text':
file.data = this._xhr.responseText;
this.game.cache.addText(file.key, file.url, file.data);
break;
case 'physics':
var data = JSON.parse(this._xhr.responseText);
this.game.cache.addPhysicsData(file.key, file.url, data, file.format);
break;
case 'script':
file.data = document.createElement('script');
file.data.language = 'javascript';
file.data.type = 'text/javascript';
file.data.defer = false;
file.data.text = this._xhr.responseText;
document.head.appendChild(file.data);
if (file.callback)
{
file.data = file.callback.call(file.callbackContext, file.key, this._xhr.responseText);
}
break;
case 'binary':
if (file.callback)
{
file.data = file.callback.call(file.callbackContext, file.key, this._xhr.response);
}
else
{
file.data = this._xhr.response;
}
this.game.cache.addBinary(file.key, file.data);
break;
}
if (loadNext)
{
this.nextFile(index, true);
}
},
/**
* Successfully loaded a JSON file.
*
* @method Phaser.Loader#jsonLoadComplete
* @param {number} index - The index of the file in the file queue that loaded.
*/
jsonLoadComplete: function (index) {
if (!this._fileList[index])
{
console.warn('Phaser.Loader jsonLoadComplete invalid index ' + index);
return;
}
var file = this._fileList[index];
var data = JSON.parse(this._xhr.responseText);
file.loaded = true;
if (file.type === 'tilemap')
{
this.game.cache.addTilemap(file.key, file.url, data, file.format);
}
else if (file.type === 'json')
{
this.game.cache.addJSON(file.key, file.url, data);
}
else
{
this.game.cache.addTextureAtlas(file.key, file.url, file.data, data, file.format);
}
this.nextFile(index, true);
},
/**
* Successfully loaded a CSV file.
*
* @method Phaser.Loader#csvLoadComplete
* @param {number} index - The index of the file in the file queue that loaded.
*/
csvLoadComplete: function (index) {
if (!this._fileList[index])
{
console.warn('Phaser.Loader csvLoadComplete invalid index ' + index);
return;
}
var file = this._fileList[index];
var data = this._xhr.responseText;
file.loaded = true;
this.game.cache.addTilemap(file.key, file.url, data, file.format);
this.nextFile(index, true);
},
/**
* Error occured when load a JSON.
*
* @method Phaser.Loader#dataLoadError
* @param {number} index - The index of the file in the file queue that errored.
*/
dataLoadError: function (index) {
var file = this._fileList[index];
file.loaded = true;
file.error = true;
console.warn("Phaser.Loader dataLoadError: " + file.key);
this.nextFile(index, true);
},
/**
* Successfully loaded an XML file.
*
* @method Phaser.Loader#xmlLoadComplete
* @param {number} index - The index of the file in the file queue that loaded.
*/
xmlLoadComplete: function (index) {
var data = this._xhr.responseText;
var xml;
try
{
if (window['DOMParser'])
{
var domparser = new DOMParser();
xml = domparser.parseFromString(data, "text/xml");
}
else
{
xml = new ActiveXObject("Microsoft.XMLDOM");
xml.async = 'false';
xml.loadXML(data);
}
}
catch (e)
{
xml = undefined;
}
if (!xml || !xml.documentElement || xml.getElementsByTagName("parsererror").length)
{
throw new Error("Phaser.Loader. Invalid XML given");
}
var file = this._fileList[index];
file.loaded = true;
if (file.type == 'bitmapfont')
{
this.game.cache.addBitmapFont(file.key, file.url, file.data, xml, file.xSpacing, file.ySpacing);
}
else if (file.type == 'textureatlas')
{
this.game.cache.addTextureAtlas(file.key, file.url, file.data, xml, file.format);
}
this.nextFile(index, true);
},
/**
* Handle loading next file.
*
* @param {number} previousIndex - Index of the previously loaded asset.
* @param {boolean} success - Whether the previous asset loaded successfully or not.
* @private
*/
nextFile: function (previousIndex, success) {
this.progressFloat += this._progressChunk;
this.progress = Math.round(this.progressFloat);
if (this.progress > 100)
{
this.progress = 100;
}
if (this.preloadSprite !== null)
{
if (this.preloadSprite.direction === 0)
{
this.preloadSprite.crop.width = Math.floor((this.preloadSprite.width / 100) * this.progress);
}
else
{
this.preloadSprite.crop.height = Math.floor((this.preloadSprite.height / 100) * this.progress);
}
}
this.onFileComplete.dispatch(this.progress, this._fileList[previousIndex].key, success, this.totalLoadedFiles(), this._fileList.length);
if (this.totalQueuedFiles() > 0)
{
this._fileIndex++;
this.loadFile();
}
else
{
this.hasLoaded = true;
this.isLoading = false;
this.removeAll();
this.onLoadComplete.dispatch();
}
},
/**
* Returns the number of files that have already been loaded, even if they errored.
*
* @return {number} The number of files that have already been loaded (even if they errored)
*/
totalLoadedFiles: function () {
var total = 0;
for (var i = 0; i < this._fileList.length; i++)
{
if (this._fileList[i].loaded)
{
total++;
}
}
return total;
},
/**
* Returns the number of files still waiting to be processed in the load queue. This value decreases as each file is in the queue is loaded.
*
* @return {number} The number of files that still remain in the load queue.
*/
totalQueuedFiles: function () {
var total = 0;
for (var i = 0; i < this._fileList.length; i++)
{
if (this._fileList[i].loaded === false)
{
total++;
}
}
return total;
}
};
Phaser.Loader.prototype.constructor = Phaser.Loader;
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2014 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* Phaser.LoaderParser parses data objects from Phaser.Loader that need more preparation before they can be inserted into the Cache.
*
* @class Phaser.LoaderParser
*/
Phaser.LoaderParser = {
/**
* Parse a Bitmap Font from an XML file.
* @method Phaser.LoaderParser.bitmapFont
* @param {Phaser.Game} game - A reference to the current game.
* @param {object} xml - XML data you want to parse.
* @param {string} cacheKey - The key of the texture this font uses in the cache.
*/
bitmapFont: function (game, xml, cacheKey, xSpacing, ySpacing) {
if (!xml || /MSIE 9/i.test(navigator.userAgent) || navigator.isCocoonJS)
{
if (typeof(window.DOMParser) === 'function')
{
var domparser = new DOMParser();
xml = domparser.parseFromString(this.ajaxRequest.responseText, 'text/xml');
}
else
{
var div = document.createElement('div');
div.innerHTML = this.ajaxRequest.responseText;
xml = div;
}
}
var data = {};
var info = xml.getElementsByTagName('info')[0];
var common = xml.getElementsByTagName('common')[0];
data.font = info.getAttribute('face');
data.size = parseInt(info.getAttribute('size'), 10);
data.lineHeight = parseInt(common.getAttribute('lineHeight'), 10) + ySpacing;
data.chars = {};
var letters = xml.getElementsByTagName('char');
var texture = PIXI.TextureCache[cacheKey];
for (var i = 0; i < letters.length; i++)
{
var charCode = parseInt(letters[i].getAttribute('id'), 10);
var textureRect = new PIXI.Rectangle(
parseInt(letters[i].getAttribute('x'), 10),
parseInt(letters[i].getAttribute('y'), 10),
parseInt(letters[i].getAttribute('width'), 10),
parseInt(letters[i].getAttribute('height'), 10)
);
data.chars[charCode] = {
xOffset: parseInt(letters[i].getAttribute('xoffset'), 10),
yOffset: parseInt(letters[i].getAttribute('yoffset'), 10),
xAdvance: parseInt(letters[i].getAttribute('xadvance'), 10) + xSpacing,
kerning: {},
texture: PIXI.TextureCache[cacheKey] = new PIXI.Texture(texture, textureRect)
};
}
var kernings = xml.getElementsByTagName('kerning');
for (i = 0; i < kernings.length; i++)
{
var first = parseInt(kernings[i].getAttribute('first'), 10);
var second = parseInt(kernings[i].getAttribute('second'), 10);
var amount = parseInt(kernings[i].getAttribute('amount'), 10);
data.chars[second].kerning[first] = amount;
}
PIXI.BitmapText.fonts[cacheKey] = data;
}
};
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2014 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* The Sound class constructor.
*
* @class Phaser.Sound
* @classdesc The Sound class
* @constructor
* @param {Phaser.Game} game - Reference to the current game instance.
* @param {string} key - Asset key for the sound.
* @param {number} [volume=1] - Default value for the volume, between 0 and 1.
* @param {boolean} [loop=false] - Whether or not the sound will loop.
*/
Phaser.Sound = function (game, key, volume, loop, connect) {
if (typeof volume == 'undefined') { volume = 1; }
if (typeof loop == 'undefined') { loop = false; }
if (typeof connect === 'undefined') { connect = game.sound.connectToMaster; }
/**
* A reference to the currently running Game.
* @property {Phaser.Game} game
*/
this.game = game;
/**
* @property {string} name - Name of the sound.
*/
this.name = key;
/**
* @property {string} key - Asset key for the sound.
*/
this.key = key;
/**
* @property {boolean} loop - Whether or not the sound will loop.
*/
this.loop = loop;
/**
* @property {number} _volume - The global audio volume. A value between 0 (silence) and 1 (full volume).
* @private
*/
this._volume = volume;
/**
* @property {object} markers - The sound markers.
*/
this.markers = {};
/**
* @property {AudioContext} context - Reference to the AudioContext instance.
*/
this.context = null;
/**
* @property {Description} _buffer - Decoded data buffer / Audio tag.
* @private
*/
this._buffer = null;
/**
* @property {boolean} _muted - Boolean indicating whether the sound is muted or not.
* @private
* @default
*/
this._muted = false;
/**
* @property {boolean} autoplay - Boolean indicating whether the sound should start automatically.
*/
this.autoplay = false;
/**
* @property {number} totalDuration - The total duration of the sound, in milliseconds
*/
this.totalDuration = 0;
/**
* @property {number} startTime - The time the Sound starts at (typically 0 unless starting from a marker)
* @default
*/
this.startTime = 0;
/**
* @property {number} currentTime - The current time the sound is at.
*/
this.currentTime = 0;
/**
* @property {number} duration - The duration of the sound.
*/
this.duration = 0;
/**
* @property {number} stopTime - The time the sound stopped.
*/
this.stopTime = 0;
/**
* @property {boolean} paused - true if the sound is paused, otherwise false.
* @default
*/
this.paused = false;
/**
* @property {number} pausedPosition - The position the sound had reached when it was paused.
*/
this.pausedPosition = 0;
/**
* @property {number} pausedTime - The game time at which the sound was paused.
*/
this.pausedTime = 0;
/**
* @property {boolean} isPlaying - true if the sound is currently playing, otherwise false.
* @default
*/
this.isPlaying = false;
/**
* @property {string} currentMarker - The string ID of the currently playing marker, if any.
* @default
*/
this.currentMarker = '';
/**
* @property {boolean} pendingPlayback - true if the sound file is pending playback
* @readonly
*/
this.pendingPlayback = false;
/**
* @property {boolean} override - if true when you play this sound it will always start from the beginning.
* @default
*/
this.override = false;
/**
* @property {boolean} usingWebAudio - true if this sound is being played with Web Audio.
* @readonly
*/
this.usingWebAudio = this.game.sound.usingWebAudio;
/**
* @property {boolean} usingAudioTag - true if the sound is being played via the Audio tag.
*/
this.usingAudioTag = this.game.sound.usingAudioTag;
/**
* @property {object} externalNode - If defined this Sound won't connect to the SoundManager master gain node, but will instead connect to externalNode.input.
*/
this.externalNode = null;
if (this.usingWebAudio)
{
this.context = this.game.sound.context;
this.masterGainNode = this.game.sound.masterGain;
if (typeof this.context.createGain === 'undefined')
{
this.gainNode = this.context.createGainNode();
}
else
{
this.gainNode = this.context.createGain();
}
this.gainNode.gain.value = volume * this.game.sound.volume;
if (connect)
{
this.gainNode.connect(this.masterGainNode);
}
}
else
{
if (this.game.cache.getSound(key) && this.game.cache.isSoundReady(key))
{
this._sound = this.game.cache.getSoundData(key);
this.totalDuration = 0;
if (this._sound.duration)
{
this.totalDuration = this._sound.duration;
}
}
else
{
this.game.cache.onSoundUnlock.add(this.soundHasUnlocked, this);
}
}
/**
* @property {Phaser.Signal} onDecoded - The onDecoded event is dispatched when the sound has finished decoding (typically for mp3 files)
*/
this.onDecoded = new Phaser.Signal();
/**
* @property {Phaser.Signal} onPlay - The onPlay event is dispatched each time this sound is played.
*/
this.onPlay = new Phaser.Signal();
/**
* @property {Phaser.Signal} onPause - The onPause event is dispatched when this sound is paused.
*/
this.onPause = new Phaser.Signal();
/**
* @property {Phaser.Signal} onResume - The onResume event is dispatched when this sound is resumed from a paused state.
*/
this.onResume = new Phaser.Signal();
/**
* @property {Phaser.Signal} onLoop - The onLoop event is dispatched when this sound loops during playback.
*/
this.onLoop = new Phaser.Signal();
/**
* @property {Phaser.Signal} onStop - The onStop event is dispatched when this sound stops playback.
*/
this.onStop = new Phaser.Signal();
/**
* @property {Phaser.Signal} onMute - The onMouse event is dispatched when this sound is muted.
*/
this.onMute = new Phaser.Signal();
/**
* @property {Phaser.Signal} onMarkerComplete - The onMarkerComplete event is dispatched when a marker within this sound completes playback.
*/
this.onMarkerComplete = new Phaser.Signal();
};
Phaser.Sound.prototype = {
/**
* Called automatically when this sound is unlocked.
* @method Phaser.Sound#soundHasUnlocked
* @param {string} key - The Phaser.Cache key of the sound file to check for decoding.
* @protected
*/
soundHasUnlocked: function (key) {
if (key == this.key)
{
this._sound = this.game.cache.getSoundData(this.key);
this.totalDuration = this._sound.duration;
// console.log('sound has unlocked' + this._sound);
}
},
/**
* Description.
* @method Phaser.Sound#addMarker
* @param {string} name - Description.
* @param {Description} start - Description.
* @param {Description} stop - Description.
* @param {Description} volume - Description.
* @param {Description} loop - Description.
addMarker: function (name, start, stop, volume, loop) {
volume = volume || 1;
if (typeof loop == 'undefined') { loop = false; }
this.markers[name] = {
name: name,
start: start,
stop: stop,
volume: volume,
duration: stop - start,
loop: loop
};
},
*/
/**
* Adds a marker into the current Sound. A marker is represented by a unique key and a start time and duration.
* This allows you to bundle multiple sounds together into a single audio file and use markers to jump between them for playback.
*
* @method Phaser.Sound#addMarker
* @param {string} name - A unique name for this marker, i.e. 'explosion', 'gunshot', etc.
* @param {number} start - The start point of this marker in the audio file, given in seconds. 2.5 = 2500ms, 0.5 = 500ms, etc.
* @param {number} duration - The duration of the marker in seconds. 2.5 = 2500ms, 0.5 = 500ms, etc.
* @param {number} [volume=1] - The volume the sound will play back at, between 0 (silent) and 1 (full volume).
* @param {boolean} [loop=false] - Sets if the sound will loop or not.
*/
addMarker: function (name, start, duration, volume, loop) {
volume = volume || 1;
if (typeof loop == 'undefined') { loop = false; }
this.markers[name] = {
name: name,
start: start,
stop: start + duration,
volume: volume,
duration: duration,
durationMS: duration * 1000,
loop: loop
};
},
/**
* Removes a marker from the sound.
* @method Phaser.Sound#removeMarker
* @param {string} name - The key of the marker to remove.
*/
removeMarker: function (name) {
delete this.markers[name];
},
/**
* Called automatically by Phaser.SoundManager.
* @method Phaser.Sound#update
* @protected
*/
update: function () {
if (this.pendingPlayback && this.game.cache.isSoundReady(this.key))
{
this.pendingPlayback = false;
this.play(this._tempMarker, this._tempPosition, this._tempVolume, this._tempLoop);
}
if (this.isPlaying)
{
this.currentTime = this.game.time.now - this.startTime;
if (this.currentTime >= this.durationMS)
{
// console.log(this.currentMarker, 'has hit duration');
if (this.usingWebAudio)
{
if (this.loop)
{
// console.log('loop1');
// won't work with markers, needs to reset the position
this.onLoop.dispatch(this);
if (this.currentMarker === '')
{
// console.log('loop2');
this.currentTime = 0;
this.startTime = this.game.time.now;
}
else
{
// console.log('loop3');
this.onMarkerComplete.dispatch(this.currentMarker, this);
this.play(this.currentMarker, 0, this.volume, true, true);
}
}
else
{
// console.log('stopping, no loop for marker');
this.stop();
}
}
else
{
if (this.loop)
{
this.onLoop.dispatch(this);
this.play(this.currentMarker, 0, this.volume, true, true);
}
else
{
this.stop();
}
}
}
}
},
/**
* Play this sound, or a marked section of it.
* @method Phaser.Sound#play
* @param {string} [marker=''] - If you want to play a marker then give the key here, otherwise leave blank to play the full sound.
* @param {number} [position=0] - The starting position to play the sound from - this is ignored if you provide a marker.
* @param {number} [volume=1] - Volume of the sound you want to play. If none is given it will use the volume given to the Sound when it was created (which defaults to 1 if none was specified).
* @param {boolean} [loop=false] - Loop when it finished playing?
* @param {boolean} [forceRestart=true] - If the sound is already playing you can set forceRestart to restart it from the beginning.
* @return {Phaser.Sound} This sound instance.
*/
play: function (marker, position, volume, loop, forceRestart) {
marker = marker || '';
position = position || 0;
if (typeof volume === 'undefined') { volume = this._volume; }
if (typeof loop === 'undefined') { loop = this.loop; }
if (typeof forceRestart === 'undefined') { forceRestart = true; }
// console.log(this.name + ' play ' + marker + ' position ' + position + ' volume ' + volume + ' loop ' + loop, 'force', forceRestart);
if (this.isPlaying === true && forceRestart === false && this.override === false)
{
// Use Restart instead
return;
}
if (this.isPlaying && this.override)
{
// console.log('asked to play ' + marker + ' but already playing ' + this.currentMarker);
if (this.usingWebAudio)
{
if (typeof this._sound.stop === 'undefined')
{
this._sound.noteOff(0);
}
else
{
this._sound.stop(0);
}
}
else if (this.usingAudioTag)
{
this._sound.pause();
this._sound.currentTime = 0;
}
}
this.currentMarker = marker;
if (marker !== '')
{
if (this.markers[marker])
{
this.position = this.markers[marker].start;
this.volume = this.markers[marker].volume;
this.loop = this.markers[marker].loop;
this.duration = this.markers[marker].duration;
this.durationMS = this.markers[marker].durationMS;
// console.log('Marker Loaded: ', marker, 'start:', this.position, 'end: ', this.duration, 'loop', this.loop);
this._tempMarker = marker;
this._tempPosition = this.position;
this._tempVolume = this.volume;
this._tempLoop = this.loop;
}
else
{
console.warn("Phaser.Sound.play: audio marker " + marker + " doesn't exist");
return;
}
}
else
{
// console.log('no marker info loaded', marker);
this.position = position;
this.volume = volume;
this.loop = loop;
this.duration = 0;
this.durationMS = 0;
this._tempMarker = marker;
this._tempPosition = position;
this._tempVolume = volume;
this._tempLoop = loop;
}
if (this.usingWebAudio)
{
// Does the sound need decoding?
if (this.game.cache.isSoundDecoded(this.key))
{
// Do we need to do this every time we play? How about just if the buffer is empty?
if (this._buffer == null)
{
this._buffer = this.game.cache.getSoundData(this.key);
}
this._sound = this.context.createBufferSource();
this._sound.buffer = this._buffer;
if (this.externalNode)
{
this._sound.connect(this.externalNode.input);
}
else
{
this._sound.connect(this.gainNode);
}
this.totalDuration = this._sound.buffer.duration;
if (this.duration === 0)
{
// console.log('duration reset');
this.duration = this.totalDuration;
this.durationMS = this.totalDuration * 1000;
}
if (this.loop && marker === '')
{
this._sound.loop = true;
}
// Useful to cache this somewhere perhaps?
if (typeof this._sound.start === 'undefined')
{
this._sound.noteGrainOn(0, this.position, this.duration);
// this._sound.noteGrainOn(0, this.position, this.duration / 1000);
//this._sound.noteOn(0); // the zero is vitally important, crashes iOS6 without it
}
else
{
// this._sound.start(0, this.position, this.duration / 1000);
this._sound.start(0, this.position, this.duration);
}
this.isPlaying = true;
this.startTime = this.game.time.now;
this.currentTime = 0;
this.stopTime = this.startTime + this.durationMS;
this.onPlay.dispatch(this);
}
else
{
this.pendingPlayback = true;
if (this.game.cache.getSound(this.key) && this.game.cache.getSound(this.key).isDecoding === false)
{
this.game.sound.decode(this.key, this);
}
}
}
else
{
// console.log('Sound play Audio');
if (this.game.cache.getSound(this.key) && this.game.cache.getSound(this.key).locked)
{
// console.log('tried playing locked sound, pending set, reload started');
this.game.cache.reloadSound(this.key);
this.pendingPlayback = true;
}
else
{
// console.log('sound not locked, state?', this._sound.readyState);
if (this._sound && (this.game.device.cocoonJS || this._sound.readyState === 4))
{
this._sound.play();
// This doesn't become available until you call play(), wonderful ...
this.totalDuration = this._sound.duration;
if (this.duration === 0)
{
this.duration = this.totalDuration;
this.durationMS = this.totalDuration * 1000;
}
// console.log('playing', this._sound);
this._sound.currentTime = this.position;
this._sound.muted = this._muted;
if (this._muted)
{
this._sound.volume = 0;
}
else
{
this._sound.volume = this._volume;
}
this.isPlaying = true;
this.startTime = this.game.time.now;
this.currentTime = 0;
this.stopTime = this.startTime + this.durationMS;
this.onPlay.dispatch(this);
}
else
{
this.pendingPlayback = true;
}
}
}
},
/**
* Restart the sound, or a marked section of it.
* @method Phaser.Sound#restart
* @param {string} [marker=''] - If you want to play a marker then give the key here, otherwise leave blank to play the full sound.
* @param {number} [position=0] - The starting position to play the sound from - this is ignored if you provide a marker.
* @param {number} [volume=1] - Volume of the sound you want to play.
* @param {boolean} [loop=false] - Loop when it finished playing?
*/
restart: function (marker, position, volume, loop) {
marker = marker || '';
position = position || 0;
volume = volume || 1;
if (typeof loop == 'undefined') { loop = false; }
this.play(marker, position, volume, loop, true);
},
/**
* Pauses the sound
* @method Phaser.Sound#pause
*/
pause: function () {
if (this.isPlaying && this._sound)
{
this.stop();
this.isPlaying = false;
this.paused = true;
this.pausedPosition = this.currentTime;
this.pausedTime = this.game.time.now;
this.onPause.dispatch(this);
}
},
/**
* Resumes the sound
* @method Phaser.Sound#resume
*/
resume: function () {
if (this.paused && this._sound)
{
if (this.usingWebAudio)
{
var p = this.position + (this.pausedPosition / 1000);
this._sound = this.context.createBufferSource();
this._sound.buffer = this._buffer;
if (this.externalNode)
{
this._sound.connect(this.externalNode.input);
}
else
{
this._sound.connect(this.gainNode);
}
if (this.loop)
{
this._sound.loop = true;
}
if (typeof this._sound.start === 'undefined')
{
this._sound.noteGrainOn(0, p, this.duration);
//this._sound.noteOn(0); // the zero is vitally important, crashes iOS6 without it
}
else
{
this._sound.start(0, p, this.duration);
}
}
else
{
this._sound.play();
}
this.isPlaying = true;
this.paused = false;
this.startTime += (this.game.time.now - this.pausedTime);
this.onResume.dispatch(this);
}
},
/**
* Stop playing this sound.
* @method Phaser.Sound#stop
*/
stop: function () {
if (this.isPlaying && this._sound)
{
if (this.usingWebAudio)
{
if (typeof this._sound.stop === 'undefined')
{
this._sound.noteOff(0);
}
else
{
this._sound.stop(0);
}
}
else if (this.usingAudioTag)
{
this._sound.pause();
this._sound.currentTime = 0;
}
}
this.isPlaying = false;
var prevMarker = this.currentMarker;
if (this.currentMarker !== '')
{
this.onMarkerComplete.dispatch(this.currentMarker, this);
}
this.currentMarker = '';
this.onStop.dispatch(this, prevMarker);
}
};
Phaser.Sound.prototype.constructor = Phaser.Sound;
/**
* @name Phaser.Sound#isDecoding
* @property {boolean} isDecoding - Returns true if the sound file is still decoding.
* @readonly
*/
Object.defineProperty(Phaser.Sound.prototype, "isDecoding", {
get: function () {
return this.game.cache.getSound(this.key).isDecoding;
}
});
/**
* @name Phaser.Sound#isDecoded
* @property {boolean} isDecoded - Returns true if the sound file has decoded.
* @readonly
*/
Object.defineProperty(Phaser.Sound.prototype, "isDecoded", {
get: function () {
return this.game.cache.isSoundDecoded(this.key);
}
});
/**
* @name Phaser.Sound#mute
* @property {boolean} mute - Gets or sets the muted state of this sound.
*/
Object.defineProperty(Phaser.Sound.prototype, "mute", {
get: function () {
return this._muted;
},
set: function (value) {
value = value || null;
if (value)
{
this._muted = true;
if (this.usingWebAudio)
{
this._muteVolume = this.gainNode.gain.value;
this.gainNode.gain.value = 0;
}
else if (this.usingAudioTag && this._sound)
{
this._muteVolume = this._sound.volume;
this._sound.volume = 0;
}
}
else
{
this._muted = false;
if (this.usingWebAudio)
{
this.gainNode.gain.value = this._muteVolume;
}
else if (this.usingAudioTag && this._sound)
{
this._sound.volume = this._muteVolume;
}
}
this.onMute.dispatch(this);
}
});
/**
* @name Phaser.Sound#volume
* @property {number} volume - Gets or sets the volume of this sound, a value between 0 and 1.
* @readonly
*/
Object.defineProperty(Phaser.Sound.prototype, "volume", {
get: function () {
return this._volume;
},
set: function (value) {
if (this.usingWebAudio)
{
this._volume = value;
this.gainNode.gain.value = value;
}
else if (this.usingAudioTag && this._sound)
{
// Causes an Index size error in Firefox if you don't clamp the value
if (value >= 0 && value <= 1)
{
this._volume = value;
this._sound.volume = value;
}
}
}
});
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2014 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* Sound Manager constructor.
* The Sound Manager is responsible for playing back audio via either the Legacy HTML Audio tag or via Web Audio if the browser supports it.
* Note: On Firefox 25+ on Linux if you have media.gstreamer disabled in about:config then it cannot play back mp3 or m4a files.
*
* @class Phaser.SoundManager
* @classdesc Phaser Sound Manager.
* @constructor
* @param {Phaser.Game} game reference to the current game instance.
*/
Phaser.SoundManager = function (game) {
/**
* @property {Phaser.Game} game - Local reference to game.
*/
this.game = game;
/**
* @property {Phaser.Signal} onSoundDecode - The event dispatched when a sound decodes (typically only for mp3 files)
*/
this.onSoundDecode = new Phaser.Signal();
/**
* @property {boolean} _codeMuted - Internal mute tracking var.
* @private
* @default
*/
this._codeMuted = false;
/**
* @property {boolean} _muted - Internal mute tracking var.
* @private
* @default
*/
this._muted = false;
/**
* @property {Description} _unlockSource - Internal unlock tracking var.
* @private
* @default
*/
this._unlockSource = null;
/**
* @property {number} _volume - The global audio volume. A value between 0 (silence) and 1 (full volume).
* @private
* @default
*/
this._volume = 1;
/**
* @property {array} _sounds - An array containing all the sounds
* @private
* @default The empty array.
*/
this._sounds = [];
/**
* @property {AudioContext} context - The AudioContext being used for playback.
* @default
*/
this.context = null;
/**
* @property {boolean} usingWebAudio - true if this sound is being played with Web Audio.
* @readonly
*/
this.usingWebAudio = true;
/**
* @property {boolean} usingAudioTag - true if the sound is being played via the Audio tag.
* @readonly
*/
this.usingAudioTag = false;
/**
* @property {boolean} noAudio - Has audio been disabled via the PhaserGlobal object? Useful if you need to use a 3rd party audio library instead.
* @default
*/
this.noAudio = false;
/**
* @property {boolean} connectToMaster - Used in conjunction with Sound.externalNode this allows you to stop a Sound node being connected to the SoundManager master gain node.
* @default
*/
this.connectToMaster = true;
/**
* @property {boolean} touchLocked - true if the audio system is currently locked awaiting a touch event.
* @default
*/
this.touchLocked = false;
/**
* @property {number} channels - The number of audio channels to use in playback.
* @default
*/
this.channels = 32;
};
Phaser.SoundManager.prototype = {
/**
* Initialises the sound manager.
* @method Phaser.SoundManager#boot
* @protected
*/
boot: function () {
if (this.game.device.iOS && this.game.device.webAudio === false)
{
this.channels = 1;
}
if (this.game.device.iOS || (window['PhaserGlobal'] && window['PhaserGlobal'].fakeiOSTouchLock))
{
this.game.input.touch.callbackContext = this;
this.game.input.touch.touchStartCallback = this.unlock;
this.game.input.mouse.callbackContext = this;
this.game.input.mouse.mouseDownCallback = this.unlock;
this.touchLocked = true;
}
else
{
// What about iOS5?
this.touchLocked = false;
}
if (window['PhaserGlobal'])
{
// Check to see if all audio playback is disabled (i.e. handled by a 3rd party class)
if (window['PhaserGlobal'].disableAudio === true)
{
this.usingWebAudio = false;
this.noAudio = true;
return;
}
// Check if the Web Audio API is disabled (for testing Audio Tag playback during development)
if (window['PhaserGlobal'].disableWebAudio === true)
{
this.usingWebAudio = false;
this.usingAudioTag = true;
this.noAudio = false;
return;
}
}
if (!!window['AudioContext'])
{
this.context = new window['AudioContext']();
}
else if (!!window['webkitAudioContext'])
{
this.context = new window['webkitAudioContext']();
}
else if (!!window['Audio'])
{
this.usingWebAudio = false;
this.usingAudioTag = true;
}
else
{
this.usingWebAudio = false;
this.noAudio = true;
}
if (this.context !== null)
{
if (typeof this.context.createGain === 'undefined')
{
this.masterGain = this.context.createGainNode();
}
else
{
this.masterGain = this.context.createGain();
}
this.masterGain.gain.value = 1;
this.masterGain.connect(this.context.destination);
}
},
/**
* Enables the audio, usually after the first touch.
* @method Phaser.SoundManager#unlock
*/
unlock: function () {
if (this.touchLocked === false)
{
return;
}
// Global override (mostly for Audio Tag testing)
if (this.game.device.webAudio === false || (window['PhaserGlobal'] && window['PhaserGlobal'].disableWebAudio === true))
{
// Create an Audio tag?
this.touchLocked = false;
this._unlockSource = null;
this.game.input.touch.callbackContext = null;
this.game.input.touch.touchStartCallback = null;
this.game.input.mouse.callbackContext = null;
this.game.input.mouse.mouseDownCallback = null;
}
else
{
// Create empty buffer and play it
var buffer = this.context.createBuffer(1, 1, 22050);
this._unlockSource = this.context.createBufferSource();
this._unlockSource.buffer = buffer;
this._unlockSource.connect(this.context.destination);
this._unlockSource.noteOn(0);
}
},
/**
* Stops all the sounds in the game.
* @method Phaser.SoundManager#stopAll
*/
stopAll: function () {
for (var i = 0; i < this._sounds.length; i++)
{
if (this._sounds[i])
{
this._sounds[i].stop();
}
}
},
/**
* Pauses all the sounds in the game.
* @method Phaser.SoundManager#pauseAll
*/
pauseAll: function () {
for (var i = 0; i < this._sounds.length; i++)
{
if (this._sounds[i])
{
this._sounds[i].pause();
}
}
},
/**
* resumes every sound in the game.
* @method Phaser.SoundManager#resumeAll
*/
resumeAll: function () {
for (var i = 0; i < this._sounds.length; i++)
{
if (this._sounds[i])
{
this._sounds[i].resume();
}
}
},
/**
* Decode a sound by its assets key.
* @method Phaser.SoundManager#decode
* @param {string} key - Assets key of the sound to be decoded.
* @param {Phaser.Sound} [sound] - Its buffer will be set to decoded data.
*/
decode: function (key, sound) {
sound = sound || null;
var soundData = this.game.cache.getSoundData(key);
if (soundData)
{
if (this.game.cache.isSoundDecoded(key) === false)
{
this.game.cache.updateSound(key, 'isDecoding', true);
var that = this;
this.context.decodeAudioData(soundData, function (buffer) {
that.game.cache.decodedSound(key, buffer);
if (sound)
{
that.onSoundDecode.dispatch(key, sound);
}
});
}
}
},
/**
* Updates every sound in the game.
* @method Phaser.SoundManager#update
*/
update: function () {
if (this.touchLocked)
{
if (this.game.device.webAudio && this._unlockSource !== null)
{
if ((this._unlockSource.playbackState === this._unlockSource.PLAYING_STATE || this._unlockSource.playbackState === this._unlockSource.FINISHED_STATE))
{
this.touchLocked = false;
this._unlockSource = null;
this.game.input.touch.callbackContext = null;
this.game.input.touch.touchStartCallback = null;
}
}
}
for (var i = 0; i < this._sounds.length; i++)
{
this._sounds[i].update();
}
},
/**
* Adds a new Sound into the SoundManager.
* @method Phaser.SoundManager#add
* @param {string} key - Asset key for the sound.
* @param {number} [volume=1] - Default value for the volume.
* @param {boolean} [loop=false] - Whether or not the sound will loop.
* @param {boolean} [connect=true] - Controls if the created Sound object will connect to the master gainNode of the SoundManager when running under WebAudio.
* @return {Phaser.Sound} The new sound instance.
*/
add: function (key, volume, loop, connect) {
if (typeof volume === 'undefined') { volume = 1; }
if (typeof loop === 'undefined') { loop = false; }
if (typeof connect === 'undefined') { connect = this.connectToMaster; }
var sound = new Phaser.Sound(this.game, key, volume, loop, connect);
this._sounds.push(sound);
return sound;
},
/**
* Adds a new Sound into the SoundManager and starts it playing.
* @method Phaser.SoundManager#play
* @param {string} key - Asset key for the sound.
* @param {number} [volume=1] - Default value for the volume.
* @param {boolean} [loop=false] - Whether or not the sound will loop.
* @return {Phaser.Sound} The new sound instance.
*/
play: function (key, volume, loop) {
var sound = this.add(key, volume, loop);
sound.play();
return sound;
},
/**
* Internal mute handler called automatically by the Sound.mute setter.
*
* @method Phaser.SoundManager#setMute
* @private
*/
setMute: function () {
if (this._muted)
{
return;
}
this._muted = true;
if (this.usingWebAudio)
{
this._muteVolume = this.masterGain.gain.value;
this.masterGain.gain.value = 0;
}
// Loop through sounds
for (var i = 0; i < this._sounds.length; i++)
{
if (this._sounds[i].usingAudioTag)
{
this._sounds[i].mute = true;
}
}
},
/**
* Internal mute handler called automatically by the Sound.mute setter.
*
* @method Phaser.SoundManager#unsetMute
* @private
*/
unsetMute: function () {
if (!this._muted || this._codeMuted)
{
return;
}
this._muted = false;
if (this.usingWebAudio)
{
this.masterGain.gain.value = this._muteVolume;
}
// Loop through sounds
for (var i = 0; i < this._sounds.length; i++)
{
if (this._sounds[i].usingAudioTag)
{
this._sounds[i].mute = false;
}
}
}
};
Phaser.SoundManager.prototype.constructor = Phaser.SoundManager;
/**
* @name Phaser.SoundManager#mute
* @property {boolean} mute - Gets or sets the muted state of the SoundManager. This effects all sounds in the game.
*/
Object.defineProperty(Phaser.SoundManager.prototype, "mute", {
get: function () {
return this._muted;
},
set: function (value) {
value = value || null;
if (value)
{
if (this._muted)
{
return;
}
this._codeMuted = true;
this.setMute();
}
else
{
if (this._muted === false)
{
return;
}
this._codeMuted = false;
this.unsetMute();
}
}
});
/**
* @name Phaser.SoundManager#volume
* @property {number} volume - Gets or sets the global volume of the SoundManager, a value between 0 and 1.
*/
Object.defineProperty(Phaser.SoundManager.prototype, "volume", {
get: function () {
if (this.usingWebAudio)
{
return this.masterGain.gain.value;
}
else
{
return this._volume;
}
},
set: function (value) {
this._volume = value;
if (this.usingWebAudio)
{
this.masterGain.gain.value = value;
}
else
{
// Loop through the sound cache and change the volume of all html audio tags
for (var i = 0; i < this._sounds.length; i++)
{
if (this._sounds[i].usingAudioTag)
{
this._sounds[i].volume = this._sounds[i].volume * value;
}
}
}
}
});
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2014 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* A collection of methods for displaying debug information about game objects.
* If your game is running in WebGL then Debug will create a Sprite that is placed at the top of the Stage display list and bind a canvas texture
* to it, which must be uploaded every frame. Be advised: this is expenive.
* If your game is using a Canvas renderer then the debug information is literally drawn on the top of the active game canvas and no Sprite is used.
*
* @class Phaser.Utils.Debug
* @constructor
* @param {Phaser.Game} game - A reference to the currently running game.
*/
Phaser.Utils.Debug = function (game) {
/**
* @property {Phaser.Game} game - A reference to the currently running Game.
*/
this.game = game;
/**
* @property {PIXI.Sprite} sprite - If debugging in WebGL mode we need this.
*/
this.sprite = null;
/**
* @property {HTMLCanvasElement} canvas - The canvas to which this BitmapData draws.
*/
this.canvas = null;
/**
* @property {PIXI.BaseTexture} baseTexture - Required Pixi var.
*/
this.baseTexture = null;
/**
* @property {PIXI.Texture} texture - Required Pixi var.
*/
this.texture = null;
/**
* @property {Phaser.Frame} textureFrame - Dimensions of the renderable area.
*/
this.textureFrame = null;
/**
* @property {CanvasRenderingContext2D} context - The 2d context of the canvas.
*/
this.context = null;
/**
* @property {string} font - The font that the debug information is rendered in.
* @default '14px Courier'
*/
this.font = '14px Courier';
/**
* @property {number} columnWidth - The spacing between columns.
*/
this.columnWidth = 100;
/**
* @property {number} lineHeight - The line height between the debug text.
*/
this.lineHeight = 16;
/**
* @property {boolean} renderShadow - Should the text be rendered with a slight shadow? Makes it easier to read on different types of background.
*/
this.renderShadow = true;
/**
* @property {Context} currentX - The current X position the debug information will be rendered at.
* @default
*/
this.currentX = 0;
/**
* @property {number} currentY - The current Y position the debug information will be rendered at.
* @default
*/
this.currentY = 0;
/**
* @property {number} currentAlpha - The current alpha the debug information will be rendered at.
* @default
*/
this.currentAlpha = 1;
/**
* @property {boolean} dirty - Does the canvas need re-rendering?
*/
this.dirty = false;
};
Phaser.Utils.Debug.prototype = {
/**
* Internal method that boots the debug displayer.
*
* @method Phaser.Utils.Debug#boot
* @protected
*/
boot: function () {
if (this.game.renderType === Phaser.CANVAS)
{
this.context = this.game.context;
}
else
{
this.canvas = Phaser.Canvas.create(this.game.width, this.game.height, '', true);
this.context = this.canvas.getContext('2d');
this.baseTexture = new PIXI.BaseTexture(this.canvas);
this.texture = new PIXI.Texture(this.baseTexture);
this.textureFrame = new Phaser.Frame(0, 0, 0, this.game.width, this.game.height, 'debug', this.game.rnd.uuid());
this.sprite = this.game.make.image(0, 0, this.texture, this.textureFrame);
this.game.stage.addChild(this.sprite);
}
},
/**
* Internal method that resets and starts the debug output values.
*
* @method Phaser.Utils.Debug#start
* @protected
* @param {number} [x=0] - The X value the debug info will start from.
* @param {number} [y=0] - The Y value the debug info will start from.
* @param {string} [color='rgb(255,255,255)'] - The color the debug text will drawn in.
* @param {number} [columnWidth=0] - The spacing between columns.
*/
start: function (x, y, color, columnWidth) {
if (typeof x !== 'number') { x = 0; }
if (typeof y !== 'number') { y = 0; }
color = color || 'rgb(255,255,255)';
if (typeof columnWidth === 'undefined') { columnWidth = 0; }
this.currentX = x;
this.currentY = y;
this.currentColor = color;
this.currentAlpha = this.context.globalAlpha;
this.columnWidth = columnWidth;
if (this.sprite && this.dirty)
{
// this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
}
this.context.save();
this.context.setTransform(1, 0, 0, 1, 0, 0);
this.context.strokeStyle = color;
this.context.fillStyle = color;
this.context.font = this.font;
this.context.globalAlpha = 1;
},
/**
* Internal method that stops the debug output.
*
* @method Phaser.Utils.Debug#stop
* @protected
*/
stop: function () {
this.context.restore();
this.context.globalAlpha = this.currentAlpha;
if (this.sprite)
{
PIXI.updateWebGLTexture(this.baseTexture, this.game.renderer.gl);
}
},
/**
* Internal method that outputs a single line of text.
*
* @method Phaser.Utils.Debug#line
* @protected
* @param {string} text - The line of text to draw.
* @param {number} [x] - The X value the debug info will start from.
* @param {number} [y] - The Y value the debug info will start from.
line: function (text, x, y) {
if (typeof x !== 'undefined') { this.currentX = x; }
if (typeof y !== 'undefined') { this.currentY = y; }
if (this.renderShadow)
{
this.context.fillStyle = 'rgb(0,0,0)';
this.context.fillText(text, this.currentX + 1, this.currentY + 1);
this.context.fillStyle = this.currentColor;
}
this.context.fillText(text, this.currentX, this.currentY);
this.currentY += this.lineHeight;
},
*/
/**
* Internal method that outputs a single line of text split over as many columns as needed, one per parameter.
*
* @method Phaser.Utils.Debug#line
* @protected
* @param {string} text - The text to render. You can have as many columns of text as you want, just pass them as additional parameters.
*/
line: function (text) {
var x = this.currentX;
for (var i = 0; i < arguments.length; i++)
{
if (this.renderShadow)
{
this.context.fillStyle = 'rgb(0,0,0)';
this.context.fillText(arguments[i], x + 1, this.currentY + 1);
this.context.fillStyle = this.currentColor;
}
this.context.fillText(arguments[i], x, this.currentY);
x += this.columnWidth;
}
this.currentY += this.lineHeight;
},
/**
* Render Sound information, including decoded state, duration, volume and more.
*
* @method Phaser.Utils.Debug#soundInfo
* @param {Phaser.Sound} sound - The sound object to debug.
* @param {number} x - X position of the debug info to be rendered.
* @param {number} y - Y position of the debug info to be rendered.
* @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string).
*/
soundInfo: function (sound, x, y, color) {
this.start(x, y, color);
this.line('Sound: ' + sound.key + ' Locked: ' + sound.game.sound.touchLocked);
this.line('Is Ready?: ' + this.game.cache.isSoundReady(sound.key) + ' Pending Playback: ' + sound.pendingPlayback);
this.line('Decoded: ' + sound.isDecoded + ' Decoding: ' + sound.isDecoding);
this.line('Total Duration: ' + sound.totalDuration + ' Playing: ' + sound.isPlaying);
this.line('Time: ' + sound.currentTime);
this.line('Volume: ' + sound.volume + ' Muted: ' + sound.mute);
this.line('WebAudio: ' + sound.usingWebAudio + ' Audio: ' + sound.usingAudioTag);
if (sound.currentMarker !== '')
{
this.line('Marker: ' + sound.currentMarker + ' Duration: ' + sound.duration);
this.line('Start: ' + sound.markers[sound.currentMarker].start + ' Stop: ' + sound.markers[sound.currentMarker].stop);
this.line('Position: ' + sound.position);
}
this.stop();
},
/**
* Render camera information including dimensions and location.
*
* @method Phaser.Utils.Debug#cameraInfo
* @param {Phaser.Camera} camera - The Phaser.Camera to show the debug information for.
* @param {number} x - X position of the debug info to be rendered.
* @param {number} y - Y position of the debug info to be rendered.
* @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string).
*/
cameraInfo: function (camera, x, y, color) {
this.start(x, y, color);
this.line('Camera (' + camera.width + ' x ' + camera.height + ')');
this.line('X: ' + camera.x + ' Y: ' + camera.y);
this.line('Bounds x: ' + camera.bounds.x + ' Y: ' + camera.bounds.y + ' w: ' + camera.bounds.width + ' h: ' + camera.bounds.height);
this.line('View x: ' + camera.view.x + ' Y: ' + camera.view.y + ' w: ' + camera.view.width + ' h: ' + camera.view.height);
this.stop();
},
/**
* Renders the Pointer.circle object onto the stage in green if down or red if up along with debug text.
*
* @method Phaser.Utils.Debug#pointer
* @param {Phaser.Pointer} pointer - The Pointer you wish to display.
* @param {boolean} [hideIfUp=false] - Doesn't render the circle if the pointer is up.
* @param {string} [downColor='rgba(0,255,0,0.5)'] - The color the circle is rendered in if down.
* @param {string} [upColor='rgba(255,0,0,0.5)'] - The color the circle is rendered in if up (and hideIfUp is false).
* @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string).
*/
pointer: function (pointer, hideIfUp, downColor, upColor, color) {
if (pointer == null)
{
return;
}
if (typeof hideIfUp === 'undefined') { hideIfUp = false; }
downColor = downColor || 'rgba(0,255,0,0.5)';
upColor = upColor || 'rgba(255,0,0,0.5)';
if (hideIfUp === true && pointer.isUp === true)
{
return;
}
this.start(pointer.x, pointer.y - 100, color);
this.context.beginPath();
this.context.arc(pointer.x, pointer.y, pointer.circle.radius, 0, Math.PI * 2);
if (pointer.active)
{
this.context.fillStyle = downColor;
}
else
{
this.context.fillStyle = upColor;
}
this.context.fill();
this.context.closePath();
// Render the points
this.context.beginPath();
this.context.moveTo(pointer.positionDown.x, pointer.positionDown.y);
this.context.lineTo(pointer.position.x, pointer.position.y);
this.context.lineWidth = 2;
this.context.stroke();
this.context.closePath();
// Render the text
// this.start(pointer.x, pointer.y - 100, color);
this.line('ID: ' + pointer.id + " Active: " + pointer.active);
this.line('World X: ' + pointer.worldX + " World Y: " + pointer.worldY);
this.line('Screen X: ' + pointer.x + " Screen Y: " + pointer.y);
this.line('Duration: ' + pointer.duration + " ms");
this.line('is Down: ' + pointer.isDown + " is Up: " + pointer.isUp);
this.stop();
},
/**
* Render Sprite Input Debug information.
*
* @method Phaser.Utils.Debug#spriteInputInfo
* @param {Phaser.Sprite|Phaser.Image} sprite - The sprite to display the input data for.
* @param {number} x - X position of the debug info to be rendered.
* @param {number} y - Y position of the debug info to be rendered.
* @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string).
*/
spriteInputInfo: function (sprite, x, y, color) {
this.start(x, y, color);
this.line('Sprite Input: (' + sprite.width + ' x ' + sprite.height + ')');
this.line('x: ' + sprite.input.pointerX().toFixed(1) + ' y: ' + sprite.input.pointerY().toFixed(1));
this.line('over: ' + sprite.input.pointerOver() + ' duration: ' + sprite.input.overDuration().toFixed(0));
this.line('down: ' + sprite.input.pointerDown() + ' duration: ' + sprite.input.downDuration().toFixed(0));
this.line('just over: ' + sprite.input.justOver() + ' just out: ' + sprite.input.justOut());
this.stop();
},
/**
* Renders Phaser.Key object information.
*
* @method Phaser.Utils.Debug#key
* @param {Phaser.Key} key - The Key to render the information for.
* @param {number} x - X position of the debug info to be rendered.
* @param {number} y - Y position of the debug info to be rendered.
* @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string).
*/
key: function (key, x, y, color) {
this.start(x, y, color, 150);
this.line('Key:', key.keyCode, 'isDown:', key.isDown);
this.line('justPressed:', key.justPressed(), 'justReleased:', key.justReleased());
this.line('Time Down:', key.timeDown.toFixed(0), 'duration:', key.duration.toFixed(0));
this.stop();
},
/**
* Render debug information about the Input object.
*
* @method Phaser.Utils.Debug#inputInfo
* @param {number} x - X position of the debug info to be rendered.
* @param {number} y - Y position of the debug info to be rendered.
* @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string).
*/
inputInfo: function (x, y, color) {
this.start(x, y, color);
this.line('Input');
this.line('X: ' + this.game.input.x + ' Y: ' + this.game.input.y);
this.line('World X: ' + this.game.input.worldX + ' World Y: ' + this.game.input.worldY);
this.line('Scale X: ' + this.game.input.scale.x.toFixed(1) + ' Scale Y: ' + this.game.input.scale.x.toFixed(1));
this.line('Screen X: ' + this.game.input.activePointer.screenX + ' Screen Y: ' + this.game.input.activePointer.screenY);
this.stop();
},
/**
* Renders the Sprites bounds. Note: This is really expensive as it has to calculate the bounds every time you call it!
*
* @method Phaser.Utils.Debug#spriteBounds
* @param {Phaser.Sprite|Phaser.Image} sprite - The sprite to display the bounds of.
* @param {string} [color] - Color of the debug info to be rendered (format is css color string).
* @param {boolean} [filled=true] - Render the rectangle as a fillRect (default, true) or a strokeRect (false)
*/
spriteBounds: function (sprite, color, filled) {
var bounds = sprite.getBounds();
this.renderRectangle(bounds, color, filled);
},
/**
* Render debug infos (including name, bounds info, position and some other properties) about the Sprite.
*
* @method Phaser.Utils.Debug#spriteInfo
* @param {Phaser.Sprite} sprite - The Sprite to display the information of.
* @param {number} x - X position of the debug info to be rendered.
* @param {number} y - Y position of the debug info to be rendered.
* @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string).
*/
spriteInfo: function (sprite, x, y, color) {
this.start(x, y, color);
this.line('Sprite: ' + ' (' + sprite.width + ' x ' + sprite.height + ') anchor: ' + sprite.anchor.x + ' x ' + sprite.anchor.y);
this.line('x: ' + sprite.x.toFixed(1) + ' y: ' + sprite.y.toFixed(1));
this.line('angle: ' + sprite.angle.toFixed(1) + ' rotation: ' + sprite.rotation.toFixed(1));
this.line('visible: ' + sprite.visible + ' in camera: ' + sprite.inCamera);
this.stop();
},
/**
* Renders the sprite coordinates in local, positional and world space.
*
* @method Phaser.Utils.Debug#spriteCoords
* @param {Phaser.Sprite|Phaser.Image} sprite - The sprite to display the coordinates for.
* @param {number} x - X position of the debug info to be rendered.
* @param {number} y - Y position of the debug info to be rendered.
* @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string).
*/
spriteCoords: function (sprite, x, y, color) {
this.start(x, y, color, 100);
if (sprite.name)
{
this.line(sprite.name);
}
this.line('x:', sprite.x.toFixed(2), 'y:', sprite.y.toFixed(2));
this.line('pos x:', sprite.position.x.toFixed(2), 'pos y:', sprite.position.y.toFixed(2));
this.line('world x:', sprite.world.x.toFixed(2), 'world y:', sprite.world.y.toFixed(2));
this.stop();
},
/**
* Renders Line information in the given color.
*
* @method Phaser.Utils.Debug#lineInfo
* @param {Phaser.Line} line - The Line to display the data for.
* @param {number} x - X position of the debug info to be rendered.
* @param {number} y - Y position of the debug info to be rendered.
* @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string).
*/
lineInfo: function (line, x, y, color) {
this.start(x, y, color, 80);
this.line('start.x:', line.start.x.toFixed(2), 'start.y:', line.start.y.toFixed(2));
this.line('end.x:', line.end.x.toFixed(2), 'end.y:', line.end.y.toFixed(2));
this.line('length:', line.length.toFixed(2), 'angle:', line.angle);
this.stop();
},
/**
* Renders a single pixel at the given size.
*
* @method Phaser.Utils.Debug#pixel
* @param {number} x - X position of the pixel to be rendered.
* @param {number} y - Y position of the pixel to be rendered.
* @param {string} [color] - Color of the pixel (format is css color string).
* @param {number} [size=2] - The 'size' to render the pixel at.
*/
pixel: function (x, y, color, size) {
size = size || 2;
this.start();
this.context.fillStyle = color;
this.context.fillRect(x, y, size, size);
this.stop();
},
/**
* Renders a Phaser geometry object including Rectangle, Circle, Point or Line.
*
* @method Phaser.Utils.Debug#geom
* @param {Phaser.Rectangle|Phaser.Circle|Phaser.Point|Phaser.Line} object - The geometry object to render.
* @param {string} [color] - Color of the debug info to be rendered (format is css color string).
* @param {boolean} [filled=true] - Render the objected as a filled (default, true) or a stroked (false)
* @param {number} [forceType=0] - Force rendering of a specific type. If 0 no type will be forced, otherwise 1 = Rectangle, 2 = Circle, 3 = Point and 4 = Line.
*/
geom: function (object, color, filled, forceType) {
if (typeof filled === 'undefined') { filled = true; }
if (typeof forceType === 'undefined') { forceType = 0; }
color = color || 'rgba(0,255,0,0.4)';
this.start();
this.context.fillStyle = color;
this.context.strokeStyle = color;
if (object instanceof Phaser.Rectangle || forceType === 1)
{
if (filled)
{
this.context.fillRect(object.x - this.game.camera.x, object.y - this.game.camera.y, object.width, object.height);
}
else
{
this.context.strokeRect(object.x - this.game.camera.x, object.y - this.game.camera.y, object.width, object.height);
}
}
else if (object instanceof Phaser.Circle || forceType === 2)
{
this.context.beginPath();
this.context.arc(object.x - this.game.camera.x, object.y - this.game.camera.y, object.radius, 0, Math.PI * 2, false);
this.context.closePath();
if (filled)
{
this.context.fill();
}
else
{
this.context.stroke();
}
}
else if (object instanceof Phaser.Point || forceType === 3)
{
this.context.fillRect(object.x - this.game.camera.x, object.y - this.game.camera.y, 4, 4);
}
else if (object instanceof Phaser.Line || forceType === 4)
{
this.context.lineWidth = 1;
this.context.beginPath();
this.context.moveTo((object.start.x + 0.5) - this.game.camera.x, (object.start.y + 0.5) - this.game.camera.y);
this.context.lineTo((object.end.x + 0.5) - this.game.camera.x, (object.end.y + 0.5) - this.game.camera.y);
this.context.closePath();
this.context.stroke();
}
this.stop();
},
/**
* Render a string of text.
*
* @method Phaser.Utils.Debug#text
* @param {string} text - The line of text to draw.
* @param {number} x - X position of the debug info to be rendered.
* @param {number} y - Y position of the debug info to be rendered.
* @param {string} [color] - Color of the debug info to be rendered (format is css color string).
* @param {string} [font] - The font of text to draw.
*/
text: function (text, x, y, color, font) {
color = color || 'rgb(255,255,255)';
font = font || '16px Courier';
this.start();
this.context.font = font;
if (this.renderShadow)
{
this.context.fillStyle = 'rgb(0,0,0)';
this.context.fillText(text, x + 1, y + 1);
}
this.context.fillStyle = color;
this.context.fillText(text, x, y);
this.stop();
},
/**
* Render Sprite Body Physics Data as text.
*
* @method Phaser.Utils.Debug#bodyInfo
* @param {Phaser.Sprite} sprite - The sprite to be rendered.
* @param {number} x - X position of the debug info to be rendered.
* @param {number} y - Y position of the debug info to be rendered.
* @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string).
*/
bodyInfo: function (sprite, x, y, color) {
this.start(x, y, color, 210);
this.line('x: ' + sprite.body.x.toFixed(2), 'y: ' + sprite.body.y.toFixed(2), 'width: ' + sprite.width, 'height: ' + sprite.height);
// this.line('speed: ' + sprite.body.speed.toFixed(2), 'angle: ' + sprite.body.angle.toFixed(2), 'linear damping: ' + sprite.body.linearDamping);
// this.line('blocked left: ' + sprite.body.blocked.left, 'right: ' + sprite.body.blocked.right, 'up: ' + sprite.body.blocked.up, 'down: ' + sprite.body.blocked.down);
// this.line('touching left: ' + sprite.body.touching.left, 'right: ' + sprite.body.touching.right, 'up: ' + sprite.body.touching.up, 'down: ' + sprite.body.touching.down);
// this.line('gravity x: ' + sprite.body.gravity.x, 'y: ' + sprite.body.gravity.y, 'world gravity x: ' + this.game.physics.gravity.x, 'y: ' + this.game.physics.gravity.y);
// this.line('acceleration x: ' + sprite.body.acceleration.x.toFixed(2), 'y: ' + sprite.body.acceleration.y.toFixed(2));
// this.line('velocity x: ' + sprite.body.velocity.x.toFixed(2), 'y: ' + sprite.body.velocity.y.toFixed(2), 'deltaX: ' + sprite.body.deltaX().toFixed(2), 'deltaY: ' + sprite.body.deltaY().toFixed(2));
// this.line('bounce x: ' + sprite.body.bounce.x.toFixed(2), 'y: ' + sprite.body.bounce.y.toFixed(2));
this.stop();
},
/**
* Renders the physics body including all shapes.
*
* @method Phaser.Utils.Debug#physicsBody
* @param {Phaser.Physics.Body} body - The Phaser.Physics.Body instance to render all shapes from.
* @param {string} [color='rgb(255,255,255)'] - The color the polygon is stroked in.
*/
physicsBody: function (body, color) {
this.start(0, 0, color);
var shapes = body.data.shapes;
var shapeOffsets = body.data.shapeOffsets;
var shapeAngles = body.data.shapeAngles;
var i = shapes.length;
var x = this.game.math.p2pxi(body.data.position[0]) - this.game.camera.view.x;
var y = this.game.math.p2pxi(body.data.position[1]) - this.game.camera.view.y;
var angle = body.data.angle;
while (i--)
{
if (shapes[i] instanceof p2.Rectangle)
{
this.shapeRectangle(x, y, angle, shapes[i], shapeOffsets[i], shapeAngles[i]);
}
else if (shapes[i] instanceof p2.Line)
{
this.shapeLine(x, y, angle, shapes[i], shapeOffsets[i], shapeAngles[i]);
}
else if (shapes[i] instanceof p2.Convex)
{
this.shapeConvex(x, y, angle, shapes[i], shapeOffsets[i], shapeAngles[i]);
}
else if (shapes[i] instanceof p2.Circle)
{
this.shapeCircle(x, y, angle, shapes[i], shapeOffsets[i], shapeAngles[i]);
}
}
this.stop();
},
/**
* Renders a p2.Rectangle shape. Do not call this directly - instead use Debug.physicsBody.
*
* @method Phaser.Utils.Debug#shapeRectangle
* @param {number} x - The x coordinate of the Shape to translate to.
* @param {number} y - The y coordinate of the Shape to translate to.
* @param {number} bodyAngle - The angle of the Body to rotate to.
* @param {p2.Shape} shape - The shape to render.
* @param {array} offset - The shape offset vector.
* @param {number} angle - The shape angle.
*/
shapeRectangle: function (x, y, bodyAngle, shape, offset, angle) {
var w = this.game.math.p2px(shape.width);
var h = this.game.math.p2px(shape.height);
var points = shape.vertices;
this.context.beginPath();
this.context.save();
this.context.translate(x + this.game.math.p2pxi(offset[0]), y + this.game.math.p2pxi(offset[1]));
this.context.rotate(bodyAngle + angle);
this.context.moveTo(this.game.math.p2pxi(points[0][0]), this.game.math.p2pxi(points[0][1]));
for (var i = 1; i < points.length; i++)
{
this.context.lineTo(this.game.math.p2pxi(points[i][0]), this.game.math.p2pxi(points[i][1]));
}
this.context.closePath();
this.context.stroke();
this.context.restore();
},
/**
* Renders a p2.Line shape. Do not call this directly - instead use Debug.physicsBody.
*
* @method Phaser.Utils.Debug#shapeLine
* @param {number} x - The x coordinate of the Shape to translate to.
* @param {number} y - The y coordinate of the Shape to translate to.
* @param {number} bodyAngle - The angle of the Body to rotate to.
* @param {p2.Shape} shape - The shape to render.
* @param {array} offset - The shape offset vector.
* @param {number} angle - The shape angle.
*/
shapeLine: function (x, y, bodyAngle, shape, offset, angle) {
this.context.beginPath();
this.context.save();
this.context.translate(x, y);
this.context.rotate(bodyAngle + angle);
this.context.lineWidth = 0.5;
this.context.moveTo(0, 0);
this.context.lineTo(this.game.math.p2px(shape.length), 0);
this.context.closePath();
this.context.stroke();
this.context.restore();
},
/**
* Renders a convex shape. Do not call this directly - instead use Debug.physicsBody.
*
* @method Phaser.Utils.Debug#shapeConvex
* @param {number} x - The x coordinate of the Shape to translate to.
* @param {number} y - The y coordinate of the Shape to translate to.
* @param {number} bodyAngle - The angle of the Body to rotate to.
* @param {p2.Shape} shape - The shape to render.
* @param {array} offset - The shape offset vector.
* @param {number} angle - The shape angle.
*/
shapeConvex: function (x, y, bodyAngle, shape, offset, angle) {
var points = shape.vertices;
this.context.beginPath();
this.context.save();
this.context.translate(x + this.game.math.p2pxi(offset[0]), y + this.game.math.p2pxi(offset[1]));
this.context.rotate(bodyAngle + angle);
this.context.moveTo(this.game.math.p2pxi(points[0][0]), this.game.math.p2pxi(points[0][1]));
for (var i = 1; i < points.length; i++)
{
this.context.lineTo(this.game.math.p2pxi(points[i][0]), this.game.math.p2pxi(points[i][1]));
}
// this.context.arc(0, 0, this.game.math.p2px(shape.radius) , 0, Math.PI * 2);
this.context.closePath();
this.context.stroke();
this.context.restore();
},
/**
* Renders a p2.Circle shape. Do not call this directly - instead use Debug.physicsBody.
*
* @method Phaser.Utils.Debug#shapeCircle
* @param {number} x - The x coordinate of the Shape to translate to.
* @param {number} y - The y coordinate of the Shape to translate to.
* @param {number} bodyAngle - The angle of the Body to rotate to.
* @param {p2.Shape} shape - The shape to render.
* @param {array} offset - The shape offset vector.
* @param {number} angle - The shape angle.
*/
shapeCircle: function (x, y, bodyAngle, shape, offset, angle) {
this.context.beginPath();
this.context.save();
this.context.translate(x + this.game.math.p2pxi(offset[0]), y + this.game.math.p2pxi(offset[1]));
this.context.arc(0, 0, this.game.math.p2px(shape.radius) , 0, Math.PI * 2);
this.context.closePath();
this.context.stroke();
this.context.restore();
}
};
Phaser.Utils.Debug.prototype.constructor = Phaser.Utils.Debug;
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2014 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* A collection of methods useful for manipulating and comparing colors.
*
* @class Phaser.Color
*/
Phaser.Color = {
/**
* Given an alpha and 3 color values this will return an integer representation of it.
*
* @method Phaser.Color.getColor32
* @static
* @param {number} alpha - The Alpha value (between 0 and 255).
* @param {number} red - The Red channel value (between 0 and 255).
* @param {number} green - The Green channel value (between 0 and 255).
* @param {number} blue - The Blue channel value (between 0 and 255).
* @returns {number} A native color value integer (format: 0xAARRGGBB).
*/
getColor32: function (alpha, red, green, blue) {
return alpha << 24 | red << 16 | green << 8 | blue;
},
/**
* Given 3 color values this will return an integer representation of it.
*
* @method Phaser.Color.getColor
* @static
* @param {number} red - The Red channel value (between 0 and 255).
* @param {number} green - The Green channel value (between 0 and 255).
* @param {number} blue - The Blue channel value (between 0 and 255).
* @returns {number} A native color value integer (format: 0xRRGGBB).
*/
getColor: function (red, green, blue) {
return red << 16 | green << 8 | blue;
},
/**
* Converts the given hex string into an integer color value.
*
* @method Phaser.Color.hexToRGB
* @static
* @param {string} h - The string hex color to convert.
* @returns {number} The rgb color value.
*/
hexToRGB: function (h) {
var hex16 = (h.charAt(0) == "#") ? h.substring(1, 7) : h;
if (hex16.length==3)
{
hex16 = hex16.charAt(0) + hex16.charAt(0) + hex16.charAt(1) + hex16.charAt(1) + hex16.charAt(2) + hex16.charAt(2);
}
var red = parseInt(hex16.substring(0, 2), 16);
var green = parseInt(hex16.substring(2, 4), 16);
var blue = parseInt(hex16.substring(4, 6), 16);
return red << 16 | green << 8 | blue;
},
/**
* Returns a string containing handy information about the given color including string hex value,
* RGB format information and HSL information. Each section starts on a newline, 3 lines in total.
*
* @method Phaser.Color.getColorInfo
* @static
* @param {number} color - A color value in the format 0xAARRGGBB.
* @returns {string} String containing the 3 lines of information.
*/
getColorInfo: function (color) {
var argb = Phaser.Color.getRGB(color);
var hsl = Phaser.Color.RGBtoHSV(color);
// Hex format
var result = Phaser.Color.RGBtoHexstring(color) + "\n";
// RGB format
result = result.concat("Alpha: " + argb.alpha + " Red: " + argb.red + " Green: " + argb.green + " Blue: " + argb.blue) + "\n";
// HSL info
result = result.concat("Hue: " + hsl.hue + " Saturation: " + hsl.saturation + " Lightnes: " + hsl.lightness);
return result;
},
/**
* Return a string representation of the color in the format 0xAARRGGBB.
*
* @method Phaser.Color.RGBtoHexstring
* @static
* @param {number} color - The color to get the string representation for
* @returns {string} A string of length 10 characters in the format 0xAARRGGBB
*/
RGBtoHexstring: function (color) {
var argb = Phaser.Color.getRGB(color);
return "0x" + Phaser.Color.colorToHexstring(argb.alpha) + Phaser.Color.colorToHexstring(argb.red) + Phaser.Color.colorToHexstring(argb.green) + Phaser.Color.colorToHexstring(argb.blue);
},
/**
* Return a string representation of the color in the format #RRGGBB.
*
* @method Phaser.Color.RGBtoWebstring
* @static
* @param {number} color - The color to get the string representation for.
* @returns {string} A string of length 10 characters in the format 0xAARRGGBB.
*/
RGBtoWebstring: function (color) {
var argb = Phaser.Color.getRGB(color);
return "#" + Phaser.Color.colorToHexstring(argb.red) + Phaser.Color.colorToHexstring(argb.green) + Phaser.Color.colorToHexstring(argb.blue);
},
/**
* Return a string containing a hex representation of the given color.
*
* @method Phaser.Color.colorToHexstring
* @static
* @param {number} color - The color channel to get the hex value for, must be a value between 0 and 255).
* @returns {string} A string of length 2 characters, i.e. 255 = FF, 0 = 00.
*/
colorToHexstring: function (color) {
var digits = "0123456789ABCDEF";
var lsd = color % 16;
var msd = (color - lsd) / 16;
var hexified = digits.charAt(msd) + digits.charAt(lsd);
return hexified;
},
/**
* Interpolates the two given colours based on the supplied step and currentStep properties.
* @method Phaser.Color.interpolateColor
* @static
* @param {number} color1 - The first color value.
* @param {number} color2 - The second color value.
* @param {number} steps - The number of steps to run the interpolation over.
* @param {number} currentStep - The currentStep value. If the interpolation will take 100 steps, a currentStep value of 50 would be half-way between the two.
* @param {number} alpha - The alpha of the returned color.
* @returns {number} The interpolated color value.
*/
interpolateColor: function (color1, color2, steps, currentStep, alpha) {
if (typeof alpha === "undefined") { alpha = 255; }
var src1 = Phaser.Color.getRGB(color1);
var src2 = Phaser.Color.getRGB(color2);
var r = (((src2.red - src1.red) * currentStep) / steps) + src1.red;
var g = (((src2.green - src1.green) * currentStep) / steps) + src1.green;
var b = (((src2.blue - src1.blue) * currentStep) / steps) + src1.blue;
return Phaser.Color.getColor32(alpha, r, g, b);
},
/**
* Interpolates the two given colours based on the supplied step and currentStep properties.
* @method Phaser.Color.interpolateColorWithRGB
* @static
* @param {number} color - The first color value.
* @param {number} r - The red color value, between 0 and 0xFF (255).
* @param {number} g - The green color value, between 0 and 0xFF (255).
* @param {number} b - The blue color value, between 0 and 0xFF (255).
* @param {number} steps - The number of steps to run the interpolation over.
* @param {number} currentStep - The currentStep value. If the interpolation will take 100 steps, a currentStep value of 50 would be half-way between the two.
* @returns {number} The interpolated color value.
*/
interpolateColorWithRGB: function (color, r, g, b, steps, currentStep) {
var src = Phaser.Color.getRGB(color);
var or = (((r - src.red) * currentStep) / steps) + src.red;
var og = (((g - src.green) * currentStep) / steps) + src.green;
var ob = (((b - src.blue) * currentStep) / steps) + src.blue;
return Phaser.Color.getColor(or, og, ob);
},
/**
* Interpolates the two given colours based on the supplied step and currentStep properties.
* @method Phaser.Color.interpolateRGB
* @static
* @param {number} r1 - The red color value, between 0 and 0xFF (255).
* @param {number} g1 - The green color value, between 0 and 0xFF (255).
* @param {number} b1 - The blue color value, between 0 and 0xFF (255).
* @param {number} r2 - The red color value, between 0 and 0xFF (255).
* @param {number} g2 - The green color value, between 0 and 0xFF (255).
* @param {number} b2 - The blue color value, between 0 and 0xFF (255).
* @param {number} steps - The number of steps to run the interpolation over.
* @param {number} currentStep - The currentStep value. If the interpolation will take 100 steps, a currentStep value of 50 would be half-way between the two.
* @returns {number} The interpolated color value.
*/
interpolateRGB: function (r1, g1, b1, r2, g2, b2, steps, currentStep) {
var r = (((r2 - r1) * currentStep) / steps) + r1;
var g = (((g2 - g1) * currentStep) / steps) + g1;
var b = (((b2 - b1) * currentStep) / steps) + b1;
return Phaser.Color.getColor(r, g, b);
},
/**
* Returns a random color value between black and white
* Set the min value to start each channel from the given offset.
* Set the max value to restrict the maximum color used per channel.
*
* @method Phaser.Color.getRandomColor
* @static
* @param {number} min - The lowest value to use for the color.
* @param {number} max - The highest value to use for the color.
* @param {number} alpha - The alpha value of the returning color (default 255 = fully opaque).
* @returns {number} 32-bit color value with alpha.
*/
getRandomColor: function (min, max, alpha) {
if (typeof min === "undefined") { min = 0; }
if (typeof max === "undefined") { max = 255; }
if (typeof alpha === "undefined") { alpha = 255; }
// Sanity checks
if (max > 255) {
return Phaser.Color.getColor(255, 255, 255);
}
if (min > max) {
return Phaser.Color.getColor(255, 255, 255);
}
var red = min + Math.round(Math.random() * (max - min));
var green = min + Math.round(Math.random() * (max - min));
var blue = min + Math.round(Math.random() * (max - min));
return Phaser.Color.getColor32(alpha, red, green, blue);
},
/**
* Return the component parts of a color as an Object with the properties alpha, red, green, blue
*
* Alpha will only be set if it exist in the given color (0xAARRGGBB)
*
* @method Phaser.Color.getRGB
* @static
* @param {number} color - Color in RGB (0xRRGGBB) or ARGB format (0xAARRGGBB).
* @returns {object} An Object with properties: alpha, red, green, blue.
*/
getRGB: function (color) {
return {
alpha: color >>> 24,
red: color >> 16 & 0xFF,
green: color >> 8 & 0xFF,
blue: color & 0xFF
};
},
/**
* Returns a CSS friendly string value from the given color.
* @method Phaser.Color.getWebRGB
* @static
* @param {number} color
* @returns {string}A string in the format: 'rgba(r,g,b,a)'
*/
getWebRGB: function (color) {
var alpha = (color >>> 24) / 255;
var red = color >> 16 & 0xFF;
var green = color >> 8 & 0xFF;
var blue = color & 0xFF;
return 'rgba(' + red.toString() + ',' + green.toString() + ',' + blue.toString() + ',' + alpha.toString() + ')';
},
/**
* Given a native color value (in the format 0xAARRGGBB) this will return the Alpha component, as a value between 0 and 255.
*
* @method Phaser.Color.getAlpha
* @static
* @param {number} color - In the format 0xAARRGGBB.
* @returns {number} The Alpha component of the color, will be between 0 and 1 (0 being no Alpha (opaque), 1 full Alpha (transparent)).
*/
getAlpha: function (color) {
return color >>> 24;
},
/**
* Given a native color value (in the format 0xAARRGGBB) this will return the Alpha component as a value between 0 and 1.
*
* @method Phaser.Color.getAlphaFloat
* @static
* @param {number} color - In the format 0xAARRGGBB.
* @returns {number} The Alpha component of the color, will be between 0 and 1 (0 being no Alpha (opaque), 1 full Alpha (transparent)).
*/
getAlphaFloat: function (color) {
return (color >>> 24) / 255;
},
/**
* Given a native color value (in the format 0xAARRGGBB) this will return the Red component, as a value between 0 and 255.
*
* @method Phaser.Color.getRed
* @static
* @param {number} color In the format 0xAARRGGBB.
* @returns {number} The Red component of the color, will be between 0 and 255 (0 being no color, 255 full Red).
*/
getRed: function (color) {
return color >> 16 & 0xFF;
},
/**
* Given a native color value (in the format 0xAARRGGBB) this will return the Green component, as a value between 0 and 255.
*
* @method Phaser.Color.getGreen
* @static
* @param {number} color - In the format 0xAARRGGBB.
* @returns {number} The Green component of the color, will be between 0 and 255 (0 being no color, 255 full Green).
*/
getGreen: function (color) {
return color >> 8 & 0xFF;
},
/**
* Given a native color value (in the format 0xAARRGGBB) this will return the Blue component, as a value between 0 and 255.
*
* @method Phaser.Color.getBlue
* @static
* @param {number} color - In the format 0xAARRGGBB.
* @returns {number} The Blue component of the color, will be between 0 and 255 (0 being no color, 255 full Blue).
*/
getBlue: function (color) {
return color & 0xFF;
}
};
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2014 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* The Physics Manager is responsible for looking after all of the running physics systems.
* Phaser supports 3 physics systems: Arcade Physics, P2 and Ninja Physics (with Box2D and Chipmunk in development)
* Game Objects can belong to only 1 physics system, but you can have multiple systems active in a single game.
*
* For example you could have P2 managing a polygon-built terrain landscape that an vehicle drives over, while it could be firing bullets that use the
* faster (due to being much simpler) Arcade Physics system.
*
* @class Phaser.Physics
*
* @constructor
* @param {Phaser.Game} game - A reference to the currently running game.
* @param {object} [physicsConfig=null] - A physics configuration object to pass to the Physics world on creation.
*/
Phaser.Physics = function (game, config) {
/**
* @property {Phaser.Game} game - Local reference to game.
*/
this.game = game;
/**
* @property {object} config - The physics configuration object as passed to the game on creation.
*/
this.config = config;
/**
* @property {Phaser.Physics.Arcade} arcade - The Arcade Physics system.
*/
this.arcade = new Phaser.Physics.Arcade(game);
/**
* @property {Phaser.Physics.P2} p2 - The P2.JS Physics system.
*/
this.p2 = null;
/**
* @property {Phaser.Physics.Ninja} ninja - The N+ Ninja Physics System.
*/
this.ninja = null;
/**
* @property {Phaser.Physics.Box2D} box2d - The Box2D Physics system (to be done).
*/
this.box2d = null;
/**
* @property {Phaser.Physics.Chipmunk} chipmunk - The Chipmunk Physics system (to be done).
*/
this.chipmunk = null;
};
/**
* @const
* @type {number}
*/
Phaser.Physics.ARCADE = 0;
/**
* @const
* @type {number}
*/
Phaser.Physics.P2 = 1;
/**
* @const
* @type {number}
*/
Phaser.Physics.NINJA = 2;
/**
* @const
* @type {number}
*/
Phaser.Physics.BOX2D = 3;
/**
* @const
* @type {number}
*/
Phaser.Physics.CHIPMUNK = 5;
Phaser.Physics.prototype = {
/**
* This will create an instance of the requested physics simulation.
* Phaser.Physics.Arcade is running by default, but all others need activating directly.
* You can start the following physics systems:
* Phaser.Physics.P2 - A full-body advanced physics system by Stefan Hedman.
* Phaser.Physics.NINJA - A port of Metanet Softwares N+ physics system.
* Phaser.Physics.BOX2D and Phaser.Physics.CHIPMUNK are still in development.
*
* @method Phaser.Physics#startSystem
* @param {number} The physics system to start.
*/
startSystem: function (system) {
if (system === Phaser.Physics.ARCADE && this.arcade === null)
{
this.arcade = new Phaser.Physics.Arcade(this.game);
}
else if (system === Phaser.Physics.P2 && this.p2 === null)
{
this.p2 = new Phaser.Physics.P2(this.game, this.config);
}
if (system === Phaser.Physics.NINJA && this.ninja === null)
{
this.ninja = new Phaser.Physics.Ninja(this.game);
}
else if (system === Phaser.Physics.BOX2D && this.box2d === null)
{
// Coming soon
}
else if (system === Phaser.Physics.CHIPMUNK && this.chipmunk === null)
{
// Coming soon
}
},
/**
* This will create a 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 object is destroyed.
* It can be for any of the physics systems that have been started:
*
* Phaser.Physics.Arcade - A light weight AABB based collision system with basic separation.
* Phaser.Physics.P2 - A full-body advanced physics system supporting multiple object shapes, polygon loading, contact materials, springs and constraints.
* Phaser.Physics.NINJA - A port of Metanet Softwares N+ physics system. Advanced AABB and Circle vs. Tile collision.
* Phaser.Physics.BOX2D and Phaser.Physics.CHIPMUNK are still in development.
*
* @method Phaser.Physics#enable
* @param {object|array} object - The game object to create the physics body on. Can also be an array of objects, a body will be created on every object in the array.
* @param {number} [system=Phaser.Physics.ARCADE] - The physics system that will be used to create the body. Defaults to Arcade Physics.
*/
enable: function (object, system) {
if (typeof system === 'undefined') { system = Phaser.Physics.ARCADE; }
var i = 1;
if (object instanceof Phaser.Group)
{
}
else
{
if (Array.isArray(object))
{
// Add to Group
i = object.length;
}
else
{
object = [object];
}
while (i--)
{
if (object[i].body === null)
{
if (system === Phaser.Physics.ARCADE)
{
object[i].body = new Phaser.Physics.Arcade.Body(object[i]);
}
else if (system === Phaser.Physics.P2)
{
object[i].body = new Phaser.Physics.P2.Body(this.game, object[i], object[i].x, object[i].y, 1);
object[i].anchor.set(0.5);
}
else if (system === Phaser.Physics.NINJA)
{
object[i].body = new Phaser.Physics.Ninja.Body(this.ninja, object[i]);
object[i].anchor.set(0.5);
}
}
}
}
},
/**
* Updates all running physics systems.
*
* @method Phaser.Physics#update
* @protected
*/
update: function () {
// ArcadePhysics / Ninja don't have a core to update
if (this.p2)
{
this.p2.update();
}
},
/**
* Updates the physics bounds to match the world dimensions.
*
* @method Phaser.Physics#setBoundsToWorld
* @protected
*/
setBoundsToWorld: function () {
if (this.ninja)
{
this.ninja.setBoundsToWorld();
}
},
/**
* Clears down all active physics systems. This doesn't destroy them, it just clears them of objects and is called when the State changes.
*
* @method Phaser.Physics#clear
* @protected
*/
clear: function () {
if (this.p2)
{
this.p2.clear();
}
}
};
Phaser.Physics.prototype.constructor = Phaser.Physics;
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2014 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* Arcade Physics constructor.
*
* @class Phaser.Physics.Arcade
* @classdesc Arcade Physics Constructor
* @constructor
* @param {Phaser.Game} game reference to the current game instance.
*/
Phaser.Physics.Arcade = function (game) {
/**
* @property {Phaser.Game} game - Local reference to game.
*/
this.game = game;
/**
* @property {Phaser.Point} gravity - The World gravity setting. Defaults to x: 0, y: 0, or no gravity.
*/
this.gravity = new Phaser.Point();
/**
* @property {Phaser.Rectangle} bounds - The bounds inside of which the physics world exists. Defaults to match the world bounds.
*/
this.bounds = new Phaser.Rectangle(0, 0, game.world.width, game.world.height);
/**
* @property {number} maxObjects - Used by the QuadTree to set the maximum number of objects per quad.
*/
this.maxObjects = 10;
/**
* @property {number} maxLevels - Used by the QuadTree to set the maximum number of iteration levels.
*/
this.maxLevels = 4;
/**
* @property {number} OVERLAP_BIAS - A value added to the delta values during collision checks.
*/
this.OVERLAP_BIAS = 4;
/**
* @property {Phaser.QuadTree} quadTree - The world QuadTree.
*/
this.quadTree = new Phaser.QuadTree(this.game.world.bounds.x, this.game.world.bounds.y, this.game.world.bounds.width, this.game.world.bounds.height, this.maxObjects, this.maxLevels);
// Avoid gc spikes by caching these values for re-use
/**
* @property {Phaser.Rectangle} _bounds1 - Internal cache var.
* @private
*/
this._bounds1 = new Phaser.Rectangle();
/**
* @property {Phaser.Rectangle} _bounds2 - Internal cache var.
* @private
*/
this._bounds2 = new Phaser.Rectangle();
/**
* @property {number} _overlap - Internal cache var.
* @private
*/
this._overlap = 0;
/**
* @property {number} _maxOverlap - Internal cache var.
* @private
*/
this._maxOverlap = 0;
/**
* @property {number} _velocity1 - Internal cache var.
* @private
*/
this._velocity1 = 0;
/**
* @property {number} _velocity2 - Internal cache var.
* @private
*/
this._velocity2 = 0;
/**
* @property {number} _newVelocity1 - Internal cache var.
* @private
*/
this._newVelocity1 = 0;
/**
* @property {number} _newVelocity2 - Internal cache var.
* @private
*/
this._newVelocity2 = 0;
/**
* @property {number} _average - Internal cache var.
* @private
*/
this._average = 0;
/**
* @property {Array} _mapData - Internal cache var.
* @private
*/
this._mapData = [];
/**
* @property {number} _mapTiles - Internal cache var.
* @private
*/
this._mapTiles = 0;
/**
* @property {boolean} _result - Internal cache var.
* @private
*/
this._result = false;
/**
* @property {number} _total - Internal cache var.
* @private
*/
this._total = 0;
/**
* @property {number} _angle - Internal cache var.
* @private
*/
this._angle = 0;
/**
* @property {number} _dx - Internal cache var.
* @private
*/
this._dx = 0;
/**
* @property {number} _dy - Internal cache var.
* @private
*/
this._dy = 0;
/**
* @property {number} _intersection - Internal cache var.
* @private
*/
// this._intersection = [0,0,0,0];
this._intersection = new Phaser.Rectangle();
};
Phaser.Physics.Arcade.prototype.constructor = Phaser.Physics.Arcade;
Phaser.Physics.Arcade.prototype = {
/**
* This will create an Arcade 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.
*
* @method Phaser.Physics.Arcade#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} [children=true] - Should a body be created on all children of this object? If true it will propagate down the display list.
*/
enable: function (object, children) {
if (typeof children === 'undefined') { children = true; }
var i = 1;
if (Array.isArray(object))
{
// Add to Group
i = object.length;
}
else
{
object = [object];
}
while (i--)
{
if (object[i] instanceof Phaser.Group)
{
object[i].forEach(this.enableBody, this, false, children);
}
else
{
this.enableBody(object[i]);
}
}
},
enableBody: function (object, children) {
if (object instanceof Phaser.Group)
{
this.enable(object, true, children);
return;
}
if (object.hasOwnProperty('body') && object.body === null)
{
object.body = new Phaser.Physics.Arcade.Body(object);
}
if (children && object.hasOwnProperty('children'))
{
object.children.forEach(this.enable, this);
}
},
/**
* Called automatically by a Physics body, it updates all motion related values on the Body.
*
* @method Phaser.Physics.Arcade#updateMotion
* @param {Phaser.Physics.Arcade.Body} The Body object to be updated.
*/
updateMotion: function (body) {
// Rotation
this._velocityDelta = (this.computeVelocity(body.angularVelocity, body.angularAcceleration, body.angularDrag, body.maxAngular, 0) - body.angularVelocity) * 0.5;
body.angularVelocity += this._velocityDelta;
body.rotation += (body.angularVelocity * this.game.time.physicsElapsed);
body.angularVelocity += this._velocityDelta;
// Apply gravity using the p2 style gravityScale
body.velocity.x += this.gravity.x * this.game.time.physicsElapsed * body.gravityScale.x;
body.velocity.y += this.gravity.y * this.game.time.physicsElapsed * body.gravityScale.y;
// Apply velocity
body.velocity.x = this.computeVelocity(body.velocity.x, body.acceleration.x, body.drag.x, body.maxVelocity.x);
body.velocity.y = this.computeVelocity(body.velocity.y, body.acceleration.y, body.drag.y, body.maxVelocity.y);
},
/**
* A tween-like function that takes a starting velocity and some other factors and returns an altered velocity.
* Based on a function in Flixel by @ADAMATOMIC
*
* @method Phaser.Physics.Arcade#computeVelocity
* @param {number} velocity - Any component of velocity (e.g. 20).
* @param {number} acceleration - Rate at which the velocity is changing.
* @param {number} drag - Really kind of a deceleration, this is how much the velocity changes if Acceleration is not set.
* @param {number} [max=10000] - An absolute value cap for the velocity.
* @return {number} The altered Velocity value.
*/
computeVelocity: function (velocity, acceleration, drag, max) {
max = max || 10000;
if (acceleration)
{
velocity + acceleration * this.game.time.physicsElapsed;
}
else if (drag)
{
this._drag = drag * this.game.time.physicsElapsed;
if (velocity - this._drag > 0)
{
velocity -= this._drag;
}
else if (velocity + this._drag < 0)
{
velocity += this._drag;
}
else
{
velocity = 0;
}
}
if (velocity > max)
{
velocity = max;
}
else if (velocity < -max)
{
velocity = -max;
}
return velocity;
},
/**
* Checks for overlaps between two game objects. The objects can be Sprites, Groups or Emitters.
* You can perform Sprite vs. Sprite, Sprite vs. Group and Group vs. Group overlap checks.
* Unlike collide the objects are NOT automatically separated or have any physics applied, they merely test for overlap results.
* The second parameter can be an array of objects, of differing types.
*
* @method Phaser.Physics.Arcade#overlap
* @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter} object1 - The first object to check. Can be an instance of Phaser.Sprite, Phaser.Group or Phaser.Particles.Emitter.
* @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter|array} object2 - The second object or array of objects to check. Can be Phaser.Sprite, Phaser.Group or Phaser.Particles.Emitter.
* @param {function} [overlapCallback=null] - An optional callback function that is called if the objects overlap. The two objects will be passed to this function in the same order in which you specified them.
* @param {function} [processCallback=null] - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then overlapCallback will only be called if processCallback returns true.
* @param {object} [callbackContext] - The context in which to run the callbacks.
* @returns {boolean} True if an overlap occured otherwise false.
*/
overlap: function (object1, object2, overlapCallback, processCallback, callbackContext) {
overlapCallback = overlapCallback || null;
processCallback = processCallback || null;
callbackContext = callbackContext || overlapCallback;
this._result = false;
this._total = 0;
if (Array.isArray(object2))
{
for (var i = 0, len = object2.length; i < len; i++)
{
this.collideHandler(object1, object2[i], overlapCallback, processCallback, callbackContext, true);
}
}
else
{
this.collideHandler(object1, object2, overlapCallback, processCallback, callbackContext, true);
}
return (this._total > 0);
},
/**
* Checks for collision between two game objects. You can perform Sprite vs. Sprite, Sprite vs. Group, Group vs. Group, Sprite vs. Tilemap Layer or Group vs. Tilemap Layer collisions.
* The second parameter can be an array of objects, of differing types.
* The objects are also automatically separated. If you don't require separation then use ArcadePhysics.overlap instead.
* An optional processCallback can be provided. If given this function will be called when two sprites are found to be colliding. It is called before any separation takes place,
* giving you the chance to perform additional checks. If the function returns true then the collision and separation is carried out. If it returns false it is skipped.
* The collideCallback is an optional function that is only called if two sprites collide. If a processCallback has been set then it needs to return true for collideCallback to be called.
*
* @method Phaser.Physics.Arcade#collide
* @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter|Phaser.Tilemap} object1 - The first object to check. Can be an instance of Phaser.Sprite, Phaser.Group, Phaser.Particles.Emitter, or Phaser.Tilemap.
* @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter|Phaser.Tilemap|array} object2 - The second object or array of objects to check. Can be Phaser.Sprite, Phaser.Group, Phaser.Particles.Emitter or Phaser.Tilemap.
* @param {function} [collideCallback=null] - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them.
* @param {function} [processCallback=null] - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them.
* @param {object} [callbackContext] - The context in which to run the callbacks.
* @returns {boolean} True if a collision occured otherwise false.
*/
collide: function (object1, object2, collideCallback, processCallback, callbackContext) {
collideCallback = collideCallback || null;
processCallback = processCallback || null;
callbackContext = callbackContext || collideCallback;
this._result = false;
this._total = 0;
if (Array.isArray(object2))
{
for (var i = 0, len = object2.length; i < len; i++)
{
this.collideHandler(object1, object2[i], collideCallback, processCallback, callbackContext, false);
}
}
else
{
this.collideHandler(object1, object2, collideCallback, processCallback, callbackContext, false);
}
return (this._total > 0);
},
/**
* Internal collision handler.
*
* @method Phaser.Physics.Arcade#collideHandler
* @private
* @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter|Phaser.Tilemap} object1 - The first object to check. Can be an instance of Phaser.Sprite, Phaser.Group, Phaser.Particles.Emitter, or Phaser.Tilemap.
* @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter|Phaser.Tilemap} object2 - The second object to check. Can be an instance of Phaser.Sprite, Phaser.Group, Phaser.Particles.Emitter or Phaser.Tilemap. Can also be an array of objects to check.
* @param {function} collideCallback - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them.
* @param {function} processCallback - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them.
* @param {object} callbackContext - The context in which to run the callbacks.
* @param {boolean} overlapOnly - Just run an overlap or a full collision.
*/
collideHandler: function (object1, object2, collideCallback, processCallback, callbackContext, overlapOnly) {
// Only collide valid objects
if (typeof object2 === 'undefined' && (object1.type === Phaser.GROUP || object1.type === Phaser.EMITTER))
{
this.collideGroupVsSelf(object1, collideCallback, processCallback, callbackContext, overlapOnly);
return;
}
if (object1 && object2 && object1.exists && object2.exists)
{
// SPRITES
if (object1.type == Phaser.SPRITE || object1.type == Phaser.TILESPRITE)
{
if (object2.type == Phaser.SPRITE || object2.type == Phaser.TILESPRITE)
{
this.collideSpriteVsSprite(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly);
}
else if (object2.type == Phaser.GROUP || object2.type == Phaser.EMITTER)
{
this.collideSpriteVsGroup(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly);
}
else if (object2.type == Phaser.TILEMAPLAYER)
{
this.collideSpriteVsTilemapLayer(object1, object2, collideCallback, processCallback, callbackContext);
}
}
// GROUPS
else if (object1.type == Phaser.GROUP)
{
if (object2.type == Phaser.SPRITE || object2.type == Phaser.TILESPRITE)
{
this.collideSpriteVsGroup(object2, object1, collideCallback, processCallback, callbackContext, overlapOnly);
}
else if (object2.type == Phaser.GROUP || object2.type == Phaser.EMITTER)
{
this.collideGroupVsGroup(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly);
}
else if (object2.type == Phaser.TILEMAPLAYER)
{
this.collideGroupVsTilemapLayer(object1, object2, collideCallback, processCallback, callbackContext);
}
}
// TILEMAP LAYERS
else if (object1.type == Phaser.TILEMAPLAYER)
{
if (object2.type == Phaser.SPRITE || object2.type == Phaser.TILESPRITE)
{
this.collideSpriteVsTilemapLayer(object2, object1, collideCallback, processCallback, callbackContext);
}
else if (object2.type == Phaser.GROUP || object2.type == Phaser.EMITTER)
{
this.collideGroupVsTilemapLayer(object2, object1, collideCallback, processCallback, callbackContext);
}
}
// EMITTER
else if (object1.type == Phaser.EMITTER)
{
if (object2.type == Phaser.SPRITE || object2.type == Phaser.TILESPRITE)
{
this.collideSpriteVsGroup(object2, object1, collideCallback, processCallback, callbackContext, overlapOnly);
}
else if (object2.type == Phaser.GROUP || object2.type == Phaser.EMITTER)
{
this.collideGroupVsGroup(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly);
}
else if (object2.type == Phaser.TILEMAPLAYER)
{
this.collideGroupVsTilemapLayer(object1, object2, collideCallback, processCallback, callbackContext);
}
}
}
},
/**
* An internal function. Use Phaser.Physics.Arcade.collide instead.
*
* @method Phaser.Physics.Arcade#collideSpriteVsSprite
* @private
*/
collideSpriteVsSprite: function (sprite1, sprite2, collideCallback, processCallback, callbackContext, overlapOnly) {
if (this.separate(sprite1.body, sprite2.body, processCallback, callbackContext, overlapOnly))
{
if (collideCallback)
{
collideCallback.call(callbackContext, sprite1, sprite2);
}
this._total++;
}
},
/**
* An internal function. Use Phaser.Physics.Arcade.collide instead.
*
* @method Phaser.Physics.Arcade#collideSpriteVsGroup
* @private
*/
collideSpriteVsGroup: function (sprite, group, collideCallback, processCallback, callbackContext, overlapOnly) {
if (group.length === 0)
{
return;
}
// What is the sprite colliding with in the quadtree?
this.quadTree.clear();
this.quadTree.reset(this.game.world.bounds.x, this.game.world.bounds.y, this.game.world.bounds.width, this.game.world.bounds.height, this.maxObjects, this.maxLevels);
this.quadTree.populate(group);
this._potentials = this.quadTree.retrieve(sprite);
for (var i = 0, len = this._potentials.length; i < len; i++)
{
// We have our potential suspects, are they in this group?
if (this.separate(sprite.body, this._potentials[i], processCallback, callbackContext, overlapOnly))
{
if (collideCallback)
{
collideCallback.call(callbackContext, sprite, this._potentials[i].sprite);
}
this._total++;
}
}
},
/**
* An internal function. Use Phaser.Physics.Arcade.collide instead.
*
* @method Phaser.Physics.Arcade#collideGroupVsSelf
* @private
*/
collideGroupVsSelf: function (group, collideCallback, processCallback, callbackContext, overlapOnly) {
if (group.length === 0)
{
return;
}
var len = group.children.length;
for (var i = 0; i < len; i++)
{
for (var j = i + 1; j <= len; j++)
{
if (group.children[i] && group.children[j] && group.children[i].exists && group.children[j].exists)
{
this.collideSpriteVsSprite(group.children[i], group.children[j], collideCallback, processCallback, callbackContext, overlapOnly);
}
}
}
},
/**
* An internal function. Use Phaser.Physics.Arcade.collide instead.
*
* @method Phaser.Physics.Arcade#collideGroupVsGroup
* @private
*/
collideGroupVsGroup: function (group1, group2, collideCallback, processCallback, callbackContext, overlapOnly) {
if (group1.length === 0 || group2.length === 0)
{
return;
}
for (var i = 0, len = group1.children.length; i < len; i++)
{
if (group1.children[i].exists)
{
this.collideSpriteVsGroup(group1.children[i], group2, collideCallback, processCallback, callbackContext, overlapOnly);
}
}
},
/**
* An internal function. Use Phaser.Physics.Arcade.collide instead.
*
* @method Phaser.Physics.Arcade#collideSpriteVsTilemapLayer
* @private
*/
collideSpriteVsTilemapLayer: function (sprite, tilemapLayer, collideCallback, processCallback, callbackContext) {
// this._mapData = tilemapLayer.getTiles(sprite.body.left, sprite.body.top, sprite.body.width, sprite.body.height, true);
// this._mapData = tilemapLayer.getTiles(sprite.body.x, sprite.body.y, sprite.body.width, sprite.body.height, true);
this._mapData = tilemapLayer.getIntersectingTiles(sprite.body.position.x, sprite.body.position.y, sprite.body.width, sprite.body.height, true);
// var vx = sprite.body.x;
// var vy = sprite.body.y;
// vx += sprite.body.newVelocity.x;
// vy += sprite.body.newVelocity.y;
// this._mapData = tilemapLayer.getIntersectingTiles(vx, vy, sprite.body.width, sprite.body.height, true);
if (this._mapData.length === 0)
{
return;
}
// if (this._mapData.length > 1)
// {
// Needs process callback added
this.separateTiles(sprite.body, this._mapData);
// }
/*
else
{
var i = 0;
if (this.separateTile(sprite.body, this._mapData[i]))
{
// They collided, is there a custom process callback?
if (processCallback)
{
if (processCallback.call(callbackContext, sprite, this._mapData[i]))
{
this._total++;
if (collideCallback)
{
collideCallback.call(callbackContext, sprite, this._mapData[i]);
}
}
}
else
{
this._total++;
if (collideCallback)
{
collideCallback.call(callbackContext, sprite, this._mapData[i]);
}
}
}
}
*/
},
/**
* An internal function. Use Phaser.Physics.Arcade.collide instead.
*
* @method Phaser.Physics.Arcade#collideGroupVsTilemapLayer
* @private
*/
collideGroupVsTilemapLayer: function (group, tilemapLayer, collideCallback, processCallback, callbackContext) {
if (group.length === 0)
{
return;
}
for (var i = 0, len = group.children.length; i < len; i++)
{
if (group.children[i].exists)
{
this.collideSpriteVsTilemapLayer(group.children[i], tilemapLayer, collideCallback, processCallback, callbackContext);
}
}
},
/**
* The core separation function to separate two physics bodies.
* @method Phaser.Physics.Arcade#separate
* @param {Phaser.Physics.Arcade.Body} body1 - The Body object to separate.
* @param {Phaser.Physics.Arcade.Body} body2 - The Body object to separate.
* @param {function} [processCallback=null] - A callback function that lets you perform additional checks against the two objects if they overlap. If this function is set then the sprites will only be collided if it returns true.
* @param {object} [callbackContext] - The context in which to run the process callback.
* @returns {boolean} Returns true if the bodies collided, otherwise false.
*/
separate: function (body1, body2, processCallback, callbackContext, overlapOnly) {
if (!Phaser.Rectangle.intersects(body1, body2))
{
return false;
}
// They overlap. Is there a custom process callback? If it returns true then we can carry on, otherwise we should abort.
if (processCallback && processCallback.call(callbackContext, body1.sprite, body2.sprite) === false)
{
return false;
}
if (this.separateX(body1, body2, overlapOnly) || this.separateY(body1, body2, overlapOnly))
{
this._result = true;
return true;
}
else
{
return false;
}
},
/**
* The core separation function to separate two physics bodies on the x axis.
* @method Phaser.Physics.Arcade#separateX
* @param {Phaser.Physics.Arcade.Body} body1 - The Body object to separate.
* @param {Phaser.Physics.Arcade.Body} body2 - The Body object to separate.
* @param {boolean} overlapOnly - If true the bodies will only have their overlap data set, no separation or exchange of velocity will take place.
* @returns {boolean} Returns true if the bodies were separated, otherwise false.
*/
separateX: function (body1, body2, overlapOnly) {
// Can't separate two immovable bodies
if (body1.immovable && body2.immovable)
{
return false;
}
this._overlap = 0;
// Check if the hulls actually overlap
if (Phaser.Rectangle.intersects(body1, body2))
{
this._maxOverlap = body1.deltaAbsX() + body2.deltaAbsX() + this.OVERLAP_BIAS;
if (body1.deltaX() === 0 && body2.deltaX() === 0)
{
// They overlap but neither of them are moving
body1.embedded = true;
body2.embedded = true;
}
else if (body1.deltaX() > body2.deltaX())
{
// Body1 is moving right and/or Body2 is moving left
this._overlap = body1.x + body1.width - body2.x;
if ((this._overlap > this._maxOverlap) || body1.checkCollision.right === false || body2.checkCollision.left === false)
{
this._overlap = 0;
}
else
{
body1.touching.right = true;
body2.touching.left = true;
}
}
else if (body1.deltaX() < body2.deltaX())
{
// Body1 is moving left and/or Body2 is moving right
this._overlap = body1.x - body2.width - body2.x;
if ((-this._overlap > this._maxOverlap) || body1.checkCollision.left === false || body2.checkCollision.right === false)
{
this._overlap = 0;
}
else
{
body1.touching.left = true;
body2.touching.right = true;
}
}
// Then adjust their positions and velocities accordingly (if there was any overlap)
if (this._overlap !== 0)
{
body1.overlapX = this._overlap;
body2.overlapX = this._overlap;
if (overlapOnly || body1.customSeparateX || body2.customSeparateX)
{
return true;
}
this._velocity1 = body1.velocity.x;
this._velocity2 = body2.velocity.x;
if (!body1.immovable && !body2.immovable)
{
this._overlap *= 0.5;
body1.x = body1.x - this._overlap;
body2.x += this._overlap;
this._newVelocity1 = Math.sqrt((this._velocity2 * this._velocity2 * body2.mass) / body1.mass) * ((this._velocity2 > 0) ? 1 : -1);
this._newVelocity2 = Math.sqrt((this._velocity1 * this._velocity1 * body1.mass) / body2.mass) * ((this._velocity1 > 0) ? 1 : -1);
this._average = (this._newVelocity1 + this._newVelocity2) * 0.5;
this._newVelocity1 -= this._average;
this._newVelocity2 -= this._average;
body1.velocity.x = this._average + this._newVelocity1 * body1.bounce.x;
body2.velocity.x = this._average + this._newVelocity2 * body2.bounce.x;
}
else if (!body1.immovable)
{
body1.x = body1.x - this._overlap;
body1.velocity.x = this._velocity2 - this._velocity1 * body1.bounce.x;
}
else if (!body2.immovable)
{
body2.x += this._overlap;
body2.velocity.x = this._velocity1 - this._velocity2 * body2.bounce.x;
}
return true;
}
}
return false;
},
/**
* The core separation function to separate two physics bodies on the y axis.
* @method Phaser.Physics.Arcade#separateY
* @param {Phaser.Physics.Arcade.Body} body1 - The Body object to separate.
* @param {Phaser.Physics.Arcade.Body} body2 - The Body object to separate.
* @param {boolean} overlapOnly - If true the bodies will only have their overlap data set, no separation or exchange of velocity will take place.
* @returns {boolean} Returns true if the bodies were separated, otherwise false.
*/
separateY: function (body1, body2, overlapOnly) {
// Can't separate two immovable or non-existing bodys
if (body1.immovable && body2.immovable)
{
return false;
}
this._overlap = 0;
// Check if the hulls actually overlap
if (Phaser.Rectangle.intersects(body1, body2))
{
this._maxOverlap = body1.deltaAbsY() + body2.deltaAbsY() + this.OVERLAP_BIAS;
if (body1.deltaY() === 0 && body2.deltaY() === 0)
{
// They overlap but neither of them are moving
body1.embedded = true;
body2.embedded = true;
}
else if (body1.deltaY() > body2.deltaY())
{
// Body1 is moving down and/or Body2 is moving up
this._overlap = body1.y + body1.height - body2.y;
if ((this._overlap > this._maxOverlap) || body1.checkCollision.down === false || body2.checkCollision.up === false)
{
this._overlap = 0;
}
else
{
body1.touching.down = true;
body2.touching.up = true;
}
}
else if (body1.deltaY() < body2.deltaY())
{
// Body1 is moving up and/or Body2 is moving down
this._overlap = body1.y - body2.height - body2.y;
if ((-this._overlap > this._maxOverlap) || body1.checkCollision.up === false || body2.checkCollision.down === false)
{
this._overlap = 0;
}
else
{
body1.touching.up = true;
body2.touching.down = true;
}
}
// Then adjust their positions and velocities accordingly (if there was any overlap)
if (this._overlap !== 0)
{
body1.overlapY = this._overlap;
body2.overlapY = this._overlap;
if (overlapOnly || body1.customSeparateY || body2.customSeparateY)
{
return true;
}
this._velocity1 = body1.velocity.y;
this._velocity2 = body2.velocity.y;
if (!body1.immovable && !body2.immovable)
{
this._overlap *= 0.5;
body1.y = body1.y - this._overlap;
body2.y += this._overlap;
this._newVelocity1 = Math.sqrt((this._velocity2 * this._velocity2 * body2.mass) / body1.mass) * ((this._velocity2 > 0) ? 1 : -1);
this._newVelocity2 = Math.sqrt((this._velocity1 * this._velocity1 * body1.mass) / body2.mass) * ((this._velocity1 > 0) ? 1 : -1);
this._average = (this._newVelocity1 + this._newVelocity2) * 0.5;
this._newVelocity1 -= this._average;
this._newVelocity2 -= this._average;
body1.velocity.y = this._average + this._newVelocity1 * body1.bounce.y;
body2.velocity.y = this._average + this._newVelocity2 * body2.bounce.y;
}
else if (!body1.immovable)
{
body1.y = body1.y - this._overlap;
body1.velocity.y = this._velocity2 - this._velocity1 * body1.bounce.y;
// This is special case code that handles things like horizontal moving platforms you can ride
if (body2.moves)
{
body1.x += body2.x - body2.prev.x;
}
}
else if (!body2.immovable)
{
body2.y += this._overlap;
body2.velocity.y = this._velocity1 - this._velocity2 * body2.bounce.y;
// This is special case code that handles things like horizontal moving platforms you can ride
if (body1.moves)
{
body2.x += body1.x - body1.prev.x;
}
}
return true;
}
}
return false;
},
separateTiles: function (body, tiles) {
body.resetResult();
var result = false;
for (var i = 0; i < tiles.length; i++)
{
if (this.separateTile(i, body, tiles[i]))
{
result = true;
}
}
return result;
},
separateTile: function (i, body, tile) {
// we re-check for collision in case body was separated in a previous step
if (i > 0 && !tile.intersects(body.position.x, body.position.y, body.right, body.bottom))
{
// no collision so bail out (separted in a previous step)
console.log('no collision so bail out (separted in a previous step');
return false;
}
// console.log('body intersecting tile');
// console.log('x', body.position.x, 'y', body.position.y, 'r', body.right, 'b', body.bottom, 'wh', body.width, body.height);
// console.log('x', tile.x, 'y', tile.y, 'r', tile.right, 'b', tile.bottom);
if (body.newVelocity.x && (tile.faceLeft || tile.faceRight))
{
var px = 0;
var tx = 0;
if (body.newVelocity.x > 0 && tile.faceLeft)
{
px = body.width;
}
else if (body.newVelocity.x < 0 && tile.faceRight)
{
tx = tile.width;
}
body.position.x = tile.worldX - px + tx;
body.velocity.x = 0; // rebound check
// body.newVelocity.x = 0; // rebound check
}
// Vertical only if still colliding
// if (tile.intersects(body.position.x, body.position.y, body.right, body.bottom))
// if (body.newVelocity.y && tile.intersects(body.position.x, body.position.y, body.right, body.bottom))
if (body.newVelocity.y && (tile.faceTop || tile.faceBottom))
{
var py = 0;
var ty = 0;
if (body.newVelocity.y > 0 && tile.faceBottom)
{
py = body.height;
}
else if (body.newVelocity.y < 0 && tile.faceTop)
{
ty = tile.height;
}
// console.log('cy', body.newVelocity.y, py, ty);
body.position.y = tile.worldY - py + ty;
body.velocity.y = 0; // rebound check
// body.newVelocity.y = 0; // rebound check
}
// var pxOffsetX = (body.newVelocity.x > 0 ? body.width : 0);
// var tileOffsetX = (body.newVelocity.x < 0 ? tile.width : 0);
// var pxOffsetY = (body.newVelocity.y > 0 ? body.height : 0);
// var tileOffsetY = (body.newVelocity.y < 0 ? tile.height : 0);
// Assume fully solid for now
// body.result.x = true;
// body.result.tile = tile;
// body.result.px = tile.x - pxOffsetX + tileOffsetX;
// body.position.x = tile.x - pxOffsetX + tileOffsetX;
// res.pos.y = tileY * this.tilesize - pxOffsetY + tileOffsetY;
// console.log('nv', body.newVelocity.x, 'tile.xy', tile.x, tile.y, 'p', pxOffsetX, 't', tileOffsetX, 'body xy', body.position.x, body.position.y);
},
/**
* The core separation function to separate a physics body and a tile.
* @method Phaser.Physics.Arcade#separateTile
* @param {Phaser.Physics.Arcade.Body} body - The Body object to separate.
* @param {Phaser.Tile} tile - The tile to collide against.
* @returns {boolean} Returns true if the body was separated, otherwise false.
*/
XXXseparateTile: function (body, tile) {
/*
this._intersection = this.tileIntersects(body, tile);
// If the intersection area is either entirely null, or has a width/height of zero, we bail out now
if (this._intersection[4] === 0 || this._intersection[2] === 0 || this._intersection[3] === 0)
{
return false;
}
Phaser.Rectangle.intersection(body, tile, this._intersection);
if (this._intersection.width === 0 && this._intersection.height === 0)
{
return false;
}
*/
// console.log(this._intersection);
// console.log(tile, body.x, body.y);
// They overlap. Any custom callbacks?
if (tile.tile.callback || tile.layer.callbacks[tile.tile.index])
{
// A local callback takes priority over a global callback.
if (tile.tile.callback && tile.tile.callback.call(tile.tile.callbackContext, body.sprite, tile) === false)
{
// Is there a tile specific collision callback? If it returns true then we can carry on, otherwise we should abort.
return false;
}
else if (tile.layer.callbacks[tile.tile.index] && tile.layer.callbacks[tile.tile.index].callback.call(tile.layer.callbacks[tile.tile.index].callbackContext, body.sprite, tile) === false)
{
// Is there a tile index collision callback? If it returns true then we can carry on, otherwise we should abort.
return false;
}
}
body.overlapX = 0;
if (body.deltaX() < 0 && body.checkCollision.left)
{
// Body is moving LEFT
if (tile.tile.faceRight && body.x < tile.right)
{
}
}
var process = false;
if (this._intersection.width > 0)
{
// Tile is blocking to the right and body is moving left
if (body.deltaX() < 0 && body.checkCollision.left && tile.tile.faceRight)
{
body.x = tile.right;
// process = true;
// body.overlapX = -this._intersection.width;
}
// Tile is blocking to the left and body is moving right
if (body.deltaX() > 0 && body.checkCollision.right && tile.tile.faceLeft)
{
body.right = tile.x;
// process = true;
// body.overlapX = this._intersection.width;
}
}
/*
if (body.overlapX !== 0)
{
if (body.overlapX < 0)
{
body.blocked.left = true;
}
else if (body.overlapX > 0)
{
body.blocked.right = true;
}
body.x -= body.overlapX;
// body.preX -= body.overlapX;
body.blocked.x = Math.floor(body.x);
body.blocked.y = Math.floor(body.y);
if (body.bounce.x === 0)
{
body.velocity.x = 0;
}
else
{
body.velocity.x = -body.velocity.x * body.bounce.x;
}
}
*/
Phaser.Rectangle.intersection(body, tile, this._intersection);
if (this._intersection.width === 0 && this._intersection.height === 0)
{
return false;
}
body.overlapY = 0;
var process = false;
if (this._intersection.height > 0)
{
// Tile is blocking to the bottom and body is moving up
if (body.deltaY() < 0 && body.checkCollision.up && tile.tile.faceBottom)
{
// process = true;
// body.overlapY = -this._intersection.height;
}
// Tile is blocking to the top and body is moving down
if (body.deltaY() > 0 && body.checkCollision.down && tile.tile.faceTop)
{
process = true;
body.overlapY = this._intersection.height;
}
}
if (body.overlapY !== 0)
{
if (body.overlapY < 0)
{
body.blocked.up = true;
}
else if (body.overlapY > 0)
{
body.blocked.down = true;
}
body.y -= body.overlapY;
// body.preY -= body.overlapY;
body.blocked.x = Math.floor(body.x);
body.blocked.y = Math.floor(body.y);
if (body.bounce.y === 0)
{
body.velocity.y = 0;
}
else
{
body.velocity.y = -body.velocity.y * body.bounce.y;
}
}
return;
/*
if (body.deltaX() < 0 && body.checkCollision.left && tile.tile.faceRight && !body.blocked.left)
// if (body.deltaX() < 0 && body.checkCollision.left && tile.tile.faceRight)
{
// LEFT
body.overlapX = body.x - tile.right;
if (body.overlapX < 0)
{
process = true;
}
else
{
body.overlapX = 0;
}
}
else if (body.deltaX() > 0 && body.checkCollision.right && tile.tile.faceLeft && !body.blocked.right)
// else if (body.deltaX() > 0 && body.checkCollision.right && tile.tile.faceLeft)
{
// RIGHT
body.overlapX = body.right - tile.x;
if (body.overlapX > 0)
{
process = true;
}
else
{
body.overlapX = 0;
}
}
if (body.deltaY() < 0 && body.checkCollision.up && tile.tile.faceBottom && !body.blocked.up)
// if (body.deltaY() < 0 && body.checkCollision.up && tile.tile.faceBottom)
{
// UP
body.overlapY = body.y - tile.bottom;
if (body.overlapY < 0)
{
process = true;
}
else
{
body.overlapY = 0;
}
}
else if (body.deltaY() > 0 && body.checkCollision.down && tile.tile.faceTop && !body.blocked.down)
// else if (body.deltaY() > 0 && body.checkCollision.down && tile.tile.faceTop)
{
// DOWN
body.overlapY = body.bottom - tile.y;
if (body.overlapY > 0)
{
process = true;
}
else
{
body.overlapY = 0;
}
}
*/
// Only separate on the smallest of the two values if it's a single tile
/*
if (body.overlapX !== 0 && body.overlapY !== 0)
{
if (Math.abs(body.overlapX) > Math.abs(body.overlapY))
{
body.overlapX = 0;
}
else
{
body.overlapY = 0;
}
}
*/
// Separate in a single sweep
/* if (process)
{
return this.processTileSeparation(body);
}
else
{
return false;
}
*/
},
/**
* Internal function to process the separation of a physics body from a tile.
* @method Phaser.Physics.Arcade#processTileSeparation
* @protected
* @param {Phaser.Physics.Arcade.Body} body - The Body object to separate.
* @returns {boolean} Returns true if separated, false if not.
*/
processTileSeparation: function (body) {
if (body.overlapX !== 0)
{
if (body.overlapX < 0)
{
body.blocked.left = true;
}
else if (body.overlapX > 0)
{
body.blocked.right = true;
}
body.x -= body.overlapX;
body.preX -= body.overlapX;
body.blocked.x = Math.floor(body.x);
body.blocked.y = Math.floor(body.y);
if (body.bounce.x === 0)
{
body.velocity.x = 0;
}
else
{
body.velocity.x = -body.velocity.x * body.bounce.x;
}
}
if (body.overlapY !== 0)
{
if (body.overlapY < 0)
{
body.blocked.up = true;
}
else if (body.overlapY > 0)
{
body.blocked.down = true;
}
body.y -= body.overlapY;
body.preY -= body.overlapY;
body.blocked.x = Math.floor(body.x);
body.blocked.y = Math.floor(body.y);
if (body.bounce.y === 0)
{
body.velocity.y = 0;
}
else
{
body.velocity.y = -body.velocity.y * body.bounce.y;
}
}
return true;
},
/**
* Move the given display object towards the destination object at a steady velocity.
* If you specify a maxTime then it will adjust the speed (overwriting what you set) so it arrives at the destination in that number of seconds.
* Timings are approximate due to the way browser timers work. Allow for a variance of +- 50ms.
* Note: The display object does not continuously track the target. If the target changes location during transit the display object will not modify its course.
* Note: The display object doesn't stop moving once it reaches the destination coordinates.
* Note: Doesn't take into account acceleration, maxVelocity or drag (if you've set drag or acceleration too high this object may not move at all)
*
* @method Phaser.Physics.Arcade#moveToObject
* @param {any} displayObject - The display object to move.
* @param {any} destination - The display object to move towards. Can be any object but must have visible x/y properties.
* @param {number} [speed=60] - The speed it will move, in pixels per second (default is 60 pixels/sec)
* @param {number} [maxTime=0] - Time given in milliseconds (1000 = 1 sec). If set the speed is adjusted so the object will arrive at destination in the given number of ms.
* @return {number} The angle (in radians) that the object should be visually set to in order to match its new velocity.
*/
moveToObject: function (displayObject, destination, speed, maxTime) {
if (typeof speed === 'undefined') { speed = 60; }
if (typeof maxTime === 'undefined') { maxTime = 0; }
this._angle = Math.atan2(destination.y - displayObject.y, destination.x - displayObject.x);
if (maxTime > 0)
{
// We know how many pixels we need to move, but how fast?
speed = this.distanceBetween(displayObject, destination) / (maxTime / 1000);
}
displayObject.body.velocity.x = Math.cos(this._angle) * speed;
displayObject.body.velocity.y = Math.sin(this._angle) * speed;
return this._angle;
},
/**
* Move the given display object towards the destination object at a steady velocity.
* If you specify a maxTime then it will adjust the speed (over-writing what you set) so it arrives at the destination in that number of seconds.
* Timings are approximate due to the way browser timers work. Allow for a variance of +- 50ms.
* Note: The display object does not continuously track the target. If the target changes location during transit the display object will not modify its course.
* Note: The display object doesn't stop moving once it reaches the destination coordinates.
* Note: Doesn't take into account acceleration, maxVelocity or drag (if you've set drag or acceleration too high this object may not move at all)
*
* @method Phaser.Physics.Arcade#moveToObject
* @param {any} displayObject - The display object to move.
* @param {any} destination - The display object to move towards. Can be any object but must have visible x/y properties.
* @param {number} [speed=60] - The speed it will move, in pixels per second (default is 60 pixels/sec)
* @param {number} [maxTime=0] - Time given in milliseconds (1000 = 1 sec). If set the speed is adjusted so the object will arrive at destination in the given number of ms.
* @return {number} The angle (in radians) that the object should be visually set to in order to match its new velocity.
*/
moveToObject: function (displayObject, destination, speed, maxTime) {
if (typeof speed === 'undefined') { speed = 60; }
if (typeof maxTime === 'undefined') { maxTime = 0; }
this._angle = Math.atan2(destination.y - displayObject.y, destination.x - displayObject.x);
if (maxTime > 0)
{
// We know how many pixels we need to move, but how fast?
speed = this.distanceBetween(displayObject, destination) / (maxTime / 1000);
}
displayObject.body.velocity.x = Math.cos(this._angle) * speed;
displayObject.body.velocity.y = Math.sin(this._angle) * speed;
return this._angle;
},
/**
* Move the given display object towards the pointer at a steady velocity. If no pointer is given it will use Phaser.Input.activePointer.
* If you specify a maxTime then it will adjust the speed (over-writing what you set) so it arrives at the destination in that number of seconds.
* Timings are approximate due to the way browser timers work. Allow for a variance of +- 50ms.
* Note: The display object does not continuously track the target. If the target changes location during transit the display object will not modify its course.
* Note: The display object doesn't stop moving once it reaches the destination coordinates.
*
* @method Phaser.Physics.Arcade#moveToPointer
* @param {any} displayObject - The display object to move.
* @param {number} [speed=60] - The speed it will move, in pixels per second (default is 60 pixels/sec)
* @param {Phaser.Pointer} [pointer] - The pointer to move towards. Defaults to Phaser.Input.activePointer.
* @param {number} [maxTime=0] - Time given in milliseconds (1000 = 1 sec). If set the speed is adjusted so the object will arrive at destination in the given number of ms.
* @return {number} The angle (in radians) that the object should be visually set to in order to match its new velocity.
*/
moveToPointer: function (displayObject, speed, pointer, maxTime) {
if (typeof speed === 'undefined') { speed = 60; }
pointer = pointer || this.game.input.activePointer;
if (typeof maxTime === 'undefined') { maxTime = 0; }
this._angle = this.angleToPointer(displayObject, pointer);
if (maxTime > 0)
{
// We know how many pixels we need to move, but how fast?
speed = this.distanceToPointer(displayObject, pointer) / (maxTime / 1000);
}
displayObject.body.velocity.x = Math.cos(this._angle) * speed;
displayObject.body.velocity.y = Math.sin(this._angle) * speed;
return this._angle;
},
/**
* Move the given display object towards the x/y coordinates at a steady velocity.
* If you specify a maxTime then it will adjust the speed (over-writing what you set) so it arrives at the destination in that number of seconds.
* Timings are approximate due to the way browser timers work. Allow for a variance of +- 50ms.
* Note: The display object does not continuously track the target. If the target changes location during transit the display object will not modify its course.
* Note: The display object doesn't stop moving once it reaches the destination coordinates.
* Note: Doesn't take into account acceleration, maxVelocity or drag (if you've set drag or acceleration too high this object may not move at all)
*
* @method Phaser.Physics.Arcade#moveToXY
* @param {any} displayObject - The display object to move.
* @param {number} x - The x coordinate to move towards.
* @param {number} y - The y coordinate to move towards.
* @param {number} [speed=60] - The speed it will move, in pixels per second (default is 60 pixels/sec)
* @param {number} [maxTime=0] - Time given in milliseconds (1000 = 1 sec). If set the speed is adjusted so the object will arrive at destination in the given number of ms.
* @return {number} The angle (in radians) that the object should be visually set to in order to match its new velocity.
*/
moveToXY: function (displayObject, x, y, speed, maxTime) {
if (typeof speed === 'undefined') { speed = 60; }
if (typeof maxTime === 'undefined') { maxTime = 0; }
this._angle = Math.atan2(y - displayObject.y, x - displayObject.x);
if (maxTime > 0)
{
// We know how many pixels we need to move, but how fast?
speed = this.distanceToXY(displayObject, x, y) / (maxTime / 1000);
}
displayObject.body.velocity.x = Math.cos(this._angle) * speed;
displayObject.body.velocity.y = Math.sin(this._angle) * speed;
return this._angle;
},
/**
* Given the angle (in degrees) and speed calculate the velocity and return it as a Point object, or set it to the given point object.
* One way to use this is: velocityFromAngle(angle, 200, sprite.velocity) which will set the values directly to the sprites velocity and not create a new Point object.
*
* @method Phaser.Physics.Arcade#velocityFromAngle
* @param {number} angle - The angle in degrees calculated in clockwise positive direction (down = 90 degrees positive, right = 0 degrees positive, up = 90 degrees negative)
* @param {number} [speed=60] - The speed it will move, in pixels per second sq.
* @param {Phaser.Point|object} [point] - The Point object in which the x and y properties will be set to the calculated velocity.
* @return {Phaser.Point} - A Point where point.x contains the velocity x value and point.y contains the velocity y value.
*/
velocityFromAngle: function (angle, speed, point) {
if (typeof speed === 'undefined') { speed = 60; }
point = point || new Phaser.Point();
return point.setTo((Math.cos(this.game.math.degToRad(angle)) * speed), (Math.sin(this.game.math.degToRad(angle)) * speed));
},
/**
* Given the rotation (in radians) and speed calculate the velocity and return it as a Point object, or set it to the given point object.
* One way to use this is: velocityFromRotation(rotation, 200, sprite.velocity) which will set the values directly to the sprites velocity and not create a new Point object.
*
* @method Phaser.Physics.Arcade#velocityFromRotation
* @param {number} rotation - The angle in radians.
* @param {number} [speed=60] - The speed it will move, in pixels per second sq.
* @param {Phaser.Point|object} [point] - The Point object in which the x and y properties will be set to the calculated velocity.
* @return {Phaser.Point} - A Point where point.x contains the velocity x value and point.y contains the velocity y value.
*/
velocityFromRotation: function (rotation, speed, point) {
if (typeof speed === 'undefined') { speed = 60; }
point = point || new Phaser.Point();
return point.setTo((Math.cos(rotation) * speed), (Math.sin(rotation) * speed));
},
/**
* Given the rotation (in radians) and speed calculate the acceleration and return it as a Point object, or set it to the given point object.
* One way to use this is: accelerationFromRotation(rotation, 200, sprite.acceleration) which will set the values directly to the sprites acceleration and not create a new Point object.
*
* @method Phaser.Physics.Arcade#accelerationFromRotation
* @param {number} rotation - The angle in radians.
* @param {number} [speed=60] - The speed it will move, in pixels per second sq.
* @param {Phaser.Point|object} [point] - The Point object in which the x and y properties will be set to the calculated acceleration.
* @return {Phaser.Point} - A Point where point.x contains the acceleration x value and point.y contains the acceleration y value.
*/
accelerationFromRotation: function (rotation, speed, point) {
if (typeof speed === 'undefined') { speed = 60; }
point = point || new Phaser.Point();
return point.setTo((Math.cos(rotation) * speed), (Math.sin(rotation) * speed));
},
/**
* Sets the acceleration.x/y property on the display object so it will move towards the target at the given speed (in pixels per second sq.)
* You must give a maximum speed value, beyond which the display object won't go any faster.
* Note: The display object does not continuously track the target. If the target changes location during transit the display object will not modify its course.
* Note: The display object doesn't stop moving once it reaches the destination coordinates.
*
* @method Phaser.Physics.Arcade#accelerateToObject
* @param {any} displayObject - The display object to move.
* @param {any} destination - The display object to move towards. Can be any object but must have visible x/y properties.
* @param {number} [speed=60] - The speed it will accelerate in pixels per second.
* @param {number} [xSpeedMax=500] - The maximum x velocity the display object can reach.
* @param {number} [ySpeedMax=500] - The maximum y velocity the display object can reach.
* @return {number} The angle (in radians) that the object should be visually set to in order to match its new trajectory.
*/
accelerateToObject: function (displayObject, destination, speed, xSpeedMax, ySpeedMax) {
if (typeof speed === 'undefined') { speed = 60; }
if (typeof xSpeedMax === 'undefined') { xSpeedMax = 1000; }
if (typeof ySpeedMax === 'undefined') { ySpeedMax = 1000; }
this._angle = this.angleBetween(displayObject, destination);
displayObject.body.acceleration.setTo(Math.cos(this._angle) * speed, Math.sin(this._angle) * speed);
displayObject.body.maxVelocity.setTo(xSpeedMax, ySpeedMax);
return this._angle;
},
/**
* Sets the acceleration.x/y property on the display object so it will move towards the target at the given speed (in pixels per second sq.)
* You must give a maximum speed value, beyond which the display object won't go any faster.
* Note: The display object does not continuously track the target. If the target changes location during transit the display object will not modify its course.
* Note: The display object doesn't stop moving once it reaches the destination coordinates.
*
* @method Phaser.Physics.Arcade#accelerateToPointer
* @param {any} displayObject - The display object to move.
* @param {Phaser.Pointer} [pointer] - The pointer to move towards. Defaults to Phaser.Input.activePointer.
* @param {number} [speed=60] - The speed it will accelerate in pixels per second.
* @param {number} [xSpeedMax=500] - The maximum x velocity the display object can reach.
* @param {number} [ySpeedMax=500] - The maximum y velocity the display object can reach.
* @return {number} The angle (in radians) that the object should be visually set to in order to match its new trajectory.
*/
accelerateToPointer: function (displayObject, pointer, speed, xSpeedMax, ySpeedMax) {
if (typeof speed === 'undefined') { speed = 60; }
if (typeof pointer === 'undefined') { pointer = this.game.input.activePointer; }
if (typeof xSpeedMax === 'undefined') { xSpeedMax = 1000; }
if (typeof ySpeedMax === 'undefined') { ySpeedMax = 1000; }
this._angle = this.angleToPointer(displayObject, pointer);
displayObject.body.acceleration.setTo(Math.cos(this._angle) * speed, Math.sin(this._angle) * speed);
displayObject.body.maxVelocity.setTo(xSpeedMax, ySpeedMax);
return this._angle;
},
/**
* Sets the acceleration.x/y property on the display object so it will move towards the x/y coordinates at the given speed (in pixels per second sq.)
* You must give a maximum speed value, beyond which the display object won't go any faster.
* Note: The display object does not continuously track the target. If the target changes location during transit the display object will not modify its course.
* Note: The display object doesn't stop moving once it reaches the destination coordinates.
*
* @method Phaser.Physics.Arcade#accelerateToXY
* @param {any} displayObject - The display object to move.
* @param {number} x - The x coordinate to accelerate towards.
* @param {number} y - The y coordinate to accelerate towards.
* @param {number} [speed=60] - The speed it will accelerate in pixels per second.
* @param {number} [xSpeedMax=500] - The maximum x velocity the display object can reach.
* @param {number} [ySpeedMax=500] - The maximum y velocity the display object can reach.
* @return {number} The angle (in radians) that the object should be visually set to in order to match its new trajectory.
*/
accelerateToXY: function (displayObject, x, y, speed, xSpeedMax, ySpeedMax) {
if (typeof speed === 'undefined') { speed = 60; }
if (typeof xSpeedMax === 'undefined') { xSpeedMax = 1000; }
if (typeof ySpeedMax === 'undefined') { ySpeedMax = 1000; }
this._angle = this.angleToXY(displayObject, x, y);
displayObject.body.acceleration.setTo(Math.cos(this._angle) * speed, Math.sin(this._angle) * speed);
displayObject.body.maxVelocity.setTo(xSpeedMax, ySpeedMax);
return this._angle;
},
/**
* Find the distance between two display objects (like Sprites).
*
* @method Phaser.Physics.Arcade#distanceBetween
* @param {any} source - The Display Object to test from.
* @param {any} target - The Display Object to test to.
* @return {number} The distance between the source and target objects.
*/
distanceBetween: function (source, target) {
this._dx = source.x - target.x;
this._dy = source.y - target.y;
return Math.sqrt(this._dx * this._dx + this._dy * this._dy);
},
/**
* Find the distance between a display object (like a Sprite) and the given x/y coordinates.
* The calculation is made from the display objects x/y coordinate. This may be the top-left if its anchor hasn't been changed.
* If you need to calculate from the center of a display object instead use the method distanceBetweenCenters()
*
* @method Phaser.Physics.Arcade#distanceToXY
* @param {any} displayObject - The Display Object to test from.
* @param {number} x - The x coordinate to move towards.
* @param {number} y - The y coordinate to move towards.
* @return {number} The distance between the object and the x/y coordinates.
*/
distanceToXY: function (displayObject, x, y) {
this._dx = displayObject.x - x;
this._dy = displayObject.y - y;
return Math.sqrt(this._dx * this._dx + this._dy * this._dy);
},
/**
* Find the distance between a display object (like a Sprite) and a Pointer. If no Pointer is given the Input.activePointer is used.
* The calculation is made from the display objects x/y coordinate. This may be the top-left if its anchor hasn't been changed.
* If you need to calculate from the center of a display object instead use the method distanceBetweenCenters()
*
* @method Phaser.Physics.Arcade#distanceToPointer
* @param {any} displayObject - The Display Object to test from.
* @param {Phaser.Pointer} [pointer] - The Phaser.Pointer to test to. If none is given then Input.activePointer is used.
* @return {number} The distance between the object and the Pointer.
*/
distanceToPointer: function (displayObject, pointer) {
pointer = pointer || this.game.input.activePointer;
this._dx = displayObject.x - pointer.x;
this._dy = displayObject.y - pointer.y;
return Math.sqrt(this._dx * this._dx + this._dy * this._dy);
},
/**
* Find the angle in radians between two display objects (like Sprites).
*
* @method Phaser.Physics.Arcade#angleBetween
* @param {any} source - The Display Object to test from.
* @param {any} target - The Display Object to test to.
* @return {number} The angle in radians between the source and target display objects.
*/
angleBetween: function (source, target) {
this._dx = target.x - source.x;
this._dy = target.y - source.y;
return Math.atan2(this._dy, this._dx);
},
/**
* Find the angle in radians between a display object (like a Sprite) and the given x/y coordinate.
*
* @method Phaser.Physics.Arcade#angleToXY
* @param {any} displayObject - The Display Object to test from.
* @param {number} x - The x coordinate to get the angle to.
* @param {number} y - The y coordinate to get the angle to.
* @return {number} The angle in radians between displayObject.x/y to Pointer.x/y
*/
angleToXY: function (displayObject, x, y) {
this._dx = x - displayObject.x;
this._dy = y - displayObject.y;
return Math.atan2(this._dy, this._dx);
},
/**
* Find the angle in radians between a display object (like a Sprite) and a Pointer, taking their x/y and center into account.
*
* @method Phaser.Physics.Arcade#angleToPointer
* @param {any} displayObject - The Display Object to test from.
* @param {Phaser.Pointer} [pointer] - The Phaser.Pointer to test to. If none is given then Input.activePointer is used.
* @return {number} The angle in radians between displayObject.x/y to Pointer.x/y
*/
angleToPointer: function (displayObject, pointer) {
pointer = pointer || this.game.input.activePointer;
this._dx = pointer.worldX - displayObject.x;
this._dy = pointer.worldY - displayObject.y;
return Math.atan2(this._dy, this._dx);
}
};
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2014 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* The Physics Body is linked to a single Sprite. All physics operations should be performed against the body rather than
* the Sprite itself. For example you can set the velocity, acceleration, bounce values etc all on the Body.
*
* @class Phaser.Physics.Arcade.Body
* @classdesc Arcade Physics Body Constructor
* @constructor
* @param {Phaser.Sprite} sprite - The Sprite object this physics body belongs to.
*/
Phaser.Physics.Arcade.Body = function (sprite) {
/**
* @property {Phaser.Sprite} sprite - Reference to the parent Sprite.
*/
this.sprite = sprite;
/**
* @property {Phaser.Game} game - Local reference to game.
*/
this.game = sprite.game;
/**
* @property {number} type - The type of physics system this body belongs to.
*/
this.type = Phaser.Physics.ARCADE;
/**
* @property {Phaser.Point} offset - The offset of the Physics Body from the Sprite x/y position.
*/
this.offset = new Phaser.Point(-(sprite.anchor.x * sprite.width), -(sprite.anchor.y * sprite.height));
/**
* @property {Phaser.Point} position - The position of the physics body.
* @readonly
*/
this.position = new Phaser.Point(sprite.x + this.offset.x, sprite.y + this.offset.y);
/**
* @property {Phaser.Point} prev - The previous position of the physics body.
* @readonly
*/
this.prev = new Phaser.Point(this.position.x, this.position.y);
/**
* @property {number} preRotation - The previous rotation of the physics body.
* @readonly
*/
this.preRotation = sprite.angle;
/**
* @property {number} sourceWidth - The un-scaled original size.
* @readonly
*/
this.sourceWidth = sprite.texture.frame.width;
/**
* @property {number} sourceHeight - The un-scaled original size.
* @readonly
*/
this.sourceHeight = sprite.texture.frame.height;
/**
* @property {number} width - The calculated width of the physics body.
*/
this.width = sprite.width;
/**
* @property .numInternal ID cache
*/
this.height = sprite.height;
/**
* @property {number} halfWidth - The calculated width / 2 of the physics body.
*/
this.halfWidth = Math.abs(sprite.width / 2);
/**
* @property {number} halfHeight - The calculated height / 2 of the physics body.
*/
this.halfHeight = Math.abs(sprite.height / 2);
/**
* @property {Phaser.Point} center - The center coordinate of the Physics Body.
*/
this.center = new Phaser.Point(sprite.x + this.halfWidth, sprite.y + this.halfHeight);
/**
* @property {number} _sx - Internal cache var.
* @private
*/
this._sx = sprite.scale.x;
/**
* @property {number} _sy - Internal cache var.
* @private
*/
this._sy = sprite.scale.y;
/**
* @property {Phaser.Point} velocity - The velocity in pixels per second sq. of the Body.
*/
this.velocity = new Phaser.Point();
/**
* @property {Phaser.Point} newVelocity - New velocity.
* @readonly
*/
this.newVelocity = new Phaser.Point(0, 0);
/**
* @property {Phaser.Point} acceleration - The velocity in pixels per second sq. of the Body.
*/
this.acceleration = new Phaser.Point();
/**
* @property {Phaser.Point} drag - The drag applied to the motion of the Body.
*/
this.drag = new Phaser.Point();
/**
* @property {Phaser.Point} gravityScale - Gravity scaling factor. If you want the body to ignore gravity, set this to zero. If you want to reverse gravity, set it to -1.
*/
this.gravityScale = new Phaser.Point(1, 1);
/**
* @property {Phaser.Point} bounce - The elasticitiy of the Body when colliding. bounce.x/y = 1 means full rebound, bounce.x/y = 0.5 means 50% rebound velocity.
*/
this.bounce = new Phaser.Point();
/**
* @property {Phaser.Point} maxVelocity - The maximum velocity in pixels per second sq. that the Body can reach.
* @default
*/
this.maxVelocity = new Phaser.Point(10000, 10000);
/**
* @property {number} angularVelocity - The angular velocity in pixels per second sq. of the Body.
* @default
*/
this.angularVelocity = 0;
/**
* @property {number} angularAcceleration - The angular acceleration in pixels per second sq. of the Body.
* @default
*/
this.angularAcceleration = 0;
/**
* @property {number} angularDrag - The angular drag applied to the rotation of the Body.
* @default
*/
this.angularDrag = 0;
/**
* @property {number} maxAngular - The maximum angular velocity in pixels per second sq. that the Body can reach.
* @default
*/
this.maxAngular = 1000;
/**
* @property {number} mass - The mass of the Body.
* @default
*/
this.mass = 1;
/**
* @property {boolean} skipQuadTree - If the Body is an irregular shape you can set this to true to avoid it being added to any QuadTrees.
* @default
*/
this.skipQuadTree = false;
/**
* @property {number} facing - A const reference to the direction the Body is traveling or facing.
* @default
*/
this.facing = Phaser.NONE;
/**
* @property {boolean} immovable - An immovable Body will not receive any impacts from other bodies.
* @default
*/
this.immovable = false;
/**
* @property {boolean} moves - Set to true to allow the Physics system to move this Body, other false to move it manually.
* @default
*/
this.moves = true;
/**
* @property {number} rotation - The amount the Body is rotated.
* @default
*/
this.rotation = 0;
/**
* @property {boolean} allowRotation - Allow this Body to be rotated? (via angularVelocity, etc)
* @default
*/
this.allowRotation = true;
/**
* This flag allows you to disable the custom x separation that takes place by Physics.Arcade.separate.
* Used in combination with your own collision processHandler you can create whatever type of collision response you need.
* @property {boolean} customSeparateX - Use a custom separation system or the built-in one?
* @default
*/
this.customSeparateX = false;
/**
* This flag allows you to disable the custom y separation that takes place by Physics.Arcade.separate.
* Used in combination with your own collision processHandler you can create whatever type of collision response you need.
* @property {boolean} customSeparateY - Use a custom separation system or the built-in one?
* @default
*/
this.customSeparateY = false;
/**
* When this body collides with another, the amount of overlap is stored here.
* @property {number} overlapX - The amount of horizontal overlap during the collision.
*/
this.overlapX = 0;
/**
* When this body collides with another, the amount of overlap is stored here.
* @property {number} overlapY - The amount of vertical overlap during the collision.
*/
this.overlapY = 0;
/**
* If a body is overlapping with another body, but neither of them are moving (maybe they spawned on-top of each other?) this is set to true.
* @property {boolean} embedded - Body embed value.
*/
this.embedded = false;
/**
* A Body can be set to collide against the World bounds automatically and rebound back into the World if this is set to true. Otherwise it will leave the World.
* @property {boolean} collideWorldBounds - Should the Body collide with the World bounds?
*/
this.collideWorldBounds = false;
/**
* Set the checkCollision properties to control which directions collision is processed for this Body.
* For example checkCollision.up = false means it won't collide when the collision happened while moving up.
* @property {object} checkCollision - An object containing allowed collision.
*/
this.checkCollision = { none: false, any: true, up: true, down: true, left: true, right: true };
/**
* This object is populated with boolean values when the Body collides with another.
* touching.up = true means the collision happened to the top of this Body for example.
* @property {object} touching - An object containing touching results.
*/
this.touching = { none: true, up: false, down: false, left: false, right: false };
/**
* This object is populated with previous touching values from the bodies previous collision.
* @property {object} wasTouching - An object containing previous touching results.
*/
this.wasTouching = { none: true, up: false, down: false, left: false, right: false };
/**
* This object is populated with boolean values when the Body collides with the World bounds or a Tile.
* For example if blocked.up is true then the Body cannot move up.
* @property {object} blocked - An object containing on which faces this Body is blocked from moving, if any.
*/
this.blocked = { x: 0, y: 0, up: false, down: false, left: false, right: false };
/**
* This object is populated with boolean values when the Body collides with the World bounds or a Tile.
* For example if blocked.up is true then the Body cannot move up.
* @property {object} blocked - An object containing on which faces this Body is blocked from moving, if any.
*/
this.result = { x: 0, y: 0, px: 0, py: 0, tx: 0, ty: 0, slope: false };
};
Phaser.Physics.Arcade.Body.prototype = {
resetResult: function () {
this.result.x = false;
this.result.y = false;
this.result.slope = false;
this.result.px = this.position.x;
this.result.py = this.position.y;
this.result.tx = 0;
this.result.ty = 0;
},
/**
* Internal method.
*
* @method Phaser.Physics.Arcade#updateBounds
* @protected
*/
updateBounds: function (centerX, centerY, scaleX, scaleY) {
if (scaleX != this._sx || scaleY != this._sy)
{
this.width = this.sourceWidth * scaleX;
this.height = this.sourceHeight * scaleY;
this.halfWidth = Math.floor(this.width / 2);
this.halfHeight = Math.floor(this.height / 2);
this._sx = scaleX;
this._sy = scaleY;
this.center.setTo(this.x + this.halfWidth, this.y + this.halfHeight);
}
},
/**
* Internal method.
*
* @method Phaser.Physics.Arcade#preUpdate
* @protected
*/
preUpdate: function () {
this.resetResult();
// Store and reset collision flags
this.wasTouching.none = this.touching.none;
this.wasTouching.up = this.touching.up;
this.wasTouching.down = this.touching.down;
this.wasTouching.left = this.touching.left;
this.wasTouching.right = this.touching.right;
this.touching.none = true;
this.touching.up = false;
this.touching.down = false;
this.touching.left = false;
this.touching.right = false;
this.embedded = false;
// this.screenX = (this.sprite.worldTransform[2] - (this.sprite.anchor.x * this.width)) + this.offset.x;
// this.screenY = (this.sprite.worldTransform[5] - (this.sprite.anchor.y * this.height)) + this.offset.y;
// this is where the Sprite currently is, in world coordinates
// this.preX = (this.sprite.world.x - (this.sprite.anchor.x * this.width)) + this.offset.x;
// this.preY = (this.sprite.world.y - (this.sprite.anchor.y * this.height)) + this.offset.y;
// this.preRotation = this.sprite.angle;
// this.x = this.preX;
// this.y = this.preY;
// this.rotation = this.preRotation;
// this.overlapX = 0;
// this.overlapY = 0;
this.prev.set(this.position.x, this.position.y);
// this.position.x = (this.sprite.world.x - (this.sprite.anchor.x * this.width)) + this.offset.x;
// this.position.y = (this.sprite.world.y - (this.sprite.anchor.y * this.height)) + this.offset.y;
// this.blocked.up = false;
// this.blocked.down = false;
// this.blocked.left = false;
// this.blocked.right = false;
if (this.moves)
{
this.game.physics.arcade.updateMotion(this);
this.newVelocity.set(this.velocity.x * this.game.time.physicsElapsed, this.velocity.y * this.game.time.physicsElapsed);
this.position.x += this.newVelocity.x;
this.position.y += this.newVelocity.y;
// Now the State update will throw collision checks at the Body
// And finally we'll integrate the new position back to the Sprite in postUpdate
if (this.collideWorldBounds)
{
this.checkWorldBounds();
}
}
},
/**
* Internal method.
*
* @method Phaser.Physics.Arcade#postUpdate
* @protected
*/
postUpdate: function () {
// if (this.result.x)
// {
// this.position.x = this.result.px;
// this.velocity.x = 0;
// }
// else
// {
// this.position.x += this.newVelocity.x;
// }
// this.position.y += this.newVelocity.y;
// this.position.add(this.newVelocity.x, this.newVelocity.y);
this.sprite.x = (this.position.x - this.offset.x);
this.sprite.y = (this.position.y - this.offset.y);
/* if (this.deltaX() < 0)
{
this.facing = Phaser.LEFT;
this.sprite.x += this.deltaX();
}
else if (this.deltaX() > 0)
{
this.facing = Phaser.RIGHT;
this.sprite.x += this.deltaX();
}
if (this.deltaY() < 0)
{
this.facing = Phaser.UP;
this.sprite.y += this.deltaY();
}
else if (this.deltaY() > 0)
{
this.facing = Phaser.DOWN;
this.sprite.y += this.deltaY();
}
*/
// this.sprite.x += this.overlapX;
// this.sprite.y += this.overlapY;
// this is where the Sprite currently is, in world coordinates
// this.sprite.x = (this.sprite.world.x - (this.sprite.anchor.x * this.width)) + this.offset.x;
// this.sprite.y = (this.sprite.world.y - (this.sprite.anchor.y * this.height)) + this.offset.y;
/*
if (this.deltaX() < 0 && this.blocked.left === false)
{
this.facing = Phaser.LEFT;
this.sprite.x += this.deltaX();
}
else if (this.deltaX() > 0 && this.blocked.right === false)
{
this.facing = Phaser.RIGHT;
this.sprite.x += this.deltaX();
}
if (this.deltaY() < 0 && this.blocked.up === false)
{
this.facing = Phaser.UP;
this.sprite.y += this.deltaY();
}
else if (this.deltaY() > 0 && this.blocked.down === false)
{
this.facing = Phaser.DOWN;
this.sprite.y += this.deltaY();
}
*/
this.center.setTo(this.x + this.halfWidth, this.y + this.halfHeight);
if (this.allowRotation)
{
this.sprite.angle += this.deltaZ();
}
},
/**
* Internal method.
*
* @method Phaser.Physics.Arcade#checkWorldBounds
* @protected
*/
checkWorldBounds: function () {
if (this.x < this.game.world.bounds.x)
{
this.x = this.game.world.bounds.x;
this.velocity.x *= -this.bounce.x;
}
else if (this.right > this.game.world.bounds.right)
{
this.x = this.game.world.bounds.right - this.width;
this.velocity.x *= -this.bounce.x;
}
if (this.y < this.game.world.bounds.y)
{
this.y = this.game.world.bounds.y;
this.velocity.y *= -this.bounce.y;
}
else if (this.bottom > this.game.world.bounds.bottom)
{
this.y = this.game.world.bounds.bottom - this.height;
this.velocity.y *= -this.bounce.y;
}
},
/**
* You can modify the size of the physics Body to be any dimension you need.
* So it could be smaller or larger than the parent Sprite. You can also control the x and y offset, which
* is the position of the Body relative to the top-left of the Sprite.
*
* @method Phaser.Physics.Arcade#setSize
* @param {number} width - The width of the Body.
* @param {number} height - The height of the Body.
* @param {number} offsetX - The X offset of the Body from the Sprite position.
* @param {number} offsetY - The Y offset of the Body from the Sprite position.
*/
setSize: function (width, height, offsetX, offsetY) {
offsetX = offsetX || this.offset.x;
offsetY = offsetY || this.offset.y;
this.sourceWidth = width;
this.sourceHeight = height;
this.width = this.sourceWidth * this._sx;
this.height = this.sourceHeight * this._sy;
this.halfWidth = Math.floor(this.width / 2);
this.halfHeight = Math.floor(this.height / 2);
this.offset.setTo(offsetX, offsetY);
this.center.setTo(this.x + this.halfWidth, this.y + this.halfHeight);
},
/**
* Resets all Body values (velocity, acceleration, rotation, etc)
*
* @method Phaser.Physics.Arcade#reset
*/
reset: function () {
this.velocity.setTo(0, 0);
this.acceleration.setTo(0, 0);
this.angularVelocity = 0;
this.angularAcceleration = 0;
this.preX = (this.sprite.world.x - (this.sprite.anchor.x * this.width)) + this.offset.x;
this.preY = (this.sprite.world.y - (this.sprite.anchor.y * this.height)) + this.offset.y;
this.preRotation = this.sprite.angle;
this.x = this.preX;
this.y = this.preY;
this.rotation = this.preRotation;
this.center.setTo(this.x + this.halfWidth, this.y + this.halfHeight);
},
/**
* Returns the absolute delta x value.
*
* @method Phaser.Physics.Arcade.Body#deltaAbsX
* @return {number} The absolute delta value.
*/
deltaAbsX: function () {
return (this.deltaX() > 0 ? this.deltaX() : -this.deltaX());
},
/**
* Returns the absolute delta y value.
*
* @method Phaser.Physics.Arcade.Body#deltaAbsY
* @return {number} The absolute delta value.
*/
deltaAbsY: function () {
return (this.deltaY() > 0 ? this.deltaY() : -this.deltaY());
},
/**
* Returns the delta x value. The difference between Body.x now and in the previous step.
*
* @method Phaser.Physics.Arcade.Body#deltaX
* @return {number} The delta value. Positive if the motion was to the right, negative if to the left.
*/
deltaX: function () {
return this.position.x - this.prev.x;
},
/**
* Returns the delta y value. The difference between Body.y now and in the previous step.
*
* @method Phaser.Physics.Arcade.Body#deltaY
* @return {number} The delta value. Positive if the motion was downwards, negative if upwards.
*/
deltaY: function () {
return this.position.y - this.prev.y;
},
/**
* Returns the delta z value. The difference between Body.rotation now and in the previous step.
*
* @method Phaser.Physics.Arcade.Body#deltaZ
* @return {number} The delta value. Positive if the motion was clockwise, negative if anti-clockwise.
*/
deltaZ: function () {
return this.rotation - this.preRotation;
}
};
/**
* @name Phaser.Physics.Arcade.Body#bottom
* @property {number} bottom - The bottom value of this Body (same as Body.y + Body.height)
* @readonly
*/
Object.defineProperty(Phaser.Physics.Arcade.Body.prototype, "bottom", {
/**
* The sum of the y and height properties.
* @method bottom
* @return {number}
* @readonly
*/
get: function () {
return this.position.y + this.height;
}
});
/**
* @name Phaser.Physics.Arcade.Body#right
* @property {number} right - The right value of this Body (same as Body.x + Body.width)
* @readonly
*/
Object.defineProperty(Phaser.Physics.Arcade.Body.prototype, "right", {
/**
* The sum of the x and width properties.
* @method right
* @return {number}
* @readonly
*/
get: function () {
return this.position.x + this.width;
}
});
/**
* @name Phaser.Physics.Arcade.Body#x
* @property {number} x - The x position.
*/
Object.defineProperty(Phaser.Physics.Arcade.Body.prototype, "x", {
/**
* The x position.
* @method x
* @return {number}
*/
get: function () {
return this.position.x;
},
/**
* The x position.
* @method x
* @param {number} value
*/
set: function (value) {
this.position.x = value;
}
});
/**
* @name Phaser.Physics.Arcade.Body#y
* @property {number} y - The y position.
*/
Object.defineProperty(Phaser.Physics.Arcade.Body.prototype, "y", {
/**
* The y position.
* @method y
* @return {number}
*/
get: function () {
return this.position.y;
},
/**
* The y position.
* @method y
* @param {number} value
*/
set: function (value) {
this.position.y = value;
}
});
Phaser.Physics.Arcade.Body.prototype.constructor = Phaser.Physics.Arcade.Body;
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2014 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* Phaser.Particles is the Particle Manager for the game. It is called during the game update loop and in turn updates any Emitters attached to it.
*
* @class Phaser.Particles
* @classdesc Phaser Particles
* @constructor
* @param {Phaser.Game} game - A reference to the currently running game.
*/
Phaser.Particles = function (game) {
/**
* @property {Phaser.Game} game - A reference to the currently running Game.
*/
this.game = game;
/**
* @property {object} emitters - Internal emitters store.
*/
this.emitters = {};
/**
* @property {number} ID -
* @default
*/
this.ID = 0;
};
Phaser.Particles.prototype = {
/**
* Adds a new Particle Emitter to the Particle Manager.
* @method Phaser.Particles#add
* @param {Phaser.Emitter} emitter - The emitter to be added to the particle manager.
* @return {Phaser.Emitter} The emitter that was added.
*/
add: function (emitter) {
this.emitters[emitter.name] = emitter;
return emitter;
},
/**
* Removes an existing Particle Emitter from the Particle Manager.
* @method Phaser.Particles#remove
* @param {Phaser.Emitter} emitter - The emitter to remove.
*/
remove: function (emitter) {
delete this.emitters[emitter.name];
},
/**
* Called by the core game loop. Updates all Emitters who have their exists value set to true.
* @method Phaser.Particles#update
* @protected
*/
update: function () {
for (var key in this.emitters)
{
if (this.emitters[key].exists)
{
this.emitters[key].update();
}
}
}
};
Phaser.Particles.prototype.constructor = Phaser.Particles;
Phaser.Particles.Arcade = {}
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2014 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* Phaser - ArcadeEmitter
*
* @class Phaser.Particles.Arcade.Emitter
* @classdesc Emitter is a lightweight particle emitter. It can be used for one-time explosions or for
* continuous effects like rain and fire. All it really does is launch Particle objects out
* at set intervals, and fixes their positions and velocities accorindgly.
* @constructor
* @extends Phaser.Group
* @param {Phaser.Game} game - Current game instance.
* @param {number} [x=0] - The x coordinate within the Emitter that the particles are emitted from.
* @param {number} [y=0] - The y coordinate within the Emitter that the particles are emitted from.
* @param {number} [maxParticles=50] - The total number of particles in this emitter..
*/
Phaser.Particles.Arcade.Emitter = function (game, x, y, maxParticles) {
/**
* @property {number} maxParticles - The total number of particles in this emitter..
* @default
*/
this.maxParticles = maxParticles || 50;
Phaser.Group.call(this, game);
/**
* @property {string} name - Description.
*/
this.name = 'emitter' + this.game.particles.ID++;
/**
* @property {number} type - Internal Phaser Type value.
* @protected
*/
this.type = Phaser.EMITTER;
/**
* @property {number} x - The X position of the top left corner of the emitter in world space.
* @default
*/
this.x = 0;
/**
* @property {number} y - The Y position of the top left corner of emitter in world space.
* @default
*/
this.y = 0;
/**
* @property {number} width - The width of the emitter. Particles can be randomly generated from anywhere within this box.
* @default
*/
this.width = 1;
/**
* @property {number} height - The height of the emitter. Particles can be randomly generated from anywhere within this box.
* @default
*/
this.height = 1;
/**
* @property {Phaser.Point} minParticleSpeed - The minimum possible velocity of a particle.
* @default
*/
this.minParticleSpeed = new Phaser.Point(-100, -100);
/**
* @property {Phaser.Point} maxParticleSpeed - The maximum possible velocity of a particle.
* @default
*/
this.maxParticleSpeed = new Phaser.Point(100, 100);
/**
* @property {number} minParticleScale - The minimum possible scale of a particle.
* @default
*/
this.minParticleScale = 1;
/**
* @property {number} maxParticleScale - The maximum possible scale of a particle.
* @default
*/
this.maxParticleScale = 1;
/**
* @property {number} minRotation - The minimum possible angular velocity of a particle.
* @default
*/
this.minRotation = -360;
/**
* @property {number} maxRotation - The maximum possible angular velocity of a particle.
* @default
*/
this.maxRotation = 360;
/**
* @property {number} gravity - Sets the `body.gravity.y` of each particle sprite to this value on launch.
* @default
*/
this.gravity = 100;
/**
* @property {any} particleClass - For emitting your own particle class types.
* @default
*/
this.particleClass = null;
/**
* @property {number} particleFriction - The friction component of particles launched from the emitter.
* @default
*/
this.particleFriction = 0;
/**
* @property {number} angularDrag - The angular drag component of particles launched from the emitter if they are rotating.
* @default
*/
this.angularDrag = 0;
/**
* @property {boolean} frequency - How often a particle is emitted in ms (if emitter is started with Explode === false).
* @default
*/
this.frequency = 100;
/**
* @property {number} lifespan - How long each particle lives once it is emitted in ms. Default is 2 seconds. Set lifespan to 'zero' for particles to live forever.
* @default
*/
this.lifespan = 2000;
/**
* @property {Phaser.Point} bounce - How much each particle should bounce on each axis. 1 = full bounce, 0 = no bounce.
*/
this.bounce = new Phaser.Point();
/**
* @property {number} _quantity - Internal helper for deciding how many particles to launch.
* @private
*/
this._quantity = 0;
/**
* @property {number} _timer - Internal helper for deciding when to launch particles or kill them.
* @private
*/
this._timer = 0;
/**
* @property {number} _counter - Internal counter for figuring out how many particles to launch.
* @private
*/
this._counter = 0;
/**
* @property {boolean} _explode - Internal helper for the style of particle emission (all at once, or one at a time).
* @private
*/
this._explode = true;
/**
* @property {boolean} on - Determines whether the emitter is currently emitting particles. It is totally safe to directly toggle this.
* @default
*/
this.on = false;
/**
* @property {boolean} exists - Determines whether the emitter is being updated by the core game loop.
* @default
*/
this.exists = true;
/**
* The point the particles are emitted from.
* Emitter.x and Emitter.y control the containers location, which updates all current particles
* Emitter.emitX and Emitter.emitY control the emission location relative to the x/y position.
* @property {boolean} emitX
*/
this.emitX = x;
/**
* The point the particles are emitted from.
* Emitter.x and Emitter.y control the containers location, which updates all current particles
* Emitter.emitX and Emitter.emitY control the emission location relative to the x/y position.
* @property {boolean} emitY
*/
this.emitY = y;
};
Phaser.Particles.Arcade.Emitter.prototype = Object.create(Phaser.Group.prototype);
Phaser.Particles.Arcade.Emitter.prototype.constructor = Phaser.Particles.Arcade.Emitter;
/**
* Called automatically by the game loop, decides when to launch particles and when to "die".
* @method Phaser.Particles.Arcade.Emitter#update
*/
Phaser.Particles.Arcade.Emitter.prototype.update = function () {
if (this.on)
{
if (this._explode)
{
this._counter = 0;
do
{
this.emitParticle();
this._counter++;
}
while (this._counter < this._quantity);
this.on = false;
}
else
{
if (this.game.time.now >= this._timer)
{
this.emitParticle();
this._counter++;
if (this._quantity > 0)
{
if (this._counter >= this._quantity)
{
this.on = false;
}
}
this._timer = this.game.time.now + this.frequency;
}
}
}
}
/**
* This function generates a new array of particle sprites to attach to the emitter.
*
* @method Phaser.Particles.Arcade.Emitter#makeParticles
* @param {array|string} keys - A string or an array of strings that the particle sprites will use as their texture. If an array one is picked at random.
* @param {array|number} frames - A frame number, or array of frames that the sprite will use. If an array one is picked at random.
* @param {number} quantity - The number of particles to generate.
* @param {boolean} [collide=false] - Sets the checkCollision.none flag on the particle sprites body.
* @param {boolean} [collideWorldBounds=false] - A particle can be set to collide against the World bounds automatically and rebound back into the World if this is set to true. Otherwise it will leave the World.
* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance.
*/
Phaser.Particles.Arcade.Emitter.prototype.makeParticles = function (keys, frames, quantity, collide, collideWorldBounds) {
if (typeof frames === 'undefined') { frames = 0; }
if (typeof quantity === 'undefined') { quantity = this.maxParticles; }
if (typeof collide === 'undefined') { collide = false; }
if (typeof collideWorldBounds === 'undefined') { collideWorldBounds = false; }
var particle;
var i = 0;
var rndKey = keys;
var rndFrame = frames;
while (i < quantity)
{
if (this.particleClass === null)
{
if (typeof keys === 'object')
{
rndKey = this.game.rnd.pick(keys);
}
if (typeof frames === 'object')
{
rndFrame = this.game.rnd.pick(frames);
}
particle = new Phaser.Sprite(this.game, 0, 0, rndKey, rndFrame);
}
// else
// {
// particle = new this.particleClass(this.game);
// }
if (collide)
{
particle.body.checkCollision.any = true;
particle.body.checkCollision.none = false;
}
else
{
particle.body.checkCollision.none = true;
}
particle.body.collideWorldBounds = collideWorldBounds;
particle.exists = false;
particle.visible = false;
// Center the origin for rotation assistance
particle.anchor.setTo(0.5, 0.5);
this.add(particle);
i++;
}
return this;
}
/**
* Call this function to turn off all the particles and the emitter.
* @method Phaser.Particles.Arcade.Emitter#kill
*/
Phaser.Particles.Arcade.Emitter.prototype.kill = function () {
this.on = false;
this.alive = false;
this.exists = false;
}
/**
* Handy for bringing game objects "back to life". Just sets alive and exists back to true.
* @method Phaser.Particles.Arcade.Emitter#revive
*/
Phaser.Particles.Arcade.Emitter.prototype.revive = function () {
this.alive = true;
this.exists = true;
}
/**
* Call this function to start emitting particles.
* @method Phaser.Particles.Arcade.Emitter#start
* @param {boolean} [explode=true] - Whether the particles should all burst out at once.
* @param {number} [lifespan=0] - How long each particle lives once emitted. 0 = forever.
* @param {number} [frequency=250] - Ignored if Explode is set to true. Frequency is how often to emit a particle in ms.
* @param {number} [quantity=0] - How many particles to launch. 0 = "all of the particles".
*/
Phaser.Particles.Arcade.Emitter.prototype.start = function (explode, lifespan, frequency, quantity) {
if (typeof explode === 'undefined') { explode = true; }
if (typeof lifespan === 'undefined') { lifespan = 0; }
if (typeof frequency === 'undefined') { frequency = 250; }
if (typeof quantity === 'undefined') { quantity = 0; }
this.revive();
this.visible = true;
this.on = true;
this._explode = explode;
this.lifespan = lifespan;
this.frequency = frequency;
if (explode)
{
this._quantity = quantity;
}
else
{
this._quantity += quantity;
}
this._counter = 0;
this._timer = this.game.time.now + frequency;
}
/**
* This function can be used both internally and externally to emit the next particle.
* @method Phaser.Particles.Arcade.Emitter#emitParticle
*/
Phaser.Particles.Arcade.Emitter.prototype.emitParticle = function () {
var particle = this.getFirstExists(false);
if (particle == null)
{
return;
}
if (this.width > 1 || this.height > 1)
{
particle.reset(this.game.rnd.integerInRange(this.left, this.right), this.game.rnd.integerInRange(this.top, this.bottom));
}
else
{
particle.reset(this.emitX, this.emitY);
}
particle.lifespan = this.lifespan;
particle.body.bounce.setTo(this.bounce.x, this.bounce.y);
if (this.minParticleSpeed.x != this.maxParticleSpeed.x)
{
particle.body.velocity.x = this.game.rnd.integerInRange(this.minParticleSpeed.x, this.maxParticleSpeed.x);
}
else
{
particle.body.velocity.x = this.minParticleSpeed.x;
}
if (this.minParticleSpeed.y != this.maxParticleSpeed.y)
{
particle.body.velocity.y = this.game.rnd.integerInRange(this.minParticleSpeed.y, this.maxParticleSpeed.y);
}
else
{
particle.body.velocity.y = this.minParticleSpeed.y;
}
particle.body.gravity.y = this.gravity;
if (this.minRotation != this.maxRotation)
{
particle.body.angularVelocity = this.game.rnd.integerInRange(this.minRotation, this.maxRotation);
}
else
{
particle.body.angularVelocity = this.minRotation;
}
if (this.minParticleScale !== 1 || this.maxParticleScale !== 1)
{
var scale = this.game.rnd.realInRange(this.minParticleScale, this.maxParticleScale);
particle.scale.setTo(scale, scale);
}
particle.body.friction = this.particleFriction;
particle.body.angularDrag = this.angularDrag;
}
/**
* A more compact way of setting the width and height of the emitter.
* @method Phaser.Particles.Arcade.Emitter#setSize
* @param {number} width - The desired width of the emitter (particles are spawned randomly within these dimensions).
* @param {number} height - The desired height of the emitter.
*/
Phaser.Particles.Arcade.Emitter.prototype.setSize = function (width, height) {
this.width = width;
this.height = height;
}
/**
* A more compact way of setting the X velocity range of the emitter.
* @method Phaser.Particles.Arcade.Emitter#setXSpeed
* @param {number} [min=0] - The minimum value for this range.
* @param {number} [max=0] - The maximum value for this range.
*/
Phaser.Particles.Arcade.Emitter.prototype.setXSpeed = function (min, max) {
min = min || 0;
max = max || 0;
this.minParticleSpeed.x = min;
this.maxParticleSpeed.x = max;
}
/**
* A more compact way of setting the Y velocity range of the emitter.
* @method Phaser.Particles.Arcade.Emitter#setYSpeed
* @param {number} [min=0] - The minimum value for this range.
* @param {number} [max=0] - The maximum value for this range.
*/
Phaser.Particles.Arcade.Emitter.prototype.setYSpeed = function (min, max) {
min = min || 0;
max = max || 0;
this.minParticleSpeed.y = min;
this.maxParticleSpeed.y = max;
}
/**
* A more compact way of setting the angular velocity constraints of the emitter.
* @method Phaser.Particles.Arcade.Emitter#setRotation
* @param {number} [min=0] - The minimum value for this range.
* @param {number} [max=0] - The maximum value for this range.
*/
Phaser.Particles.Arcade.Emitter.prototype.setRotation = function (min, max) {
min = min || 0;
max = max || 0;
this.minRotation = min;
this.maxRotation = max;
}
/**
* Change the emitters center to match the center of any object with a `center` property, such as a Sprite.
* @method Phaser.Particles.Arcade.Emitter#at
* @param {object|Phaser.Sprite} object - The object that you wish to match the center with.
*/
Phaser.Particles.Arcade.Emitter.prototype.at = function (object) {
if (object.center)
{
this.emitX = object.center.x;
this.emitY = object.center.y;
}
}
/**
* The emitters alpha value.
* @name Phaser.Particles.Arcade.Emitter#alpha
* @property {number} alpha - Gets or sets the alpha value of the Emitter.
Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "alpha", {
get: function () {
return this._container.alpha;
},
set: function (value) {
this._container.alpha = value;
}
});
*/
/**
* The emitter visible state.
* @name Phaser.Particles.Arcade.Emitter#visible
* @property {boolean} visible - Gets or sets the Emitter visible state.
Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "visible", {
get: function () {
return this._container.visible;
},
set: function (value) {
this._container.visible = value;
}
});
*/
/**
* @name Phaser.Particles.Arcade.Emitter#x
* @property {number} x - Gets or sets the x position of the Emitter.
*/
Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "x", {
get: function () {
return this.emitX;
},
set: function (value) {
this.emitX = value;
}
});
/**
* @name Phaser.Particles.Arcade.Emitter#y
* @property {number} y - Gets or sets the y position of the Emitter.
*/
Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "y", {
get: function () {
return this.emitY;
},
set: function (value) {
this.emitY = value;
}
});
/**
* @name Phaser.Particles.Arcade.Emitter#left
* @property {number} left - Gets the left position of the Emitter.
* @readonly
*/
Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "left", {
get: function () {
return Math.floor(this.x - (this.width / 2));
}
});
/**
* @name Phaser.Particles.Arcade.Emitter#right
* @property {number} right - Gets the right position of the Emitter.
* @readonly
*/
Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "right", {
get: function () {
return Math.floor(this.x + (this.width / 2));
}
});
/**
* @name Phaser.Particles.Arcade.Emitter#top
* @property {number} top - Gets the top position of the Emitter.
* @readonly
*/
Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "top", {
get: function () {
return Math.floor(this.y - (this.height / 2));
}
});
/**
* @name Phaser.Particles.Arcade.Emitter#bottom
* @property {number} bottom - Gets the bottom position of the Emitter.
* @readonly
*/
Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "bottom", {
get: function () {
return Math.floor(this.y + (this.height / 2));
}
});
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2014 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* Create a new `Tile` object.
*
* @class Phaser.Tile
* @classdesc A Tile is a representation of a single tile within the Tilemap.
* @constructor
* @param {object} layer - The layer in the Tilemap data that this tile belongs to.
* @param {number} index - The index of this tile type in the core map data.
* @param {number} x - The x coordinate of this tile.
* @param {number} y - The y coordinate of this tile.
* @param {number} width - Width of the tile.
* @param {number} height - Height of the tile.
*/
Phaser.Tile = function (layer, index, x, y, width, height) {
/**
* @property {object} layer - The layer in the Tilemap data that this tile belongs to.
*/
this.layer = layer;
/**
* @property {number} index - The index of this tile within the map data corresponding to the tileset.
*/
this.index = index;
/**
* @property {number} x - The x map coordinate of this tile.
*/
this.x = x;
/**
* @property {number} y - The y map coordinate of this tile.
*/
this.y = y;
/**
* @property {number} x - The x map coordinate of this tile.
*/
this.worldX = x * width;
/**
* @property {number} y - The y map coordinate of this tile.
*/
this.worldY = y * height;
/**
* @property {number} width - The width of the tile in pixels.
*/
this.width = width;
/**
* @property {number} height - The height of the tile in pixels.
*/
this.height = height;
/**
* @property {number} width - The width of the tile in pixels.
*/
this.centerX = Math.abs(width / 2);
/**
* @property {number} height - The height of the tile in pixels.
*/
this.centerY = Math.abs(height / 2);
/**
* @property {number} alpha - The alpha value at which this tile is drawn to the canvas.
*/
this.alpha = 1;
/**
* @property {object} properties - Tile specific properties.
*/
this.properties = {};
/**
* @property {boolean} scanned - Has this tile been walked / turned into a poly?
*/
this.scanned = false;
/**
* @property {boolean} faceTop - Is the top of this tile an interesting edge?
*/
this.faceTop = false;
/**
* @property {boolean} faceBottom - Is the bottom of this tile an interesting edge?
*/
this.faceBottom = false;
/**
* @property {boolean} faceLeft - Is the left of this tile an interesting edge?
*/
this.faceLeft = false;
/**
* @property {boolean} faceRight - Is the right of this tile an interesting edge?
*/
this.faceRight = false;
/**
* @property {boolean} collides - Does this tile collide at all?
*/
this.collides = false;
/**
* @property {boolean} collideNone - Indicating this Tile doesn't collide at all.
* @default
*/
this.collideNone = true;
/**
* @property {boolean} collideLeft - Indicating collide with any object on the left.
* @default
*/
this.collideLeft = false;
/**
* @property {boolean} collideRight - Indicating collide with any object on the right.
* @default
*/
this.collideRight = false;
/**
* @property {boolean} collideUp - Indicating collide with any object on the top.
* @default
*/
this.collideUp = false;
/**
* @property {boolean} collideDown - Indicating collide with any object on the bottom.
* @default
*/
this.collideDown = false;
/**
* @property {function} collisionCallback - Tile collision callback.
* @default
*/
this.collisionCallback = null;
/**
* @property {object} collisionCallbackContext - The context in which the collision callback will be called.
* @default
*/
this.collisionCallbackContext = this;
};
Phaser.Tile.prototype = {
intersects: function (x, y, right, bottom) {
if (right <= this.worldX)
{
return false;
}
if (bottom <= this.worldY)
{
return false;
}
if (x >= this.worldX + this.width)
{
return false;
}
if (y >= this.worldY + this.height)
{
return false;
}
return true;
},
/**
* Set a callback to be called when this tile is hit by an object.
* The callback must true true for collision processing to take place.
*
* @method Phaser.Tile#setCollisionCallback
* @param {function} callback - Callback function.
* @param {object} context - Callback will be called within this context.
*/
setCollisionCallback: function (callback, context) {
this.collisionCallback = callback;
this.collisionCallbackContext = context;
},
/**
* Clean up memory.
* @method Phaser.Tile#destroy
*/
destroy: function () {
this.collisionCallback = null;
this.collisionCallbackContext = null;
this.properties = null;
},
/**
* Set collision settings on this tile.
* @method Phaser.Tile#setCollision
* @param {boolean} left - Indicating collide with any object on the left.
* @param {boolean} right - Indicating collide with any object on the right.
* @param {boolean} up - Indicating collide with any object on the top.
* @param {boolean} down - Indicating collide with any object on the bottom.
*/
setCollision: function (left, right, up, down) {
this.collideLeft = left;
this.collideRight = right;
this.collideUp = up;
this.collideDown = down;
if (left || right || up || down)
{
this.collides = true;
this.collideNone = false;
}
else
{
this.collides = false;
this.collideNone = true;
}
},
/**
* Reset collision status flags.
* @method Phaser.Tile#resetCollision
*/
resetCollision: function () {
this.collideNone = true;
this.collideLeft = false;
this.collideRight = false;
this.collideUp = false;
this.collideDown = false;
this.collides = false;
this.faceTop = false;
this.faceBottom = false;
this.faceLeft = false;
this.faceRight = false;
},
/**
* Copies the tile data and properties from the given tile to this tile.
* @method Phaser.Tile#copy
* @param {Phaser.Tile} tile - The tile to copy from.
*/
copy: function (tile) {
this.index = tile.index;
this.alpha = tile.alpha;
this.properties = tile.properties;
this.collides = tile.collides;
this.collideNone = tile.collideNone;
this.collideUp = tile.collideUp;
this.collideDown = tile.collideDown;
this.collideLeft = tile.collideLeft;
this.collideRight = tile.collideRight;
this.collisionCallback = tile.collisionCallback;
this.collisionCallbackContext = tile.collisionCallbackContext;
}
};
Phaser.Tile.prototype.constructor = Phaser.Tile;
/**
* @name Phaser.Tile#canCollide
* @property {boolean} canCollide - True if this tile can collide or has a collision callback.
* @readonly
*/
Object.defineProperty(Phaser.Tile.prototype, "canCollide", {
get: function () {
return (this.collides || this.collisionCallback || this.layer.callbacks[this.index]);
}
});
/**
* @name Phaser.Tile#left
* @property {number} left - The x value.
* @readonly
*/
Object.defineProperty(Phaser.Tile.prototype, "left", {
get: function () {
return this.x;
}
});
/**
* @name Phaser.Tile#right
* @property {number} right - The sum of the x and width properties.
* @readonly
*/
Object.defineProperty(Phaser.Tile.prototype, "right", {
get: function () {
return this.x + this.width;
}
});
/**
* @name Phaser.Tile#top
* @property {number} top - The y value.
* @readonly
*/
Object.defineProperty(Phaser.Tile.prototype, "top", {
get: function () {
return this.y;
}
});
/**
* @name Phaser.Tile#bottom
* @property {number} bottom - The sum of the y and height properties.
* @readonly
*/
Object.defineProperty(Phaser.Tile.prototype, "bottom", {
get: function () {
return this.y + this.height;
}
});
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2014 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* Creates a new Phaser.Tilemap object. The map can either be populated with data from a Tiled JSON file or from a CSV file.
* To do this pass the Cache key as the first parameter. When using Tiled data you need only provide the key.
* When using CSV data you must provide the key and the tileWidth and tileHeight parameters.
* If creating a blank tilemap to be populated later, you can either specify no parameters at all and then use `Tilemap.create` or pass the map and tile dimensions here.
* Note that all Tilemaps use a base tile size to calculate dimensions from, but that a TilemapLayer may have its own unique tile size that overrides it.
* A Tile map is rendered to the display using a TilemapLayer. It is not added to the display list directly itself.
* A map may have multiple layers. You can perform operations on the map data such as copying, pasting, filling and shuffling the tiles around.
*
* @class Phaser.Tilemap
* @constructor
* @param {Phaser.Game} game - Game reference to the currently running game.
* @param {string} [key] - The key of the tilemap data as stored in the Cache. If you're creating a blank map either leave this parameter out or pass `null`.
* @param {number} [tileWidth=32] - The pixel width of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data.
* @param {number} [tileHeight=32] - The pixel height of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data.
* @param {number} [width=10] - The width of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this.
* @param {number} [height=10] - The height of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this.
*/
Phaser.Tilemap = function (game, key, tileWidth, tileHeight, width, height) {
/**
* @property {Phaser.Game} game - A reference to the currently running Game.
*/
this.game = game;
/**
* @property {string} key - The key of this map data in the Phaser.Cache.
*/
this.key = key;
var data = Phaser.TilemapParser.parse(this.game, key, tileWidth, tileHeight, width, height);
if (data === null)
{
return;
}
/**
* @property {number} width - The width of the map (in tiles).
*/
this.width = data.width;
/**
* @property {number} height - The height of the map (in tiles).
*/
this.height = data.height;
/**
* @property {number} tileWidth - The base width of the tiles in the map (in pixels).
*/
this.tileWidth = data.tileWidth;
/**
* @property {number} tileHeight - The base height of the tiles in the map (in pixels).
*/
this.tileHeight = data.tileHeight;
/**
* @property {string} orientation - The orientation of the map data (as specified in Tiled), usually 'orthogonal'.
*/
this.orientation = data.orientation;
/**
* @property {number} version - The version of the map data (as specified in Tiled, usually 1).
*/
this.version = data.version;
/**
* @property {object} properties - Map specific properties as specified in Tiled.
*/
this.properties = data.properties;
/**
* @property {number} widthInPixels - The width of the map in pixels based on width * tileWidth.
*/
this.widthInPixels = data.widthInPixels;
/**
* @property {number} heightInPixels - The height of the map in pixels based on height * tileHeight.
*/
this.heightInPixels = data.heightInPixels;
/**
* @property {array} layers - An array of Tilemap layer data.
*/
this.layers = data.layers;
/**
* @property {array} tilesets - An array of Tilesets.
*/
this.tilesets = data.tilesets;
/**
* @property {array} tiles - The super array of Tiles.
*/
this.tiles = data.tiles;
/**
* @property {array} objects - An array of Tiled Object Layers.
*/
this.objects = data.objects;
/**
* @property {array} collideIndexes - An array of tile indexes that collide.
*/
this.collideIndexes = [];
/**
* @property {array} collision - An array of collision data (polylines, etc).
*/
this.collision = data.collision;
/**
* @property {array} images - An array of Tiled Image Layers.
*/
this.images = data.images;
/**
* @property {number} currentLayer - The current layer.
*/
this.currentLayer = 0;
/**
* @property {array} debugMap - Map data used for debug values only.
*/
this.debugMap = [];
/**
* @property {array} _results - Internal var.
* @private
*/
this._results = [];
/**
* @property {number} _tempA - Internal var.
* @private
*/
this._tempA = 0;
/**
* @property {number} _tempB - Internal var.
* @private
*/
this._tempB = 0;
};
/**
* @constant
* @type {number}
*/
Phaser.Tilemap.CSV = 0;
/**
* @constant
* @type {number}
*/
Phaser.Tilemap.TILED_JSON = 1;
Phaser.Tilemap.prototype = {
/**
* Creates an empty map of the given dimensions.
*
* @method Phaser.Tilemap#create
* @param {string} name - The name of the default layer of the map
* @param {number} width - The width of the map in tiles.
* @param {number} height - The height of the map in tiles.
* @param {number} tileWidth - The width of the tiles the map uses for calculations.
* @param {number} tileHeight - The height of the tiles the map uses for calculations.
*/
create: function (name, width, height, tileWidth, tileHeight) {
this.width = width;
this.height = height;
this.setTileSize(tileWidth, tileHeight);
var row;
var output = [];
for (var y = 0; y < height; y++)
{
row = [];
for (var x = 0; x < width; x++)
{
row.push(null);
}
output.push(row);
}
this.layers.push({
name: name,
x: 0,
y: 0,
width: width,
height: height,
widthInPixels: this.widthInPixels,
heightInPixels: this.heightInPixels,
alpha: 1,
visible: true,
properties: {},
indexes: [],
callbacks: [],
bodies: [],
data: output
});
this.currentLayer = this.layers.length - 1;
},
/**
* Sets the base tile size for the map.
*
* @method Phaser.Tilemap#setTileSize
* @param {number} tileWidth - The width of the tiles the map uses for calculations.
* @param {number} tileHeight - The height of the tiles the map uses for calculations.
*/
setTileSize: function (tileWidth, tileHeight) {
this.tileWidth = tileWidth;
this.tileHeight = tileHeight;
this.widthInPixels = this.width * tileWidth;
this.heightInPixels = this.height * tileHeight;
},
/**
* Adds an image to the map to be used as a tileset. A single map may use multiple tilesets.
* Note that the tileset name can be found in the JSON file exported from Tiled, or in the Tiled editor.
*
* @method Phaser.Tilemap#addTilesetImage
* @param {string} tileset - The name of the tileset as specified in the map data.
* @param {string} [key] - The key of the Phaser.Cache image used for this tileset. If not specified it will look for an image with a key matching the tileset parameter.
* @param {number} [tileWidth] - The width of the tiles in the Tileset Image. If not given it will default to the map.tileWidth value.
* @param {number} [tileHeight] - The height of the tiles in the Tileset Image. If not given it will default to the map.tileHeight value.
* @param {number} [tileMargin=0] - The width of the tiles in the Tileset Image. If not given it will default to the map.tileWidth value.
* @param {number} [tileSpacing=0] - The height of the tiles in the Tileset Image. If not given it will default to the map.tileHeight value.
*/
addTilesetImage: function (tileset, key, tileWidth, tileHeight, tileMargin, tileSpacing) {
if (typeof tileWidth === 'undefined') { tileWidth = this.tileWidth; }
if (typeof tileHeight === 'undefined') { tileHeight = this.tileHeight; }
if (typeof tileMargin === 'undefined') { tileMargin = 0; }
if (typeof tileSpacing === 'undefined') { tileSpacing = 0; }
if (typeof key === 'undefined')
{
if (typeof tileset === 'string')
{
key = tileset;
}
else
{
return false;
}
}
if (typeof tileset === 'string')
{
tileset = this.getTilesetIndex(tileset);
}
if (this.tilesets[tileset])
{
this.tilesets[tileset].setImage(this.game.cache.getImage(key));
return true;
}
else
{
var newSet = new Phaser.Tileset(key, 0, tileWidth, tileHeight, tileMargin, tileSpacing, {});
newSet.setImage(this.game.cache.getImage(key));
this.tilesets.push(newSet);
}
return false;
},
/*
createFromTiles: function (layer, tileIndex, key, frame, group) {
if (typeof group === 'undefined') { group = this.game.world; }
},
*/
/**
* Creates a Sprite for every object matching the given gid in the map data. You can optionally specify the group that the Sprite will be created in. If none is
* given it will be created in the World. All properties from the map data objectgroup are copied across to the Sprite, so you can use this as an easy way to
* configure Sprite properties from within the map editor. For example giving an object a property if alpha: 0.5 in the map editor will duplicate that when the
* Sprite is created. You could also give it a value like: body.velocity.x: 100 to set it moving automatically.
*
* @method Phaser.Tilemap#createFromObjects
* @param {string} name - The name of the Object Group to create Sprites from.
* @param {number} gid - The layer array index value, or if a string is given the layer name, within the map data that this TilemapLayer represents.
* @param {string} key - The Game.cache key of the image that this Sprite will use.
* @param {number|string} [frame] - If the Sprite image contains multiple frames you can specify which one to use here.
* @param {boolean} [exists=true] - The default exists state of the Sprite.
* @param {boolean} [autoCull=false] - The default autoCull state of the Sprite. Sprites that are autoCulled are culled from the camera if out of its range.
* @param {Phaser.Group} [group=Phaser.World] - Group to add the Sprite to. If not specified it will be added to the World group.
* @param {object} [objectClass=Phaser.Sprite] - If you wish to create your own class, rather than Phaser.Sprite, pass the class here. Your class must extend Phaser.Sprite and have the same constructor parameters.
*/
createFromObjects: function (name, gid, key, frame, exists, autoCull, group, objectClass) {
if (typeof exists === 'undefined') { exists = true; }
if (typeof autoCull === 'undefined') { autoCull = false; }
if (typeof group === 'undefined') { group = this.game.world; }
if (typeof objectClass === 'undefined') { objectClass = Phaser.Sprite; }
if (!this.objects[name])
{
console.warn('Tilemap.createFromObjects: Invalid objectgroup name given: ' + name);
return;
}
var sprite;
for (var i = 0, len = this.objects[name].length; i < len; i++)
{
if (this.objects[name][i].gid === gid)
{
sprite = new objectClass(this.game, this.objects[name][i].x, this.objects[name][i].y, key, frame);
sprite.anchor.setTo(0, 1);
sprite.name = this.objects[name][i].name;
sprite.visible = this.objects[name][i].visible;
sprite.autoCull = autoCull;
sprite.exists = exists;
group.add(sprite);
for (property in this.objects[name][i].properties)
{
group.set(sprite, property, this.objects[name][i].properties[property], false, false, 0);
}
}
}
},
/**
* Clears all physics bodies from the world for the given layer.
*
* @method Phaser.Tilemap#clearPhysicsBodies
* @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to this.currentLayer.
*/
clearPhysicsBodies: function (layer) {
layer = this.getLayer(layer);
var i = this.layers[layer].bodies.length;
while (i--)
{
this.layers[layer].bodies[i].destroy();
}
},
/**
* Goes through all tiles in the given layer and converts those set to collide into physics bodies in the world.
* 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 an expensive operation and not to be done in a core game update loop.
*
* @method Phaser.Tilemap#generateCollisionData
* @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to this.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.
* @return {array} An array of the Phaser.Physics.Body objects that have been created.
*/
generateCollisionData: function (layer, addToWorld) {
layer = this.getLayer(layer);
if (typeof addToWorld === 'undefined') { addToWorld = true; }
// If the bodies array is already populated we need to nuke it
if (this.layers[layer].bodies.length > 0)
{
this.clearPhysicsBodies(layer);
}
this.layers[layer].bodies.length = [];
var width = 0;
var sx = 0;
var sy = 0;
for (var y = 0, h = this.layers[layer].height; y < h; y++)
{
width = 0;
for (var x = 0, w = this.layers[layer].width; x < w; x++)
{
var tile = this.layers[layer].data[y][x];
if (tile)
{
right = this.getTileRight(layer, x, y);
if (width === 0)
{
sx = tile.x * tile.width;
sy = tile.y * tile.height;
width = tile.width;
}
if (right && right.collides)
{
width += tile.width;
}
else
{
var body = this.game.physics.createBody(sx, sy, 0, false);
body.addRectangle(width, tile.height, width / 2, tile.height / 2, 0);
if (addToWorld)
{
this.game.physics.addBody(body);
}
this.layers[layer].bodies.push(body);
width = 0;
}
}
}
}
return this.layers[layer].bodies;
},
/**
* Converts all of the polylines 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.
*
* @method Phaser.Tilemap#createCollisionObjects
* @param {string} [layer] - The Tiled layer to operate on that contains the collision data.
* @param {boolean} [addToWorld=true] - If true it will automatically add each body to the world.
* @return {array} An array of the Phaser.Physics.Body objects that have been created.
*/
createCollisionObjects: function (layer, addToWorld) {
if (typeof addToWorld === 'undefined') { addToWorld = true; }
var output = [];
for (var i = 0, len = this.collision[layer].length; i < len; i++)
{
// name: json.layers[i].objects[v].name,
// x: json.layers[i].objects[v].x,
// y: json.layers[i].objects[v].y,
// width: json.layers[i].objects[v].width,
// height: json.layers[i].objects[v].height,
// visible: json.layers[i].objects[v].visible,
// properties: json.layers[i].objects[v].properties,
// polyline: json.layers[i].objects[v].polyline
var object = this.collision[layer][i];
var body = this.game.physics.createBody(object.x, object.y, 0, addToWorld, {}, object.polyline);
if (body)
{
output.push(body);
}
}
return output;
},
/**
* Creates a new TilemapLayer object. By default TilemapLayers are fixed to the camera.
* The `layer` parameter is important. If you've created your map in Tiled then you can get this by looking in Tiled and looking at the Layer name.
* Or you can open the JSON file it exports and look at the layers[].name value. Either way it must match.
*
* @method Phaser.Tilemap#createLayer
* @param {number|string} layer - The layer array index value, or if a string is given the layer name, within the map data that this TilemapLayer represents.
* @param {number} [width] - The rendered width of the layer, should never be wider than Game.width. If not given it will be set to Game.width.
* @param {number} [height] - The rendered height of the layer, should never be wider than Game.height. If not given it will be set to Game.height.
* @param {Phaser.Group} [group] - Optional Group to add the object to. If not specified it will be added to the World group.
* @return {Phaser.TilemapLayer} The TilemapLayer object. This is an extension of Phaser.Sprite and can be moved around the display list accordingly.
*/
createLayer: function (layer, width, height, group) {
// Add Buffer support for the left of the canvas
if (typeof width === 'undefined') { width = this.game.width; }
if (typeof height === 'undefined') { height = this.game.height; }
if (typeof group === 'undefined') { group = this.game.world; }
var index = layer;
if (typeof layer === 'string')
{
index = this.getLayerIndex(layer);
}
if (index === null || index > this.layers.length)
{
console.warn('Tilemap.createLayer: Invalid layer ID given: ' + index);
return;
}
return group.add(new Phaser.TilemapLayer(this.game, this, index, width, height));
},
/**
* Gets the layer index based on the layers name.
*
* @method Phaser.Tilemap#getIndex
* @protected
* @param {array} location - The local array to search.
* @param {string} name - The name of the array element to get.
* @return {number} The index of the element in the array, or null if not found.
*/
getIndex: function (location, name) {
for (var i = 0; i < location.length; i++)
{
if (location[i].name === name)
{
return i;
}
}
return null;
},
/**
* Gets the layer index based on its name.
*
* @method Phaser.Tilemap#getLayerIndex
* @param {string} name - The name of the layer to get.
* @return {number} The index of the layer in this tilemap, or null if not found.
*/
getLayerIndex: function (name) {
return this.getIndex(this.layers, name);
},
/**
* Gets the tileset index based on its name.
*
* @method Phaser.Tilemap#getTilesetIndex
* @param {string} name - The name of the tileset to get.
* @return {number} The index of the tileset in this tilemap, or null if not found.
*/
getTilesetIndex: function (name) {
return this.getIndex(this.tilesets, name);
},
/**
* Gets the image index based on its name.
*
* @method Phaser.Tilemap#getImageIndex
* @param {string} name - The name of the image to get.
* @return {number} The index of the image in this tilemap, or null if not found.
*/
getImageIndex: function (name) {
return this.getIndex(this.images, name);
},
/**
* Gets the object index based on its name.
*
* @method Phaser.Tilemap#getObjectIndex
* @param {string} name - The name of the object to get.
* @return {number} The index of the object in this tilemap, or null if not found.
*/
getObjectIndex: function (name) {
return this.getIndex(this.objects, name);
},
/**
* Sets a global collision callback for the given tile index within the layer. This will affect all tiles on this layer that have the same index.
* If a callback is already set for the tile index it will be replaced. Set the callback to null to remove it.
* If you want to set a callback for a tile at a specific location on the map then see setTileLocationCallback.
*
* @method Phaser.Tilemap#setTileIndexCallback
* @param {number|array} indexes - Either a single tile index, or an array of tile indexes to have a collision callback set for.
* @param {function} callback - The callback that will be invoked when the tile is collided with.
* @param {object} callbackContext - The context under which the callback is called.
* @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to this.currentLayer.
*/
setTileIndexCallback: function (indexes, callback, callbackContext, layer) {
layer = this.getLayer(layer);
if (typeof indexes === 'number')
{
// This may seem a bit wasteful, because it will cause empty array elements to be created, but the look-up cost is much
// less than having to iterate through the callbacks array hunting down tile indexes each time, so I'll take the small memory hit.
this.layers[layer].callbacks[indexes] = { callback: callback, callbackContext: callbackContext };
}
else
{
for (var i = 0, len = indexes.length; i < len; i++)
{
this.layers[layer].callbacks[indexes[i]] = { callback: callback, callbackContext: callbackContext };
}
}
},
/**
* Sets a global collision callback for the given tile index within the layer. This will affect all tiles on this layer that have the same index.
* If a callback is already set for the tile index it will be replaced. Set the callback to null to remove it.
* If you want to set a callback for a tile at a specific location on the map then see setTileLocationCallback.
*
* @method Phaser.Tilemap#setTileLocationCallback
* @param {number} x - X position of the top left of the area to copy (given in tiles, not pixels)
* @param {number} y - Y position of the top left of the area to copy (given in tiles, not pixels)
* @param {number} width - The width of the area to copy (given in tiles, not pixels)
* @param {number} height - The height of the area to copy (given in tiles, not pixels)
* @param {function} callback - The callback that will be invoked when the tile is collided with.
* @param {object} callbackContext - The context under which the callback is called.
* @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to this.currentLayer.
*/
setTileLocationCallback: function (x, y, width, height, callback, callbackContext, layer) {
layer = this.getLayer(layer);
this.copy(x, y, width, height, layer);
if (this._results.length < 2)
{
return;
}
for (var i = 1; i < this._results.length; i++)
{
this._results[i].setCollisionCallback(callback, callbackContext);
}
},
/**
* Sets collision the given tile or tiles. You can pass in either a single numeric index or an array of indexes: [ 2, 3, 15, 20].
* The `collides` parameter controls if collision will be enabled (true) or disabled (false).
*
* @method Phaser.Tilemap#setCollision
* @param {number|array} indexes - Either a single tile index, or an array of tile IDs to be checked for collision.
* @param {boolean} [collides=true] - If true it will enable collision. If false it will clear collision.
* @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to this.currentLayer.
*/
setCollision: function (indexes, collides, layer) {
if (typeof collides === 'undefined') { collides = true; }
layer = this.getLayer(layer);
if (typeof indexes === 'number')
{
return this.setCollisionByIndex(indexes, collides, layer, true);
}
else
{
// Collide all of the IDs given in the indexes array
for (var i = 0, len = indexes.length; i < len; i++)
{
this.setCollisionByIndex(indexes[i], collides, layer, false);
}
// Now re-calculate interesting faces
this.calculateFaces(layer);
}
},
/**
* Sets collision on a range of tiles where the tile IDs increment sequentially.
* Calling this with a start value of 10 and a stop value of 14 would set collision for tiles 10, 11, 12, 13 and 14.
* The `collides` parameter controls if collision will be enabled (true) or disabled (false).
*
* @method Phaser.Tilemap#setCollisionBetween
* @param {number} start - The first index of the tile to be set for collision.
* @param {number} stop - The last index of the tile to be set for collision.
* @param {boolean} [collides=true] - If true it will enable collision. If false it will clear collision.
* @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to this.currentLayer.
*/
setCollisionBetween: function (start, stop, collides, layer) {
if (typeof collides === 'undefined') { collides = true; }
layer = this.getLayer(layer);
if (start > stop)
{
return;
}
for (var index = start; index <= stop; index++)
{
this.setCollisionByIndex(index, collides, layer, false);
}
// Now re-calculate interesting faces
this.calculateFaces(layer);
},
/**
* Sets collision on all tiles in the given layer, except for the IDs of those in the given array.
* The `collides` parameter controls if collision will be enabled (true) or disabled (false).
*
* @method Phaser.Tilemap#setCollisionByExclusion
* @param {array} indexes - An array of the tile IDs to not be counted for collision.
* @param {boolean} [collides=true] - If true it will enable collision. If false it will clear collision.
* @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to this.currentLayer.
*/
setCollisionByExclusion: function (indexes, collides, layer) {
if (typeof collides === 'undefined') { collides = true; }
layer = this.getLayer(layer);
// Collide everything, except the IDs given in the indexes array
for (var i = 0, len = this.tiles.length; i < len; i++)
{
if (indexes.indexOf(i) === -1)
{
this.setCollisionByIndex(i, collides, layer, false);
}
}
// Now re-calculate interesting faces
this.calculateFaces(layer);
},
/**
* Sets collision values on a tile in the set.
* You shouldn't usually call this method directly, instead use setCollision, setCollisionBetween or setCollisionByExclusion.
*
* @method Phaser.Tilemap#setCollisionByIndex
* @protected
* @param {number} index - The index of the tile on the layer.
* @param {boolean} [collides=true] - If true it will enable collision on the tile. If false it will clear collision values from the tile.
* @param {number} [layer] - The layer to operate on. If not given will default to this.currentLayer.
* @param {boolean} [recalculate=true] - Recalculates the tile faces after the update.
*/
setCollisionByIndex: function (index, collides, layer, recalculate) {
if (typeof collides === 'undefined') { collides = true; }
if (typeof layer === 'undefined') { layer = this.currentLayer; }
if (typeof recalculate === 'undefined') { recalculate = true; }
if (collides)
{
this.collideIndexes.push(index);
}
else
{
var i = this.collideIndexes.indexOf(index);
if (i > -1)
{
this.collideIndexes.splice(i, 1);
}
}
for (var y = 0; y < this.layers[layer].height ; y++)
{
for (var x = 0; x < this.layers[layer].width; x++)
{
var tile = this.layers[layer].data[y][x];
if (tile && tile.index === index)
{
tile.collides = collides;
tile.faceTop = collides;
tile.faceBottom = collides;
tile.faceLeft = collides;
tile.faceRight = collides;
}
}
}
if (recalculate)
{
// Now re-calculate interesting faces
this.calculateFaces(layer);
}
return layer;
},
/**
* Gets the TilemapLayer index as used in the setCollision calls.
*
* @method Phaser.Tilemap#getLayer
* @protected
* @param {number|string|Phaser.TilemapLayer} layer - The layer to operate on. If not given will default to this.currentLayer.
* @return {number} The TilemapLayer index.
*/
getLayer: function (layer) {
if (typeof layer === 'undefined')
{
layer = this.currentLayer;
}
// else if (typeof layer === 'number')
// {
// layer = layer;
// }
else if (typeof layer === 'string')
{
layer = this.getLayerIndex(layer);
}
else if (layer instanceof Phaser.TilemapLayer)
{
layer = layer.index;
}
return layer;
},
/**
* Internal function.
*
* @method Phaser.Tilemap#calculateFaces
* @protected
* @param {number} layer - The index of the TilemapLayer to operate on.
*/
calculateFaces: function (layer) {
var above = null;
var below = null;
var left = null;
var right = null;
for (var y = 0, h = this.layers[layer].height; y < h; y++)
{
for (var x = 0, w = this.layers[layer].width; x < w; x++)
{
var tile = this.layers[layer].data[y][x];
if (tile)
{
above = this.getTileAbove(layer, x, y);
below = this.getTileBelow(layer, x, y);
left = this.getTileLeft(layer, x, y);
right = this.getTileRight(layer, x, y);
if (tile.collides)
{
tile.faceTop = true;
tile.faceBottom = true;
tile.faceLeft = true;
tile.faceRight = true;
}
if (above && above.collides)
{
// There is a tile above this one that also collides, so the top of this tile is no longer interesting
tile.faceTop = false;
}
if (below && below.collides)
{
// There is a tile below this one that also collides, so the bottom of this tile is no longer interesting
tile.faceBottom = false;
}
if (left && left.collides)
{
// There is a tile left this one that also collides, so the left of this tile is no longer interesting
tile.faceLeft = false;
}
if (right && right.collides)
{
// There is a tile right this one that also collides, so the right of this tile is no longer interesting
tile.faceRight = false;
}
}
}
}
},
/**
* Gets the tile above the tile coordinates given.
* Mostly used as an internal function by calculateFaces.
*
* @method Phaser.Tilemap#getTileAbove
* @param {number} layer - The local layer index to get the tile from. Can be determined by Tilemap.getLayer().
* @param {number} x - The x coordinate to get the tile from. In tiles, not pixels.
* @param {number} y - The y coordinate to get the tile from. In tiles, not pixels.
*/
getTileAbove: function (layer, x, y) {
if (y > 0)
{
return this.layers[layer].data[y - 1][x];
}
return null;
},
/**
* Gets the tile below the tile coordinates given.
* Mostly used as an internal function by calculateFaces.
*
* @method Phaser.Tilemap#getTileBelow
* @param {number} layer - The local layer index to get the tile from. Can be determined by Tilemap.getLayer().
* @param {number} x - The x coordinate to get the tile from. In tiles, not pixels.
* @param {number} y - The y coordinate to get the tile from. In tiles, not pixels.
*/
getTileBelow: function (layer, x, y) {
if (y < this.layers[layer].height - 1)
{
return this.layers[layer].data[y + 1][x];
}
return null;
},
/**
* Gets the tile to the left of the tile coordinates given.
* Mostly used as an internal function by calculateFaces.
*
* @method Phaser.Tilemap#getTileLeft
* @param {number} layer - The local layer index to get the tile from. Can be determined by Tilemap.getLayer().
* @param {number} x - The x coordinate to get the tile from. In tiles, not pixels.
* @param {number} y - The y coordinate to get the tile from. In tiles, not pixels.
*/
getTileLeft: function (layer, x, y) {
if (x > 0)
{
return this.layers[layer].data[y][x - 1];
}
return null;
},
/**
* Gets the tile to the right of the tile coordinates given.
* Mostly used as an internal function by calculateFaces.
*
* @method Phaser.Tilemap#getTileRight
* @param {number} layer - The local layer index to get the tile from. Can be determined by Tilemap.getLayer().
* @param {number} x - The x coordinate to get the tile from. In tiles, not pixels.
* @param {number} y - The y coordinate to get the tile from. In tiles, not pixels.
*/
getTileRight: function (layer, x, y) {
if (x < this.layers[layer].width - 1)
{
return this.layers[layer].data[y][x + 1];
}
return null;
},
/**
* Sets the current layer to the given index.
*
* @method Phaser.Tilemap#setLayer
* @param {number|string|Phaser.TilemapLayer} layer - The layer to set as current.
*/
setLayer: function (layer) {
layer = this.getLayer(layer);
if (this.layers[layer])
{
this.currentLayer = layer;
}
},
/**
* Checks if there is a tile at the given location.
*
* @method Phaser.Tilemap#hasTile
* @param {number} x - X position to check if a tile exists at (given in tile units, not pixels)
* @param {number} y - Y position to check if a tile exists at (given in tile units, not pixels)
* @param {number|string|Phaser.TilemapLayer} layer - The layer to set as current.
* @return {boolean} True if there is a tile at the given location, otherwise false.
*/
hasTile: function (x, y, layer) {
return (this.layers[layer].data[y] !== null && this.layers[layer].data[y][x] !== null);
},
/**
* Puts a tile of the given index value at the coordinate specified.
*
* @method Phaser.Tilemap#putTile
* @param {Phaser.Tile|number} tile - The index of this tile to set or a Phaser.Tile object.
* @param {number} x - X position to place the tile (given in tile units, not pixels)
* @param {number} y - Y position to place the tile (given in tile units, not pixels)
* @param {number|string|Phaser.TilemapLayer} [layer] - The layer to modify.
*/
putTile: function (tile, x, y, layer) {
layer = this.getLayer(layer);
if (x >= 0 && x < this.layers[layer].width && y >= 0 && y < this.layers[layer].height)
{
var index;
if (tile instanceof Phaser.Tile)
{
index = tile.index;
if (this.hasTile(x, y, layer))
{
this.layers[layer].data[y][x].copy(tile);
}
else
{
this.layers[layer].data[y][x] = new Phaser.Tile(layer, index, x, y, tile.width, tile.height);
}
}
else
{
index = tile;
if (this.hasTile(x, y, layer))
{
this.layers[layer].data[y][x].index = index;
}
else
{
this.layers[layer].data[y][x] = new Phaser.Tile(layer, index, x, y, this.tileWidth, this.tileHeight);
}
}
if (this.collideIndexes.indexOf(index) > -1)
{
this.layers[layer].data[y][x].setCollision(true, true, true, true);
}
else
{
this.layers[layer].data[y][x].resetCollision();
}
this.layers[layer].dirty = true;
this.calculateFaces(layer);
}
},
/**
* Puts a tile into the Tilemap layer. The coordinates are given in pixel values.
*
* @method Phaser.Tilemap#putTileWorldXY
* @param {Phaser.Tile|number} tile - The index of this tile to set or a Phaser.Tile object.
* @param {number} x - X position to insert the tile (given in pixels)
* @param {number} y - Y position to insert the tile (given in pixels)
* @param {number} tileWidth - The width of the tile in pixels.
* @param {number} tileHeight - The height of the tile in pixels.
* @param {number|string|Phaser.TilemapLayer} [layer] - The layer to modify.
*/
putTileWorldXY: function (tile, x, y, tileWidth, tileHeight, layer) {
layer = this.getLayer(layer);
x = this.game.math.snapToFloor(x, tileWidth) / tileWidth;
y = this.game.math.snapToFloor(y, tileHeight) / tileHeight;
this.putTile(tile, x, y, layer);
},
/**
* Gets a tile from the Tilemap Layer. The coordinates are given in tile values.
*
* @method Phaser.Tilemap#getTile
* @param {number} x - X position to get the tile from (given in tile units, not pixels)
* @param {number} y - Y position to get the tile from (given in tile units, not pixels)
* @param {number|string|Phaser.TilemapLayer} [layer] - The layer to get the tile from.
* @return {Phaser.Tile} The tile at the given coordinates.
*/
getTile: function (x, y, layer) {
layer = this.getLayer(layer);
if (x >= 0 && x < this.layers[layer].width && y >= 0 && y < this.layers[layer].height)
{
return this.layers[layer].data[y][x];
}
},
/**
* Gets a tile from the Tilemap layer. The coordinates are given in pixel values.
*
* @method Phaser.Tilemap#getTileWorldXY
* @param {number} x - X position to get the tile from (given in pixels)
* @param {number} y - Y position to get the tile from (given in pixels)
* @param {number} [tileWidth] - The width of the tiles. If not given the map default is used.
* @param {number} [tileHeight] - The height of the tiles. If not given the map default is used.
* @param {number|string|Phaser.TilemapLayer} [layer] - The layer to get the tile from.
* @return {Phaser.Tile} The tile at the given coordinates.
*/
getTileWorldXY: function (x, y, tileWidth, tileHeight, layer) {
if (typeof tileWidth === 'undefined') { tileWidth = this.tileWidth; }
if (typeof tileHeight === 'undefined') { tileHeight = this.tileHeight; }
layer = this.getLayer(layer);
x = this.game.math.snapToFloor(x, tileWidth) / tileWidth;
y = this.game.math.snapToFloor(y, tileHeight) / tileHeight;
return this.getTile(x, y, layer);
},
/**
* Copies all of the tiles in the given rectangular block into the tilemap data buffer.
*
* @method Phaser.Tilemap#copy
* @param {number} x - X position of the top left of the area to copy (given in tiles, not pixels)
* @param {number} y - Y position of the top left of the area to copy (given in tiles, not pixels)
* @param {number} width - The width of the area to copy (given in tiles, not pixels)
* @param {number} height - The height of the area to copy (given in tiles, not pixels)
* @param {number|string|Phaser.TilemapLayer} [layer] - The layer to copy the tiles from.
* @return {array} An array of the tiles that were copied.
*/
copy: function (x, y, width, height, layer) {
layer = this.getLayer(layer);
if (!this.layers[layer])
{
this._results.length = 0;
return;
}
if (typeof x === "undefined") { x = 0; }
if (typeof y === "undefined") { y = 0; }
if (typeof width === "undefined") { width = this.layers[layer].width; }
if (typeof height === "undefined") { height = this.layers[layer].height; }
if (x < 0)
{
x = 0;
}
if (y < 0)
{
y = 0;
}
if (width > this.layers[layer].width)
{
width = this.layers[layer].width;
}
if (height > this.layers[layer].height)
{
height = this.layers[layer].height;
}
this._results.length = 0;
this._results.push( { x: x, y: y, width: width, height: height, layer: layer });
for (var ty = y; ty < y + height; ty++)
{
for (var tx = x; tx < x + width; tx++)
{
this._results.push(this.layers[layer].data[ty][tx]);
}
}
return this._results;
},
/**
* Pastes a previously copied block of tile data into the given x/y coordinates. Data should have been prepared with Tilemap.copy.
*
* @method Phaser.Tilemap#paste
* @param {number} x - X position of the top left of the area to paste to (given in tiles, not pixels)
* @param {number} y - Y position of the top left of the area to paste to (given in tiles, not pixels)
* @param {array} tileblock - The block of tiles to paste.
* @param {number|string|Phaser.TilemapLayer} [layer] - The layer to paste the tiles into.
*/
paste: function (x, y, tileblock, layer) {
if (typeof x === "undefined") { x = 0; }
if (typeof y === "undefined") { y = 0; }
layer = this.getLayer(layer);
if (!tileblock || tileblock.length < 2)
{
return;
}
// Find out the difference between tileblock[1].x/y and x/y and use it as an offset, as it's the top left of the block to paste
var diffX = tileblock[1].x - x;
var diffY = tileblock[1].y - y;
for (var i = 1; i < tileblock.length; i++)
{
this.layers[layer].data[ diffY + tileblock[i].y ][ diffX + tileblock[i].x ].copy(tileblock[i]);
}
this.layers[layer].dirty = true;
this.calculateFaces(layer);
},
/**
* Scans the given area for tiles with an index matching tileA and swaps them with tileB.
*
* @method Phaser.Tilemap#swapTile
* @param {number} tileA - First tile index.
* @param {number} tileB - Second tile index.
* @param {number} x - X position of the top left of the area to operate one, given in tiles, not pixels.
* @param {number} y - Y position of the top left of the area to operate one, given in tiles, not pixels.
* @param {number} width - The width in tiles of the area to operate on.
* @param {number} height - The height in tiles of the area to operate on.
* @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on.
*/
swap: function (tileA, tileB, x, y, width, height, layer) {
layer = this.getLayer(layer);
this.copy(x, y, width, height, layer);
if (this._results.length < 2)
{
return;
}
this._tempA = tileA;
this._tempB = tileB;
this._results.forEach(this.swapHandler, this);
this.paste(x, y, this._results, layer);
},
/**
* Internal function that handles the swapping of tiles.
*
* @method Phaser.Tilemap#swapHandler
* @private
* @param {number} value
* @param {number} index
*/
swapHandler: function (value, index) {
if (value.index === this._tempA)
{
this._results[index].index = this._tempB;
}
else if (value.index === this._tempB)
{
this._results[index].index = this._tempA;
}
},
/**
* For each tile in the given area defined by x/y and width/height run the given callback.
*
* @method Phaser.Tilemap#forEach
* @param {number} callback - The callback. Each tile in the given area will be passed to this callback as the first and only parameter.
* @param {number} context - The context under which the callback should be run.
* @param {number} x - X position of the top left of the area to operate one, given in tiles, not pixels.
* @param {number} y - Y position of the top left of the area to operate one, given in tiles, not pixels.
* @param {number} width - The width in tiles of the area to operate on.
* @param {number} height - The height in tiles of the area to operate on.
* @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on.
*/
forEach: function (callback, context, x, y, width, height, layer) {
layer = this.getLayer(layer);
this.copy(x, y, width, height, layer);
if (this._results.length < 2)
{
return;
}
this._results.forEach(callback, context);
this.paste(x, y, this._results, layer);
},
/**
* Scans the given area for tiles with an index matching `source` and updates their index to match `dest`.
*
* @method Phaser.Tilemap#replace
* @param {number} source - The tile index value to scan for.
* @param {number} dest - The tile index value to replace found tiles with.
* @param {number} x - X position of the top left of the area to operate one, given in tiles, not pixels.
* @param {number} y - Y position of the top left of the area to operate one, given in tiles, not pixels.
* @param {number} width - The width in tiles of the area to operate on.
* @param {number} height - The height in tiles of the area to operate on.
* @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on.
*/
replace: function (source, dest, x, y, width, height, layer) {
layer = this.getLayer(layer);
this.copy(x, y, width, height, layer);
if (this._results.length < 2)
{
return;
}
for (var i = 1; i < this._results.length; i++)
{
if (this._results[i].index === source)
{
this._results[i].index = dest;
}
}
this.paste(x, y, this._results, layer);
},
/**
* Randomises a set of tiles in a given area.
*
* @method Phaser.Tilemap#random
* @param {number} x - X position of the top left of the area to operate one, given in tiles, not pixels.
* @param {number} y - Y position of the top left of the area to operate one, given in tiles, not pixels.
* @param {number} width - The width in tiles of the area to operate on.
* @param {number} height - The height in tiles of the area to operate on.
* @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on.
*/
random: function (x, y, width, height, layer) {
layer = this.getLayer(layer);
this.copy(x, y, width, height, layer);
if (this._results.length < 2)
{
return;
}
var indexes = [];
for (var t = 1; t < this._results.length; t++)
{
if (this._results[t].index)
{
var idx = this._results[t].index;
if (indexes.indexOf(idx) === -1)
{
indexes.push(idx);
}
}
}
for (var i = 1; i < this._results.length; i++)
{
this._results[i].index = this.game.rnd.pick(indexes);
}
this.paste(x, y, this._results, layer);
},
/**
* Shuffles a set of tiles in a given area. It will only randomise the tiles in that area, so if they're all the same nothing will appear to have changed!
*
* @method Phaser.Tilemap#shuffle
* @param {number} x - X position of the top left of the area to operate one, given in tiles, not pixels.
* @param {number} y - Y position of the top left of the area to operate one, given in tiles, not pixels.
* @param {number} width - The width in tiles of the area to operate on.
* @param {number} height - The height in tiles of the area to operate on.
* @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on.
*/
shuffle: function (x, y, width, height, layer) {
layer = this.getLayer(layer);
this.copy(x, y, width, height, layer);
if (this._results.length < 2)
{
return;
}
var indexes = [];
for (var t = 1; t < this._results.length; t++)
{
if (this._results[t].index)
{
indexes.push(this._results[t].index);
}
}
Phaser.Utils.shuffle(indexes);
for (var i = 1; i < this._results.length; i++)
{
this._results[i].index = indexes[i - 1];
}
this.paste(x, y, this._results, layer);
},
/**
* Fills the given area with the specified tile.
*
* @method Phaser.Tilemap#fill
* @param {number} index - The index of the tile that the area will be filled with.
* @param {number} x - X position of the top left of the area to operate one, given in tiles, not pixels.
* @param {number} y - Y position of the top left of the area to operate one, given in tiles, not pixels.
* @param {number} width - The width in tiles of the area to operate on.
* @param {number} height - The height in tiles of the area to operate on.
* @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on.
*/
fill: function (index, x, y, width, height, layer) {
layer = this.getLayer(layer);
this.copy(x, y, width, height, layer);
if (this._results.length < 2)
{
return;
}
for (var i = 1; i < this._results.length; i++)
{
this._results[i].index = index;
}
this.paste(x, y, this._results, layer);
},
/**
* Removes all layers from this tile map.
*
* @method Phaser.Tilemap#removeAllLayers
*/
removeAllLayers: function () {
this.layers.length = 0;
this.currentLayer = 0;
},
/**
* Dumps the tilemap data out to the console.
*
* @method Phaser.Tilemap#dump
*/
dump: function () {
var txt = '';
var args = [''];
for (var y = 0; y < this.layers[this.currentLayer].height; y++)
{
for (var x = 0; x < this.layers[this.currentLayer].width; x++)
{
txt += "%c ";
if (this.layers[this.currentLayer].data[y][x] > 1)
{
if (this.debugMap[this.layers[this.currentLayer].data[y][x]])
{
args.push("background: " + this.debugMap[this.layers[this.currentLayer].data[y][x]]);
}
else
{
args.push("background: #ffffff");
}
}
else
{
args.push("background: rgb(0, 0, 0)");
}
}
txt += "\n";
}
args[0] = txt;
console.log.apply(console, args);
},
/**
* Removes all layers from this tile map and nulls the game reference.
*
* @method Phaser.Tilemap#destroy
*/
destroy: function () {
this.removeAllLayers();
this.data = [];
this.game = null;
}
};
Phaser.Tilemap.prototype.constructor = Phaser.Tilemap;
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2014 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* A Tilemap Layer is a set of map data combined with a Tileset in order to render that data to the game.
*
* @class Phaser.TilemapLayer
* @constructor
* @param {Phaser.Game} game - Game reference to the currently running game.
* @param {Phaser.Tilemap} tilemap - The tilemap to which this layer belongs.
* @param {number} index - The layer index within the map that this TilemapLayer represents.
* @param {number} width - Width of the renderable area of the layer.
* @param {number} height - Height of the renderable area of the layer.
*/
Phaser.TilemapLayer = function (game, tilemap, index, width, height) {
/**
* @property {Phaser.Game} game - A reference to the currently running Game.
*/
this.game = game;
/**
* @property {Phaser.Tilemap} map - The Tilemap to which this layer is bound.
*/
this.map = tilemap;
/**
* @property {number} index - The index of this layer within the Tilemap.
*/
this.index = index;
/**
* @property {object} layer - The layer object within the Tilemap that this layer represents.
*/
this.layer = tilemap.layers[index];
/**
* @property {HTMLCanvasElement} canvas - The canvas to which this TilemapLayer draws.
*/
this.canvas = Phaser.Canvas.create(width, height, '', true);
/**
* @property {CanvasRenderingContext2D} context - The 2d context of the canvas.
*/
this.context = this.canvas.getContext('2d');
/**
* @property {PIXI.BaseTexture} baseTexture - Required Pixi var.
*/
this.baseTexture = new PIXI.BaseTexture(this.canvas);
/**
* @property {PIXI.Texture} texture - Required Pixi var.
*/
this.texture = new PIXI.Texture(this.baseTexture);
/**
* @property {Phaser.Frame} textureFrame - Dimensions of the renderable area.
*/
this.textureFrame = new Phaser.Frame(0, 0, 0, width, height, 'tilemapLayer', game.rnd.uuid());
// Phaser.Sprite.call(this, this.game, 0, 0, this.texture, this.textureFrame);
Phaser.Image.call(this, this.game, 0, 0, this.texture, this.textureFrame);
/**
* @property {string} name - The name of the layer.
*/
this.name = '';
/**
* @property {number} type - The const type of this object.
* @default
*/
this.type = Phaser.TILEMAPLAYER;
/**
* An object that is fixed to the camera ignores the position of any ancestors in the display list and uses its x/y coordinates as offsets from the top left of the camera.
* @property {boolean} fixedToCamera - Fixes this object to the Camera.
* @default
*/
this.fixedToCamera = true;
/**
* @property {Phaser.Point} cameraOffset - If this object is fixed to the camera then use this Point to specify how far away from the Camera x/y it's rendered.
*/
this.cameraOffset = new Phaser.Point(0, 0);
/**
* @property {string} tileColor - If no tileset is given the tiles will be rendered as rectangles in this color. Provide in hex or rgb/rgba string format.
* @default
*/
this.tileColor = 'rgb(255, 255, 255)';
/**
* @property {boolean} debug - If set to true the collideable tile edges path will be rendered. Only works when game is running in Phaser.CANVAS mode.
* @default
*/
this.debug = false;
/**
* @property {number} debugAlpha - If debug is true then the tileset is rendered with this alpha level, to make the tile edges clearer.
* @default
*/
this.debugAlpha = 0.5;
/**
* @property {string} debugColor - If debug is true this is the color used to outline the edges of collidable tiles. Provide in hex or rgb/rgba string format.
* @default
*/
this.debugColor = 'rgba(0, 255, 0, 1)';
/**
* @property {boolean} debugFill - If true the debug tiles are filled with debugFillColor AND stroked around.
* @default
*/
this.debugFill = false;
/**
* @property {string} debugFillColor - If debugFill is true this is the color used to fill the tiles. Provide in hex or rgb/rgba string format.
* @default
*/
this.debugFillColor = 'rgba(0, 255, 0, 0.2)';
/**
* @property {string} debugCallbackColor - If debug is true this is the color used to outline the edges of tiles that have collision callbacks. Provide in hex or rgb/rgba string format.
* @default
*/
this.debugCallbackColor = 'rgba(255, 0, 0, 1)';
/**
* @property {number} scrollFactorX - speed at which this layer scrolls
* horizontally, relative to the camera (e.g. scrollFactorX of 0.5 scrolls
* half as quickly as the 'normal' camera-locked layers do)
* @default 1
*/
this.scrollFactorX = 1;
/**
* @property {number} scrollFactorY - speed at which this layer scrolls
* vertically, relative to the camera (e.g. scrollFactorY of 0.5 scrolls
* half as quickly as the 'normal' camera-locked layers do)
* @default 1
*/
this.scrollFactorY = 1;
/**
* @property {boolean} dirty - Flag controlling when to re-render the layer.
*/
this.dirty = true;
/**
* @property {number} _cw - Local collision var.
* @private
*/
this._cw = tilemap.tileWidth;
/**
* @property {number} _ch - Local collision var.
* @private
*/
this._ch = tilemap.tileHeight;
/**
* @property {number} _ga - Local render loop var to help avoid gc spikes.
* @private
*/
this._ga = 1;
/**
* @property {number} _dx - Local render loop var to help avoid gc spikes.
* @private
*/
this._dx = 0;
/**
* @property {number} _dy - Local render loop var to help avoid gc spikes.
* @private
*/
this._dy = 0;
/**
* @property {number} _dw - Local render loop var to help avoid gc spikes.
* @private
*/
this._dw = 0;
/**
* @property {number} _dh - Local render loop var to help avoid gc spikes.
* @private
*/
this._dh = 0;
/**
* @property {number} _tx - Local render loop var to help avoid gc spikes.
* @private
*/
this._tx = 0;
/**
* @property {number} _ty - Local render loop var to help avoid gc spikes.
* @private
*/
this._ty = 0;
/**
* @property {number} _tw - Local render loop var to help avoid gc spikes.
* @private
*/
this._tw = 0;
/**
* @property {number} _th - Local render loop var to help avoid gc spikes.
* @private
*/
this._th = 0;
/**
* @property {number} _tl - Local render loop var to help avoid gc spikes.
* @private
*/
this._tl = 0;
/**
* @property {number} _maxX - Local render loop var to help avoid gc spikes.
* @private
*/
this._maxX = 0;
/**
* @property {number} _maxY - Local render loop var to help avoid gc spikes.
* @private
*/
this._maxY = 0;
/**
* @property {number} _startX - Local render loop var to help avoid gc spikes.
* @private
*/
this._startX = 0;
/**
* @property {number} _startY - Local render loop var to help avoid gc spikes.
* @private
*/
this._startY = 0;
/**
* @property {array} _results - Local render loop var to help avoid gc spikes.
* @private
*/
this._results = [];
/**
* @property {number} _x - Private var.
* @private
*/
this._x = 0;
/**
* @property {number} _y - Private var.
* @private
*/
this._y = 0;
/**
* @property {number} _prevX - Private var.
* @private
*/
this._prevX = 0;
/**
* @property {number} _prevY - Private var.
* @private
*/
this._prevY = 0;
this.updateMax();
};
Phaser.TilemapLayer.prototype = Object.create(Phaser.Image.prototype);
// Phaser.TilemapLayer.prototype = Phaser.Utils.extend(true, Phaser.TilemapLayer.prototype, Phaser.Sprite.prototype, PIXI.Sprite.prototype);
Phaser.TilemapLayer.prototype.constructor = Phaser.TilemapLayer;
/**
* Automatically called by World.postUpdate. Handles cache updates.
*
* @method Phaser.TilemapLayer#postUpdate
* @memberof Phaser.TilemapLayer
*/
Phaser.TilemapLayer.prototype.postUpdate = function () {
// Phaser.Sprite.prototype.postUpdate.call(this);
Phaser.Image.prototype.postUpdate.call(this);
// Stops you being able to auto-scroll the camera if it's not following a sprite
this.scrollX = this.game.camera.x * this.scrollFactorX;
this.scrollY = this.game.camera.y * this.scrollFactorY;
this.render();
}
/**
* Sets the world size to match the size of this layer.
*
* @method Phaser.TilemapLayer#resizeWorld
* @memberof Phaser.TilemapLayer
*/
Phaser.TilemapLayer.prototype.resizeWorld = function () {
this.game.world.setBounds(0, 0, this.layer.widthInPixels, this.layer.heightInPixels);
}
/**
* Take an x coordinate that doesn't account for scrollFactorX and 'fix' it
* into a scrolled local space. Used primarily internally
* @method Phaser.TilemapLayer#_fixX
* @memberof Phaser.TilemapLayer
* @private
* @param {number} x - x coordinate in camera space
* @return {number} x coordinate in scrollFactor-adjusted dimensions
*/
Phaser.TilemapLayer.prototype._fixX = function(x) {
if (x < 0)
{
x = 0;
}
if (this.scrollFactorX === 1)
{
return x;
}
return this._x + (x - (this._x / this.scrollFactorX));
}
/**
* Take an x coordinate that _does_ account for scrollFactorX and 'unfix' it
* back to camera space. Used primarily internally
* @method Phaser.TilemapLayer#_unfixX
* @memberof Phaser.TilemapLayer
* @private
* @param {number} x - x coordinate in scrollFactor-adjusted dimensions
* @return {number} x coordinate in camera space
*/
Phaser.TilemapLayer.prototype._unfixX = function(x) {
if (this.scrollFactorX === 1)
{
return x;
}
return (this._x / this.scrollFactorX) + (x - this._x);
}
/**
* Take a y coordinate that doesn't account for scrollFactorY and 'fix' it
* into a scrolled local space. Used primarily internally
* @method Phaser.TilemapLayer#_fixY
* @memberof Phaser.TilemapLayer
* @private
* @param {number} y - y coordinate in camera space
* @return {number} y coordinate in scrollFactor-adjusted dimensions
*/
Phaser.TilemapLayer.prototype._fixY = function(y) {
if (y < 0)
{
y = 0;
}
if (this.scrollFactorY === 1)
{
return y;
}
return this._y + (y - (this._y / this.scrollFactorY));
}
/**
* Take a y coordinate that _does_ account for scrollFactorY and 'unfix' it
* back to camera space. Used primarily internally
* @method Phaser.TilemapLayer#_unfixY
* @memberof Phaser.TilemapLayer
* @private
* @param {number} y - y coordinate in scrollFactor-adjusted dimensions
* @return {number} y coordinate in camera space
*/
Phaser.TilemapLayer.prototype._unfixY = function(y) {
if (this.scrollFactorY === 1)
{
return y;
}
return (this._y / this.scrollFactorY) + (y - this._y);
}
/**
* Convert a pixel value to a tile coordinate.
* @method Phaser.TilemapLayer#getTileX
* @memberof Phaser.TilemapLayer
* @param {number} x - X position of the point in target tile.
* @return {Phaser.Tile} The tile with specific properties.
*/
Phaser.TilemapLayer.prototype.getTileX = function (x) {
// var tileWidth = this.tileWidth * this.scale.x;
return this.game.math.snapToFloor(this._fixX(x), this.map.tileWidth) / this.map.tileWidth;
}
/**
* Convert a pixel value to a tile coordinate.
* @method Phaser.TilemapLayer#getTileY
* @memberof Phaser.TilemapLayer
* @param {number} y - Y position of the point in target tile.
* @return {Phaser.Tile} The tile with specific properties.
*/
Phaser.TilemapLayer.prototype.getTileY = function (y) {
// var tileHeight = this.tileHeight * this.scale.y;
return this.game.math.snapToFloor(this._fixY(y), this.map.tileHeight) / this.map.tileHeight;
}
/**
* Convert a pixel value to a tile coordinate.
* @method Phaser.TilemapLayer#getTileXY
* @memberof Phaser.TilemapLayer
* @param {number} x - X position of the point in target tile.
* @param {number} y - Y position of the point in target tile.
* @param {Phaser.Point|object} point - The Point object to set the x and y values on.
* @return {Phaser.Point|object} A Point object with its x and y properties set.
*/
Phaser.TilemapLayer.prototype.getTileXY = function (x, y, point) {
point.x = this.getTileX(x);
point.y = this.getTileY(y);
return point;
}
Phaser.TilemapLayer.prototype.getIntersectingTiles = function (x, y, width, height) {
// var tiles = this.getTiles(x, y, width,height, true);
var tiles = this.getTiles(x, y, width,height, false);
var right = x + width;
var bottom = y + height;
// We only want the ones that we actually intersect with
var i = tiles.length;
while (i--)
{
if (tiles[i].intersects(x, y, right, bottom))
{
// tiles[i].debug = true;
}
else
{
// console.log('sliced off tile', i);
// tiles.pop();
}
}
return tiles;
}
/*
Phaser.TilemapLayer.prototype.getTilesX = function (x, y, width, height, collides) {
// Should we only get tiles that have at least one of their collision flags set? (true = yes, false = no just get them all)
if (typeof collides === 'undefined') { collides = false; }
// adjust the x,y coordinates for scrollFactor
x = this._fixX(x);
y = this._fixY(y);
if (width > this.layer.widthInPixels)
{
width = this.layer.widthInPixels;
}
if (height > this.layer.heightInPixels)
{
height = this.layer.heightInPixels;
}
// Convert the pixel values into tile coordinates
// this._tx = this.game.math.snapToFloor(x, this._cw) / this._cw;
// this._ty = this.game.math.snapToFloor(y, this._ch) / this._ch;
// this._tw = (this.game.math.snapToCeil(width, this._cw) + this._cw) / this._cw;
// this._th = (this.game.math.snapToCeil(height, this._ch) + this._ch) / this._ch;
// var firstTileX = Math.max( Math.floor(res.pos.x / this.tilesize), 0 );
// var lastTileX = Math.min( Math.ceil((res.pos.x + width) / this.tilesize), this.width );
// var tileY = Math.floor( (res.pos.y + pxOffsetY) / this.tilesize );
this._tx = Math.max(Math.floor(x / this.tileWidth), 0);
this._tw = Math.min(Math.ceil((x + width) / this.tileWidth), this.width);
this._ty = Math.floor((y + px) / this.tileHeight);
this._results.length = 0;
for (var wy = this._ty; wy < this._ty + this._th; wy++)
{
for (var wx = this._tx; wx < this._tx + this._tw; wx++)
{
if (this.layer.data[wy] && this.layer.data[wy][wx])
{
if (collides === false || (collides && this.layer.data[wy][wx].canCollide))
{
this._results.push(this.layer.data[wy][wx]);
}
}
}
}
// DEBUG ONLY - REMOVE
this.layer.dirty = true;
return this._results;
}
*/
/**
* Get all tiles that exist within the given area, defined by the top-left corner, width and height. Values given are in pixels, not tiles.
* @method Phaser.TilemapLayer#getTiles
* @memberof Phaser.TilemapLayer
* @param {number} x - X position of the top left corner.
* @param {number} y - Y position of the top left corner.
* @param {number} width - Width of the area to get.
* @param {number} height - Height of the area to get.
* @param {boolean} [collides=false] - If true only return tiles that collide on one or more faces.
* @return {array} Array with tiles informations (each contains x, y, and the tile).
*/
Phaser.TilemapLayer.prototype.getTiles = function (x, y, width, height, collides) {
// Should we only get tiles that have at least one of their collision flags set? (true = yes, false = no just get them all)
if (typeof collides === 'undefined') { collides = false; }
// adjust the x,y coordinates for scrollFactor
x = this._fixX(x);
y = this._fixY(y);
if (width > this.layer.widthInPixels)
{
width = this.layer.widthInPixels;
}
if (height > this.layer.heightInPixels)
{
height = this.layer.heightInPixels;
}
// Convert the pixel values into tile coordinates
this._tx = this.game.math.snapToFloor(x, this._cw) / this._cw;
this._ty = this.game.math.snapToFloor(y, this._ch) / this._ch;
this._tw = (this.game.math.snapToCeil(width, this._cw) + this._cw) / this._cw;
this._th = (this.game.math.snapToCeil(height, this._ch) + this._ch) / this._ch;
// This should apply the layer x/y here
// this._results.length = 0;
this._results = [];
for (var wy = this._ty; wy < this._ty + this._th; wy++)
{
for (var wx = this._tx; wx < this._tx + this._tw; wx++)
{
if (this.layer.data[wy] && this.layer.data[wy][wx])
{
if (collides === false || (collides && this.layer.data[wy][wx].canCollide))
{
/*
// Convert tile coordinates back to camera space for return
var _wx = this._unfixX(wx * this._cw) / this._cw;
var _wy = this._unfixY(wy * this._ch) / this._ch;
this._results.push({
x: _wx * this._cw,
y: _wy * this._ch,
right: (_wx * this._cw) + this._cw,
bottom: (_wy * this._ch) + this._ch,
tile: this.layer.data[wy][wx],
layer: this.layer.data[wy][wx].layer
});
*/
this._results.push(this.layer.data[wy][wx]);
}
}
}
}
// DEBUG ONLY - REMOVE
this.layer.dirty = true;
return this._results;
}
/**
* Internal function to update maximum values.
* @method Phaser.TilemapLayer#updateMax
* @memberof Phaser.TilemapLayer
*/
Phaser.TilemapLayer.prototype.updateMax = function () {
this._maxX = this.game.math.ceil(this.canvas.width / this.map.tileWidth) + 1;
this._maxY = this.game.math.ceil(this.canvas.height / this.map.tileHeight) + 1;
if (this.layer)
{
if (this._maxX > this.layer.width)
{
this._maxX = this.layer.width;
}
if (this._maxY > this.layer.height)
{
this._maxY = this.layer.height;
}
}
this.dirty = true;
}
/**
* Renders the tiles to the layer canvas and pushes to the display.
* @method Phaser.TilemapLayer#render
* @memberof Phaser.TilemapLayer
*/
Phaser.TilemapLayer.prototype.render = function () {
if (this.layer.dirty)
{
this.dirty = true;
}
if (!this.dirty || !this.visible)
{
return;
}
this._prevX = this._dx;
this._prevY = this._dy;
this._dx = -(this._x - (this._startX * this.map.tileWidth));
this._dy = -(this._y - (this._startY * this.map.tileHeight));
this._tx = this._dx;
this._ty = this._dy;
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
this.context.fillStyle = this.tileColor;
var tile;
var set;
var ox = 0;
var oy = 0;
if (this.debug)
{
this.context.globalAlpha = this.debugAlpha;
}
for (var y = this._startY, lenY = this._startY + this._maxY; y < lenY; y++)
{
this._column = this.layer.data[y];
for (var x = this._startX, lenX = this._startX + this._maxX; x < lenX; x++)
{
if (this._column[x])
{
tile = this._column[x];
// this needs to know which set the index is from
// set = this.map.tilesets[this.map.tiles[tile.index][2]]
set = this.map.tilesets[0];
if (this.debug === false && tile.alpha !== this.context.globalAlpha)
{
this.context.globalAlpha = tile.alpha;
}
set.draw(this.context, Math.floor(this._tx), Math.floor(this._ty), tile.index);
if (tile.debug)
{
this.context.fillStyle = 'rgba(0, 255, 0, 0.4)';
this.context.fillRect(Math.floor(this._tx), Math.floor(this._ty), this.map.tileWidth, this.map.tileHeight);
}
}
this._tx += this.map.tileWidth;
}
this._tx = this._dx;
this._ty += this.map.tileHeight;
}
if (this.debug)
{
this.context.globalAlpha = 1;
this.renderDebug();
}
if (this.game.renderType === Phaser.WEBGL)
{
// PIXI.updateWebGLTexture(this.baseTexture, renderSession.gl);
PIXI.updateWebGLTexture(this.baseTexture, this.game.renderer.gl);
}
this.dirty = false;
this.layer.dirty = false;
return true;
}
/**
* Renders the tiles to the layer canvas and pushes to the display.
* @method Phaser.TilemapLayer#render
* @memberof Phaser.TilemapLayer
*/
Phaser.TilemapLayer.prototype.OLDrender = function () {
if (this.layer.dirty)
{
this.dirty = true;
}
if (!this.dirty || !this.visible)
{
// return;
}
this._prevX = this._dx;
this._prevY = this._dy;
this._dx = -(this._x - (this._startX * this.map.tileWidth));
this._dy = -(this._y - (this._startY * this.map.tileHeight));
this._tx = this._dx;
this._ty = this._dy;
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
this.context.fillStyle = this.tileColor;
var tile;
var set;
var ox = 0;
var oy = 0;
if (this.debug)
{
this.context.globalAlpha = this.debugAlpha;
}
for (var y = this._startY, lenY = this._startY + this._maxY; y < lenY; y++)
{
this._column = this.layer.data[y];
for (var x = this._startX, lenX = this._startX + this._maxX; x < lenX; x++)
{
if (this._column[x])
{
tile = this._column[x];
if (this.map.tiles[tile.index])
{
set = this.map.tilesets[this.map.tiles[tile.index][2]]
if (set.image)
{
if (this.debug === false && tile.alpha !== this.context.globalAlpha)
{
this.context.globalAlpha = tile.alpha;
}
if (set.tileWidth !== this.map.tileWidth || set.tileHeight !== this.map.tileHeight)
{
// TODO: Smaller sized tile check
this.context.drawImage(
this.map.tilesets[this.map.tiles[tile.index][2]].image,
this.map.tiles[tile.index][0],
this.map.tiles[tile.index][1],
set.tileWidth,
set.tileHeight,
Math.floor(this._tx),
Math.floor(this._ty) - (set.tileHeight - this.map.tileHeight),
set.tileWidth,
set.tileHeight
);
}
else
{
this.context.drawImage(
this.map.tilesets[this.map.tiles[tile.index][2]].image,
this.map.tiles[tile.index][0],
this.map.tiles[tile.index][1],
this.map.tileWidth,
this.map.tileHeight,
Math.floor(this._tx),
Math.floor(this._ty),
this.map.tileWidth,
this.map.tileHeight
);
}
// if (tile.debug)
// {
this.context.fillStyle = 'rgba(0, 255, 0, 0.4)';
this.context.fillRect(Math.floor(this._tx), Math.floor(this._ty), this.map.tileWidth, this.map.tileHeight);
// }
}
else
{
this.context.fillRect(Math.floor(this._tx), Math.floor(this._ty), this.map.tileWidth, this.map.tileHeight);
}
}
}
this._tx += this.map.tileWidth;
}
this._tx = this._dx;
this._ty += this.map.tileHeight;
}
if (this.debug)
{
this.context.globalAlpha = 1;
this.renderDebug();
}
if (this.game.renderType === Phaser.WEBGL)
{
// PIXI.updateWebGLTexture(this.baseTexture, renderSession.gl);
PIXI.updateWebGLTexture(this.baseTexture, this.game.renderer.gl);
}
this.dirty = false;
this.layer.dirty = false;
return true;
}
/**
* Renders a collision debug overlay on-top of the canvas. Called automatically by render when debug = true.
* @method Phaser.TilemapLayer#renderDebug
* @memberof Phaser.TilemapLayer
*/
Phaser.TilemapLayer.prototype.renderDebug = function () {
this._tx = this._dx;
this._ty = this._dy;
this.context.strokeStyle = this.debugColor;
this.context.fillStyle = this.debugFillColor;
for (var y = this._startY, lenY = this._startY + this._maxY; y < lenY; y++)
{
this._column = this.layer.data[y];
for (var x = this._startX, lenX = this._startX + this._maxX; x < lenX; x++)
{
var tile = this._column[x];
if (tile && (tile.faceTop || tile.faceBottom || tile.faceLeft || tile.faceRight))
{
this._tx = Math.floor(this._tx);
if (this.debugFill)
{
this.context.fillRect(this._tx, this._ty, this._cw, this._ch);
}
this.context.beginPath();
if (tile.faceTop)
{
this.context.moveTo(this._tx, this._ty);
this.context.lineTo(this._tx + this._cw, this._ty);
}
if (tile.faceBottom)
{
this.context.moveTo(this._tx, this._ty + this._ch);
this.context.lineTo(this._tx + this._cw, this._ty + this._ch);
}
if (tile.faceLeft)
{
this.context.moveTo(this._tx, this._ty);
this.context.lineTo(this._tx, this._ty + this._ch);
}
if (tile.faceRight)
{
this.context.moveTo(this._tx + this._cw, this._ty);
this.context.lineTo(this._tx + this._cw, this._ty + this._ch);
}
this.context.stroke();
}
// Collision callback
// if (tile && (tile.collisionCallback || tile.layer.callbacks[tile.index]))
// {
// this.context.fillStyle = this.debugCallbackColor;
// this.context.fillRect(this._tx, this._ty, this._cw, this._ch);
// this.context.fillStyle = this.debugFillColor;
// }
this._tx += this.map.tileWidth;
}
this._tx = this._dx;
this._ty += this.map.tileHeight;
}
}
/**
* @name Phaser.TilemapLayer#scrollX
* @property {number} scrollX - Scrolls the map horizontally or returns the current x position.
*/
Object.defineProperty(Phaser.TilemapLayer.prototype, "scrollX", {
get: function () {
return this._x;
},
set: function (value) {
// if (value !== this._x && value >= 0 && this.layer && this.layer.widthInPixels > this.width)
if (value !== this._x && value >= 0 && this.layer.widthInPixels > this.width)
{
this._x = value;
if (this._x > (this.layer.widthInPixels - this.width))
{
this._x = this.layer.widthInPixels - this.width;
}
this._startX = this.game.math.floor(this._x / this.map.tileWidth);
if (this._startX < 0)
{
this._startX = 0;
}
if (this._startX + this._maxX > this.layer.width)
{
this._startX = this.layer.width - this._maxX;
}
this.dirty = true;
}
}
});
/**
* @name Phaser.TilemapLayer#scrollY
* @property {number} scrollY - Scrolls the map vertically or returns the current y position.
*/
Object.defineProperty(Phaser.TilemapLayer.prototype, "scrollY", {
get: function () {
return this._y;
},
set: function (value) {
// if (value !== this._y && value >= 0 && this.layer && this.heightInPixels > this.renderHeight)
if (value !== this._y && value >= 0 && this.layer.heightInPixels > this.height)
{
this._y = value;
if (this._y > (this.layer.heightInPixels - this.height))
{
this._y = this.layer.heightInPixels - this.height;
}
this._startY = this.game.math.floor(this._y / this.map.tileHeight);
if (this._startY < 0)
{
this._startY = 0;
}
if (this._startY + this._maxY > this.layer.height)
{
this._startY = this.layer.height - this._maxY;
}
this.dirty = true;
}
}
});
/**
* @name Phaser.TilemapLayer#collisionWidth
* @property {number} collisionWidth - The width of the collision tiles.
*/
Object.defineProperty(Phaser.TilemapLayer.prototype, "collisionWidth", {
get: function () {
return this._cw;
},
set: function (value) {
this._cw = value;
this.dirty = true;
}
});
/**
* @name Phaser.TilemapLayer#collisionHeight
* @property {number} collisionHeight - The height of the collision tiles.
*/
Object.defineProperty(Phaser.TilemapLayer.prototype, "collisionHeight", {
get: function () {
return this._ch;
},
set: function (value) {
this._ch = value;
this.dirty = true;
}
});
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2014 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* Phaser.TilemapParser parses data objects from Phaser.Loader that need more preparation before they can be inserted into a Tilemap.
*
* @class Phaser.TilemapParser
*/
Phaser.TilemapParser = {
/**
* Creates a Tileset object.
* @method Phaser.TilemapParser.tileset
* @param {Phaser.Game} game - Game reference to the currently running game.
* @param {string} key - The Cache key of this tileset.
* @param {number} tileWidth - Width of each single tile in pixels.
* @param {number} tileHeight - Height of each single tile in pixels.
* @param {number} [tileMargin=0] - If the tiles have been drawn with a margin, specify the amount here.
* @param {number} [tileSpacing=0] - If the tiles have been drawn with spacing between them, specify the amount here.
* @param {number} [rows=-1] - How many tiles are placed horizontally in each row? If -1 it will calculate rows by dividing the image width by tileWidth.
* @param {number} [columns=-1] - How many tiles are placed vertically in each column? If -1 it will calculate columns by dividing the image height by tileHeight.
* @param {number} [total=-1] - The maximum number of tiles to extract from the image. If -1 it will extract `rows * columns` worth. You can also set a value lower than the actual number of tiles.
* @return {Phaser.Tileset} Generated Tileset object.
*/
tileset: function (game, key, tileWidth, tileHeight, tileMargin, tileSpacing, rows, columns, total) {
// How big is our image?
var img = game.cache.getTilesetImage(key);
if (img === null)
{
console.warn("Phaser.TilemapParser.tileSet: Invalid image key given");
return null;
}
var width = img.width;
var height = img.height;
if (rows === -1)
{
rows = Math.round(width / tileWidth);
}
if (columns === -1)
{
columns = Math.round(height / tileHeight);
}
if (total === -1)
{
total = rows * columns;
}
// Zero or smaller than tile sizes?
if (width === 0 || height === 0 || width < tileWidth || height < tileHeight || total === 0)
{
console.warn("Phaser.TilemapParser.tileSet: width/height zero or width/height < given tileWidth/tileHeight");
return null;
}
return new Phaser.Tileset(img, key, tileWidth, tileHeight, tileMargin, tileSpacing, rows, columns, total);
},
/**
* Parse tilemap data from the cache and creates a Tilemap object.
*
* @method Phaser.TilemapParser.parse
* @param {Phaser.Game} game - Game reference to the currently running game.
* @param {string} key - The key of the tilemap in the Cache.
* @param {number} [tileWidth=32] - The pixel width of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data.
* @param {number} [tileHeight=32] - The pixel height of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data.
* @param {number} [width=10] - The width of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this.
* @param {number} [height=10] - The height of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this.
* @return {object} The parsed map object.
*/
parse: function (game, key, tileWidth, tileHeight, width, height) {
if (typeof tileWidth === 'undefined') { tileWidth = 32; }
if (typeof tileHeight === 'undefined') { tileHeight = 32; }
if (typeof width === 'undefined') { width = 10; }
if (typeof height === 'undefined') { height = 10; }
if (typeof key === 'undefined')
{
return this.getEmptyData();
}
if (key === null)
{
return this.getEmptyData(tileWidth, tileHeight, width, height);
}
var map = game.cache.getTilemapData(key);
if (map)
{
if (map.format === Phaser.Tilemap.CSV)
{
return this.parseCSV(key, map.data, tileWidth, tileHeight);
}
else if (!map.format || map.format === Phaser.Tilemap.TILED_JSON)
{
return this.parseTiledJSON(map.data);
}
}
else
{
console.warn('Phaser.TilemapParser.parse - No map data found for key ' + key);
}
},
/**
* Parses a CSV file into valid map data.
*
* @method Phaser.TilemapParser.parseCSV
* @param {string} data - The CSV file data.
* @param {number} [tileWidth=32] - The pixel width of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data.
* @param {number} [tileHeight=32] - The pixel height of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data.
* @return {object} Generated map data.
*/
parseCSV: function (key, data, tileWidth, tileHeight) {
var map = this.getEmptyData();
// Trim any rogue whitespace from the data
data = data.trim();
var output = [];
var rows = data.split("\n");
var height = rows.length;
var width = 0;
for (var y = 0; y < rows.length; y++)
{
output[y] = [];
var column = rows[y].split(",");
for (var x = 0; x < column.length; x++)
{
output[y][x] = new Phaser.Tile(0, parseInt(column[x], 10), x, y, tileWidth, tileHeight);
}
if (width === 0)
{
width = column.length;
}
}
map.name = key;
map.width = width;
map.height = height;
map.tileWidth = tileWidth;
map.tileHeight = tileHeight;
map.widthInPixels = width * tileWidth;
map.heightInPixels = height * tileHeight;
map.layers[0].width = width;
map.layers[0].height = height;
map.layers[0].widthInPixels = map.widthInPixels;
map.layers[0].heightInPixels = map.heightInPixels;
map.layers[0].data = output;
return map;
},
/**
* Returns an empty map data object.
* @method Phaser.TilemapParser.getEmptyData
* @return {object} Generated map data.
*/
getEmptyData: function (tileWidth, tileHeight, width, height) {
var map = {};
map.width = 0;
map.height = 0;
map.tileWidth = 0;
map.tileHeight = 0;
if (typeof tileWidth !== 'undefined' && tileWidth !== null) { map.tileWidth = tileWidth; }
if (typeof tileHeight !== 'undefined' && tileHeight !== null) { map.tileHeight = tileHeight; }
if (typeof width !== 'undefined' && width !== null) { map.width = width; }
if (typeof height !== 'undefined' && height !== null) { map.height = height; }
map.orientation = 'orthogonal';
map.version = '1';
map.properties = {};
map.widthInPixels = 0;
map.heightInPixels = 0;
var layers = [];
var layer = {
name: 'layer',
x: 0,
y: 0,
width: 0,
height: 0,
widthInPixels: 0,
heightInPixels: 0,
alpha: 1,
visible: true,
properties: {},
indexes: [],
callbacks: [],
data: []
};
// fill with nulls?
layers.push(layer);
map.layers = layers;
map.images = [];
map.objects = {};
map.collision = {};
map.tilesets = [];
map.tiles = [];
return map;
},
/**
* Parses a Tiled JSON file into valid map data.
* @method Phaser.TilemapParser.parseJSON
* @param {object} json - The JSON map data.
* @return {object} Generated and parsed map data.
*/
parseTiledJSON: function (json) {
if (json.orientation !== 'orthogonal')
{
console.warn('TilemapParser.parseTiledJSON: Only orthogonal map types are supported in this version of Phaser');
return null;
}
// Map data will consist of: layers, objects, images, tilesets, sizes
var map = {};
map.width = json.width;
map.height = json.height;
map.tileWidth = json.tilewidth;
map.tileHeight = json.tileheight;
map.orientation = json.orientation;
map.version = json.version;
map.properties = json.properties;
map.widthInPixels = map.width * map.tileWidth;
map.heightInPixels = map.height * map.tileHeight;
// Tile Layers
var layers = [];
for (var i = 0; i < json.layers.length; i++)
{
if (json.layers[i].type !== 'tilelayer')
{
continue;
}
var layer = {
name: json.layers[i].name,
x: json.layers[i].x,
y: json.layers[i].y,
width: json.layers[i].width,
height: json.layers[i].height,
widthInPixels: json.layers[i].width * json.tilewidth,
heightInPixels: json.layers[i].height * json.tileheight,
alpha: json.layers[i].opacity,
visible: json.layers[i].visible,
properties: {},
indexes: [],
callbacks: [],
bodies: []
};
if (json.layers[i].properties)
{
layer.properties = json.layers[i].properties;
}
var x = 0;
var row = [];
var output = [];
// Loop through the data field in the JSON.
// This is an array containing the tile indexes, one after the other. null = no tile, everything else = the tile index (starting at 1 for Tiled, 0 for CSV)
// If the map contains multiple tilesets then the indexes are relative to that which the set starts from.
// Need to set which tileset in the cache = which tileset in the JSON, if you do this manually it means you can use the same map data but a new tileset.
for (var t = 0, len = json.layers[i].data.length; t < len; t++)
{
// index, x, y, width, height
if (json.layers[i].data[t] > 0)
{
row.push(new Phaser.Tile(layer, json.layers[i].data[t], x, output.length, json.tilewidth, json.tileheight));
}
else
{
row.push(null);
}
x++;
if (x === json.layers[i].width)
{
output.push(row);
x = 0;
row = [];
}
}
layer.data = output;
layers.push(layer);
}
map.layers = layers;
// Images
var images = [];
for (var i = 0; i < json.layers.length; i++)
{
if (json.layers[i].type !== 'imagelayer')
{
continue;
}
var image = {
name: json.layers[i].name,
image: json.layers[i].image,
x: json.layers[i].x,
y: json.layers[i].y,
alpha: json.layers[i].opacity,
visible: json.layers[i].visible,
properties: {}
};
if (json.layers[i].properties)
{
image.properties = json.layers[i].properties;
}
images.push(image);
}
map.images = images;
// Objects & Collision Data (polylines, etc)
var objects = {};
var collision = {};
for (var i = 0; i < json.layers.length; i++)
{
if (json.layers[i].type !== 'objectgroup')
{
continue;
}
objects[json.layers[i].name] = [];
collision[json.layers[i].name] = [];
for (var v = 0, len = json.layers[i].objects.length; v < len; v++)
{
// Object Tiles
if (json.layers[i].objects[v].gid)
{
var object = {
gid: json.layers[i].objects[v].gid,
name: json.layers[i].objects[v].name,
x: json.layers[i].objects[v].x,
y: json.layers[i].objects[v].y,
visible: json.layers[i].objects[v].visible,
properties: json.layers[i].objects[v].properties
};
objects[json.layers[i].name].push(object);
}
else if (json.layers[i].objects[v].polyline)
{
var object = {
name: json.layers[i].objects[v].name,
x: json.layers[i].objects[v].x,
y: json.layers[i].objects[v].y,
width: json.layers[i].objects[v].width,
height: json.layers[i].objects[v].height,
visible: json.layers[i].objects[v].visible,
properties: json.layers[i].objects[v].properties
};
object.polyline = [];
// Parse the polyline into an array
for (var p = 0; p < json.layers[i].objects[v].polyline.length; p++)
{
object.polyline.push([ json.layers[i].objects[v].polyline[p].x, json.layers[i].objects[v].polyline[p].y ]);
}
collision[json.layers[i].name].push(object);
}
}
}
map.objects = objects;
map.collision = collision;
// Tilesets
var tilesets = [];
for (var i = 0; i < json.tilesets.length; i++)
{
// name, firstgid, width, height, margin, spacing, properties
var set = json.tilesets[i];
var newSet = new Phaser.Tileset(set.name, set.firstgid, set.tilewidth, set.tileheight, set.margin, set.spacing, set.properties);
if (set.tileproperties)
{
newSet.tileProperties = set.tileproperties;
}
newSet.rows = Math.round((set.imageheight - set.margin) / (set.tileheight + set.spacing));
newSet.columns = Math.round((set.imagewidth - set.margin) / (set.tilewidth + set.spacing));
newSet.total = newSet.rows * newSet.columns;
if (newSet.rows % 1 !== 0 || newSet.columns % 1 !== 0)
{
console.warn('TileSet image dimensions do not match expected dimensions. Tileset width/height must be evenly divisible by Tilemap tile width/height.');
}
else
{
tilesets.push(newSet);
}
}
map.tilesets = tilesets;
map.tiles = [];
// Finally lets build our super tileset index
for (var i = 0; i < map.tilesets.length; i++)
{
var set = map.tilesets[i];
var x = set.tileMargin;
var y = set.tileMargin;
var count = 0;
var countX = 0;
var countY = 0;
for (var t = set.firstgid; t < set.firstgid + set.total; t++)
{
// Can add extra properties here as needed
map.tiles[t] = [x, y, i];
x += set.tileWidth + set.tileSpacing;
count++;
if (count === set.total)
{
break;
}
countX++;
if (countX === set.columns)
{
x = set.tileMargin;
y += set.tileHeight + set.tileSpacing;
countX = 0;
countY++;
if (countY === set.rows)
{
break;
}
}
}
}
return map;
}
}
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2014 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* A Tile set is a combination of an image containing the tiles and collision data per tile.
* You should not normally instantiate this class directly.
*
* @class Phaser.Tileset
* @constructor
* @param {string} name - The name of the tileset in the map data.
* @param {number} firstgid - The Tiled firstgid value. In non-Tiled data this should be considered the starting index value of the first tile in this set.
* @param {number} width - Width of each tile in pixels.
* @param {number} height - Height of each tile in pixels.
* @param {number} margin - The amount of margin around the tilesheet.
* @param {number} spacing - The amount of spacing between each tile in the sheet.
* @param {object} properties - Tileset properties.
*/
Phaser.Tileset = function (name, firstgid, width, height, margin, spacing, properties) {
/**
* @property {string} name - The name of the Tileset.
*/
this.name = name;
/**
* @property {number} firstgid - The Tiled firstgid value. In non-Tiled data this should be considered the starting index value of the first tile in this set.
*/
this.firstgid = firstgid;
/**
* @property {number} tileWidth - The width of a tile in pixels.
*/
this.tileWidth = width;
/**
* @property {number} tileHeight - The height of a tile in pixels.
*/
this.tileHeight = height;
/**
* @property {number} tileMargin - The margin around the tiles in the tileset.
*/
this.tileMargin = margin;
/**
* @property {number} tileSpacing - The spacing in pixels between each tile in the tileset.
*/
this.tileSpacing = spacing;
/**
* @property {object} properties - Tileset specific properties (typically defined in the Tiled editor).
*/
this.properties = properties;
/**
* @property {object} image - The image used for rendering. This is a reference to the image stored in Phaser.Cache.
*/
this.image = null;
/**
* @property {number} rows - The number of rows in the tile sheet.
*/
this.rows = 0;
/**
* @property {number} columns - The number of columns in the tile sheet.
*/
this.columns = 0;
/**
* @property {number} total - The total number of tiles in the tilesheet.
*/
this.total = 0;
/**
* @property {array} draw - The tile drawImage look-up table
* @private
*/
this.drawCoords = [];
};
Phaser.Tileset.prototype = {
/**
* Draws a tile from this Tileset at the given coordinates on the context.
*
* @method Phaser.Tileset#draw
* @param {HTMLCanvasContext} context - The context to draw the tile onto.
* @param {number} x - The x coordinate to draw to.
* @param {number} y - The y coordinate to draw to.
* @param {number} index - The index of the tile within the set to draw.
*/
draw: function (context, x, y, index) {
if (!this.image || !this.drawCoords[index])
{
return;
}
context.drawImage(
this.image,
this.drawCoords[index][0],
this.drawCoords[index][1],
this.tileWidth,
this.tileHeight,
x,
y,
this.tileWidth,
this.tileHeight
);
},
/**
* Adds a reference from this Tileset to an Image stored in the Phaser.Cache.
*
* @method Phaser.Tileset#setImage
* @param {Image} image - The image this tileset will use to draw with.
*/
setImage: function (image) {
this.image = image;
this.rows = Math.round((image.height - this.tileMargin) / (this.tileHeight + this.tileSpacing));
this.columns = Math.round((image.width - this.tileMargin) / (this.tileWidth + this.tileSpacing));
this.total = this.rows * this.columns;
// Create the index look-up
this.drawCoords.length = 0;
var tx = this.tileMargin;
var ty = this.tileMargin;
var i = this.firstgid;
for (var y = 0; y < this.rows; y++)
{
for (var x = 0; x < this.columns; x++)
{
this.drawCoords[i] = [ tx, ty ];
tx += this.tileWidth + this.tileSpacing;
i++;
}
tx = this.tileMargin;
ty += this.tileHeight + this.tileSpacing;
}
},
/**
* Sets tile spacing and margins.
*
* @method Phaser.Tileset#setSpacing
* @param {number} [tileMargin] - The margin around the tiles in the sheet.
* @param {number} [tileSpacing] - The spacing between the tiles in the sheet.
*/
setSpacing: function (margin, spacing) {
this.tileMargin = margin;
this.tileSpacing = spacing;
this.setImage(this.image);
}
};
Phaser.Tileset.prototype.constructor = Phaser.Tileset;
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2014 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
if (typeof exports !== 'undefined') {
if (typeof module !== 'undefined' && module.exports) {
exports = module.exports = Phaser;
}
exports.Phaser = Phaser;
} else if (typeof define !== 'undefined' && define.amd) {
define('phaser', Phaser);
} else {
root.Phaser = Phaser;
}
}).call(this);
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2014 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* Ninja Physics constructor.
*
* The Ninja Physics system was created in Flash by Metanet Software and ported to JavaScript by Richard Davey.
*
* @class Phaser.Physics.Ninja
* @classdesc Ninja Physics Constructor
* @constructor
* @param {Phaser.Game} game reference to the current game instance.
*/
Phaser.Physics.Ninja = function (game) {
/**
* @property {Phaser.Game} game - Local reference to game.
*/
this.game = game;
this.time = this.game.time;
/**
* @property {number} gravity - The World gravity setting.
*/
this.gravity = 0.2;
/**
* @property {Phaser.Rectangle} bounds - The bounds inside of which the physics world exists. Defaults to match the world bounds.
*/
this.bounds = new Phaser.Rectangle(0, 0, game.world.width, game.world.height);
/**
* @property {Phaser.QuadTree} quadTree - The world QuadTree.
*/
// this.quadTree = new Phaser.Physics.Ninja.QuadTree(this, this.game.world.bounds.x, this.game.world.bounds.y, this.game.world.bounds.width, this.game.world.bounds.height, this.maxObjects, this.maxLevels);
/**
* @property {Array} _mapData - Internal cache var.
* @private
*/
this._mapData = [];
};
Phaser.Physics.Ninja.prototype.constructor = Phaser.Physics.Ninja;
Phaser.Physics.Ninja.prototype = {
/**
* This will create a Ninja Physics AABB body on the given game object. Its dimensions will match the width and height of the object at the point it is created.
* 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.
*
* @method Phaser.Physics.Ninja#enableAABB
* @param {object|array} object - The game object to create the physics body on. Can also be an array of objects, a body will be created on every object in the array.
*/
enableAABB: function (object) {
this.enable(object, 1);
},
/**
* This will create a Ninja Physics Circle 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 object is destroyed.
*
* @method Phaser.Physics.Ninja#enableCircle
* @param {object|array} object - The game object to create the physics body on. Can also be an array of objects, a body will be created on every object in the array.
* @param {number} radius - The radius of the Circle.
*/
enableCircle: function (object, radius) {
this.enable(object, 2, 0, radius);
},
/**
* This will create a Ninja Physics Tile body on the given game object. There are 34 different types of tile you can create, including 45 degree slopes,
* convex and concave circles and more. The id parameter controls which Tile type is created, but you can also change it at run-time.
* Note that for all degree based tile types they need to have an equal width and height. If the given object doesn't have equal width and height it will use the width.
* 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.
*
* @method Phaser.Physics.Ninja#enableTile
* @param {object|array} object - The game object to create the physics body on. Can also be an array of objects, a body will be created on every object in the array.
* @param {number} [id=1] - The type of Tile this will use, i.e. Phaser.Physics.Ninja.Tile.SLOPE_45DEGpn, Phaser.Physics.Ninja.Tile.CONVEXpp, etc.
*/
enableTile: function (object, id) {
this.enable(object, 3, id);
},
/**
* This will create a Ninja Physics Tile body on the given game object. There are 34 different types of tile you can create, including 45 degree slopes,
* convex and concave circles and more. The id parameter controls which Tile type is created, but you can also change it at run-time.
* Note that for all degree based tile types they need to have an equal width and height. If the given object doesn't have equal width and height it will use the width.
* 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.
*
* @method Phaser.Physics.Ninja#enable
* @param {object|array} object - The game object to create the physics body on. Can also be an array of objects, a body will be created on every object in the array.
* @param {number} [type=1] - The type of Ninja shape to create. 1 = AABB, 2 = Circle or 3 = Tile.
* @param {number} [id=1] - If this body is using a Tile shape, you can set the Tile id here, i.e. Phaser.Physics.Ninja.Tile.SLOPE_45DEGpn, Phaser.Physics.Ninja.Tile.CONVEXpp, etc.
* @param {number} [radius=0] - If this body is using a Circle shape this controls the radius.
*/
enable: function (object, type, id, radius) {
if (typeof type === 'undefined') { type = 1; }
if (typeof id === 'undefined') { id = 1; }
var i = 1;
if (Array.isArray(object))
{
// Add to Group
i = object.length;
}
else
{
object = [object];
}
while (i--)
{
if (object[i].body === null)
{
object[i].body = new Phaser.Physics.Ninja.Body(this, object[i], type, id, radius);
object[i].anchor.set(0.5);
}
}
},
/**
* Updates the size of this physics world.
*
* @method Phaser.Physics.Ninja#setBounds
* @param {number} x - Top left most corner of the world.
* @param {number} y - Top left most corner of the world.
* @param {number} width - New width of the world. Can never be smaller than the Game.width.
* @param {number} height - New height of the world. Can never be smaller than the Game.height.
*/
setBounds: function (x, y, width, height) {
this.bounds.setTo(x, y, width, height);
},
/**
* Updates the size of this physics world to match the size of the game world.
*
* @method Phaser.Physics.Ninja#setBoundsToWorld
*/
setBoundsToWorld: function () {
this.bounds.setTo(this.game.world.bounds.x, this.game.world.bounds.y, this.game.world.bounds.width, this.game.world.bounds.height);
},
/**
* Called automatically by a Physics body, it updates all motion related values on the Body.
*
* @method Phaser.Physics.Ninja#updateMotion
* @param {Phaser.Physics.Ninja.Body} The Body object to be updated.
update: function () {
},
*/
/**
* Checks for overlaps between two game objects. The objects can be Sprites, Groups or Emitters.
* You can perform Sprite vs. Sprite, Sprite vs. Group and Group vs. Group overlap checks.
* Unlike collide the objects are NOT automatically separated or have any physics applied, they merely test for overlap results.
* The second parameter can be an array of objects, of differing types.
*
* @method Phaser.Physics.Arcade#overlap
* @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter} object1 - The first object to check. Can be an instance of Phaser.Sprite, Phaser.Group or Phaser.Particles.Emitter.
* @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter|array} object2 - The second object or array of objects to check. Can be Phaser.Sprite, Phaser.Group or Phaser.Particles.Emitter.
* @param {function} [overlapCallback=null] - An optional callback function that is called if the objects overlap. The two objects will be passed to this function in the same order in which you specified them.
* @param {function} [processCallback=null] - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then overlapCallback will only be called if processCallback returns true.
* @param {object} [callbackContext] - The context in which to run the callbacks.
* @returns {boolean} True if an overlap occured otherwise false.
*/
overlap: function (object1, object2, overlapCallback, processCallback, callbackContext) {
overlapCallback = overlapCallback || null;
processCallback = processCallback || null;
callbackContext = callbackContext || overlapCallback;
this._result = false;
this._total = 0;
if (Array.isArray(object2))
{
for (var i = 0, len = object2.length; i < len; i++)
{
this.collideHandler(object1, object2[i], overlapCallback, processCallback, callbackContext, true);
}
}
else
{
this.collideHandler(object1, object2, overlapCallback, processCallback, callbackContext, true);
}
return (this._total > 0);
},
/**
* Checks for collision between two game objects. You can perform Sprite vs. Sprite, Sprite vs. Group, Group vs. Group, Sprite vs. Tilemap Layer or Group vs. Tilemap Layer collisions.
* The second parameter can be an array of objects, of differing types.
* The objects are also automatically separated. If you don't require separation then use ArcadePhysics.overlap instead.
* An optional processCallback can be provided. If given this function will be called when two sprites are found to be colliding. It is called before any separation takes place,
* giving you the chance to perform additional checks. If the function returns true then the collision and separation is carried out. If it returns false it is skipped.
* The collideCallback is an optional function that is only called if two sprites collide. If a processCallback has been set then it needs to return true for collideCallback to be called.
*
* @method Phaser.Physics.Ninja#collide
* @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter|Phaser.Tilemap} object1 - The first object to check. Can be an instance of Phaser.Sprite, Phaser.Group, Phaser.Particles.Emitter, or Phaser.Tilemap.
* @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter|Phaser.Tilemap|array} object2 - The second object or array of objects to check. Can be Phaser.Sprite, Phaser.Group, Phaser.Particles.Emitter or Phaser.Tilemap.
* @param {function} [collideCallback=null] - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them.
* @param {function} [processCallback=null] - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them.
* @param {object} [callbackContext] - The context in which to run the callbacks.
* @returns {boolean} True if a collision occured otherwise false.
*/
collide: function (object1, object2, collideCallback, processCallback, callbackContext) {
collideCallback = collideCallback || null;
processCallback = processCallback || null;
callbackContext = callbackContext || collideCallback;
this._result = false;
this._total = 0;
if (Array.isArray(object2))
{
for (var i = 0, len = object2.length; i < len; i++)
{
this.collideHandler(object1, object2[i], collideCallback, processCallback, callbackContext, false);
}
}
else
{
this.collideHandler(object1, object2, collideCallback, processCallback, callbackContext, false);
}
return (this._total > 0);
},
/**
* Internal collision handler.
*
* @method Phaser.Physics.Arcade#collideHandler
* @private
* @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter|Phaser.Tilemap} object1 - The first object to check. Can be an instance of Phaser.Sprite, Phaser.Group, Phaser.Particles.Emitter, or Phaser.Tilemap.
* @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter|Phaser.Tilemap} object2 - The second object to check. Can be an instance of Phaser.Sprite, Phaser.Group, Phaser.Particles.Emitter or Phaser.Tilemap. Can also be an array of objects to check.
* @param {function} collideCallback - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them.
* @param {function} processCallback - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them.
* @param {object} callbackContext - The context in which to run the callbacks.
* @param {boolean} overlapOnly - Just run an overlap or a full collision.
*/
collideHandler: function (object1, object2, collideCallback, processCallback, callbackContext, overlapOnly) {
// Only collide valid objects
if (typeof object2 === 'undefined' && (object1.type === Phaser.GROUP || object1.type === Phaser.EMITTER))
{
this.collideGroupVsSelf(object1, collideCallback, processCallback, callbackContext, overlapOnly);
return;
}
if (object1 && object2 && object1.exists && object2.exists)
{
// SPRITES
if (object1.type == Phaser.SPRITE || object1.type == Phaser.TILESPRITE)
{
if (object2.type == Phaser.SPRITE || object2.type == Phaser.TILESPRITE)
{
this.collideSpriteVsSprite(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly);
}
else if (object2.type == Phaser.GROUP || object2.type == Phaser.EMITTER)
{
this.collideSpriteVsGroup(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly);
}
else if (object2.type == Phaser.TILEMAPLAYER)
{
this.collideSpriteVsTilemapLayer(object1, object2, collideCallback, processCallback, callbackContext);
}
}
// GROUPS
else if (object1.type == Phaser.GROUP)
{
if (object2.type == Phaser.SPRITE || object2.type == Phaser.TILESPRITE)
{
this.collideSpriteVsGroup(object2, object1, collideCallback, processCallback, callbackContext, overlapOnly);
}
else if (object2.type == Phaser.GROUP || object2.type == Phaser.EMITTER)
{
this.collideGroupVsGroup(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly);
}
else if (object2.type == Phaser.TILEMAPLAYER)
{
this.collideGroupVsTilemapLayer(object1, object2, collideCallback, processCallback, callbackContext);
}
}
// TILEMAP LAYERS
else if (object1.type == Phaser.TILEMAPLAYER)
{
if (object2.type == Phaser.SPRITE || object2.type == Phaser.TILESPRITE)
{
this.collideSpriteVsTilemapLayer(object2, object1, collideCallback, processCallback, callbackContext);
}
else if (object2.type == Phaser.GROUP || object2.type == Phaser.EMITTER)
{
this.collideGroupVsTilemapLayer(object2, object1, collideCallback, processCallback, callbackContext);
}
}
// EMITTER
else if (object1.type == Phaser.EMITTER)
{
if (object2.type == Phaser.SPRITE || object2.type == Phaser.TILESPRITE)
{
this.collideSpriteVsGroup(object2, object1, collideCallback, processCallback, callbackContext, overlapOnly);
}
else if (object2.type == Phaser.GROUP || object2.type == Phaser.EMITTER)
{
this.collideGroupVsGroup(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly);
}
else if (object2.type == Phaser.TILEMAPLAYER)
{
this.collideGroupVsTilemapLayer(object1, object2, collideCallback, processCallback, callbackContext);
}
}
}
},
/**
* An internal function. Use Phaser.Physics.Arcade.collide instead.
*
* @method Phaser.Physics.Arcade#collideSpriteVsSprite
* @private
*/
collideSpriteVsSprite: function (sprite1, sprite2, collideCallback, processCallback, callbackContext, overlapOnly) {
if (this.separate(sprite1.body, sprite2.body, processCallback, callbackContext, overlapOnly))
{
if (collideCallback)
{
collideCallback.call(callbackContext, sprite1, sprite2);
}
this._total++;
}
},
/**
* An internal function. Use Phaser.Physics.Arcade.collide instead.
*
* @method Phaser.Physics.Arcade#collideSpriteVsGroup
* @private
*/
collideSpriteVsGroup: function (sprite, group, collideCallback, processCallback, callbackContext, overlapOnly) {
if (group.length === 0)
{
return;
}
// What is the sprite colliding with in the quadtree?
// this.quadTree.clear();
// this.quadTree = new Phaser.QuadTree(this.game.world.bounds.x, this.game.world.bounds.y, this.game.world.bounds.width, this.game.world.bounds.height, this.maxObjects, this.maxLevels);
// this.quadTree.populate(group);
// this._potentials = this.quadTree.retrieve(sprite);
for (var i = 0, len = group.children.length; i < len; i++)
{
// We have our potential suspects, are they in this group?
if (group.children[i].exists && group.children[i].body && this.separate(sprite.body, group.children[i].body, processCallback, callbackContext, overlapOnly))
{
if (collideCallback)
{
collideCallback.call(callbackContext, sprite, group.children[i]);
}
this._total++;
}
}
},
/**
* An internal function. Use Phaser.Physics.Arcade.collide instead.
*
* @method Phaser.Physics.Arcade#collideGroupVsSelf
* @private
*/
collideGroupVsSelf: function (group, collideCallback, processCallback, callbackContext, overlapOnly) {
if (group.length === 0)
{
return;
}
var len = group.children.length;
for (var i = 0; i < len; i++)
{
for (var j = i + 1; j <= len; j++)
{
if (group.children[i] && group.children[j] && group.children[i].exists && group.children[j].exists)
{
this.collideSpriteVsSprite(group.children[i], group.children[j], collideCallback, processCallback, callbackContext, overlapOnly);
}
}
}
},
/**
* An internal function. Use Phaser.Physics.Arcade.collide instead.
*
* @method Phaser.Physics.Arcade#collideGroupVsGroup
* @private
*/
collideGroupVsGroup: function (group1, group2, collideCallback, processCallback, callbackContext, overlapOnly) {
if (group1.length === 0 || group2.length === 0)
{
return;
}
for (var i = 0, len = group1.children.length; i < len; i++)
{
if (group1.children[i].exists)
{
this.collideSpriteVsGroup(group1.children[i], group2, collideCallback, processCallback, callbackContext, overlapOnly);
}
}
},
/**
* The core separation function to separate two physics bodies.
* @method Phaser.Physics.Arcade#separate
* @param {Phaser.Physics.Arcade.Body} body1 - The Body object to separate.
* @param {Phaser.Physics.Arcade.Body} body2 - The Body object to separate.
* @param {function} [processCallback=null] - UN-USED: A callback function that lets you perform additional checks against the two objects if they overlap. If this function is set then the sprites will only be collided if it returns true.
* @param {object} [callbackContext] - UN-USED: The context in which to run the process callback.
* @returns {boolean} Returns true if the bodies collided, otherwise false.
*/
separate: function (body1, body2, processCallback, callbackContext, overlapOnly) {
if (body1.type !== Phaser.Physics.NINJA || body2.type !== Phaser.Physics.NINJA)
{
return false;
}
if (body1.aabb && body2.aabb)
{
return body1.aabb.collideAABBVsAABB(body2.aabb);
}
if (body1.aabb && body2.tile)
{
return body1.aabb.collideAABBVsTile(body2.tile);
}
if (body1.tile && body2.aabb)
{
return body2.aabb.collideAABBVsTile(body1.tile);
}
if (body1.circle && body2.tile)
{
return body1.circle.collideCircleVsTile(body2.tile);
}
if (body1.tile && body2.circle)
{
return body2.circle.collideCircleVsTile(body1.tile);
}
}
};
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2014 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* The Physics Body is linked to a single Sprite. All physics operations should be performed against the body rather than
* the Sprite itself. For example you can set the velocity, bounce values etc all on the Body.
*
* @class Phaser.Physics.Ninja.Body
* @classdesc Ninja Physics Body Constructor
* @constructor
* @param {Phaser.Physics.Ninja} system - The physics system this Body belongs to.
* @param {Phaser.Sprite} sprite - The Sprite object this physics body belongs to.
* @param {number} [type=1] - The type of Ninja shape to create. 1 = AABB, 2 = Circle or 3 = Tile.
* @param {number} [id=1] - If this body is using a Tile shape, you can set the Tile id here, i.e. Phaser.Physics.Ninja.Tile.SLOPE_45DEGpn, Phaser.Physics.Ninja.Tile.CONVEXpp, etc.
* @param {number} [radius=16] - If this body is using a Circle shape this controls the radius.
*/
Phaser.Physics.Ninja.Body = function (system, sprite, type, id, radius) {
if (typeof type === 'undefined') { type = 1; }
if (typeof id === 'undefined') { id = 1; }
if (typeof radius === 'undefined') { radius = 16; }
/**
* @property {Phaser.Sprite} sprite - Reference to the parent Sprite.
*/
this.sprite = sprite;
/**
* @property {Phaser.Game} game - Local reference to game.
*/
this.game = sprite.game;
/**
* @property {number} type - The type of physics system this body belongs to.
*/
this.type = Phaser.Physics.NINJA;
/**
* @property {Phaser.Physics.Ninja} system - The parent physics system.
*/
this.system = system;
/**
* @property {Phaser.Physics.Ninja.AABB} aabb - The AABB object this body is using for collision.
*/
this.aabb = null;
/**
* @property {Phaser.Physics.Ninja.Tile} tile - The Tile object this body is using for collision.
*/
this.tile = null;
/**
* @property {Phaser.Physics.Ninja.Circle} circle - The Circle object this body is using for collision.
*/
this.circle = null;
/**
* @property {object} shape - A local reference to the body shape.
*/
this.shape = null;
// Setting drag to 0 and friction to 0 means you get a normalised speed (px psec)
/**
* @property {number} drag - The drag applied to this object as it moves.
* @default
*/
this.drag = 1;
/**
* @property {number} friction - The friction applied to this object as it moves.
* @default
*/
this.friction = 0.05;
/**
* @property {number} gravityScale - How much of the world gravity should be applied to this object? 1 = all of it, 0.5 = 50%, etc.
* @default
*/
this.gravityScale = 1;
/**
* @property {number} bounce - The bounciness of this object when it collides. A value between 0 and 1. We recommend setting it to 0.999 to avoid jittering.
* @default
*/
this.bounce = 0.3;
/**
* @property {Phaser.Point} velocity - The velocity in pixels per second sq. of the Body.
*/
this.velocity = new Phaser.Point();
/**
* @property {boolean} skipQuadTree - If the Body is an irregular shape you can set this to true to avoid it being added to any QuadTrees.
* @default
*/
this.skipQuadTree = false;
/**
* @property {number} facing - A const reference to the direction the Body is traveling or facing.
* @default
*/
this.facing = Phaser.NONE;
/**
* @property {boolean} immovable - An immovable Body will not receive any impacts from other bodies.
* @default
*/
this.immovable = false;
/**
* A Body can be set to collide against the World bounds automatically and rebound back into the World if this is set to true. Otherwise it will leave the World.
* @property {boolean} collideWorldBounds - Should the Body collide with the World bounds?
*/
this.collideWorldBounds = true;
/**
* This object is populated with boolean values when the Body collides with another.
* touching.up = true means the collision happened to the top of this Body for example.
* @property {object} touching - An object containing touching results.
*/
this.touching = { none: true, up: false, down: false, left: false, right: false };
/**
* This object is populated with previous touching values from the bodies previous collision.
* @property {object} wasTouching - An object containing previous touching results.
*/
this.wasTouching = { none: true, up: false, down: false, left: false, right: false };
/**
* @property {number} maxSpeed - The maximum speed this body can travel at (taking drag and friction into account)
* @default
*/
this.maxSpeed = 8;
var sx = sprite.x;
var sy = sprite.y;
if (sprite.anchor.x === 0)
{
sx += (sprite.width * 0.5);
}
if (sprite.anchor.y === 0)
{
sy += (sprite.height * 0.5);
}
if (type === 1)
{
this.aabb = new Phaser.Physics.Ninja.AABB(this, sx, sy, sprite.width, sprite.height);
this.shape = this.aabb;
}
else if (type === 2)
{
this.circle = new Phaser.Physics.Ninja.Circle(this, sx, sy, radius);
this.shape = this.circle;
}
else if (type === 3)
{
this.tile = new Phaser.Physics.Ninja.Tile(this, sx, sy, sprite.width, sprite.height, id);
this.shape = this.tile;
}
};
Phaser.Physics.Ninja.Body.prototype = {
/**
* Internal method.
*
* @method Phaser.Physics.Ninja.Body#updateBounds
* @protected
*/
updateBounds: function (centerX, centerY, scaleX, scaleY) {
},
/**
* Internal method.
*
* @method Phaser.Physics.Ninja.Body#preUpdate
* @protected
*/
preUpdate: function () {
// Store and reset collision flags
this.wasTouching.none = this.touching.none;
this.wasTouching.up = this.touching.up;
this.wasTouching.down = this.touching.down;
this.wasTouching.left = this.touching.left;
this.wasTouching.right = this.touching.right;
this.touching.none = true;
this.touching.up = false;
this.touching.down = false;
this.touching.left = false;
this.touching.right = false;
this.shape.integrate();
if (this.collideWorldBounds)
{
this.shape.collideWorldBounds();
}
this.speed = Math.sqrt(this.shape.velocity.x * this.shape.velocity.x + this.shape.velocity.y * this.shape.velocity.y);
this.angle = Math.atan2(this.shape.velocity.y, this.shape.velocity.x);
},
/**
* Internal method.
*
* @method Phaser.Physics.Ninja.Body#postUpdate
* @protected
*/
postUpdate: function () {
if (this.sprite.type === Phaser.TILESPRITE)
{
// TileSprites don't use their anchor property, so we need to adjust the coordinates
this.sprite.x = this.shape.pos.x - this.shape.xw;
this.sprite.y = this.shape.pos.y - this.shape.yw;
}
else
{
this.sprite.x = this.shape.pos.x;
this.sprite.y = this.shape.pos.y;
}
},
/**
* Stops all movement of this body.
*
* @method Phaser.Physics.Ninja.Body#setZeroVelocity
*/
setZeroVelocity: function () {
this.shape.oldpos.x = this.shape.pos.x;
this.shape.oldpos.y = this.shape.pos.y;
},
/**
* Moves the Body forwards based on its current angle and the given speed.
* The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms).
*
* @method Phaser.Physics.Body#moveTo
* @param {number} speed - The speed at which it should move forwards.
* @param {number} angle - The angle in which it should move, given in degrees.
*/
moveTo: function (speed, angle) {
var magnitude = speed * this.game.time.physicsElapsed;
var angle = this.game.math.degToRad(angle);
this.shape.pos.x = this.shape.oldpos.x + (magnitude * Math.cos(angle));
this.shape.pos.y = this.shape.oldpos.y + (magnitude * Math.sin(angle));
},
/**
* Moves the Body backwards based on its current angle and the given speed.
* The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms).
*
* @method Phaser.Physics.Body#moveBackward
* @param {number} speed - The speed at which it should move backwards.
* @param {number} angle - The angle in which it should move, given in degrees.
*/
moveFrom: function (speed, angle) {
var magnitude = -speed * this.game.time.physicsElapsed;
var angle = this.game.math.degToRad(angle);
this.shape.pos.x = this.shape.oldpos.x + (magnitude * Math.cos(angle));
this.shape.pos.y = this.shape.oldpos.y + (magnitude * Math.sin(angle));
},
/**
* If this Body is dynamic then this will move it to the left by setting its x velocity to the given speed.
* The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms).
*
* @method Phaser.Physics.Body#moveLeft
* @param {number} speed - The speed at which it should move to the left, in pixels per second.
*/
moveLeft: function (speed) {
var fx = -speed * this.game.time.physicsElapsed;
this.shape.pos.x = this.shape.oldpos.x + Math.min(this.maxSpeed, Math.max(-this.maxSpeed, this.shape.pos.x - this.shape.oldpos.x + fx));
},
/**
* If this Body is dynamic then this will move it to the right by setting its x velocity to the given speed.
* The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms).
*
* @method Phaser.Physics.Body#moveRight
* @param {number} speed - The speed at which it should move to the right, in pixels per second.
*/
moveRight: function (speed) {
var fx = speed * this.game.time.physicsElapsed;
this.shape.pos.x = this.shape.oldpos.x + Math.min(this.maxSpeed, Math.max(-this.maxSpeed, this.shape.pos.x - this.shape.oldpos.x + fx));
},
/**
* If this Body is dynamic then this will move it up by setting its y velocity to the given speed.
* The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms).
*
* @method Phaser.Physics.Body#moveUp
* @param {number} speed - The speed at which it should move up, in pixels per second.
*/
moveUp: function (speed) {
var fx = -speed * this.game.time.physicsElapsed;
this.shape.pos.y = this.shape.oldpos.y + Math.min(this.maxSpeed, Math.max(-this.maxSpeed, this.shape.pos.y - this.shape.oldpos.y + fx));
},
/**
* If this Body is dynamic then this will move it down by setting its y velocity to the given speed.
* The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms).
*
* @method Phaser.Physics.Body#moveDown
* @param {number} speed - The speed at which it should move down, in pixels per second.
*/
moveDown: function (speed) {
var fx = speed * this.game.time.physicsElapsed;
this.shape.pos.y = this.shape.oldpos.y + Math.min(this.maxSpeed, Math.max(-this.maxSpeed, this.shape.pos.y - this.shape.oldpos.y + fx));
},
/**
* Resets all Body values (velocity, acceleration, rotation, etc)
*
* @method Phaser.Physics.Ninja.Body#reset
*/
reset: function () {
},
};
/**
* @name Phaser.Physics.Ninja.Body#x
* @property {number} x - The x position.
*/
Object.defineProperty(Phaser.Physics.Ninja.Body.prototype, "x", {
/**
* The x position.
* @method x
* @return {number}
*/
get: function () {
return this.shape.pos.x;
},
/**
* The x position.
* @method x
* @param {number} value
*/
set: function (value) {
this.shape.pos.x = value;
}
});
/**
* @name Phaser.Physics.Ninja.Body#y
* @property {number} y - The y position.
*/
Object.defineProperty(Phaser.Physics.Ninja.Body.prototype, "y", {
/**
* The y position.
* @method y
* @return {number}
*/
get: function () {
return this.shape.pos.y;
},
/**
* The y position.
* @method y
* @param {number} value
*/
set: function (value) {
this.shape.pos.y = value;
}
});
/**
* @name Phaser.Physics.Ninja.Body#width
* @property {number} width - The width of this Body
* @readonly
*/
Object.defineProperty(Phaser.Physics.Ninja.Body.prototype, "width", {
/**
* The width of this Body
* @method width
* @return {number}
* @readonly
*/
get: function () {
return this.shape.width;
}
});
/**
* @name Phaser.Physics.Ninja.Body#height
* @property {number} height - The height of this Body
* @readonly
*/
Object.defineProperty(Phaser.Physics.Ninja.Body.prototype, "height", {
/**
* The height of this Body
* @method height
* @return {number}
* @readonly
*/
get: function () {
return this.shape.height;
}
});
/**
* @name Phaser.Physics.Ninja.Body#bottom
* @property {number} bottom - The bottom value of this Body (same as Body.y + Body.height)
* @readonly
*/
Object.defineProperty(Phaser.Physics.Ninja.Body.prototype, "bottom", {
/**
* The sum of the y and height properties.
* @method bottom
* @return {number}
* @readonly
*/
get: function () {
return this.shape.pos.y + this.shape.height;
}
});
/**
* @name Phaser.Physics.Ninja.Body#right
* @property {number} right - The right value of this Body (same as Body.x + Body.width)
* @readonly
*/
Object.defineProperty(Phaser.Physics.Ninja.Body.prototype, "right", {
/**
* The sum of the x and width properties.
* @method right
* @return {number}
* @readonly
*/
get: function () {
return this.shape.pos.x + this.shape.width;
}
});
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2014 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* Ninja Physics AABB constructor.
* Note: This class could be massively optimised and reduced in size. I leave that challenge up to you.
*
* @class Phaser.Physics.Ninja.AABB
* @classdesc Arcade Physics Constructor
* @constructor
* @param {Phaser.Physics.Ninja.Body} body - The body that owns this shape.
* @param {number} x - The x coordinate to create this shape at.
* @param {number} y - The y coordinate to create this shape at.
* @param {number} width - The width of this AABB.
* @param {number} height - The height of this AABB.
*/
Phaser.Physics.Ninja.AABB = function (body, x, y, width, height) {
/**
* @property {Phaser.Physics.Ninja.Body} system - A reference to the body that owns this shape.
*/
this.body = body;
/**
* @property {Phaser.Physics.Ninja} system - A reference to the physics system.
*/
this.system = body.system;
/**
* @property {Phaser.Point} pos - The position of this object.
*/
this.pos = new Phaser.Point(x, y);
/**
* @property {Phaser.Point} oldpos - The position of this object in the previous update.
*/
this.oldpos = new Phaser.Point(x, y);
/**
* @property {number} xw - Half the width.
* @readonly
*/
this.xw = Math.abs(width / 2);
/**
* @property {number} xw - Half the height.
* @readonly
*/
this.yw = Math.abs(height / 2);
/**
* @property {number} width - The width.
* @readonly
*/
this.width = width;
/**
* @property {number} height - The height.
* @readonly
*/
this.height = height;
/**
* @property {number} oH - Internal var.
* @private
*/
this.oH = 0;
/**
* @property {number} oV - Internal var.
* @private
*/
this.oV = 0;
/**
* @property {Phaser.Point} velocity - The velocity of this object.
*/
this.velocity = new Phaser.Point();
/**
* @property {object} aabbTileProjections - All of the collision response handlers.
*/
this.aabbTileProjections = {};
this.aabbTileProjections[Phaser.Physics.Ninja.Tile.TYPE_FULL] = this.projAABB_Full;
this.aabbTileProjections[Phaser.Physics.Ninja.Tile.TYPE_45DEG] = this.projAABB_45Deg;
this.aabbTileProjections[Phaser.Physics.Ninja.Tile.TYPE_CONCAVE] = this.projAABB_Concave;
this.aabbTileProjections[Phaser.Physics.Ninja.Tile.TYPE_CONVEX] = this.projAABB_Convex;
this.aabbTileProjections[Phaser.Physics.Ninja.Tile.TYPE_22DEGs] = this.projAABB_22DegS;
this.aabbTileProjections[Phaser.Physics.Ninja.Tile.TYPE_22DEGb] = this.projAABB_22DegB;
this.aabbTileProjections[Phaser.Physics.Ninja.Tile.TYPE_67DEGs] = this.projAABB_67DegS;
this.aabbTileProjections[Phaser.Physics.Ninja.Tile.TYPE_67DEGb] = this.projAABB_67DegB;
this.aabbTileProjections[Phaser.Physics.Ninja.Tile.TYPE_HALF] = this.projAABB_Half;
};
Phaser.Physics.Ninja.AABB.prototype.constructor = Phaser.Physics.Ninja.AABB;
Phaser.Physics.Ninja.AABB.COL_NONE = 0;
Phaser.Physics.Ninja.AABB.COL_AXIS = 1;
Phaser.Physics.Ninja.AABB.COL_OTHER = 2;
Phaser.Physics.Ninja.AABB.prototype = {
/**
* Updates this AABBs position.
*
* @method Phaser.Physics.Ninja.AABB#integrate
*/
integrate: function () {
var px = this.pos.x;
var py = this.pos.y;
// integrate
this.pos.x += (this.body.drag * this.pos.x) - (this.body.drag * this.oldpos.x);
this.pos.y += (this.body.drag * this.pos.y) - (this.body.drag * this.oldpos.y) + (this.system.gravity * this.body.gravityScale);
// store
this.velocity.set(this.pos.x - px, this.pos.y - py);
this.oldpos.set(px, py);
},
/**
* Process a world collision and apply the resulting forces.
*
* @method Phaser.Physics.Ninja.AABB#reportCollisionVsWorld
* @param {number} px - The tangent velocity
* @param {number} py - The tangent velocity
* @param {number} dx - Collision normal
* @param {number} dy - Collision normal
* @param {number} obj - Object this AABB collided with
*/
reportCollisionVsWorld: function (px, py, dx, dy, obj) {
var p = this.pos;
var o = this.oldpos;
// Calc velocity
var vx = p.x - o.x;
var vy = p.y - o.y;
// Find component of velocity parallel to collision normal
var dp = (vx * dx + vy * dy);
var nx = dp * dx; //project velocity onto collision normal
var ny = dp * dy; //nx,ny is normal velocity
var tx = vx - nx; //px,py is tangent velocity
var ty = vy - ny;
// We only want to apply collision response forces if the object is travelling into, and not out of, the collision
var b, bx, by, fx, fy;
if (dp < 0)
{
fx = tx * this.body.friction;
fy = ty * this.body.friction;
b = 1 + this.body.bounce;
bx = (nx * b);
by = (ny * b);
if (dx === 1)
{
this.body.touching.left = true;
}
else if (dx === -1)
{
this.body.touching.right = true;
}
if (dy === 1)
{
this.body.touching.up = true;
}
else if (dy === -1)
{
this.body.touching.down = true;
}
}
else
{
// Moving out of collision, do not apply forces
bx = by = fx = fy = 0;
}
// Project object out of collision
p.x += px;
p.y += py;
// Apply bounce+friction impulses which alter velocity
o.x += px + bx + fx;
o.y += py + by + fy;
},
/**
* Process a body collision and apply the resulting forces.
*
* @method Phaser.Physics.Ninja.AABB#reportCollisionVsBody
* @param {number} px - The tangent velocity
* @param {number} py - The tangent velocity
* @param {number} dx - Collision normal
* @param {number} dy - Collision normal
* @param {number} obj - Object this AABB collided with
*/
reportCollisionVsBody: function (px, py, dx, dy, obj) {
// Here - we check if obj is immovable, etc and then we canswap the p/o values below depending on which is heavy
// But then still need to work out how to split force
var p = this.pos;
var o = this.oldpos;
// Calc velocity
var vx = p.x - o.x;
var vy = p.y - o.y;
// Find component of velocity parallel to collision normal
var dp = (vx * dx + vy * dy);
var nx = dp * dx; //project velocity onto collision normal
var ny = dp * dy; //nx,ny is normal velocity
var tx = vx - nx; //px,py is tangent velocity
var ty = vy - ny;
// We only want to apply collision response forces if the object is travelling into, and not out of, the collision
var b, bx, by, fx, fy;
if (dp < 0)
{
fx = tx * this.body.friction;
fy = ty * this.body.friction;
b = 1 + this.body.bounce;
bx = (nx * b);
by = (ny * b);
}
else
{
// Moving out of collision, do not apply forces
bx = by = fx = fy = 0;
}
// working version
// p.x += px;
// p.y += py;
// o.x += px + bx + fx;
// o.y += py + by + fy;
// Project object out of collision (applied to the position value)
p.x += px;
p.y += py;
// obj.pos.x += px;
// obj.pos.y += py;
// Apply bounce+friction impulses which alter velocity (applied to old position, thus setting a sort of velocity up)
var rx = px + bx + fx;
var ry = py + by + fy;
// let's pretend obj is immovable
// rx *= -1;
// ry *= -1;
// Now let's share the load
o.x += rx;
o.y += ry;
// work out objs velocity
// rx *= -1;
// ry *= -1;
// obj.oldpos.x += rx;
// obj.oldpos.y += ry;
// console.log(this.body.sprite.name, 'o.x', rx, ry, obj);
},
/**
* Collides this AABB against the world bounds.
*
* @method Phaser.Physics.Ninja.AABB#collideWorldBounds
*/
collideWorldBounds: function () {
var dx = this.system.bounds.x - (this.pos.x - this.xw);
if (0 < dx)
{
this.reportCollisionVsWorld(dx, 0, 1, 0, null);
}
else
{
dx = (this.pos.x + this.xw) - this.system.bounds.width;
if (0 < dx)
{
this.reportCollisionVsWorld(-dx, 0, -1, 0, null);
}
}
var dy = this.system.bounds.y - (this.pos.y - this.yw);
if (0 < dy)
{
this.reportCollisionVsWorld(0, dy, 0, 1, null);
}
else
{
dy = (this.pos.y + this.yw) - this.system.bounds.height;
if (0 < dy)
{
this.reportCollisionVsWorld(0, -dy, 0, -1, null);
}
}
},
/**
* Collides this AABB against a AABB.
*
* @method Phaser.Physics.Ninja.AABB#collideAABBVsAABB
* @param {Phaser.Physics.Ninja.AABB} aabb - The AABB to collide against.
*/
collideAABBVsAABB: function (aabb) {
var pos = this.pos;
var c = aabb;
var tx = c.pos.x;
var ty = c.pos.y;
var txw = c.xw;
var tyw = c.yw;
var dx = pos.x - tx;//tile->obj delta
var px = (txw + this.xw) - Math.abs(dx);//penetration depth in x
if (0 < px)
{
var dy = pos.y - ty;//tile->obj delta
var py = (tyw + this.yw) - Math.abs(dy);//pen depth in y
if (0 < py)
{
//object may be colliding with tile; call tile-specific collision function
//calculate projection vectors
if (px < py)
{
//project in x
if (dx < 0)
{
//project to the left
px *= -1;
py = 0;
}
else
{
//proj to right
py = 0;
}
}
else
{
//project in y
if (dy < 0)
{
//project up
px = 0;
py *= -1;
}
else
{
//project down
px = 0;
}
}
// return this.aabbTileProjections[1](px, py, this, c);
var l = Math.sqrt(px * px + py * py);
// this.reportCollisionVsWorld(px, py, px / l, py / l, c);
this.reportCollisionVsBody(px, py, px / l, py / l, c);
return Phaser.Physics.Ninja.AABB.COL_AXIS;
}
}
return false;
},
/**
* Collides this AABB against a Tile.
*
* @method Phaser.Physics.Ninja.AABB#collideAABBVsTile
* @param {Phaser.Physics.Ninja.Tile} tile - The Tile to collide against.
*/
collideAABBVsTile: function (tile) {
var pos = this.pos;
var c = tile;
var tx = c.pos.x;
var ty = c.pos.y;
var txw = c.xw;
var tyw = c.yw;
var dx = pos.x - tx;//tile->obj delta
var px = (txw + this.xw) - Math.abs(dx);//penetration depth in x
if (0 < px)
{
var dy = pos.y - ty;//tile->obj delta
var py = (tyw + this.yw) - Math.abs(dy);//pen depth in y
if (0 < py)
{
//object may be colliding with tile; call tile-specific collision function
//calculate projection vectors
if (px < py)
{
//project in x
if (dx < 0)
{
//project to the left
px *= -1;
py = 0;
}
else
{
//proj to right
py = 0;
}
}
else
{
//project in y
if (dy < 0)
{
//project up
px = 0;
py *= -1;
}
else
{
//project down
px = 0;
}
}
return this.resolveTile(px, py, this, c);
}
}
return false;
},
/**
* Resolves tile collision.
*
* @method Phaser.Physics.Ninja.AABB#resolveTile
* @param {number} x - Penetration depth on the x axis.
* @param {number} y - Penetration depth on the y axis.
* @param {Phaser.Physics.Ninja.AABB} body - The AABB involved in the collision.
* @param {Phaser.Physics.Ninja.Tile} tile - The Tile involved in the collision.
* @return {boolean} True if the collision was processed, otherwise false.
*/
resolveTile: function (x, y, body, tile) {
if (0 < tile.id)
{
return this.aabbTileProjections[tile.type](x, y, body, tile);
}
else
{
// console.warn("Ninja.AABB.resolveTile was called with an empty (or unknown) tile!: id=" + tile.id + ")");
return false;
}
},
/**
* Resolves Full tile collision.
*
* @method Phaser.Physics.Ninja.AABB#projAABB_Full
* @param {number} x - Penetration depth on the x axis.
* @param {number} y - Penetration depth on the y axis.
* @param {Phaser.Physics.Ninja.AABB} obj - The AABB involved in the collision.
* @param {Phaser.Physics.Ninja.Tile} t - The Tile involved in the collision.
* @return {number} The result of the collision.
*/
projAABB_Full: function (x, y, obj, t) {
var l = Math.sqrt(x * x + y * y);
obj.reportCollisionVsWorld(x, y, x / l, y / l, t);
return Phaser.Physics.Ninja.AABB.COL_AXIS;
},
/**
* Resolves Half tile collision.
*
* @method Phaser.Physics.Ninja.AABB#projAABB_Half
* @param {number} x - Penetration depth on the x axis.
* @param {number} y - Penetration depth on the y axis.
* @param {Phaser.Physics.Ninja.AABB} obj - The AABB involved in the collision.
* @param {Phaser.Physics.Ninja.Tile} t - The Tile involved in the collision.
* @return {number} The result of the collision.
*/
projAABB_Half: function (x, y, obj, t) {
//signx or signy must be 0; the other must be -1 or 1
//calculate the projection vector for the half-edge, and then
//(if collision is occuring) pick the minimum
var sx = t.signx;
var sy = t.signy;
var ox = (obj.pos.x - (sx*obj.xw)) - t.pos.x;//this gives is the coordinates of the innermost
var oy = (obj.pos.y - (sy*obj.yw)) - t.pos.y;//point on the AABB, relative to the tile center
//we perform operations analogous to the 45deg tile, except we're using
//an axis-aligned slope instead of an angled one..
//if the dotprod of (ox,oy) and (sx,sy) is negative, the corner is in the slope
//and we need toproject it out by the magnitude of the projection of (ox,oy) onto (sx,sy)
var dp = (ox*sx) + (oy*sy);
if (dp < 0)
{
//collision; project delta onto slope and use this to displace the object
sx *= -dp;//(sx,sy) is now the projection vector
sy *= -dp;
var lenN = Math.sqrt(sx*sx + sy*sy);
var lenP = Math.sqrt(x*x + y*y);
if (lenP < lenN)
{
//project along axis; note that we're assuming that this tile is horizontal OR vertical
//relative to the AABB's current tile, and not diagonal OR the current tile.
obj.reportCollisionVsWorld(x,y,x/lenP, y/lenP, t);
return Phaser.Physics.Ninja.AABB.COL_AXIS;
}
else
{
//note that we could use -= instead of -dp
obj.reportCollisionVsWorld(sx,sy,t.signx, t.signy, t);
return Phaser.Physics.Ninja.AABB.COL_OTHER;
}
}
return Phaser.Physics.Ninja.AABB.COL_NONE;
},
/**
* Resolves 45 Degree tile collision.
*
* @method Phaser.Physics.Ninja.AABB#projAABB_45Deg
* @param {number} x - Penetration depth on the x axis.
* @param {number} y - Penetration depth on the y axis.
* @param {Phaser.Physics.Ninja.AABB} obj - The AABB involved in the collision.
* @param {Phaser.Physics.Ninja.Tile} t - The Tile involved in the collision.
* @return {number} The result of the collision.
*/
projAABB_45Deg: function (x, y, obj, t) {
var signx = t.signx;
var signy = t.signy;
var ox = (obj.pos.x - (signx*obj.xw)) - t.pos.x;//this gives is the coordinates of the innermost
var oy = (obj.pos.y - (signy*obj.yw)) - t.pos.y;//point on the AABB, relative to the tile center
var sx = t.sx;
var sy = t.sy;
//if the dotprod of (ox,oy) and (sx,sy) is negative, the corner is in the slope
//and we need toproject it out by the magnitude of the projection of (ox,oy) onto (sx,sy)
var dp = (ox*sx) + (oy*sy);
if (dp < 0)
{
//collision; project delta onto slope and use this to displace the object
sx *= -dp;//(sx,sy) is now the projection vector
sy *= -dp;
var lenN = Math.sqrt(sx*sx + sy*sy);
var lenP = Math.sqrt(x*x + y*y);
if (lenP < lenN)
{
//project along axis
obj.reportCollisionVsWorld(x,y,x/lenP, y/lenP, t);
return Phaser.Physics.Ninja.AABB.COL_AXIS;
}
else
{
//project along slope
obj.reportCollisionVsWorld(sx,sy,t.sx,t.sy);
return Phaser.Physics.Ninja.AABB.COL_OTHER;
}
}
return Phaser.Physics.Ninja.AABB.COL_NONE;
},
/**
* Resolves 22 Degree tile collision.
*
* @method Phaser.Physics.Ninja.AABB#projAABB_22DegS
* @param {number} x - Penetration depth on the x axis.
* @param {number} y - Penetration depth on the y axis.
* @param {Phaser.Physics.Ninja.AABB} obj - The AABB involved in the collision.
* @param {Phaser.Physics.Ninja.Tile} t - The Tile involved in the collision.
* @return {number} The result of the collision.
*/
projAABB_22DegS: function (x, y, obj, t) {
var signx = t.signx;
var signy = t.signy;
//first we need to check to make sure we're colliding with the slope at all
var py = obj.pos.y - (signy*obj.yw);
var penY = t.pos.y - py;//this is the vector from the innermost point on the box to the highest point on
//the tile; if it is positive, this means the box is above the tile and
//no collision is occuring
if (0 < (penY*signy))
{
var ox = (obj.pos.x - (signx*obj.xw)) - (t.pos.x + (signx*t.xw));//this gives is the coordinates of the innermost
var oy = (obj.pos.y - (signy*obj.yw)) - (t.pos.y - (signy*t.yw));//point on the AABB, relative to a point on the slope
var sx = t.sx;//get slope unit normal
var sy = t.sy;
//if the dotprod of (ox,oy) and (sx,sy) is negative, the corner is in the slope
//and we need toproject it out by the magnitude of the projection of (ox,oy) onto (sx,sy)
var dp = (ox*sx) + (oy*sy);
if (dp < 0)
{
//collision; project delta onto slope and use this to displace the object
sx *= -dp;//(sx,sy) is now the projection vector
sy *= -dp;
var lenN = Math.sqrt(sx*sx + sy*sy);
var lenP = Math.sqrt(x*x + y*y);
var aY = Math.abs(penY);
if (lenP < lenN)
{
if (aY < lenP)
{
obj.reportCollisionVsWorld(0, penY, 0, penY/aY, t);
return Phaser.Physics.Ninja.AABB.COL_OTHER;
}
else
{
obj.reportCollisionVsWorld(x,y,x/lenP, y/lenP, t);
return Phaser.Physics.Ninja.AABB.COL_AXIS;
}
}
else
{
if (aY < lenN)
{
obj.reportCollisionVsWorld(0, penY, 0, penY/aY, t);
return Phaser.Physics.Ninja.AABB.COL_OTHER;
}
else
{
obj.reportCollisionVsWorld(sx,sy,t.sx,t.sy,t);
return Phaser.Physics.Ninja.AABB.COL_OTHER;
}
}
}
}
//if we've reached this point, no collision has occured
return Phaser.Physics.Ninja.AABB.COL_NONE;
},
/**
* Resolves 22 Degree tile collision.
*
* @method Phaser.Physics.Ninja.AABB#projAABB_22DegB
* @param {number} x - Penetration depth on the x axis.
* @param {number} y - Penetration depth on the y axis.
* @param {Phaser.Physics.Ninja.AABB} obj - The AABB involved in the collision.
* @param {Phaser.Physics.Ninja.Tile} t - The Tile involved in the collision.
* @return {number} The result of the collision.
*/
projAABB_22DegB: function (x, y, obj, t) {
var signx = t.signx;
var signy = t.signy;
var ox = (obj.pos.x - (signx*obj.xw)) - (t.pos.x - (signx*t.xw));//this gives is the coordinates of the innermost
var oy = (obj.pos.y - (signy*obj.yw)) - (t.pos.y + (signy*t.yw));//point on the AABB, relative to a point on the slope
var sx = t.sx;//get slope unit normal
var sy = t.sy;
//if the dotprod of (ox,oy) and (sx,sy) is negative, the corner is in the slope
//and we need toproject it out by the magnitude of the projection of (ox,oy) onto (sx,sy)
var dp = (ox*sx) + (oy*sy);
if (dp < 0)
{
//collision; project delta onto slope and use this to displace the object
sx *= -dp;//(sx,sy) is now the projection vector
sy *= -dp;
var lenN = Math.sqrt(sx*sx + sy*sy);
var lenP = Math.sqrt(x*x + y*y);
if (lenP < lenN)
{
obj.reportCollisionVsWorld(x,y,x/lenP, y/lenP, t);
return Phaser.Physics.Ninja.AABB.COL_AXIS;
}
else
{
obj.reportCollisionVsWorld(sx,sy,t.sx,t.sy,t);
return Phaser.Physics.Ninja.AABB.COL_OTHER;
}
}
return Phaser.Physics.Ninja.AABB.COL_NONE;
},
/**
* Resolves 67 Degree tile collision.
*
* @method Phaser.Physics.Ninja.AABB#projAABB_67DegS
* @param {number} x - Penetration depth on the x axis.
* @param {number} y - Penetration depth on the y axis.
* @param {Phaser.Physics.Ninja.AABB} obj - The AABB involved in the collision.
* @param {Phaser.Physics.Ninja.Tile} t - The Tile involved in the collision.
* @return {number} The result of the collision.
*/
projAABB_67DegS: function (x, y, obj, t) {
var signx = t.signx;
var signy = t.signy;
var px = obj.pos.x - (signx*obj.xw);
var penX = t.pos.x - px;
if (0 < (penX*signx))
{
var ox = (obj.pos.x - (signx*obj.xw)) - (t.pos.x - (signx*t.xw));//this gives is the coordinates of the innermost
var oy = (obj.pos.y - (signy*obj.yw)) - (t.pos.y + (signy*t.yw));//point on the AABB, relative to a point on the slope
var sx = t.sx;//get slope unit normal
var sy = t.sy;
//if the dotprod of (ox,oy) and (sx,sy) is negative, the corner is in the slope
//and we need to project it out by the magnitude of the projection of (ox,oy) onto (sx,sy)
var dp = (ox*sx) + (oy*sy);
if (dp < 0)
{
//collision; project delta onto slope and use this to displace the object
sx *= -dp;//(sx,sy) is now the projection vector
sy *= -dp;
var lenN = Math.sqrt(sx*sx + sy*sy);
var lenP = Math.sqrt(x*x + y*y);
var aX = Math.abs(penX);
if (lenP < lenN)
{
if (aX < lenP)
{
obj.reportCollisionVsWorld(penX, 0, penX/aX, 0, t);
return Phaser.Physics.Ninja.AABB.COL_OTHER;
}
else
{
obj.reportCollisionVsWorld(x,y,x/lenP, y/lenP, t);
return Phaser.Physics.Ninja.AABB.COL_AXIS;
}
}
else
{
if (aX < lenN)
{
obj.reportCollisionVsWorld(penX, 0, penX/aX, 0, t);
return Phaser.Physics.Ninja.AABB.COL_OTHER;
}
else
{
obj.reportCollisionVsWorld(sx,sy,t.sx,t.sy,t);
return Phaser.Physics.Ninja.AABB.COL_OTHER;
}
}
}
}
//if we've reached this point, no collision has occured
return Phaser.Physics.Ninja.AABB.COL_NONE;
},
/**
* Resolves 67 Degree tile collision.
*
* @method Phaser.Physics.Ninja.AABB#projAABB_67DegB
* @param {number} x - Penetration depth on the x axis.
* @param {number} y - Penetration depth on the y axis.
* @param {Phaser.Physics.Ninja.AABB} obj - The AABB involved in the collision.
* @param {Phaser.Physics.Ninja.Tile} t - The Tile involved in the collision.
* @return {number} The result of the collision.
*/
projAABB_67DegB: function (x, y, obj, t) {
var signx = t.signx;
var signy = t.signy;
var ox = (obj.pos.x - (signx*obj.xw)) - (t.pos.x + (signx*t.xw));//this gives is the coordinates of the innermost
var oy = (obj.pos.y - (signy*obj.yw)) - (t.pos.y - (signy*t.yw));//point on the AABB, relative to a point on the slope
var sx = t.sx;//get slope unit normal
var sy = t.sy;
//if the dotprod of (ox,oy) and (sx,sy) is negative, the corner is in the slope
//and we need toproject it out by the magnitude of the projection of (ox,oy) onto (sx,sy)
var dp = (ox*sx) + (oy*sy);
if (dp < 0)
{
//collision; project delta onto slope and use this to displace the object
sx *= -dp;//(sx,sy) is now the projection vector
sy *= -dp;
var lenN = Math.sqrt(sx*sx + sy*sy);
var lenP = Math.sqrt(x*x + y*y);
if (lenP < lenN)
{
obj.reportCollisionVsWorld(x,y,x/lenP, y/lenP, t);
return Phaser.Physics.Ninja.AABB.COL_AXIS;
}
else
{
obj.reportCollisionVsWorld(sx,sy,t.sx,t.sy,t);
return Phaser.Physics.Ninja.AABB.COL_OTHER;
}
}
return Phaser.Physics.Ninja.AABB.COL_NONE;
},
/**
* Resolves Convex tile collision.
*
* @method Phaser.Physics.Ninja.AABB#projAABB_Convex
* @param {number} x - Penetration depth on the x axis.
* @param {number} y - Penetration depth on the y axis.
* @param {Phaser.Physics.Ninja.AABB} obj - The AABB involved in the collision.
* @param {Phaser.Physics.Ninja.Tile} t - The Tile involved in the collision.
* @return {number} The result of the collision.
*/
projAABB_Convex: function (x, y, obj, t) {
//if distance from "innermost" corner of AABB is less than than tile radius,
//collision is occuring and we need to project
var signx = t.signx;
var signy = t.signy;
var ox = (obj.pos.x - (signx * obj.xw)) - (t.pos.x - (signx * t.xw));//(ox,oy) is the vector from the circle center to
var oy = (obj.pos.y - (signy * obj.yw)) - (t.pos.y - (signy * t.yw));//the AABB
var len = Math.sqrt(ox * ox + oy * oy);
var twid = t.xw * 2;
var rad = Math.sqrt(twid * twid + 0);//this gives us the radius of a circle centered on the tile's corner and extending to the opposite edge of the tile;
//note that this should be precomputed at compile-time since it's constant
var pen = rad - len;
if (((signx * ox) < 0) || ((signy * oy) < 0))
{
//the test corner is "outside" the 1/4 of the circle we're interested in
var lenP = Math.sqrt(x * x + y * y);
obj.reportCollisionVsWorld(x, y, x / lenP, y / lenP, t);
return Phaser.Physics.Ninja.AABB.COL_AXIS;//we need to report
}
else if (0 < pen)
{
//project along corner->circle vector
ox /= len;
oy /= len;
obj.reportCollisionVsWorld(ox * pen, oy * pen, ox, oy, t);
return Phaser.Physics.Ninja.AABB.COL_OTHER;
}
return Phaser.Physics.Ninja.AABB.COL_NONE;
},
/**
* Resolves Concave tile collision.
*
* @method Phaser.Physics.Ninja.AABB#projAABB_Concave
* @param {number} x - Penetration depth on the x axis.
* @param {number} y - Penetration depth on the y axis.
* @param {Phaser.Physics.Ninja.AABB} obj - The AABB involved in the collision.
* @param {Phaser.Physics.Ninja.Tile} t - The Tile involved in the collision.
* @return {number} The result of the collision.
*/
projAABB_Concave: function (x, y, obj, t) {
//if distance from "innermost" corner of AABB is further than tile radius,
//collision is occuring and we need to project
var signx = t.signx;
var signy = t.signy;
var ox = (t.pos.x + (signx * t.xw)) - (obj.pos.x - (signx * obj.xw));//(ox,oy) is the vector form the innermost AABB corner to the
var oy = (t.pos.y + (signy * t.yw)) - (obj.pos.y - (signy * obj.yw));//circle's center
var twid = t.xw * 2;
var rad = Math.sqrt(twid * twid + 0);//this gives us the radius of a circle centered on the tile's corner and extending to the opposite edge of the tile;
//note that this should be precomputed at compile-time since it's constant
var len = Math.sqrt(ox * ox + oy * oy);
var pen = len - rad;
if (0 < pen)
{
//collision; we need to either project along the axes, or project along corner->circlecenter vector
var lenP = Math.sqrt(x * x + y * y);
if (lenP < pen)
{
//it's shorter to move along axis directions
obj.reportCollisionVsWorld(x, y, x / lenP, y / lenP, t);
return Phaser.Physics.Ninja.AABB.COL_AXIS;
}
else
{
//project along corner->circle vector
ox /= len;//len should never be 0, since if it IS 0, rad should be > than len
oy /= len;//and we should never reach here
obj.reportCollisionVsWorld(ox * pen, oy * pen, ox, oy, t);
return Phaser.Physics.Ninja.AABB.COL_OTHER;
}
}
return Phaser.Physics.Ninja.AABB.COL_NONE;
}
}
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2014 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* Ninja Physics Tile constructor.
* A Tile is defined by its width, height and type. It's type can include slope data, such as 45 degree slopes, or convex slopes.
* Understand that for any type including a slope (types 2 to 29) the Tile must be SQUARE, i.e. have an equal width and height.
* Also note that as Tiles are primarily used for levels they have gravity disabled and world bounds collision disabled by default.
*
* Note: This class could be massively optimised and reduced in size. I leave that challenge up to you.
*
* @class Phaser.Physics.Ninja.Tile
* @classdesc The Ninja Physics Tile class. Based on code by Metanet Software.
* @constructor
* @param {Phaser.Physics.Ninja.Body} body - The body that owns this shape.
* @param {number} x - The x coordinate to create this shape at.
* @param {number} y - The y coordinate to create this shape at.
* @param {number} width - The width of this AABB.
* @param {number} height - The height of this AABB.
* @param {number} [type=1] - The type of Ninja shape to create. 1 = AABB, 2 = Circle or 3 = Tile.
*/
Phaser.Physics.Ninja.Tile = function (body, x, y, width, height, type) {
if (typeof type === 'undefined') { type = Phaser.Physics.Ninja.Tile.EMPTY; }
/**
* @property {Phaser.Physics.Ninja.Body} system - A reference to the body that owns this shape.
*/
this.body = body;
/**
* @property {Phaser.Physics.Ninja} system - A reference to the physics system.
*/
this.system = body.system;
/**
* @property {number} id - The ID of this Tile.
* @readonly
*/
this.id = type;
/**
* @property {number} type - The type of this Tile.
* @readonly
*/
this.type = Phaser.Physics.Ninja.Tile.TYPE_EMPTY;
/**
* @property {Phaser.Point} pos - The position of this object.
*/
this.pos = new Phaser.Point(x, y);
/**
* @property {Phaser.Point} oldpos - The position of this object in the previous update.
*/
this.oldpos = new Phaser.Point(x, y);
if (this.id > 1 && this.id < 30)
{
// Tile Types 2 to 29 require square tile dimensions, so use the width as the base
height = width;
}
/**
* @property {number} xw - Half the width.
* @readonly
*/
this.xw = Math.abs(width / 2);
/**
* @property {number} xw - Half the height.
* @readonly
*/
this.yw = Math.abs(height / 2);
/**
* @property {number} width - The width.
* @readonly
*/
this.width = width;
/**
* @property {number} height - The height.
* @readonly
*/
this.height = height;
/**
* @property {Phaser.Point} velocity - The velocity of this object.
*/
this.velocity = new Phaser.Point();
/**
* @property {number} signx - Internal var.
* @private
*/
this.signx = 0;
/**
* @property {number} signy - Internal var.
* @private
*/
this.signy = 0;
/**
* @property {number} sx - Internal var.
* @private
*/
this.sx = 0;
/**
* @property {number} sy - Internal var.
* @private
*/
this.sy = 0;
// By default Tiles disable gravity and world bounds collision
this.body.gravityScale = 0;
this.body.collideWorldBounds = false;
if (this.id > 0)
{
this.setType(this.id);
}
};
Phaser.Physics.Ninja.Tile.prototype.constructor = Phaser.Physics.Ninja.Tile;
Phaser.Physics.Ninja.Tile.prototype = {
/**
* Updates this objects position.
*
* @method Phaser.Physics.Ninja.Tile#integrate
*/
integrate: function () {
var px = this.pos.x;
var py = this.pos.y;
this.pos.x += (this.body.drag * this.pos.x) - (this.body.drag * this.oldpos.x);
this.pos.y += (this.body.drag * this.pos.y) - (this.body.drag * this.oldpos.y) + (this.system.gravity * this.body.gravityScale);
this.velocity.set(this.pos.x - px, this.pos.y - py);
this.oldpos.set(px, py);
},
/**
* Tiles cannot collide with the world bounds, it's up to you to keep them where you want them. But we need this API stub to satisfy the Body.
*
* @method Phaser.Physics.Ninja.Tile#collideWorldBounds
*/
collideWorldBounds: function () {
var dx = this.system.bounds.x - (this.pos.x - this.xw);
if (0 < dx)
{
this.reportCollisionVsWorld(dx, 0, 1, 0, null);
}
else
{
dx = (this.pos.x + this.xw) - this.system.bounds.width;
if (0 < dx)
{
this.reportCollisionVsWorld(-dx, 0, -1, 0, null);
}
}
var dy = this.system.bounds.y - (this.pos.y - this.yw);
if (0 < dy)
{
this.reportCollisionVsWorld(0, dy, 0, 1, null);
}
else
{
dy = (this.pos.y + this.yw) - this.system.bounds.height;
if (0 < dy)
{
this.reportCollisionVsWorld(0, -dy, 0, -1, null);
}
}
},
/**
* Process a world collision and apply the resulting forces.
*
* @method Phaser.Physics.Ninja.Tile#reportCollisionVsWorld
* @param {number} px - The tangent velocity
* @param {number} py - The tangent velocity
* @param {number} dx - Collision normal
* @param {number} dy - Collision normal
* @param {number} obj - Object this Tile collided with
*/
reportCollisionVsWorld: function (px, py, dx, dy, obj) {
var p = this.pos;
var o = this.oldpos;
// Calc velocity
var vx = p.x - o.x;
var vy = p.y - o.y;
// Find component of velocity parallel to collision normal
var dp = (vx * dx + vy * dy);
var nx = dp * dx; //project velocity onto collision normal
var ny = dp * dy; //nx,ny is normal velocity
var tx = vx - nx; //px,py is tangent velocity
var ty = vy - ny;
// We only want to apply collision response forces if the object is travelling into, and not out of, the collision
var b, bx, by, fx, fy;
if (dp < 0)
{
fx = tx * this.body.friction;
fy = ty * this.body.friction;
b = 1 + this.body.bounce;
bx = (nx * b);
by = (ny * b);
if (dx === 1)
{
this.body.touching.left = true;
}
else if (dx === -1)
{
this.body.touching.right = true;
}
if (dy === 1)
{
this.body.touching.up = true;
}
else if (dy === -1)
{
this.body.touching.down = true;
}
}
else
{
// Moving out of collision, do not apply forces
bx = by = fx = fy = 0;
}
// Project object out of collision
p.x += px;
p.y += py;
// Apply bounce+friction impulses which alter velocity
o.x += px + bx + fx;
o.y += py + by + fy;
},
/**
* Tiles cannot collide with the world bounds, it's up to you to keep them where you want them. But we need this API stub to satisfy the Body.
*
* @method Phaser.Physics.Ninja.Tile#setType
* @param {number} id - The type of Tile this will use, i.e. Phaser.Physics.Ninja.Tile.SLOPE_45DEGpn, Phaser.Physics.Ninja.Tile.CONVEXpp, etc.
*/
setType: function (id) {
if (id === Phaser.Physics.Ninja.Tile.EMPTY)
{
this.clear();
}
else
{
this.id = id;
this.updateType();
}
return this;
},
/**
* Sets this tile to be empty.
*
* @method Phaser.Physics.Ninja.Tile#clear
*/
clear: function () {
this.id = Phaser.Physics.Ninja.Tile.EMPTY;
this.updateType();
},
/**
* This converts a tile from implicitly-defined (via id), to explicit (via properties).
* Don't call directly, instead of setType.
*
* @method Phaser.Physics.Ninja.Tile#updateType
* @private
*/
updateType: function () {
if (this.id === 0)
{
//EMPTY
this.type = Phaser.Physics.Ninja.Tile.TYPE_EMPTY;
this.signx = 0;
this.signy = 0;
this.sx = 0;
this.sy = 0;
return true;
}
//tile is non-empty; collide
if (this.id < Phaser.Physics.Ninja.Tile.TYPE_45DEG)
{
//FULL
this.type = Phaser.Physics.Ninja.Tile.TYPE_FULL;
this.signx = 0;
this.signy = 0;
this.sx = 0;
this.sy = 0;
}
else if (this.id < Phaser.Physics.Ninja.Tile.TYPE_CONCAVE)
{
// 45deg
this.type = Phaser.Physics.Ninja.Tile.TYPE_45DEG;
if (this.id == Phaser.Physics.Ninja.Tile.SLOPE_45DEGpn)
{
this.signx = 1;
this.signy = -1;
this.sx = this.signx / Math.SQRT2;//get slope _unit_ normal
this.sy = this.signy / Math.SQRT2;//since normal is (1,-1), length is sqrt(1*1 + -1*-1) = sqrt(2)
}
else if (this.id == Phaser.Physics.Ninja.Tile.SLOPE_45DEGnn)
{
this.signx = -1;
this.signy = -1;
this.sx = this.signx / Math.SQRT2;//get slope _unit_ normal
this.sy = this.signy / Math.SQRT2;//since normal is (1,-1), length is sqrt(1*1 + -1*-1) = sqrt(2)
}
else if (this.id == Phaser.Physics.Ninja.Tile.SLOPE_45DEGnp)
{
this.signx = -1;
this.signy = 1;
this.sx = this.signx / Math.SQRT2;//get slope _unit_ normal
this.sy = this.signy / Math.SQRT2;//since normal is (1,-1), length is sqrt(1*1 + -1*-1) = sqrt(2)
}
else if (this.id == Phaser.Physics.Ninja.Tile.SLOPE_45DEGpp)
{
this.signx = 1;
this.signy = 1;
this.sx = this.signx / Math.SQRT2;//get slope _unit_ normal
this.sy = this.signy / Math.SQRT2;//since normal is (1,-1), length is sqrt(1*1 + -1*-1) = sqrt(2)
}
else
{
return false;
}
}
else if (this.id < Phaser.Physics.Ninja.Tile.TYPE_CONVEX)
{
// Concave
this.type = Phaser.Physics.Ninja.Tile.TYPE_CONCAVE;
if (this.id == Phaser.Physics.Ninja.Tile.CONCAVEpn)
{
this.signx = 1;
this.signy = -1;
this.sx = 0;
this.sy = 0;
}
else if (this.id == Phaser.Physics.Ninja.Tile.CONCAVEnn)
{
this.signx = -1;
this.signy = -1;
this.sx = 0;
this.sy = 0;
}
else if (this.id == Phaser.Physics.Ninja.Tile.CONCAVEnp)
{
this.signx = -1;
this.signy = 1;
this.sx = 0;
this.sy = 0;
}
else if (this.id == Phaser.Physics.Ninja.Tile.CONCAVEpp)
{
this.signx = 1;
this.signy = 1;
this.sx = 0;
this.sy = 0;
}
else
{
return false;
}
}
else if (this.id < Phaser.Physics.Ninja.Tile.TYPE_22DEGs)
{
// Convex
this.type = Phaser.Physics.Ninja.Tile.TYPE_CONVEX;
if (this.id == Phaser.Physics.Ninja.Tile.CONVEXpn)
{
this.signx = 1;
this.signy = -1;
this.sx = 0;
this.sy = 0;
}
else if (this.id == Phaser.Physics.Ninja.Tile.CONVEXnn)
{
this.signx = -1;
this.signy = -1;
this.sx = 0;
this.sy = 0;
}
else if (this.id == Phaser.Physics.Ninja.Tile.CONVEXnp)
{
this.signx = -1;
this.signy = 1;
this.sx = 0;
this.sy = 0;
}
else if (this.id == Phaser.Physics.Ninja.Tile.CONVEXpp)
{
this.signx = 1;
this.signy = 1;
this.sx = 0;
this.sy = 0;
}
else
{
return false;
}
}
else if (this.id < Phaser.Physics.Ninja.Tile.TYPE_22DEGb)
{
// 22deg small
this.type = Phaser.Physics.Ninja.Tile.TYPE_22DEGs;
if (this.id == Phaser.Physics.Ninja.Tile.SLOPE_22DEGpnS)
{
this.signx = 1;
this.signy = -1;
var slen = Math.sqrt(2 * 2 + 1 * 1);
this.sx = (this.signx * 1) / slen;
this.sy = (this.signy * 2) / slen;
}
else if (this.id == Phaser.Physics.Ninja.Tile.SLOPE_22DEGnnS)
{
this.signx = -1;
this.signy = -1;
var slen = Math.sqrt(2 * 2 + 1 * 1);
this.sx = (this.signx * 1) / slen;
this.sy = (this.signy * 2) / slen;
}
else if (this.id == Phaser.Physics.Ninja.Tile.SLOPE_22DEGnpS)
{
this.signx = -1;
this.signy = 1;
var slen = Math.sqrt(2 * 2 + 1 * 1);
this.sx = (this.signx * 1) / slen;
this.sy = (this.signy * 2) / slen;
}
else if (this.id == Phaser.Physics.Ninja.Tile.SLOPE_22DEGppS)
{
this.signx = 1;
this.signy = 1;
var slen = Math.sqrt(2 * 2 + 1 * 1);
this.sx = (this.signx * 1) / slen;
this.sy = (this.signy * 2) / slen;
}
else
{
return false;
}
}
else if (this.id < Phaser.Physics.Ninja.Tile.TYPE_67DEGs)
{
// 22deg big
this.type = Phaser.Physics.Ninja.Tile.TYPE_22DEGb;
if (this.id == Phaser.Physics.Ninja.Tile.SLOPE_22DEGpnB)
{
this.signx = 1;
this.signy = -1;
var slen = Math.sqrt(2 * 2 + 1 * 1);
this.sx = (this.signx * 1) / slen;
this.sy = (this.signy * 2) / slen;
}
else if (this.id == Phaser.Physics.Ninja.Tile.SLOPE_22DEGnnB)
{
this.signx = -1;
this.signy = -1;
var slen = Math.sqrt(2 * 2 + 1 * 1);
this.sx = (this.signx * 1) / slen;
this.sy = (this.signy * 2) / slen;
}
else if (this.id == Phaser.Physics.Ninja.Tile.SLOPE_22DEGnpB)
{
this.signx = -1;
this.signy = 1;
var slen = Math.sqrt(2 * 2 + 1 * 1);
this.sx = (this.signx * 1) / slen;
this.sy = (this.signy * 2) / slen;
}
else if (this.id == Phaser.Physics.Ninja.Tile.SLOPE_22DEGppB)
{
this.signx = 1;
this.signy = 1;
var slen = Math.sqrt(2 * 2 + 1 * 1);
this.sx = (this.signx * 1) / slen;
this.sy = (this.signy * 2) / slen;
}
else
{
return false;
}
}
else if (this.id < Phaser.Physics.Ninja.Tile.TYPE_67DEGb)
{
// 67deg small
this.type = Phaser.Physics.Ninja.Tile.TYPE_67DEGs;
if (this.id == Phaser.Physics.Ninja.Tile.SLOPE_67DEGpnS)
{
this.signx = 1;
this.signy = -1;
var slen = Math.sqrt(2 * 2 + 1 * 1);
this.sx = (this.signx * 2) / slen;
this.sy = (this.signy * 1) / slen;
}
else if (this.id == Phaser.Physics.Ninja.Tile.SLOPE_67DEGnnS)
{
this.signx = -1;
this.signy = -1;
var slen = Math.sqrt(2 * 2 + 1 * 1);
this.sx = (this.signx * 2) / slen;
this.sy = (this.signy * 1) / slen;
}
else if (this.id == Phaser.Physics.Ninja.Tile.SLOPE_67DEGnpS)
{
this.signx = -1;
this.signy = 1;
var slen = Math.sqrt(2 * 2 + 1 * 1);
this.sx = (this.signx * 2) / slen;
this.sy = (this.signy * 1) / slen;
}
else if (this.id == Phaser.Physics.Ninja.Tile.SLOPE_67DEGppS)
{
this.signx = 1;
this.signy = 1;
var slen = Math.sqrt(2 * 2 + 1 * 1);
this.sx = (this.signx * 2) / slen;
this.sy = (this.signy * 1) / slen;
}
else
{
return false;
}
}
else if (this.id < Phaser.Physics.Ninja.Tile.TYPE_HALF)
{
// 67deg big
this.type = Phaser.Physics.Ninja.Tile.TYPE_67DEGb;
if (this.id == Phaser.Physics.Ninja.Tile.SLOPE_67DEGpnB)
{
this.signx = 1;
this.signy = -1;
var slen = Math.sqrt(2 * 2 + 1 * 1);
this.sx = (this.signx * 2) / slen;
this.sy = (this.signy * 1) / slen;
}
else if (this.id == Phaser.Physics.Ninja.Tile.SLOPE_67DEGnnB)
{
this.signx = -1;
this.signy = -1;
var slen = Math.sqrt(2 * 2 + 1 * 1);
this.sx = (this.signx * 2) / slen;
this.sy = (this.signy * 1) / slen;
}
else if (this.id == Phaser.Physics.Ninja.Tile.SLOPE_67DEGnpB)
{
this.signx = -1;
this.signy = 1;
var slen = Math.sqrt(2 * 2 + 1 * 1);
this.sx = (this.signx * 2) / slen;
this.sy = (this.signy * 1) / slen;
}
else if (this.id == Phaser.Physics.Ninja.Tile.SLOPE_67DEGppB)
{
this.signx = 1;
this.signy = 1;
var slen = Math.sqrt(2 * 2 + 1 * 1);
this.sx = (this.signx * 2) / slen;
this.sy = (this.signy * 1) / slen;
}
else
{
return false;
}
}
else
{
// Half-full tile
this.type = Phaser.Physics.Ninja.Tile.TYPE_HALF;
if (this.id == Phaser.Physics.Ninja.Tile.HALFd)
{
this.signx = 0;
this.signy = -1;
this.sx = this.signx;
this.sy = this.signy;
}
else if (this.id == Phaser.Physics.Ninja.Tile.HALFu)
{
this.signx = 0;
this.signy = 1;
this.sx = this.signx;
this.sy = this.signy;
}
else if (this.id == Phaser.Physics.Ninja.Tile.HALFl)
{
this.signx = 1;
this.signy = 0;
this.sx = this.signx;
this.sy = this.signy;
}
else if (this.id == Phaser.Physics.Ninja.Tile.HALFr)
{
this.signx = -1;
this.signy = 0;
this.sx = this.signx;
this.sy = this.signy;
}
else
{
return false;
}
}
}
}
/**
* @name Phaser.Physics.Ninja.Tile#x
* @property {number} x - The x position.
*/
Object.defineProperty(Phaser.Physics.Ninja.Tile.prototype, "x", {
/**
* The x position.
* @method x
* @return {number}
*/
get: function () {
return this.pos.x - this.xw;
},
/**
* The x position.
* @method x
* @param {number} value
*/
set: function (value) {
this.pos.x = value;
}
});
/**
* @name Phaser.Physics.Ninja.Tile#y
* @property {number} y - The y position.
*/
Object.defineProperty(Phaser.Physics.Ninja.Tile.prototype, "y", {
/**
* The y position.
* @method y
* @return {number}
*/
get: function () {
return this.pos.y - this.yw;
},
/**
* The y position.
* @method y
* @param {number} value
*/
set: function (value) {
this.pos.y = value;
}
});
/**
* @name Phaser.Physics.Ninja.Tile#bottom
* @property {number} bottom - The bottom value of this Body (same as Body.y + Body.height)
* @readonly
*/
Object.defineProperty(Phaser.Physics.Ninja.Tile.prototype, "bottom", {
/**
* The sum of the y and height properties.
* @method bottom
* @return {number}
* @readonly
*/
get: function () {
return this.pos.y + this.yw;
}
});
/**
* @name Phaser.Physics.Ninja.Tile#right
* @property {number} right - The right value of this Body (same as Body.x + Body.width)
* @readonly
*/
Object.defineProperty(Phaser.Physics.Ninja.Tile.prototype, "right", {
/**
* The sum of the x and width properties.
* @method right
* @return {number}
* @readonly
*/
get: function () {
return this.pos.x + this.xw;
}
});
Phaser.Physics.Ninja.Tile.EMPTY = 0;
Phaser.Physics.Ninja.Tile.FULL = 1;//fullAABB tile
Phaser.Physics.Ninja.Tile.SLOPE_45DEGpn = 2;//45-degree triangle, whose normal is (+ve,-ve)
Phaser.Physics.Ninja.Tile.SLOPE_45DEGnn = 3;//(+ve,+ve)
Phaser.Physics.Ninja.Tile.SLOPE_45DEGnp = 4;//(-ve,+ve)
Phaser.Physics.Ninja.Tile.SLOPE_45DEGpp = 5;//(-ve,-ve)
Phaser.Physics.Ninja.Tile.CONCAVEpn = 6;//1/4-circle cutout
Phaser.Physics.Ninja.Tile.CONCAVEnn = 7;
Phaser.Physics.Ninja.Tile.CONCAVEnp = 8;
Phaser.Physics.Ninja.Tile.CONCAVEpp = 9;
Phaser.Physics.Ninja.Tile.CONVEXpn = 10;//1/4/circle
Phaser.Physics.Ninja.Tile.CONVEXnn = 11;
Phaser.Physics.Ninja.Tile.CONVEXnp = 12;
Phaser.Physics.Ninja.Tile.CONVEXpp = 13;
Phaser.Physics.Ninja.Tile.SLOPE_22DEGpnS = 14;//22.5 degree slope
Phaser.Physics.Ninja.Tile.SLOPE_22DEGnnS = 15;
Phaser.Physics.Ninja.Tile.SLOPE_22DEGnpS = 16;
Phaser.Physics.Ninja.Tile.SLOPE_22DEGppS = 17;
Phaser.Physics.Ninja.Tile.SLOPE_22DEGpnB = 18;
Phaser.Physics.Ninja.Tile.SLOPE_22DEGnnB = 19;
Phaser.Physics.Ninja.Tile.SLOPE_22DEGnpB = 20;
Phaser.Physics.Ninja.Tile.SLOPE_22DEGppB = 21;
Phaser.Physics.Ninja.Tile.SLOPE_67DEGpnS = 22;//67.5 degree slope
Phaser.Physics.Ninja.Tile.SLOPE_67DEGnnS = 23;
Phaser.Physics.Ninja.Tile.SLOPE_67DEGnpS = 24;
Phaser.Physics.Ninja.Tile.SLOPE_67DEGppS = 25;
Phaser.Physics.Ninja.Tile.SLOPE_67DEGpnB = 26;
Phaser.Physics.Ninja.Tile.SLOPE_67DEGnnB = 27;
Phaser.Physics.Ninja.Tile.SLOPE_67DEGnpB = 28;
Phaser.Physics.Ninja.Tile.SLOPE_67DEGppB = 29;
Phaser.Physics.Ninja.Tile.HALFd = 30;//half-full tiles
Phaser.Physics.Ninja.Tile.HALFr = 31;
Phaser.Physics.Ninja.Tile.HALFu = 32;
Phaser.Physics.Ninja.Tile.HALFl = 33;
Phaser.Physics.Ninja.Tile.TYPE_EMPTY = 0;
Phaser.Physics.Ninja.Tile.TYPE_FULL = 1;
Phaser.Physics.Ninja.Tile.TYPE_45DEG = 2;
Phaser.Physics.Ninja.Tile.TYPE_CONCAVE = 6;
Phaser.Physics.Ninja.Tile.TYPE_CONVEX = 10;
Phaser.Physics.Ninja.Tile.TYPE_22DEGs = 14;
Phaser.Physics.Ninja.Tile.TYPE_22DEGb = 18;
Phaser.Physics.Ninja.Tile.TYPE_67DEGs = 22;
Phaser.Physics.Ninja.Tile.TYPE_67DEGb = 26;
Phaser.Physics.Ninja.Tile.TYPE_HALF = 30;
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2014 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* Ninja Physics Circle constructor.
* Note: This class could be massively optimised and reduced in size. I leave that challenge up to you.
*
* @class Phaser.Physics.Ninja.Circle
* @classdesc Arcade Physics Constructor
* @constructor
* @param {Phaser.Physics.Ninja.Body} body - The body that owns this shape.
* @param {number} x - The x coordinate to create this shape at.
* @param {number} y - The y coordinate to create this shape at.
* @param {number} radius - The radius of this Circle.
*/
Phaser.Physics.Ninja.Circle = function (body, x, y, radius) {
/**
* @property {Phaser.Physics.Ninja.Body} system - A reference to the body that owns this shape.
*/
this.body = body;
/**
* @property {Phaser.Physics.Ninja} system - A reference to the physics system.
*/
this.system = body.system;
/**
* @property {Phaser.Point} pos - The position of this object.
*/
this.pos = new Phaser.Point(x, y);
/**
* @property {Phaser.Point} oldpos - The position of this object in the previous update.
*/
this.oldpos = new Phaser.Point(x, y);
/**
* @property {number} radius - The radius of this circle shape.
*/
this.radius = radius;
/**
* @property {number} width - The width.
* @readonly
*/
this.width = radius * 2;
/**
* @property {number} height - The height.
* @readonly
*/
this.height = radius * 2;
/**
* @property {number} oH - Internal var.
* @private
*/
this.oH = 0;
/**
* @property {number} oV - Internal var.
* @private
*/
this.oV = 0;
/**
* @property {Phaser.Point} velocity - The velocity of this object.
*/
this.velocity = new Phaser.Point();
/**
* @property {object} circleTileProjections - All of the collision response handlers.
*/
this.circleTileProjections = {};
this.circleTileProjections[Phaser.Physics.Ninja.Tile.TYPE_FULL] = this.projCircle_Full;
this.circleTileProjections[Phaser.Physics.Ninja.Tile.TYPE_45DEG] = this.projCircle_45Deg;
this.circleTileProjections[Phaser.Physics.Ninja.Tile.TYPE_CONCAVE] = this.projCircle_Concave;
this.circleTileProjections[Phaser.Physics.Ninja.Tile.TYPE_CONVEX] = this.projCircle_Convex;
this.circleTileProjections[Phaser.Physics.Ninja.Tile.TYPE_22DEGs] = this.projCircle_22DegS;
this.circleTileProjections[Phaser.Physics.Ninja.Tile.TYPE_22DEGb] = this.projCircle_22DegB;
this.circleTileProjections[Phaser.Physics.Ninja.Tile.TYPE_67DEGs] = this.projCircle_67DegS;
this.circleTileProjections[Phaser.Physics.Ninja.Tile.TYPE_67DEGb] = this.projCircle_67DegB;
this.circleTileProjections[Phaser.Physics.Ninja.Tile.TYPE_HALF] = this.projCircle_Half;
}
Phaser.Physics.Ninja.Circle.prototype.constructor = Phaser.Physics.Ninja.Circle;
Phaser.Physics.Ninja.Circle.COL_NONE = 0;
Phaser.Physics.Ninja.Circle.COL_AXIS = 1;
Phaser.Physics.Ninja.Circle.COL_OTHER = 2;
Phaser.Physics.Ninja.Circle.prototype = {
/**
* Updates this Circles position.
*
* @method Phaser.Physics.Ninja.Circle#integrate
*/
integrate: function () {
var px = this.pos.x;
var py = this.pos.y;
// integrate
this.pos.x += (this.body.drag * this.pos.x) - (this.body.drag * this.oldpos.x);
this.pos.y += (this.body.drag * this.pos.y) - (this.body.drag * this.oldpos.y) + (this.system.gravity * this.body.gravityScale);
// store
this.velocity.set(this.pos.x - px, this.pos.y - py);
this.oldpos.set(px, py);
},
/**
* Process a world collision and apply the resulting forces.
*
* @method Phaser.Physics.Ninja.Circle#reportCollisionVsWorld
* @param {number} px - The tangent velocity
* @param {number} py - The tangent velocity
* @param {number} dx - Collision normal
* @param {number} dy - Collision normal
* @param {number} obj - Object this Circle collided with
*/
reportCollisionVsWorld: function (px, py, dx, dy, obj) {
var p = this.pos;
var o = this.oldpos;
// Calc velocity
var vx = p.x - o.x;
var vy = p.y - o.y;
// Find component of velocity parallel to collision normal
var dp = (vx * dx + vy * dy);
var nx = dp * dx; //project velocity onto collision normal
var ny = dp * dy; //nx,ny is normal velocity
var tx = vx - nx; //px,py is tangent velocity
var ty = vy - ny;
// We only want to apply collision response forces if the object is travelling into, and not out of, the collision
var b, bx, by, fx, fy;
if (dp < 0)
{
fx = tx * this.body.friction;
fy = ty * this.body.friction;
b = 1 + this.body.bounce;
bx = (nx * b);
by = (ny * b);
if (dx === 1)
{
this.body.touching.left = true;
}
else if (dx === -1)
{
this.body.touching.right = true;
}
if (dy === 1)
{
this.body.touching.up = true;
}
else if (dy === -1)
{
this.body.touching.down = true;
}
}
else
{
// Moving out of collision, do not apply forces
bx = by = fx = fy = 0;
}
// Project object out of collision
p.x += px;
p.y += py;
// Apply bounce+friction impulses which alter velocity
o.x += px + bx + fx;
o.y += py + by + fy;
},
/**
* Collides this Circle against the world bounds.
*
* @method Phaser.Physics.Ninja.Circle#collideWorldBounds
*/
collideWorldBounds: function () {
var dx = this.system.bounds.x - (this.pos.x - this.xw);
if (0 < dx)
{
this.reportCollisionVsWorld(dx, 0, 1, 0, null);
}
else
{
dx = (this.pos.x + this.xw) - this.system.bounds.width;
if (0 < dx)
{
this.reportCollisionVsWorld(-dx, 0, -1, 0, null);
}
}
var dy = this.system.bounds.y - (this.pos.y - this.yw);
if (0 < dy)
{
this.reportCollisionVsWorld(0, dy, 0, 1, null);
}
else
{
dy = (this.pos.y + this.yw) - this.system.bounds.height;
if (0 < dy)
{
this.reportCollisionVsWorld(0, -dy, 0, -1, null);
}
}
},
/**
* Collides this Circle with a Tile.
*
* @method Phaser.Physics.Ninja.Circle#collideCircleVsTile
* @param {Phaser.Physics.Ninja.Tile} t - The Tile involved in the collision.
* @return {boolean} True if they collide, otherwise false.
*/
collideCircleVsTile: function (tile) {
var pos = this.pos;
var r = this.radius;
var c = tile;
var tx = c.pos.x;
var ty = c.pos.y;
var txw = c.xw;
var tyw = c.yw;
var dx = pos.x - tx; // tile->obj delta
var px = (txw + r) - Math.abs(dx); // penetration depth in x
if (0 < px)
{
var dy = pos.y - ty; // tile->obj delta
var py = (tyw + r) - Math.abs(dy); // pen depth in y
if (0 < py)
{
// object may be colliding with tile
// determine grid/voronoi region of circle center
this.oH = 0;
this.oV = 0;
if (dx < -txw)
{
// circle is on left side of tile
this.oH = -1;
}
else if (txw < dx)
{
// circle is on right side of tile
this.oH = 1;
}
if (dy < -tyw)
{
// circle is on top side of tile
this.oV = -1;
}
else if (tyw < dy)
{
// circle is on bottom side of tile
this.oV = 1;
}
return this.resolveCircleTile(px, py, this.oH, this.oV, this, c);
}
}
},
/**
* Resolves tile collision.
*
* @method Phaser.Physics.Ninja.Circle#resolveCircleTile
* @param {number} x - Penetration depth on the x axis.
* @param {number} y - Penetration depth on the y axis.
* @param {number} oH - Grid / voronoi region.
* @param {number} oV - Grid / voronoi region.
* @param {Phaser.Physics.Ninja.Circle} obj - The Circle involved in the collision.
* @param {Phaser.Physics.Ninja.Tile} t - The Tile involved in the collision.
* @return {number} The result of the collision.
*/
resolveCircleTile: function (x, y, oH, oV, obj, t) {
if (0 < t.id)
{
return this.circleTileProjections[t.type](x, y, oH, oV, obj, t);
}
else
{
// console.log("ResolveCircleTile() was called with an empty (or unknown) tile!: ID=" + t.id + ")");
return false;
}
},
/**
* Resolves Full tile collision.
*
* @method Phaser.Physics.Ninja.Circle#projCircle_Full
* @param {number} x - Penetration depth on the x axis.
* @param {number} y - Penetration depth on the y axis.
* @param {number} oH - Grid / voronoi region.
* @param {number} oV - Grid / voronoi region.
* @param {Phaser.Physics.Ninja.Circle} obj - The Circle involved in the collision.
* @param {Phaser.Physics.Ninja.Tile} t - The Tile involved in the collision.
* @return {number} The result of the collision.
*/
projCircle_Full: function (x, y, oH, oV, obj, t) {
//if we're colliding vs. the current cell, we need to project along the
//smallest penetration vector.
//if we're colliding vs. horiz. or vert. neighb, we simply project horiz/vert
//if we're colliding diagonally, we need to collide vs. tile corner
if (oH == 0)
{
if (oV == 0)
{
//collision with current cell
if (x < y)
{
//penetration in x is smaller; project in x
var dx = obj.pos.x - t.pos.x;//get sign for projection along x-axis
//NOTE: should we handle the delta == 0 case?! and how? (project towards oldpos?)
if (dx < 0)
{
obj.reportCollisionVsWorld(-x, 0, -1, 0, t);
return Phaser.Physics.Ninja.Circle.COL_AXIS;
}
else
{
obj.reportCollisionVsWorld(x, 0, 1, 0, t);
return Phaser.Physics.Ninja.Circle.COL_AXIS;
}
}
else
{
//penetration in y is smaller; project in y
var dy = obj.pos.y - t.pos.y;//get sign for projection along y-axis
//NOTE: should we handle the delta == 0 case?! and how? (project towards oldpos?)
if (dy < 0)
{
obj.reportCollisionVsWorld(0, -y, 0, -1, t);
return Phaser.Physics.Ninja.Circle.COL_AXIS;
}
else
{
obj.reportCollisionVsWorld(0, y, 0, 1, t);
return Phaser.Physics.Ninja.Circle.COL_AXIS;
}
}
}
else
{
//collision with vertical neighbor
obj.reportCollisionVsWorld(0, y * oV, 0, oV, t);
return Phaser.Physics.Ninja.Circle.COL_AXIS;
}
}
else if (oV == 0)
{
//collision with horizontal neighbor
obj.reportCollisionVsWorld(x * oH, 0, oH, 0, t);
return Phaser.Physics.Ninja.Circle.COL_AXIS;
}
else
{
//diagonal collision
//get diag vertex position
var vx = t.pos.x + (oH * t.xw);
var vy = t.pos.y + (oV * t.yw);
var dx = obj.pos.x - vx;//calc vert->circle vector
var dy = obj.pos.y - vy;
var len = Math.sqrt(dx * dx + dy * dy);
var pen = obj.radius - len;
if (0 < pen)
{
//vertex is in the circle; project outward
if (len == 0)
{
//project out by 45deg
dx = oH / Math.SQRT2;
dy = oV / Math.SQRT2;
}
else
{
dx /= len;
dy /= len;
}
obj.reportCollisionVsWorld(dx * pen, dy * pen, dx, dy, t);
return Phaser.Physics.Ninja.Circle.COL_OTHER;
}
}
return Phaser.Physics.Ninja.Circle.COL_NONE;
},
/**
* Resolves 45 Degree tile collision.
*
* @method Phaser.Physics.Ninja.Circle#projCircle_45Deg
* @param {number} x - Penetration depth on the x axis.
* @param {number} y - Penetration depth on the y axis.
* @param {number} oH - Grid / voronoi region.
* @param {number} oV - Grid / voronoi region.
* @param {Phaser.Physics.Ninja.Circle} obj - The Circle involved in the collision.
* @param {Phaser.Physics.Ninja.Tile} t - The Tile involved in the collision.
* @return {number} The result of the collision.
*/
projCircle_45Deg: function (x, y, oH, oV, obj, t) {
//if we're colliding diagonally:
// -if obj is in the diagonal pointed to by the slope normal: we can't collide, do nothing
// -else, collide vs. the appropriate vertex
//if obj is in this tile: perform collision as for aabb-ve-45deg
//if obj is horiz OR very neighb in direction of slope: collide only vs. slope
//if obj is horiz or vert neigh against direction of slope: collide vs. face
var signx = t.signx;
var signy = t.signy;
var lenP;
if (oH == 0)
{
if (oV == 0)
{
//colliding with current tile
var sx = t.sx;
var sy = t.sy;
var ox = (obj.pos.x - (sx * obj.radius)) - t.pos.x;//this gives is the coordinates of the innermost
var oy = (obj.pos.y - (sy * obj.radius)) - t.pos.y;//point on the circle, relative to the tile center
//if the dotprod of (ox,oy) and (sx,sy) is negative, the innermost point is in the slope
//and we need toproject it out by the magnitude of the projection of (ox,oy) onto (sx,sy)
var dp = (ox * sx) + (oy * sy);
if (dp < 0)
{
//collision; project delta onto slope and use this as the slope penetration vector
sx *= -dp;//(sx,sy) is now the penetration vector
sy *= -dp;
//find the smallest axial projection vector
if (x < y)
{
//penetration in x is smaller
lenP = x;
y = 0;
//get sign for projection along x-axis
if ((obj.pos.x - t.pos.x) < 0)
{
x *= -1;
}
}
else
{
//penetration in y is smaller
lenP = y;
x = 0;
//get sign for projection along y-axis
if ((obj.pos.y - t.pos.y) < 0)
{
y *= -1;
}
}
var lenN = Math.sqrt(sx * sx + sy * sy);
if (lenP < lenN)
{
obj.reportCollisionVsWorld(x, y, x / lenP, y / lenP, t);
return Phaser.Physics.Ninja.Circle.COL_AXIS;
}
else
{
obj.reportCollisionVsWorld(sx, sy, t.sx, t.sy, t);
return Phaser.Physics.Ninja.Circle.COL_OTHER;
}
}
}
else
{
//colliding vertically
if ((signy * oV) < 0)
{
//colliding with face/edge
obj.reportCollisionVsWorld(0, y * oV, 0, oV, t);
return Phaser.Physics.Ninja.Circle.COL_AXIS;
}
else
{
//we could only be colliding vs the slope OR a vertex
//look at the vector form the closest vert to the circle to decide
var sx = t.sx;
var sy = t.sy;
var ox = obj.pos.x - (t.pos.x - (signx * t.xw));//this gives is the coordinates of the innermost
var oy = obj.pos.y - (t.pos.y + (oV * t.yw));//point on the circle, relative to the closest tile vert
//if the component of (ox,oy) parallel to the normal's righthand normal
//has the same sign as the slope of the slope (the sign of the slope's slope is signx*signy)
//then we project by the vertex, otherwise by the normal.
//note that this is simply a VERY tricky/weird method of determining
//if the circle is in side the slope/face's voronoi region, or that of the vertex.
var perp = (ox * -sy) + (oy * sx);
if (0 < (perp * signx * signy))
{
//collide vs. vertex
var len = Math.sqrt(ox * ox + oy * oy);
var pen = obj.radius - len;
if (0 < pen)
{
//note: if len=0, then perp=0 and we'll never reach here, so don't worry about div-by-0
ox /= len;
oy /= len;
obj.reportCollisionVsWorld(ox * pen, oy * pen, ox, oy, t);
return Phaser.Physics.Ninja.Circle.COL_OTHER;
}
}
else
{
//collide vs. slope
//if the component of (ox,oy) parallel to the normal is less than the circle radius, we're
//penetrating the slope. note that this method of penetration calculation doesn't hold
//in general (i.e it won't work if the circle is in the slope), but works in this case
//because we know the circle is in a neighboring cell
var dp = (ox * sx) + (oy * sy);
var pen = obj.radius - Math.abs(dp);//note: we don't need the abs because we know the dp will be positive, but just in case..
if (0 < pen)
{
//collision; circle out along normal by penetration amount
obj.reportCollisionVsWorld(sx * pen, sy * pen, sx, sy, t);
return Phaser.Physics.Ninja.Circle.COL_OTHER;
}
}
}
}
}
else if (oV == 0)
{
//colliding horizontally
if ((signx * oH) < 0)
{
//colliding with face/edge
obj.reportCollisionVsWorld(x * oH, 0, oH, 0, t);
return Phaser.Physics.Ninja.Circle.COL_AXIS;
}
else
{
//we could only be colliding vs the slope OR a vertex
//look at the vector form the closest vert to the circle to decide
var sx = t.sx;
var sy = t.sy;
var ox = obj.pos.x - (t.pos.x + (oH * t.xw));//this gives is the coordinates of the innermost
var oy = obj.pos.y - (t.pos.y - (signy * t.yw));//point on the circle, relative to the closest tile vert
//if the component of (ox,oy) parallel to the normal's righthand normal
//has the same sign as the slope of the slope (the sign of the slope's slope is signx*signy)
//then we project by the normal, otherwise by the vertex.
//(NOTE: this is the opposite logic of the vertical case;
// for vertical, if the perp prod and the slope's slope agree, it's outside.
// for horizontal, if the perp prod and the slope's slope agree, circle is inside.
// ..but this is only a property of flahs' coord system (i.e the rules might swap
// in righthanded systems))
//note that this is simply a VERY tricky/weird method of determining
//if the circle is in side the slope/face's voronio region, or that of the vertex.
var perp = (ox * -sy) + (oy * sx);
if ((perp * signx * signy) < 0)
{
//collide vs. vertex
var len = Math.sqrt(ox * ox + oy * oy);
var pen = obj.radius - len;
if (0 < pen)
{
//note: if len=0, then perp=0 and we'll never reach here, so don't worry about div-by-0
ox /= len;
oy /= len;
obj.reportCollisionVsWorld(ox * pen, oy * pen, ox, oy, t);
return Phaser.Physics.Ninja.Circle.COL_OTHER;
}
}
else
{
//collide vs. slope
//if the component of (ox,oy) parallel to the normal is less than the circle radius, we're
//penetrating the slope. note that this method of penetration calculation doesn't hold
//in general (i.e it won't work if the circle is in the slope), but works in this case
//because we know the circle is in a neighboring cell
var dp = (ox * sx) + (oy * sy);
var pen = obj.radius - Math.abs(dp);//note: we don't need the abs because we know the dp will be positive, but just in case..
if (0 < pen)
{
//collision; circle out along normal by penetration amount
obj.reportCollisionVsWorld(sx * pen, sy * pen, sx, sy, t);
return Phaser.Physics.Ninja.Circle.COL_OTHER;
}
}
}
}
else
{
//colliding diagonally
if (0 < ((signx * oH) + (signy * oV)))
{
//the dotprod of slope normal and cell offset is strictly positive,
//therefore obj is in the diagonal neighb pointed at by the normal, and
//it cannot possibly reach/touch/penetrate the slope
return Phaser.Physics.Ninja.Circle.COL_NONE;
}
else
{
//collide vs. vertex
//get diag vertex position
var vx = t.pos.x + (oH * t.xw);
var vy = t.pos.y + (oV * t.yw);
var dx = obj.pos.x - vx;//calc vert->circle vector
var dy = obj.pos.y - vy;
var len = Math.sqrt(dx * dx + dy * dy);
var pen = obj.radius - len;
if (0 < pen)
{
//vertex is in the circle; project outward
if (len == 0)
{
//project out by 45deg
dx = oH / Math.SQRT2;
dy = oV / Math.SQRT2;
}
else
{
dx /= len;
dy /= len;
}
obj.reportCollisionVsWorld(dx * pen, dy * pen, dx, dy, t);
return Phaser.Physics.Ninja.Circle.COL_OTHER;
}
}
}
return Phaser.Physics.Ninja.Circle.COL_NONE;
},
/**
* Resolves Concave tile collision.
*
* @method Phaser.Physics.Ninja.Circle#projCircle_Concave
* @param {number} x - Penetration depth on the x axis.
* @param {number} y - Penetration depth on the y axis.
* @param {number} oH - Grid / voronoi region.
* @param {number} oV - Grid / voronoi region.
* @param {Phaser.Physics.Ninja.Circle} obj - The Circle involved in the collision.
* @param {Phaser.Physics.Ninja.Tile} t - The Tile involved in the collision.
* @return {number} The result of the collision.
*/
projCircle_Concave: function (x, y, oH, oV, obj, t) {
//if we're colliding diagonally:
// -if obj is in the diagonal pointed to by the slope normal: we can't collide, do nothing
// -else, collide vs. the appropriate vertex
//if obj is in this tile: perform collision as for aabb
//if obj is horiz OR very neighb in direction of slope: collide vs vert
//if obj is horiz or vert neigh against direction of slope: collide vs. face
var signx = t.signx;
var signy = t.signy;
var lenP;
if (oH == 0)
{
if (oV == 0)
{
//colliding with current tile
var ox = (t.pos.x + (signx * t.xw)) - obj.pos.x;//(ox,oy) is the vector from the circle to
var oy = (t.pos.y + (signy * t.yw)) - obj.pos.y;//tile-circle's center
var twid = t.xw * 2;
var trad = Math.sqrt(twid * twid + 0);//this gives us the radius of a circle centered on the tile's corner and extending to the opposite edge of the tile;
//note that this should be precomputed at compile-time since it's constant
var len = Math.sqrt(ox * ox + oy * oy);
var pen = (len + obj.radius) - trad;
if (0 < pen)
{
//find the smallest axial projection vector
if (x < y)
{
//penetration in x is smaller
lenP = x;
y = 0;
//get sign for projection along x-axis
if ((obj.pos.x - t.pos.x) < 0)
{
x *= -1;
}
}
else
{
//penetration in y is smaller
lenP = y;
x = 0;
//get sign for projection along y-axis
if ((obj.pos.y - t.pos.y) < 0)
{
y *= -1;
}
}
if (lenP < pen)
{
obj.reportCollisionVsWorld(x, y, x / lenP, y / lenP, t);
return Phaser.Physics.Ninja.Circle.COL_AXIS;
}
else
{
//we can assume that len >0, because if we're here then
//(len + obj.radius) > trad, and since obj.radius <= trad
//len MUST be > 0
ox /= len;
oy /= len;
obj.reportCollisionVsWorld(ox * pen, oy * pen, ox, oy, t);
return Phaser.Physics.Ninja.Circle.COL_OTHER;
}
}
else
{
return Phaser.Physics.Ninja.Circle.COL_NONE;
}
}
else
{
//colliding vertically
if ((signy * oV) < 0)
{
//colliding with face/edge
obj.reportCollisionVsWorld(0, y * oV, 0, oV, t);
return Phaser.Physics.Ninja.Circle.COL_AXIS;
}
else
{
//we could only be colliding vs the vertical tip
//get diag vertex position
var vx = t.pos.x - (signx * t.xw);
var vy = t.pos.y + (oV * t.yw);
var dx = obj.pos.x - vx;//calc vert->circle vector
var dy = obj.pos.y - vy;
var len = Math.sqrt(dx * dx + dy * dy);
var pen = obj.radius - len;
if (0 < pen)
{
//vertex is in the circle; project outward
if (len == 0)
{
//project out vertically
dx = 0;
dy = oV;
}
else
{
dx /= len;
dy /= len;
}
obj.reportCollisionVsWorld(dx * pen, dy * pen, dx, dy, t);
return Phaser.Physics.Ninja.Circle.COL_OTHER;
}
}
}
}
else if (oV == 0)
{
//colliding horizontally
if ((signx * oH) < 0)
{
//colliding with face/edge
obj.reportCollisionVsWorld(x * oH, 0, oH, 0, t);
return Phaser.Physics.Ninja.Circle.COL_AXIS;
}
else
{
//we could only be colliding vs the horizontal tip
//get diag vertex position
var vx = t.pos.x + (oH * t.xw);
var vy = t.pos.y - (signy * t.yw);
var dx = obj.pos.x - vx;//calc vert->circle vector
var dy = obj.pos.y - vy;
var len = Math.sqrt(dx * dx + dy * dy);
var pen = obj.radius - len;
if (0 < pen)
{
//vertex is in the circle; project outward
if (len == 0)
{
//project out horizontally
dx = oH;
dy = 0;
}
else
{
dx /= len;
dy /= len;
}
obj.reportCollisionVsWorld(dx * pen, dy * pen, dx, dy, t);
return Phaser.Physics.Ninja.Circle.COL_OTHER;
}
}
}
else
{
//colliding diagonally
if (0 < ((signx * oH) + (signy * oV)))
{
//the dotprod of slope normal and cell offset is strictly positive,
//therefore obj is in the diagonal neighb pointed at by the normal, and
//it cannot possibly reach/touch/penetrate the slope
return Phaser.Physics.Ninja.Circle.COL_NONE;
}
else
{
//collide vs. vertex
//get diag vertex position
var vx = t.pos.x + (oH * t.xw);
var vy = t.pos.y + (oV * t.yw);
var dx = obj.pos.x - vx;//calc vert->circle vector
var dy = obj.pos.y - vy;
var len = Math.sqrt(dx * dx + dy * dy);
var pen = obj.radius - len;
if (0 < pen)
{
//vertex is in the circle; project outward
if (len == 0)
{
//project out by 45deg
dx = oH / Math.SQRT2;
dy = oV / Math.SQRT2;
}
else
{
dx /= len;
dy /= len;
}
obj.reportCollisionVsWorld(dx * pen, dy * pen, dx, dy, t);
return Phaser.Physics.Ninja.Circle.COL_OTHER;
}
}
}
return Phaser.Physics.Ninja.Circle.COL_NONE;
},
/**
* Resolves Convex tile collision.
*
* @method Phaser.Physics.Ninja.Circle#projCircle_Convex
* @param {number} x - Penetration depth on the x axis.
* @param {number} y - Penetration depth on the y axis.
* @param {number} oH - Grid / voronoi region.
* @param {number} oV - Grid / voronoi region.
* @param {Phaser.Physics.Ninja.Circle} obj - The Circle involved in the collision.
* @param {Phaser.Physics.Ninja.Tile} t - The Tile involved in the collision.
* @return {number} The result of the collision.
*/
projCircle_Convex: function (x, y, oH, oV, obj, t) {
//if the object is horiz AND/OR vertical neighbor in the normal (signx,signy)
//direction, collide vs. tile-circle only.
//if we're colliding diagonally:
// -else, collide vs. the appropriate vertex
//if obj is in this tile: perform collision as for aabb
//if obj is horiz or vert neigh against direction of slope: collide vs. face
var signx = t.signx;
var signy = t.signy;
var lenP;
if (oH == 0)
{
if (oV == 0)
{
//colliding with current tile
var ox = obj.pos.x - (t.pos.x - (signx * t.xw));//(ox,oy) is the vector from the tile-circle to
var oy = obj.pos.y - (t.pos.y - (signy * t.yw));//the circle's center
var twid = t.xw * 2;
var trad = Math.sqrt(twid * twid + 0);//this gives us the radius of a circle centered on the tile's corner and extending to the opposite edge of the tile;
//note that this should be precomputed at compile-time since it's constant
var len = Math.sqrt(ox * ox + oy * oy);
var pen = (trad + obj.radius) - len;
if (0 < pen)
{
//find the smallest axial projection vector
if (x < y)
{
//penetration in x is smaller
lenP = x;
y = 0;
//get sign for projection along x-axis
if ((obj.pos.x - t.pos.x) < 0)
{
x *= -1;
}
}
else
{
//penetration in y is smaller
lenP = y;
x = 0;
//get sign for projection along y-axis
if ((obj.pos.y - t.pos.y) < 0)
{
y *= -1;
}
}
if (lenP < pen)
{
obj.reportCollisionVsWorld(x, y, x / lenP, y / lenP, t);
return Phaser.Physics.Ninja.Circle.COL_AXIS;
}
else
{
//note: len should NEVER be == 0, because if it is,
//projeciton by an axis shoudl always be shorter, and we should
//never arrive here
ox /= len;
oy /= len;
obj.reportCollisionVsWorld(ox * pen, oy * pen, ox, oy, t);
return Phaser.Physics.Ninja.Circle.COL_OTHER;
}
}
}
else
{
//colliding vertically
if ((signy * oV) < 0)
{
//colliding with face/edge
obj.reportCollisionVsWorld(0, y * oV, 0, oV, t);
return Phaser.Physics.Ninja.Circle.COL_AXIS;
}
else
{
//obj in neighboring cell pointed at by tile normal;
//we could only be colliding vs the tile-circle surface
var ox = obj.pos.x - (t.pos.x - (signx * t.xw));//(ox,oy) is the vector from the tile-circle to
var oy = obj.pos.y - (t.pos.y - (signy * t.yw));//the circle's center
var twid = t.xw * 2;
var trad = Math.sqrt(twid * twid + 0);//this gives us the radius of a circle centered on the tile's corner and extending to the opposite edge of the tile;
//note that this should be precomputed at compile-time since it's constant
var len = Math.sqrt(ox * ox + oy * oy);
var pen = (trad + obj.radius) - len;
if (0 < pen)
{
//note: len should NEVER be == 0, because if it is,
//obj is not in a neighboring cell!
ox /= len;
oy /= len;
obj.reportCollisionVsWorld(ox * pen, oy * pen, ox, oy, t);
return Phaser.Physics.Ninja.Circle.COL_OTHER;
}
}
}
}
else if (oV == 0)
{
//colliding horizontally
if ((signx * oH) < 0)
{
//colliding with face/edge
obj.reportCollisionVsWorld(x * oH, 0, oH, 0, t);
return Phaser.Physics.Ninja.Circle.COL_AXIS;
}
else
{
//obj in neighboring cell pointed at by tile normal;
//we could only be colliding vs the tile-circle surface
var ox = obj.pos.x - (t.pos.x - (signx * t.xw));//(ox,oy) is the vector from the tile-circle to
var oy = obj.pos.y - (t.pos.y - (signy * t.yw));//the circle's center
var twid = t.xw * 2;
var trad = Math.sqrt(twid * twid + 0);//this gives us the radius of a circle centered on the tile's corner and extending to the opposite edge of the tile;
//note that this should be precomputed at compile-time since it's constant
var len = Math.sqrt(ox * ox + oy * oy);
var pen = (trad + obj.radius) - len;
if (0 < pen)
{
//note: len should NEVER be == 0, because if it is,
//obj is not in a neighboring cell!
ox /= len;
oy /= len;
obj.reportCollisionVsWorld(ox * pen, oy * pen, ox, oy, t);
return Phaser.Physics.Ninja.Circle.COL_OTHER;
}
}
}
else
{
//colliding diagonally
if (0 < ((signx * oH) + (signy * oV)))
{
//obj in diag neighb cell pointed at by tile normal;
//we could only be colliding vs the tile-circle surface
var ox = obj.pos.x - (t.pos.x - (signx * t.xw));//(ox,oy) is the vector from the tile-circle to
var oy = obj.pos.y - (t.pos.y - (signy * t.yw));//the circle's center
var twid = t.xw * 2;
var trad = Math.sqrt(twid * twid + 0);//this gives us the radius of a circle centered on the tile's corner and extending to the opposite edge of the tile;
//note that this should be precomputed at compile-time since it's constant
var len = Math.sqrt(ox * ox + oy * oy);
var pen = (trad + obj.radius) - len;
if (0 < pen)
{
//note: len should NEVER be == 0, because if it is,
//obj is not in a neighboring cell!
ox /= len;
oy /= len;
obj.reportCollisionVsWorld(ox * pen, oy * pen, ox, oy, t);
return Phaser.Physics.Ninja.Circle.COL_OTHER;
}
}
else
{
//collide vs. vertex
//get diag vertex position
var vx = t.pos.x + (oH * t.xw);
var vy = t.pos.y + (oV * t.yw);
var dx = obj.pos.x - vx;//calc vert->circle vector
var dy = obj.pos.y - vy;
var len = Math.sqrt(dx * dx + dy * dy);
var pen = obj.radius - len;
if (0 < pen)
{
//vertex is in the circle; project outward
if (len == 0)
{
//project out by 45deg
dx = oH / Math.SQRT2;
dy = oV / Math.SQRT2;
}
else
{
dx /= len;
dy /= len;
}
obj.reportCollisionVsWorld(dx * pen, dy * pen, dx, dy, t);
return Phaser.Physics.Ninja.Circle.COL_OTHER;
}
}
}
return Phaser.Physics.Ninja.Circle.COL_NONE;
},
/**
* Resolves Half tile collision.
*
* @method Phaser.Physics.Ninja.Circle#projCircle_Half
* @param {number} x - Penetration depth on the x axis.
* @param {number} y - Penetration depth on the y axis.
* @param {number} oH - Grid / voronoi region.
* @param {number} oV - Grid / voronoi region.
* @param {Phaser.Physics.Ninja.Circle} obj - The Circle involved in the collision.
* @param {Phaser.Physics.Ninja.Tile} t - The Tile involved in the collision.
* @return {number} The result of the collision.
*/
projCircle_Half: function (x,y,oH,oV,obj,t) {
//if obj is in a neighbor pointed at by the halfedge normal,
//we'll never collide (i.e if the normal is (0,1) and the obj is in the DL.D, or R neighbors)
//
//if obj is in a neigbor perpendicular to the halfedge normal, it might
//collide with the halfedge-vertex, or with the halfedge side.
//
//if obj is in a neigb pointing opposite the halfedge normal, obj collides with edge
//
//if obj is in a diagonal (pointing away from the normal), obj collides vs vertex
//
//if obj is in the halfedge cell, it collides as with aabb
var signx = t.signx;
var signy = t.signy;
var celldp = (oH*signx + oV*signy);//this tells us about the configuration of cell-offset relative to tile normal
if(0 < celldp)
{
//obj is in "far" (pointed-at-by-normal) neighbor of halffull tile, and will never hit
return Phaser.Physics.Ninja.Circle.COL_NONE;
}
else if(oH == 0)
{
if(oV == 0)
{
//colliding with current tile
var r = obj.radius;
var ox = (obj.pos.x - (signx*r)) - t.pos.x;//this gives is the coordinates of the innermost
var oy = (obj.pos.y - (signy*r)) - t.pos.y;//point on the circle, relative to the tile center
//we perform operations analogous to the 45deg tile, except we're using
//an axis-aligned slope instead of an angled one..
var sx = signx;
var sy = signy;
//if the dotprod of (ox,oy) and (sx,sy) is negative, the corner is in the slope
//and we need toproject it out by the magnitude of the projection of (ox,oy) onto (sx,sy)
var dp = (ox*sx) + (oy*sy);
if(dp < 0)
{
//collision; project delta onto slope and use this to displace the object
sx *= -dp;//(sx,sy) is now the projection vector
sy *= -dp;
var lenN = Math.sqrt(sx*sx + sy*sy);
var lenP = Math.sqrt(x*x + y*y);
if(lenP < lenN)
{
obj.reportCollisionVsWorld(x,y,x/lenP, y/lenP,t);
return Phaser.Physics.Ninja.Circle.COL_AXIS;
}
else
{
obj.reportCollisionVsWorld(sx,sy,t.signx,t.signy);
return Phaser.Physics.Ninja.Circle.COL_OTHER;
}
return true;
}
}
else
{
//colliding vertically
if(celldp == 0)
{
var r = obj.radius;
var dx = obj.pos.x - t.pos.x;
//we're in a cell perpendicular to the normal, and can collide vs. halfedge vertex
//or halfedge side
if((dx*signx) < 0)
{
//collision with halfedge side
obj.reportCollisionVsWorld(0,y*oV,0,oV,t);
return Phaser.Physics.Ninja.Circle.COL_AXIS;
}
else
{
//collision with halfedge vertex
var dy = obj.pos.y - (t.pos.y + oV*t.yw);//(dx,dy) is now the vector from the appropriate halfedge vertex to the circle
var len = Math.sqrt(dx*dx + dy*dy);
var pen = obj.radius - len;
if(0 < pen)
{
//vertex is in the circle; project outward
if(len == 0)
{
//project out by 45deg
dx = signx / Math.SQRT2;
dy = oV / Math.SQRT2;
}
else
{
dx /= len;
dy /= len;
}
obj.reportCollisionVsWorld(dx*pen, dy*pen, dx, dy, t);
return Phaser.Physics.Ninja.Circle.COL_OTHER;
}
}
}
else
{
//due to the first conditional (celldp >0), we know we're in the cell "opposite" the normal, and so
//we can only collide with the cell edge
//collision with vertical neighbor
obj.reportCollisionVsWorld(0,y*oV,0,oV,t);
return Phaser.Physics.Ninja.Circle.COL_AXIS;
}
}
}
else if(oV == 0)
{
//colliding horizontally
if(celldp == 0)
{
var r = obj.radius;
var dy = obj.pos.y - t.pos.y;
//we're in a cell perpendicular to the normal, and can collide vs. halfedge vertex
//or halfedge side
if((dy*signy) < 0)
{
//collision with halfedge side
obj.reportCollisionVsWorld(x*oH,0,oH,0,t);
return Phaser.Physics.Ninja.Circle.COL_AXIS;
}
else
{
//collision with halfedge vertex
var dx = obj.pos.x - (t.pos.x + oH*t.xw);//(dx,dy) is now the vector from the appropriate halfedge vertex to the circle
var len = Math.sqrt(dx*dx + dy*dy);
var pen = obj.radius - len;
if(0 < pen)
{
//vertex is in the circle; project outward
if(len == 0)
{
//project out by 45deg
dx = signx / Math.SQRT2;
dy = oV / Math.SQRT2;
}
else
{
dx /= len;
dy /= len;
}
obj.reportCollisionVsWorld(dx*pen, dy*pen, dx, dy, t);
return Phaser.Physics.Ninja.Circle.COL_OTHER;
}
}
}
else
{
//due to the first conditional (celldp >0), we know w're in the cell "opposite" the normal, and so
//we can only collide with the cell edge
obj.reportCollisionVsWorld(x*oH, 0, oH, 0, t);
return Phaser.Physics.Ninja.Circle.COL_AXIS;
}
}
else
{
//colliding diagonally; we know, due to the initial (celldp >0) test which has failed
//if we've reached this point, that we're in a diagonal neighbor on the non-normal side, so
//we could only be colliding with the cell vertex, if at all.
//get diag vertex position
var vx = t.pos.x + (oH*t.xw);
var vy = t.pos.y + (oV*t.yw);
var dx = obj.pos.x - vx;//calc vert->circle vector
var dy = obj.pos.y - vy;
var len = Math.sqrt(dx*dx + dy*dy);
var pen = obj.radius - len;
if(0 < pen)
{
//vertex is in the circle; project outward
if(len == 0)
{
//project out by 45deg
dx = oH / Math.SQRT2;
dy = oV / Math.SQRT2;
}
else
{
dx /= len;
dy /= len;
}
obj.reportCollisionVsWorld(dx*pen, dy*pen, dx, dy, t);
return Phaser.Physics.Ninja.Circle.COL_OTHER;
}
}
return Phaser.Physics.Ninja.Circle.COL_NONE;
},
/**
* Resolves 22 Degree tile collision.
*
* @method Phaser.Physics.Ninja.Circle#projCircle_22DegS
* @param {number} x - Penetration depth on the x axis.
* @param {number} y - Penetration depth on the y axis.
* @param {number} oH - Grid / voronoi region.
* @param {number} oV - Grid / voronoi region.
* @param {Phaser.Physics.Ninja.Circle} obj - The Circle involved in the collision.
* @param {Phaser.Physics.Ninja.Tile} t - The Tile involved in the collision.
* @return {number} The result of the collision.
*/
projCircle_22DegS: function (x,y,oH,oV,obj,t) {
//if the object is in a cell pointed at by signy, no collision will ever occur
//otherwise,
//
//if we're colliding diagonally:
// -collide vs. the appropriate vertex
//if obj is in this tile: collide vs slope or vertex
//if obj is horiz neighb in direction of slope: collide vs. slope or vertex
//if obj is horiz neighb against the slope:
// if(distance in y from circle to 90deg corner of tile < 1/2 tileheight, collide vs. face)
// else(collide vs. corner of slope) (vert collision with a non-grid-aligned vert)
//if obj is vert neighb against direction of slope: collide vs. face
var signx = t.signx;
var signy = t.signy;
if(0 < (signy*oV))
{
//object will never collide vs tile, it can't reach that far
return Phaser.Physics.Ninja.Circle.COL_NONE;
}
else if(oH == 0)
{
if(oV == 0)
{
//colliding with current tile
//we could only be colliding vs the slope OR a vertex
//look at the vector form the closest vert to the circle to decide
var sx = t.sx;
var sy = t.sy;
var r = obj.radius;
var ox = obj.pos.x - (t.pos.x - (signx*t.xw));//this gives is the coordinates of the innermost
var oy = obj.pos.y - t.pos.y;//point on the circle, relative to the tile corner
//if the component of (ox,oy) parallel to the normal's righthand normal
//has the same sign as the slope of the slope (the sign of the slope's slope is signx*signy)
//then we project by the vertex, otherwise by the normal or axially.
//note that this is simply a VERY tricky/weird method of determining
//if the circle is in side the slope/face's voronio region, or that of the vertex.
var perp = (ox*-sy) + (oy*sx);
if(0 < (perp*signx*signy))
{
//collide vs. vertex
var len = Math.sqrt(ox*ox + oy*oy);
var pen = r - len;
if(0 < pen)
{
//note: if len=0, then perp=0 and we'll never reach here, so don't worry about div-by-0
ox /= len;
oy /= len;
obj.reportCollisionVsWorld(ox*pen, oy*pen, ox, oy, t);
return Phaser.Physics.Ninja.Circle.COL_OTHER;
}
}
else
{
//collide vs. slope or vs axis
ox -= r*sx;//this gives us the vector from
oy -= r*sy;//a point on the slope to the innermost point on the circle
//if the dotprod of (ox,oy) and (sx,sy) is negative, the point on the circle is in the slope
//and we need toproject it out by the magnitude of the projection of (ox,oy) onto (sx,sy)
var dp = (ox*sx) + (oy*sy);
if(dp < 0)
{
//collision; project delta onto slope and use this to displace the object
sx *= -dp;//(sx,sy) is now the projection vector
sy *= -dp;
var lenN = Math.sqrt(sx*sx + sy*sy);
//find the smallest axial projection vector
if(x < y)
{
//penetration in x is smaller
lenP = x;
y = 0;
//get sign for projection along x-axis
if((obj.pos.x - t.pos.x) < 0)
{
x *= -1;
}
}
else
{
//penetration in y is smaller
lenP = y;
x = 0;
//get sign for projection along y-axis
if((obj.pos.y - t.pos.y)< 0)
{
y *= -1;
}
}
if(lenP < lenN)
{
obj.reportCollisionVsWorld(x,y,x/lenP, y/lenP, t);
return Phaser.Physics.Ninja.Circle.COL_AXIS;
}
else
{
obj.reportCollisionVsWorld(sx,sy,t.sx,t.sy,t);
return Phaser.Physics.Ninja.Circle.COL_OTHER;
}
}
}
}
else
{
//colliding vertically; we can assume that (signy*oV) < 0
//due to the first conditional far above
obj.reportCollisionVsWorld(0,y*oV, 0, oV, t);
return Phaser.Physics.Ninja.Circle.COL_AXIS;
}
}
else if(oV == 0)
{
//colliding horizontally
if((signx*oH) < 0)
{
//colliding with face/edge OR with corner of wedge, depending on our position vertically
//collide vs. vertex
//get diag vertex position
var vx = t.pos.x - (signx*t.xw);
var vy = t.pos.y;
var dx = obj.pos.x - vx;//calc vert->circle vector
var dy = obj.pos.y - vy;
if((dy*signy) < 0)
{
//colliding vs face
obj.reportCollisionVsWorld(x*oH, 0, oH, 0, t);
return Phaser.Physics.Ninja.Circle.COL_AXIS;
}
else
{
//colliding vs. vertex
var len = Math.sqrt(dx*dx + dy*dy);
var pen = obj.radius - len;
if(0 < pen)
{
//vertex is in the circle; project outward
if(len == 0)
{
//project out by 45deg
dx = oH / Math.SQRT2;
dy = oV / Math.SQRT2;
}
else
{
dx /= len;
dy /= len;
}
obj.reportCollisionVsWorld(dx*pen, dy*pen, dx, dy, t);
return Phaser.Physics.Ninja.Circle.COL_OTHER;
}
}
}
else
{
//we could only be colliding vs the slope OR a vertex
//look at the vector form the closest vert to the circle to decide
var sx = t.sx;
var sy = t.sy;
var ox = obj.pos.x - (t.pos.x + (oH*t.xw));//this gives is the coordinates of the innermost
var oy = obj.pos.y - (t.pos.y - (signy*t.yw));//point on the circle, relative to the closest tile vert
//if the component of (ox,oy) parallel to the normal's righthand normal
//has the same sign as the slope of the slope (the sign of the slope's slope is signx*signy)
//then we project by the normal, otherwise by the vertex.
//(NOTE: this is the opposite logic of the vertical case;
// for vertical, if the perp prod and the slope's slope agree, it's outside.
// for horizontal, if the perp prod and the slope's slope agree, circle is inside.
// ..but this is only a property of flahs' coord system (i.e the rules might swap
// in righthanded systems))
//note that this is simply a VERY tricky/weird method of determining
//if the circle is in side the slope/face's voronio region, or that of the vertex.
var perp = (ox*-sy) + (oy*sx);
if((perp*signx*signy) < 0)
{
//collide vs. vertex
var len = Math.sqrt(ox*ox + oy*oy);
var pen = obj.radius - len;
if(0 < pen)
{
//note: if len=0, then perp=0 and we'll never reach here, so don't worry about div-by-0
ox /= len;
oy /= len;
obj.reportCollisionVsWorld(ox*pen, oy*pen, ox, oy, t);
return Phaser.Physics.Ninja.Circle.COL_OTHER;
}
}
else
{
//collide vs. slope
//if the component of (ox,oy) parallel to the normal is less than the circle radius, we're
//penetrating the slope. note that this method of penetration calculation doesn't hold
//in general (i.e it won't work if the circle is in the slope), but works in this case
//because we know the circle is in a neighboring cell
var dp = (ox*sx) + (oy*sy);
var pen = obj.radius - Math.abs(dp);//note: we don't need the abs because we know the dp will be positive, but just in case..
if(0 < pen)
{
//collision; circle out along normal by penetration amount
obj.reportCollisionVsWorld(sx*pen, sy*pen, sx, sy, t);
return Phaser.Physics.Ninja.Circle.COL_OTHER;
}
}
}
}
else
{
//colliding diagonally; due to the first conditional above,
//obj is vertically offset against slope, and offset in either direction horizontally
//collide vs. vertex
//get diag vertex position
var vx = t.pos.x + (oH*t.xw);
var vy = t.pos.y + (oV*t.yw);
var dx = obj.pos.x - vx;//calc vert->circle vector
var dy = obj.pos.y - vy;
var len = Math.sqrt(dx*dx + dy*dy);
var pen = obj.radius - len;
if(0 < pen)
{
//vertex is in the circle; project outward
if(len == 0)
{
//project out by 45deg
dx = oH / Math.SQRT2;
dy = oV / Math.SQRT2;
}
else
{
dx /= len;
dy /= len;
}
obj.reportCollisionVsWorld(dx*pen, dy*pen, dx, dy, t);
return Phaser.Physics.Ninja.Circle.COL_OTHER;
}
}
return Phaser.Physics.Ninja.Circle.COL_NONE;
},
/**
* Resolves 22 Degree tile collision.
*
* @method Phaser.Physics.Ninja.Circle#projCircle_22DegB
* @param {number} x - Penetration depth on the x axis.
* @param {number} y - Penetration depth on the y axis.
* @param {number} oH - Grid / voronoi region.
* @param {number} oV - Grid / voronoi region.
* @param {Phaser.Physics.Ninja.Circle} obj - The Circle involved in the collision.
* @param {Phaser.Physics.Ninja.Tile} t - The Tile involved in the collision.
* @return {number} The result of the collision.
*/
projCircle_22DegB: function (x,y,oH, oV, obj,t) {
//if we're colliding diagonally:
// -if we're in the cell pointed at by the normal, collide vs slope, else
// collide vs. the appropriate corner/vertex
//
//if obj is in this tile: collide as with aabb
//
//if obj is horiz or vertical neighbor AGAINST the slope: collide with edge
//
//if obj is horiz neighb in direction of slope: collide vs. slope or vertex or edge
//
//if obj is vert neighb in direction of slope: collide vs. slope or vertex
var signx = t.signx;
var signy = t.signy;
if(oH == 0)
{
if(oV == 0)
{
//colliding with current cell
var sx = t.sx;
var sy = t.sy;
var r = obj.radius;
var ox = (obj.pos.x - (sx*r)) - (t.pos.x - (signx*t.xw));//this gives is the coordinates of the innermost
var oy = (obj.pos.y - (sy*r)) - (t.pos.y + (signy*t.yw));//point on the AABB, relative to a point on the slope
//if the dotprod of (ox,oy) and (sx,sy) is negative, the point on the circle is in the slope
//and we need toproject it out by the magnitude of the projection of (ox,oy) onto (sx,sy)
var dp = (ox*sx) + (oy*sy);
if(dp < 0)
{
//collision; project delta onto slope and use this to displace the object
sx *= -dp;//(sx,sy) is now the projection vector
sy *= -dp;
var lenN = Math.sqrt(sx*sx + sy*sy);
//find the smallest axial projection vector
if(x < y)
{
//penetration in x is smaller
lenP = x;
y = 0;
//get sign for projection along x-axis
if((obj.pos.x - t.pos.x) < 0)
{
x *= -1;
}
}
else
{
//penetration in y is smaller
lenP = y;
x = 0;
//get sign for projection along y-axis
if((obj.pos.y - t.pos.y)< 0)
{
y *= -1;
}
}
if(lenP < lenN)
{
obj.reportCollisionVsWorld(x, y, x/lenP, y/lenP, t);
return Phaser.Physics.Ninja.Circle.COL_AXIS;
}
else
{
obj.reportCollisionVsWorld(sx, sy, t.sx, t.sy, t);
return Phaser.Physics.Ninja.Circle.COL_OTHER;
}
}
}
else
{
//colliding vertically
if((signy*oV) < 0)
{
//colliding with face/edge
obj.reportCollisionVsWorld(0, y*oV, 0, oV, t);
return Phaser.Physics.Ninja.Circle.COL_AXIS;
}
else
{
//we could only be colliding vs the slope OR a vertex
//look at the vector form the closest vert to the circle to decide
var sx = t.sx;
var sy = t.sy;
var ox = obj.pos.x - (t.pos.x - (signx*t.xw));//this gives is the coordinates of the innermost
var oy = obj.pos.y - (t.pos.y + (signy*t.yw));//point on the circle, relative to the closest tile vert
//if the component of (ox,oy) parallel to the normal's righthand normal
//has the same sign as the slope of the slope (the sign of the slope's slope is signx*signy)
//then we project by the vertex, otherwise by the normal.
//note that this is simply a VERY tricky/weird method of determining
//if the circle is in side the slope/face's voronio region, or that of the vertex.
var perp = (ox*-sy) + (oy*sx);
if(0 < (perp*signx*signy))
{
//collide vs. vertex
var len = Math.sqrt(ox*ox + oy*oy);
var pen = obj.radius - len;
if(0 < pen)
{
//note: if len=0, then perp=0 and we'll never reach here, so don't worry about div-by-0
ox /= len;
oy /= len;
obj.reportCollisionVsWorld(ox*pen, oy*pen, ox, oy, t);
return Phaser.Physics.Ninja.Circle.COL_OTHER;
}
}
else
{
//collide vs. slope
//if the component of (ox,oy) parallel to the normal is less than the circle radius, we're
//penetrating the slope. note that this method of penetration calculation doesn't hold
//in general (i.e it won't work if the circle is in the slope), but works in this case
//because we know the circle is in a neighboring cell
var dp = (ox*sx) + (oy*sy);
var pen = obj.radius - Math.abs(dp);//note: we don't need the abs because we know the dp will be positive, but just in case..
if(0 < pen)
{
//collision; circle out along normal by penetration amount
obj.reportCollisionVsWorld(sx*pen, sy*pen,sx, sy, t);
return Phaser.Physics.Ninja.Circle.COL_OTHER;
}
}
}
}
}
else if(oV == 0)
{
//colliding horizontally
if((signx*oH) < 0)
{
//colliding with face/edge
obj.reportCollisionVsWorld(x*oH, 0, oH, 0, t);
return Phaser.Physics.Ninja.Circle.COL_AXIS;
}
else
{
//colliding with edge, slope, or vertex
var ox = obj.pos.x - (t.pos.x + (signx*t.xw));//this gives is the coordinates of the innermost
var oy = obj.pos.y - t.pos.y;//point on the circle, relative to the closest tile vert
if((oy*signy) < 0)
{
//we're colliding with the halfface
obj.reportCollisionVsWorld(x*oH, 0, oH, 0, t);
return Phaser.Physics.Ninja.Circle.COL_AXIS;
}
else
{
//colliding with the vertex or slope
var sx = t.sx;
var sy = t.sy;
//if the component of (ox,oy) parallel to the normal's righthand normal
//has the same sign as the slope of the slope (the sign of the slope's slope is signx*signy)
//then we project by the slope, otherwise by the vertex.
//note that this is simply a VERY tricky/weird method of determining
//if the circle is in side the slope/face's voronio region, or that of the vertex.
var perp = (ox*-sy) + (oy*sx);
if((perp*signx*signy) < 0)
{
//collide vs. vertex
var len = Math.sqrt(ox*ox + oy*oy);
var pen = obj.radius - len;
if(0 < pen)
{
//note: if len=0, then perp=0 and we'll never reach here, so don't worry about div-by-0
ox /= len;
oy /= len;
obj.reportCollisionVsWorld(ox*pen, oy*pen, ox, oy, t);
return Phaser.Physics.Ninja.Circle.COL_OTHER;
}
}
else
{
//collide vs. slope
//if the component of (ox,oy) parallel to the normal is less than the circle radius, we're
//penetrating the slope. note that this method of penetration calculation doesn't hold
//in general (i.e it won't work if the circle is in the slope), but works in this case
//because we know the circle is in a neighboring cell
var dp = (ox*sx) + (oy*sy);
var pen = obj.radius - Math.abs(dp);//note: we don't need the abs because we know the dp will be positive, but just in case..
if(0 < pen)
{
//collision; circle out along normal by penetration amount
obj.reportCollisionVsWorld(sx*pen, sy*pen, t.sx, t.sy, t);
return Phaser.Physics.Ninja.Circle.COL_OTHER;
}
}
}
}
}
else
{
//colliding diagonally
if( 0 < ((signx*oH) + (signy*oV)) )
{
//the dotprod of slope normal and cell offset is strictly positive,
//therefore obj is in the diagonal neighb pointed at by the normal.
//collide vs slope
//we should really precalc this at compile time, but for now, fuck it
var slen = Math.sqrt(2*2 + 1*1);//the raw slope is (-2,-1)
var sx = (signx*1) / slen;//get slope _unit_ normal;
var sy = (signy*2) / slen;//raw RH normal is (1,-2)
var r = obj.radius;
var ox = (obj.pos.x - (sx*r)) - (t.pos.x - (signx*t.xw));//this gives is the coordinates of the innermost
var oy = (obj.pos.y - (sy*r)) - (t.pos.y + (signy*t.yw));//point on the circle, relative to a point on the slope
//if the dotprod of (ox,oy) and (sx,sy) is negative, the point on the circle is in the slope
//and we need toproject it out by the magnitude of the projection of (ox,oy) onto (sx,sy)
var dp = (ox*sx) + (oy*sy);
if(dp < 0)
{
//collision; project delta onto slope and use this to displace the object
//(sx,sy)*-dp is the projection vector
obj.reportCollisionVsWorld(-sx*dp, -sy*dp, t.sx, t.sy, t);
return Phaser.Physics.Ninja.Circle.COL_OTHER;
}
return Phaser.Physics.Ninja.Circle.COL_NONE;
}
else
{
//collide vs the appropriate vertex
var vx = t.pos.x + (oH*t.xw);
var vy = t.pos.y + (oV*t.yw);
var dx = obj.pos.x - vx;//calc vert->circle vector
var dy = obj.pos.y - vy;
var len = Math.sqrt(dx*dx + dy*dy);
var pen = obj.radius - len;
if(0 < pen)
{
//vertex is in the circle; project outward
if(len == 0)
{
//project out by 45deg
dx = oH / Math.SQRT2;
dy = oV / Math.SQRT2;
}
else
{
dx /= len;
dy /= len;
}
obj.reportCollisionVsWorld(dx*pen, dy*pen, dx, dy, t);
return Phaser.Physics.Ninja.Circle.COL_OTHER;
}
}
}
return Phaser.Physics.Ninja.Circle.COL_NONE;
},
/**
* Resolves 67 Degree tile collision.
*
* @method Phaser.Physics.Ninja.Circle#projCircle_67DegS
* @param {number} x - Penetration depth on the x axis.
* @param {number} y - Penetration depth on the y axis.
* @param {number} oH - Grid / voronoi region.
* @param {number} oV - Grid / voronoi region.
* @param {Phaser.Physics.Ninja.Circle} obj - The Circle involved in the collision.
* @param {Phaser.Physics.Ninja.Tile} t - The Tile involved in the collision.
* @return {number} The result of the collision.
*/
projCircle_67DegS: function (x,y,oH,oV,obj,t) {
//if the object is in a cell pointed at by signx, no collision will ever occur
//otherwise,
//
//if we're colliding diagonally:
// -collide vs. the appropriate vertex
//if obj is in this tile: collide vs slope or vertex or axis
//if obj is vert neighb in direction of slope: collide vs. slope or vertex
//if obj is vert neighb against the slope:
// if(distance in y from circle to 90deg corner of tile < 1/2 tileheight, collide vs. face)
// else(collide vs. corner of slope) (vert collision with a non-grid-aligned vert)
//if obj is horiz neighb against direction of slope: collide vs. face
var signx = t.signx;
var signy = t.signy;
if(0 < (signx*oH))
{
//object will never collide vs tile, it can't reach that far
return Phaser.Physics.Ninja.Circle.COL_NONE;
}
else if(oH == 0)
{
if(oV == 0)
{
//colliding with current tile
//we could only be colliding vs the slope OR a vertex
//look at the vector form the closest vert to the circle to decide
var sx = t.sx;
var sy = t.sy;
var r = obj.radius;
var ox = obj.pos.x - t.pos.x;//this gives is the coordinates of the innermost
var oy = obj.pos.y - (t.pos.y - (signy*t.yw));//point on the circle, relative to the tile corner
//if the component of (ox,oy) parallel to the normal's righthand normal
//has the same sign as the slope of the slope (the sign of the slope's slope is signx*signy)
//then we project by the normal or axis, otherwise by the corner/vertex
//note that this is simply a VERY tricky/weird method of determining
//if the circle is in side the slope/face's voronoi region, or that of the vertex.
var perp = (ox*-sy) + (oy*sx);
if((perp*signx*signy) < 0)
{
//collide vs. vertex
var len = Math.sqrt(ox*ox + oy*oy);
var pen = r - len;
if(0 < pen)
{
//note: if len=0, then perp=0 and we'll never reach here, so don't worry about div-by-0
ox /= len;
oy /= len;
obj.reportCollisionVsWorld(ox*pen, oy*pen, ox, oy, t);
return Phaser.Physics.Ninja.Circle.COL_OTHER;
}
}
else
{
//collide vs. slope or vs axis
ox -= r*sx;//this gives us the vector from
oy -= r*sy;//a point on the slope to the innermost point on the circle
//if the dotprod of (ox,oy) and (sx,sy) is negative, the point on the circle is in the slope
//and we need toproject it out by the magnitude of the projection of (ox,oy) onto (sx,sy)
var dp = (ox*sx) + (oy*sy);
if(dp < 0)
{
//collision; project delta onto slope and use this to displace the object
sx *= -dp;//(sx,sy) is now the projection vector
sy *= -dp;
var lenN = Math.sqrt(sx*sx + sy*sy);
//find the smallest axial projection vector
if(x < y)
{
//penetration in x is smaller
lenP = x;
y = 0;
//get sign for projection along x-axis
if((obj.pos.x - t.pos.x) < 0)
{
x *= -1;
}
}
else
{
//penetration in y is smaller
lenP = y;
x = 0;
//get sign for projection along y-axis
if((obj.pos.y - t.pos.y)< 0)
{
y *= -1;
}
}
if(lenP < lenN)
{
obj.reportCollisionVsWorld(x,y,x/lenP, y/lenP, t);
return Phaser.Physics.Ninja.Circle.COL_AXIS
}
else
{
obj.reportCollisionVsWorld(sx,sy,t.sx,t.sy,t);
return Phaser.Physics.Ninja.Circle.COL_OTHER;
}
}
}
}
else
{
//colliding vertically
if((signy*oV) < 0)
{
//colliding with face/edge OR with corner of wedge, depending on our position vertically
//collide vs. vertex
//get diag vertex position
var vx = t.pos.x;
var vy = t.pos.y - (signy*t.yw);
var dx = obj.pos.x - vx;//calc vert->circle vector
var dy = obj.pos.y - vy;
if((dx*signx) < 0)
{
//colliding vs face
obj.reportCollisionVsWorld(0, y*oV, 0, oV, t);
return Phaser.Physics.Ninja.Circle.COL_AXIS;
}
else
{
//colliding vs. vertex
var len = Math.sqrt(dx*dx + dy*dy);
var pen = obj.radius - len;
if(0 < pen)
{
//vertex is in the circle; project outward
if(len == 0)
{
//project out by 45deg
dx = oH / Math.SQRT2;
dy = oV / Math.SQRT2;
}
else
{
dx /= len;
dy /= len;
}
obj.reportCollisionVsWorld(dx*pen, dy*pen, dx, dy, t);
return Phaser.Physics.Ninja.Circle.COL_OTHER;
}
}
}
else
{
//we could only be colliding vs the slope OR a vertex
//look at the vector form the closest vert to the circle to decide
var sx = t.sx;
var sy = t.sy;
var ox = obj.pos.x - (t.pos.x - (signx*t.xw));//this gives is the coordinates of the innermost
var oy = obj.pos.y - (t.pos.y + (oV*t.yw));//point on the circle, relative to the closest tile vert
//if the component of (ox,oy) parallel to the normal's righthand normal
//has the same sign as the slope of the slope (the sign of the slope's slope is signx*signy)
//then we project by the vertex, otherwise by the normal.
//note that this is simply a VERY tricky/weird method of determining
//if the circle is in side the slope/face's voronio region, or that of the vertex.
var perp = (ox*-sy) + (oy*sx);
if(0 < (perp*signx*signy))
{
//collide vs. vertex
var len = Math.sqrt(ox*ox + oy*oy);
var pen = obj.radius - len;
if(0 < pen)
{
//note: if len=0, then perp=0 and we'll never reach here, so don't worry about div-by-0
ox /= len;
oy /= len;
obj.reportCollisionVsWorld(ox*pen, oy*pen, ox, oy, t);
return Phaser.Physics.Ninja.Circle.COL_OTHER;
}
}
else
{
//collide vs. slope
//if the component of (ox,oy) parallel to the normal is less than the circle radius, we're
//penetrating the slope. note that this method of penetration calculation doesn't hold
//in general (i.e it won't work if the circle is in the slope), but works in this case
//because we know the circle is in a neighboring cell
var dp = (ox*sx) + (oy*sy);
var pen = obj.radius - Math.abs(dp);//note: we don't need the abs because we know the dp will be positive, but just in case..
if(0 < pen)
{
//collision; circle out along normal by penetration amount
obj.reportCollisionVsWorld(sx*pen, sy*pen, t.sx, t.sy, t);
return Phaser.Physics.Ninja.Circle.COL_OTHER;
}
}
}
}
}
else if(oV == 0)
{
//colliding horizontally; we can assume that (signy*oV) < 0
//due to the first conditional far above
obj.reportCollisionVsWorld(x*oH, 0, oH, 0, t);
return Phaser.Physics.Ninja.Circle.COL_AXIS;
}
else
{
//colliding diagonally; due to the first conditional above,
//obj is vertically offset against slope, and offset in either direction horizontally
//collide vs. vertex
//get diag vertex position
var vx = t.pos.x + (oH*t.xw);
var vy = t.pos.y + (oV*t.yw);
var dx = obj.pos.x - vx;//calc vert->circle vector
var dy = obj.pos.y - vy;
var len = Math.sqrt(dx*dx + dy*dy);
var pen = obj.radius - len;
if(0 < pen)
{
//vertex is in the circle; project outward
if(len == 0)
{
//project out by 45deg
dx = oH / Math.SQRT2;
dy = oV / Math.SQRT2;
}
else
{
dx /= len;
dy /= len;
}
obj.reportCollisionVsWorld(dx*pen, dy*pen, dx, dy, t);
return Phaser.Physics.Ninja.Circle.COL_OTHER;
}
}
return Phaser.Physics.Ninja.Circle.COL_NONE;
},
/**
* Resolves 67 Degree tile collision.
*
* @method Phaser.Physics.Ninja.Circle#projCircle_67DegB
* @param {number} x - Penetration depth on the x axis.
* @param {number} y - Penetration depth on the y axis.
* @param {number} oH - Grid / voronoi region.
* @param {number} oV - Grid / voronoi region.
* @param {Phaser.Physics.Ninja.Circle} obj - The Circle involved in the collision.
* @param {Phaser.Physics.Ninja.Tile} t - The Tile involved in the collision.
* @return {number} The result of the collision.
*/
projCircle_67DegB: function (x,y,oH, oV, obj,t) {
//if we're colliding diagonally:
// -if we're in the cell pointed at by the normal, collide vs slope, else
// collide vs. the appropriate corner/vertex
//
//if obj is in this tile: collide as with aabb
//
//if obj is horiz or vertical neighbor AGAINST the slope: collide with edge
//
//if obj is vert neighb in direction of slope: collide vs. slope or vertex or halfedge
//
//if obj is horiz neighb in direction of slope: collide vs. slope or vertex
var signx = t.signx;
var signy = t.signy;
if(oH == 0)
{
if(oV == 0)
{
//colliding with current cell
var sx = t.sx;
var sy = t.sy;
var r = obj.radius;
var ox = (obj.pos.x - (sx*r)) - (t.pos.x + (signx*t.xw));//this gives is the coordinates of the innermost
var oy = (obj.pos.y - (sy*r)) - (t.pos.y - (signy*t.yw));//point on the AABB, relative to a point on the slope
//if the dotprod of (ox,oy) and (sx,sy) is negative, the point on the circle is in the slope
//and we need toproject it out by the magnitude of the projection of (ox,oy) onto (sx,sy)
var dp = (ox*sx) + (oy*sy);
if(dp < 0)
{
//collision; project delta onto slope and use this to displace the object
sx *= -dp;//(sx,sy) is now the projection vector
sy *= -dp;
var lenN = Math.sqrt(sx*sx + sy*sy);
//find the smallest axial projection vector
if(x < y)
{
//penetration in x is smaller
lenP = x;
y = 0;
//get sign for projection along x-axis
if((obj.pos.x - t.pos.x) < 0)
{
x *= -1;
}
}
else
{
//penetration in y is smaller
lenP = y;
x = 0;
//get sign for projection along y-axis
if((obj.pos.y - t.pos.y)< 0)
{
y *= -1;
}
}
if(lenP < lenN)
{
obj.reportCollisionVsWorld(x,y,x/lenP, y/lenP, t);
return Phaser.Physics.Ninja.Circle.COL_AXIS;
}
else
{
obj.reportCollisionVsWorld(sx, sy, t.sx, t.sy, t);
return Phaser.Physics.Ninja.Circle.COL_OTHER;
}
}
}
else
{
//colliding vertically
if((signy*oV) < 0)
{
//colliding with face/edge
obj.reportCollisionVsWorld(0, y*oV, 0, oV, t);
return Phaser.Physics.Ninja.Circle.COL_AXIS;
}
else
{
//colliding with edge, slope, or vertex
var ox = obj.pos.x - t.pos.x;//this gives is the coordinates of the innermost
var oy = obj.pos.y - (t.pos.y + (signy*t.yw));//point on the circle, relative to the closest tile vert
if((ox*signx) < 0)
{
//we're colliding with the halfface
obj.reportCollisionVsWorld(0, y*oV, 0, oV, t);
return Phaser.Physics.Ninja.Circle.COL_AXIS;
}
else
{
//colliding with the vertex or slope
var sx = t.sx;
var sy = t.sy;
//if the component of (ox,oy) parallel to the normal's righthand normal
//has the same sign as the slope of the slope (the sign of the slope's slope is signx*signy)
//then we project by the vertex, otherwise by the slope.
//note that this is simply a VERY tricky/weird method of determining
//if the circle is in side the slope/face's voronio region, or that of the vertex.
var perp = (ox*-sy) + (oy*sx);
if(0 < (perp*signx*signy))
{
//collide vs. vertex
var len = Math.sqrt(ox*ox + oy*oy);
var pen = obj.radius - len;
if(0 < pen)
{
//note: if len=0, then perp=0 and we'll never reach here, so don't worry about div-by-0
ox /= len;
oy /= len;
obj.reportCollisionVsWorld(ox*pen, oy*pen, ox, oy, t);
return Phaser.Physics.Ninja.Circle.COL_OTHER;
}
}
else
{
//collide vs. slope
//if the component of (ox,oy) parallel to the normal is less than the circle radius, we're
//penetrating the slope. note that this method of penetration calculation doesn't hold
//in general (i.e it won't work if the circle is in the slope), but works in this case
//because we know the circle is in a neighboring cell
var dp = (ox*sx) + (oy*sy);
var pen = obj.radius - Math.abs(dp);//note: we don't need the abs because we know the dp will be positive, but just in case..
if(0 < pen)
{
//collision; circle out along normal by penetration amount
obj.reportCollisionVsWorld(sx*pen, sy*pen, sx, sy, t);
return Phaser.Physics.Ninja.Circle.COL_OTHER;
}
}
}
}
}
}
else if(oV == 0)
{
//colliding horizontally
if((signx*oH) < 0)
{
//colliding with face/edge
obj.reportCollisionVsWorld(x*oH, 0, oH, 0, t);
return Phaser.Physics.Ninja.Circle.COL_AXIS;
}
else
{
//we could only be colliding vs the slope OR a vertex
//look at the vector form the closest vert to the circle to decide
var slen = Math.sqrt(2*2 + 1*1);//the raw slope is (-2,-1)
var sx = (signx*2) / slen;//get slope _unit_ normal;
var sy = (signy*1) / slen;//raw RH normal is (1,-2)
var ox = obj.pos.x - (t.pos.x + (signx*t.xw));//this gives is the coordinates of the innermost
var oy = obj.pos.y - (t.pos.y - (signy*t.yw));//point on the circle, relative to the closest tile vert
//if the component of (ox,oy) parallel to the normal's righthand normal
//has the same sign as the slope of the slope (the sign of the slope's slope is signx*signy)
//then we project by the slope, otherwise by the vertex.
//note that this is simply a VERY tricky/weird method of determining
//if the circle is in side the slope/face's voronio region, or that of the vertex.
var perp = (ox*-sy) + (oy*sx);
if((perp*signx*signy) < 0)
{
//collide vs. vertex
var len = Math.sqrt(ox*ox + oy*oy);
var pen = obj.radius - len;
if(0 < pen)
{
//note: if len=0, then perp=0 and we'll never reach here, so don't worry about div-by-0
ox /= len;
oy /= len;
obj.reportCollisionVsWorld(ox*pen, oy*pen, ox, oy, t);
return Phaser.Physics.Ninja.Circle.COL_OTHER;
}
}
else
{
//collide vs. slope
//if the component of (ox,oy) parallel to the normal is less than the circle radius, we're
//penetrating the slope. note that this method of penetration calculation doesn't hold
//in general (i.e it won't work if the circle is in the slope), but works in this case
//because we know the circle is in a neighboring cell
var dp = (ox*sx) + (oy*sy);
var pen = obj.radius - Math.abs(dp);//note: we don't need the abs because we know the dp will be positive, but just in case..
if(0 < pen)
{
//collision; circle out along normal by penetration amount
obj.reportCollisionVsWorld(sx*pen, sy*pen, t.sx, t.sy, t);
return Phaser.Physics.Ninja.Circle.COL_OTHER;
}
}
}
}
else
{
//colliding diagonally
if( 0 < ((signx*oH) + (signy*oV)) )
{
//the dotprod of slope normal and cell offset is strictly positive,
//therefore obj is in the diagonal neighb pointed at by the normal.
//collide vs slope
var sx = t.sx;
var sy = t.sy;
var r = obj.radius;
var ox = (obj.pos.x - (sx*r)) - (t.pos.x + (signx*t.xw));//this gives is the coordinates of the innermost
var oy = (obj.pos.y - (sy*r)) - (t.pos.y - (signy*t.yw));//point on the circle, relative to a point on the slope
//if the dotprod of (ox,oy) and (sx,sy) is negative, the point on the circle is in the slope
//and we need toproject it out by the magnitude of the projection of (ox,oy) onto (sx,sy)
var dp = (ox*sx) + (oy*sy);
if(dp < 0)
{
//collision; project delta onto slope and use this to displace the object
//(sx,sy)*-dp is the projection vector
obj.reportCollisionVsWorld(-sx*dp, -sy*dp, t.sx, t.sy, t);
return Phaser.Physics.Ninja.Circle.COL_OTHER;
}
return Phaser.Physics.Ninja.Circle.COL_NONE;
}
else
{
//collide vs the appropriate vertex
var vx = t.pos.x + (oH*t.xw);
var vy = t.pos.y + (oV*t.yw);
var dx = obj.pos.x - vx;//calc vert->circle vector
var dy = obj.pos.y - vy;
var len = Math.sqrt(dx*dx + dy*dy);
var pen = obj.radius - len;
if(0 < pen)
{
//vertex is in the circle; project outward
if(len == 0)
{
//project out by 45deg
dx = oH / Math.SQRT2;
dy = oV / Math.SQRT2;
}
else
{
dx /= len;
dy /= len;
}
obj.reportCollisionVsWorld(dx*pen, dy*pen, dx, dy, t);
return Phaser.Physics.Ninja.Circle.COL_OTHER;
}
}
}
return Phaser.Physics.Ninja.Circle.COL_NONE;
}
}
/**
* The MIT License (MIT)
*
* Copyright (c) 2013 p2.js authors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
!function(e){"object"==typeof exports?module.exports=e():"function"==typeof define&&define.amd?define('p2', (function() { return this.p2 = e(); })()):"undefined"!=typeof window?window.p2=e():"undefined"!=typeof global?self.p2=e():"undefined"!=typeof self&&(self.p2=e())}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
/* Copyright (c) 2012, Brandon Jones, Colin MacKenzie IV. All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
/**
* @class 2x2 Matrix
* @name mat2
*/
var mat2 = {};
var mat2Identity = new Float32Array([
1, 0,
0, 1
]);
if(!GLMAT_EPSILON) {
var GLMAT_EPSILON = 0.000001;
}
/**
* Creates a new identity mat2
*
* @returns {mat2} a new 2x2 matrix
*/
mat2.create = function() {
return new Float32Array(mat2Identity);
};
/**
* Creates a new mat2 initialized with values from an existing matrix
*
* @param {mat2} a matrix to clone
* @returns {mat2} a new 2x2 matrix
*/
mat2.clone = function(a) {
var out = new Float32Array(4);
out[0] = a[0];
out[1] = a[1];
out[2] = a[2];
out[3] = a[3];
return out;
};
/**
* Copy the values from one mat2 to another
*
* @param {mat2} out the receiving matrix
* @param {mat2} a the source matrix
* @returns {mat2} out
*/
mat2.copy = function(out, a) {
out[0] = a[0];
out[1] = a[1];
out[2] = a[2];
out[3] = a[3];
return out;
};
/**
* Set a mat2 to the identity matrix
*
* @param {mat2} out the receiving matrix
* @returns {mat2} out
*/
mat2.identity = function(out) {
out[0] = 1;
out[1] = 0;
out[2] = 0;
out[3] = 1;
return out;
};
/**
* Transpose the values of a mat2
*
* @param {mat2} out the receiving matrix
* @param {mat2} a the source matrix
* @returns {mat2} out
*/
mat2.transpose = function(out, a) {
// If we are transposing ourselves we can skip a few steps but have to cache some values
if (out === a) {
var a1 = a[1];
out[1] = a[2];
out[2] = a1;
} else {
out[0] = a[0];
out[1] = a[2];
out[2] = a[1];
out[3] = a[3];
}
return out;
};
/**
* Inverts a mat2
*
* @param {mat2} out the receiving matrix
* @param {mat2} a the source matrix
* @returns {mat2} out
*/
mat2.invert = function(out, a) {
var a0 = a[0], a1 = a[1], a2 = a[2], a3 = a[3],
// Calculate the determinant
det = a0 * a3 - a2 * a1;
if (!det) {
return null;
}
det = 1.0 / det;
out[0] = a3 * det;
out[1] = -a1 * det;
out[2] = -a2 * det;
out[3] = a0 * det;
return out;
};
/**
* Caclulates the adjugate of a mat2
*
* @param {mat2} out the receiving matrix
* @param {mat2} a the source matrix
* @returns {mat2} out
*/
mat2.adjoint = function(out, a) {
// Caching this value is nessecary if out == a
var a0 = a[0];
out[0] = a[3];
out[1] = -a[1];
out[2] = -a[2];
out[3] = a0;
return out;
};
/**
* Calculates the determinant of a mat2
*
* @param {mat2} a the source matrix
* @returns {Number} determinant of a
*/
mat2.determinant = function (a) {
return a[0] * a[3] - a[2] * a[1];
};
/**
* Multiplies two mat2's
*
* @param {mat2} out the receiving matrix
* @param {mat2} a the first operand
* @param {mat2} b the second operand
* @returns {mat2} out
*/
mat2.multiply = function (out, a, b) {
var a0 = a[0], a1 = a[1], a2 = a[2], a3 = a[3];
var b0 = b[0], b1 = b[1], b2 = b[2], b3 = b[3];
out[0] = a0 * b0 + a1 * b2;
out[1] = a0 * b1 + a1 * b3;
out[2] = a2 * b0 + a3 * b2;
out[3] = a2 * b1 + a3 * b3;
return out;
};
/**
* Alias for {@link mat2.multiply}
* @function
*/
mat2.mul = mat2.multiply;
/**
* Rotates a mat2 by the given angle
*
* @param {mat2} out the receiving matrix
* @param {mat2} a the matrix to rotate
* @param {mat2} rad the angle to rotate the matrix by
* @returns {mat2} out
*/
mat2.rotate = function (out, a, rad) {
var a0 = a[0], a1 = a[1], a2 = a[2], a3 = a[3],
s = Math.sin(rad),
c = Math.cos(rad);
out[0] = a0 * c + a1 * s;
out[1] = a0 * -s + a1 * c;
out[2] = a2 * c + a3 * s;
out[3] = a2 * -s + a3 * c;
return out;
};
/**
* Scales the mat2 by the dimensions in the given vec2
*
* @param {mat2} out the receiving matrix
* @param {mat2} a the matrix to rotate
* @param {mat2} v the vec2 to scale the matrix by
* @returns {mat2} out
**/
mat2.scale = function(out, a, v) {
var a0 = a[0], a1 = a[1], a2 = a[2], a3 = a[3],
v0 = v[0], v1 = v[1];
out[0] = a0 * v0;
out[1] = a1 * v1;
out[2] = a2 * v0;
out[3] = a3 * v1;
return out;
};
/**
* Returns a string representation of a mat2
*
* @param {mat2} mat matrix to represent as a string
* @returns {String} string representation of the matrix
*/
mat2.str = function (a) {
return 'mat2(' + a[0] + ', ' + a[1] + ', ' + a[2] + ', ' + a[3] + ')';
};
if(typeof(exports) !== 'undefined') {
exports.mat2 = mat2;
}
},{}],2:[function(require,module,exports){
/* Copyright (c) 2012, Brandon Jones, Colin MacKenzie IV. All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
/**
* @class 2 Dimensional Vector
* @name vec2
*/
var vec2 = {};
if(!GLMAT_EPSILON) {
var GLMAT_EPSILON = 0.000001;
}
/**
* Creates a new, empty vec2
*
* @returns {vec2} a new 2D vector
*/
vec2.create = function() {
return new Float32Array(2);
};
/**
* Creates a new vec2 initialized with values from an existing vector
*
* @param {vec2} a vector to clone
* @returns {vec2} a new 2D vector
*/
vec2.clone = function(a) {
var out = new Float32Array(2);
out[0] = a[0];
out[1] = a[1];
return out;
};
/**
* Creates a new vec2 initialized with the given values
*
* @param {Number} x X component
* @param {Number} y Y component
* @returns {vec2} a new 2D vector
*/
vec2.fromValues = function(x, y) {
var out = new Float32Array(2);
out[0] = x;
out[1] = y;
return out;
};
/**
* Copy the values from one vec2 to another
*
* @param {vec2} out the receiving vector
* @param {vec2} a the source vector
* @returns {vec2} out
*/
vec2.copy = function(out, a) {
out[0] = a[0];
out[1] = a[1];
return out;
};
/**
* Set the components of a vec2 to the given values
*
* @param {vec2} out the receiving vector
* @param {Number} x X component
* @param {Number} y Y component
* @returns {vec2} out
*/
vec2.set = function(out, x, y) {
out[0] = x;
out[1] = y;
return out;
};
/**
* Adds two vec2's
*
* @param {vec2} out the receiving vector
* @param {vec2} a the first operand
* @param {vec2} b the second operand
* @returns {vec2} out
*/
vec2.add = function(out, a, b) {
out[0] = a[0] + b[0];
out[1] = a[1] + b[1];
return out;
};
/**
* Subtracts two vec2's
*
* @param {vec2} out the receiving vector
* @param {vec2} a the first operand
* @param {vec2} b the second operand
* @returns {vec2} out
*/
vec2.subtract = function(out, a, b) {
out[0] = a[0] - b[0];
out[1] = a[1] - b[1];
return out;
};
/**
* Alias for {@link vec2.subtract}
* @function
*/
vec2.sub = vec2.subtract;
/**
* Multiplies two vec2's
*
* @param {vec2} out the receiving vector
* @param {vec2} a the first operand
* @param {vec2} b the second operand
* @returns {vec2} out
*/
vec2.multiply = function(out, a, b) {
out[0] = a[0] * b[0];
out[1] = a[1] * b[1];
return out;
};
/**
* Alias for {@link vec2.multiply}
* @function
*/
vec2.mul = vec2.multiply;
/**
* Divides two vec2's
*
* @param {vec2} out the receiving vector
* @param {vec2} a the first operand
* @param {vec2} b the second operand
* @returns {vec2} out
*/
vec2.divide = function(out, a, b) {
out[0] = a[0] / b[0];
out[1] = a[1] / b[1];
return out;
};
/**
* Alias for {@link vec2.divide}
* @function
*/
vec2.div = vec2.divide;
/**
* Returns the minimum of two vec2's
*
* @param {vec2} out the receiving vector
* @param {vec2} a the first operand
* @param {vec2} b the second operand
* @returns {vec2} out
*/
vec2.min = function(out, a, b) {
out[0] = Math.min(a[0], b[0]);
out[1] = Math.min(a[1], b[1]);
return out;
};
/**
* Returns the maximum of two vec2's
*
* @param {vec2} out the receiving vector
* @param {vec2} a the first operand
* @param {vec2} b the second operand
* @returns {vec2} out
*/
vec2.max = function(out, a, b) {
out[0] = Math.max(a[0], b[0]);
out[1] = Math.max(a[1], b[1]);
return out;
};
/**
* Scales a vec2 by a scalar number
*
* @param {vec2} out the receiving vector
* @param {vec2} a the vector to scale
* @param {vec2} b amount to scale the vector by
* @returns {vec2} out
*/
vec2.scale = function(out, a, b) {
out[0] = a[0] * b;
out[1] = a[1] * b;
return out;
};
/**
* Calculates the euclidian distance between two vec2's
*
* @param {vec2} a the first operand
* @param {vec2} b the second operand
* @returns {Number} distance between a and b
*/
vec2.distance = function(a, b) {
var x = b[0] - a[0],
y = b[1] - a[1];
return Math.sqrt(x*x + y*y);
};
/**
* Alias for {@link vec2.distance}
* @function
*/
vec2.dist = vec2.distance;
/**
* Calculates the squared euclidian distance between two vec2's
*
* @param {vec2} a the first operand
* @param {vec2} b the second operand
* @returns {Number} squared distance between a and b
*/
vec2.squaredDistance = function(a, b) {
var x = b[0] - a[0],
y = b[1] - a[1];
return x*x + y*y;
};
/**
* Alias for {@link vec2.squaredDistance}
* @function
*/
vec2.sqrDist = vec2.squaredDistance;
/**
* Caclulates the length of a vec2
*
* @param {vec2} a vector to calculate length of
* @returns {Number} length of a
*/
vec2.length = function (a) {
var x = a[0],
y = a[1];
return Math.sqrt(x*x + y*y);
};
/**
* Alias for {@link vec2.length}
* @function
*/
vec2.len = vec2.length;
/**
* Caclulates the squared length of a vec2
*
* @param {vec2} a vector to calculate squared length of
* @returns {Number} squared length of a
*/
vec2.squaredLength = function (a) {
var x = a[0],
y = a[1];
return x*x + y*y;
};
/**
* Alias for {@link vec2.squaredLength}
* @function
*/
vec2.sqrLen = vec2.squaredLength;
/**
* Negates the components of a vec2
*
* @param {vec2} out the receiving vector
* @param {vec2} a vector to negate
* @returns {vec2} out
*/
vec2.negate = function(out, a) {
out[0] = -a[0];
out[1] = -a[1];
return out;
};
/**
* Normalize a vec2
*
* @param {vec2} out the receiving vector
* @param {vec2} a vector to normalize
* @returns {vec2} out
*/
vec2.normalize = function(out, a) {
var x = a[0],
y = a[1];
var len = x*x + y*y;
if (len > 0) {
//TODO: evaluate use of glm_invsqrt here?
len = 1 / Math.sqrt(len);
out[0] = a[0] * len;
out[1] = a[1] * len;
}
return out;
};
/**
* Caclulates the dot product of two vec2's
*
* @param {vec2} a the first operand
* @param {vec2} b the second operand
* @returns {Number} dot product of a and b
*/
vec2.dot = function (a, b) {
return a[0] * b[0] + a[1] * b[1];
};
/**
* Computes the cross product of two vec2's
* Note that the cross product must by definition produce a 3D vector
*
* @param {vec3} out the receiving vector
* @param {vec2} a the first operand
* @param {vec2} b the second operand
* @returns {vec3} out
*/
vec2.cross = function(out, a, b) {
var z = a[0] * b[1] - a[1] * b[0];
out[0] = out[1] = 0;
out[2] = z;
return out;
};
/**
* Performs a linear interpolation between two vec2's
*
* @param {vec3} out the receiving vector
* @param {vec2} a the first operand
* @param {vec2} b the second operand
* @param {Number} t interpolation amount between the two inputs
* @returns {vec2} out
*/
vec2.lerp = function (out, a, b, t) {
var ax = a[0],
ay = a[1];
out[0] = ax + t * (b[0] - ax);
out[1] = ay + t * (b[1] - ay);
return out;
};
/**
* Transforms the vec2 with a mat2
*
* @param {vec2} out the receiving vector
* @param {vec2} a the vector to transform
* @param {mat2} m matrix to transform with
* @returns {vec2} out
*/
vec2.transformMat2 = function(out, a, m) {
var x = a[0],
y = a[1];
out[0] = x * m[0] + y * m[1];
out[1] = x * m[2] + y * m[3];
return out;
};
/**
* Perform some operation over an array of vec2s.
*
* @param {Array} a the array of vectors to iterate over
* @param {Number} stride Number of elements between the start of each vec2. If 0 assumes tightly packed
* @param {Number} offset Number of elements to skip at the beginning of the array
* @param {Number} count Number of vec2s to iterate over. If 0 iterates over entire array
* @param {Function} fn Function to call for each vector in the array
* @param {Object} [arg] additional argument to pass to fn
* @returns {Array} a
* @function
*/
vec2.forEach = (function() {
var vec = new Float32Array(2);
return function(a, stride, offset, count, fn, arg) {
var i, l;
if(!stride) {
stride = 2;
}
if(!offset) {
offset = 0;
}
if(count) {
l = Math.min((count * stride) + offset, a.length);
} else {
l = a.length;
}
for(i = offset; i < l; i += stride) {
vec[0] = a[i]; vec[1] = a[i+1];
fn(vec, vec, arg);
a[i] = vec[0]; a[i+1] = vec[1];
}
return a;
};
})();
/**
* Returns a string representation of a vector
*
* @param {vec2} vec vector to represent as a string
* @returns {String} string representation of the vector
*/
vec2.str = function (a) {
return 'vec2(' + a[0] + ', ' + a[1] + ')';
};
if(typeof(exports) !== 'undefined') {
exports.vec2 = vec2;
}
},{}],3:[function(require,module,exports){
var Scalar = require('./Scalar');
module.exports = Line;
/**
* Container for line-related functions
* @class Line
*/
function Line(){};
/**
* Compute the intersection between two lines.
* @static
* @method lineInt
* @param {Array} l1 Line vector 1
* @param {Array} l2 Line vector 2
* @param {Number} precision Precision to use when checking if the lines are parallel
* @return {Array} The intersection point.
*/
Line.lineInt = function(l1,l2,precision){
precision = precision || 0;
var i = [0,0]; // point
var a1, b1, c1, a2, b2, c2, det; // scalars
a1 = l1[1][1] - l1[0][1];
b1 = l1[0][0] - l1[1][0];
c1 = a1 * l1[0][0] + b1 * l1[0][1];
a2 = l2[1][1] - l2[0][1];
b2 = l2[0][0] - l2[1][0];
c2 = a2 * l2[0][0] + b2 * l2[0][1];
det = a1 * b2 - a2*b1;
if (!Scalar.eq(det, 0, precision)) { // lines are not parallel
i[0] = (b2 * c1 - b1 * c2) / det;
i[1] = (a1 * c2 - a2 * c1) / det;
}
return i;
};
/**
* Checks if two line segments intersects.
* @method segmentsIntersect
* @param {Array} p1 The start vertex of the first line segment.
* @param {Array} p2 The end vertex of the first line segment.
* @param {Array} q1 The start vertex of the second line segment.
* @param {Array} q2 The end vertex of the second line segment.
* @return {Boolean} True if the two line segments intersect
*/
Line.segmentsIntersect = function(p1, p2, q1, q2){
var dx = p2[0] - p1[0];
var dy = p2[1] - p1[1];
var da = q2[0] - q1[0];
var db = q2[1] - q1[1];
// segments are parallel
if(da*dy - db*dx == 0)
return false;
var s = (dx * (q1[1] - p1[1]) + dy * (p1[0] - q1[0])) / (da * dy - db * dx)
var t = (da * (p1[1] - q1[1]) + db * (q1[0] - p1[0])) / (db * dx - da * dy)
return (s>=0 && s<=1 && t>=0 && t<=1);
};
},{"./Scalar":6}],4:[function(require,module,exports){
module.exports = Point;
/**
* Point related functions
* @class Point
*/
function Point(){};
/**
* Get the area of a triangle spanned by the three given points. Note that the area will be negative if the points are not given in counter-clockwise order.
* @static
* @method area
* @param {Array} a
* @param {Array} b
* @param {Array} c
* @return {Number}
*/
Point.area = function(a,b,c){
return (((b[0] - a[0])*(c[1] - a[1]))-((c[0] - a[0])*(b[1] - a[1])));
};
Point.left = function(a,b,c){
return Point.area(a,b,c) > 0;
};
Point.leftOn = function(a,b,c) {
return Point.area(a, b, c) >= 0;
};
Point.right = function(a,b,c) {
return Point.area(a, b, c) < 0;
};
Point.rightOn = function(a,b,c) {
return Point.area(a, b, c) <= 0;
};
var tmpPoint1 = [],
tmpPoint2 = [];
/**
* Check if three points are collinear
* @method collinear
* @param {Array} a
* @param {Array} b
* @param {Array} c
* @param {Number} [thresholdAngle=0] Threshold angle to use when comparing the vectors. The function will return true if the angle between the resulting vectors is less than this value. Use zero for max precision.
* @return {Boolean}
*/
Point.collinear = function(a,b,c,thresholdAngle) {
if(!thresholdAngle)
return Point.area(a, b, c) == 0;
else {
var ab = tmpPoint1,
bc = tmpPoint2;
ab[0] = b[0]-a[0];
ab[1] = b[1]-a[1];
bc[0] = c[0]-b[0];
bc[1] = c[1]-b[1];
var dot = ab[0]*bc[0] + ab[1]*bc[1],
magA = Math.sqrt(ab[0]*ab[0] + ab[1]*ab[1]),
magB = Math.sqrt(bc[0]*bc[0] + bc[1]*bc[1]),
angle = Math.acos(dot/(magA*magB));
return angle < thresholdAngle;
}
};
Point.sqdist = function(a,b){
var dx = b[0] - a[0];
var dy = b[1] - a[1];
return dx * dx + dy * dy;
};
},{}],5:[function(require,module,exports){
var Line = require("./Line")
, Point = require("./Point")
, Scalar = require("./Scalar")
module.exports = Polygon;
/**
* Polygon class.
* @class Polygon
* @constructor
*/
function Polygon(){
/**
* Vertices that this polygon consists of. An array of array of numbers, example: [[0,0],[1,0],..]
* @property vertices
* @type {Array}
*/
this.vertices = [];
}
/**
* Get a vertex at position i. It does not matter if i is out of bounds, this function will just cycle.
* @method at
* @param {Number} i
* @return {Array}
*/
Polygon.prototype.at = function(i){
var v = this.vertices,
s = v.length;
return v[i < 0 ? i % s + s : i % s];
};
/**
* Get first vertex
* @method first
* @return {Array}
*/
Polygon.prototype.first = function(){
return this.vertices[0];
};
/**
* Get last vertex
* @method last
* @return {Array}
*/
Polygon.prototype.last = function(){
return this.vertices[this.vertices.length-1];
};
/**
* Clear the polygon data
* @method clear
* @return {Array}
*/
Polygon.prototype.clear = function(){
this.vertices.length = 0;
};
/**
* Append points "from" to "to"-1 from an other polygon "poly" onto this one.
* @method append
* @param {Polygon} poly The polygon to get points from.
* @param {Number} from The vertex index in "poly".
* @param {Number} to The end vertex index in "poly". Note that this vertex is NOT included when appending.
* @return {Array}
*/
Polygon.prototype.append = function(poly,from,to){
if(typeof(from) == "undefined") throw new Error("From is not given!");
if(typeof(to) == "undefined") throw new Error("To is not given!");
if(to-1 < from) throw new Error("lol1");
if(to > poly.vertices.length) throw new Error("lol2");
if(from < 0) throw new Error("lol3");
for(var i=from; i<to; i++){
this.vertices.push(poly.vertices[i]);
}
};
/**
* Make sure that the polygon vertices are ordered counter-clockwise.
* @method makeCCW
*/
Polygon.prototype.makeCCW = function(){
var br = 0,
v = this.vertices;
// find bottom right point
for (var i = 1; i < this.vertices.length; ++i) {
if (v[i][1] < v[br][1] || (v[i][1] == v[br][1] && v[i][0] > v[br][0])) {
br = i;
}
}
// reverse poly if clockwise
if (!Point.left(this.at(br - 1), this.at(br), this.at(br + 1))) {
this.reverse();
}
};
/**
* Reverse the vertices in the polygon
* @method reverse
*/
Polygon.prototype.reverse = function(){
var tmp = [];
for(var i=0, N=this.vertices.length; i!==N; i++){
tmp.push(this.vertices.pop());
}
this.vertices = tmp;
};
/**
* Check if a point in the polygon is a reflex point
* @method isReflex
* @param {Number} i
* @return {Boolean}
*/
Polygon.prototype.isReflex = function(i){
return Point.right(this.at(i - 1), this.at(i), this.at(i + 1));
};
var tmpLine1=[],
tmpLine2=[];
/**
* Check if two vertices in the polygon can see each other
* @method canSee
* @param {Number} a Vertex index 1
* @param {Number} b Vertex index 2
* @return {Boolean}
*/
Polygon.prototype.canSee = function(a,b) {
var p, dist, l1=tmpLine1, l2=tmpLine2;
if (Point.leftOn(this.at(a + 1), this.at(a), this.at(b)) && Point.rightOn(this.at(a - 1), this.at(a), this.at(b))) {
return false;
}
dist = Point.sqdist(this.at(a), this.at(b));
for (var i = 0; i !== this.vertices.length; ++i) { // for each edge
if ((i + 1) % this.vertices.length === a || i === a) // ignore incident edges
continue;
if (Point.leftOn(this.at(a), this.at(b), this.at(i + 1)) && Point.rightOn(this.at(a), this.at(b), this.at(i))) { // if diag intersects an edge
l1[0] = this.at(a);
l1[1] = this.at(b);
l2[0] = this.at(i);
l2[1] = this.at(i + 1);
p = Line.lineInt(l1,l2);
if (Point.sqdist(this.at(a), p) < dist) { // if edge is blocking visibility to b
return false;
}
}
}
return true;
};
/**
* Copy the polygon from vertex i to vertex j.
* @method copy
* @param {Number} i
* @param {Number} j
* @param {Polygon} [targetPoly] Optional target polygon to save in.
* @return {Polygon} The resulting copy.
*/
Polygon.prototype.copy = function(i,j,targetPoly){
var p = targetPoly || new Polygon();
p.clear();
if (i < j) {
// Insert all vertices from i to j
for(var k=i; k<=j; k++)
p.vertices.push(this.vertices[k]);
} else {
// Insert vertices 0 to j
for(var k=0; k<=j; k++)
p.vertices.push(this.vertices[k]);
// Insert vertices i to end
for(var k=i; k<this.vertices.length; k++)
p.vertices.push(this.vertices[k]);
}
return p;
};
/**
* Decomposes the polygon into convex pieces. Returns a list of edges [[p1,p2],[p2,p3],...] that cuts the polygon.
* Note that this algorithm has complexity O(N^4) and will be very slow for polygons with many vertices.
* @method getCutEdges
* @return {Array}
*/
Polygon.prototype.getCutEdges = function() {
var min=[], tmp1=[], tmp2=[], tmpPoly = new Polygon();
var nDiags = Number.MAX_VALUE;
for (var i = 0; i < this.vertices.length; ++i) {
if (this.isReflex(i)) {
for (var j = 0; j < this.vertices.length; ++j) {
if (this.canSee(i, j)) {
tmp1 = this.copy(i, j, tmpPoly).getCutEdges();
tmp2 = this.copy(j, i, tmpPoly).getCutEdges();
for(var k=0; k<tmp2.length; k++)
tmp1.push(tmp2[k]);
if (tmp1.length < nDiags) {
min = tmp1;
nDiags = tmp1.length;
min.push([this.at(i), this.at(j)]);
}
}
}
}
}
return min;
};
/**
* Decomposes the polygon into one or more convex sub-Polygons.
* @method decomp
* @return {Array} An array or Polygon objects.
*/
Polygon.prototype.decomp = function(){
var edges = this.getCutEdges();
if(edges.length > 0)
return this.slice(edges);
else
return [this];
};
/**
* Slices the polygon given one or more cut edges. If given one, this function will return two polygons (false on failure). If many, an array of polygons.
* @method slice
* @param {Array} cutEdges A list of edges, as returned by .getCutEdges()
* @return {Array}
*/
Polygon.prototype.slice = function(cutEdges){
if(cutEdges.length == 0) return [this];
if(cutEdges instanceof Array && cutEdges.length && cutEdges[0] instanceof Array && cutEdges[0].length==2 && cutEdges[0][0] instanceof Array){
var polys = [this];
for(var i=0; i<cutEdges.length; i++){
var cutEdge = cutEdges[i];
// Cut all polys
for(var j=0; j<polys.length; j++){
var poly = polys[j];
var result = poly.slice(cutEdge);
if(result){
// Found poly! Cut and quit
polys.splice(j,1);
polys.push(result[0],result[1]);
break;
}
}
}
return polys;
} else {
// Was given one edge
var cutEdge = cutEdges;
var i = this.vertices.indexOf(cutEdge[0]);
var j = this.vertices.indexOf(cutEdge[1]);
if(i != -1 && j != -1){
return [this.copy(i,j),
this.copy(j,i)];
} else {
return false;
}
}
};
/**
* Checks that the line segments of this polygon do not intersect each other.
* @method isSimple
* @param {Array} path An array of vertices e.g. [[0,0],[0,1],...]
* @return {Boolean}
* @todo Should it check all segments with all others?
*/
Polygon.prototype.isSimple = function(){
var path = this.vertices;
// Check
for(var i=0; i<path.length-1; i++){
for(var j=0; j<i-1; j++){
if(Line.segmentsIntersect(path[i], path[i+1], path[j], path[j+1] )){
return false;
}
}
}
// Check the segment between the last and the first point to all others
for(var i=1; i<path.length-2; i++){
if(Line.segmentsIntersect(path[0], path[path.length-1], path[i], path[i+1] )){
return false;
}
}
return true;
};
function getIntersectionPoint(p1, p2, q1, q2, delta){
delta = delta || 0;
var a1 = p2[1] - p1[1];
var b1 = p1[0] - p2[0];
var c1 = (a1 * p1[0]) + (b1 * p1[1]);
var a2 = q2[1] - q1[1];
var b2 = q1[0] - q2[0];
var c2 = (a2 * q1[0]) + (b2 * q1[1]);
var det = (a1 * b2) - (a2 * b1);
if(!Scalar.eq(det,0,delta))
return [((b2 * c1) - (b1 * c2)) / det, ((a1 * c2) - (a2 * c1)) / det]
else
return [0,0]
}
/**
* Quickly decompose the Polygon into convex sub-polygons.
* @method quickDecomp
* @param {Array} result
* @param {Array} [reflexVertices]
* @param {Array} [steinerPoints]
* @param {Number} [delta]
* @param {Number} [maxlevel]
* @param {Number} [level]
* @return {Array}
*/
Polygon.prototype.quickDecomp = function(result,reflexVertices,steinerPoints,delta,maxlevel,level){
maxlevel = maxlevel || 100;
level = level || 0;
delta = delta || 25;
result = typeof(result)!="undefined" ? result : [];
reflexVertices = reflexVertices || [];
steinerPoints = steinerPoints || [];
var upperInt=[0,0], lowerInt=[0,0], p=[0,0]; // Points
var upperDist=0, lowerDist=0, d=0, closestDist=0; // scalars
var upperIndex=0, lowerIndex=0, closestIndex=0; // Integers
var lowerPoly=new Polygon(), upperPoly=new Polygon(); // polygons
var poly = this,
v = this.vertices;
if(v.length < 3) return result;
level++;
if(level > maxlevel){
console.warn("quickDecomp: max level ("+maxlevel+") reached.");
return result;
}
for (var i = 0; i < this.vertices.length; ++i) {
if (poly.isReflex(i)) {
reflexVertices.push(poly.vertices[i]);
upperDist = lowerDist = Number.MAX_VALUE;
for (var j = 0; j < this.vertices.length; ++j) {
if (Point.left(poly.at(i - 1), poly.at(i), poly.at(j))
&& Point.rightOn(poly.at(i - 1), poly.at(i), poly.at(j - 1))) { // if line intersects with an edge
p = getIntersectionPoint(poly.at(i - 1), poly.at(i), poly.at(j), poly.at(j - 1)); // find the point of intersection
if (Point.right(poly.at(i + 1), poly.at(i), p)) { // make sure it's inside the poly
d = Point.sqdist(poly.vertices[i], p);
if (d < lowerDist) { // keep only the closest intersection
lowerDist = d;
lowerInt = p;
lowerIndex = j;
}
}
}
if (Point.left(poly.at(i + 1), poly.at(i), poly.at(j + 1))
&& Point.rightOn(poly.at(i + 1), poly.at(i), poly.at(j))) {
p = getIntersectionPoint(poly.at(i + 1), poly.at(i), poly.at(j), poly.at(j + 1));
if (Point.left(poly.at(i - 1), poly.at(i), p)) {
d = Point.sqdist(poly.vertices[i], p);
if (d < upperDist) {
upperDist = d;
upperInt = p;
upperIndex = j;
}
}
}
}
// if there are no vertices to connect to, choose a point in the middle
if (lowerIndex == (upperIndex + 1) % this.vertices.length) {
//console.log("Case 1: Vertex("+i+"), lowerIndex("+lowerIndex+"), upperIndex("+upperIndex+"), poly.size("+this.vertices.length+")");
p[0] = (lowerInt[0] + upperInt[0]) / 2;
p[1] = (lowerInt[1] + upperInt[1]) / 2;
steinerPoints.push(p);
if (i < upperIndex) {
//lowerPoly.insert(lowerPoly.end(), poly.begin() + i, poly.begin() + upperIndex + 1);
lowerPoly.append(poly, i, upperIndex+1);
lowerPoly.vertices.push(p);
upperPoly.vertices.push(p);
if (lowerIndex != 0){
//upperPoly.insert(upperPoly.end(), poly.begin() + lowerIndex, poly.end());
upperPoly.append(poly,lowerIndex,poly.vertices.length);
}
//upperPoly.insert(upperPoly.end(), poly.begin(), poly.begin() + i + 1);
upperPoly.append(poly,0,i+1);
} else {
if (i != 0){
//lowerPoly.insert(lowerPoly.end(), poly.begin() + i, poly.end());
lowerPoly.append(poly,i,poly.vertices.length);
}
//lowerPoly.insert(lowerPoly.end(), poly.begin(), poly.begin() + upperIndex + 1);
lowerPoly.append(poly,0,upperIndex+1);
lowerPoly.vertices.push(p);
upperPoly.vertices.push(p);
//upperPoly.insert(upperPoly.end(), poly.begin() + lowerIndex, poly.begin() + i + 1);
upperPoly.append(poly,lowerIndex,i+1);
}
} else {
// connect to the closest point within the triangle
//console.log("Case 2: Vertex("+i+"), closestIndex("+closestIndex+"), poly.size("+this.vertices.length+")\n");
if (lowerIndex > upperIndex) {
upperIndex += this.vertices.length;
}
closestDist = Number.MAX_VALUE;
if(upperIndex < lowerIndex){
return result;
}
for (var j = lowerIndex; j <= upperIndex; ++j) {
if (Point.leftOn(poly.at(i - 1), poly.at(i), poly.at(j))
&& Point.rightOn(poly.at(i + 1), poly.at(i), poly.at(j))) {
d = Point.sqdist(poly.at(i), poly.at(j));
if (d < closestDist) {
closestDist = d;
closestIndex = j % this.vertices.length;
}
}
}
if (i < closestIndex) {
lowerPoly.append(poly,i,closestIndex+1);
if (closestIndex != 0){
upperPoly.append(poly,closestIndex,v.length);
}
upperPoly.append(poly,0,i+1);
} else {
if (i != 0){
lowerPoly.append(poly,i,v.length);
}
lowerPoly.append(poly,0,closestIndex+1);
upperPoly.append(poly,closestIndex,i+1);
}
}
// solve smallest poly first
if (lowerPoly.vertices.length < upperPoly.vertices.length) {
lowerPoly.quickDecomp(result,reflexVertices,steinerPoints,delta,maxlevel,level);
upperPoly.quickDecomp(result,reflexVertices,steinerPoints,delta,maxlevel,level);
} else {
upperPoly.quickDecomp(result,reflexVertices,steinerPoints,delta,maxlevel,level);
lowerPoly.quickDecomp(result,reflexVertices,steinerPoints,delta,maxlevel,level);
}
return result;
}
}
result.push(this);
return result;
};
/**
* Remove collinear points in the polygon.
* @method removeCollinearPoints
* @param {Number} [precision] The threshold angle to use when determining whether two edges are collinear. Use zero for finest precision.
* @return {Number} The number of points removed
*/
Polygon.prototype.removeCollinearPoints = function(precision){
var num = 0;
for(var i=this.vertices.length-1; this.vertices.length>3 && i>=0; --i){
if(Point.collinear(this.at(i-1),this.at(i),this.at(i+1),precision)){
// Remove the middle point
this.vertices.splice(i%this.vertices.length,1);
i--; // Jump one point forward. Otherwise we may get a chain removal
num++;
}
}
return num;
};
},{"./Line":3,"./Point":4,"./Scalar":6}],6:[function(require,module,exports){
module.exports = Scalar;
/**
* Scalar functions
* @class Scalar
*/
function Scalar(){}
/**
* Check if two scalars are equal
* @static
* @method eq
* @param {Number} a
* @param {Number} b
* @param {Number} [precision]
* @return {Boolean}
*/
Scalar.eq = function(a,b,precision){
precision = precision || 0;
return Math.abs(a-b) < precision;
};
},{}],7:[function(require,module,exports){
module.exports = {
Polygon : require("./Polygon"),
Point : require("./Point"),
};
},{"./Point":4,"./Polygon":5}],8:[function(require,module,exports){
module.exports={
"name": "p2",
"version": "0.4.0",
"description": "A JavaScript 2D physics engine.",
"author": "Stefan Hedman <schteppe@gmail.com> (http://steffe.se)",
"keywords": [
"p2.js",
"p2",
"physics",
"engine",
"2d"
],
"main": "./src/p2.js",
"engines": {
"node": "*"
},
"repository": {
"type": "git",
"url": "https://github.com/schteppe/p2.js.git"
},
"bugs": {
"url": "https://github.com/schteppe/p2.js/issues"
},
"licenses" : [
{
"type" : "MIT"
}
],
"devDependencies" : {
"jshint" : "latest",
"nodeunit" : "latest",
"grunt": "~0.4.0",
"grunt-contrib-jshint": "~0.1.1",
"grunt-contrib-nodeunit": "~0.1.2",
"grunt-contrib-concat": "~0.1.3",
"grunt-contrib-uglify": "*",
"grunt-browserify" : "*",
"browserify":"*"
},
"dependencies" : {
"underscore":"*",
"poly-decomp" : "git://github.com/schteppe/poly-decomp.js",
"gl-matrix":"2.0.0",
"jsonschema":"*"
}
}
},{}],9:[function(require,module,exports){
var vec2 = require('../math/vec2')
, Utils = require('../utils/Utils')
module.exports = AABB;
/**
* Axis aligned bounding box class.
* @class AABB
* @constructor
* @param {Object} options
* @param {Array} upperBound
* @param {Array} lowerBound
*/
function AABB(options){
/**
* The lower bound of the bounding box.
* @property lowerBound
* @type {Array}
*/
this.lowerBound = vec2.create();
if(options && options.lowerBound) vec2.copy(this.lowerBound, options.lowerBound);
/**
* The upper bound of the bounding box.
* @property upperBound
* @type {Array}
*/
this.upperBound = vec2.create();
if(options && options.upperBound) vec2.copy(this.upperBound, options.upperBound);
}
var tmp = vec2.create();
/**
* Set the AABB bounds from a set of points.
* @method setFromPoints
* @param {Array} points An array of vec2's.
*/
AABB.prototype.setFromPoints = function(points,position,angle){
var l = this.lowerBound,
u = this.upperBound;
vec2.set(l, Number.MAX_VALUE, Number.MAX_VALUE);
vec2.set(u, -Number.MAX_VALUE, -Number.MAX_VALUE);
for(var i=0; i<points.length; i++){
var p = points[i];
if(typeof(angle) =="number"){
vec2.rotate(tmp,p,angle);
p = tmp;
}
for(var j=0; j<2; j++){
if(p[j] > u[j]){
u[j] = p[j];
}
if(p[j] < l[j]){
l[j] = p[j];
}
}
}
// Add offset
if(position){
vec2.add(this.lowerBound, this.lowerBound, position);
vec2.add(this.upperBound, this.upperBound, position);
}
};
/**
* Copy bounds from an AABB to this AABB
* @method copy
* @param {AABB} aabb
*/
AABB.prototype.copy = function(aabb){
vec2.copy(this.lowerBound, aabb.lowerBound);
vec2.copy(this.upperBound, aabb.upperBound);
};
/**
* Extend this AABB so that it covers the given AABB too.
* @method extend
* @param {AABB} aabb
*/
AABB.prototype.extend = function(aabb){
// Loop over x and y
for(var i=0; i<2; i++){
// Extend lower bound
if(aabb.lowerBound[i] < this.lowerBound[i])
this.lowerBound[i] = aabb.lowerBound[i];
// Upper
if(aabb.upperBound[i] > this.upperBound[i])
this.upperBound[i] = aabb.upperBound[i];
}
};
/**
* Returns true if the given AABB overlaps this AABB.
* @method overlaps
* @param {AABB} aabb
* @return {Boolean}
*/
AABB.prototype.overlaps = function(aabb){
var l1 = this.lowerBound,
u1 = this.upperBound,
l2 = aabb.lowerBound,
u2 = aabb.upperBound;
// l2 u2
// |---------|
// |--------|
// l1 u1
return ((l2[0] <= u1[0] && u1[0] <= u2[0]) || (l1[0] <= u2[0] && u2[0] <= u1[0])) &&
((l2[1] <= u1[1] && u1[1] <= u2[1]) || (l1[1] <= u2[1] && u2[1] <= u1[1]));
};
},{"../math/vec2":33,"../utils/Utils":50}],10:[function(require,module,exports){
var vec2 = require('../math/vec2')
var Body = require('../objects/Body')
module.exports = Broadphase;
/**
* Base class for broadphase implementations.
* @class Broadphase
* @constructor
*/
function Broadphase(type){
this.type = type;
/**
* The resulting overlapping pairs. Will be filled with results during .getCollisionPairs().
* @property result
* @type {Array}
*/
this.result = [];
/**
* The world to search for collision pairs in. To change it, use .setWorld()
* @property world
* @type {World}
*/
this.world = null;
};
/**
* Set the world that we are searching for collision pairs in
* @method setWorld
* @param {World} world
*/
Broadphase.prototype.setWorld = function(world){
this.world = world;
};
/**
* Get all potential intersecting body pairs.
* @method getCollisionPairs
* @param {World} world The world to search in.
* @return {Array} An array of the bodies, ordered in pairs. Example: A result of [a,b,c,d] means that the potential pairs are: (a,b), (c,d).
*/
Broadphase.prototype.getCollisionPairs = function(world){
throw new Error("getCollisionPairs must be implemented in a subclass!");
};
var dist = vec2.create();
/**
* Check whether the bounding radius of two bodies overlap.
* @method boundingRadiusCheck
* @param {Body} bodyA
* @param {Body} bodyB
* @return {Boolean}
*/
Broadphase.boundingRadiusCheck = function(bodyA, bodyB){
vec2.sub(dist, bodyA.position, bodyB.position);
var d2 = vec2.squaredLength(dist),
r = bodyA.boundingRadius + bodyB.boundingRadius;
return d2 <= r*r;
};
/**
* Check whether the bounding radius of two bodies overlap.
* @method boundingRadiusCheck
* @param {Body} bodyA
* @param {Body} bodyB
* @return {Boolean}
*/
Broadphase.aabbCheck = function(bodyA, bodyB){
if(bodyA.aabbNeedsUpdate) bodyA.updateAABB();
if(bodyB.aabbNeedsUpdate) bodyB.updateAABB();
return bodyA.aabb.overlaps(bodyB.aabb);
};
/**
* Check whether two bodies are allowed to collide at all.
* @method canCollide
* @param {Body} bodyA
* @param {Body} bodyB
* @return {Boolean}
*/
Broadphase.canCollide = function(bodyA, bodyB){
// Cannot collide static bodies
if(bodyA.motionState == Body.STATIC && bodyB.motionState == Body.STATIC)
return false;
// Cannot collide static vs kinematic bodies
if( (bodyA.motionState == Body.KINEMATIC && bodyB.motionState == Body.STATIC) ||
(bodyA.motionState == Body.STATIC && bodyB.motionState == Body.KINEMATIC))
return false;
// Cannot collide kinematic vs kinematic
if(bodyA.motionState == Body.KINEMATIC && bodyB.motionState == Body.KINEMATIC)
return false;
// Cannot collide both sleeping bodies
if(bodyA.sleepState == Body.SLEEPING && bodyB.sleepState == Body.SLEEPING)
return false;
return true;
};
Broadphase.NAIVE = 1;
Broadphase.SAP = 2;
},{"../math/vec2":33,"../objects/Body":34}],11:[function(require,module,exports){
var Circle = require('../shapes/Circle')
, Plane = require('../shapes/Plane')
, Particle = require('../shapes/Particle')
, Broadphase = require('../collision/Broadphase')
, vec2 = require('../math/vec2')
module.exports = GridBroadphase;
/**
* Broadphase that uses axis-aligned bins.
* @class GridBroadphase
* @constructor
* @extends Broadphase
* @param {number} xmin Lower x bound of the grid
* @param {number} xmax Upper x bound
* @param {number} ymin Lower y bound
* @param {number} ymax Upper y bound
* @param {number} nx Number of bins along x axis
* @param {number} ny Number of bins along y axis
* @todo test
*/
function GridBroadphase(xmin,xmax,ymin,ymax,nx,ny){
Broadphase.apply(this);
nx = nx || 10;
ny = ny || 10;
this.binsizeX = (xmax-xmin) / nx;
this.binsizeY = (ymax-ymin) / ny;
this.nx = nx;
this.ny = ny;
this.xmin = xmin;
this.ymin = ymin;
this.xmax = xmax;
this.ymax = ymax;
};
GridBroadphase.prototype = new Broadphase();
/**
* Get a bin index given a world coordinate
* @method getBinIndex
* @param {Number} x
* @param {Number} y
* @return {Number} Integer index
*/
GridBroadphase.prototype.getBinIndex = function(x,y){
var nx = this.nx,
ny = this.ny,
xmin = this.xmin,
ymin = this.ymin,
xmax = this.xmax,
ymax = this.ymax;
var xi = Math.floor(nx * (x - xmin) / (xmax-xmin));
var yi = Math.floor(ny * (y - ymin) / (ymax-ymin));
return xi*ny + yi;
}
/**
* Get collision pairs.
* @method getCollisionPairs
* @param {World} world
* @return {Array}
*/
GridBroadphase.prototype.getCollisionPairs = function(world){
var result = [],
collidingBodies = world.bodies,
Ncolliding = Ncolliding=collidingBodies.length,
binsizeX = this.binsizeX,
binsizeY = this.binsizeY;
var bins=[], Nbins=nx*ny;
for(var i=0; i<Nbins; i++)
bins.push([]);
var xmult = nx / (xmax-xmin);
var ymult = ny / (ymax-ymin);
// Put all bodies into bins
for(var i=0; i!==Ncolliding; i++){
var bi = collidingBodies[i];
var si = bi.shape;
if (si === undefined) {
continue;
} else if(si instanceof Circle){
// Put in bin
// check if overlap with other bins
var x = bi.position[0];
var y = bi.position[1];
var r = si.radius;
var xi1 = Math.floor(xmult * (x-r - xmin));
var yi1 = Math.floor(ymult * (y-r - ymin));
var xi2 = Math.floor(xmult * (x+r - xmin));
var yi2 = Math.floor(ymult * (y+r - ymin));
for(var j=xi1; j<=xi2; j++){
for(var k=yi1; k<=yi2; k++){
var xi = j;
var yi = k;
if(xi*(ny-1) + yi >= 0 && xi*(ny-1) + yi < Nbins)
bins[ xi*(ny-1) + yi ].push(bi);
}
}
} else if(si instanceof Plane){
// Put in all bins for now
if(bi.angle == 0){
var y = bi.position[1];
for(var j=0; j!==Nbins && ymin+binsizeY*(j-1)<y; j++){
for(var k=0; k<nx; k++){
var xi = k;
var yi = Math.floor(ymult * (binsizeY*j - ymin));
bins[ xi*(ny-1) + yi ].push(bi);
}
}
} else if(bi.angle == Math.PI*0.5){
var x = bi.position[0];
for(var j=0; j!==Nbins && xmin+binsizeX*(j-1)<x; j++){
for(var k=0; k<ny; k++){
var yi = k;
var xi = Math.floor(xmult * (binsizeX*j - xmin));
bins[ xi*(ny-1) + yi ].push(bi);
}
}
} else {
for(var j=0; j!==Nbins; j++)
bins[j].push(bi);
}
} else {
throw new Error("Shape not supported in GridBroadphase!");
}
}
// Check each bin
for(var i=0; i!==Nbins; i++){
var bin = bins[i];
for(var j=0, NbodiesInBin=bin.length; j!==NbodiesInBin; j++){
var bi = bin[j];
var si = bi.shape;
for(var k=0; k!==j; k++){
var bj = bin[k];
var sj = bj.shape;
if(si instanceof Circle){
if(sj instanceof Circle) c=Broadphase.circleCircle (bi,bj);
else if(sj instanceof Particle) c=Broadphase.circleParticle(bi,bj);
else if(sj instanceof Plane) c=Broadphase.circlePlane (bi,bj);
} else if(si instanceof Particle){
if(sj instanceof Circle) c=Broadphase.circleParticle(bj,bi);
} else if(si instanceof Plane){
if(sj instanceof Circle) c=Broadphase.circlePlane (bj,bi);
}
}
}
}
return result;
};
},{"../collision/Broadphase":10,"../math/vec2":33,"../shapes/Circle":38,"../shapes/Particle":42,"../shapes/Plane":43}],12:[function(require,module,exports){
var Circle = require('../shapes/Circle')
, Plane = require('../shapes/Plane')
, Shape = require('../shapes/Shape')
, Particle = require('../shapes/Particle')
, Broadphase = require('../collision/Broadphase')
, vec2 = require('../math/vec2')
module.exports = NaiveBroadphase;
/**
* Naive broadphase implementation. Does N^2 tests.
*
* @class NaiveBroadphase
* @constructor
* @extends Broadphase
*/
function NaiveBroadphase(){
Broadphase.call(this,Broadphase.NAIVE);
/**
* Set to true to use bounding box checks instead of bounding radius.
* @property useBoundingBoxes
* @type {Boolean}
*/
this.useBoundingBoxes = false;
};
NaiveBroadphase.prototype = new Broadphase();
/**
* Get the colliding pairs
* @method getCollisionPairs
* @param {World} world
* @return {Array}
*/
NaiveBroadphase.prototype.getCollisionPairs = function(world){
var bodies = world.bodies,
result = this.result,
i, j, bi, bj,
check = this.useBoundingBoxes ? Broadphase.aabbCheck : Broadphase.boundingRadiusCheck;
result.length = 0;
for(i=0, Ncolliding=bodies.length; i!==Ncolliding; i++){
bi = bodies[i];
for(j=0; j<i; j++){
bj = bodies[j];
if(Broadphase.canCollide(bi,bj) && check(bi,bj))
result.push(bi,bj);
}
}
return result;
};
},{"../collision/Broadphase":10,"../math/vec2":33,"../shapes/Circle":38,"../shapes/Particle":42,"../shapes/Plane":43,"../shapes/Shape":45}],13:[function(require,module,exports){
var vec2 = require('../math/vec2')
, sub = vec2.sub
, add = vec2.add
, dot = vec2.dot
, Utils = require('../utils/Utils')
, ContactEquation = require('../equations/ContactEquation')
, FrictionEquation = require('../equations/FrictionEquation')
, Circle = require('../shapes/Circle')
, Shape = require('../shapes/Shape')
, Body = require('../objects/Body')
, Rectangle = require('../shapes/Rectangle')
module.exports = Narrowphase;
// Temp things
var yAxis = vec2.fromValues(0,1);
var tmp1 = vec2.fromValues(0,0)
, tmp2 = vec2.fromValues(0,0)
, tmp3 = vec2.fromValues(0,0)
, tmp4 = vec2.fromValues(0,0)
, tmp5 = vec2.fromValues(0,0)
, tmp6 = vec2.fromValues(0,0)
, tmp7 = vec2.fromValues(0,0)
, tmp8 = vec2.fromValues(0,0)
, tmp9 = vec2.fromValues(0,0)
, tmp10 = vec2.fromValues(0,0)
, tmp11 = vec2.fromValues(0,0)
, tmp12 = vec2.fromValues(0,0)
, tmp13 = vec2.fromValues(0,0)
, tmp14 = vec2.fromValues(0,0)
, tmp15 = vec2.fromValues(0,0)
, tmp16 = vec2.fromValues(0,0)
, tmp17 = vec2.fromValues(0,0)
, tmp18 = vec2.fromValues(0,0)
, tmpArray = []
/**
* Narrowphase. Creates contacts and friction given shapes and transforms.
* @class Narrowphase
* @constructor
*/
function Narrowphase(){
/**
* @property contactEquations
* @type {Array}
*/
this.contactEquations = [];
/**
* @property frictionEquations
* @type {Array}
*/
this.frictionEquations = [];
/**
* Whether to make friction equations in the upcoming contacts.
* @property enableFriction
* @type {Boolean}
*/
this.enableFriction = true;
/**
* The friction slip force to use when creating friction equations.
* @property slipForce
* @type {Number}
*/
this.slipForce = 10.0;
/**
* The friction value to use in the upcoming friction equations.
* @property frictionCoefficient
* @type {Number}
*/
this.frictionCoefficient = 0.3;
/**
* Will be the .relativeVelocity in each produced FrictionEquation.
* @property {Number} surfaceVelocity
*/
this.surfaceVelocity = 0;
this.reuseObjects = true;
this.reusableContactEquations = [];
this.reusableFrictionEquations = [];
/**
* The restitution value to use in the next contact equations.
* @property restitution
* @type {Number}
*/
this.restitution = 0;
/**
* The stiffness value to use in the next contact equations.
* @property {Number} stiffness
*/
this.stiffness = 1e7;
/**
* The stiffness value to use in the next contact equations.
* @property {Number} stiffness
*/
this.relaxation = 3;
/**
* The stiffness value to use in the next friction equations.
* @property frictionStiffness
* @type {Number}
*/
this.frictionStiffness = 1e7;
/**
* The relaxation value to use in the next friction equations.
* @property frictionRelaxation
* @type {Number}
*/
this.frictionRelaxation = 3;
// Keep track of the colliding bodies last step
this.collidingBodiesLastStep = { keys:[] };
};
/**
* Check if the bodies were in contact since the last reset().
* @method collidedLastStep
* @param {Body} bi
* @param {Body} bj
* @return {Boolean}
*/
Narrowphase.prototype.collidedLastStep = function(bi,bj){
var id1 = bi.id,
id2 = bj.id;
if(id1 > id2){
var tmp = id1;
id1 = id2;
id2 = tmp;
}
return !!this.collidingBodiesLastStep[id1 + " " + id2];
};
// "for in" loops aren't optimised in chrome... is there a better way to handle last-step collision memory?
// Maybe do this: http://jsperf.com/reflection-vs-array-of-keys
function clearObject(obj){
for(var i = 0, l = obj.keys.length; i < l; i++) {
delete obj[obj.keys[i]];
}
obj.keys.length = 0;
/*
for(var key in this.collidingBodiesLastStep)
delete this.collidingBodiesLastStep[key];
*/
}
/**
* Throws away the old equations and gets ready to create new
* @method reset
* @param {World} world
*/
Narrowphase.prototype.reset = function(world){
// Save the colliding bodies data
clearObject(this.collidingBodiesLastStep);
for(var i=0; i!==this.contactEquations.length; i++){
var eq = this.contactEquations[i],
id1 = eq.bi.id,
id2 = eq.bj.id;
if(id1 > id2){
var tmp = id1;
id1 = id2;
id2 = tmp;
}
var key = id1 + " " + id2;
if(!this.collidingBodiesLastStep[key]){
this.collidingBodiesLastStep[key] = true;
this.collidingBodiesLastStep.keys.push(key);
}
}
if(this.reuseObjects){
var ce = this.contactEquations,
fe = this.frictionEquations,
rfe = this.reusableFrictionEquations,
rce = this.reusableContactEquations;
Utils.appendArray(rce,ce);
Utils.appendArray(rfe,fe);
}
// Reset
this.contactEquations.length = this.frictionEquations.length = 0;
};
/**
* Creates a ContactEquation, either by reusing an existing object or creating a new one.
* @method createContactEquation
* @param {Body} bodyA
* @param {Body} bodyB
* @return {ContactEquation}
*/
Narrowphase.prototype.createContactEquation = function(bodyA,bodyB,shapeA,shapeB){
var c = this.reusableContactEquations.length ? this.reusableContactEquations.pop() : new ContactEquation(bodyA,bodyB);
c.bi = bodyA;
c.bj = bodyB;
c.shapeA = shapeA;
c.shapeB = shapeB;
c.restitution = this.restitution;
c.firstImpact = !this.collidedLastStep(bodyA,bodyB);
c.stiffness = this.stiffness;
c.relaxation = this.relaxation;
c.enabled = true;
if(bodyA.allowSleep && (bodyA.motionState == Body.DYNAMIC) && !(bodyB.motionState == Body.STATIC || bodyB.sleepState === Body.SLEEPY))
bodyA.wakeUp();
if(bodyB.allowSleep && (bodyB.motionState == Body.DYNAMIC) && !(bodyA.motionState == Body.STATIC || bodyA.sleepState === Body.SLEEPY))
bodyB.wakeUp();
return c;
};
/**
* Creates a FrictionEquation, either by reusing an existing object or creating a new one.
* @method createFrictionEquation
* @param {Body} bodyA
* @param {Body} bodyB
* @return {FrictionEquation}
*/
Narrowphase.prototype.createFrictionEquation = function(bodyA,bodyB,shapeA,shapeB){
var c = this.reusableFrictionEquations.length ? this.reusableFrictionEquations.pop() : new FrictionEquation(bodyA,bodyB);
c.bi = bodyA;
c.bj = bodyB;
c.shapeA = shapeA;
c.shapeB = shapeB;
c.setSlipForce(this.slipForce);
c.frictionCoefficient = this.frictionCoefficient;
c.relativeVelocity = this.surfaceVelocity;
c.enabled = true;
c.frictionStiffness = this.frictionStiffness;
c.frictionRelaxation = this.frictionRelaxation;
return c;
};
/**
* Creates a FrictionEquation given the data in the ContactEquation. Uses same offset vectors ri and rj, but the tangent vector will be constructed from the collision normal.
* @method createFrictionFromContact
* @param {ContactEquation} contactEquation
* @return {FrictionEquation}
*/
Narrowphase.prototype.createFrictionFromContact = function(c){
var eq = this.createFrictionEquation(c.bi,c.bj,c.shapeA,c.shapeB);
vec2.copy(eq.ri, c.ri);
vec2.copy(eq.rj, c.rj);
vec2.rotate(eq.t, c.ni, -Math.PI / 2);
eq.contactEquation = c;
return eq;
}
/**
* Convex/line narrowphase
* @method convexLine
* @param {Body} bi
* @param {Convex} si
* @param {Array} xi
* @param {Number} ai
* @param {Body} bj
* @param {Line} sj
* @param {Array} xj
* @param {Number} aj
* @todo Implement me!
*/
Narrowphase.prototype[Shape.LINE | Shape.CONVEX] =
Narrowphase.prototype.convexLine = function(bi,si,xi,ai, bj,sj,xj,aj, justTest){
// TODO
if(justTest)
return false;
else
return 0;
};
/**
* Line/rectangle narrowphase
* @method lineRectangle
* @param {Body} bi
* @param {Line} si
* @param {Array} xi
* @param {Number} ai
* @param {Body} bj
* @param {Rectangle} sj
* @param {Array} xj
* @param {Number} aj
* @todo Implement me!
*/
Narrowphase.prototype[Shape.LINE | Shape.RECTANGLE] =
Narrowphase.prototype.lineRectangle = function(bi,si,xi,ai, bj,sj,xj,aj, justTest){
// TODO
if(justTest)
return false;
else
return 0;
};
function setConvexToCapsuleShapeMiddle(convexShape, capsuleShape){
vec2.set(convexShape.vertices[0], -capsuleShape.length * 0.5, -capsuleShape.radius);
vec2.set(convexShape.vertices[1], capsuleShape.length * 0.5, -capsuleShape.radius);
vec2.set(convexShape.vertices[2], capsuleShape.length * 0.5, capsuleShape.radius);
vec2.set(convexShape.vertices[3], -capsuleShape.length * 0.5, capsuleShape.radius);
}
var convexCapsule_tempRect = new Rectangle(1,1),
convexCapsule_tempVec = vec2.create();
/**
* Convex/capsule narrowphase
* @method convexCapsule
* @param {Body} bi
* @param {Convex} si
* @param {Array} xi
* @param {Number} ai
* @param {Body} bj
* @param {Capsule} sj
* @param {Array} xj
* @param {Number} aj
* @todo Implement me!
*/
Narrowphase.prototype[Shape.CAPSULE | Shape.CONVEX] =
Narrowphase.prototype[Shape.CAPSULE | Shape.RECTANGLE] =
Narrowphase.prototype.convexCapsule = function(bi,si,xi,ai, bj,sj,xj,aj, justTest){
// Check the circles
// Add offsets!
var circlePos = convexCapsule_tempVec;
vec2.set(circlePos, sj.length/2,0);
vec2.rotate(circlePos,circlePos,aj);
vec2.add(circlePos,circlePos,xj);
var result1 = this.circleConvex(bj,sj,circlePos,aj, bi,si,xi,ai, justTest, sj.radius);
vec2.set(circlePos,-sj.length/2, 0);
vec2.rotate(circlePos,circlePos,aj);
vec2.add(circlePos,circlePos,xj);
var result2 = this.circleConvex(bj,sj,circlePos,aj, bi,si,xi,ai, justTest, sj.radius);
if(justTest && (result1 || result2))
return true;
// Check center rect
var r = convexCapsule_tempRect;
setConvexToCapsuleShapeMiddle(r,sj);
var result = this.convexConvex(bi,si,xi,ai, bj,r,xj,aj, justTest);
return result + result1 + result2;
};
/**
* Capsule/line narrowphase
* @method lineCapsule
* @param {Body} bi
* @param {Line} si
* @param {Array} xi
* @param {Number} ai
* @param {Body} bj
* @param {Capsule} sj
* @param {Array} xj
* @param {Number} aj
* @todo Implement me!
*/
Narrowphase.prototype[Shape.CAPSULE | Shape.LINE] =
Narrowphase.prototype.lineCapsule = function(bi,si,xi,ai, bj,sj,xj,aj, justTest){
// TODO
if(justTest)
return false;
else
return 0;
};
var capsuleCapsule_tempVec1 = vec2.create();
var capsuleCapsule_tempVec2 = vec2.create();
var capsuleCapsule_tempRect1 = new Rectangle(1,1);
/**
* Capsule/capsule narrowphase
* @method capsuleCapsule
* @param {Body} bi
* @param {Capsule} si
* @param {Array} xi
* @param {Number} ai
* @param {Body} bj
* @param {Capsule} sj
* @param {Array} xj
* @param {Number} aj
* @todo Implement me!
*/
Narrowphase.prototype[Shape.CAPSULE | Shape.CAPSULE] =
Narrowphase.prototype.capsuleCapsule = function(bi,si,xi,ai, bj,sj,xj,aj, justTest){
// Check the circles
// Add offsets!
var circlePosi = capsuleCapsule_tempVec1,
circlePosj = capsuleCapsule_tempVec2;
var numContacts = 0;
// Need 4 circle checks, between all
for(var i=0; i<2; i++){
vec2.set(circlePosi,(i==0?-1:1)*si.length/2,0);
vec2.rotate(circlePosi,circlePosi,ai);
vec2.add(circlePosi,circlePosi,xi);
for(var j=0; j<2; j++){
vec2.set(circlePosj,(j==0?-1:1)*sj.length/2, 0);
vec2.rotate(circlePosj,circlePosj,aj);
vec2.add(circlePosj,circlePosj,xj);
var result = this.circleCircle(bi,si,circlePosi,ai, bj,sj,circlePosj,aj, justTest, si.radius, sj.radius);
if(justTest && result)
return true;
numContacts += result;
}
}
// Check circles against the center rectangles
var rect = capsuleCapsule_tempRect1;
setConvexToCapsuleShapeMiddle(rect,si);
var result1 = this.convexCapsule(bi,rect,xi,ai, bj,sj,xj,aj, justTest);
if(justTest && result1) return true;
numContacts += result1;
setConvexToCapsuleShapeMiddle(rect,sj);
var result2 = this.convexCapsule(bj,rect,xj,aj, bi,si,xi,ai, justTest);
if(justTest && result2) return true;
numContacts += result2;
return numContacts;
};
/**
* Line/line narrowphase
* @method lineLine
* @param {Body} bi
* @param {Line} si
* @param {Array} xi
* @param {Number} ai
* @param {Body} bj
* @param {Line} sj
* @param {Array} xj
* @param {Number} aj
* @todo Implement me!
*/
Narrowphase.prototype[Shape.LINE | Shape.LINE] =
Narrowphase.prototype.lineLine = function(bi,si,xi,ai, bj,sj,xj,aj, justTest){
// TODO
if(justTest)
return false;
else
return 0;
};
/**
* Plane/line Narrowphase
* @method planeLine
* @param {Body} planeBody
* @param {Plane} planeShape
* @param {Array} planeOffset
* @param {Number} planeAngle
* @param {Body} lineBody
* @param {Line} lineShape
* @param {Array} lineOffset
* @param {Number} lineAngle
*/
Narrowphase.prototype[Shape.PLANE | Shape.LINE] =
Narrowphase.prototype.planeLine = function(planeBody, planeShape, planeOffset, planeAngle,
lineBody, lineShape, lineOffset, lineAngle, justTest){
var worldVertex0 = tmp1,
worldVertex1 = tmp2,
worldVertex01 = tmp3,
worldVertex11 = tmp4,
worldEdge = tmp5,
worldEdgeUnit = tmp6,
dist = tmp7,
worldNormal = tmp8,
worldTangent = tmp9,
verts = tmpArray
numContacts = 0;
// Get start and end points
vec2.set(worldVertex0, -lineShape.length/2, 0);
vec2.set(worldVertex1, lineShape.length/2, 0);
// Not sure why we have to use worldVertex*1 here, but it won't work otherwise. Tired.
vec2.rotate(worldVertex01, worldVertex0, lineAngle);
vec2.rotate(worldVertex11, worldVertex1, lineAngle);
add(worldVertex01, worldVertex01, lineOffset);
add(worldVertex11, worldVertex11, lineOffset);
vec2.copy(worldVertex0,worldVertex01);
vec2.copy(worldVertex1,worldVertex11);
// Get vector along the line
sub(worldEdge, worldVertex1, worldVertex0);
vec2.normalize(worldEdgeUnit, worldEdge);
// Get tangent to the edge.
vec2.rotate(worldTangent, worldEdgeUnit, -Math.PI/2);
vec2.rotate(worldNormal, yAxis, planeAngle);
// Check line ends
verts[0] = worldVertex0;
verts[1] = worldVertex1;
for(var i=0; i<verts.length; i++){
var v = verts[i];
sub(dist, v, planeOffset);
var d = dot(dist,worldNormal);
if(d < 0){
if(justTest)
return true;
var c = this.createContactEquation(planeBody,lineBody,planeShape,lineShape);
numContacts++;
vec2.copy(c.ni, worldNormal);
vec2.normalize(c.ni,c.ni);
// distance vector along plane normal
vec2.scale(dist, worldNormal, d);
// Vector from plane center to contact
sub(c.ri, v, dist);
sub(c.ri, c.ri, planeBody.position);
// From line center to contact
sub(c.rj, v, lineOffset);
add(c.rj, c.rj, lineOffset);
sub(c.rj, c.rj, lineBody.position);
this.contactEquations.push(c);
// TODO : only need one friction equation if both points touch
if(this.enableFriction){
this.frictionEquations.push(this.createFrictionFromContact(c));
}
}
}
return numContacts;
};
Narrowphase.prototype[Shape.PARTICLE | Shape.CAPSULE] =
Narrowphase.prototype.particleCapsule = function(bi,si,xi,ai, bj,sj,xj,aj, justTest){
return this.circleLine(bi,si,xi,ai, bj,sj,xj,aj, justTest, sj.radius, 0);
};
/**
* Circle/line Narrowphase
* @method circleLine
* @param {Body} bi
* @param {Circle} si
* @param {Array} xi
* @param {Number} ai
* @param {Body} bj
* @param {Line} sj
* @param {Array} xj
* @param {Number} aj
* @param {Boolean} justTest If set to true, this function will return the result (intersection or not) without adding equations.
* @param {Number} lineRadius Radius to add to the line. Can be used to test Capsules.
* @param {Number} circleRadius If set, this value overrides the circle shape radius.
*/
Narrowphase.prototype[Shape.CIRCLE | Shape.LINE] =
Narrowphase.prototype.circleLine = function(bi,si,xi,ai, bj,sj,xj,aj, justTest, lineRadius, circleRadius){
var lineShape = sj,
lineAngle = aj,
lineBody = bj,
lineOffset = xj,
circleOffset = xi,
circleBody = bi,
circleShape = si,
lineRadius = lineRadius || 0,
circleRadius = typeof(circleRadius)!="undefined" ? circleRadius : circleShape.radius,
orthoDist = tmp1,
lineToCircleOrthoUnit = tmp2,
projectedPoint = tmp3,
centerDist = tmp4,
worldTangent = tmp5,
worldEdge = tmp6,
worldEdgeUnit = tmp7,
worldVertex0 = tmp8,
worldVertex1 = tmp9,
worldVertex01 = tmp10,
worldVertex11 = tmp11,
dist = tmp12,
lineToCircle = tmp13,
lineEndToLineRadius = tmp14,
verts = tmpArray;
// Get start and end points
vec2.set(worldVertex0, -lineShape.length/2, 0);
vec2.set(worldVertex1, lineShape.length/2, 0);
// Not sure why we have to use worldVertex*1 here, but it won't work otherwise. Tired.
vec2.rotate(worldVertex01, worldVertex0, lineAngle);
vec2.rotate(worldVertex11, worldVertex1, lineAngle);
add(worldVertex01, worldVertex01, lineOffset);
add(worldVertex11, worldVertex11, lineOffset);
vec2.copy(worldVertex0,worldVertex01);
vec2.copy(worldVertex1,worldVertex11);
// Get vector along the line
sub(worldEdge, worldVertex1, worldVertex0);
vec2.normalize(worldEdgeUnit, worldEdge);
// Get tangent to the edge.
vec2.rotate(worldTangent, worldEdgeUnit, -Math.PI/2);
// Check distance from the plane spanned by the edge vs the circle
sub(dist, circleOffset, worldVertex0);
var d = dot(dist, worldTangent); // Distance from center of line to circle center
sub(centerDist, worldVertex0, lineOffset);
sub(lineToCircle, circleOffset, lineOffset);
if(Math.abs(d) < circleRadius+lineRadius){
// Now project the circle onto the edge
vec2.scale(orthoDist, worldTangent, d);
sub(projectedPoint, circleOffset, orthoDist);
// Add the missing line radius
vec2.scale(lineToCircleOrthoUnit, worldTangent, dot(worldTangent, lineToCircle));
vec2.normalize(lineToCircleOrthoUnit,lineToCircleOrthoUnit);
vec2.scale(lineToCircleOrthoUnit, lineToCircleOrthoUnit, lineRadius);
add(projectedPoint,projectedPoint,lineToCircleOrthoUnit);
// Check if the point is within the edge span
var pos = dot(worldEdgeUnit, projectedPoint);
var pos0 = dot(worldEdgeUnit, worldVertex0);
var pos1 = dot(worldEdgeUnit, worldVertex1);
if(pos > pos0 && pos < pos1){
// We got contact!
if(justTest) return true;
var c = this.createContactEquation(circleBody,lineBody,si,sj);
vec2.scale(c.ni, orthoDist, -1);
vec2.normalize(c.ni, c.ni);
vec2.scale( c.ri, c.ni, circleRadius);
add(c.ri, c.ri, circleOffset);
sub(c.ri, c.ri, circleBody.position);
sub(c.rj, projectedPoint, lineOffset);
add(c.rj, c.rj, lineOffset);
sub(c.rj, c.rj, lineBody.position);
this.contactEquations.push(c);
if(this.enableFriction){
this.frictionEquations.push(this.createFrictionFromContact(c));
}
return 1;
}
}
// Add corner
// @todo reuse array object
verts[0] = worldVertex0;
verts[1] = worldVertex1;
for(var i=0; i<verts.length; i++){
var v = verts[i];
sub(dist, v, circleOffset);
if(vec2.squaredLength(dist) < (circleRadius+lineRadius)*(circleRadius+lineRadius)){
if(justTest) return true;
var c = this.createContactEquation(circleBody,lineBody,si,sj);
vec2.copy(c.ni, dist);
vec2.normalize(c.ni,c.ni);
// Vector from circle to contact point is the normal times the circle radius
vec2.scale(c.ri, c.ni, circleRadius);
add(c.ri, c.ri, circleOffset);
sub(c.ri, c.ri, circleBody.position);
sub(c.rj, v, lineOffset);
vec2.scale(lineEndToLineRadius, c.ni, -lineRadius);
add(c.rj, c.rj, lineEndToLineRadius);
add(c.rj, c.rj, lineOffset);
sub(c.rj, c.rj, lineBody.position);
this.contactEquations.push(c);
if(this.enableFriction){
this.frictionEquations.push(this.createFrictionFromContact(c));
}
return 1;
}
}
return 0;
};
/**
* Circle/capsule Narrowphase
* @method circleCapsule
* @param {Body} bi
* @param {Circle} si
* @param {Array} xi
* @param {Number} ai
* @param {Body} bj
* @param {Line} sj
* @param {Array} xj
* @param {Number} aj
*/
Narrowphase.prototype[Shape.CIRCLE | Shape.CAPSULE] =
Narrowphase.prototype.circleCapsule = function(bi,si,xi,ai, bj,sj,xj,aj, justTest){
return this.circleLine(bi,si,xi,ai, bj,sj,xj,aj, justTest, sj.radius);
};
/**
* Circle/convex Narrowphase
* @method circleConvex
* @param {Body} bi
* @param {Circle} si
* @param {Array} xi
* @param {Number} ai
* @param {Body} bj
* @param {Convex} sj
* @param {Array} xj
* @param {Number} aj
*/
Narrowphase.prototype[Shape.CIRCLE | Shape.CONVEX] =
Narrowphase.prototype[Shape.CIRCLE | Shape.RECTANGLE] =
Narrowphase.prototype.circleConvex = function( bi,si,xi,ai, bj,sj,xj,aj, justTest, circleRadius){
var convexShape = sj,
convexAngle = aj,
convexBody = bj,
convexOffset = xj,
circleOffset = xi,
circleBody = bi,
circleShape = si,
circleRadius = typeof(circleRadius)=="number" ? circleRadius : circleShape.radius;
var worldVertex0 = tmp1,
worldVertex1 = tmp2,
worldEdge = tmp3,
worldEdgeUnit = tmp4,
worldTangent = tmp5,
centerDist = tmp6,
convexToCircle = tmp7,
orthoDist = tmp8,
projectedPoint = tmp9,
dist = tmp10,
worldVertex = tmp11,
closestEdge = -1,
closestEdgeDistance = null,
closestEdgeOrthoDist = tmp12,
closestEdgeProjectedPoint = tmp13,
candidate = tmp14,
candidateDist = tmp15,
minCandidate = tmp16,
found = false,
minCandidateDistance = Number.MAX_VALUE;
var numReported = 0;
// New algorithm:
// 1. Check so center of circle is not inside the polygon. If it is, this wont work...
// 2. For each edge
// 2. 1. Get point on circle that is closest to the edge (scale normal with -radius)
// 2. 2. Check if point is inside.
verts = convexShape.vertices;
// Check all edges first
for(var i=0; i!==verts.length+1; i++){
var v0 = verts[i%verts.length],
v1 = verts[(i+1)%verts.length];
vec2.rotate(worldVertex0, v0, convexAngle);
vec2.rotate(worldVertex1, v1, convexAngle);
add(worldVertex0, worldVertex0, convexOffset);
add(worldVertex1, worldVertex1, convexOffset);
sub(worldEdge, worldVertex1, worldVertex0);
vec2.normalize(worldEdgeUnit, worldEdge);
// Get tangent to the edge. Points out of the Convex
vec2.rotate(worldTangent, worldEdgeUnit, -Math.PI/2);
// Get point on circle, closest to the polygon
vec2.scale(candidate,worldTangent,-circleShape.radius);
add(candidate,candidate,circleOffset);
if(pointInConvex(candidate,convexShape,convexOffset,convexAngle)){
vec2.sub(candidateDist,worldVertex0,candidate);
var candidateDistance = Math.abs(vec2.dot(candidateDist,worldTangent));
/*
// Check distance from the plane spanned by the edge vs the circle
sub(dist, circleOffset, worldVertex0);
var d = dot(dist, worldTangent);
sub(centerDist, worldVertex0, convexOffset);
sub(convexToCircle, circleOffset, convexOffset);
if(d < circleRadius && dot(centerDist,convexToCircle) > 0){
// Now project the circle onto the edge
vec2.scale(orthoDist, worldTangent, d);
sub(projectedPoint, circleOffset, orthoDist);
// Check if the point is within the edge span
var pos = dot(worldEdgeUnit, projectedPoint);
var pos0 = dot(worldEdgeUnit, worldVertex0);
var pos1 = dot(worldEdgeUnit, worldVertex1);
if(pos > pos0 && pos < pos1){
// We got contact!
if(justTest) return true;
if(closestEdgeDistance === null || d*d<closestEdgeDistance*closestEdgeDistance){
closestEdgeDistance = d;
closestEdge = i;
vec2.copy(closestEdgeOrthoDist, orthoDist);
vec2.copy(closestEdgeProjectedPoint, projectedPoint);
}
}
}
*/
if(candidateDistance < minCandidateDistance){
vec2.copy(minCandidate,candidate);
minCandidateDistance = candidateDistance;
vec2.scale(closestEdgeProjectedPoint,worldTangent,candidateDistance);
vec2.add(closestEdgeProjectedPoint,closestEdgeProjectedPoint,candidate);
found = true;
}
}
}
if(found){
if(justTest)
return true;
var c = this.createContactEquation(circleBody,convexBody,si,sj);
vec2.sub(c.ni, minCandidate, circleOffset)
vec2.normalize(c.ni, c.ni);
vec2.scale(c.ri, c.ni, circleRadius);
add(c.ri, c.ri, circleOffset);
sub(c.ri, c.ri, circleBody.position);
sub(c.rj, closestEdgeProjectedPoint, convexOffset);
add(c.rj, c.rj, convexOffset);
sub(c.rj, c.rj, convexBody.position);
this.contactEquations.push(c);
if(this.enableFriction)
this.frictionEquations.push( this.createFrictionFromContact(c) );
return 1;
}
/*
if(closestEdge != -1){
var c = this.createContactEquation(circleBody,convexBody);
vec2.scale(c.ni, closestEdgeOrthoDist, -1);
vec2.normalize(c.ni, c.ni);
vec2.scale(c.ri, c.ni, circleRadius);
add(c.ri, c.ri, circleOffset);
sub(c.ri, c.ri, circleBody.position);
sub(c.rj, closestEdgeProjectedPoint, convexOffset);
add(c.rj, c.rj, convexOffset);
sub(c.rj, c.rj, convexBody.position);
this.contactEquations.push(c);
if(this.enableFriction)
this.frictionEquations.push( this.createFrictionFromContact(c) );
return true;
}
*/
// Check all vertices
if(circleRadius > 0){
for(var i=0; i<verts.length; i++){
var localVertex = verts[i];
vec2.rotate(worldVertex, localVertex, convexAngle);
add(worldVertex, worldVertex, convexOffset);
sub(dist, worldVertex, circleOffset);
if(vec2.squaredLength(dist) < circleRadius*circleRadius){
if(justTest) return true;
var c = this.createContactEquation(circleBody,convexBody,si,sj);
vec2.copy(c.ni, dist);
vec2.normalize(c.ni,c.ni);
// Vector from circle to contact point is the normal times the circle radius
vec2.scale(c.ri, c.ni, circleRadius);
add(c.ri, c.ri, circleOffset);
sub(c.ri, c.ri, circleBody.position);
sub(c.rj, worldVertex, convexOffset);
add(c.rj, c.rj, convexOffset);
sub(c.rj, c.rj, convexBody.position);
this.contactEquations.push(c);
if(this.enableFriction){
this.frictionEquations.push(this.createFrictionFromContact(c));
}
return 1;
}
}
}
return 0;
};
// Check if a point is in a polygon
var pic_worldVertex0 = vec2.create(),
pic_worldVertex1 = vec2.create(),
pic_r0 = vec2.create(),
pic_r1 = vec2.create();
function pointInConvex(worldPoint,convexShape,convexOffset,convexAngle){
var worldVertex0 = pic_worldVertex0,
worldVertex1 = pic_worldVertex1,
r0 = pic_r0,
r1 = pic_r1,
point = worldPoint,
verts = convexShape.vertices,
lastCross = null;
for(var i=0; i!==verts.length+1; i++){
var v0 = verts[i%verts.length],
v1 = verts[(i+1)%verts.length];
// Transform vertices to world
// can we instead transform point to local of the convex???
vec2.rotate(worldVertex0, v0, convexAngle);
vec2.rotate(worldVertex1, v1, convexAngle);
add(worldVertex0, worldVertex0, convexOffset);
add(worldVertex1, worldVertex1, convexOffset);
sub(r0, worldVertex0, point);
sub(r1, worldVertex1, point);
var cross = vec2.crossLength(r0,r1);
if(lastCross===null) lastCross = cross;
// If we got a different sign of the distance vector, the point is out of the polygon
if(cross*lastCross <= 0){
return false;
}
lastCross = cross;
}
return true;
};
/**
* Particle/convex Narrowphase
* @method particleConvex
* @param {Body} bi
* @param {Particle} si
* @param {Array} xi
* @param {Number} ai
* @param {Body} bj
* @param {Convex} sj
* @param {Array} xj
* @param {Number} aj
* @todo use pointInConvex and code more similar to circleConvex
*/
Narrowphase.prototype[Shape.PARTICLE | Shape.CONVEX] =
Narrowphase.prototype[Shape.PARTICLE | Shape.RECTANGLE] =
Narrowphase.prototype.particleConvex = function( bi,si,xi,ai, bj,sj,xj,aj, justTest ){
var convexShape = sj,
convexAngle = aj,
convexBody = bj,
convexOffset = xj,
particleOffset = xi,
particleBody = bi,
particleShape = si,
worldVertex0 = tmp1,
worldVertex1 = tmp2,
worldEdge = tmp3,
worldEdgeUnit = tmp4,
worldTangent = tmp5,
centerDist = tmp6,
convexToparticle = tmp7,
orthoDist = tmp8,
projectedPoint = tmp9,
dist = tmp10,
worldVertex = tmp11,
closestEdge = -1,
closestEdgeDistance = null,
closestEdgeOrthoDist = tmp12,
closestEdgeProjectedPoint = tmp13,
r0 = tmp14, // vector from particle to vertex0
r1 = tmp15,
localPoint = tmp16,
candidateDist = tmp17,
minEdgeNormal = tmp18,
minCandidateDistance = Number.MAX_VALUE;
var numReported = 0,
found = false,
verts = convexShape.vertices;
// Check if the particle is in the polygon at all
if(!pointInConvex(particleOffset,convexShape,convexOffset,convexAngle))
return 0;
if(justTest) return true;
// Check edges first
var lastCross = null;
for(var i=0; i!==verts.length+1; i++){
var v0 = verts[i%verts.length],
v1 = verts[(i+1)%verts.length];
// Transform vertices to world
vec2.rotate(worldVertex0, v0, convexAngle);
vec2.rotate(worldVertex1, v1, convexAngle);
add(worldVertex0, worldVertex0, convexOffset);
add(worldVertex1, worldVertex1, convexOffset);
// Get world edge
sub(worldEdge, worldVertex1, worldVertex0);
vec2.normalize(worldEdgeUnit, worldEdge);
// Get tangent to the edge. Points out of the Convex
vec2.rotate(worldTangent, worldEdgeUnit, -Math.PI/2);
// Check distance from the infinite line (spanned by the edge) to the particle
sub(dist, particleOffset, worldVertex0);
var d = dot(dist, worldTangent);
sub(centerDist, worldVertex0, convexOffset);
sub(convexToparticle, particleOffset, convexOffset);
/*
if(d < 0 && dot(centerDist,convexToparticle) >= 0){
// Now project the particle onto the edge
vec2.scale(orthoDist, worldTangent, d);
sub(projectedPoint, particleOffset, orthoDist);
// Check if the point is within the edge span
var pos = dot(worldEdgeUnit, projectedPoint);
var pos0 = dot(worldEdgeUnit, worldVertex0);
var pos1 = dot(worldEdgeUnit, worldVertex1);
if(pos > pos0 && pos < pos1){
// We got contact!
if(justTest) return true;
if(closestEdgeDistance === null || d*d<closestEdgeDistance*closestEdgeDistance){
closestEdgeDistance = d;
closestEdge = i;
vec2.copy(closestEdgeOrthoDist, orthoDist);
vec2.copy(closestEdgeProjectedPoint, projectedPoint);
}
}
}
*/
vec2.sub(candidateDist,worldVertex0,particleOffset);
var candidateDistance = Math.abs(vec2.dot(candidateDist,worldTangent));
if(candidateDistance < minCandidateDistance){
minCandidateDistance = candidateDistance;
vec2.scale(closestEdgeProjectedPoint,worldTangent,candidateDistance);
vec2.add(closestEdgeProjectedPoint,closestEdgeProjectedPoint,particleOffset);
vec2.copy(minEdgeNormal,worldTangent);
found = true;
}
}
if(found){
var c = this.createContactEquation(particleBody,convexBody,si,sj);
vec2.scale(c.ni, minEdgeNormal, -1);
vec2.normalize(c.ni, c.ni);
// Particle has no extent to the contact point
vec2.set(c.ri, 0, 0);
add(c.ri, c.ri, particleOffset);
sub(c.ri, c.ri, particleBody.position);
// From convex center to point
sub(c.rj, closestEdgeProjectedPoint, convexOffset);
add(c.rj, c.rj, convexOffset);
sub(c.rj, c.rj, convexBody.position);
this.contactEquations.push(c);
if(this.enableFriction)
this.frictionEquations.push( this.createFrictionFromContact(c) );
return 1;
}
return 0;
};
/**
* Circle/circle Narrowphase
* @method circleCircle
* @param {Body} bi
* @param {Circle} si
* @param {Array} xi
* @param {Number} ai
* @param {Body} bj
* @param {Circle} sj
* @param {Array} xj
* @param {Number} aj
*/
Narrowphase.prototype[Shape.CIRCLE] =
Narrowphase.prototype.circleCircle = function( bi,si,xi,ai, bj,sj,xj,aj, justTest, radiusA, radiusB){
var bodyA = bi,
shapeA = si,
offsetA = xi,
bodyB = bj,
shapeB = sj,
offsetB = xj,
dist = tmp1,
radiusA = radiusA || shapeA.radius,
radiusB = radiusB || shapeB.radius;
sub(dist,xi,xj);
var r = radiusA + radiusB;
if(vec2.squaredLength(dist) > r*r)
return 0;
if(justTest) return true;
var c = this.createContactEquation(bodyA,bodyB,si,sj);
sub(c.ni, offsetB, offsetA);
vec2.normalize(c.ni,c.ni);
vec2.scale( c.ri, c.ni, radiusA);
vec2.scale( c.rj, c.ni, -radiusB);
add(c.ri, c.ri, offsetA);
sub(c.ri, c.ri, bodyA.position);
add(c.rj, c.rj, offsetB);
sub(c.rj, c.rj, bodyB.position);
this.contactEquations.push(c);
if(this.enableFriction){
this.frictionEquations.push(this.createFrictionFromContact(c));
}
return 1;
};
/**
* Plane/Convex Narrowphase
* @method planeConvex
* @param {Body} bi
* @param {Plane} si
* @param {Array} xi
* @param {Number} ai
* @param {Body} bj
* @param {Convex} sj
* @param {Array} xj
* @param {Number} aj
*/
Narrowphase.prototype[Shape.PLANE | Shape.CONVEX] =
Narrowphase.prototype[Shape.PLANE | Shape.RECTANGLE] =
Narrowphase.prototype.planeConvex = function( bi,si,xi,ai, bj,sj,xj,aj, justTest ){
var convexBody = bj,
convexOffset = xj,
convexShape = sj,
convexAngle = aj,
planeBody = bi,
planeShape = si,
planeOffset = xi,
planeAngle = ai;
var worldVertex = tmp1,
worldNormal = tmp2,
dist = tmp3;
var numReported = 0;
vec2.rotate(worldNormal, yAxis, planeAngle);
for(var i=0; i<convexShape.vertices.length; i++){
var v = convexShape.vertices[i];
vec2.rotate(worldVertex, v, convexAngle);
add(worldVertex, worldVertex, convexOffset);
sub(dist, worldVertex, planeOffset);
if(dot(dist,worldNormal) < 0){
if(justTest) return true;
// Found vertex
numReported++;
var c = this.createContactEquation(planeBody,convexBody,planeShape,convexShape);
sub(dist, worldVertex, planeOffset);
vec2.copy(c.ni, worldNormal);
var d = dot(dist, c.ni);
vec2.scale(dist, c.ni, d);
// rj is from convex center to contact
sub(c.rj, worldVertex, convexBody.position);
// ri is from plane center to contact
sub( c.ri, worldVertex, dist);
sub( c.ri, c.ri, planeBody.position);
this.contactEquations.push(c);
// TODO: if we have 2 contacts, we do only need 1 friction equation
if(this.enableFriction){
this.frictionEquations.push(this.createFrictionFromContact(c));
}
if(numReported >= 2)
break;
}
}
return numReported;
};
/**
* @method convexPlane
* @deprecated Use .planeConvex() instead!
*/
Narrowphase.prototype.convexPlane = function( bi,si,xi,ai, bj,sj,xj,aj, justTest ){
console.warn("Narrowphase.prototype.convexPlane is deprecated. Use planeConvex instead!");
return this.planeConvex( bj,sj,xj,aj, bi,si,xi,ai, justTest );
}
/**
* Narrowphase for particle vs plane
* @method particlePlane
* @param {Body} bi The particle body
* @param {Particle} si Particle shape
* @param {Array} xi World position for the particle
* @param {Number} ai World angle for the particle
* @param {Body} bj Plane body
* @param {Plane} sj Plane shape
* @param {Array} xj World position for the plane
* @param {Number} aj World angle for the plane
*/
Narrowphase.prototype[Shape.PARTICLE | Shape.PLANE] =
Narrowphase.prototype.particlePlane = function( bi,si,xi,ai, bj,sj,xj,aj, justTest ){
var particleBody = bi,
particleShape = si,
particleOffset = xi,
planeBody = bj,
planeShape = sj,
planeOffset = xj,
planeAngle = aj;
var dist = tmp1,
worldNormal = tmp2;
planeAngle = planeAngle || 0;
sub(dist, particleOffset, planeOffset);
vec2.rotate(worldNormal, yAxis, planeAngle);
var d = dot(dist, worldNormal);
if(d > 0) return 0;
if(justTest) return true;
var c = this.createContactEquation(planeBody,particleBody,sj,si);
vec2.copy(c.ni, worldNormal);
vec2.scale( dist, c.ni, d );
// dist is now the distance vector in the normal direction
// ri is the particle position projected down onto the plane, from the plane center
sub( c.ri, particleOffset, dist);
sub( c.ri, c.ri, planeBody.position);
// rj is from the body center to the particle center
sub( c.rj, particleOffset, particleBody.position );
this.contactEquations.push(c);
if(this.enableFriction){
this.frictionEquations.push(this.createFrictionFromContact(c));
}
return 1;
};
/**
* Circle/Particle Narrowphase
* @method circleParticle
* @param {Body} bi
* @param {Circle} si
* @param {Array} xi
* @param {Number} ai
* @param {Body} bj
* @param {Particle} sj
* @param {Array} xj
* @param {Number} aj
*/
Narrowphase.prototype[Shape.CIRCLE | Shape.PARTICLE] =
Narrowphase.prototype.circleParticle = function( bi,si,xi,ai, bj,sj,xj,aj, justTest ){
var circleBody = bi,
circleShape = si,
circleOffset = xi,
particleBody = bj,
particleShape = sj,
particleOffset = xj,
dist = tmp1;
sub(dist, particleOffset, circleOffset);
if(vec2.squaredLength(dist) > circleShape.radius*circleShape.radius) return 0;
if(justTest) return true;
var c = this.createContactEquation(circleBody,particleBody,si,sj);
vec2.copy(c.ni, dist);
vec2.normalize(c.ni,c.ni);
// Vector from circle to contact point is the normal times the circle radius
vec2.scale(c.ri, c.ni, circleShape.radius);
add(c.ri, c.ri, circleOffset);
sub(c.ri, c.ri, circleBody.position);
// Vector from particle center to contact point is zero
sub(c.rj, particleOffset, particleBody.position);
this.contactEquations.push(c);
if(this.enableFriction){
this.frictionEquations.push(this.createFrictionFromContact(c));
}
return 1;
};
var capsulePlane_tmpCircle = new Circle(1),
capsulePlane_tmp1 = vec2.create(),
capsulePlane_tmp2 = vec2.create(),
capsulePlane_tmp3 = vec2.create();
Narrowphase.prototype[Shape.PLANE | Shape.CAPSULE] =
Narrowphase.prototype.planeCapsule = function( bi,si,xi,ai, bj,sj,xj,aj, justTest ){
var end1 = capsulePlane_tmp1,
end2 = capsulePlane_tmp2,
circle = capsulePlane_tmpCircle,
dst = capsulePlane_tmp3;
// Compute world end positions
vec2.set(end1, -sj.length/2, 0);
vec2.rotate(end1,end1,aj);
add(end1,end1,xj);
vec2.set(end2, sj.length/2, 0);
vec2.rotate(end2,end2,aj);
add(end2,end2,xj);
circle.radius = sj.radius;
// Do Narrowphase as two circles
var numContacts1 = this.circlePlane(bj,circle,end1,0, bi,si,xi,ai, justTest),
numContacts2 = this.circlePlane(bj,circle,end2,0, bi,si,xi,ai, justTest);
if(justTest)
return numContacts1 || numContacts2;
else
return numContacts1 + numContacts2;
};
/**
* @method capsulePlane
* @deprecated Use .planeCapsule() instead!
*/
Narrowphase.prototype.capsulePlane = function( bi,si,xi,ai, bj,sj,xj,aj, justTest ){
console.warn("Narrowphase.prototype.capsulePlane() is deprecated. Use .planeCapsule() instead!");
return this.planeCapsule( bj,sj,xj,aj, bi,si,xi,ai, justTest );
}
/**
* Creates ContactEquations and FrictionEquations for a collision.
* @method circlePlane
* @param {Body} bi The first body that should be connected to the equations.
* @param {Circle} si The circle shape participating in the collision.
* @param {Array} xi Extra offset to take into account for the Shape, in addition to the one in circleBody.position. Will *not* be rotated by circleBody.angle (maybe it should, for sake of homogenity?). Set to null if none.
* @param {Body} bj The second body that should be connected to the equations.
* @param {Plane} sj The Plane shape that is participating
* @param {Array} xj Extra offset for the plane shape.
* @param {Number} aj Extra angle to apply to the plane
*/
Narrowphase.prototype[Shape.CIRCLE | Shape.PLANE] =
Narrowphase.prototype.circlePlane = function( bi,si,xi,ai, bj,sj,xj,aj, justTest ){
var circleBody = bi,
circleShape = si,
circleOffset = xi, // Offset from body center, rotated!
planeBody = bj,
shapeB = sj,
planeOffset = xj,
planeAngle = aj;
planeAngle = planeAngle || 0;
// Vector from plane to circle
var planeToCircle = tmp1,
worldNormal = tmp2,
temp = tmp3;
sub(planeToCircle, circleOffset, planeOffset);
// World plane normal
vec2.rotate(worldNormal, yAxis, planeAngle);
// Normal direction distance
var d = dot(worldNormal, planeToCircle);
if(d > circleShape.radius) return 0; // No overlap. Abort.
if(justTest) return true;
// Create contact
var contact = this.createContactEquation(planeBody,circleBody,sj,si);
// ni is the plane world normal
vec2.copy(contact.ni, worldNormal);
// rj is the vector from circle center to the contact point
vec2.scale(contact.rj, contact.ni, -circleShape.radius);
add(contact.rj, contact.rj, circleOffset);
sub(contact.rj, contact.rj, circleBody.position);
// ri is the distance from plane center to contact.
vec2.scale(temp, contact.ni, d);
sub(contact.ri, planeToCircle, temp ); // Subtract normal distance vector from the distance vector
add(contact.ri, contact.ri, planeOffset);
sub(contact.ri, contact.ri, planeBody.position);
this.contactEquations.push(contact);
if(this.enableFriction){
this.frictionEquations.push( this.createFrictionFromContact(contact) );
}
return 1;
};
Narrowphase.convexPrecision = 1e-10;
/**
* Convex/convex Narrowphase.See <a href="http://www.altdevblogaday.com/2011/05/13/contact-generation-between-3d-convex-meshes/">this article</a> for more info.
* @method convexConvex
* @param {Body} bi
* @param {Convex} si
* @param {Array} xi
* @param {Number} ai
* @param {Body} bj
* @param {Convex} sj
* @param {Array} xj
* @param {Number} aj
*/
Narrowphase.prototype[Shape.CONVEX] =
Narrowphase.prototype[Shape.CONVEX | Shape.RECTANGLE] =
Narrowphase.prototype[Shape.RECTANGLE] =
Narrowphase.prototype.convexConvex = function( bi,si,xi,ai, bj,sj,xj,aj, justTest, precision ){
var sepAxis = tmp1,
worldPoint = tmp2,
worldPoint0 = tmp3,
worldPoint1 = tmp4,
worldEdge = tmp5,
projected = tmp6,
penetrationVec = tmp7,
dist = tmp8,
worldNormal = tmp9,
numContacts = 0,
precision = precision || Narrowphase.convexPrecision;
var found = Narrowphase.findSeparatingAxis(si,xi,ai,sj,xj,aj,sepAxis);
if(!found) return 0;
// Make sure the separating axis is directed from shape i to shape j
sub(dist,xj,xi);
if(dot(sepAxis,dist) > 0){
vec2.scale(sepAxis,sepAxis,-1);
}
// Find edges with normals closest to the separating axis
var closestEdge1 = Narrowphase.getClosestEdge(si,ai,sepAxis,true), // Flipped axis
closestEdge2 = Narrowphase.getClosestEdge(sj,aj,sepAxis);
if(closestEdge1==-1 || closestEdge2==-1) return 0;
// Loop over the shapes
for(var k=0; k<2; k++){
var closestEdgeA = closestEdge1,
closestEdgeB = closestEdge2,
shapeA = si, shapeB = sj,
offsetA = xi, offsetB = xj,
angleA = ai, angleB = aj,
bodyA = bi, bodyB = bj;
if(k==0){
// Swap!
var tmp;
tmp = closestEdgeA; closestEdgeA = closestEdgeB; closestEdgeB = tmp;
tmp = shapeA; shapeA = shapeB; shapeB = tmp;
tmp = offsetA; offsetA = offsetB; offsetB = tmp;
tmp = angleA; angleA = angleB; angleB = tmp;
tmp = bodyA; bodyA = bodyB; bodyB = tmp;
}
// Loop over 2 points in convex B
for(var j=closestEdgeB; j<closestEdgeB+2; j++){
// Get world point
var v = shapeB.vertices[(j+shapeB.vertices.length)%shapeB.vertices.length];
vec2.rotate(worldPoint, v, angleB);
add(worldPoint, worldPoint, offsetB);
var insideNumEdges = 0;
// Loop over the 3 closest edges in convex A
for(var i=closestEdgeA-1; i<closestEdgeA+2; i++){
var v0 = shapeA.vertices[(i +shapeA.vertices.length)%shapeA.vertices.length],
v1 = shapeA.vertices[(i+1+shapeA.vertices.length)%shapeA.vertices.length];
// Construct the edge
vec2.rotate(worldPoint0, v0, angleA);
vec2.rotate(worldPoint1, v1, angleA);
add(worldPoint0, worldPoint0, offsetA);
add(worldPoint1, worldPoint1, offsetA);
sub(worldEdge, worldPoint1, worldPoint0);
vec2.rotate(worldNormal, worldEdge, -Math.PI/2); // Normal points out of convex 1
vec2.normalize(worldNormal,worldNormal);
sub(dist, worldPoint, worldPoint0);
var d = dot(worldNormal,dist);
if(d <= precision){
insideNumEdges++;
}
}
if(insideNumEdges == 3){
if(justTest) return true;
// worldPoint was on the "inside" side of each of the 3 checked edges.
// Project it to the center edge and use the projection direction as normal
// Create contact
var c = this.createContactEquation(bodyA,bodyB,shapeA,shapeB);
numContacts++;
// Get center edge from body A
var v0 = shapeA.vertices[(closestEdgeA) % shapeA.vertices.length],
v1 = shapeA.vertices[(closestEdgeA+1) % shapeA.vertices.length];
// Construct the edge
vec2.rotate(worldPoint0, v0, angleA);
vec2.rotate(worldPoint1, v1, angleA);
add(worldPoint0, worldPoint0, offsetA);
add(worldPoint1, worldPoint1, offsetA);
sub(worldEdge, worldPoint1, worldPoint0);
vec2.rotate(c.ni, worldEdge, -Math.PI/2); // Normal points out of convex A
vec2.normalize(c.ni,c.ni);
sub(dist, worldPoint, worldPoint0); // From edge point to the penetrating point
var d = dot(c.ni,dist); // Penetration
vec2.scale(penetrationVec, c.ni, d); // Vector penetration
sub(c.ri, worldPoint, offsetA);
sub(c.ri, c.ri, penetrationVec);
add(c.ri, c.ri, offsetA);
sub(c.ri, c.ri, bodyA.position);
sub(c.rj, worldPoint, offsetB);
add(c.rj, c.rj, offsetB);
sub(c.rj, c.rj, bodyB.position);
this.contactEquations.push(c);
// Todo reduce to 1 friction equation if we have 2 contact points
if(this.enableFriction)
this.frictionEquations.push(this.createFrictionFromContact(c));
}
}
}
return numContacts;
};
// .projectConvex is called by other functions, need local tmp vectors
var pcoa_tmp1 = vec2.fromValues(0,0);
/**
* Project a Convex onto a world-oriented axis
* @method projectConvexOntoAxis
* @static
* @param {Convex} convexShape
* @param {Array} convexOffset
* @param {Number} convexAngle
* @param {Array} worldAxis
* @param {Array} result
*/
Narrowphase.projectConvexOntoAxis = function(convexShape, convexOffset, convexAngle, worldAxis, result){
var max=null,
min=null,
v,
value,
localAxis = pcoa_tmp1;
// Convert the axis to local coords of the body
vec2.rotate(localAxis, worldAxis, -convexAngle);
// Get projected position of all vertices
for(var i=0; i<convexShape.vertices.length; i++){
v = convexShape.vertices[i];
value = dot(v,localAxis);
if(max === null || value > max) max = value;
if(min === null || value < min) min = value;
}
if(min > max){
var t = min;
min = max;
max = t;
}
// Project the position of the body onto the axis - need to add this to the result
var offset = dot(convexOffset, worldAxis);
vec2.set( result, min + offset, max + offset);
};
// .findSeparatingAxis is called by other functions, need local tmp vectors
var fsa_tmp1 = vec2.fromValues(0,0)
, fsa_tmp2 = vec2.fromValues(0,0)
, fsa_tmp3 = vec2.fromValues(0,0)
, fsa_tmp4 = vec2.fromValues(0,0)
, fsa_tmp5 = vec2.fromValues(0,0)
, fsa_tmp6 = vec2.fromValues(0,0)
/**
* Find a separating axis between the shapes, that maximizes the separating distance between them.
* @method findSeparatingAxis
* @static
* @param {Convex} c1
* @param {Array} offset1
* @param {Number} angle1
* @param {Convex} c2
* @param {Array} offset2
* @param {Number} angle2
* @param {Array} sepAxis The resulting axis
* @return {Boolean} Whether the axis could be found.
*/
Narrowphase.findSeparatingAxis = function(c1,offset1,angle1,c2,offset2,angle2,sepAxis){
var maxDist = null,
overlap = false,
found = false,
edge = fsa_tmp1,
worldPoint0 = fsa_tmp2,
worldPoint1 = fsa_tmp3,
normal = fsa_tmp4,
span1 = fsa_tmp5,
span2 = fsa_tmp6;
for(var j=0; j!==2; j++){
var c = c1,
angle = angle1;
if(j===1){
c = c2;
angle = angle2;
}
for(var i=0; i!==c.vertices.length; i++){
// Get the world edge
vec2.rotate(worldPoint0, c.vertices[i], angle);
vec2.rotate(worldPoint1, c.vertices[(i+1)%c.vertices.length], angle);
sub(edge, worldPoint1, worldPoint0);
// Get normal - just rotate 90 degrees since vertices are given in CCW
vec2.rotate(normal, edge, -Math.PI / 2);
vec2.normalize(normal,normal);
// Project hulls onto that normal
Narrowphase.projectConvexOntoAxis(c1,offset1,angle1,normal,span1);
Narrowphase.projectConvexOntoAxis(c2,offset2,angle2,normal,span2);
// Order by span position
var a=span1,
b=span2,
swapped = false;
if(span1[0] > span2[0]){
b=span1;
a=span2;
swapped = true;
}
// Get separating distance
var dist = b[0] - a[1];
overlap = dist < 0;
if(maxDist===null || dist > maxDist){
vec2.copy(sepAxis, normal);
maxDist = dist;
found = overlap;
}
}
}
return found;
};
// .getClosestEdge is called by other functions, need local tmp vectors
var gce_tmp1 = vec2.fromValues(0,0)
, gce_tmp2 = vec2.fromValues(0,0)
, gce_tmp3 = vec2.fromValues(0,0)
/**
* Get the edge that has a normal closest to an axis.
* @method getClosestEdge
* @static
* @param {Convex} c
* @param {Number} angle
* @param {Array} axis
* @param {Boolean} flip
* @return {Number} Index of the edge that is closest. This index and the next spans the resulting edge. Returns -1 if failed.
*/
Narrowphase.getClosestEdge = function(c,angle,axis,flip){
var localAxis = gce_tmp1,
edge = gce_tmp2,
normal = gce_tmp3;
// Convert the axis to local coords of the body
vec2.rotate(localAxis, axis, -angle);
if(flip){
vec2.scale(localAxis,localAxis,-1);
}
var closestEdge = -1,
N = c.vertices.length,
halfPi = Math.PI / 2;
for(var i=0; i!==N; i++){
// Get the edge
sub(edge, c.vertices[(i+1)%N], c.vertices[i%N]);
// Get normal - just rotate 90 degrees since vertices are given in CCW
vec2.rotate(normal, edge, -halfPi);
vec2.normalize(normal,normal);
var d = dot(normal,localAxis);
if(closestEdge == -1 || d > maxDot){
closestEdge = i % N;
maxDot = d;
}
}
return closestEdge;
};
var circleHeightfield_candidate = vec2.create(),
circleHeightfield_dist = vec2.create(),
circleHeightfield_v0 = vec2.create(),
circleHeightfield_v1 = vec2.create(),
circleHeightfield_minCandidate = vec2.create(),
circleHeightfield_worldNormal = vec2.create(),
circleHeightfield_minCandidateNormal = vec2.create();
/**
* @method circleHeightfield
* @param {Body} bi
* @param {Circle} si
* @param {Array} xi
* @param {Body} bj
* @param {Heightfield} sj
* @param {Array} xj
* @param {Number} aj
*/
Narrowphase.prototype[Shape.CIRCLE | Shape.HEIGHTFIELD] =
Narrowphase.prototype.circleHeightfield = function( circleBody,circleShape,circlePos,circleAngle,
hfBody,hfShape,hfPos,hfAngle, justTest, radius ){
var data = hfShape.data,
radius = radius || circleShape.radius,
w = hfShape.elementWidth,
dist = circleHeightfield_dist,
candidate = circleHeightfield_candidate,
minCandidate = circleHeightfield_minCandidate,
minCandidateNormal = circleHeightfield_minCandidateNormal,
worldNormal = circleHeightfield_worldNormal,
v0 = circleHeightfield_v0,
v1 = circleHeightfield_v1;
// Get the index of the points to test against
var idxA = Math.floor( (circlePos[0] - radius - hfPos[0]) / w ),
idxB = Math.ceil( (circlePos[0] + radius - hfPos[0]) / w );
/*if(idxB < 0 || idxA >= data.length)
return justTest ? false : 0;*/
if(idxA < 0) idxA = 0;
if(idxB >= data.length) idxB = data.length-1;
// Get max and min
var max = data[idxA],
min = data[idxB];
for(var i=idxA; i<idxB; i++){
if(data[i] < min) min = data[i];
if(data[i] > max) max = data[i];
}
if(circlePos[1]-radius > max)
return justTest ? false : 0;
if(circlePos[1]+radius < min){
// Below the minimum point... We can just guess.
// TODO
}
// 1. Check so center of circle is not inside the field. If it is, this wont work...
// 2. For each edge
// 2. 1. Get point on circle that is closest to the edge (scale normal with -radius)
// 2. 2. Check if point is inside.
var found = false,
minDist = false;
// Check all edges first
for(var i=idxA; i<idxB; i++){
// Get points
vec2.set(v0, i*w, data[i] );
vec2.set(v1, (i+1)*w, data[i+1]);
vec2.add(v0,v0,hfPos);
vec2.add(v1,v1,hfPos);
// Get normal
vec2.sub(worldNormal, v1, v0);
vec2.rotate(worldNormal, worldNormal, Math.PI/2);
vec2.normalize(worldNormal,worldNormal);
// Get point on circle, closest to the edge
vec2.scale(candidate,worldNormal,-radius);
vec2.add(candidate,candidate,circlePos);
// Distance from v0 to the candidate point
vec2.sub(dist,candidate,v0);
// Check if it is in the element "stick"
var d = vec2.dot(dist,worldNormal);
if(candidate[0] >= v0[0] && candidate[0] < v1[0] && d <= 0){
if(minDist === false || Math.abs(d) < minDist){
// Store the candidate point, projected to the edge
vec2.scale(dist,worldNormal,-d);
vec2.add(minCandidate,candidate,dist);
vec2.copy(minCandidateNormal,worldNormal);
found = true;
minDist = Math.abs(d);
if(justTest)
return true;
}
}
}
if(found){
var c = this.createContactEquation(hfBody,circleBody,hfShape,circleShape);
// Normal is out of the heightfield
vec2.copy(c.ni, minCandidateNormal);
// Vector from circle to heightfield
vec2.scale(c.rj, c.ni, -radius);
add(c.rj, c.rj, circlePos);
sub(c.rj, c.rj, circleBody.position);
vec2.copy(c.ri, minCandidate);
//vec2.sub(c.ri, c.ri, hfPos);
vec2.sub(c.ri, c.ri, hfBody.position);
this.contactEquations.push(c);
if(this.enableFriction)
this.frictionEquations.push( this.createFrictionFromContact(c) );
return 1;
}
// Check all vertices
if(radius > 0){
for(var i=idxA; i<=idxB; i++){
// Get point
vec2.set(v0, i*w, data[i]);
vec2.add(v0,v0,hfPos);
vec2.sub(dist, circlePos, v0);
if(vec2.squaredLength(dist) < radius*radius){
if(justTest) return true;
var c = this.createContactEquation(hfBody,circleBody,hfShape,circleShape);
// Construct normal - out of heightfield
vec2.copy(c.ni, dist);
vec2.normalize(c.ni,c.ni);
vec2.scale(c.rj, c.ni, -radius);
add(c.rj, c.rj, circlePos);
sub(c.rj, c.rj, circleBody.position);
sub(c.ri, v0, hfPos);
add(c.ri, c.ri, hfPos);
sub(c.ri, c.ri, hfBody.position);
this.contactEquations.push(c);
if(this.enableFriction){
this.frictionEquations.push(this.createFrictionFromContact(c));
}
return 1;
}
}
}
return 0;
};
},{"../equations/ContactEquation":23,"../equations/FrictionEquation":25,"../math/vec2":33,"../objects/Body":34,"../shapes/Circle":38,"../shapes/Rectangle":44,"../shapes/Shape":45,"../utils/Utils":50}],14:[function(require,module,exports){
var Plane = require("../shapes/Plane");
var Broadphase = require("../collision/Broadphase");
module.exports = {
QuadTree : QuadTree,
Node : Node,
BoundsNode : BoundsNode,
};
/**
* QuadTree data structure. See https://github.com/mikechambers/ExamplesByMesh/tree/master/JavaScript/QuadTree
* @class QuadTree
* @constructor
* @param {Object} An object representing the bounds of the top level of the QuadTree. The object
* should contain the following properties : x, y, width, height
* @param {Boolean} pointQuad Whether the QuadTree will contain points (true), or items with bounds
* (width / height)(false). Default value is false.
* @param {Number} maxDepth The maximum number of levels that the quadtree will create. Default is 4.
* @param {Number} maxChildren The maximum number of children that a node can contain before it is split into sub-nodes.
*/
function QuadTree(bounds, pointQuad, maxDepth, maxChildren){
var node;
if(pointQuad){
node = new Node(bounds, 0, maxDepth, maxChildren);
} else {
node = new BoundsNode(bounds, 0, maxDepth, maxChildren);
}
/**
* The root node of the QuadTree which covers the entire area being segmented.
* @property root
* @type Node
*/
this.root = node;
}
/**
* Inserts an item into the QuadTree.
* @method insert
* @param {Object|Array} item The item or Array of items to be inserted into the QuadTree. The item should expose x, y
* properties that represents its position in 2D space.
*/
QuadTree.prototype.insert = function(item){
if(item instanceof Array){
var len = item.length;
for(var i = 0; i < len; i++){
this.root.insert(item[i]);
}
} else {
this.root.insert(item);
}
}
/**
* Clears all nodes and children from the QuadTree
* @method clear
*/
QuadTree.prototype.clear = function(){
this.root.clear();
}
/**
* Retrieves all items / points in the same node as the specified item / point. If the specified item
* overlaps the bounds of a node, then all children in both nodes will be returned.
* @method retrieve
* @param {Object} item An object representing a 2D coordinate point (with x, y properties), or a shape
* with dimensions (x, y, width, height) properties.
*/
QuadTree.prototype.retrieve = function(item){
//get a copy of the array of items
var out = this.root.retrieve(item).slice(0);
return out;
}
QuadTree.prototype.getCollisionPairs = function(world){
var result = [];
// Add all bodies
this.insert(world.bodies);
/*
console.log("bodies",world.bodies.length);
console.log("maxDepth",this.root.maxDepth,"maxChildren",this.root.maxChildren);
*/
for(var i=0; i!==world.bodies.length; i++){
var b = world.bodies[i],
items = this.retrieve(b);
//console.log("items",items.length);
// Check results
for(var j=0, len=items.length; j!==len; j++){
var item = items[j];
if(b === item) continue; // Do not add self
// Check if they were already added
var found = false;
for(var k=0, numAdded=result.length; k<numAdded; k+=2){
var r1 = result[k],
r2 = result[k+1];
if( (r1==item && r2==b) || (r2==item && r1==b) ){
found = true;
break;
}
}
if(!found && Broadphase.boundingRadiusCheck(b,item)){
result.push(b,item);
}
}
}
//console.log("results",result.length);
// Clear until next
this.clear();
return result;
};
function Node(bounds, depth, maxDepth, maxChildren){
this.bounds = bounds;
this.children = [];
this.nodes = [];
if(maxChildren){
this.maxChildren = maxChildren;
}
if(maxDepth){
this.maxDepth = maxDepth;
}
if(depth){
this.depth = depth;
}
}
//subnodes
Node.prototype.classConstructor = Node;
//children contained directly in the node
Node.prototype.children = null;
//read only
Node.prototype.depth = 0;
Node.prototype.maxChildren = 4;
Node.prototype.maxDepth = 4;
Node.TOP_LEFT = 0;
Node.TOP_RIGHT = 1;
Node.BOTTOM_LEFT = 2;
Node.BOTTOM_RIGHT = 3;
Node.prototype.insert = function(item){
if(this.nodes.length){
var index = this.findIndex(item);
this.nodes[index].insert(item);
return;
}
this.children.push(item);
var len = this.children.length;
if(!(this.depth >= this.maxDepth) && len > this.maxChildren) {
this.subdivide();
for(var i = 0; i < len; i++){
this.insert(this.children[i]);
}
this.children.length = 0;
}
}
Node.prototype.retrieve = function(item){
if(this.nodes.length){
var index = this.findIndex(item);
return this.nodes[index].retrieve(item);
}
return this.children;
}
Node.prototype.findIndex = function(item){
var b = this.bounds;
var left = (item.position[0]-item.boundingRadius > b.x + b.width / 2) ? false : true;
var top = (item.position[1]-item.boundingRadius > b.y + b.height / 2) ? false : true;
if(item instanceof Plane){
left = top = false; // Will overlap the left/top boundary since it is infinite
}
//top left
var index = Node.TOP_LEFT;
if(left){
if(!top){
index = Node.BOTTOM_LEFT;
}
} else {
if(top){
index = Node.TOP_RIGHT;
} else {
index = Node.BOTTOM_RIGHT;
}
}
return index;
}
Node.prototype.subdivide = function(){
var depth = this.depth + 1;
var bx = this.bounds.x;
var by = this.bounds.y;
//floor the values
var b_w_h = (this.bounds.width / 2);
var b_h_h = (this.bounds.height / 2);
var bx_b_w_h = bx + b_w_h;
var by_b_h_h = by + b_h_h;
//top left
this.nodes[Node.TOP_LEFT] = new this.classConstructor({
x:bx,
y:by,
width:b_w_h,
height:b_h_h
},
depth);
//top right
this.nodes[Node.TOP_RIGHT] = new this.classConstructor({
x:bx_b_w_h,
y:by,
width:b_w_h,
height:b_h_h
},
depth);
//bottom left
this.nodes[Node.BOTTOM_LEFT] = new this.classConstructor({
x:bx,
y:by_b_h_h,
width:b_w_h,
height:b_h_h
},
depth);
//bottom right
this.nodes[Node.BOTTOM_RIGHT] = new this.classConstructor({
x:bx_b_w_h,
y:by_b_h_h,
width:b_w_h,
height:b_h_h
},
depth);
}
Node.prototype.clear = function(){
this.children.length = 0;
var len = this.nodes.length;
for(var i = 0; i < len; i++){
this.nodes[i].clear();
}
this.nodes.length = 0;
}
// BoundsQuadTree
function BoundsNode(bounds, depth, maxChildren, maxDepth){
Node.call(this, bounds, depth, maxChildren, maxDepth);
this.stuckChildren = [];
}
BoundsNode.prototype = new Node();
BoundsNode.prototype.classConstructor = BoundsNode;
BoundsNode.prototype.stuckChildren = null;
//we use this to collect and conctenate items being retrieved. This way
//we dont have to continuously create new Array instances.
//Note, when returned from QuadTree.retrieve, we then copy the array
BoundsNode.prototype.out = [];
BoundsNode.prototype.insert = function(item){
if(this.nodes.length){
var index = this.findIndex(item);
var node = this.nodes[index];
/*
console.log("radius:",item.boundingRadius);
console.log("item x:",item.position[0] - item.boundingRadius,"x range:",node.bounds.x,node.bounds.x+node.bounds.width);
console.log("item y:",item.position[1] - item.boundingRadius,"y range:",node.bounds.y,node.bounds.y+node.bounds.height);
*/
//todo: make _bounds bounds
if( !(item instanceof Plane) && // Plane is infinite.. Make it a "stuck" child
item.position[0] - item.boundingRadius >= node.bounds.x &&
item.position[0] + item.boundingRadius <= node.bounds.x + node.bounds.width &&
item.position[1] - item.boundingRadius >= node.bounds.y &&
item.position[1] + item.boundingRadius <= node.bounds.y + node.bounds.height){
this.nodes[index].insert(item);
} else {
this.stuckChildren.push(item);
}
return;
}
this.children.push(item);
var len = this.children.length;
if(this.depth < this.maxDepth && len > this.maxChildren){
this.subdivide();
for(var i=0; i<len; i++){
this.insert(this.children[i]);
}
this.children.length = 0;
}
}
BoundsNode.prototype.getChildren = function(){
return this.children.concat(this.stuckChildren);
}
BoundsNode.prototype.retrieve = function(item){
var out = this.out;
out.length = 0;
if(this.nodes.length){
var index = this.findIndex(item);
out.push.apply(out, this.nodes[index].retrieve(item));
}
out.push.apply(out, this.stuckChildren);
out.push.apply(out, this.children);
return out;
}
BoundsNode.prototype.clear = function(){
this.stuckChildren.length = 0;
//array
this.children.length = 0;
var len = this.nodes.length;
if(!len){
return;
}
for(var i = 0; i < len; i++){
this.nodes[i].clear();
}
//array
this.nodes.length = 0;
//we could call the super clear function but for now, im just going to inline it
//call the hidden super.clear, and make sure its called with this = this instance
//Object.getPrototypeOf(BoundsNode.prototype).clear.call(this);
}
},{"../collision/Broadphase":10,"../shapes/Plane":43}],15:[function(require,module,exports){
var Circle = require('../shapes/Circle')
, Plane = require('../shapes/Plane')
, Shape = require('../shapes/Shape')
, Particle = require('../shapes/Particle')
, Utils = require('../utils/Utils')
, Broadphase = require('../collision/Broadphase')
, vec2 = require('../math/vec2')
module.exports = SAPBroadphase;
/**
* Sweep and prune broadphase along one axis.
*
* @class SAPBroadphase
* @constructor
* @extends Broadphase
*/
function SAPBroadphase(){
Broadphase.call(this,Broadphase.SAP);
/**
* List of bodies currently in the broadphase.
* @property axisListX
* @type {Array}
*/
this.axisListX = [];
/**
* List of bodies currently in the broadphase.
* @property axisListY
* @type {Array}
*/
this.axisListY = [];
/**
* The world to search in.
* @property world
* @type {World}
*/
this.world = null;
var axisListX = this.axisListX,
axisListY = this.axisListY;
this._addBodyHandler = function(e){
axisListX.push(e.body);
axisListY.push(e.body);
};
this._removeBodyHandler = function(e){
// Remove from X list
var idx = axisListX.indexOf(e.body);
if(idx !== -1) axisListX.splice(idx,1);
// Remove from Y list
idx = axisListY.indexOf(e.body);
if(idx !== -1) axisListY.splice(idx,1);
}
};
SAPBroadphase.prototype = new Broadphase();
/**
* Change the world
* @method setWorld
* @param {World} world
*/
SAPBroadphase.prototype.setWorld = function(world){
// Clear the old axis array
this.axisListX.length = this.axisListY.length = 0;
// Add all bodies from the new world
Utils.appendArray(this.axisListX,world.bodies);
Utils.appendArray(this.axisListY,world.bodies);
// Remove old handlers, if any
world
.off("addBody",this._addBodyHandler)
.off("removeBody",this._removeBodyHandler);
// Add handlers to update the list of bodies.
world.on("addBody",this._addBodyHandler).on("removeBody",this._removeBodyHandler);
this.world = world;
};
/**
* Sorts bodies along the X axis.
* @method sortAxisListX
* @param {Array} a
* @return {Array}
*/
SAPBroadphase.sortAxisListX = function(a){
for(var i=1,l=a.length;i<l;i++) {
var v = a[i];
for(var j=i - 1;j>=0;j--) {
if(a[j].aabb.lowerBound[0] <= v.aabb.lowerBound[0])
break;
a[j+1] = a[j];
}
a[j+1] = v;
}
return a;
};
/**
* Sorts bodies along the Y axis.
* @method sortAxisListY
* @param {Array} a
* @return {Array}
*/
SAPBroadphase.sortAxisListY = function(a){
for(var i=1,l=a.length;i<l;i++) {
var v = a[i];
for(var j=i - 1;j>=0;j--) {
if(a[j].aabb.lowerBound[1] <= v.aabb.lowerBound[1])
break;
a[j+1] = a[j];
}
a[j+1] = v;
}
return a;
};
var preliminaryList = { keys:[] };
/**
* Get the colliding pairs
* @method getCollisionPairs
* @param {World} world
* @return {Array}
*/
SAPBroadphase.prototype.getCollisionPairs = function(world){
var bodiesX = this.axisListX,
bodiesY = this.axisListY,
result = this.result,
axisIndex = this.axisIndex,
i,j;
result.length = 0;
// Update all AABBs if needed
for(i=0; i!==bodiesX.length; i++){
var b = bodiesX[i];
if(b.aabbNeedsUpdate) b.updateAABB();
}
// Sort the lists
SAPBroadphase.sortAxisListX(bodiesX);
SAPBroadphase.sortAxisListY(bodiesY);
// Look through the X list
for(i=0, N=bodiesX.length; i!==N; i++){
var bi = bodiesX[i];
for(j=i+1; j<N; j++){
var bj = bodiesX[j];
// Bounds overlap?
if(!SAPBroadphase.checkBounds(bi,bj,0))
break;
// add pair to preliminary list
if(Broadphase.canCollide(bi,bj)){
var key = bi.id < bj.id ? bi.id+' '+bj.id : bj.id+' '+bi.id;
preliminaryList[key] = true;
preliminaryList.keys.push(key);
}
}
}
// Look through the Y list
for(i=0, N=bodiesY.length; i!==N; i++){
var bi = bodiesY[i];
for(j=i+1; j<N; j++){
var bj = bodiesY[j];
if(!SAPBroadphase.checkBounds(bi,bj,1))
break;
// If in preliminary list, add to final result
if(Broadphase.canCollide(bi,bj)){
var key = bi.id < bj.id ? bi.id+' '+bj.id : bj.id+' '+bi.id;
if(preliminaryList[key] && Broadphase.boundingRadiusCheck(bi,bj))
result.push(bi,bj);
}
}
}
// Empty prel list
var keys = preliminaryList.keys;
for(i=0, N=keys.length; i!==N; i++){
delete preliminaryList[keys[i]];
}
keys.length = 0;
return result;
};
/**
* Check if the bounds of two bodies overlap, along the given SAP axis.
* @static
* @method checkBounds
* @param {Body} bi
* @param {Body} bj
* @param {Number} axisIndex
* @return {Boolean}
*/
SAPBroadphase.checkBounds = function(bi,bj,axisIndex){
/*
var biPos = bi.position[axisIndex],
ri = bi.boundingRadius,
bjPos = bj.position[axisIndex],
rj = bj.boundingRadius,
boundA1 = biPos-ri,
boundA2 = biPos+ri,
boundB1 = bjPos-rj,
boundB2 = bjPos+rj;
return boundB1 < boundA2;
*/
return bj.aabb.lowerBound[axisIndex] < bi.aabb.upperBound[axisIndex];
};
},{"../collision/Broadphase":10,"../math/vec2":33,"../shapes/Circle":38,"../shapes/Particle":42,"../shapes/Plane":43,"../shapes/Shape":45,"../utils/Utils":50}],16:[function(require,module,exports){
module.exports = Constraint;
/**
* Base constraint class.
*
* @class Constraint
* @constructor
* @author schteppe
* @param {Body} bodyA
* @param {Body} bodyB
*/
function Constraint(bodyA,bodyB,type){
this.type = type;
/**
* Equations to be solved in this constraint
* @property equations
* @type {Array}
*/
this.equations = [];
/**
* First body participating in the constraint.
* @property bodyA
* @type {Body}
*/
this.bodyA = bodyA;
/**
* Second body participating in the constraint.
* @property bodyB
* @type {Body}
*/
this.bodyB = bodyB;
if(bodyA) bodyA.wakeUp();
if(bodyB) bodyB.wakeUp();
};
/**
* To be implemented by subclasses. Should update the internal constraint parameters.
* @method update
*/
/*Constraint.prototype.update = function(){
throw new Error("method update() not implmemented in this Constraint subclass!");
};*/
Constraint.DISTANCE = 1;
Constraint.GEAR = 2;
Constraint.LOCK = 3;
Constraint.PRISMATIC = 4;
Constraint.REVOLUTE = 5;
},{}],17:[function(require,module,exports){
var Constraint = require('./Constraint')
, Equation = require('../equations/Equation')
, vec2 = require('../math/vec2')
module.exports = DistanceConstraint;
/**
* Constraint that tries to keep the distance between two bodies constant.
*
* @class DistanceConstraint
* @constructor
* @author schteppe
* @param {Body} bodyA
* @param {Body} bodyB
* @param {number} dist The distance to keep between the bodies.
* @param {number} maxForce
* @extends {Constraint}
*/
function DistanceConstraint(bodyA,bodyB,distance,maxForce){
Constraint.call(this,bodyA,bodyB,Constraint.DISTANCE);
/**
* The distance to keep.
* @property distance
* @type {Number}
*/
this.distance = distance;
if(typeof(maxForce)==="undefined" )
maxForce = Number.MAX_VALUE;
var normal = new Equation(bodyA,bodyB,-maxForce,maxForce); // Just in the normal direction
this.equations = [ normal ];
var r = vec2.create();
normal.computeGq = function(){
vec2.sub(r, bodyB.position, bodyA.position);
return vec2.length(r)-distance;
};
// Make the contact constraint bilateral
this.setMaxForce(maxForce);
}
DistanceConstraint.prototype = new Constraint();
/**
* Update the constraint equations. Should be done if any of the bodies changed position, before solving.
* @method update
*/
var n = vec2.create();
DistanceConstraint.prototype.update = function(){
var normal = this.equations[0],
bodyA = this.bodyA,
bodyB = this.bodyB,
distance = this.distance,
G = normal.G;
vec2.sub(n, bodyB.position, bodyA.position);
vec2.normalize(n,n);
G[0] = -n[0];
G[1] = -n[1];
G[3] = n[0];
G[4] = n[1];
};
/**
* Set the max force to be used
* @method setMaxForce
* @param {Number} f
*/
DistanceConstraint.prototype.setMaxForce = function(f){
var normal = this.equations[0];
normal.minForce = -f;
normal.maxForce = f;
};
/**
* Get the max force
* @method getMaxForce
* @return {Number}
*/
DistanceConstraint.prototype.getMaxForce = function(f){
var normal = this.equations[0];
return normal.maxForce;
};
},{"../equations/Equation":24,"../math/vec2":33,"./Constraint":16}],18:[function(require,module,exports){
var Constraint = require('./Constraint')
, Equation = require('../equations/Equation')
, AngleLockEquation = require('../equations/AngleLockEquation')
, vec2 = require('../math/vec2')
module.exports = GearConstraint;
/**
* Connects two bodies at given offset points, letting them rotate relative to each other around this point.
* @class GearConstraint
* @constructor
* @author schteppe
* @param {Body} bodyA
* @param {Body} bodyB
* @param {Number} maxForce The maximum force that should be applied to constrain the bodies.
* @extends {Constraint}
* @todo Ability to specify world points
*/
function GearConstraint(bodyA, bodyB, options){
Constraint.call(this,bodyA,bodyB,Constraint.GEAR);
// Equations to be fed to the solver
var eqs = this.equations = [
new AngleLockEquation(bodyA,bodyB,options),
];
/**
* The relative angle
* @property angle
* @type {Number}
*/
this.angle = typeof(options.angle) == "number" ? options.angle : 0;
/**
* The gear ratio
* @property ratio
* @type {Number}
*/
this.ratio = typeof(options.ratio) == "number" ? options.ratio : 1;
}
GearConstraint.prototype = new Constraint();
GearConstraint.prototype.update = function(){
var eq = this.equations[0];
if(eq.ratio != this.ratio)
eq.setRatio(this.ratio);
eq.angle = this.angle;
};
},{"../equations/AngleLockEquation":22,"../equations/Equation":24,"../math/vec2":33,"./Constraint":16}],19:[function(require,module,exports){
var Constraint = require('./Constraint')
, vec2 = require('../math/vec2')
, Equation = require('../equations/Equation')
module.exports = LockConstraint;
/**
* Locks the relative position between two bodies.
*
* @class LockConstraint
* @constructor
* @author schteppe
* @param {Body} bodyA
* @param {Body} bodyB
* @param {Object} [options]
* @param {Array} [options.localOffsetB] The offset of bodyB in bodyA's frame.
* @param {number} [options.localAngleB] The angle of bodyB in bodyA's frame.
* @param {number} [options.maxForce]
* @extends {Constraint}
*/
function LockConstraint(bodyA,bodyB,options){
Constraint.call(this,bodyA,bodyB,Constraint.LOCK);
var maxForce = ( typeof(options.maxForce)=="undefined" ? Number.MAX_VALUE : options.maxForce );
var localOffsetB = options.localOffsetB || vec2.fromValues(0,0);
localOffsetB = vec2.fromValues(localOffsetB[0],localOffsetB[1]);
var localAngleB = options.localAngleB || 0;
// Use 3 equations:
// gx = (xj - xi - l) * xhat = 0
// gy = (xj - xi - l) * yhat = 0
// gr = (xi - xj + r) * that = 0
//
// ...where:
// l is the localOffsetB vector rotated to world in bodyA frame
// r is the same vector but reversed and rotated from bodyB frame
// xhat, yhat are world axis vectors
// that is the tangent of r
//
// For the first two constraints, we get
// G*W = (vj - vi - ldot ) * xhat
// = (vj - vi - wi x l) * xhat
//
// Since (wi x l) * xhat = (l x xhat) * wi, we get
// G*W = [ -1 0 (-l x xhat) 1 0 0] * [vi wi vj wj]
//
// The last constraint gives
// GW = (vi - vj + wj x r) * that
// = [ that 0 -that (r x t) ]
var x = new Equation(bodyA,bodyB,-maxForce,maxForce),
y = new Equation(bodyA,bodyB,-maxForce,maxForce),
rot = new Equation(bodyA,bodyB,-maxForce,maxForce);
var l = vec2.create(),
g = vec2.create();
x.computeGq = function(){
vec2.rotate(l,localOffsetB,bodyA.angle);
vec2.sub(g,bodyB.position,bodyA.position);
vec2.sub(g,g,l);
return g[0];
}
y.computeGq = function(){
vec2.rotate(l,localOffsetB,bodyA.angle);
vec2.sub(g,bodyB.position,bodyA.position);
vec2.sub(g,g,l);
return g[1];
};
var r = vec2.create(),
t = vec2.create();
rot.computeGq = function(){
vec2.rotate(r,localOffsetB,bodyB.angle - localAngleB);
vec2.scale(r,r,-1);
vec2.sub(g,bodyA.position,bodyB.position);
vec2.add(g,g,r);
vec2.rotate(t,r,-Math.PI/2);
vec2.normalize(t,t);
return vec2.dot(g,t);
};
this.localOffsetB = localOffsetB;
this.localAngleB = localAngleB;
this.maxForce = maxForce;
var eqs = this.equations = [ x, y, rot ];
}
LockConstraint.prototype = new Constraint();
var l = vec2.create();
var r = vec2.create();
var t = vec2.create();
var xAxis = vec2.fromValues(1,0);
var yAxis = vec2.fromValues(0,1);
LockConstraint.prototype.update = function(){
var x = this.equations[0],
y = this.equations[1],
rot = this.equations[2],
bodyA = this.bodyA,
bodyB = this.bodyB;
vec2.rotate(l,this.localOffsetB,bodyA.angle);
vec2.rotate(r,this.localOffsetB,bodyB.angle - this.localAngleB);
vec2.scale(r,r,-1);
vec2.rotate(t,r,Math.PI/2);
vec2.normalize(t,t);
x.G[0] = -1;
x.G[1] = 0;
x.G[2] = -vec2.crossLength(l,xAxis);
x.G[3] = 1;
y.G[0] = 0;
y.G[1] = -1;
y.G[2] = -vec2.crossLength(l,yAxis);
y.G[4] = 1;
rot.G[0] = -t[0];
rot.G[1] = -t[1];
rot.G[3] = t[0];
rot.G[4] = t[1];
rot.G[5] = vec2.crossLength(r,t);
};
},{"../equations/Equation":24,"../math/vec2":33,"./Constraint":16}],20:[function(require,module,exports){
var Constraint = require('./Constraint')
, ContactEquation = require('../equations/ContactEquation')
, Equation = require('../equations/Equation')
, vec2 = require('../math/vec2')
, RotationalLockEquation = require('../equations/RotationalLockEquation')
module.exports = PrismaticConstraint;
/**
* Constraint that only allows bodies to move along a line, relative to each other. See <a href="http://www.iforce2d.net/b2dtut/joints-prismatic">this tutorial</a>.
*
* @class PrismaticConstraint
* @constructor
* @extends {Constraint}
* @author schteppe
* @param {Body} bodyA
* @param {Body} bodyB
* @param {Object} options
* @param {Number} options.maxForce Max force to be applied by the constraint
* @param {Array} options.localAnchorA Body A's anchor point, defined in its own local frame.
* @param {Array} options.localAnchorB Body B's anchor point, defined in its own local frame.
* @param {Array} options.localAxisA An axis, defined in body A frame, that body B's anchor point may slide along.
* @param {Boolean} options.disableRotationalLock If set to true, bodyB will be free to rotate around its anchor point.
*/
function PrismaticConstraint(bodyA,bodyB,options){
options = options || {};
Constraint.call(this,bodyA,bodyB,Constraint.PRISMATIC);
// Get anchors
var localAnchorA = vec2.fromValues(0,0),
localAxisA = vec2.fromValues(1,0),
localAnchorB = vec2.fromValues(0,0);
if(options.localAnchorA) vec2.copy(localAnchorA, options.localAnchorA);
if(options.localAxisA) vec2.copy(localAxisA, options.localAxisA);
if(options.localAnchorB) vec2.copy(localAnchorB, options.localAnchorB);
/**
* @property localAnchorA
* @type {Array}
*/
this.localAnchorA = localAnchorA;
/**
* @property localAnchorB
* @type {Array}
*/
this.localAnchorB = localAnchorB;
/**
* @property localAxisA
* @type {Array}
*/
this.localAxisA = localAxisA;
/*
The constraint violation for the common axis point is
g = ( xj + rj - xi - ri ) * t := gg*t
where r are body-local anchor points, and t is a tangent to the constraint axis defined in body i frame.
gdot = ( vj + wj x rj - vi - wi x ri ) * t + ( xj + rj - xi - ri ) * ( wi x t )
Note the use of the chain rule. Now we identify the jacobian
G*W = [ -t -ri x t + t x gg t rj x t ] * [vi wi vj wj]
The rotational part is just a rotation lock.
*/
var maxForce = this.maxForce = typeof(options.maxForce)!="undefined" ? options.maxForce : Number.MAX_VALUE;
// Translational part
var trans = new Equation(bodyA,bodyB,-maxForce,maxForce);
var ri = new vec2.create(),
rj = new vec2.create(),
gg = new vec2.create(),
t = new vec2.create();
trans.computeGq = function(){
// g = ( xj + rj - xi - ri ) * t
return vec2.dot(gg,t);
};
trans.update = function(){
var G = this.G,
xi = bodyA.position,
xj = bodyB.position;
vec2.rotate(ri,localAnchorA,bodyA.angle);
vec2.rotate(rj,localAnchorB,bodyB.angle);
vec2.add(gg,xj,rj);
vec2.sub(gg,gg,xi);
vec2.sub(gg,gg,ri);
vec2.rotate(t,localAxisA,bodyA.angle+Math.PI/2);
G[0] = -t[0];
G[1] = -t[1];
G[2] = -vec2.crossLength(ri,t) + vec2.crossLength(t,gg);
G[3] = t[0];
G[4] = t[1];
G[5] = vec2.crossLength(rj,t);
}
this.equations.push(trans);
// Rotational part
if(!options.disableRotationalLock){
var rot = new RotationalLockEquation(bodyA,bodyB,-maxForce,maxForce);
this.equations.push(rot);
}
/**
* The position of anchor A relative to anchor B, along the constraint axis.
* @property position
* @type {Number}
*/
this.position = 0;
this.velocity = 0;
/**
* Set to true to enable lower limit.
* @property lowerLimitEnabled
* @type {Boolean}
*/
this.lowerLimitEnabled = false;
/**
* Set to true to enable upper limit.
* @property upperLimitEnabled
* @type {Boolean}
*/
this.upperLimitEnabled = false;
/**
* Lower constraint limit. The constraint position is forced to be larger than this value.
* @property lowerLimit
* @type {Number}
*/
this.lowerLimit = 0;
/**
* Upper constraint limit. The constraint position is forced to be smaller than this value.
* @property upperLimit
* @type {Number}
*/
this.upperLimit = 1;
// Equations used for limits
this.upperLimitEquation = new ContactEquation(bodyA,bodyB);
this.lowerLimitEquation = new ContactEquation(bodyA,bodyB);
// Set max/min forces
this.upperLimitEquation.minForce = this.lowerLimitEquation.minForce = 0;
this.upperLimitEquation.maxForce = this.lowerLimitEquation.maxForce = maxForce;
/**
* Equation used for the motor.
* @property motorEquation
* @type {Equation}
*/
this.motorEquation = new Equation(bodyA,bodyB);
/**
* The current motor state. Enable or disable the motor using .enableMotor
* @property motorEnabled
* @type {Boolean}
*/
this.motorEnabled = false;
/**
* Set the target speed for the motor.
* @property motorSpeed
* @type {Number}
*/
this.motorSpeed = 0;
var that = this;
var motorEquation = this.motorEquation;
var old = motorEquation.computeGW;
motorEquation.computeGq = function(){ return 0; };
motorEquation.computeGW = function(){
var G = this.G,
bi = this.bi,
bj = this.bj,
vi = bi.velocity,
vj = bj.velocity,
wi = bi.angularVelocity,
wj = bj.angularVelocity;
return this.transformedGmult(G,vi,wi,vj,wj) + that.motorSpeed;
};
}
PrismaticConstraint.prototype = new Constraint();
var worldAxisA = vec2.create(),
worldAnchorA = vec2.create(),
worldAnchorB = vec2.create(),
orientedAnchorA = vec2.create(),
orientedAnchorB = vec2.create(),
tmp = vec2.create();
/**
* Update the constraint equations. Should be done if any of the bodies changed position, before solving.
* @method update
*/
PrismaticConstraint.prototype.update = function(){
var eqs = this.equations,
trans = eqs[0],
upperLimit = this.upperLimit,
lowerLimit = this.lowerLimit,
upperLimitEquation = this.upperLimitEquation,
lowerLimitEquation = this.lowerLimitEquation,
bodyA = this.bodyA,
bodyB = this.bodyB,
localAxisA = this.localAxisA,
localAnchorA = this.localAnchorA,
localAnchorB = this.localAnchorB;
trans.update();
// Transform local things to world
vec2.rotate(worldAxisA, localAxisA, bodyA.angle);
vec2.rotate(orientedAnchorA, localAnchorA, bodyA.angle);
vec2.add(worldAnchorA, orientedAnchorA, bodyA.position);
vec2.rotate(orientedAnchorB, localAnchorB, bodyB.angle);
vec2.add(worldAnchorB, orientedAnchorB, bodyB.position);
var relPosition = this.position = vec2.dot(worldAnchorB,worldAxisA) - vec2.dot(worldAnchorA,worldAxisA);
// Motor
if(this.motorEnabled){
// G = [ a a x ri -a -a x rj ]
var G = this.motorEquation.G;
G[0] = worldAxisA[0];
G[1] = worldAxisA[1];
G[2] = vec2.crossLength(worldAxisA,orientedAnchorB);
G[3] = -worldAxisA[0];
G[4] = -worldAxisA[1];
G[5] = -vec2.crossLength(worldAxisA,orientedAnchorA);
}
/*
Limits strategy:
Add contact equation, with normal along the constraint axis.
min/maxForce is set so the constraint is repulsive in the correct direction.
Some offset is added to either equation.ri or .rj to get the correct upper/lower limit.
^
|
upperLimit x
| ------
anchorB x<---| B |
| | |
------ | ------
| | |
| A |-->x anchorA
------ |
x lowerLimit
|
axis
*/
if(this.upperLimitEnabled && relPosition > upperLimit){
// Update contact constraint normal, etc
vec2.scale(upperLimitEquation.ni, worldAxisA, -1);
vec2.sub(upperLimitEquation.ri, worldAnchorA, bodyA.position);
vec2.sub(upperLimitEquation.rj, worldAnchorB, bodyB.position);
vec2.scale(tmp,worldAxisA,upperLimit);
vec2.add(upperLimitEquation.ri,upperLimitEquation.ri,tmp);
if(eqs.indexOf(upperLimitEquation)==-1)
eqs.push(upperLimitEquation);
} else {
var idx = eqs.indexOf(upperLimitEquation);
if(idx != -1) eqs.splice(idx,1);
}
if(this.lowerLimitEnabled && relPosition < lowerLimit){
// Update contact constraint normal, etc
vec2.scale(lowerLimitEquation.ni, worldAxisA, 1);
vec2.sub(lowerLimitEquation.ri, worldAnchorA, bodyA.position);
vec2.sub(lowerLimitEquation.rj, worldAnchorB, bodyB.position);
vec2.scale(tmp,worldAxisA,lowerLimit);
vec2.sub(lowerLimitEquation.rj,lowerLimitEquation.rj,tmp);
if(eqs.indexOf(lowerLimitEquation)==-1)
eqs.push(lowerLimitEquation);
} else {
var idx = eqs.indexOf(lowerLimitEquation);
if(idx != -1) eqs.splice(idx,1);
}
};
/**
* Enable the motor
* @method enableMotor
*/
PrismaticConstraint.prototype.enableMotor = function(){
if(this.motorEnabled) return;
this.equations.push(this.motorEquation);
this.motorEnabled = true;
};
/**
* Disable the rotational motor
* @method disableMotor
*/
PrismaticConstraint.prototype.disableMotor = function(){
if(!this.motorEnabled) return;
var i = this.equations.indexOf(this.motorEquation);
this.equations.splice(i,1);
this.motorEnabled = false;
};
},{"../equations/ContactEquation":23,"../equations/Equation":24,"../equations/RotationalLockEquation":26,"../math/vec2":33,"./Constraint":16}],21:[function(require,module,exports){
var Constraint = require('./Constraint')
, Equation = require('../equations/Equation')
, RotationalVelocityEquation = require('../equations/RotationalVelocityEquation')
, RotationalLockEquation = require('../equations/RotationalLockEquation')
, vec2 = require('../math/vec2')
module.exports = RevoluteConstraint;
var worldPivotA = vec2.create(),
worldPivotB = vec2.create(),
xAxis = vec2.fromValues(1,0),
yAxis = vec2.fromValues(0,1),
g = vec2.create();
/**
* Connects two bodies at given offset points, letting them rotate relative to each other around this point.
* @class RevoluteConstraint
* @constructor
* @author schteppe
* @param {Body} bodyA
* @param {Float32Array} pivotA The point relative to the center of mass of bodyA which bodyA is constrained to.
* @param {Body} bodyB Body that will be constrained in a similar way to the same point as bodyA. We will therefore get sort of a link between bodyA and bodyB. If not specified, bodyA will be constrained to a static point.
* @param {Float32Array} pivotB See pivotA.
* @param {Number} maxForce The maximum force that should be applied to constrain the bodies.
* @extends {Constraint}
* @todo Ability to specify world points
*/
function RevoluteConstraint(bodyA, pivotA, bodyB, pivotB, maxForce){
Constraint.call(this,bodyA,bodyB,Constraint.REVOLUTE);
maxForce = this.maxForce = typeof(maxForce)!="undefined" ? maxForce : Number.MAX_VALUE;
this.pivotA = pivotA;
this.pivotB = pivotB;
// Equations to be fed to the solver
var eqs = this.equations = [
new Equation(bodyA,bodyB,-maxForce,maxForce),
new Equation(bodyA,bodyB,-maxForce,maxForce),
];
var x = eqs[0];
var y = eqs[1];
x.computeGq = function(){
vec2.rotate(worldPivotA, pivotA, bodyA.angle);
vec2.rotate(worldPivotB, pivotB, bodyB.angle);
vec2.add(g, bodyB.position, worldPivotB);
vec2.sub(g, g, bodyA.position);
vec2.sub(g, g, worldPivotA);
return vec2.dot(g,xAxis);
};
y.computeGq = function(){
vec2.rotate(worldPivotA, pivotA, bodyA.angle);
vec2.rotate(worldPivotB, pivotB, bodyB.angle);
vec2.add(g, bodyB.position, worldPivotB);
vec2.sub(g, g, bodyA.position);
vec2.sub(g, g, worldPivotA);
return vec2.dot(g,yAxis);
};
y.minForce = x.minForce = -maxForce;
y.maxForce = x.maxForce = maxForce;
this.motorEquation = new RotationalVelocityEquation(bodyA,bodyB);
this.motorEnabled = false;
/**
* The constraint position
* @property angle
* @type {Number}
*/
this.angle = 0;
/**
* Set to true to enable lower limit
* @property lowerLimitEnabled
* @type {Boolean}
*/
this.lowerLimitEnabled = false;
/**
* Set to true to enable upper limit
* @property upperLimitEnabled
* @type {Boolean}
*/
this.upperLimitEnabled = false;
/**
* The lower limit on the constraint angle.
* @property lowerLimit
* @type {Boolean}
*/
this.lowerLimit = 0;
/**
* The upper limit on the constraint angle.
* @property upperLimit
* @type {Boolean}
*/
this.upperLimit = 0;
this.upperLimitEquation = new RotationalLockEquation(bodyA,bodyB);
this.lowerLimitEquation = new RotationalLockEquation(bodyA,bodyB);
this.upperLimitEquation.minForce = 0;
this.lowerLimitEquation.maxForce = 0;
}
RevoluteConstraint.prototype = new Constraint();
RevoluteConstraint.prototype.update = function(){
var bodyA = this.bodyA,
bodyB = this.bodyB,
pivotA = this.pivotA,
pivotB = this.pivotB,
eqs = this.equations,
normal = eqs[0],
tangent= eqs[1],
x = eqs[0],
y = eqs[1],
upperLimit = this.upperLimit,
lowerLimit = this.lowerLimit,
upperLimitEquation = this.upperLimitEquation,
lowerLimitEquation = this.lowerLimitEquation;
var relAngle = this.angle = bodyB.angle - bodyA.angle;
if(this.upperLimitEnabled && relAngle > upperLimit){
upperLimitEquation.angle = upperLimit;
if(eqs.indexOf(upperLimitEquation)==-1)
eqs.push(upperLimitEquation);
} else {
var idx = eqs.indexOf(upperLimitEquation);
if(idx != -1) eqs.splice(idx,1);
}
if(this.lowerLimitEnabled && relAngle < lowerLimit){
lowerLimitEquation.angle = lowerLimit;
if(eqs.indexOf(lowerLimitEquation)==-1)
eqs.push(lowerLimitEquation);
} else {
var idx = eqs.indexOf(lowerLimitEquation);
if(idx != -1) eqs.splice(idx,1);
}
/*
The constraint violation is
g = xj + rj - xi - ri
...where xi and xj are the body positions and ri and rj world-oriented offset vectors. Differentiate:
gdot = vj + wj x rj - vi - wi x ri
We split this into x and y directions. (let x and y be unit vectors along the respective axes)
gdot * x = ( vj + wj x rj - vi - wi x ri ) * x
= ( vj*x + (wj x rj)*x -vi*x -(wi x ri)*x
= ( vj*x + (rj x x)*wj -vi*x -(ri x x)*wi
= [ -x -(ri x x) x (rj x x)] * [vi wi vj wj]
= G*W
...and similar for y. We have then identified the jacobian entries for x and y directions:
Gx = [ x (rj x x) -x -(ri x x)]
Gy = [ y (rj x y) -y -(ri x y)]
*/
vec2.rotate(worldPivotA, pivotA, bodyA.angle);
vec2.rotate(worldPivotB, pivotB, bodyB.angle);
// todo: these are a bit sparse. We could save some computations on making custom eq.computeGW functions, etc
x.G[0] = -1;
x.G[1] = 0;
x.G[2] = -vec2.crossLength(worldPivotA,xAxis);
x.G[3] = 1;
x.G[4] = 0;
x.G[5] = vec2.crossLength(worldPivotB,xAxis);
y.G[0] = 0;
y.G[1] = -1;
y.G[2] = -vec2.crossLength(worldPivotA,yAxis);
y.G[3] = 0;
y.G[4] = 1;
y.G[5] = vec2.crossLength(worldPivotB,yAxis);
};
/**
* Enable the rotational motor
* @method enableMotor
*/
RevoluteConstraint.prototype.enableMotor = function(){
if(this.motorEnabled) return;
this.equations.push(this.motorEquation);
this.motorEnabled = true;
};
/**
* Disable the rotational motor
* @method disableMotor
*/
RevoluteConstraint.prototype.disableMotor = function(){
if(!this.motorEnabled) return;
var i = this.equations.indexOf(this.motorEquation);
this.equations.splice(i,1);
this.motorEnabled = false;
};
/**
* Check if the motor is enabled.
* @method motorIsEnabled
* @return {Boolean}
*/
RevoluteConstraint.prototype.motorIsEnabled = function(){
return !!this.motorEnabled;
};
/**
* Set the speed of the rotational constraint motor
* @method setMotorSpeed
* @param {Number} speed
*/
RevoluteConstraint.prototype.setMotorSpeed = function(speed){
if(!this.motorEnabled) return;
var i = this.equations.indexOf(this.motorEquation);
this.equations[i].relativeVelocity = speed;
};
/**
* Get the speed of the rotational constraint motor
* @method getMotorSpeed
* @return {Number} The current speed, or false if the motor is not enabled.
*/
RevoluteConstraint.prototype.getMotorSpeed = function(){
if(!this.motorEnabled) return false;
return this.motorEquation.relativeVelocity;
};
},{"../equations/Equation":24,"../equations/RotationalLockEquation":26,"../equations/RotationalVelocityEquation":27,"../math/vec2":33,"./Constraint":16}],22:[function(require,module,exports){
var Equation = require("./Equation"),
vec2 = require('../math/vec2');
module.exports = AngleLockEquation;
/**
* Locks the relative angle between two bodies. The constraint tries to keep the dot product between two vectors, local in each body, to zero. The local angle in body i is a parameter.
*
* @class AngleLockEquation
* @constructor
* @extends Equation
* @param {Body} bi
* @param {Body} bj
* @param {Object} options
* @param {Number} options.angle Angle to add to the local vector in body i.
* @param {Number} options.ratio Gear ratio
*/
function AngleLockEquation(bi,bj,options){
options = options || {};
Equation.call(this,bi,bj,-Number.MAX_VALUE,Number.MAX_VALUE);
this.angle = options.angle || 0;
this.ratio = typeof(options.ratio)=="number" ? options.ratio : 1;
this.setRatio(this.ratio);
};
AngleLockEquation.prototype = new Equation();
AngleLockEquation.prototype.constructor = AngleLockEquation;
AngleLockEquation.prototype.computeGq = function(){
return this.ratio*this.bi.angle - this.bj.angle + this.angle;
};
AngleLockEquation.prototype.setRatio = function(ratio){
var G = this.G;
G[2] = ratio;
G[5] = -1;
this.ratio = ratio;
};
},{"../math/vec2":33,"./Equation":24}],23:[function(require,module,exports){
var Equation = require("./Equation"),
vec2 = require('../math/vec2'),
mat2 = require('../math/mat2');
module.exports = ContactEquation;
/**
* Non-penetration constraint equation. Tries to make the ri and rj vectors the same point.
*
* @class ContactEquation
* @constructor
* @extends Equation
* @param {Body} bi
* @param {Body} bj
*/
function ContactEquation(bi,bj){
Equation.call(this,bi,bj,0,Number.MAX_VALUE);
/**
* Vector from body i center of mass to the contact point.
* @property ri
* @type {Array}
*/
this.ri = vec2.create();
this.penetrationVec = vec2.create();
/**
* Vector from body j center of mass to the contact point.
* @property rj
* @type {Array}
*/
this.rj = vec2.create();
/**
* The normal vector, pointing out of body i
* @property ni
* @type {Array}
*/
this.ni = vec2.create();
/**
* The restitution to use. 0=no bounciness, 1=max bounciness.
* @property restitution
* @type {Number}
*/
this.restitution = 0;
/**
* Set to true if this is the first impact between the bodies (not persistant contact).
* @property firstImpact
* @type {Boolean}
*/
this.firstImpact = false;
/**
* The shape in body i that triggered this contact.
* @property shapeA
* @type {Shape}
*/
this.shapeA = null;
/**
* The shape in body j that triggered this contact.
* @property shapeB
* @type {Shape}
*/
this.shapeB = null;
};
ContactEquation.prototype = new Equation();
ContactEquation.prototype.constructor = ContactEquation;
ContactEquation.prototype.computeB = function(a,b,h){
var bi = this.bi,
bj = this.bj,
ri = this.ri,
rj = this.rj,
xi = bi.position,
xj = bj.position;
var penetrationVec = this.penetrationVec,
n = this.ni,
G = this.G;
// Caluclate cross products
var rixn = vec2.crossLength(ri,n),
rjxn = vec2.crossLength(rj,n);
// G = [-n -rixn n rjxn]
G[0] = -n[0];
G[1] = -n[1];
G[2] = -rixn;
G[3] = n[0];
G[4] = n[1];
G[5] = rjxn;
// Calculate q = xj+rj -(xi+ri) i.e. the penetration vector
vec2.add(penetrationVec,xj,rj);
vec2.sub(penetrationVec,penetrationVec,xi);
vec2.sub(penetrationVec,penetrationVec,ri);
// Compute iteration
var GW, Gq;
if(this.firstImpact && this.restitution !== 0){
Gq = 0;
GW = (1/b)*(1+this.restitution) * this.computeGW();
} else {
Gq = vec2.dot(n,penetrationVec);
GW = this.computeGW();
}
var GiMf = this.computeGiMf();
var B = - Gq * a - GW * b - h*GiMf;
return B;
};
},{"../math/mat2":31,"../math/vec2":33,"./Equation":24}],24:[function(require,module,exports){
module.exports = Equation;
var vec2 = require('../math/vec2'),
mat2 = require('../math/mat2'),
Utils = require('../utils/Utils');
/**
* Base class for constraint equations.
* @class Equation
* @constructor
* @param {Body} bi First body participating in the equation
* @param {Body} bj Second body participating in the equation
* @param {number} minForce Minimum force to apply. Default: -1e6
* @param {number} maxForce Maximum force to apply. Default: 1e6
*/
function Equation(bi,bj,minForce,maxForce){
/**
* Minimum force to apply when solving
* @property minForce
* @type {Number}
*/
this.minForce = typeof(minForce)=="undefined" ? -1e6 : minForce;
/**
* Max force to apply when solving
* @property maxForce
* @type {Number}
*/
this.maxForce = typeof(maxForce)=="undefined" ? 1e6 : maxForce;
/**
* First body participating in the constraint
* @property bi
* @type {Body}
*/
this.bi = bi;
/**
* Second body participating in the constraint
* @property bj
* @type {Body}
*/
this.bj = bj;
/**
* The stiffness of this equation. Typically chosen to a large number (~1e7), but can be chosen somewhat freely to get a stable simulation.
* @property stiffness
* @type {Number}
*/
this.stiffness = 1e6;
/**
* The number of time steps needed to stabilize the constraint equation. Typically between 3 and 5 time steps.
* @property relaxation
* @type {Number}
*/
this.relaxation = 4;
/**
* The Jacobian entry of this equation. 6 numbers, 3 per body (x,y,angle).
* @property G
* @type {Array}
*/
this.G = new Utils.ARRAY_TYPE(6);
for(var i=0; i<6; i++) this.G[i]=0;
// Constraint frames for body i and j
/*
this.xi = vec2.create();
this.xj = vec2.create();
this.ai = 0;
this.aj = 0;
*/
this.offset = 0;
this.a = 0;
this.b = 0;
this.eps = 0;
this.h = 0;
this.updateSpookParams(1/60);
/**
* The resulting constraint multiplier from the last solve. This is mostly equivalent to the force produced by the constraint.
* @property multiplier
* @type {Number}
*/
this.multiplier = 0;
/**
* Relative velocity.
* @property {Number} relativeVelocity
*/
this.relativeVelocity = 0;
/**
* Whether this equation is enabled or not. If true, it will be added to the solver.
* @property {Boolean} enabled
*/
this.enabled = true;
};
Equation.prototype.constructor = Equation;
/**
* Update SPOOK parameters .a, .b and .eps according to the given time step. See equations 9, 10 and 11 in the <a href="http://www8.cs.umu.se/kurser/5DV058/VT09/lectures/spooknotes.pdf">SPOOK notes</a>.
* @method updateSpookParams
* @param {number} timeStep
*/
Equation.prototype.updateSpookParams = function(timeStep){
var k = this.stiffness,
d = this.relaxation,
h = timeStep;
this.a = 4.0 / (h * (1 + 4 * d));
this.b = (4.0 * d) / (1 + 4 * d);
this.eps = 4.0 / (h * h * k * (1 + 4 * d));
this.h = timeStep;
};
function Gmult(G,vi,wi,vj,wj){
return G[0] * vi[0] +
G[1] * vi[1] +
G[2] * wi +
G[3] * vj[0] +
G[4] * vj[1] +
G[5] * wj;
}
/**
* Computes the RHS of the SPOOK equation
* @method computeB
* @return {Number}
*/
Equation.prototype.computeB = function(a,b,h){
var GW = this.computeGW();
var Gq = this.computeGq();
var GiMf = this.computeGiMf();
return - Gq * a - GW * b - GiMf*h;
};
/**
* Computes G*q, where q are the generalized body coordinates
* @method computeGq
* @return {Number}
*/
var qi = vec2.create(),
qj = vec2.create();
Equation.prototype.computeGq = function(){
var G = this.G,
bi = this.bi,
bj = this.bj,
xi = bi.position,
xj = bj.position,
ai = bi.angle,
aj = bj.angle;
// Transform to the given body frames
/*
vec2.rotate(qi,this.xi,ai);
vec2.rotate(qj,this.xj,aj);
vec2.add(qi,qi,xi);
vec2.add(qj,qj,xj);
*/
return Gmult(G, qi, ai, qj, aj) + this.offset;
};
var tmp_i = vec2.create(),
tmp_j = vec2.create();
Equation.prototype.transformedGmult = function(G,vi,wi,vj,wj){
// Transform velocity to the given body frames
// v_p = v + w x r
/*
vec2.rotate(tmp_i,this.xi,Math.PI / 2 + this.bi.angle); // Get r, and rotate 90 degrees. We get the "x r" part
vec2.rotate(tmp_j,this.xj,Math.PI / 2 + this.bj.angle);
vec2.scale(tmp_i,tmp_i,wi); // Temp vectors are now (w x r)
vec2.scale(tmp_j,tmp_j,wj);
vec2.add(tmp_i,tmp_i,vi);
vec2.add(tmp_j,tmp_j,vj);
*/
// Note: angular velocity is same
return Gmult(G,vi,wi,vj,wj);
};
/**
* Computes G*W, where W are the body velocities
* @method computeGW
* @return {Number}
*/
Equation.prototype.computeGW = function(){
var G = this.G,
bi = this.bi,
bj = this.bj,
vi = bi.velocity,
vj = bj.velocity,
wi = bi.angularVelocity,
wj = bj.angularVelocity;
return this.transformedGmult(G,vi,wi,vj,wj) + this.relativeVelocity;
};
/**
* Computes G*Wlambda, where W are the body velocities
* @method computeGWlambda
* @return {Number}
*/
Equation.prototype.computeGWlambda = function(){
var G = this.G,
bi = this.bi,
bj = this.bj,
vi = bi.vlambda,
vj = bj.vlambda,
wi = bi.wlambda,
wj = bj.wlambda;
return Gmult(G,vi,wi,vj,wj);
};
/**
* Computes G*inv(M)*f, where M is the mass matrix with diagonal blocks for each body, and f are the forces on the bodies.
* @method computeGiMf
* @return {Number}
*/
var iMfi = vec2.create(),
iMfj = vec2.create();
Equation.prototype.computeGiMf = function(){
var bi = this.bi,
bj = this.bj,
fi = bi.force,
ti = bi.angularForce,
fj = bj.force,
tj = bj.angularForce,
invMassi = bi.invMass,
invMassj = bj.invMass,
invIi = bi.invInertia,
invIj = bj.invInertia,
G = this.G;
vec2.scale(iMfi, fi,invMassi);
vec2.scale(iMfj, fj,invMassj);
return this.transformedGmult(G,iMfi,ti*invIi,iMfj,tj*invIj);
};
/**
* Computes G*inv(M)*G'
* @method computeGiMGt
* @return {Number}
*/
Equation.prototype.computeGiMGt = function(){
var bi = this.bi,
bj = this.bj,
invMassi = bi.invMass,
invMassj = bj.invMass,
invIi = bi.invInertia,
invIj = bj.invInertia,
G = this.G;
return G[0] * G[0] * invMassi +
G[1] * G[1] * invMassi +
G[2] * G[2] * invIi +
G[3] * G[3] * invMassj +
G[4] * G[4] * invMassj +
G[5] * G[5] * invIj;
};
var addToWlambda_temp = vec2.create(),
addToWlambda_Gi = vec2.create(),
addToWlambda_Gj = vec2.create(),
addToWlambda_ri = vec2.create(),
addToWlambda_rj = vec2.create(),
addToWlambda_Mdiag = vec2.create();
var tmpMat1 = mat2.create(),
tmpMat2 = mat2.create();
/**
* Add constraint velocity to the bodies.
* @method addToWlambda
* @param {Number} deltalambda
*/
Equation.prototype.addToWlambda = function(deltalambda){
var bi = this.bi,
bj = this.bj,
temp = addToWlambda_temp,
imMat1 = tmpMat1,
imMat2 = tmpMat2,
Gi = addToWlambda_Gi,
Gj = addToWlambda_Gj,
ri = addToWlambda_ri,
rj = addToWlambda_rj,
Mdiag = addToWlambda_Mdiag,
G = this.G;
Gi[0] = G[0];
Gi[1] = G[1];
Gj[0] = G[3];
Gj[1] = G[4];
/*
mat2.identity(imMat1);
mat2.identity(imMat2);
imMat1[0] = imMat1[3] = bi.invMass;
imMat2[0] = imMat2[3] = bj.invMass;
*/
/*
vec2.rotate(ri,this.xi,bi.angle);
vec2.rotate(rj,this.xj,bj.angle);
*/
// Add to linear velocity
// v_lambda += inv(M) * delta_lamba * G
//vec2.set(Mdiag,bi.invMass,bi.invMass);
//vec2.scale(temp,vec2.transformMat2(temp,Gi,imMat1),deltalambda);
vec2.scale(temp,Gi,bi.invMass*deltalambda);
vec2.add( bi.vlambda, bi.vlambda, temp);
// This impulse is in the offset frame
// Also add contribution to angular
//bi.wlambda -= vec2.crossLength(temp,ri);
//vec2.set(Mdiag,bj.invMass,bj.invMass);
//vec2.scale(temp,vec2.transformMat2(temp,Gj,imMat2),deltalambda);
vec2.scale(temp,Gj,bj.invMass*deltalambda);
vec2.add( bj.vlambda, bj.vlambda, temp);
//bj.wlambda -= vec2.crossLength(temp,rj);
// Add to angular velocity
bi.wlambda += bi.invInertia * G[2] * deltalambda;
bj.wlambda += bj.invInertia * G[5] * deltalambda;
};
function massMatVecMultiply(out, m, v) {
out[0] = v[0] * m;
out[1] = v[1] * m;
return out;
}
/**
* Compute the denominator part of the SPOOK equation: C = G*inv(M)*G' + eps
* @method computeInvC
* @param {Number} eps
* @return {Number}
*/
Equation.prototype.computeInvC = function(eps){
return 1.0 / (this.computeGiMGt() + eps);
};
},{"../math/mat2":31,"../math/vec2":33,"../utils/Utils":50}],25:[function(require,module,exports){
var mat2 = require('../math/mat2')
, vec2 = require('../math/vec2')
, Equation = require('./Equation')
, Utils = require('../utils/Utils')
module.exports = FrictionEquation;
/**
* Constrains the slipping in a contact along a tangent
*
* @class FrictionEquation
* @constructor
* @param {Body} bi
* @param {Body} bj
* @param {Number} slipForce
* @extends {Equation}
*/
function FrictionEquation(bi,bj,slipForce){
Equation.call(this,bi,bj,-slipForce,slipForce);
/**
* Relative vector from center of body i to the contact point, in world coords.
* @property ri
* @type {Float32Array}
*/
this.ri = vec2.create();
/**
* Relative vector from center of body j to the contact point, in world coords.
* @property rj
* @type {Float32Array}
*/
this.rj = vec2.create();
/**
* Tangent vector that the friction force will act along, in world coords.
* @property t
* @type {Float32Array}
*/
this.t = vec2.create();
/**
* A ContactEquation connected to this friction. The contact equation can be used to rescale the max force for the friction.
* @property contactEquation
* @type {ContactEquation}
*/
this.contactEquation = null;
/**
* The shape in body i that triggered this friction.
* @property shapeA
* @type {Shape}
* @todo Needed? The shape can be looked up via contactEquation.shapeA...
*/
this.shapeA = null;
/**
* The shape in body j that triggered this friction.
* @property shapeB
* @type {Shape}
* @todo Needed? The shape can be looked up via contactEquation.shapeB...
*/
this.shapeB = null;
/**
* The friction coefficient to use.
* @property frictionCoefficient
* @type {Number}
*/
this.frictionCoefficient = 0.3;
};
FrictionEquation.prototype = new Equation();
FrictionEquation.prototype.constructor = FrictionEquation;
/**
* Set the slipping condition for the constraint. The friction force cannot be
* larger than this value.
* @method setSlipForce
* @param {Number} slipForce
* @deprecated Use .frictionCoefficient instead
*/
FrictionEquation.prototype.setSlipForce = function(slipForce){
this.maxForce = slipForce;
this.minForce = -slipForce;
};
FrictionEquation.prototype.computeB = function(a,b,h){
var bi = this.bi,
bj = this.bj,
ri = this.ri,
rj = this.rj,
t = this.t,
G = this.G;
// G = [-t -rixt t rjxt]
// And remember, this is a pure velocity constraint, g is always zero!
G[0] = -t[0];
G[1] = -t[1];
G[2] = -vec2.crossLength(ri,t);
G[3] = t[0];
G[4] = t[1];
G[5] = vec2.crossLength(rj,t);
var GW = this.computeGW(),
GiMf = this.computeGiMf();
var B = /* - g * a */ - GW * b - h*GiMf;
return B;
};
},{"../math/mat2":31,"../math/vec2":33,"../utils/Utils":50,"./Equation":24}],26:[function(require,module,exports){
var Equation = require("./Equation"),
vec2 = require('../math/vec2');
module.exports = RotationalLockEquation;
/**
* Locks the relative angle between two bodies. The constraint tries to keep the dot product between two vectors, local in each body, to zero. The local angle in body i is a parameter.
*
* @class RotationalLockEquation
* @constructor
* @extends Equation
* @param {Body} bi
* @param {Body} bj
* @param {Object} options
* @param {Number} options.angle Angle to add to the local vector in body i.
*/
function RotationalLockEquation(bi,bj,options){
options = options || {};
Equation.call(this,bi,bj,-Number.MAX_VALUE,Number.MAX_VALUE);
this.angle = options.angle || 0;
var G = this.G;
G[2] = 1;
G[5] = -1;
};
RotationalLockEquation.prototype = new Equation();
RotationalLockEquation.prototype.constructor = RotationalLockEquation;
var worldVectorA = vec2.create(),
worldVectorB = vec2.create(),
xAxis = vec2.fromValues(1,0),
yAxis = vec2.fromValues(0,1);
RotationalLockEquation.prototype.computeGq = function(){
vec2.rotate(worldVectorA,xAxis,this.bi.angle+this.angle);
vec2.rotate(worldVectorB,yAxis,this.bj.angle);
return vec2.dot(worldVectorA,worldVectorB);
};
},{"../math/vec2":33,"./Equation":24}],27:[function(require,module,exports){
var Equation = require("./Equation"),
vec2 = require('../math/vec2');
module.exports = RotationalVelocityEquation;
/**
* Syncs rotational velocity of two bodies, or sets a relative velocity (motor).
*
* @class RotationalVelocityEquation
* @constructor
* @extends Equation
* @param {Body} bi
* @param {Body} bj
*/
function RotationalVelocityEquation(bi,bj){
Equation.call(this,bi,bj,-Number.MAX_VALUE,Number.MAX_VALUE);
this.relativeVelocity = 1;
this.ratio = 1;
};
RotationalVelocityEquation.prototype = new Equation();
RotationalVelocityEquation.prototype.constructor = RotationalVelocityEquation;
RotationalVelocityEquation.prototype.computeB = function(a,b,h){
var G = this.G;
G[2] = -1;
G[5] = this.ratio;
var GiMf = this.computeGiMf();
var GW = this.computeGW();
var B = - GW * b - h*GiMf;
return B;
};
},{"../math/vec2":33,"./Equation":24}],28:[function(require,module,exports){
/**
* Base class for objects that dispatches events.
* @class EventEmitter
* @constructor
*/
var EventEmitter = function () {}
module.exports = EventEmitter;
EventEmitter.prototype = {
constructor: EventEmitter,
/**
* Add an event listener
* @method on
* @param {String} type
* @param {Function} listener
* @return {EventEmitter} The self object, for chainability.
*/
on: function ( type, listener, context ) {
listener.context = context || this;
if ( this._listeners === undefined ) this._listeners = {};
var listeners = this._listeners;
if ( listeners[ type ] === undefined ) {
listeners[ type ] = [];
}
if ( listeners[ type ].indexOf( listener ) === - 1 ) {
listeners[ type ].push( listener );
}
return this;
},
/**
* Check if an event listener is added
* @method has
* @param {String} type
* @param {Function} listener
* @return {Boolean}
*/
has: function ( type, listener ) {
if ( this._listeners === undefined ) return false;
var listeners = this._listeners;
if ( listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1 ) {
return true;
}
return false;
},
/**
* Remove an event listener
* @method off
* @param {String} type
* @param {Function} listener
* @return {EventEmitter} The self object, for chainability.
*/
off: function ( type, listener ) {
if ( this._listeners === undefined ) return this;
var listeners = this._listeners;
var index = listeners[ type ].indexOf( listener );
if ( index !== - 1 ) {
listeners[ type ].splice( index, 1 );
}
return this;
},
/**
* Emit an event.
* @method emit
* @param {Object} event
* @param {String} event.type
* @return {EventEmitter} The self object, for chainability.
*/
emit: function ( event ) {
if ( this._listeners === undefined ) return this;
var listeners = this._listeners;
var listenerArray = listeners[ event.type ];
if ( listenerArray !== undefined ) {
event.target = this;
for ( var i = 0, l = listenerArray.length; i < l; i ++ ) {
var listener = listenerArray[ i ];
listener.call( listener.context, event );
}
}
return this;
}
};
},{}],29:[function(require,module,exports){
var Material = require('./Material');
module.exports = ContactMaterial;
/**
* Defines what happens when two materials meet, such as what friction coefficient to use. You can also set other things such as restitution, surface velocity and constraint parameters.
* @class ContactMaterial
* @constructor
* @param {Material} materialA
* @param {Material} materialB
* @param {Object} [options]
* @param {Number} options.friction Friction coefficient.
* @param {Number} options.restitution Restitution coefficient aka "bounciness".
* @param {Number} options.stiffness ContactEquation stiffness.
* @param {Number} options.relaxation ContactEquation relaxation.
* @param {Number} options.frictionStiffness FrictionEquation stiffness.
* @param {Number} options.frictionRelaxation FrictionEquation relaxation.
* @param {Number} options.surfaceVelocity Surface velocity.
* @author schteppe
*/
function ContactMaterial(materialA, materialB, options){
options = options || {};
if(!(materialA instanceof Material) || !(materialB instanceof Material))
throw new Error("First two arguments must be Material instances.");
/**
* The contact material identifier
* @property id
* @type {Number}
*/
this.id = ContactMaterial.idCounter++;
/**
* First material participating in the contact material
* @property materialA
* @type {Material}
*/
this.materialA = materialA;
/**
* Second material participating in the contact material
* @property materialB
* @type {Material}
*/
this.materialB = materialB;
/**
* Friction to use in the contact of these two materials
* @property friction
* @type {Number}
*/
this.friction = typeof(options.friction) !== "undefined" ? Number(options.friction) : 0.3;
/**
* Restitution to use in the contact of these two materials
* @property restitution
* @type {Number}
*/
this.restitution = typeof(options.restitution) !== "undefined" ? Number(options.restitution) : 0.0;
/**
* Stiffness of the resulting ContactEquation that this ContactMaterial generate
* @property stiffness
* @type {Number}
*/
this.stiffness = typeof(options.stiffness) !== "undefined" ? Number(options.stiffness) : 1e7;
/**
* Relaxation of the resulting ContactEquation that this ContactMaterial generate
* @property relaxation
* @type {Number}
*/
this.relaxation = typeof(options.relaxation) !== "undefined" ? Number(options.relaxation) : 3;
/**
* Stiffness of the resulting FrictionEquation that this ContactMaterial generate
* @property frictionStiffness
* @type {Number}
*/
this.frictionStiffness = typeof(options.frictionStiffness) !== "undefined" ? Number(options.frictionStiffness) : 1e7;
/**
* Relaxation of the resulting FrictionEquation that this ContactMaterial generate
* @property frictionRelaxation
* @type {Number}
*/
this.frictionRelaxation = typeof(options.frictionRelaxation) !== "undefined" ? Number(options.frictionRelaxation) : 3;
/**
* Will add surface velocity to this material. If bodyA rests on top if bodyB, and the surface velocity is positive, bodyA will slide to the right.
* @property {Number} surfaceVelocity
*/
this.surfaceVelocity = typeof(options.surfaceVelocity) !== "undefined" ? Number(options.surfaceVelocity) : 0
};
ContactMaterial.idCounter = 0;
},{"./Material":30}],30:[function(require,module,exports){
module.exports = Material;
/**
* Defines a physics material.
* @class Material
* @constructor
* @param string name
* @author schteppe
*/
function Material(){
/**
* The material identifier
* @property id
* @type {Number}
*/
this.id = Material.idCounter++;
};
Material.idCounter = 0;
},{}],31:[function(require,module,exports){
/**
* The mat2 object from glMatrix, extended with the functions documented here. See http://glmatrix.net for full doc.
* @class mat2
*/
// Only import mat2 from gl-matrix and skip the rest
var mat2 = require('../../node_modules/gl-matrix/src/gl-matrix/mat2').mat2;
// Export everything
module.exports = mat2;
},{"../../node_modules/gl-matrix/src/gl-matrix/mat2":1}],32:[function(require,module,exports){
/*
PolyK library
url: http://polyk.ivank.net
Released under MIT licence.
Copyright (c) 2012 Ivan Kuckir
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/
var PolyK = {};
/*
Is Polygon self-intersecting?
O(n^2)
*/
/*
PolyK.IsSimple = function(p)
{
var n = p.length>>1;
if(n<4) return true;
var a1 = new PolyK._P(), a2 = new PolyK._P();
var b1 = new PolyK._P(), b2 = new PolyK._P();
var c = new PolyK._P();
for(var i=0; i<n; i++)
{
a1.x = p[2*i ];
a1.y = p[2*i+1];
if(i==n-1) { a2.x = p[0 ]; a2.y = p[1 ]; }
else { a2.x = p[2*i+2]; a2.y = p[2*i+3]; }
for(var j=0; j<n; j++)
{
if(Math.abs(i-j) < 2) continue;
if(j==n-1 && i==0) continue;
if(i==n-1 && j==0) continue;
b1.x = p[2*j ];
b1.y = p[2*j+1];
if(j==n-1) { b2.x = p[0 ]; b2.y = p[1 ]; }
else { b2.x = p[2*j+2]; b2.y = p[2*j+3]; }
if(PolyK._GetLineIntersection(a1,a2,b1,b2,c) != null) return false;
}
}
return true;
}
PolyK.IsConvex = function(p)
{
if(p.length<6) return true;
var l = p.length - 4;
for(var i=0; i<l; i+=2)
if(!PolyK._convex(p[i], p[i+1], p[i+2], p[i+3], p[i+4], p[i+5])) return false;
if(!PolyK._convex(p[l ], p[l+1], p[l+2], p[l+3], p[0], p[1])) return false;
if(!PolyK._convex(p[l+2], p[l+3], p[0 ], p[1 ], p[2], p[3])) return false;
return true;
}
*/
PolyK.GetArea = function(p)
{
if(p.length <6) return 0;
var l = p.length - 2;
var sum = 0;
for(var i=0; i<l; i+=2)
sum += (p[i+2]-p[i]) * (p[i+1]+p[i+3]);
sum += (p[0]-p[l]) * (p[l+1]+p[1]);
return - sum * 0.5;
}
/*
PolyK.GetAABB = function(p)
{
var minx = Infinity;
var miny = Infinity;
var maxx = -minx;
var maxy = -miny;
for(var i=0; i<p.length; i+=2)
{
minx = Math.min(minx, p[i ]);
maxx = Math.max(maxx, p[i ]);
miny = Math.min(miny, p[i+1]);
maxy = Math.max(maxy, p[i+1]);
}
return {x:minx, y:miny, width:maxx-minx, height:maxy-miny};
}
*/
PolyK.Triangulate = function(p)
{
var n = p.length>>1;
if(n<3) return [];
var tgs = [];
var avl = [];
for(var i=0; i<n; i++) avl.push(i);
var i = 0;
var al = n;
while(al > 3)
{
var i0 = avl[(i+0)%al];
var i1 = avl[(i+1)%al];
var i2 = avl[(i+2)%al];
var ax = p[2*i0], ay = p[2*i0+1];
var bx = p[2*i1], by = p[2*i1+1];
var cx = p[2*i2], cy = p[2*i2+1];
var earFound = false;
if(PolyK._convex(ax, ay, bx, by, cx, cy))
{
earFound = true;
for(var j=0; j<al; j++)
{
var vi = avl[j];
if(vi==i0 || vi==i1 || vi==i2) continue;
if(PolyK._PointInTriangle(p[2*vi], p[2*vi+1], ax, ay, bx, by, cx, cy)) {earFound = false; break;}
}
}
if(earFound)
{
tgs.push(i0, i1, i2);
avl.splice((i+1)%al, 1);
al--;
i= 0;
}
else if(i++ > 3*al) break; // no convex angles :(
}
tgs.push(avl[0], avl[1], avl[2]);
return tgs;
}
/*
PolyK.ContainsPoint = function(p, px, py)
{
var n = p.length>>1;
var ax, ay, bx = p[2*n-2]-px, by = p[2*n-1]-py;
var depth = 0;
for(var i=0; i<n; i++)
{
ax = bx; ay = by;
bx = p[2*i ] - px;
by = p[2*i+1] - py;
if(ay< 0 && by< 0) continue; // both "up" or both "donw"
if(ay>=0 && by>=0) continue; // both "up" or both "donw"
if(ax< 0 && bx< 0) continue;
var lx = ax + (bx-ax)*(-ay)/(by-ay);
if(lx>0) depth++;
}
return (depth & 1) == 1;
}
PolyK.Slice = function(p, ax, ay, bx, by)
{
if(PolyK.ContainsPoint(p, ax, ay) || PolyK.ContainsPoint(p, bx, by)) return [p.slice(0)];
var a = new PolyK._P(ax, ay);
var b = new PolyK._P(bx, by);
var iscs = []; // intersections
var ps = []; // points
for(var i=0; i<p.length; i+=2) ps.push(new PolyK._P(p[i], p[i+1]));
for(var i=0; i<ps.length; i++)
{
var isc = new PolyK._P(0,0);
isc = PolyK._GetLineIntersection(a, b, ps[i], ps[(i+1)%ps.length], isc);
if(isc)
{
isc.flag = true;
iscs.push(isc);
ps.splice(i+1,0,isc);
i++;
}
}
if(iscs.length == 0) return [p.slice(0)];
var comp = function(u,v) {return PolyK._P.dist(a,u) - PolyK._P.dist(a,v); }
iscs.sort(comp);
var pgs = [];
var dir = 0;
while(iscs.length > 0)
{
var n = ps.length;
var i0 = iscs[0];
var i1 = iscs[1];
var ind0 = ps.indexOf(i0);
var ind1 = ps.indexOf(i1);
var solved = false;
if(PolyK._firstWithFlag(ps, ind0) == ind1) solved = true;
else
{
i0 = iscs[1];
i1 = iscs[0];
ind0 = ps.indexOf(i0);
ind1 = ps.indexOf(i1);
if(PolyK._firstWithFlag(ps, ind0) == ind1) solved = true;
}
if(solved)
{
dir--;
var pgn = PolyK._getPoints(ps, ind0, ind1);
pgs.push(pgn);
ps = PolyK._getPoints(ps, ind1, ind0);
i0.flag = i1.flag = false;
iscs.splice(0,2);
if(iscs.length == 0) pgs.push(ps);
}
else { dir++; iscs.reverse(); }
if(dir>1) break;
}
var result = [];
for(var i=0; i<pgs.length; i++)
{
var pg = pgs[i];
var npg = [];
for(var j=0; j<pg.length; j++) npg.push(pg[j].x, pg[j].y);
result.push(npg);
}
return result;
}
PolyK.Raycast = function(p, x, y, dx, dy, isc)
{
var l = p.length - 2;
var tp = PolyK._tp;
var a1 = tp[0], a2 = tp[1],
b1 = tp[2], b2 = tp[3], c = tp[4];
a1.x = x; a1.y = y;
a2.x = x+dx; a2.y = y+dy;
if(isc==null) isc = {dist:0, edge:0, norm:{x:0, y:0}, refl:{x:0, y:0}};
isc.dist = Infinity;
for(var i=0; i<l; i+=2)
{
b1.x = p[i ]; b1.y = p[i+1];
b2.x = p[i+2]; b2.y = p[i+3];
var nisc = PolyK._RayLineIntersection(a1, a2, b1, b2, c);
if(nisc) PolyK._updateISC(dx, dy, a1, b1, b2, c, i/2, isc);
}
b1.x = b2.x; b1.y = b2.y;
b2.x = p[0]; b2.y = p[1];
var nisc = PolyK._RayLineIntersection(a1, a2, b1, b2, c);
if(nisc) PolyK._updateISC(dx, dy, a1, b1, b2, c, p.length/2, isc);
return (isc.dist != Infinity) ? isc : null;
}
PolyK.ClosestEdge = function(p, x, y, isc)
{
var l = p.length - 2;
var tp = PolyK._tp;
var a1 = tp[0],
b1 = tp[2], b2 = tp[3], c = tp[4];
a1.x = x; a1.y = y;
if(isc==null) isc = {dist:0, edge:0, point:{x:0, y:0}, norm:{x:0, y:0}};
isc.dist = Infinity;
for(var i=0; i<l; i+=2)
{
b1.x = p[i ]; b1.y = p[i+1];
b2.x = p[i+2]; b2.y = p[i+3];
PolyK._pointLineDist(a1, b1, b2, i>>1, isc);
}
b1.x = b2.x; b1.y = b2.y;
b2.x = p[0]; b2.y = p[1];
PolyK._pointLineDist(a1, b1, b2, l>>1, isc);
var idst = 1/isc.dist;
isc.norm.x = (x-isc.point.x)*idst;
isc.norm.y = (y-isc.point.y)*idst;
return isc;
}
PolyK._pointLineDist = function(p, a, b, edge, isc)
{
var x = p.x, y = p.y, x1 = a.x, y1 = a.y, x2 = b.x, y2 = b.y;
var A = x - x1;
var B = y - y1;
var C = x2 - x1;
var D = y2 - y1;
var dot = A * C + B * D;
var len_sq = C * C + D * D;
var param = dot / len_sq;
var xx, yy;
if (param < 0 || (x1 == x2 && y1 == y2)) {
xx = x1;
yy = y1;
}
else if (param > 1) {
xx = x2;
yy = y2;
}
else {
xx = x1 + param * C;
yy = y1 + param * D;
}
var dx = x - xx;
var dy = y - yy;
var dst = Math.sqrt(dx * dx + dy * dy);
if(dst<isc.dist)
{
isc.dist = dst;
isc.edge = edge;
isc.point.x = xx;
isc.point.y = yy;
}
}
PolyK._updateISC = function(dx, dy, a1, b1, b2, c, edge, isc)
{
var nrl = PolyK._P.dist(a1, c);
if(nrl<isc.dist)
{
var ibl = 1/PolyK._P.dist(b1, b2);
var nx = -(b2.y-b1.y)*ibl;
var ny = (b2.x-b1.x)*ibl;
var ddot = 2*(dx*nx+dy*ny);
isc.dist = nrl;
isc.norm.x = nx;
isc.norm.y = ny;
isc.refl.x = -ddot*nx+dx;
isc.refl.y = -ddot*ny+dy;
isc.edge = edge;
}
}
PolyK._getPoints = function(ps, ind0, ind1)
{
var n = ps.length;
var nps = [];
if(ind1<ind0) ind1 += n;
for(var i=ind0; i<= ind1; i++) nps.push(ps[i%n]);
return nps;
}
PolyK._firstWithFlag = function(ps, ind)
{
var n = ps.length;
while(true)
{
ind = (ind+1)%n;
if(ps[ind].flag) return ind;
}
}
*/
PolyK._PointInTriangle = function(px, py, ax, ay, bx, by, cx, cy)
{
var v0x = cx-ax;
var v0y = cy-ay;
var v1x = bx-ax;
var v1y = by-ay;
var v2x = px-ax;
var v2y = py-ay;
var dot00 = v0x*v0x+v0y*v0y;
var dot01 = v0x*v1x+v0y*v1y;
var dot02 = v0x*v2x+v0y*v2y;
var dot11 = v1x*v1x+v1y*v1y;
var dot12 = v1x*v2x+v1y*v2y;
var invDenom = 1 / (dot00 * dot11 - dot01 * dot01);
var u = (dot11 * dot02 - dot01 * dot12) * invDenom;
var v = (dot00 * dot12 - dot01 * dot02) * invDenom;
// Check if point is in triangle
return (u >= 0) && (v >= 0) && (u + v < 1);
}
/*
PolyK._RayLineIntersection = function(a1, a2, b1, b2, c)
{
var dax = (a1.x-a2.x), dbx = (b1.x-b2.x);
var day = (a1.y-a2.y), dby = (b1.y-b2.y);
var Den = dax*dby - day*dbx;
if (Den == 0) return null; // parallel
var A = (a1.x * a2.y - a1.y * a2.x);
var B = (b1.x * b2.y - b1.y * b2.x);
var I = c;
var iDen = 1/Den;
I.x = ( A*dbx - dax*B ) * iDen;
I.y = ( A*dby - day*B ) * iDen;
if(!PolyK._InRect(I, b1, b2)) return null;
if((day>0 && I.y>a1.y) || (day<0 && I.y<a1.y)) return null;
if((dax>0 && I.x>a1.x) || (dax<0 && I.x<a1.x)) return null;
return I;
}
PolyK._GetLineIntersection = function(a1, a2, b1, b2, c)
{
var dax = (a1.x-a2.x), dbx = (b1.x-b2.x);
var day = (a1.y-a2.y), dby = (b1.y-b2.y);
var Den = dax*dby - day*dbx;
if (Den == 0) return null; // parallel
var A = (a1.x * a2.y - a1.y * a2.x);
var B = (b1.x * b2.y - b1.y * b2.x);
var I = c;
I.x = ( A*dbx - dax*B ) / Den;
I.y = ( A*dby - day*B ) / Den;
if(PolyK._InRect(I, a1, a2) && PolyK._InRect(I, b1, b2)) return I;
return null;
}
PolyK._InRect = function(a, b, c)
{
if (b.x == c.x) return (a.y>=Math.min(b.y, c.y) && a.y<=Math.max(b.y, c.y));
if (b.y == c.y) return (a.x>=Math.min(b.x, c.x) && a.x<=Math.max(b.x, c.x));
if(a.x >= Math.min(b.x, c.x) && a.x <= Math.max(b.x, c.x)
&& a.y >= Math.min(b.y, c.y) && a.y <= Math.max(b.y, c.y))
return true;
return false;
}
*/
PolyK._convex = function(ax, ay, bx, by, cx, cy)
{
return (ay-by)*(cx-bx) + (bx-ax)*(cy-by) >= 0;
}
/*
PolyK._P = function(x,y)
{
this.x = x;
this.y = y;
this.flag = false;
}
PolyK._P.prototype.toString = function()
{
return "Point ["+this.x+", "+this.y+"]";
}
PolyK._P.dist = function(a,b)
{
var dx = b.x-a.x;
var dy = b.y-a.y;
return Math.sqrt(dx*dx + dy*dy);
}
PolyK._tp = [];
for(var i=0; i<10; i++) PolyK._tp.push(new PolyK._P(0,0));
*/
module.exports = PolyK;
},{}],33:[function(require,module,exports){
/**
* The vec2 object from glMatrix, extended with the functions documented here. See http://glmatrix.net for full doc.
* @class vec2
*/
// Only import vec2 from gl-matrix and skip the rest
var vec2 = require('../../node_modules/gl-matrix/src/gl-matrix/vec2').vec2;
// Now add some extensions
/**
* Get the vector x component
* @method getX
* @static
* @param {Float32Array} a
* @return {Number}
*/
vec2.getX = function(a){
return a[0];
};
/**
* Get the vector y component
* @method getY
* @static
* @param {Float32Array} a
* @return {Number}
*/
vec2.getY = function(a){
return a[1];
};
/**
* Make a cross product and only return the z component
* @method crossLength
* @static
* @param {Float32Array} a
* @param {Float32Array} b
* @return {Number}
*/
vec2.crossLength = function(a,b){
return a[0] * b[1] - a[1] * b[0];
};
/**
* Cross product between a vector and the Z component of a vector
* @method crossVZ
* @static
* @param {Float32Array} out
* @param {Float32Array} vec
* @param {Number} zcomp
* @return {Number}
*/
vec2.crossVZ = function(out, vec, zcomp){
vec2.rotate(out,vec,-Math.PI/2);// Rotate according to the right hand rule
vec2.scale(out,out,zcomp); // Scale with z
return out;
};
/**
* Cross product between a vector and the Z component of a vector
* @method crossZV
* @static
* @param {Float32Array} out
* @param {Number} zcomp
* @param {Float32Array} vec
* @return {Number}
*/
vec2.crossZV = function(out, zcomp, vec){
vec2.rotate(out,vec,Math.PI/2); // Rotate according to the right hand rule
vec2.scale(out,out,zcomp); // Scale with z
return out;
};
/**
* Rotate a vector by an angle
* @method rotate
* @static
* @param {Float32Array} out
* @param {Float32Array} a
* @param {Number} angle
*/
vec2.rotate = function(out,a,angle){
var c = Math.cos(angle),
s = Math.sin(angle),
x = a[0],
y = a[1];
out[0] = c*x -s*y;
out[1] = s*x +c*y;
};
vec2.toLocalFrame = function(out, worldPoint, framePosition, frameAngle){
vec2.copy(out, worldPoint);
vec2.sub(out, out, framePosition);
vec2.rotate(out, out, -frameAngle);
};
vec2.toGlobalFrame = function(out, localPoint, framePosition, frameAngle){
vec2.copy(out, localPoint);
vec2.rotate(out, out, frameAngle);
vec2.add(out, out, framePosition);
};
/**
* Compute centroid of a triangle spanned by vectors a,b,c. See http://easycalculation.com/analytical/learn-centroid.php
* @method centroid
* @static
* @param {Float32Array} out
* @param {Float32Array} a
* @param {Float32Array} b
* @param {Float32Array} c
* @return {Float32Array} The out object
*/
vec2.centroid = function(out, a, b, c){
vec2.add(out, a, b);
vec2.add(out, out, c);
vec2.scale(out, out, 1/3);
return out;
};
// Export everything
module.exports = vec2;
},{"../../node_modules/gl-matrix/src/gl-matrix/vec2":2}],34:[function(require,module,exports){
var vec2 = require('../math/vec2')
, decomp = require('poly-decomp')
, Convex = require('../shapes/Convex')
, AABB = require('../collision/AABB')
, EventEmitter = require('../events/EventEmitter')
module.exports = Body;
/**
* A rigid body. Has got a center of mass, position, velocity and a number of
* shapes that are used for collisions.
*
* @class Body
* @constructor
* @extends {EventEmitter}
* @param {Object} [options]
* @param {Number} [options.mass=0] A number >= 0. If zero, the .motionState will be set to Body.STATIC.
* @param {Float32Array|Array} [options.position]
* @param {Float32Array|Array} [options.velocity]
* @param {Number} [options.angle=0]
* @param {Number} [options.angularVelocity=0]
* @param {Float32Array|Array} [options.force]
* @param {Number} [options.angularForce=0]
* @param {Number} [options.fixedRotation=false]
*/
function Body(options){
options = options || {};
EventEmitter.call(this);
/**
* The body identifyer
* @property id
* @type {Number}
*/
this.id = ++Body._idCounter;
/**
* The world that this body is added to. This property is set to NULL if the body is not added to any world.
* @property world
* @type {World}
*/
this.world = null;
/**
* The shapes of the body. The local transform of the shape in .shapes[i] is
* defined by .shapeOffsets[i] and .shapeAngles[i].
*
* @property shapes
* @type {Array}
*/
this.shapes = [];
/**
* The local shape offsets, relative to the body center of mass. This is an
* array of Float32Array.
* @property shapeOffsets
* @type {Array}
*/
this.shapeOffsets = [];
/**
* The body-local shape angle transforms. This is an array of numbers (angles).
* @property shapeAngles
* @type {Array}
*/
this.shapeAngles = [];
/**
* The mass of the body.
* @property mass
* @type {number}
*/
this.mass = options.mass || 0;
/**
* The inverse mass of the body.
* @property invMass
* @type {number}
*/
this.invMass = 0;
/**
* The inertia of the body around the Z axis.
* @property inertia
* @type {number}
*/
this.inertia = 0;
/**
* The inverse inertia of the body.
* @property invInertia
* @type {number}
*/
this.invInertia = 0;
/**
* Set to true if you want to fix the rotation of the body.
* @property fixedRotation
* @type {Boolean}
*/
this.fixedRotation = !!options.fixedRotation || false;
/**
* The position of the body
* @property position
* @type {Array}
*/
this.position = vec2.fromValues(0,0);
if(options.position) vec2.copy(this.position, options.position);
/**
* The interpolated position of the body.
* @property interpolatedPosition
* @type {Array}
*/
this.interpolatedPosition = vec2.fromValues(0,0);
/**
* The velocity of the body
* @property velocity
* @type {Float32Array}
*/
this.velocity = vec2.fromValues(0,0);
if(options.velocity) vec2.copy(this.velocity, options.velocity);
/**
* Constraint velocity that was added to the body during the last step.
* @property vlambda
* @type {Float32Array}
*/
this.vlambda = vec2.fromValues(0,0);
/**
* Angular constraint velocity that was added to the body during last step.
* @property wlambda
* @type {Float32Array}
*/
this.wlambda = 0;
/**
* The angle of the body, in radians.
* @property angle
* @type {number}
* @example
* // The angle property is not normalized to the interval 0 to 2*pi, it can be any value.
* // If you need a value between 0 and 2*pi, use the following function to normalize it.
* function normalizeAngle(angle){
* angle = angle % (2*Math.PI);
* if(angle < 0){
* angle += (2*Math.PI);
* }
* return angle;
* }
*/
this.angle = options.angle || 0;
/**
* The angular velocity of the body
* @property angularVelocity
* @type {number}
*/
this.angularVelocity = options.angularVelocity || 0;
/**
* The force acting on the body
* @property force
* @type {Float32Array}
*/
this.force = vec2.create();
if(options.force) vec2.copy(this.force, options.force);
/**
* The angular force acting on the body
* @property angularForce
* @type {number}
*/
this.angularForce = options.angularForce || 0;
/**
* The linear damping acting on the body in the velocity direction
* @property damping
* @type {Number}
*/
this.damping = typeof(options.damping)=="number" ? options.damping : 0.1;
/**
* The angular force acting on the body
* @property angularDamping
* @type {Number}
*/
this.angularDamping = typeof(options.angularDamping)=="number" ? options.angularDamping : 0.1;
/**
* The type of motion this body has. Should be one of: Body.STATIC (the body
* does not move), Body.DYNAMIC (body can move and respond to collisions)
* and Body.KINEMATIC (only moves according to its .velocity).
*
* @property motionState
* @type {number}
*
* @example
* // This body will move and interact with other bodies
* var dynamicBody = new Body();
* dynamicBody.motionState = Body.DYNAMIC;
*
* @example
* // This body will not move at all
* var staticBody = new Body();
* staticBody.motionState = Body.STATIC;
*
* @example
* // This body will only move if you change its velocity
* var kinematicBody = new Body();
* kinematicBody.motionState = Body.KINEMATIC;
*/
this.motionState = this.mass == 0 ? Body.STATIC : Body.DYNAMIC;
/**
* Bounding circle radius
* @property boundingRadius
* @type {Number}
*/
this.boundingRadius = 0;
/**
* Bounding box of this body
* @property aabb
* @type {AABB}
*/
this.aabb = new AABB();
/**
* Indicates if the AABB needs update. Update it with .updateAABB()
* @property aabbNeedsUpdate
* @type {Boolean}
*/
this.aabbNeedsUpdate = true;
/**
* If true, the body will automatically fall to sleep.
* @property allowSleep
* @type {Boolean}
*/
this.allowSleep = false;
/**
* One of Body.AWAKE, Body.SLEEPY, Body.SLEEPING
* @property sleepState
* @type {Number}
*/
this.sleepState = Body.AWAKE;
/**
* If the speed (the norm of the velocity) is smaller than this value, the body is considered sleepy.
* @property sleepSpeedLimit
* @type {Number}
*/
this.sleepSpeedLimit = 0.1;
/**
* If the body has been sleepy for this sleepTimeLimit seconds, it is considered sleeping.
* @property sleepTimeLimit
* @type {Number}
*/
this.sleepTimeLimit = 1;
/**
* Gravity scaling factor. If you want the body to ignore gravity, set this to zero. If you want to reverse gravity, set it to -1.
* @property {Number} gravityScale
*/
this.gravityScale = 1;
this.timeLastSleepy = 0;
this.concavePath = null;
this.lastDampingScale = 1;
this.lastAngularDampingScale = 1;
this.lastDampingTimeStep = -1;
this.updateMassProperties();
};
Body.prototype = new EventEmitter();
Body._idCounter = 0;
/**
* Set the total density of the body
* @method setDensity
*/
Body.prototype.setDensity = function(density) {
var totalArea = this.getArea();
this.mass = totalArea * density;
this.updateMassProperties();
};
/**
* Get the total area of all shapes in the body
* @method setDensity
*/
Body.prototype.getArea = function() {
var totalArea = 0;
for(var i=0; i<this.shapes.length; i++){
totalArea += this.shapes[i].area;
}
return totalArea;
};
var shapeAABB = new AABB(),
tmp = vec2.create();
/**
* Updates the AABB of the Body
* @method updateAABB
*/
Body.prototype.updateAABB = function() {
var shapes = this.shapes,
shapeOffsets = this.shapeOffsets,
shapeAngles = this.shapeAngles,
N = shapes.length;
for(var i=0; i!==N; i++){
var shape = shapes[i],
offset = tmp,
angle = shapeAngles[i] + this.angle;
// Get shape world offset
vec2.rotate(offset,shapeOffsets[i],this.angle);
vec2.add(offset,offset,this.position);
// Get shape AABB
shape.computeAABB(shapeAABB,offset,angle);
if(i===0)
this.aabb.copy(shapeAABB);
else
this.aabb.extend(shapeAABB);
}
this.aabbNeedsUpdate = false;
};
/**
* Update the bounding radius of the body. Should be done if any of the shapes
* are changed.
* @method updateBoundingRadius
*/
Body.prototype.updateBoundingRadius = function(){
var shapes = this.shapes,
shapeOffsets = this.shapeOffsets,
N = shapes.length,
radius = 0;
for(var i=0; i!==N; i++){
var shape = shapes[i],
offset = vec2.length(shapeOffsets[i]),
r = shape.boundingRadius;
if(offset + r > radius)
radius = offset + r;
}
this.boundingRadius = radius;
};
/**
* Add a shape to the body. You can pass a local transform when adding a shape,
* so that the shape gets an offset and angle relative to the body center of mass.
* Will automatically update the mass properties and bounding radius.
*
* @method addShape
* @param {Shape} shape
* @param {Float32Array|Array} [offset] Local body offset of the shape.
* @param {Number} [angle] Local body angle.
*
* @example
* var body = new Body(),
* shape = new Circle();
*
* // Add the shape to the body, positioned in the center
* body.addShape(shape);
*
* // Add another shape to the body, positioned 1 unit length from the body center of mass along the local x-axis.
* body.addShape(shape,[1,0]);
*
* // Add another shape to the body, positioned 1 unit length from the body center of mass along the local y-axis, and rotated 90 degrees CCW.
* body.addShape(shape,[0,1],Math.PI/2);
*/
Body.prototype.addShape = function(shape,offset,angle){
angle = angle || 0.0;
// Copy the offset vector
if(offset){
offset = vec2.fromValues(offset[0],offset[1]);
} else {
offset = vec2.fromValues(0,0);
}
this.shapes .push(shape);
this.shapeOffsets.push(offset);
this.shapeAngles .push(angle);
this.updateMassProperties();
this.updateBoundingRadius();
this.aabbNeedsUpdate = true;
};
/**
* Remove a shape
* @method removeShape
* @param {Shape} shape
* @return {Boolean} True if the shape was found and removed, else false.
*/
Body.prototype.removeShape = function(shape){
var idx = this.shapes.indexOf(shape);
if(idx != -1){
this.shapes.splice(idx,1);
this.shapeOffsets.splice(idx,1);
this.shapeAngles.splice(idx,1);
this.aabbNeedsUpdate = true;
return true;
} else
return false;
};
/**
* Updates .inertia, .invMass, .invInertia for this Body. Should be called when
* changing the structure or mass of the Body.
*
* @method updateMassProperties
*
* @example
* body.mass += 1;
* body.updateMassProperties();
*/
Body.prototype.updateMassProperties = function(){
if(this.motionState == Body.STATIC || this.motionState == Body.KINEMATIC){
this.mass = Number.MAX_VALUE;
this.invMass = 0;
this.inertia = Number.MAX_VALUE;
this.invInertia = 0;
} else {
var shapes = this.shapes,
N = shapes.length,
m = this.mass / N,
I = 0;
if(!this.fixedRotation){
for(var i=0; i<N; i++){
var shape = shapes[i],
r2 = vec2.squaredLength(this.shapeOffsets[i]),
Icm = shape.computeMomentOfInertia(m);
I += Icm + m*r2;
}
this.inertia = I;
this.invInertia = I>0 ? 1/I : 0;
} else {
this.inertia = Number.MAX_VALUE;
this.invInertia = 0;
}
// Inverse mass properties are easy
this.invMass = 1/this.mass;// > 0 ? 1/this.mass : 0;
}
};
var Body_applyForce_r = vec2.create();
/**
* Apply force to a world point. This could for example be a point on the RigidBody surface. Applying force this way will add to Body.force and Body.angularForce.
* @method applyForce
* @param {Float32Array} force The force to add.
* @param {Float32Array} worldPoint A world point to apply the force on.
*/
Body.prototype.applyForce = function(force,worldPoint){
// Compute point position relative to the body center
var r = Body_applyForce_r;
vec2.sub(r,worldPoint,this.position);
// Add linear force
vec2.add(this.force,this.force,force);
// Compute produced rotational force
var rotForce = vec2.crossLength(r,force);
// Add rotational force
this.angularForce += rotForce;
};
/**
* Transform a world point to local body frame.
* @method toLocalFrame
* @param {Float32Array|Array} out The vector to store the result in
* @param {Float32Array|Array} worldPoint The input world vector
*/
Body.prototype.toLocalFrame = function(out, worldPoint){
vec2.toLocalFrame(out, worldPoint, this.position, this.angle);
};
/**
* Transform a local point to world frame.
* @method toWorldFrame
* @param {Array} out The vector to store the result in
* @param {Array} localPoint The input local vector
*/
Body.prototype.toWorldFrame = function(out, localPoint){
vec2.toGlobalFrame(out, localPoint, this.position, this.angle);
};
/**
* Reads a polygon shape path, and assembles convex shapes from that and puts them at proper offset points.
* @method fromPolygon
* @param {Array} path An array of 2d vectors, e.g. [[0,0],[0,1],...] that resembles a concave or convex polygon. The shape must be simple and without holes.
* @param {Object} [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.
* @return {Boolean} True on success, else false.
*/
Body.prototype.fromPolygon = function(path,options){
options = options || {};
// Remove all shapes
for(var i=this.shapes.length; i>=0; --i)
this.removeShape(this.shapes[i]);
var p = new decomp.Polygon();
p.vertices = path;
// Make it counter-clockwise
p.makeCCW();
if(typeof(options.removeCollinearPoints)=="number"){
p.removeCollinearPoints(options.removeCollinearPoints);
}
// Check if any line segment intersects the path itself
if(typeof(options.skipSimpleCheck) == "undefined"){
if(!p.isSimple()) return false;
}
// Save this path for later
this.concavePath = p.vertices.slice(0);
for(var i=0; i<this.concavePath.length; i++){
var v = [0,0];
vec2.copy(v,this.concavePath[i]);
this.concavePath[i] = v;
}
// Slow or fast decomp?
var convexes;
if(options.optimalDecomp) convexes = p.decomp();
else convexes = p.quickDecomp();
var cm = vec2.create();
// Add convexes
for(var i=0; i!==convexes.length; i++){
// Create convex
var c = new Convex(convexes[i].vertices);
// Move all vertices so its center of mass is in the local center of the convex
for(var j=0; j!==c.vertices.length; j++){
var v = c.vertices[j];
vec2.sub(v,v,c.centerOfMass);
}
vec2.scale(cm,c.centerOfMass,1);
c.updateTriangles();
c.updateCenterOfMass();
c.updateBoundingRadius();
// Add the shape
this.addShape(c,cm);
}
this.adjustCenterOfMass();
this.aabbNeedsUpdate = true;
return true;
};
var adjustCenterOfMass_tmp1 = vec2.fromValues(0,0),
adjustCenterOfMass_tmp2 = vec2.fromValues(0,0),
adjustCenterOfMass_tmp3 = vec2.fromValues(0,0),
adjustCenterOfMass_tmp4 = vec2.fromValues(0,0);
/**
* Moves the shape offsets so their center of mass becomes the body center of mass.
* @method adjustCenterOfMass
*/
Body.prototype.adjustCenterOfMass = function(){
var offset_times_area = adjustCenterOfMass_tmp2,
sum = adjustCenterOfMass_tmp3,
cm = adjustCenterOfMass_tmp4,
totalArea = 0;
vec2.set(sum,0,0);
for(var i=0; i!==this.shapes.length; i++){
var s = this.shapes[i],
offset = this.shapeOffsets[i];
vec2.scale(offset_times_area,offset,s.area);
vec2.add(sum,sum,offset_times_area);
totalArea += s.area;
}
vec2.scale(cm,sum,1/totalArea);
// Now move all shapes
for(var i=0; i!==this.shapes.length; i++){
var s = this.shapes[i],
offset = this.shapeOffsets[i];
// Offset may be undefined. Fix that.
if(!offset){
offset = this.shapeOffsets[i] = vec2.create();
}
vec2.sub(offset,offset,cm);
}
// Move the body position too
vec2.add(this.position,this.position,cm);
// And concave path
for(var i=0; this.concavePath && i<this.concavePath.length; i++){
vec2.sub(this.concavePath[i], this.concavePath[i], cm);
}
this.updateMassProperties();
this.updateBoundingRadius();
};
/**
* Sets the force on the body to zero.
* @method setZeroForce
*/
Body.prototype.setZeroForce = function(){
vec2.set(this.force,0.0,0.0);
this.angularForce = 0.0;
};
Body.prototype.resetConstraintVelocity = function(){
var b = this,
vlambda = b.vlambda;
vec2.set(vlambda,0,0);
b.wlambda = 0;
};
Body.prototype.addConstraintVelocity = function(){
var b = this,
v = b.velocity;
vec2.add( v, v, b.vlambda);
b.angularVelocity += b.wlambda;
};
/**
* Apply damping, see <a href="http://code.google.com/p/bullet/issues/detail?id=74">this</a> for details.
* @method applyDamping
* @param {number} dt Current time step
*/
Body.prototype.applyDamping = function(dt){
if(this.motionState == Body.DYNAMIC){ // Only for dynamic bodies
// Since Math.pow generates garbage we check if we can reuse the scaling coefficient from last step
if(dt != this.lastDampingTimeStep){
this.lastDampingScale = Math.pow(1.0 - this.damping,dt);
this.lastAngularDampingScale = Math.pow(1.0 - this.angularDamping,dt);
this.lastDampingTimeStep = dt;
}
var v = this.velocity;
vec2.scale(v,v,this.lastDampingScale);
this.angularVelocity *= this.lastAngularDampingScale;
}
};
/**
* @method wakeUp
* @brief Wake the body up.
*/
Body.prototype.wakeUp = function(){
var s = this.sleepState;
this.sleepState = Body.AWAKE;
if(s !== Body.AWAKE){
this.emit(Body.wakeUpEvent);
}
};
/**
* @method sleep
* @brief Force body sleep
*/
Body.prototype.sleep = function(){
this.sleepState = Body.SLEEPING;
this.emit(Body.sleepEvent);
};
/**
* @method sleepTick
* @param float time The world time in seconds
* @brief Called every timestep to update internal sleep timer and change sleep state if needed.
*/
Body.prototype.sleepTick = function(time){
if(!this.allowSleep)
return;
var sleepState = this.sleepState,
speedSquared = vec2.squaredLength(this.velocity) + Math.pow(this.angularVelocity,2),
speedLimitSquared = Math.pow(this.sleepSpeedLimit,2);
if(sleepState===Body.AWAKE && speedSquared < speedLimitSquared){
this.sleepState = Body.SLEEPY; // Sleepy
this.timeLastSleepy = time;
this.emit(Body.sleepyEvent);
} else if(sleepState===Body.SLEEPY && speedSquared > speedLimitSquared){
this.wakeUp(); // Wake up
} else if(sleepState===Body.SLEEPY && (time - this.timeLastSleepy ) > this.sleepTimeLimit){
this.sleep();
}
};
/**
* @event sleepy
*/
Body.sleepyEvent = {
type: "sleepy"
};
/**
* @event sleep
*/
Body.sleepEvent = {
type: "sleep"
};
/**
* @event wakeup
*/
Body.wakeUpEvent = {
type: "wakeup"
};
/**
* Dynamic body.
* @property DYNAMIC
* @type {Number}
* @static
*/
Body.DYNAMIC = 1;
/**
* Static body.
* @property STATIC
* @type {Number}
* @static
*/
Body.STATIC = 2;
/**
* Kinematic body.
* @property KINEMATIC
* @type {Number}
* @static
*/
Body.KINEMATIC = 4;
/**
* @property AWAKE
* @type {Number}
* @static
*/
Body.AWAKE = 0;
/**
* @property SLEEPY
* @type {Number}
* @static
*/
Body.SLEEPY = 1;
/**
* @property SLEEPING
* @type {Number}
* @static
*/
Body.SLEEPING = 2;
},{"../collision/AABB":9,"../events/EventEmitter":28,"../math/vec2":33,"../shapes/Convex":39,"poly-decomp":7}],35:[function(require,module,exports){
var vec2 = require('../math/vec2');
module.exports = Spring;
/**
* A spring, connecting two bodies.
*
* @class Spring
* @constructor
* @param {Body} bodyA
* @param {Body} bodyB
* @param {Object} [options]
* @param {number} options.restLength A number > 0. Default: 1
* @param {number} options.stiffness A number >= 0. Default: 100
* @param {number} options.damping A number >= 0. Default: 1
* @param {Array} options.worldAnchorA Where to hook the spring to body A, in world coordinates.
* @param {Array} options.worldAnchorB
* @param {Array} options.localAnchorA Where to hook the spring to body A, in local body coordinates.
* @param {Array} options.localAnchorB
*/
function Spring(bodyA,bodyB,options){
options = options || {};
/**
* Rest length of the spring.
* @property restLength
* @type {number}
*/
this.restLength = typeof(options.restLength)=="number" ? options.restLength : 1;
/**
* Stiffness of the spring.
* @property stiffness
* @type {number}
*/
this.stiffness = options.stiffness || 100;
/**
* Damping of the spring.
* @property damping
* @type {number}
*/
this.damping = options.damping || 1;
/**
* First connected body.
* @property bodyA
* @type {Body}
*/
this.bodyA = bodyA;
/**
* Second connected body.
* @property bodyB
* @type {Body}
*/
this.bodyB = bodyB;
/**
* Anchor for bodyA in local bodyA coordinates.
* @property localAnchorA
* @type {Array}
*/
this.localAnchorA = vec2.fromValues(0,0);
/**
* Anchor for bodyB in local bodyB coordinates.
* @property localAnchorB
* @type {Array}
*/
this.localAnchorB = vec2.fromValues(0,0);
if(options.localAnchorA) vec2.copy(this.localAnchorA, options.localAnchorA);
if(options.localAnchorB) vec2.copy(this.localAnchorB, options.localAnchorB);
if(options.worldAnchorA) this.setWorldAnchorA(options.worldAnchorA);
if(options.worldAnchorB) this.setWorldAnchorB(options.worldAnchorB);
};
/**
* Set the anchor point on body A, using world coordinates.
* @method setWorldAnchorA
* @param {Array} worldAnchorA
*/
Spring.prototype.setWorldAnchorA = function(worldAnchorA){
this.bodyA.toLocalFrame(this.localAnchorA, worldAnchorA);
};
/**
* Set the anchor point on body B, using world coordinates.
* @method setWorldAnchorB
* @param {Array} worldAnchorB
*/
Spring.prototype.setWorldAnchorB = function(worldAnchorB){
this.bodyB.toLocalFrame(this.localAnchorB, worldAnchorB);
};
/**
* Get the anchor point on body A, in world coordinates.
* @method getWorldAnchorA
* @param {Array} result The vector to store the result in.
*/
Spring.prototype.getWorldAnchorA = function(result){
this.bodyA.toWorldFrame(result, this.localAnchorA);
};
/**
* Get the anchor point on body B, in world coordinates.
* @method getWorldAnchorB
* @param {Array} result The vector to store the result in.
*/
Spring.prototype.getWorldAnchorB = function(result){
this.bodyB.toWorldFrame(result, this.localAnchorB);
};
var applyForce_r = vec2.create(),
applyForce_r_unit = vec2.create(),
applyForce_u = vec2.create(),
applyForce_f = vec2.create(),
applyForce_worldAnchorA = vec2.create(),
applyForce_worldAnchorB = vec2.create(),
applyForce_ri = vec2.create(),
applyForce_rj = vec2.create(),
applyForce_tmp = vec2.create();
/**
* Apply the spring force to the connected bodies.
* @method applyForce
*/
Spring.prototype.applyForce = function(){
var k = this.stiffness,
d = this.damping,
l = this.restLength,
bodyA = this.bodyA,
bodyB = this.bodyB,
r = applyForce_r,
r_unit = applyForce_r_unit,
u = applyForce_u,
f = applyForce_f,
tmp = applyForce_tmp;
var worldAnchorA = applyForce_worldAnchorA,
worldAnchorB = applyForce_worldAnchorB,
ri = applyForce_ri,
rj = applyForce_rj;
// Get world anchors
this.getWorldAnchorA(worldAnchorA);
this.getWorldAnchorB(worldAnchorB);
// Get offset points
vec2.sub(ri, worldAnchorA, bodyA.position);
vec2.sub(rj, worldAnchorB, bodyB.position);
// Compute distance vector between world anchor points
vec2.sub(r, worldAnchorB, worldAnchorA);
var rlen = vec2.len(r);
vec2.normalize(r_unit,r);
//console.log(rlen)
//console.log("A",vec2.str(worldAnchorA),"B",vec2.str(worldAnchorB))
// Compute relative velocity of the anchor points, u
vec2.sub(u, bodyB.velocity, bodyA.velocity);
vec2.crossZV(tmp, bodyB.angularVelocity, rj);
vec2.add(u, u, tmp);
vec2.crossZV(tmp, bodyA.angularVelocity, ri);
vec2.sub(u, u, tmp);
// F = - k * ( x - L ) - D * ( u )
vec2.scale(f, r_unit, -k*(rlen-l) - d*vec2.dot(u,r_unit));
// Add forces to bodies
vec2.sub( bodyA.force, bodyA.force, f);
vec2.add( bodyB.force, bodyB.force, f);
// Angular force
var ri_x_f = vec2.crossLength(ri, f);
var rj_x_f = vec2.crossLength(rj, f);
bodyA.angularForce -= ri_x_f;
bodyB.angularForce += rj_x_f;
};
},{"../math/vec2":33}],36:[function(require,module,exports){
// Export p2 classes
module.exports = {
AABB : require('./collision/AABB'),
AngleLockEquation : require('./equations/AngleLockEquation'),
Body : require('./objects/Body'),
Broadphase : require('./collision/Broadphase'),
Capsule : require('./shapes/Capsule'),
Circle : require('./shapes/Circle'),
Constraint : require('./constraints/Constraint'),
ContactEquation : require('./equations/ContactEquation'),
ContactMaterial : require('./material/ContactMaterial'),
Convex : require('./shapes/Convex'),
DistanceConstraint : require('./constraints/DistanceConstraint'),
Equation : require('./equations/Equation'),
EventEmitter : require('./events/EventEmitter'),
FrictionEquation : require('./equations/FrictionEquation'),
GearConstraint : require('./constraints/GearConstraint'),
GridBroadphase : require('./collision/GridBroadphase'),
GSSolver : require('./solver/GSSolver'),
Heightfield : require('./shapes/Heightfield'),
Island : require('./solver/IslandSolver'),
IslandSolver : require('./solver/IslandSolver'),
Line : require('./shapes/Line'),
LockConstraint : require('./constraints/LockConstraint'),
Material : require('./material/Material'),
Narrowphase : require('./collision/Narrowphase'),
NaiveBroadphase : require('./collision/NaiveBroadphase'),
Particle : require('./shapes/Particle'),
Plane : require('./shapes/Plane'),
RevoluteConstraint : require('./constraints/RevoluteConstraint'),
PrismaticConstraint : require('./constraints/PrismaticConstraint'),
Rectangle : require('./shapes/Rectangle'),
RotationalVelocityEquation : require('./equations/RotationalVelocityEquation'),
SAPBroadphase : require('./collision/SAPBroadphase'),
Shape : require('./shapes/Shape'),
Solver : require('./solver/Solver'),
Spring : require('./objects/Spring'),
Utils : require('./utils/Utils'),
World : require('./world/World'),
QuadTree : require('./collision/QuadTree').QuadTree,
vec2 : require('./math/vec2'),
version : require('../package.json').version,
};
},{"../package.json":8,"./collision/AABB":9,"./collision/Broadphase":10,"./collision/GridBroadphase":11,"./collision/NaiveBroadphase":12,"./collision/Narrowphase":13,"./collision/QuadTree":14,"./collision/SAPBroadphase":15,"./constraints/Constraint":16,"./constraints/DistanceConstraint":17,"./constraints/GearConstraint":18,"./constraints/LockConstraint":19,"./constraints/PrismaticConstraint":20,"./constraints/RevoluteConstraint":21,"./equations/AngleLockEquation":22,"./equations/ContactEquation":23,"./equations/Equation":24,"./equations/FrictionEquation":25,"./equations/RotationalVelocityEquation":27,"./events/EventEmitter":28,"./material/ContactMaterial":29,"./material/Material":30,"./math/vec2":33,"./objects/Body":34,"./objects/Spring":35,"./shapes/Capsule":37,"./shapes/Circle":38,"./shapes/Convex":39,"./shapes/Heightfield":40,"./shapes/Line":41,"./shapes/Particle":42,"./shapes/Plane":43,"./shapes/Rectangle":44,"./shapes/Shape":45,"./solver/GSSolver":46,"./solver/IslandSolver":48,"./solver/Solver":49,"./utils/Utils":50,"./world/World":51}],37:[function(require,module,exports){
var Shape = require('./Shape')
, vec2 = require('../math/vec2')
module.exports = Capsule;
/**
* Capsule shape class.
* @class Capsule
* @constructor
* @extends {Shape}
* @param {Number} length The distance between the end points
* @param {Number} radius Radius of the capsule
*/
function Capsule(length,radius){
/**
* The distance between the end points.
* @property {Number} length
*/
this.length = length || 1;
/**
* The radius of the capsule.
* @property {Number} radius
*/
this.radius = radius || 1;
Shape.call(this,Shape.CAPSULE);
};
Capsule.prototype = new Shape();
/**
* Compute the mass moment of inertia of the Capsule.
* @method conputeMomentOfInertia
* @param {Number} mass
* @return {Number}
* @todo
*/
Capsule.prototype.computeMomentOfInertia = function(mass){
// Approximate with rectangle
var r = this.radius,
w = this.length + r, // 2*r is too much, 0 is too little
h = r*2;
return mass * (h*h + w*w) / 12;
};
/**
* @method updateBoundingRadius
*/
Capsule.prototype.updateBoundingRadius = function(){
this.boundingRadius = this.radius + this.length/2;
};
/**
* @method updateArea
*/
Capsule.prototype.updateArea = function(){
this.area = Math.PI * this.radius * this.radius + this.radius * 2 * this.length;
};
var r = vec2.create();
/**
* @method computeAABB
* @param {AABB} out The resulting AABB.
* @param {Array} position
* @param {Number} angle
*/
Capsule.prototype.computeAABB = function(out, position, angle){
var radius = this.radius;
// Compute center position of one of the the circles, world oriented, but with local offset
vec2.set(r,this.length,0);
vec2.rotate(r,r,angle);
// Get bounds
vec2.set(out.upperBound, Math.max(r[0]+radius, -r[0]+radius),
Math.max(r[1]+radius, -r[1]+radius));
vec2.set(out.lowerBound, Math.min(r[0]-radius, -r[0]-radius),
Math.min(r[1]-radius, -r[1]-radius));
// Add offset
vec2.add(out.lowerBound, out.lowerBound, position);
vec2.add(out.upperBound, out.upperBound, position);
};
},{"../math/vec2":33,"./Shape":45}],38:[function(require,module,exports){
var Shape = require('./Shape')
, vec2 = require('../math/vec2')
module.exports = Circle;
/**
* Circle shape class.
* @class Circle
* @extends {Shape}
* @constructor
* @param {number} radius The radius of this circle
*/
function Circle(radius){
/**
* The radius of the circle.
* @property radius
* @type {number}
*/
this.radius = radius || 1;
Shape.call(this,Shape.CIRCLE);
};
Circle.prototype = new Shape();
/**
* @method computeMomentOfInertia
* @param {Number} mass
* @return {Number}
*/
Circle.prototype.computeMomentOfInertia = function(mass){
var r = this.radius;
return mass * r * r / 2;
};
Circle.prototype.updateBoundingRadius = function(){
this.boundingRadius = this.radius;
};
Circle.prototype.updateArea = function(){
this.area = Math.PI * this.radius * this.radius;
};
/**
* @method computeAABB
* @param {AABB} out The resulting AABB.
* @param {Array} position
* @param {Number} angle
*/
Circle.prototype.computeAABB = function(out, position, angle){
var r = this.radius;
vec2.set(out.upperBound, r, r);
vec2.set(out.lowerBound, -r, -r);
if(position){
vec2.add(out.lowerBound, out.lowerBound, position);
vec2.add(out.upperBound, out.upperBound, position);
}
};
},{"../math/vec2":33,"./Shape":45}],39:[function(require,module,exports){
var Shape = require('./Shape')
, vec2 = require('../math/vec2')
, polyk = require('../math/polyk')
, decomp = require('poly-decomp')
module.exports = Convex;
/**
* Convex shape class.
* @class Convex
* @constructor
* @extends {Shape}
* @param {Array} vertices An array of Float32Array vertices that span this shape. Vertices are given in counter-clockwise (CCW) direction.
*/
function Convex(vertices){
/**
* Vertices defined in the local frame.
* @property vertices
* @type {Array}
*/
this.vertices = [];
// Copy the verts
for(var i=0; i<vertices.length; i++){
var v = vec2.create();
vec2.copy(v,vertices[i]);
this.vertices.push(v);
}
/**
* The center of mass of the Convex
* @property centerOfMass
* @type {Float32Array}
*/
this.centerOfMass = vec2.fromValues(0,0);
/**
* Triangulated version of this convex. The structure is Array of 3-Arrays, and each subarray contains 3 integers, referencing the vertices.
* @property triangles
* @type {Array}
*/
this.triangles = [];
if(this.vertices.length){
this.updateTriangles();
this.updateCenterOfMass();
}
/**
* The bounding radius of the convex
* @property boundingRadius
* @type {Number}
*/
this.boundingRadius = 0;
Shape.call(this,Shape.CONVEX);
this.updateBoundingRadius();
this.updateArea();
if(this.area < 0)
throw new Error("Convex vertices must be given in conter-clockwise winding.");
};
Convex.prototype = new Shape();
/**
* Update the .triangles property
* @method updateTriangles
*/
Convex.prototype.updateTriangles = function(){
this.triangles.length = 0;
// Rewrite on polyk notation, array of numbers
var polykVerts = [];
for(var i=0; i<this.vertices.length; i++){
var v = this.vertices[i];
polykVerts.push(v[0],v[1]);
}
// Triangulate
var triangles = polyk.Triangulate(polykVerts);
// Loop over all triangles, add their inertia contributions to I
for(var i=0; i<triangles.length; i+=3){
var id1 = triangles[i],
id2 = triangles[i+1],
id3 = triangles[i+2];
// Add to triangles
this.triangles.push([id1,id2,id3]);
}
};
var updateCenterOfMass_centroid = vec2.create(),
updateCenterOfMass_centroid_times_mass = vec2.create(),
updateCenterOfMass_a = vec2.create(),
updateCenterOfMass_b = vec2.create(),
updateCenterOfMass_c = vec2.create(),
updateCenterOfMass_ac = vec2.create(),
updateCenterOfMass_ca = vec2.create(),
updateCenterOfMass_cb = vec2.create(),
updateCenterOfMass_n = vec2.create();
/**
* Update the .centerOfMass property.
* @method updateCenterOfMass
*/
Convex.prototype.updateCenterOfMass = function(){
var triangles = this.triangles,
verts = this.vertices,
cm = this.centerOfMass,
centroid = updateCenterOfMass_centroid,
n = updateCenterOfMass_n,
a = updateCenterOfMass_a,
b = updateCenterOfMass_b,
c = updateCenterOfMass_c,
ac = updateCenterOfMass_ac,
ca = updateCenterOfMass_ca,
cb = updateCenterOfMass_cb,
centroid_times_mass = updateCenterOfMass_centroid_times_mass;
vec2.set(cm,0,0);
var totalArea = 0;
for(var i=0; i!==triangles.length; i++){
var t = triangles[i],
a = verts[t[0]],
b = verts[t[1]],
c = verts[t[2]];
vec2.centroid(centroid,a,b,c);
// Get mass for the triangle (density=1 in this case)
// http://math.stackexchange.com/questions/80198/area-of-triangle-via-vectors
var m = Convex.triangleArea(a,b,c)
totalArea += m;
// Add to center of mass
vec2.scale(centroid_times_mass, centroid, m);
vec2.add(cm, cm, centroid_times_mass);
}
vec2.scale(cm,cm,1/totalArea);
};
/**
* Compute the mass moment of inertia of the Convex.
* @method computeMomentOfInertia
* @param {Number} mass
* @return {Number}
* @see http://www.gamedev.net/topic/342822-moment-of-inertia-of-a-polygon-2d/
*/
Convex.prototype.computeMomentOfInertia = function(mass){
var denom = 0.0,
numer = 0.0,
N = this.vertices.length;
for(var j = N-1, i = 0; i < N; j = i, i ++){
var p0 = this.vertices[j];
var p1 = this.vertices[i];
var a = Math.abs(vec2.crossLength(p0,p1));
var b = vec2.dot(p1,p1) + vec2.dot(p1,p0) + vec2.dot(p0,p0);
denom += a * b;
numer += a;
}
return (mass / 6.0) * (denom / numer);
};
/**
* Updates the .boundingRadius property
* @method updateBoundingRadius
*/
Convex.prototype.updateBoundingRadius = function(){
var verts = this.vertices,
r2 = 0;
for(var i=0; i!==verts.length; i++){
var l2 = vec2.squaredLength(verts[i]);
if(l2 > r2) r2 = l2;
}
this.boundingRadius = Math.sqrt(r2);
};
/**
* Get the area of the triangle spanned by the three points a, b, c. The area is positive if the points are given in counter-clockwise order, otherwise negative.
* @static
* @method triangleArea
* @param {Array} a
* @param {Array} b
* @param {Array} c
* @return {Number}
*/
Convex.triangleArea = function(a,b,c){
return (((b[0] - a[0])*(c[1] - a[1]))-((c[0] - a[0])*(b[1] - a[1]))) * 0.5;
}
/**
* Update the .area
* @method updateArea
*/
Convex.prototype.updateArea = function(){
this.updateTriangles();
this.area = 0;
var triangles = this.triangles,
verts = this.vertices;
for(var i=0; i!==triangles.length; i++){
var t = triangles[i],
a = verts[t[0]],
b = verts[t[1]],
c = verts[t[2]];
// Get mass for the triangle (density=1 in this case)
var m = Convex.triangleArea(a,b,c);
this.area += m;
}
};
/**
* @method computeAABB
* @param {AABB} out
* @param {Array} position
* @param {Number} angle
*/
Convex.prototype.computeAABB = function(out, position, angle){
out.setFromPoints(this.vertices,position,angle);
};
},{"../math/polyk":32,"../math/vec2":33,"./Shape":45,"poly-decomp":7}],40:[function(require,module,exports){
var Shape = require('./Shape')
, vec2 = require('../math/vec2')
module.exports = Heightfield;
/**
* Heightfield shape class. Height data is given as an array. These data points are spread out evenly with a distance "elementWidth".
* @class Heightfield
* @extends {Shape}
* @constructor
*/
function Heightfield(data,maxValue,elementWidth){
this.data = data;
this.maxValue = maxValue;
this.elementWidth = elementWidth;
Shape.call(this,Shape.HEIGHTFIELD);
};
Heightfield.prototype = new Shape();
/**
* @method computeMomentOfInertia
* @param {Number} mass
* @return {Number}
*/
Heightfield.prototype.computeMomentOfInertia = function(mass){
return Number.MAX_VALUE;
};
Heightfield.prototype.updateBoundingRadius = function(){
this.boundingRadius = Number.MAX_VALUE;
};
Heightfield.prototype.updateArea = function(){
var data = this.data,
area = 0;
for(var i=0; i<data.length-1; i++){
area += (data[i]+data[i+1]) / 2 * this.elementWidth;
}
this.area = area;
};
/**
* @method computeAABB
* @param {AABB} out The resulting AABB.
* @param {Array} position
* @param {Number} angle
*/
Heightfield.prototype.computeAABB = function(out, position, angle){
// Use the max data rectangle
out.upperBound[0] = this.elementWidth * this.data.length + position[0];
out.upperBound[1] = this.maxValue + position[1];
out.lowerBound[0] = position[0];
out.lowerBound[1] = position[1];
};
},{"../math/vec2":33,"./Shape":45}],41:[function(require,module,exports){
var Shape = require('./Shape')
, vec2 = require('../math/vec2')
module.exports = Line;
/**
* Line shape class. The line shape is along the x direction, and stretches from [-length/2, 0] to [length/2,0].
* @class Line
* @param {Number} length The total length of the line
* @extends {Shape}
* @constructor
*/
function Line(length){
/**
* Length of this line
* @property length
* @type {Number}
*/
this.length = length;
Shape.call(this,Shape.LINE);
};
Line.prototype = new Shape();
Line.prototype.computeMomentOfInertia = function(mass){
return mass * Math.pow(this.length,2) / 12;
};
Line.prototype.updateBoundingRadius = function(){
this.boundingRadius = this.length/2;
};
var points = [vec2.create(),vec2.create()];
/**
* @method computeAABB
* @param {AABB} out The resulting AABB.
* @param {Array} position
* @param {Number} angle
*/
Line.prototype.computeAABB = function(out, position, angle){
var l = this.length;
vec2.set(points[0], -l/2, 0);
vec2.set(points[1], l/2, 0);
out.setFromPoints(points,position,angle);
};
},{"../math/vec2":33,"./Shape":45}],42:[function(require,module,exports){
var Shape = require('./Shape')
, vec2 = require('../math/vec2')
module.exports = Particle;
/**
* Particle shape class.
* @class Particle
* @constructor
* @extends {Shape}
*/
function Particle(){
Shape.call(this,Shape.PARTICLE);
};
Particle.prototype = new Shape();
Particle.prototype.computeMomentOfInertia = function(mass){
return 0; // Can't rotate a particle
};
Particle.prototype.updateBoundingRadius = function(){
this.boundingRadius = 0;
};
/**
* @method computeAABB
* @param {AABB} out
* @param {Array} position
* @param {Number} angle
*/
Particle.prototype.computeAABB = function(out, position, angle){
var l = this.length;
vec2.copy(out.lowerBound, position);
vec2.copy(out.upperBound, position);
};
},{"../math/vec2":33,"./Shape":45}],43:[function(require,module,exports){
var Shape = require('./Shape')
, vec2 = require('../math/vec2')
, Utils = require('../utils/Utils')
module.exports = Plane;
/**
* Plane shape class. The plane is facing in the Y direction.
* @class Plane
* @extends {Shape}
* @constructor
*/
function Plane(){
Shape.call(this,Shape.PLANE);
};
Plane.prototype = new Shape();
/**
* Compute moment of inertia
* @method computeMomentOfInertia
*/
Plane.prototype.computeMomentOfInertia = function(mass){
return 0; // Plane is infinite. The inertia should therefore be infinty but by convention we set 0 here
};
/**
* Update the bounding radius
* @method updateBoundingRadius
*/
Plane.prototype.updateBoundingRadius = function(){
this.boundingRadius = Number.MAX_VALUE;
};
/**
* @method computeAABB
* @param {AABB} out
* @param {Array} position
* @param {Number} angle
*/
Plane.prototype.computeAABB = function(out, position, angle){
var a = 0,
set = vec2.set;
if(typeof(angle) == "number")
a = angle % (2*Math.PI);
if(a == 0){
// y goes from -inf to 0
set(out.lowerBound, -Number.MAX_VALUE, -Number.MAX_VALUE);
set(out.upperBound, Number.MAX_VALUE, 0);
} else if(a == Math.PI / 2){
// x goes from 0 to inf
set(out.lowerBound, 0, -Number.MAX_VALUE);
set(out.upperBound, Number.MAX_VALUE, Number.MAX_VALUE);
} else if(a == Math.PI){
// y goes from 0 to inf
set(out.lowerBound, -Number.MAX_VALUE, 0);
set(out.upperBound, Number.MAX_VALUE, Number.MAX_VALUE);
} else if(a == 3*Math.PI/2){
// x goes from -inf to 0
set(out.lowerBound, -Number.MAX_VALUE, -Number.MAX_VALUE);
set(out.upperBound, 0, Number.MAX_VALUE);
} else {
// Set max bounds
set(out.lowerBound, -Number.MAX_VALUE, -Number.MAX_VALUE);
set(out.upperBound, Number.MAX_VALUE, Number.MAX_VALUE);
}
vec2.add(out.lowerBound, out.lowerBound, position);
vec2.add(out.upperBound, out.upperBound, position);
};
Plane.prototype.updateArea = function(){
this.area = Number.MAX_VALUE;
};
},{"../math/vec2":33,"../utils/Utils":50,"./Shape":45}],44:[function(require,module,exports){
var vec2 = require('../math/vec2')
, Shape = require('./Shape')
, Convex = require('./Convex')
module.exports = Rectangle;
/**
* Rectangle shape class.
* @class Rectangle
* @constructor
* @param {Number} w Width
* @param {Number} h Height
* @extends {Convex}
*/
function Rectangle(w,h){
var verts = [ vec2.fromValues(-w/2, -h/2),
vec2.fromValues( w/2, -h/2),
vec2.fromValues( w/2, h/2),
vec2.fromValues(-w/2, h/2)];
/**
* Total width of the rectangle
* @property width
* @type {Number}
*/
this.width = w;
/**
* Total height of the rectangle
* @property height
* @type {Number}
*/
this.height = h;
Convex.call(this,verts);
this.type = Shape.RECTANGLE;
};
Rectangle.prototype = new Convex([]);
/**
* Compute moment of inertia
* @method computeMomentOfInertia
* @param {Number} mass
* @return {Number}
*/
Rectangle.prototype.computeMomentOfInertia = function(mass){
var w = this.width,
h = this.height;
return mass * (h*h + w*w) / 12;
};
/**
* Update the bounding radius
* @method updateBoundingRadius
*/
Rectangle.prototype.updateBoundingRadius = function(){
var w = this.width,
h = this.height;
this.boundingRadius = Math.sqrt(w*w + h*h) / 2;
};
var corner1 = vec2.create(),
corner2 = vec2.create(),
corner3 = vec2.create(),
corner4 = vec2.create();
/**
* @method computeAABB
* @param {AABB} out The resulting AABB.
* @param {Array} position
* @param {Number} angle
*/
Rectangle.prototype.computeAABB = function(out, position, angle){
out.setFromPoints(this.vertices,position,angle);
};
Rectangle.prototype.updateArea = function(){
this.area = this.width * this.height;
};
},{"../math/vec2":33,"./Convex":39,"./Shape":45}],45:[function(require,module,exports){
module.exports = Shape;
/**
* Base class for shapes.
* @class Shape
* @constructor
*/
function Shape(type){
this.type = type;
/**
* Shape object identifier.
* @type {Number}
* @property id
*/
this.id = Shape.idCounter++;
/**
* Bounding circle radius of this shape
* @property boundingRadius
* @type {Number}
*/
this.boundingRadius = 0;
/**
* Collision group that this shape belongs to (bit mask). See <a href="http://www.aurelienribon.com/blog/2011/07/box2d-tutorial-collision-filtering/">this tutorial</a>.
* @property collisionGroup
* @type {Number}
* @example
* // Setup bits for each available group
* var PLAYER = Math.pow(2,0),
* ENEMY = Math.pow(2,1),
* GROUND = Math.pow(2,2)
*
* // Put shapes into their groups
* player1Shape.collisionGroup = PLAYER;
* player2Shape.collisionGroup = PLAYER;
* enemyShape .collisionGroup = ENEMY;
* groundShape .collisionGroup = GROUND;
*
* // Assign groups that each shape collide with.
* // Note that the players can collide with ground and enemies, but not with other players.
* player1Shape.collisionMask = ENEMY | GROUND;
* player2Shape.collisionMask = ENEMY | GROUND;
* enemyShape .collisionMask = PLAYER | GROUND;
* groundShape .collisionMask = PLAYER | ENEMY;
*
* @example
* // How collision check is done
* if(shapeA.collisionGroup & shapeB.collisionMask)!=0 && (shapeB.collisionGroup & shapeA.collisionMask)!=0){
* // The shapes will collide
* }
*/
this.collisionGroup = 1;
/**
* Collision mask of this shape. See .collisionGroup.
* @property collisionMask
* @type {Number}
*/
this.collisionMask = 1;
if(type) this.updateBoundingRadius();
/**
* Material to use in collisions for this Shape. If this is set to null, the world will use default material properties instead.
* @property material
* @type {Material}
*/
this.material = null;
/**
* Area of this shape.
* @property area
* @type {Number}
*/
this.area = 0;
/**
* Set to true if you want this shape to be a sensor. A sensor does not generate contacts, but it still reports contact events. This is good if you want to know if a shape is overlapping another shape, without them generating contacts.
* @property {Boolean} sensor
*/
this.sensor = false;
this.updateArea();
};
Shape.idCounter = 0;
/**
* @static
* @property {Number} CIRCLE
*/
Shape.CIRCLE = 1;
/**
* @static
* @property {Number} PARTICLE
*/
Shape.PARTICLE = 2;
/**
* @static
* @property {Number} PLANE
*/
Shape.PLANE = 4;
/**
* @static
* @property {Number} CONVEX
*/
Shape.CONVEX = 8;
/**
* @static
* @property {Number} LINE
*/
Shape.LINE = 16;
/**
* @static
* @property {Number} RECTANGLE
*/
Shape.RECTANGLE = 32;
/**
* @static
* @property {Number} CAPSULE
*/
Shape.CAPSULE = 64;
/**
* @static
* @property {Number} HEIGHTFIELD
*/
Shape.HEIGHTFIELD = 128;
/**
* Should return the moment of inertia around the Z axis of the body given the total mass. See <a href="http://en.wikipedia.org/wiki/List_of_moments_of_inertia">Wikipedia's list of moments of inertia</a>.
* @method computeMomentOfInertia
* @param {Number} mass
* @return {Number} If the inertia is infinity or if the object simply isn't possible to rotate, return 0.
*/
Shape.prototype.computeMomentOfInertia = function(mass){
throw new Error("Shape.computeMomentOfInertia is not implemented in this Shape...");
};
/**
* Returns the bounding circle radius of this shape.
* @method updateBoundingRadius
* @return {Number}
*/
Shape.prototype.updateBoundingRadius = function(){
throw new Error("Shape.updateBoundingRadius is not implemented in this Shape...");
};
/**
* Update the .area property of the shape.
* @method updateArea
*/
Shape.prototype.updateArea = function(){
// To be implemented in all subclasses
};
/**
* Compute the world axis-aligned bounding box (AABB) of this shape.
* @method computeAABB
* @param {AABB} out The resulting AABB.
* @param {Array} position
* @param {Number} angle
*/
Shape.prototype.computeAABB = function(out, position, angle){
// To be implemented in each subclass
};
},{}],46:[function(require,module,exports){
var vec2 = require('../math/vec2')
, Solver = require('./Solver')
, Utils = require('../utils/Utils')
, FrictionEquation = require('../equations/FrictionEquation')
module.exports = GSSolver;
/**
* Iterative Gauss-Seidel constraint equation solver.
*
* @class GSSolver
* @constructor
* @extends Solver
* @param {Object} [options]
* @param {Number} options.iterations
* @param {Number} options.timeStep
* @param {Number} options.stiffness
* @param {Number} options.relaxation
* @param {Number} options.tolerance
*/
function GSSolver(options){
Solver.call(this,options,Solver.GS);
options = options || {};
/**
* The number of iterations to do when solving. More gives better results, but is more expensive.
* @property iterations
* @type {Number}
*/
this.iterations = options.iterations || 10;
/**
* The error tolerance. If the total error is below this limit, the solver will stop. Set to zero for as good solution as possible.
* @property tolerance
* @type {Number}
*/
this.tolerance = options.tolerance || 0;
this.debug = options.debug || false;
this.arrayStep = 30;
this.lambda = new Utils.ARRAY_TYPE(this.arrayStep);
this.Bs = new Utils.ARRAY_TYPE(this.arrayStep);
this.invCs = new Utils.ARRAY_TYPE(this.arrayStep);
/**
* Whether to use .stiffness and .relaxation parameters from the Solver instead of each Equation individually.
* @type {Boolean}
* @property useGlobalEquationParameters
*/
this.useGlobalEquationParameters = true;
/**
* Global equation stiffness. Larger number gives harder contacts, etc, but may also be more expensive to compute, or it will make your simulation explode.
* @property stiffness
* @type {Number}
*/
this.stiffness = 1e6;
/**
* Global equation relaxation. This is the number of timesteps required for a constraint to be resolved. Larger number will give softer contacts. Set to around 3 or 4 for good enough results.
* @property relaxation
* @type {Number}
*/
this.relaxation = 4;
/**
* Set to true to set all right hand side terms to zero when solving. Can be handy for a few applications.
* @property useZeroRHS
* @type {Boolean}
*/
this.useZeroRHS = false;
this.useNormalForceForFriction = false;
/**
* Number of friction iterations to skip. If .skipFrictionIterations=2, then no FrictionEquations will be iterated until the third iteration.
* @property skipFrictionIterations
* @type {Number}
*/
this.skipFrictionIterations = 0;
};
GSSolver.prototype = new Solver();
function setArrayZero(array){
for(var i=0; i!==array.length; i++){
array[i] = 0.0;
}
}
/**
* Solve the system of equations
* @method solve
* @param {Number} h Time step
* @param {World} world World to solve
*/
GSSolver.prototype.solve = function(h,world){
this.sortEquations();
var iter = 0,
maxIter = this.iterations,
skipFrictionIter = this.skipFrictionIterations,
tolSquared = this.tolerance*this.tolerance,
equations = this.equations,
Neq = equations.length,
bodies = world.bodies,
Nbodies = world.bodies.length,
d = this.relaxation,
k = this.stiffness,
eps = 4.0 / (h * h * k * (1 + 4 * d)),
a = 4.0 / (h * (1 + 4 * d)),
b = (4.0 * d) / (1 + 4 * d),
useGlobalParams = this.useGlobalEquationParameters,
add = vec2.add,
set = vec2.set,
useZeroRHS = this.useZeroRHS,
lambda = this.lambda;
// Things that does not change during iteration can be computed once
if(lambda.length < Neq){
lambda = this.lambda = new Utils.ARRAY_TYPE(Neq + this.arrayStep);
this.Bs = new Utils.ARRAY_TYPE(Neq + this.arrayStep);
this.invCs = new Utils.ARRAY_TYPE(Neq + this.arrayStep);
}
setArrayZero(lambda);
var invCs = this.invCs,
Bs = this.Bs,
lambda = this.lambda;
if(!useGlobalParams){
for(var i=0, c; c = equations[i]; i++){
c.updateSpookParams(h);
Bs[i] = c.computeB(c.a,c.b,h);
invCs[i] = c.computeInvC(c.eps);
}
} else {
for(var i=0, c; c = equations[i]; i++){
Bs[i] = c.computeB(a,b,h);
invCs[i] = c.computeInvC(eps);
}
}
var q, B, c, deltalambdaTot,i,j;
if(Neq !== 0){
// Reset vlambda
for(i=0; i!==Nbodies; i++){
bodies[i].resetConstraintVelocity();
}
// Iterate over equations
for(iter=0; iter!==maxIter; iter++){
// Accumulate the total error for each iteration.
deltalambdaTot = 0.0;
for(j=0; j!==Neq; j++){
c = equations[j];
if(c instanceof FrictionEquation && iter < skipFrictionIter)
continue;
var _eps = useGlobalParams ? eps : c.eps;
var deltalambda = GSSolver.iterateEquation(j,c,_eps,Bs,invCs,lambda,useZeroRHS,h,iter,skipFrictionIter,this.useNormalForceForFriction);
deltalambdaTot += Math.abs(deltalambda);
}
// If the total error is small enough - stop iterate
if(deltalambdaTot*deltalambdaTot <= tolSquared) break;
}
// Add result to velocity
for(i=0; i!==Nbodies; i++){
bodies[i].addConstraintVelocity();
}
}
};
GSSolver.iterateEquation = function(j,eq,eps,Bs,invCs,lambda,useZeroRHS,dt,iter,skipFrictionIter,useNormal){
// Compute iteration
var B = Bs[j],
invC = invCs[j],
lambdaj = lambda[j],
GWlambda = eq.computeGWlambda();
if(useNormal && eq instanceof FrictionEquation && iter == skipFrictionIter){
// Rescale the max friction force according to the normal force
eq.maxForce = eq.contactEquation.multiplier * eq.frictionCoefficient * dt;
eq.minForce = -eq.contactEquation.multiplier * eq.frictionCoefficient * dt;
}
var maxForce = eq.maxForce,
minForce = eq.minForce;
if(useZeroRHS) B = 0;
var deltalambda = invC * ( B - GWlambda - eps * lambdaj );
// Clamp if we are not within the min/max interval
var lambdaj_plus_deltalambda = lambdaj + deltalambda;
if(lambdaj_plus_deltalambda < minForce*dt){
deltalambda = minForce*dt - lambdaj;
} else if(lambdaj_plus_deltalambda > maxForce*dt){
deltalambda = maxForce*dt - lambdaj;
}
lambda[j] += deltalambda;
eq.multiplier = lambda[j] / dt;
eq.addToWlambda(deltalambda);
return deltalambda;
};
},{"../equations/FrictionEquation":25,"../math/vec2":33,"../utils/Utils":50,"./Solver":49}],47:[function(require,module,exports){
module.exports = Island;
/**
* An island of bodies connected with equations.
* @class Island
* @constructor
*/
function Island(){
/**
* Current equations in this island.
* @property equations
* @type {Array}
*/
this.equations = [];
/**
* Current bodies in this island.
* @property bodies
* @type {Array}
*/
this.bodies = [];
}
/**
* Clean this island from bodies and equations.
* @method reset
*/
Island.prototype.reset = function(){
this.equations.length = this.bodies.length = 0;
}
/**
* Get all unique bodies in this island.
* @method getBodies
* @return {Array} An array of Body
*/
Island.prototype.getBodies = function(){
var bodies = [],
bodyIds = [],
eqs = this.equations;
for(var i=0; i!==eqs.length; i++){
var eq = eqs[i];
if(bodyIds.indexOf(eq.bi.id)===-1){
bodies.push(eq.bi);
bodyIds.push(eq.bi.id);
}
if(bodyIds.indexOf(eq.bj.id)===-1){
bodies.push(eq.bj);
bodyIds.push(eq.bj.id);
}
}
return bodies;
};
/**
* Solves all constraints in the group of islands.
* @method solve
* @param {Number} dt
* @param {Solver} solver
*/
Island.prototype.solve = function(dt,solver){
var bodies = [];
solver.removeAllEquations();
// Add equations to solver
var numEquations = this.equations.length;
for(var j=0; j!==numEquations; j++){
solver.addEquation(this.equations[j]);
}
var islandBodies = this.getBodies();
var numBodies = islandBodies.length;
for(var j=0; j!==numBodies; j++){
bodies.push(islandBodies[j]);
}
// Solve
solver.solve(dt,{bodies:bodies});
};
},{}],48:[function(require,module,exports){
var Solver = require('./Solver')
, vec2 = require('../math/vec2')
, Island = require('../solver/Island')
, Body = require('../objects/Body')
, STATIC = Body.STATIC
module.exports = IslandSolver;
/**
* Splits the system of bodies and equations into independent islands
*
* @class IslandSolver
* @constructor
* @param {Solver} subsolver
* @param {Object} options
* @extends Solver
*/
function IslandSolver(subsolver,options){
Solver.call(this,options,Solver.ISLAND);
var that = this;
/**
* The solver used in the workers.
* @property subsolver
* @type {Solver}
*/
this.subsolver = subsolver;
/**
* Number of islands. Read only.
* @property numIslands
* @type {number}
*/
this.numIslands = 0;
// Pooling of node objects saves some GC load
this._nodePool = [];
this._islandPool = [];
/**
* Fires before an island is solved.
* @event beforeSolveIsland
* @param {Island} island
*/
this.beforeSolveIslandEvent = {
type : "beforeSolveIsland",
island : null,
};
};
IslandSolver.prototype = new Solver();
function getUnvisitedNode(nodes){
var Nnodes = nodes.length;
for(var i=0; i!==Nnodes; i++){
var node = nodes[i];
if(!node.visited && !(node.body.motionState == STATIC)){ // correct?
return node;
}
}
return false;
}
function visitFunc(node,bds,eqs){
bds.push(node.body);
var Neqs = node.eqs.length;
for(var i=0; i!==Neqs; i++){
var eq = node.eqs[i];
if(eqs.indexOf(eq) === -1){
eqs.push(eq);
}
}
}
var queue = [];
function bfs(root,visitFunc,bds,eqs){
queue.length = 0;
queue.push(root);
root.visited = true;
visitFunc(root,bds,eqs);
while(queue.length) {
var node = queue.pop();
// Loop over unvisited child nodes
var child;
while((child = getUnvisitedNode(node.children))) {
child.visited = true;
visitFunc(child,bds,eqs);
queue.push(child);
}
}
}
var tmpArray = [],
tmpArray2 = [],
tmpArray3 = [],
tmpArray4 = [];
/**
* Solves the full system.
* @method solve
* @param {Number} dt
* @param {World} world
*/
IslandSolver.prototype.solve = function(dt,world){
var nodes = tmpArray,
bodies=world.bodies,
equations=this.equations,
Neq=equations.length,
Nbodies=bodies.length,
subsolver=this.subsolver,
workers = this._workers,
workerData = this._workerData,
workerIslandGroups = this._workerIslandGroups,
islandPool = this._islandPool;
tmpArray.length = 0;
// Create needed nodes, reuse if possible
for(var i=0; i!==Nbodies; i++){
if(this._nodePool.length)
nodes.push( this._nodePool.pop() );
else {
nodes.push({
body:bodies[i],
children:[],
eqs:[],
visited:false
});
}
}
// Reset node values
for(var i=0; i!==Nbodies; i++){
var node = nodes[i];
node.body = bodies[i];
node.children.length = 0;
node.eqs.length = 0;
node.visited = false;
}
// Add connectivity data. Each equation connects 2 bodies.
for(var k=0; k!==Neq; k++){
var eq=equations[k],
i=bodies.indexOf(eq.bi),
j=bodies.indexOf(eq.bj),
ni=nodes[i],
nj=nodes[j];
ni.children.push(nj);
ni.eqs.push(eq);
nj.children.push(ni);
nj.eqs.push(eq);
}
// The BFS search algorithm needs a traversal function. What we do is gather all bodies and equations connected.
var child, n=0, eqs=tmpArray2, bds=tmpArray3;
eqs.length = 0;
bds.length = 0;
// Get islands
var islands = tmpArray4;
islands.length = 0;
while((child = getUnvisitedNode(nodes))){
var island = islandPool.length ? islandPool.pop() : new Island();
eqs.length = 0;
bds.length = 0;
bfs(child,visitFunc,bds,eqs); // run search algo to gather an island of bodies
// Add equations to island
var Neqs = eqs.length;
for(var i=0; i!==Neqs; i++){
var eq = eqs[i];
island.equations.push(eq);
}
n++;
islands.push(island);
}
this.numIslands = n;
// Solve islands
var e = this.beforeSolveIslandEvent;
for(var i=0; i<islands.length; i++){
var island = islands[i];
e.island = island;
this.emit(e);
island.solve(dt,this.subsolver);
// Turn it back to the pool
island.reset();
islandPool.push(island);
}
};
},{"../math/vec2":33,"../objects/Body":34,"../solver/Island":47,"./Solver":49}],49:[function(require,module,exports){
var Utils = require('../utils/Utils')
, EventEmitter = require('../events/EventEmitter')
module.exports = Solver;
/**
* Base class for constraint solvers.
* @class Solver
* @constructor
* @extends {EventEmitter}
*/
function Solver(options,type){
options = options || {};
EventEmitter.call(this);
this.type = type;
/**
* Current equations in the solver.
*
* @property equations
* @type {Array}
*/
this.equations = [];
/**
* Function that is used to sort all equations before each solve.
* @property equationSortFunction
* @type {function|boolean}
*/
this.equationSortFunction = options.equationSortFunction || false;
};
Solver.prototype = new EventEmitter();
/**
* Method to be implemented in each subclass
* @method solve
* @param {Number} dt
* @param {World} world
*/
Solver.prototype.solve = function(dt,world){
throw new Error("Solver.solve should be implemented by subclasses!");
};
/**
* Sort all equations using the .equationSortFunction. Should be called by subclasses before solving.
* @method sortEquations
*/
Solver.prototype.sortEquations = function(){
if(this.equationSortFunction)
this.equations.sort(this.equationSortFunction);
};
/**
* Add an equation to be solved.
*
* @method addEquation
* @param {Equation} eq
*/
Solver.prototype.addEquation = function(eq){
if(eq.enabled)
this.equations.push(eq);
};
/**
* Add equations. Same as .addEquation, but this time the argument is an array of Equations
*
* @method addEquations
* @param {Array} eqs
*/
Solver.prototype.addEquations = function(eqs){
//Utils.appendArray(this.equations,eqs);
for(var i=0, N=eqs.length; i!==N; i++){
var eq = eqs[i];
if(eq.enabled)
this.equations.push(eq);
}
};
/**
* Remove an equation.
*
* @method removeEquation
* @param {Equation} eq
*/
Solver.prototype.removeEquation = function(eq){
var i = this.equations.indexOf(eq);
if(i!=-1)
this.equations.splice(i,1);
};
/**
* Remove all currently added equations.
*
* @method removeAllEquations
*/
Solver.prototype.removeAllEquations = function(){
this.equations.length=0;
};
Solver.GS=1;
Solver.ISLAND=2;
},{"../events/EventEmitter":28,"../utils/Utils":50}],50:[function(require,module,exports){
module.exports = Utils;
/**
* Misc utility functions
* @class Utils
* @constructor
*/
function Utils(){};
/**
* Append the values in array b to the array a. See <a href="http://stackoverflow.com/questions/1374126/how-to-append-an-array-to-an-existing-javascript-array/1374131#1374131">this</a> for an explanation.
* @method appendArray
* @static
* @param {Array} a
* @param {Array} b
*/
Utils.appendArray = function(a,b){
if (b.length < 150000) {
a.push.apply(a, b)
} else {
for (var i = 0, len = b.length; i !== len; ++i) {
a.push(b[i]);
}
}
};
/**
* Garbage free Array.splice(). Does not allocate a new array.
* @method splice
* @static
* @param {Array} array
* @param {Number} index
* @param {Number} howmany
*/
Utils.splice = function(array,index,howmany){
howmany = howmany || 1;
for (var i=index, len=array.length-howmany; i < len; i++)
array[i] = array[i + howmany];
array.length = len;
};
/**
* The array type to use for internal numeric computations.
* @type {Array}
* @static
* @property ARRAY_TYPE
*/
Utils.ARRAY_TYPE = Float32Array || Array;
},{}],51:[function(require,module,exports){
var GSSolver = require('../solver/GSSolver')
, NaiveBroadphase = require('../collision/NaiveBroadphase')
, vec2 = require('../math/vec2')
, Circle = require('../shapes/Circle')
, Rectangle = require('../shapes/Rectangle')
, Convex = require('../shapes/Convex')
, Line = require('../shapes/Line')
, Plane = require('../shapes/Plane')
, Capsule = require('../shapes/Capsule')
, Particle = require('../shapes/Particle')
, EventEmitter = require('../events/EventEmitter')
, Body = require('../objects/Body')
, Spring = require('../objects/Spring')
, Material = require('../material/Material')
, ContactMaterial = require('../material/ContactMaterial')
, DistanceConstraint = require('../constraints/DistanceConstraint')
, LockConstraint = require('../constraints/LockConstraint')
, RevoluteConstraint = require('../constraints/RevoluteConstraint')
, PrismaticConstraint = require('../constraints/PrismaticConstraint')
, pkg = require('../../package.json')
, Broadphase = require('../collision/Broadphase')
, Narrowphase = require('../collision/Narrowphase')
, Utils = require('../utils/Utils')
module.exports = World;
var currentVersion = pkg.version.split(".").slice(0,2).join("."); // "X.Y"
if(typeof performance === 'undefined')
performance = {};
if(!performance.now){
var nowOffset = Date.now();
if (performance.timing && performance.timing.navigationStart){
nowOffset = performance.timing.navigationStart
}
performance.now = function(){
return Date.now() - nowOffset;
}
}
/**
* The dynamics world, where all bodies and constraints lives.
*
* @class World
* @constructor
* @param {Object} [options]
* @param {Solver} options.solver Defaults to GSSolver.
* @param {Float32Array} options.gravity Defaults to [0,-9.78]
* @param {Broadphase} options.broadphase Defaults to NaiveBroadphase
* @param {Boolean} options.doProfiling
* @extends {EventEmitter}
*/
function World(options){
EventEmitter.apply(this);
options = options || {};
/**
* All springs in the world.
*
* @property springs
* @type {Array}
*/
this.springs = [];
/**
* All bodies in the world.
*
* @property bodies
* @type {Array}
*/
this.bodies = [];
/**
* The solver used to satisfy constraints and contacts.
*
* @property solver
* @type {Solver}
*/
this.solver = options.solver || new GSSolver();
/**
* The narrowphase to use to generate contacts.
*
* @property narrowphase
* @type {Narrowphase}
*/
this.narrowphase = new Narrowphase(this);
/**
* Gravity in the world. This is applied on all bodies in the beginning of each step().
*
* @property
* @type {Float32Array}
*/
this.gravity = options.gravity || vec2.fromValues(0, -9.78);
/**
* Whether to do timing measurements during the step() or not.
*
* @property doPofiling
* @type {Boolean}
*/
this.doProfiling = options.doProfiling || false;
/**
* How many millisecconds the last step() took. This is updated each step if .doProfiling is set to true.
*
* @property lastStepTime
* @type {Number}
*/
this.lastStepTime = 0.0;
/**
* The broadphase algorithm to use.
*
* @property broadphase
* @type {Broadphase}
*/
this.broadphase = options.broadphase || new NaiveBroadphase();
this.broadphase.setWorld(this);
/**
* User-added constraints.
*
* @property constraints
* @type {Array}
*/
this.constraints = [];
/**
* Friction between colliding bodies. This value is used if no matching ContactMaterial is found for a Material pair.
* @property defaultFriction
* @type {Number}
*/
this.defaultFriction = 0.3;
/**
* Default coefficient of restitution between colliding bodies. This value is used if no matching ContactMaterial is found for a Material pair.
* @property defaultRestitution
* @type {Number}
*/
this.defaultRestitution = 0.0;
this.defaultMaterial = new Material();
this.defaultContactMaterial = new ContactMaterial(this.defaultMaterial,this.defaultMaterial);
/**
* For keeping track of what time step size we used last step
* @property lastTimeStep
* @type {Number}
*/
this.lastTimeStep = 1/60;
/**
* Enable to automatically apply spring forces each step.
* @property applySpringForces
* @type {Boolean}
*/
this.applySpringForces = true;
/**
* Enable to automatically apply body damping each step.
* @property applyDamping
* @type {Boolean}
*/
this.applyDamping = true;
/**
* Enable to automatically apply gravity each step.
* @property applyGravity
* @type {Boolean}
*/
this.applyGravity = true;
/**
* Enable/disable constraint solving in each step.
* @property solveConstraints
* @type {Boolean}
*/
this.solveConstraints = true;
/**
* The ContactMaterials added to the World.
* @property contactMaterials
* @type {Array}
*/
this.contactMaterials = [];
/**
* World time.
* @property time
* @type {Number}
*/
this.time = 0.0;
this.fixedStepTime = 0.0;
/**
* Set to true if you want to the world to emit the "impact" event. Turning this off could improve performance.
* @property emitImpactEvent
* @type {Boolean}
*/
this.emitImpactEvent = true;
// Id counters
this._constraintIdCounter = 0;
this._bodyIdCounter = 0;
/**
* Fired after the step().
* @event postStep
*/
this.postStepEvent = {
type : "postStep",
};
/**
* @event addBody
* @param {Body} body
*/
this.addBodyEvent = {
type : "addBody",
body : null
};
/**
* @event removeBody
* @param {Body} body
*/
this.removeBodyEvent = {
type : "removeBody",
body : null
};
/**
* Fired when a spring is added to the world.
* @event addSpring
* @param {Spring} spring
*/
this.addSpringEvent = {
type : "addSpring",
spring : null,
};
/**
* Fired when a first contact is created between two bodies. This event is fired after the step has been done.
* @event impact
* @param {Body} bodyA
* @param {Body} bodyB
*/
this.impactEvent = {
type: "impact",
bodyA : null,
bodyB : null,
shapeA : null,
shapeB : null,
contactEquation : null,
};
/**
* 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 postBroadphase
* @param {Array} pairs 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.
*/
this.postBroadphaseEvent = {
type:"postBroadphase",
pairs:null,
};
/**
* Enable / disable automatic body sleeping
* @property allowSleep
* @type {Boolean}
*/
this.enableBodySleeping = false;
/**
* Fired when two shapes starts start to overlap. Fired in the narrowphase, during step.
* @event beginContact
* @param {Shape} shapeA
* @param {Shape} shapeB
* @param {Body} bodyA
* @param {Body} bodyB
* @param {Array} contactEquations
*/
this.beginContactEvent = {
type:"beginContact",
shapeA : null,
shapeB : null,
bodyA : null,
bodyB : null,
contactEquations : [],
};
/**
* Fired when two shapes stop overlapping, after the narrowphase (during step).
* @event endContact
* @param {Shape} shapeA
* @param {Shape} shapeB
* @param {Body} bodyA
* @param {Body} bodyB
* @param {Array} contactEquations
*/
this.endContactEvent = {
type:"endContact",
shapeA : null,
shapeB : null,
bodyA : null,
bodyB : null,
};
/**
* Fired just before equations are added to the solver to be solved. Can be used to control what equations goes into the solver.
* @event preSolve
* @param {Array} contactEquations An array of contacts to be solved.
* @param {Array} frictionEquations An array of friction equations to be solved.
*/
this.preSolveEvent = {
type:"preSolve",
contactEquations:null,
frictionEquations:null,
};
// For keeping track of overlapping shapes
this.overlappingShapesLastState = { keys:[] };
this.overlappingShapesCurrentState = { keys:[] };
this.overlappingShapeLookup = { keys:[] };
};
World.prototype = new Object(EventEmitter.prototype);
/**
* Add a constraint to the simulation.
*
* @method addConstraint
* @param {Constraint} c
*/
World.prototype.addConstraint = function(c){
this.constraints.push(c);
};
/**
* Add a ContactMaterial to the simulation.
* @method addContactMaterial
* @param {ContactMaterial} contactMaterial
*/
World.prototype.addContactMaterial = function(contactMaterial){
this.contactMaterials.push(contactMaterial);
};
/**
* Removes a contact material
*
* @method removeContactMaterial
* @param {ContactMaterial} cm
*/
World.prototype.removeContactMaterial = function(cm){
var idx = this.contactMaterials.indexOf(cm);
if(idx!==-1)
Utils.splice(this.contactMaterials,idx,1);
};
/**
* Get a contact material given two materials
* @method getContactMaterial
* @param {Material} materialA
* @param {Material} materialB
* @return {ContactMaterial} The matching ContactMaterial, or false on fail.
* @todo Use faster hash map to lookup from material id's
*/
World.prototype.getContactMaterial = function(materialA,materialB){
var cmats = this.contactMaterials;
for(var i=0, N=cmats.length; i!==N; i++){
var cm = cmats[i];
if( (cm.materialA === materialA) && (cm.materialB === materialB) ||
(cm.materialA === materialB) && (cm.materialB === materialA) )
return cm;
}
return false;
};
/**
* Removes a constraint
*
* @method removeConstraint
* @param {Constraint} c
*/
World.prototype.removeConstraint = function(c){
var idx = this.constraints.indexOf(c);
if(idx!==-1){
Utils.splice(this.constraints,idx,1);
}
};
var step_r = vec2.create(),
step_runit = vec2.create(),
step_u = vec2.create(),
step_f = vec2.create(),
step_fhMinv = vec2.create(),
step_velodt = vec2.create(),
step_mg = vec2.create(),
xiw = vec2.fromValues(0,0),
xjw = vec2.fromValues(0,0),
zero = vec2.fromValues(0,0);
/**
* 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.
*
* @method step
* @param {Number} dt The fixed time step size to use.
* @param {Number} [timeSinceLastCalled=0] The time elapsed since the function was last called.
* @param {Number} [maxSubSteps=10] Maximum number of fixed steps to take per function call.
*
* @example
* // fixed timestepping without interpolation
* var world = new World();
* world.step(0.01);
*/
World.prototype.step = function(dt,timeSinceLastCalled,maxSubSteps){
maxSubSteps = maxSubSteps || 10;
timeSinceLastCalled = timeSinceLastCalled || 0;
if(timeSinceLastCalled == 0){ // Fixed, simple stepping
this.internalStep(dt);
// Increment time
this.time += dt;
} else {
var internalSteps = Math.floor( (this.time+timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
internalSteps = Math.min(internalSteps,maxSubSteps);
for(var i=0; i<internalSteps; i++){
this.internalStep(dt);
/*
for(var j=0; j!==this.bodies.length; j++){
// Store state for interpolation
// Todo
var b = this.bodies[j];
}
*/
}
// Increment time
this.time += timeSinceLastCalled;
this.fixedStepTime += internalSteps * dt;
// Compute the interpolation data
var h = this.time - this.fixedStepTime - dt;
for(var j=0; j!==this.bodies.length; j++){
// Store interpolated state
var b = this.bodies[j];
b.interpolatedPosition[0] = b.position[0] + b.velocity[0]*h;
b.interpolatedPosition[1] = b.position[1] + b.velocity[1]*h;
}
}
};
World.prototype.internalStep = function(dt){
var that = this,
doProfiling = this.doProfiling,
Nsprings = this.springs.length,
springs = this.springs,
bodies = this.bodies,
g = this.gravity,
solver = this.solver,
Nbodies = this.bodies.length,
broadphase = this.broadphase,
np = this.narrowphase,
constraints = this.constraints,
t0, t1,
fhMinv = step_fhMinv,
velodt = step_velodt,
mg = step_mg,
scale = vec2.scale,
add = vec2.add,
rotate = vec2.rotate;
this.lastTimeStep = dt;
if(doProfiling){
t0 = performance.now();
}
var glen = vec2.length(this.gravity);
// Add gravity to bodies
if(this.applyGravity){
for(var i=0; i!==Nbodies; i++){
var b = bodies[i],
fi = b.force;
if(b.motionState != Body.DYNAMIC)
continue;
vec2.scale(mg,g,b.mass*b.gravityScale); // F=m*g
add(fi,fi,mg);
}
}
// Add spring forces
if(this.applySpringForces){
for(var i=0; i!==Nsprings; i++){
var s = springs[i];
s.applyForce();
}
}
if(this.applyDamping){
for(var i=0; i!==Nbodies; i++){
var b = bodies[i];
if(b.motionState == Body.DYNAMIC)
b.applyDamping(dt);
}
}
// Broadphase
var result = broadphase.getCollisionPairs(this);
// postBroadphase event
this.postBroadphaseEvent.pairs = result;
this.emit(this.postBroadphaseEvent);
// Narrowphase
np.reset(this);
for(var i=0, Nresults=result.length; i!==Nresults; i+=2){
var bi = result[i],
bj = result[i+1];
// Loop over all shapes of body i
for(var k=0, Nshapesi=bi.shapes.length; k!==Nshapesi; k++){
var si = bi.shapes[k],
xi = bi.shapeOffsets[k],
ai = bi.shapeAngles[k];
// All shapes of body j
for(var l=0, Nshapesj=bj.shapes.length; l!==Nshapesj; l++){
var sj = bj.shapes[l],
xj = bj.shapeOffsets[l],
aj = bj.shapeAngles[l];
/*
var mu = this.defaultFriction,
restitution = this.defaultRestitution,
surfaceVelocity = 0;
*/
var cm = this.defaultContactMaterial;
if(si.material && sj.material){
var tmp = this.getContactMaterial(si.material,sj.material);
if(tmp){
cm = tmp;
/*
mu = cm.friction;
restitution = cm.restitution;
surfaceVelocity = cm.surfaceVelocity;
*/
}
}
this.runNarrowphase(np,bi,si,xi,ai,bj,sj,xj,aj,cm,glen);
}
}
}
// Emit shape end overlap events
var last = this.overlappingShapesLastState;
for(var i=0; i!==last.keys.length; i++){
var key = last.keys[i];
if(last[key]!==true)
continue;
if(!this.overlappingShapesCurrentState[key]){
// Not overlapping in current state, but in last state. Emit event!
var e = this.endContactEvent;
// Add shapes to the event object
e.shapeA = last[key+"_shapeA"];
e.shapeB = last[key+"_shapeB"];
e.bodyA = last[key+"_bodyA"];
e.bodyB = last[key+"_bodyB"];
this.emit(e);
}
}
// Clear last object
for(var i=0; i!==last.keys.length; i++)
delete last[last.keys[i]];
last.keys.length = 0;
// Transfer from new object to old
var current = this.overlappingShapesCurrentState;
for(var i=0; i!==current.keys.length; i++){
last[current.keys[i]] = current[current.keys[i]];
last.keys.push(current.keys[i]);
}
// Clear current object
for(var i=0; i!==current.keys.length; i++)
delete current[current.keys[i]];
current.keys.length = 0;
var preSolveEvent = this.preSolveEvent;
preSolveEvent.contactEquations = np.contactEquations;
preSolveEvent.frictionEquations = np.frictionEquations;
this.emit(preSolveEvent);
// Add contact equations to solver
solver.addEquations(np.contactEquations);
solver.addEquations(np.frictionEquations);
// Add user-defined constraint equations
var Nconstraints = constraints.length;
for(i=0; i!==Nconstraints; i++){
var c = constraints[i];
c.update();
solver.addEquations(c.equations);
}
if(this.solveConstraints)
solver.solve(dt,this);
solver.removeAllEquations();
// Step forward
for(var i=0; i!==Nbodies; i++){
var body = bodies[i];
if(body.sleepState !== Body.SLEEPING && body.motionState!=Body.STATIC){
World.integrateBody(body,dt);
}
}
// Reset force
for(var i=0; i!==Nbodies; i++){
bodies[i].setZeroForce();
}
if(doProfiling){
t1 = performance.now();
that.lastStepTime = t1-t0;
}
// Emit impact event
if(this.emitImpactEvent){
var ev = this.impactEvent;
for(var i=0; i!==np.contactEquations.length; i++){
var eq = np.contactEquations[i];
if(eq.firstImpact){
ev.bodyA = eq.bi;
ev.bodyB = eq.bj;
ev.shapeA = eq.shapeA;
ev.shapeB = eq.shapeB;
ev.contactEquation = eq;
this.emit(ev);
}
}
}
// Sleeping update
if(this.enableBodySleeping){
for(i=0; i!==Nbodies; i++){
bodies[i].sleepTick(this.time);
}
}
this.emit(this.postStepEvent);
};
var ib_fhMinv = vec2.create();
var ib_velodt = vec2.create();
/**
* Move a body forward in time.
* @static
* @method integrateBody
* @param {Body} body
* @param {Number} dt
*/
World.integrateBody = function(body,dt){
var minv = body.invMass,
f = body.force,
pos = body.position,
velo = body.velocity;
// Angular step
if(!body.fixedRotation){
body.angularVelocity += body.angularForce * body.invInertia * dt;
body.angle += body.angularVelocity * dt;
}
// Linear step
vec2.scale(ib_fhMinv,f,dt*minv);
vec2.add(velo,ib_fhMinv,velo);
vec2.scale(ib_velodt,velo,dt);
vec2.add(pos,pos,ib_velodt);
body.aabbNeedsUpdate = true;
};
/**
* Runs narrowphase for the shape pair i and j.
* @method runNarrowphase
* @param {Narrowphase} np
* @param {Body} bi
* @param {Shape} si
* @param {Array} xi
* @param {Number} ai
* @param {Body} bj
* @param {Shape} sj
* @param {Array} xj
* @param {Number} aj
* @param {Number} mu
*/
World.prototype.runNarrowphase = function(np,bi,si,xi,ai,bj,sj,xj,aj,cm,glen){ /* mu,restitution,surfaceVelocity */
if(!((si.collisionGroup & sj.collisionMask) !== 0 && (sj.collisionGroup & si.collisionMask) !== 0))
return;
/*
var reducedMass = bi.invMass + bj.invMass;
if(reducedMass > 0)
reducedMass = 1/reducedMass;
*/
// Get world position and angle of each shape
vec2.rotate(xiw, xi, bi.angle);
vec2.rotate(xjw, xj, bj.angle);
vec2.add(xiw, xiw, bi.position);
vec2.add(xjw, xjw, bj.position);
var aiw = ai + bi.angle;
var ajw = aj + bj.angle;
// Run narrowphase
np.enableFriction = cm.friction > 0;
np.frictionCoefficient = cm.friction;
var reducedMass;
if(bi.motionState == Body.STATIC || bi.motionState == Body.KINEMATIC)
reducedMass = bj.mass;
else if(bj.motionState == Body.STATIC || bj.motionState == Body.KINEMATIC)
reducedMass = bi.mass;
else
reducedMass = (bi.mass*bj.mass)/(bi.mass+bj.mass);
np.slipForce = cm.friction*glen*reducedMass;
np.restitution = cm.restitution;
np.surfaceVelocity = cm.surfaceVelocity;
np.frictionStiffness = cm.frictionStiffness;
np.frictionRelaxation = cm.frictionRelaxation;
np.stiffness = cm.stiffness;
np.relaxation = cm.relaxation;
var resolver = np[si.type | sj.type],
numContacts = 0;
if (resolver) {
var sensor = si.sensor || sj.sensor;
if (si.type < sj.type) {
numContacts = resolver.call(np, bi,si,xiw,aiw, bj,sj,xjw,ajw, sensor);
} else {
numContacts = resolver.call(np, bj,sj,xjw,ajw, bi,si,xiw,aiw, sensor);
}
if(numContacts){
var key = si.id < sj.id ? si.id+" "+ sj.id : sj.id+" "+ si.id;
if(!this.overlappingShapesLastState[key]){
// Report new shape overlap
var e = this.beginContactEvent;
e.shapeA = si;
e.shapeB = sj;
e.bodyA = bi;
e.bodyB = bj;
if(typeof(numContacts)=="number"){
// Add contacts to the event object
e.contactEquations.length = 0;
for(var i=np.contactEquations.length-numContacts; i<np.contactEquations.length; i++)
e.contactEquations.push(np.contactEquations[i]);
}
this.emit(e);
}
// Store current contact state
var current = this.overlappingShapesCurrentState;
if(!current[key]){
current[key] = true;
current.keys.push(key);
// Also store shape & body data
current[key+"_shapeA"] = si;
current.keys.push(key+"_shapeA");
current[key+"_shapeB"] = sj;
current.keys.push(key+"_shapeB");
current[key+"_bodyA"] = bi;
current.keys.push(key+"_bodyA");
current[key+"_bodyB"] = bj;
current.keys.push(key+"_bodyB");
}
}
}
};
/**
* Add a spring to the simulation
*
* @method addSpring
* @param {Spring} s
*/
World.prototype.addSpring = function(s){
this.springs.push(s);
this.addSpringEvent.spring = s;
this.emit(this.addSpringEvent);
};
/**
* Remove a spring
*
* @method removeSpring
* @param {Spring} s
*/
World.prototype.removeSpring = function(s){
var idx = this.springs.indexOf(s);
if(idx===-1)
Utils.splice(this.springs,idx,1);
};
/**
* Add a body to the simulation
*
* @method addBody
* @param {Body} body
*
* @example
* var world = new World(),
* body = new Body();
* world.addBody(body);
*
*/
World.prototype.addBody = function(body){
if(body.world)
throw new Error("This body is already added to a World.");
this.bodies.push(body);
body.world = this;
this.addBodyEvent.body = body;
this.emit(this.addBodyEvent);
};
/**
* Remove a body from the simulation
*
* @method removeBody
* @param {Body} body
*/
World.prototype.removeBody = function(body){
if(body.world !== this)
throw new Error("The body was never added to this World, cannot remove it.");
body.world = null;
var idx = this.bodies.indexOf(body);
if(idx!==-1){
Utils.splice(this.bodies,idx,1);
this.removeBodyEvent.body = body;
body.resetConstraintVelocity();
this.emit(this.removeBodyEvent);
}
};
/**
* Get a body by its id.
* @method getBodyById
* @return {Body|Boolean} The body, or false if it was not found.
*/
World.prototype.getBodyById = function(id){
var bodies = this.bodies;
for(var i=0; i<bodies.length; i++){
var b = bodies[i];
if(b.id === id)
return b;
}
return false;
};
/**
* Convert the world to a JSON-serializable Object.
*
* @method toJSON
* @return {Object}
* @deprecated Should use Serializer instead.
*/
World.prototype.toJSON = function(){
var json = {
p2 : currentVersion,
bodies : [],
springs : [],
solver : {},
gravity : v2a(this.gravity),
broadphase : {},
constraints : [],
contactMaterials : [],
};
// Serialize springs
for(var i=0; i!==this.springs.length; i++){
var s = this.springs[i];
json.springs.push({
bodyA : this.bodies.indexOf(s.bodyA),
bodyB : this.bodies.indexOf(s.bodyB),
stiffness : s.stiffness,
damping : s.damping,
restLength : s.restLength,
localAnchorA : v2a(s.localAnchorA),
localAnchorB : v2a(s.localAnchorB),
});
}
// Serialize constraints
for(var i=0; i<this.constraints.length; i++){
var c = this.constraints[i];
var jc = {
bodyA : this.bodies.indexOf(c.bodyA),
bodyB : this.bodies.indexOf(c.bodyB),
}
if(c instanceof DistanceConstraint){
jc.type = "DistanceConstraint";
jc.distance = c.distance;
jc.maxForce = c.getMaxForce();
} else if(c instanceof RevoluteConstraint){
jc.type = "RevoluteConstraint";
jc.pivotA = v2a(c.pivotA);
jc.pivotB = v2a(c.pivotB);
jc.maxForce = c.maxForce;
jc.motorSpeed = c.getMotorSpeed(); // False if motor is disabled, otherwise number.
jc.lowerLimit = c.lowerLimit;
jc.lowerLimitEnabled = c.lowerLimitEnabled;
jc.upperLimit = c.upperLimit;
jc.upperLimitEnabled = c.upperLimitEnabled;
} else if(c instanceof PrismaticConstraint){
jc.type = "PrismaticConstraint";
jc.localAxisA = v2a(c.localAxisA);
jc.localAnchorA = v2a(c.localAnchorA);
jc.localAnchorB = v2a(c.localAnchorB);
jc.maxForce = c.maxForce;
} else if(c instanceof LockConstraint){
jc.type = "LockConstraint";
jc.localOffsetB = v2a(c.localOffsetB);
jc.localAngleB = c.localAngleB;
jc.maxForce = c.maxForce;
} else {
console.error("Constraint not supported yet!");
continue;
}
json.constraints.push(jc);
}
// Serialize bodies
for(var i=0; i!==this.bodies.length; i++){
var b = this.bodies[i],
ss = b.shapes,
jsonShapes = [];
for(var j=0; j<ss.length; j++){
var s = ss[j],
jsonShape;
// Check type
if(s instanceof Circle){
jsonShape = {
type : "Circle",
radius : s.radius,
};
} else if(s instanceof Plane){
jsonShape = { type : "Plane", };
} else if(s instanceof Particle){
jsonShape = { type : "Particle", };
} else if(s instanceof Line){
jsonShape = { type : "Line",
length : s.length };
} else if(s instanceof Rectangle){
jsonShape = { type : "Rectangle",
width : s.width,
height : s.height };
} else if(s instanceof Convex){
var verts = [];
for(var k=0; k<s.vertices.length; k++)
verts.push(v2a(s.vertices[k]));
jsonShape = { type : "Convex",
verts : verts };
} else if(s instanceof Capsule){
jsonShape = { type : "Capsule",
length : s.length,
radius : s.radius };
} else {
throw new Error("Shape type not supported yet!");
}
jsonShape.offset = v2a(b.shapeOffsets[j]);
jsonShape.angle = b.shapeAngles[j];
jsonShape.collisionGroup = s.collisionGroup;
jsonShape.collisionMask = s.collisionMask;
jsonShape.material = s.material && {
id : s.material.id,
};
jsonShapes.push(jsonShape);
}
json.bodies.push({
id : b.id,
mass : b.mass,
angle : b.angle,
position : v2a(b.position),
velocity : v2a(b.velocity),
angularVelocity : b.angularVelocity,
force : v2a(b.force),
shapes : jsonShapes,
concavePath : b.concavePath,
});
}
// Serialize contactmaterials
for(var i=0; i<this.contactMaterials.length; i++){
var cm = this.contactMaterials[i];
json.contactMaterials.push({
id : cm.id,
materialA : cm.materialA.id, // Note: Reference by id!
materialB : cm.materialB.id,
friction : cm.friction,
restitution : cm.restitution,
stiffness : cm.stiffness,
relaxation : cm.relaxation,
frictionStiffness : cm.frictionStiffness,
frictionRelaxation : cm.frictionRelaxation,
});
}
return json;
function v2a(v){
if(!v) return v;
return [v[0],v[1]];
}
};
/**
* Upgrades a JSON object to current version
* @method upgradeJSON
* @param {Object} json
* @return {Object|Boolean} New json object, or false on failure.
*/
World.upgradeJSON = function(json){
if(!json || !json.p2)
return false;
// Clone the json object
json = JSON.parse(JSON.stringify(json));
// Check version
switch(json.p2){
case currentVersion:
// We are at latest json version
return json;
case "0.3":
// Changes:
// - Started caring about versioning
// - Added LockConstraint type
// Can't do much about that now though. Ignore.
// Changed PrismaticConstraint arguments...
for(var i=0; i<json.constraints.length; i++){
var jc = json.constraints[i];
if(jc.type=="PrismaticConstraint"){
// ...from these...
delete jc.localAxisA;
delete jc.localAxisB;
// ...to these. We cant make up anything good here, just do something
jc.localAxisA = [1,0];
jc.localAnchorA = [0,0];
jc.localAnchorB = [0,0];
}
}
// Upgrade version number
json.p2 = "0.4";
break;
}
return World.upgradeJSON(json);
};
/**
* Load a scene from a serialized state in JSON format.
*
* @method fromJSON
* @param {Object} json
* @return {Boolean} True on success, else false.
*/
World.prototype.fromJSON = function(json){
this.clear();
json = World.upgradeJSON(json);
// Upgrade failed.
if(!json) return false;
if(!json.p2)
return false;
// Set gravity
vec2.copy(this.gravity, json.gravity);
var bodies = this.bodies;
// Load bodies
var id2material = {};
for(var i=0; i!==json.bodies.length; i++){
var jb = json.bodies[i],
jss = jb.shapes;
var b = new Body({
mass : jb.mass,
position : jb.position,
angle : jb.angle,
velocity : jb.velocity,
angularVelocity : jb.angularVelocity,
force : jb.force,
});
b.id = jb.id;
for(var j=0; j<jss.length; j++){
var shape, js=jss[j];
switch(js.type){
case "Circle": shape = new Circle(js.radius); break;
case "Plane": shape = new Plane(); break;
case "Particle": shape = new Particle(); break;
case "Line": shape = new Line(js.length); break;
case "Rectangle": shape = new Rectangle(js.width,js.height); break;
case "Convex": shape = new Convex(js.verts); break;
case "Capsule": shape = new Capsule(js.length, js.radius); break;
default:
throw new Error("Shape type not supported: "+js.type);
break;
}
shape.collisionMask = js.collisionMask;
shape.collisionGroup = js.collisionGroup;
shape.material = js.material;
if(shape.material){
shape.material = new Material();
shape.material.id = js.material.id;
id2material[shape.material.id+""] = shape.material;
}
b.addShape(shape,js.offset,js.angle);
}
if(jb.concavePath)
b.concavePath = jb.concavePath;
this.addBody(b);
}
// Load springs
for(var i=0; i<json.springs.length; i++){
var js = json.springs[i];
var s = new Spring(bodies[js.bodyA], bodies[js.bodyB], {
stiffness : js.stiffness,
damping : js.damping,
restLength : js.restLength,
localAnchorA : js.localAnchorA,
localAnchorB : js.localAnchorB,
});
this.addSpring(s);
}
// Load contact materials
for(var i=0; i<json.contactMaterials.length; i++){
var jm = json.contactMaterials[i];
var cm = new ContactMaterial(id2material[jm.materialA+""], id2material[jm.materialB+""], {
friction : jm.friction,
restitution : jm.restitution,
stiffness : jm.stiffness,
relaxation : jm.relaxation,
frictionStiffness : jm.frictionStiffness,
frictionRelaxation : jm.frictionRelaxation,
});
cm.id = jm.id;
this.addContactMaterial(cm);
}
// Load constraints
for(var i=0; i<json.constraints.length; i++){
var jc = json.constraints[i],
c;
switch(jc.type){
case "DistanceConstraint":
c = new DistanceConstraint(bodies[jc.bodyA], bodies[jc.bodyB], jc.distance, jc.maxForce);
break;
case "RevoluteConstraint":
c = new RevoluteConstraint(bodies[jc.bodyA], jc.pivotA, bodies[jc.bodyB], jc.pivotB, jc.maxForce);
if(jc.motorSpeed){
c.enableMotor();
c.setMotorSpeed(jc.motorSpeed);
}
c.lowerLimit = jc.lowerLimit || 0;
c.upperLimit = jc.upperLimit || 0;
c.lowerLimitEnabled = jc.lowerLimitEnabled || false;
c.upperLimitEnabled = jc.upperLimitEnabled || false;
break;
case "PrismaticConstraint":
c = new PrismaticConstraint(bodies[jc.bodyA], bodies[jc.bodyB], {
maxForce : jc.maxForce,
localAxisA : jc.localAxisA,
localAnchorA : jc.localAnchorA,
localAnchorB : jc.localAnchorB,
});
break;
case "LockConstraint":
c = new LockConstraint(bodies[jc.bodyA], bodies[jc.bodyB], {
maxForce : jc.maxForce,
localOffsetB : jc.localOffsetB,
localAngleB : jc.localAngleB,
});
break;
default:
throw new Error("Constraint type not recognized: "+jc.type);
}
this.addConstraint(c);
}
return true;
};
/**
* Resets the World, removes all bodies, constraints and springs.
*
* @method clear
*/
World.prototype.clear = function(){
this.time = 0;
// Remove all solver equations
if(this.solver && this.solver.equations.length)
this.solver.removeAllEquations();
// Remove all constraints
var cs = this.constraints;
for(var i=cs.length-1; i>=0; i--){
this.removeConstraint(cs[i]);
}
// Remove all bodies
var bodies = this.bodies;
for(var i=bodies.length-1; i>=0; i--){
this.removeBody(bodies[i]);
}
// Remove all springs
var springs = this.springs;
for(var i=springs.length-1; i>=0; i--){
this.removeSpring(springs[i]);
}
// Remove all contact materials
var cms = this.contactMaterials;
for(var i=cms.length-1; i>=0; i--){
this.removeContactMaterial(cms[i]);
}
};
/**
* Get a copy of this World instance
* @method clone
* @return {World}
*/
World.prototype.clone = function(){
var world = new World();
world.fromJSON(this.toJSON());
return world;
};
var hitTest_tmp1 = vec2.create(),
hitTest_zero = vec2.fromValues(0,0),
hitTest_tmp2 = vec2.fromValues(0,0);
/**
* Test if a world point overlaps bodies
* @method hitTest
* @param {Array} worldPoint Point to use for intersection tests
* @param {Array} bodies A list of objects to check for intersection
* @param {Number} precision Used for matching against particles and lines. Adds some margin to these infinitesimal objects.
* @return {Array} Array of bodies that overlap the point
*/
World.prototype.hitTest = function(worldPoint,bodies,precision){
precision = precision || 0;
// Create a dummy particle body with a particle shape to test against the bodies
var pb = new Body({ position:worldPoint }),
ps = new Particle(),
px = worldPoint,
pa = 0,
x = hitTest_tmp1,
zero = hitTest_zero,
tmp = hitTest_tmp2;
pb.addShape(ps);
var n = this.narrowphase,
result = [];
// Check bodies
for(var i=0, N=bodies.length; i!==N; i++){
var b = bodies[i];
for(var j=0, NS=b.shapes.length; j!==NS; j++){
var s = b.shapes[j],
offset = b.shapeOffsets[j] || zero,
angle = b.shapeAngles[j] || 0.0;
// Get shape world position + angle
vec2.rotate(x, offset, b.angle);
vec2.add(x, x, b.position);
var a = angle + b.angle;
if( (s instanceof Circle && n.circleParticle (b,s,x,a, pb,ps,px,pa, true)) ||
(s instanceof Convex && n.particleConvex (pb,ps,px,pa, b,s,x,a, true)) ||
(s instanceof Plane && n.particlePlane (pb,ps,px,pa, b,s,x,a, true)) ||
(s instanceof Capsule && n.particleCapsule (pb,ps,px,pa, b,s,x,a, true)) ||
(s instanceof Particle && vec2.squaredLength(vec2.sub(tmp,x,worldPoint)) < precision*precision)
){
result.push(b);
}
}
}
return result;
};
},{"../../package.json":8,"../collision/Broadphase":10,"../collision/NaiveBroadphase":12,"../collision/Narrowphase":13,"../constraints/DistanceConstraint":17,"../constraints/LockConstraint":19,"../constraints/PrismaticConstraint":20,"../constraints/RevoluteConstraint":21,"../events/EventEmitter":28,"../material/ContactMaterial":29,"../material/Material":30,"../math/vec2":33,"../objects/Body":34,"../objects/Spring":35,"../shapes/Capsule":37,"../shapes/Circle":38,"../shapes/Convex":39,"../shapes/Line":41,"../shapes/Particle":42,"../shapes/Plane":43,"../shapes/Rectangle":44,"../solver/GSSolver":46,"../utils/Utils":50}]},{},[36])
(36)
});
;
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2014 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @const
* @type {number}
*/
Phaser.Physics.P2.LIME_CORONA_JSON = 0;
// Add an extra properties to p2 that we need
p2.Body.prototype.parent = null;
p2.Spring.prototype.parent = null;
/**
* @class Phaser.Physics.P2
* @classdesc Physics World Constructor
* @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 (typeof config === 'undefined')
{
config = { gravity: [0, 0], broadphase: new p2.SAPBroadphase() };
}
/**
* @property {p2.World} game - The p2 World in which the simulation is run.
* @protected
*/
this.world = new p2.World(config);
/**
* @property {array<Phaser.Physics.P2.Material>} materials - A local array of all created Materials.
* @protected
*/
this.materials = [];
/**
* @property {Phaser.InversePointProxy} gravity - The gravity applied to all bodies each step.
*/
this.gravity = new Phaser.Physics.P2.InversePointProxy(game, this.world.gravity);
/**
* @property {p2.Body} bounds - The bounds body contains the 4 walls that border the World. Define or disable with setBounds.
*/
this.bounds = null;
/**
* @property {array} _wallShapes - The wall bounds shapes.
* @private
*/
this._wallShapes = [ null, null, null, null ];
/**
* @property {Phaser.Signal} onBodyAdded - Dispatched when a new Body is added to the World.
*/
this.onBodyAdded = new Phaser.Signal();
/**
* @property {Phaser.Signal} onBodyRemoved - Dispatched when a Body is removed from the World.
*/
this.onBodyRemoved = new Phaser.Signal();
/**
* @property {Phaser.Signal} onSpringAdded - Dispatched when a new Spring is added to the World.
*/
this.onSpringAdded = new Phaser.Signal();
/**
* @property {Phaser.Signal} onSpringRemoved - Dispatched when a Spring is removed from the World.
*/
this.onSpringRemoved = new Phaser.Signal();
/**
* @property {Phaser.Signal} onConstraintAdded - Dispatched when a new Constraint is added to the World.
*/
this.onConstraintAdded = new Phaser.Signal();
/**
* @property {Phaser.Signal} onConstraintRemoved - Dispatched when a Constraint is removed from the World.
*/
this.onConstraintRemoved = new Phaser.Signal();
/**
* @property {Phaser.Signal} onContactMaterialAdded - Dispatched when a new ContactMaterial is added to the World.
*/
this.onContactMaterialAdded = new Phaser.Signal();
/**
* @property {Phaser.Signal} onContactMaterialRemoved - Dispatched when a ContactMaterial is removed from the World.
*/
this.onContactMaterialRemoved = new Phaser.Signal();
/**
* @property {Phaser.Signal} onPostStep - Dispatched after the World.step()
*/
this.onPostStep = new Phaser.Signal();
/**
* @property {Phaser.Signal} onPostBroadphase - Dispatched after the Broadphase has collected collision pairs in the world.
*/
this.onPostBroadphase = new Phaser.Signal();
/**
* @property {Phaser.Signal} onImpact - Dispatched when a first contact is created between two bodies. This event is fired after the step has been done.
*/
this.onImpact = new Phaser.Signal();
/**
* @property {Phaser.Signal} onBeginContact - Dispatched when a first contact is created between two bodies. This event is fired before the step has been done.
*/
this.onBeginContact = new Phaser.Signal();
/**
* @property {Phaser.Signal} onEndContact - Dispatched when final contact occurs between two bodies. This event is fired before the step has been done.
*/
this.onEndContact = new Phaser.Signal();
// Hook into the World events
this.world.on("postStep", this.postStepHandler, this);
this.world.on("postBroadphase", this.postBroadphaseHandler, this);
this.world.on("impact", this.impactHandler, this);
this.world.on("beginContact", this.beginContactHandler, this);
this.world.on("endContact", this.endContactHandler, this);
/**
* @property {array} collisionGroups - Internal var.
*/
this.collisionGroups = [];
/**
* @property {number} _collisionGroupID - Internal var.
* @private
*/
this._collisionGroupID = 2;
this.nothingCollisionGroup = new Phaser.Physics.P2.CollisionGroup(1);
this.boundsCollisionGroup = new Phaser.Physics.P2.CollisionGroup(2);
this.everythingCollisionGroup = new Phaser.Physics.P2.CollisionGroup(2147483648);
this.boundsCollidesWith = [];
// Group vs. Group callbacks
// By default we want everything colliding with everything
this.setBoundsToWorld(true, true, true, true, false);
};
Phaser.Physics.P2.prototype = {
/**
* Handles a p2 postStep event.
*
* @method Phaser.Physics.P2#postStepHandler
* @private
* @param {object} event - The event data.
*/
postStepHandler: function (event) {
},
/**
* 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.
*
* @method Phaser.Physics.P2#postBroadphaseHandler
* @private
* @param {object} event - The event data.
*/
postBroadphaseHandler: function (event) {
// Body.id 1 is always the World bounds object
for (var i = 0; i < event.pairs.length; i += 2)
{
var a = event.pairs[i];
var b = event.pairs[i+1];
if (a.id !== 1 && b.id !== 1)
{
// console.log('postBroadphaseHandler', a, b);
}
}
},
/**
* Handles a p2 impact event.
*
* @method Phaser.Physics.P2#impactHandler
* @private
* @param {object} event - The event data.
*/
impactHandler: function (event) {
if (event.bodyA.parent && event.bodyB.parent)
{
// Body vs. Body callbacks
var a = event.bodyA.parent;
var b = event.bodyB.parent;
if (a._bodyCallbacks[event.bodyB.id])
{
a._bodyCallbacks[event.bodyB.id].call(a._bodyCallbackContext[event.bodyB.id], a, b, event.shapeA, event.shapeB);
}
if (b._bodyCallbacks[event.bodyA.id])
{
b._bodyCallbacks[event.bodyA.id].call(b._bodyCallbackContext[event.bodyA.id], b, a, event.shapeB, event.shapeA);
}
// Body vs. Group callbacks
if (a._groupCallbacks[event.shapeB.collisionGroup])
{
a._groupCallbacks[event.shapeB.collisionGroup].call(a._groupCallbackContext[event.shapeB.collisionGroup], a, b, event.shapeA, event.shapeB);
}
if (b._groupCallbacks[event.shapeA.collisionGroup])
{
b._groupCallbacks[event.shapeA.collisionGroup].call(b._groupCallbackContext[event.shapeA.collisionGroup], b, a, event.shapeB, event.shapeA);
}
}
},
/**
* Handles a p2 begin contact event.
*
* @method Phaser.Physics.P2#beginContactHandler
* @private
* @param {object} event - The event data.
*/
beginContactHandler: function (event) {
// console.log('beginContactHandler');
// console.log(event);
if (event.bodyA.id > 1 && event.bodyB.id > 1)
{
// console.log('beginContactHandler');
// console.log(event.bodyA.parent.sprite.key);
// console.log(event.bodyB.parent.sprite.key);
}
},
/**
* Handles a p2 end contact event.
*
* @method Phaser.Physics.P2#endContactHandler
* @private
* @param {object} event - The event data.
*/
endContactHandler: function (event) {
// console.log('endContactHandler');
// console.log(event);
if (event.bodyA.id > 1 && event.bodyB.id > 1)
{
// console.log('endContactHandler');
// console.log(event);
}
},
/**
* Sets the bounds of the Physics world to match the Game.World dimensions.
* You can optionally set which 'walls' to create: left, right, top or bottom.
*
* @method Phaser.Physics#setBoundsToWorld
* @param {boolean} [left=true] - If true will create the left bounds wall.
* @param {boolean} [right=true] - If true will create the right bounds wall.
* @param {boolean} [top=true] - If true will create the top bounds wall.
* @param {boolean} [bottom=true] - If true will create the bottom bounds wall.
* @param {boolean} [setCollisionGroup=true] - If true the Bounds will be set to use its own Collision Group.
*/
setBoundsToWorld: function (left, right, top, bottom, setCollisionGroup) {
this.setBounds(this.game.world.bounds.x, this.game.world.bounds.y, this.game.world.bounds.width, this.game.world.bounds.height, left, right, top, bottom, setCollisionGroup);
},
/**
* Sets the given material against the 4 bounds of this World.
*
* @method Phaser.Physics#setWorldMaterial
* @param {Phaser.Physics.P2.Material} material - The material to set.
* @param {boolean} [left=true] - If true will set the material on the left bounds wall.
* @param {boolean} [right=true] - If true will set the material on the right bounds wall.
* @param {boolean} [top=true] - If true will set the material on the top bounds wall.
* @param {boolean} [bottom=true] - If true will set the material on the bottom bounds wall.
*/
setWorldMaterial: function (material, left, right, top, bottom) {
if (typeof left === 'undefined') { left = true; }
if (typeof right === 'undefined') { right = true; }
if (typeof top === 'undefined') { top = true; }
if (typeof bottom === 'undefined') { bottom = true; }
if (left && this._wallShapes[0])
{
this._wallShapes[0].material = material;
}
if (right && this._wallShapes[1])
{
this._wallShapes[1].material = material;
}
if (top && this._wallShapes[2])
{
this._wallShapes[2].material = material;
}
if (bottom && this._wallShapes[3])
{
this._wallShapes[3].material = material;
}
},
/**
* Sets the bounds of the Physics world to match the given world pixel dimensions.
* You can optionally set which 'walls' to create: left, right, top or bottom.
*
* @method Phaser.Physics.P2#setBounds
* @param {number} x - The x coordinate of the top-left corner of the bounds.
* @param {number} y - The y coordinate of the top-left corner of the bounds.
* @param {number} width - The width of the bounds.
* @param {number} height - The height of the bounds.
* @param {boolean} [left=true] - If true will create the left bounds wall.
* @param {boolean} [right=true] - If true will create the right bounds wall.
* @param {boolean} [top=true] - If true will create the top bounds wall.
* @param {boolean} [bottom=true] - If true will create the bottom bounds wall.
* @param {boolean} [setCollisionGroup=true] - If true the Bounds will be set to use its own Collision Group.
*/
setBounds: function (x, y, width, height, left, right, top, bottom, setCollisionGroup) {
if (typeof left === 'undefined') { left = true; }
if (typeof right === 'undefined') { right = true; }
if (typeof top === 'undefined') { top = true; }
if (typeof bottom === 'undefined') { bottom = true; }
if (typeof setCollisionGroup === 'undefined') { setCollisionGroup = true; }
var hw = (width / 2);
var hh = (height / 2);
var cx = hw + x;
var cy = hh + y;
if (this.bounds !== null)
{
if (this.bounds.world)
{
this.world.removeBody(this.bounds);
}
var i = this.bounds.shapes.length;
while (i--)
{
var shape = this.bounds.shapes[i];
this.bounds.removeShape(shape);
}
this.bounds.position[0] = this.game.math.px2pi(cx);
this.bounds.position[1] = this.game.math.px2pi(cy);
}
else
{
this.bounds = new p2.Body({ mass: 0, position:[this.game.math.px2pi(cx), this.game.math.px2pi(cy)] });
}
if (left)
{
this._wallShapes[0] = new p2.Plane();
if (setCollisionGroup)
{
this._wallShapes[0].collisionGroup = this.boundsCollisionGroup.mask;
// this._wallShapes[0].collisionGroup = this.everythingCollisionGroup.mask;
// this._wallShapes[0].collisionMask = this.everythingCollisionGroup.mask;
}
this.bounds.addShape(this._wallShapes[0], [this.game.math.px2pi(-hw), 0], 1.5707963267948966 );
}
if (right)
{
this._wallShapes[1] = new p2.Plane();
if (setCollisionGroup)
{
this._wallShapes[1].collisionGroup = this.boundsCollisionGroup.mask;
// this._wallShapes[1].collisionGroup = this.everythingCollisionGroup.mask;
// this._wallShapes[1].collisionMask = this.everythingCollisionGroup.mask;
}
this.bounds.addShape(this._wallShapes[1], [this.game.math.px2pi(hw), 0], -1.5707963267948966 );
}
if (top)
{
this._wallShapes[2] = new p2.Plane();
if (setCollisionGroup)
{
this._wallShapes[2].collisionGroup = this.boundsCollisionGroup.mask;
// this._wallShapes[2].collisionGroup = this.everythingCollisionGroup.mask;
// this._wallShapes[2].collisionMask = this.everythingCollisionGroup.mask;
}
this.bounds.addShape(this._wallShapes[2], [0, this.game.math.px2pi(-hh)], -3.141592653589793 );
}
if (bottom)
{
this._wallShapes[3] = new p2.Plane();
if (setCollisionGroup)
{
this._wallShapes[3].collisionGroup = this.boundsCollisionGroup.mask;
// this._wallShapes[3].collisionGroup = this.everythingCollisionGroup.mask;
// this._wallShapes[3].collisionMask = this.everythingCollisionGroup.mask;
}
this.bounds.addShape(this._wallShapes[3], [0, this.game.math.px2pi(hh)] );
}
this.world.addBody(this.bounds);
},
/**
* @method Phaser.Physics.P2#update
*/
update: function () {
this.world.step(1 / 60);
},
/**
* Clears all bodies from the simulation.
*
* @method Phaser.Physics.P2#clear
*/
clear: function () {
this.world.clear();
},
/**
* Clears all bodies from the simulation and unlinks World from Game. Should only be called on game shutdown. Call `clear` on a State change.
*
* @method Phaser.Physics.P2#destroy
*/
destroy: function () {
this.world.clear();
this.game = null;
},
/**
* Add a body to the world.
*
* @method Phaser.Physics.P2#addBody
* @param {Phaser.Physics.P2.Body} body - The Body to add to the World.
* @return {boolean} True if the Body was added successfully, otherwise false.
*/
addBody: function (body) {
if (body.data.world)
{
return false;
}
else
{
this.world.addBody(body.data);
this.onBodyAdded.dispatch(body);
return true;
}
},
/**
* Removes a body from the world.
*
* @method Phaser.Physics.P2#removeBody
* @param {Phaser.Physics.P2.Body} body - The Body to remove from the World.
* @return {Phaser.Physics.P2.Body} The Body that was removed.
*/
removeBody: function (body) {
this.world.removeBody(body.data);
this.onBodyRemoved.dispatch(body);
return body;
},
/**
* Adds a Spring to the world.
*
* @method Phaser.Physics.P2#addSpring
* @param {Phaser.Physics.P2.Spring} spring - The Spring to add to the World.
* @return {Phaser.Physics.P2.Spring} The Spring that was added.
*/
addSpring: function (spring) {
this.world.addSpring(spring);
this.onSpringAdded.dispatch(spring);
return spring;
},
/**
* Removes a Spring from the world.
*
* @method Phaser.Physics.P2#removeSpring
* @param {Phaser.Physics.P2.Spring} spring - The Spring to remove from the World.
* @return {Phaser.Physics.P2.Spring} The Spring that was removed.
*/
removeSpring: function (spring) {
this.world.removeSpring(spring);
this.onSpringRemoved.dispatch(spring);
return spring;
},
/**
* Adds a Constraint to the world.
*
* @method Phaser.Physics.P2#addConstraint
* @param {Phaser.Physics.P2.Constraint} constraint - The Constraint to add to the World.
* @return {Phaser.Physics.P2.Constraint} The Constraint that was added.
*/
addConstraint: function (constraint) {
this.world.addConstraint(constraint);
this.onConstraintAdded.dispatch(constraint);
return constraint;
},
/**
* Removes a Constraint from the world.
*
* @method Phaser.Physics.P2#removeConstraint
* @param {Phaser.Physics.P2.Constraint} constraint - The Constraint to be removed from the World.
* @return {Phaser.Physics.P2.Constraint} The Constraint that was removed.
*/
removeConstraint: function (constraint) {
this.world.removeConstraint(constraint);
this.onConstraintRemoved.dispatch(constraint);
return constraint;
},
/**
* Adds a Contact Material to the world.
*
* @method Phaser.Physics.P2#addContactMaterial
* @param {Phaser.Physics.P2.ContactMaterial} material - The Contact Material to be added to the World.
* @return {Phaser.Physics.P2.ContactMaterial} The Contact Material that was added.
*/
addContactMaterial: function (material) {
this.world.addContactMaterial(material);
this.onContactMaterialAdded.dispatch(material);
return material;
},
/**
* Removes a Contact Material from the world.
*
* @method Phaser.Physics.P2#removeContactMaterial
* @param {Phaser.Physics.P2.ContactMaterial} material - The Contact Material to be removed from the World.
* @return {Phaser.Physics.P2.ContactMaterial} The Contact Material that was removed.
*/
removeContactMaterial: function (material) {
this.world.removeContactMaterial(material);
this.onContactMaterialRemoved.dispatch(material);
return material;
},
/**
* Gets a Contact Material based on the two given Materials.
*
* @method Phaser.Physics.P2#getContactMaterial
* @param {Phaser.Physics.P2.Material} materialA - The first Material to search for.
* @param {Phaser.Physics.P2.Material} materialB - The second Material to search for.
* @return {Phaser.Physics.P2.ContactMaterial|boolean} The Contact Material or false if none was found matching the Materials given.
*/
getContactMaterial: function (materialA, materialB) {
return this.world.getContactMaterial(materialA, materialB);
},
/**
* 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.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 (typeof materialA === 'undefined') { materialA = this.createMaterial(); }
if (typeof materialB === 'undefined') { materialB = this.createMaterial(); }
var contact = new Phaser.Physics.P2.ContactMaterial(materialA, materialB, options);
return this.addContactMaterial(contact);
},
/**
* Populates and returns an array 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;
},
/**
* 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]);
}
return output;
},
/**
* Populates and returns an array of all current Constraints in the world.
*
* @method Phaser.Physics.P2#getConstraints
* @return {array<Phaser.Physics.P2.Constraints>} 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.springs[i]);
}
return output;
},
/**
* Test if a world point overlaps bodies.
*
* @method Phaser.Physics.P2#hitTest
* @param {Phaser.Point} worldPoint - Point to use for intersection tests.
* @param {Array} bodies - A list of objects to check for intersection.
* @param {number} precision - Used for matching against particles and lines. Adds some margin to these infinitesimal objects.
* @return {Array} Array of bodies that overlap the point.
*/
hitTest: function (worldPoint, bodies, precision) {
},
/**
* Converts the current world into a JSON object.
*
* @method Phaser.Physics.P2#toJSON
* @return {object} A JSON representation of the world.
*/
toJSON: function () {
this.world.toJSON();
},
createCollisionGroup: function () {
var bitmask = Math.pow(2, this._collisionGroupID);
if (this._wallShapes[0])
{
this._wallShapes[0].collisionMask = this._wallShapes[0].collisionMask | bitmask;
}
if (this._wallShapes[1])
{
this._wallShapes[1].collisionMask = this._wallShapes[1].collisionMask | bitmask;
}
if (this._wallShapes[2])
{
this._wallShapes[2].collisionMask = this._wallShapes[2].collisionMask | bitmask;
}
if (this._wallShapes[3])
{
this._wallShapes[3].collisionMask = this._wallShapes[3].collisionMask | bitmask;
}
this._collisionGroupID++;
var group = new Phaser.Physics.P2.CollisionGroup(bitmask);
this.collisionGroups.push(group);
return group;
},
/**
* @method Phaser.Physics.P2.prototype.createBody
* @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.
*/
createBody: function (x, y, mass, addToWorld, options, data) {
if (typeof 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;
},
/**
* @method Phaser.Physics.P2.prototype.createBody
* @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 (typeof 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;
},
};
/**
* @name Phaser.Physics.P2#friction
* @property {number} friction - Friction between colliding bodies. This value is used if no matching ContactMaterial is found for a Material pair.
*/
Object.defineProperty(Phaser.Physics.P2.prototype, "friction", {
get: function () {
return this.world.defaultFriction;
},
set: function (value) {
this.world.defaultFriction = value;
}
});
/**
* @name Phaser.Physics.P2#restituion
* @property {number} restitution - Default coefficient of restitution between colliding bodies. This value is used if no matching ContactMaterial is found for a Material pair.
*/
Object.defineProperty(Phaser.Physics.P2.prototype, "restituion", {
get: function () {
return this.world.defaultRestitution;
},
set: function (value) {
this.world.defaultRestitution = value;
}
});
/**
* @name Phaser.Physics.P2#applySpringForces
* @property {boolean} applySpringForces - Enable to automatically apply spring forces each step.
*/
Object.defineProperty(Phaser.Physics.P2.prototype, "applySpringForces", {
get: function () {
return this.world.applySpringForces;
},
set: function (value) {
this.world.applySpringForces = value;
}
});
/**
* @name Phaser.Physics.P2#applyDamping
* @property {boolean} applyDamping - Enable to automatically apply body damping each step.
*/
Object.defineProperty(Phaser.Physics.P2.prototype, "applyDamping", {
get: function () {
return this.world.applyDamping;
},
set: function (value) {
this.world.applyDamping = value;
}
});
/**
* @name Phaser.Physics.P2#applyGravity
* @property {boolean} applyGravity - Enable to automatically apply gravity each step.
*/
Object.defineProperty(Phaser.Physics.P2.prototype, "applyGravity", {
get: function () {
return this.world.applyGravity;
},
set: function (value) {
this.world.applyGravity = value;
}
});
/**
* @name Phaser.Physics.P2#solveConstraints
* @property {boolean} solveConstraints - Enable/disable constraint solving in each step.
*/
Object.defineProperty(Phaser.Physics.P2.prototype, "solveConstraints", {
get: function () {
return this.world.solveConstraints;
},
set: function (value) {
this.world.solveConstraints = value;
}
});
/**
* @name Phaser.Physics.P2#time
* @property {boolean} time - The World time.
* @readonly
*/
Object.defineProperty(Phaser.Physics.P2.prototype, "time", {
get: function () {
return this.world.time;
}
});
/**
* @name Phaser.Physics.P2#emitImpactEvent
* @property {boolean} emitImpactEvent - Set to true if you want to the world to emit the "impact" event. Turning this off could improve performance.
*/
Object.defineProperty(Phaser.Physics.P2.prototype, "emitImpactEvent", {
get: function () {
return this.world.emitImpactEvent;
},
set: function (value) {
this.world.emitImpactEvent = value;
}
});
/**
* @name Phaser.Physics.P2#enableBodySleeping
* @property {boolean} enableBodySleeping - Enable / disable automatic body sleeping.
*/
Object.defineProperty(Phaser.Physics.P2.prototype, "enableBodySleeping", {
get: function () {
return this.world.enableBodySleeping;
},
set: function (value) {
this.world.enableBodySleeping = value;
}
});
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2014 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* A PointProxy is an internal class that allows for direct getter/setter style property access to Arrays and TypedArrays.
*
* @class Phaser.Physics.P2.PointProxy
* @classdesc PointProxy
* @constructor
* @param {Phaser.Game} game - A reference to the Phaser.Game instance.
* @param {any} destination - The object to bind to.
*/
Phaser.Physics.P2.PointProxy = function (game, destination) {
this.game = game;
this.destination = destination;
};
Phaser.Physics.P2.PointProxy.prototype.constructor = Phaser.Physics.P2.PointProxy;
/**
* @name Phaser.Physics.P2.PointProxy#x
* @property {number} x - The x property of this PointProxy.
*/
Object.defineProperty(Phaser.Physics.P2.PointProxy.prototype, "x", {
get: function () {
return this.destination[0];
},
set: function (value) {
this.destination[0] = this.game.math.px2p(value);
}
});
/**
* @name Phaser.Physics.P2.PointProxy#y
* @property {number} y - The y property of this PointProxy.
*/
Object.defineProperty(Phaser.Physics.P2.PointProxy.prototype, "y", {
get: function () {
return this.destination[1];
},
set: function (value) {
this.destination[1] = this.game.math.px2p(value);
}
});
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2014 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* A InversePointProxy is an internal class that allows for direct getter/setter style property access to Arrays and TypedArrays but inverses the values on set.
*
* @class Phaser.Physics.P2.InversePointProxy
* @classdesc InversePointProxy
* @constructor
* @param {Phaser.Game} game - A reference to the Phaser.Game instance.
* @param {any} destination - The object to bind to.
*/
Phaser.Physics.P2.InversePointProxy = function (game, destination) {
this.game = game;
this.destination = destination;
};
Phaser.Physics.P2.InversePointProxy.prototype.constructor = Phaser.Physics.P2.InversePointProxy;
/**
* @name Phaser.Physics.P2.InversePointProxy#x
* @property {number} x - The x property of this InversePointProxy.
*/
Object.defineProperty(Phaser.Physics.P2.InversePointProxy.prototype, "x", {
get: function () {
return this.destination[0];
},
set: function (value) {
this.destination[0] = this.game.math.px2p(-value);
}
});
/**
* @name Phaser.Physics.P2.InversePointProxy#y
* @property {number} y - The y property of this InversePointProxy.
*/
Object.defineProperty(Phaser.Physics.P2.InversePointProxy.prototype, "y", {
get: function () {
return this.destination[1];
},
set: function (value) {
this.destination[1] = this.game.math.px2p(-value);
}
});
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2014 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* The Physics Body is typically linked to a single Sprite and defines properties that determine how the physics body is simulated.
* These properties affect how the body reacts to forces, what forces it generates on itself (to simulate friction), and how it reacts to collisions in the scene.
* In most cases, the properties are used to simulate physical effects. Each body also has its own property values that determine exactly how it reacts to forces and collisions in the scene.
* By default a single Rectangle shape is added to the Body that matches the dimensions of the parent Sprite. See addShape, removeShape, clearShapes to add extra shapes around the Body.
* Note: When bound to a Sprite to avoid single-pixel jitters on mobile devices we strongly recommend using Sprite sizes that are even on both axis, i.e. 128x128 not 127x127.
*
* @class Phaser.Physics.Body
* @classdesc Physics Body Constructor
* @constructor
* @param {Phaser.Game} game - Game reference to the currently running game.
* @param {Phaser.Sprite} [sprite] - The Sprite object this physics body belongs to.
* @param {number} [x=0] - The x coordinate of this Body.
* @param {number} [y=0] - The y coordinate of this Body.
* @param {number} [mass=1] - The default mass of this Body (0 = static).
*/
Phaser.Physics.Body = function (game, sprite, x, y, mass) {
sprite = sprite || null;
x = x || 0;
y = y || 0;
if (typeof mass === 'undefined') { mass = 1; }
/**
* @property {Phaser.Game} game - Local reference to game.
*/
this.game = game;
/**
* @property {Phaser.Sprite} sprite - Reference to the parent Sprite.
*/
this.sprite = sprite;
/**
* @property {number} type - The type of physics system this body belongs to.
*/
this.type = Phaser.Physics.P2;
/**
* @property {Phaser.Point} offset - The offset of the Physics Body from the Sprite x/y position.
*/
this.offset = new Phaser.Point();
/**
* @property {p2.Body} data - The p2 Body data.
* @protected
*/
this.data = new p2.Body({ position:[this.px2pi(x), this.px2pi(y)], mass: mass });
this.data.parent = this;
/**
* @property {Phaser.InversePointProxy} velocity - The velocity of the body. Set velocity.x to a negative value to move to the left, position to the right. velocity.y negative values move up, positive move down.
*/
this.velocity = new Phaser.Physics.InversePointProxy(this.game, this.data.velocity);
/**
* @property {Phaser.InversePointProxy} force - The force applied to the body.
*/
this.force = new Phaser.Physics.InversePointProxy(this.game, this.data.force);
/**
* @property {Phaser.Point} gravity - A locally applied gravity force to the Body. Applied directly before the world step. NOTE: Not currently implemented.
*/
this.gravity = new Phaser.Point();
/**
* A Body can be set to collide against the World bounds automatically if this is set to true. Otherwise it will leave the World.
* Note that this only applies if your World has bounds! The response to the collision should be managed via CollisionMaterials.
* @property {boolean} collideWorldBounds - Should the Body collide with the World bounds?
*/
this.collideWorldBounds = true;
/**
* @property {Phaser.Signal} onImpact - Dispatched when the shape/s of this Body impact with another. The event will be sent 2 parameters, this Body and the impact Body.
*/
this.onImpact = new Phaser.Signal();
/**
* @property {array} collidesWith - Array of CollisionGroups that this Bodies shapes collide with.
* @private
*/
this.collidesWith = [];
/**
* @property {array} _bodyCallbacks - Array of Body callbacks.
* @private
*/
this._bodyCallbacks = [];
/**
* @property {array} _bodyCallbackContext - Array of Body callback contexts.
* @private
*/
this._bodyCallbackContext = [];
/**
* @property {array} _groupCallbacks - Array of Group callbacks.
* @private
*/
this._groupCallbacks = [];
/**
* @property {array} _bodyCallbackContext - Array of Grouo callback contexts.
* @private
*/
this._groupCallbackContext = [];
// Set-up the default shape
if (sprite)
{
this.setRectangleFromSprite(sprite);
this.game.physics.addBody(this);
}
};
Phaser.Physics.Body.prototype = {
/**
* Sets a callback to be fired any time this Body impacts with the given Body. The impact test is performed against body.id values.
* The callback will be sent 4 parameters: This body, the body that impacted, the Shape in this body and the shape in the impacting body.
*
* @method Phaser.Physics.Body#createBodyCallback
* @param {Phaser.Physics.Body} body - The Body to send impact events for.
* @param {function} callback - The callback to fire on impact. Set to null to clear a previously set callback.
* @param {object} callbackContext - The context under which the callback will fire.
*/
createBodyCallback: function (body, callback, callbackContext) {
this._bodyCallbacks[body.data.id] = callback;
this._bodyCallbackContext[body.data.id] = callbackContext;
},
/**
* Sets a callback to be fired any time this Body impacts with the given Group. The impact test is performed against shape.collisionGroup values.
* The callback will be sent 4 parameters: This body, the body that impacted, the Shape in this body and the shape in the impacting body.
* This callback will only fire if this Body has been assigned a collision group.
*
* @method Phaser.Physics.Body#createGroupCallback
* @param {Phaser.Physics.CollisionGroup} group - The Group to send impact events for.
* @param {function} callback - The callback to fire on impact. Set to null to clear a previously set callback.
* @param {object} callbackContext - The context under which the callback will fire.
*/
createGroupCallback: function (group, callback, callbackContext) {
this._groupCallbacks[group.mask] = callback;
this._groupCallbackContext[group.mask] = callbackContext;
},
/**
* Gets the collision bitmask from the groups this body collides with.
*
* @method Phaser.Physics.Body#getCollisionMask
* @return {number} The bitmask.
*/
getCollisionMask: function () {
var mask = 0;
if (this.collideWorldBounds)
{
mask = this.game.physics.boundsCollisionGroup.mask;
}
for (var i = 0; i < this.collidesWith.length; i++)
{
mask = mask | this.collidesWith[i].mask;
}
return mask;
},
/**
* Sets the given CollisionGroup to be the collision group for all shapes in this Body, unless a shape is specified.
* This also resets the collisionMask.
*
* @method Phaser.Physics.Body#setCollisionGroup
* @param {Phaser.Physics.CollisionGroup|array} group - The Collision Group that this Bodies shapes will use.
* @param {p2.Shape} [shape] - An optional Shape. If not provided the collision group will be added to all Shapes in this Body.
*/
setCollisionGroup: function (group, shape) {
var mask = this.getCollisionMask();
if (typeof shape === 'undefined')
{
for (var i = this.data.shapes.length - 1; i >= 0; i--)
{
this.data.shapes[i].collisionGroup = group.mask;
this.data.shapes[i].collisionMask = mask;
}
}
else
{
shape.collisionGroup = group.mask;
shapes.collisionMask = mask;
}
},
/**
* Clears the collision data from the shapes in this Body. Optionally clears Group and/or Mask.
*
* @method Phaser.Physics.Body#clearCollision
* @param {boolean} [clearGroup=true] - Clear the collisionGroup value from the shape/s?
* @param {boolean} [clearMask=true] - Clear the collisionMask value from the shape/s?
* @param {p2.Shape} [shape] - An optional Shape. If not provided the collision data will be cleared from all Shapes in this Body.
*/
clearCollision: function (clearGroup, clearMask, shape) {
if (typeof shape === 'undefined')
{
for (var i = this.data.shapes.length - 1; i >= 0; i--)
{
if (clearGroup)
{
this.data.shapes[i].collisionGroup = null;
}
if (clearMask)
{
this.data.shapes[i].collisionMask = null;
}
}
}
else
{
if (clearGroup)
{
shapes.collisionGroup = null;
}
if (clearMask)
{
shapes.collisionMask = null;
}
}
if (clearGroup)
{
this.collidesWith.length = 0;
}
},
/**
* Adds the given CollisionGroup, or array of CollisionGroups, to the list of groups that this body will collide with and updates the collision masks.
*
* @method Phaser.Physics.Body#collides
* @param {Phaser.Physics.CollisionGroup|array} group - The Collision Group or Array of Collision Groups that this Bodies shapes will collide with.
* @param {function} [callback] - Optional callback that will be triggered when this Body impacts with the given Group.
* @param {object} [callbackContext] - The context under which the callback will be called.
* @param {p2.Shape} [shape] - An optional Shape. If not provided the collision mask will be added to all Shapes in this Body.
*/
collides: function (group, callback, callbackContext, shape) {
if (Array.isArray(group))
{
for (var i = 0; i < group.length; i++)
{
if (this.collidesWith.indexOf(group[i]) === -1)
{
this.collidesWith.push(group[i]);
if (callback)
{
this.createGroupCallback(group[i], callback, callbackContext);
}
}
}
}
else
{
if (this.collidesWith.indexOf(group) === -1)
{
this.collidesWith.push(group);
if (callback)
{
this.createGroupCallback(group, callback, callbackContext);
}
}
}
var mask = this.getCollisionMask();
if (typeof shape === 'undefined')
{
for (var i = this.data.shapes.length - 1; i >= 0; i--)
{
this.data.shapes[i].collisionMask = mask;
}
}
else
{
shape.collisionMask = mask;
}
},
/**
* Moves the shape offsets so their center of mass becomes the body center of mass.
*
* @method Phaser.Physics.Body#adjustCenterOfMass
*/
adjustCenterOfMass: function () {
this.data.adjustCenterOfMass();
},
/**
* Apply damping, see http://code.google.com/p/bullet/issues/detail?id=74 for details.
*
* @method Phaser.Physics.Body#applyDamping
* @param {number} dt - Current time step.
*/
applyDamping: function (dt) {
this.data.applyDamping(dt);
},
/**
* Apply force to a world point. This could for example be a point on the RigidBody surface. Applying force this way will add to Body.force and Body.angularForce.
*
* @method Phaser.Physics.Body#applyForce
* @param {number} force - The force to add.
* @param {number} worldX - The world x point to apply the force on.
* @param {number} worldY - The world y point to apply the force on.
*/
applyForce: function (force, worldX, worldY) {
this.data.applyForce(force, [this.px2p(worldX), this.px2p(worldY)]);
},
/**
* Sets the force on the body to zero.
*
* @method Phaser.Physics.Body#setZeroForce
*/
setZeroForce: function () {
this.data.setZeroForce();
},
/**
* If this Body is dynamic then this will zero its angular velocity.
*
* @method Phaser.Physics.Body#setZeroRotation
*/
setZeroRotation: function () {
this.data.angularVelocity = 0;
},
/**
* If this Body is dynamic then this will zero its velocity on both axis.
*
* @method Phaser.Physics.Body#setZeroVelocity
*/
setZeroVelocity: function () {
this.data.velocity[0] = 0;
this.data.velocity[1] = 0;
},
/**
* Sets the Body damping and angularDamping to zero.
*
* @method Phaser.Physics.Body#setZeroDamping
*/
setZeroDamping: function () {
this.data.damping = 0;
this.data.angularDamping = 0;
},
/**
* Transform a world point to local body frame.
*
* @method Phaser.Physics.Body#toLocalFrame
* @param {Float32Array|Array} out - The vector to store the result in.
* @param {Float32Array|Array} worldPoint - The input world vector.
*/
toLocalFrame: function (out, worldPoint) {
return this.data.toLocalFrame(out, worldPoint);
},
/**
* Transform a local point to world frame.
*
* @method Phaser.Physics.Body#toWorldFrame
* @param {Array} out - The vector to store the result in.
* @param {Array} localPoint - The input local vector.
*/
toWorldFrame: function (out, localPoint) {
return this.data.toWorldFrame(out, localPoint);
},
/**
* This will rotate the Body by the given speed to the left (counter-clockwise).
*
* @method Phaser.Physics.Body#rotateLeft
* @param {number} speed - The speed at which it should rotate.
*/
rotateLeft: function (speed) {
this.data.angularVelocity = this.px2p(-speed);
},
/**
* This will rotate the Body by the given speed to the left (clockwise).
*
* @method Phaser.Physics.Body#rotateRight
* @param {number} speed - The speed at which it should rotate.
*/
rotateRight: function (speed) {
this.data.angularVelocity = this.px2p(speed);
},
/**
* Moves the Body forwards based on its current angle and the given speed.
* The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms).
*
* @method Phaser.Physics.Body#moveForward
* @param {number} speed - The speed at which it should move forwards.
*/
moveForward: function (speed) {
var magnitude = this.px2pi(-speed);
var angle = this.data.angle + Math.PI / 2;
this.data.velocity[0] = magnitude * Math.cos(angle);
this.data.velocity[1] = magnitude * Math.sin(angle);
},
/**
* Moves the Body backwards based on its current angle and the given speed.
* The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms).
*
* @method Phaser.Physics.Body#moveBackward
* @param {number} speed - The speed at which it should move backwards.
*/
moveBackward: function (speed) {
var magnitude = this.px2pi(-speed);
var angle = this.data.angle + Math.PI / 2;
this.data.velocity[0] = -(magnitude * Math.cos(angle));
this.data.velocity[1] = -(magnitude * Math.sin(angle));
},
/**
* Applies a force to the Body that causes it to 'thrust' forwards, based on its current angle and the given speed.
* The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms).
*
* @method Phaser.Physics.Body#thrust
* @param {number} speed - The speed at which it should thrust.
*/
thrust: function (speed) {
var magnitude = this.px2pi(-speed);
var angle = this.data.angle + Math.PI / 2;
this.data.force[0] += magnitude * Math.cos(angle);
this.data.force[1] += magnitude * Math.sin(angle);
},
/**
* Applies a force to the Body that causes it to 'thrust' backwards (in reverse), based on its current angle and the given speed.
* The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms).
*
* @method Phaser.Physics.Body#rever
* @param {number} speed - The speed at which it should reverse.
*/
reverse: function (speed) {
var magnitude = this.px2pi(-speed);
var angle = this.data.angle + Math.PI / 2;
this.data.force[0] -= magnitude * Math.cos(angle);
this.data.force[1] -= magnitude * Math.sin(angle);
},
/**
* If this Body is dynamic then this will move it to the left by setting its x velocity to the given speed.
* The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms).
*
* @method Phaser.Physics.Body#moveLeft
* @param {number} speed - The speed at which it should move to the left, in pixels per second.
*/
moveLeft: function (speed) {
this.data.velocity[0] = this.px2pi(-speed);
},
/**
* If this Body is dynamic then this will move it to the right by setting its x velocity to the given speed.
* The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms).
*
* @method Phaser.Physics.Body#moveRight
* @param {number} speed - The speed at which it should move to the right, in pixels per second.
*/
moveRight: function (speed) {
this.data.velocity[0] = this.px2pi(speed);
},
/**
* If this Body is dynamic then this will move it up by setting its y velocity to the given speed.
* The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms).
*
* @method Phaser.Physics.Body#moveUp
* @param {number} speed - The speed at which it should move up, in pixels per second.
*/
moveUp: function (speed) {
this.data.velocity[1] = this.px2pi(-speed);
},
/**
* If this Body is dynamic then this will move it down by setting its y velocity to the given speed.
* The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms).
*
* @method Phaser.Physics.Body#moveDown
* @param {number} speed - The speed at which it should move down, in pixels per second.
*/
moveDown: function (speed) {
this.data.velocity[1] = this.px2pi(speed);
},
/**
* Internal method. This is called directly before the sprites are sent to the renderer and after the update function has finished.
*
* @method Phaser.Physics.Body#preUpdate
* @protected
*/
preUpdate: function () {
},
/**
* Internal method. This is called directly before the sprites are sent to the renderer and after the update function has finished.
*
* @method Phaser.Physics.Body#postUpdate
* @protected
*/
postUpdate: function () {
this.sprite.x = this.p2pxi(this.data.position[0]);
this.sprite.y = this.p2pxi(this.data.position[1]);
if (!this.fixedRotation)
{
this.sprite.rotation = this.data.angle;
}
},
/**
* Resets the Body force, velocity (linear and angular) and rotation. Optionally resets damping and mass.
*
* @method Phaser.Physics.Body#reset
* @param {number} x - The new x position of the Body.
* @param {number} y - The new x position of the Body.
* @param {boolean} [resetDamping=false] - Resets the linear and angular damping.
* @param {boolean} [resetMass=false] - Sets the Body mass back to 1.
*/
reset: function (x, y, resetDamping, resetMass) {
if (typeof resetDamping === 'undefined') { resetDamping = false; }
if (typeof resetMass === 'undefined') { resetMass = false; }
this.setZeroForce();
this.setZeroVelocity();
this.setZeroRotation();
if (resetDamping)
{
this.setZeroDamping();
}
if (resetMass)
{
this.mass = 1;
}
this.x = x;
this.y = y;
},
/**
* Adds this physics body to the world.
*
* @method Phaser.Physics.Body#addToWorld
*/
addToWorld: function () {
if (this.data.world !== this.game.physics.world)
{
this.game.physics.addBody(this);
}
},
/**
* Removes this physics body from the world.
*
* @method Phaser.Physics.Body#removeFromWorld
*/
removeFromWorld: function () {
if (this.data.world === this.game.physics.world)
{
this.game.physics.removeBody(this);
}
},
/**
* Destroys this Body and all references it holds to other objects.
*
* @method Phaser.Physics.Body#destroy
*/
destroy: function () {
this.removeFromWorld();
this.clearShapes();
this.sprite = null;
/*
this.collideCallback = null;
this.collideCallbackContext = null;
*/
},
/**
* Removes all Shapes from this Body.
*
* @method Phaser.Physics.Body#clearShapes
*/
clearShapes: function () {
for (var i = this.data.shapes.length - 1; i >= 0; i--)
{
var shape = this.data.shapes[i];
this.data.removeShape(shape);
}
},
/**
* Add a shape to the body. You can pass a local transform when adding a shape, so that the shape gets an offset and an angle relative to the body center of mass.
* Will automatically update the mass properties and bounding radius.
*
* @method Phaser.Physics.Body#addShape
* @param {*} shape - The shape to add to the body.
* @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass.
* @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass.
* @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians.
* @return {p2.Circle|p2.Rectangle|p2.Plane|p2.Line|p2.Particle} The shape that was added to the body.
*/
addShape: function (shape, offsetX, offsetY, rotation) {
if (typeof offsetX === 'undefined') { offsetX = 0; }
if (typeof offsetY === 'undefined') { offsetY = 0; }
if (typeof rotation === 'undefined') { rotation = 0; }
this.data.addShape(shape, [this.px2pi(offsetX), this.px2pi(offsetY)], rotation);
return shape;
},
/**
* Adds a Circle shape to this Body. You can control the offset from the center of the body and the rotation.
*
* @method Phaser.Physics.Body#addCircle
* @param {number} radius - The radius of this circle (in pixels)
* @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass.
* @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass.
* @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians.
* @return {p2.Circle} The Circle shape that was added to the Body.
*/
addCircle: function (radius, offsetX, offsetY, rotation) {
var shape = new p2.Circle(this.px2p(radius));
return this.addShape(shape, offsetX, offsetY, rotation);
},
/**
* Adds a Rectangle shape to this Body. You can control the offset from the center of the body and the rotation.
*
* @method Phaser.Physics.Body#addRectangle
* @param {number} width - The width of the rectangle in pixels.
* @param {number} height - The height of the rectangle in pixels.
* @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass.
* @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass.
* @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians.
* @return {p2.Rectangle} The Rectangle shape that was added to the Body.
*/
addRectangle: function (width, height, offsetX, offsetY, rotation) {
var shape = new p2.Rectangle(this.px2p(width), this.px2p(height));
return this.addShape(shape, offsetX, offsetY, rotation);
},
/**
* Adds a Plane shape to this Body. The plane is facing in the Y direction. You can control the offset from the center of the body and the rotation.
*
* @method Phaser.Physics.Body#addPlane
* @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass.
* @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass.
* @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians.
* @return {p2.Plane} The Plane shape that was added to the Body.
*/
addPlane: function (offsetX, offsetY, rotation) {
var shape = new p2.Plane();
return this.addShape(shape, offsetX, offsetY, rotation);
},
/**
* Adds a Particle shape to this Body. You can control the offset from the center of the body and the rotation.
*
* @method Phaser.Physics.Body#addParticle
* @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass.
* @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass.
* @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians.
* @return {p2.Particle} The Particle shape that was added to the Body.
*/
addParticle: function (offsetX, offsetY, rotation) {
var shape = new p2.Particle();
return this.addShape(shape, offsetX, offsetY, rotation);
},
/**
* Adds a Line shape to this Body.
* The line shape is along the x direction, and stretches from [-length/2, 0] to [length/2,0].
* You can control the offset from the center of the body and the rotation.
*
* @method Phaser.Physics.Body#addLine
* @param {number} length - The length of this line (in pixels)
* @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass.
* @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass.
* @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians.
* @return {p2.Line} The Line shape that was added to the Body.
*/
addLine: function (length, offsetX, offsetY, rotation) {
var shape = new p2.Line(this.px2p(length));
return this.addShape(shape, offsetX, offsetY, rotation);
},
/**
* Adds a Capsule shape to this Body.
* You can control the offset from the center of the body and the rotation.
*
* @method Phaser.Physics.Body#addCapsule
* @param {number} length - The distance between the end points in pixels.
* @param {number} radius - Radius of the capsule in radians.
* @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass.
* @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass.
* @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians.
* @return {p2.Capsule} The Capsule shape that was added to the Body.
*/
addCapsule: function (length, radius, offsetX, offsetY, rotation) {
var shape = new p2.Capsule(this.px2p(length), radius);
return this.addShape(shape, offsetX, offsetY, rotation);
},
/**
* Reads a polygon shape path, and assembles convex shapes from that and puts them at proper offset points. The shape must be simple and without holes.
* This function expects the x.y values to be given in pixels. If you want to provide them at p2 world scales then call Body.data.fromPolygon directly.
*
* @method Phaser.Physics.Body#addPolygon
* @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 {boolean} True on success, else false.
*/
addPolygon: function (options, points) {
options = options || {};
points = Array.prototype.slice.call(arguments, 1);
var path = [];
// Did they pass in a single array of points?
if (points.length === 1 && Array.isArray(points[0]))
{
path = points[0].slice(0);
}
else if (Array.isArray(points[0]))
{
path = points[0].slice(0);
// for (var i = 0, len = points[0].length; i < len; i += 2)
// {
// path.push([points[0][i], points[0][i + 1]]);
// }
}
else if (typeof points[0] === 'number')
{
// console.log('addPolygon --- We\'ve a list of numbers');
// We've a list of numbers
for (var i = 0, len = points.length; i < len; i += 2)
{
path.push([points[i], points[i + 1]]);
}
}
// console.log('addPolygon PATH pre');
// console.log(path[1]);
// console.table(path);
// top and tail
var idx = path.length - 1;
if ( path[idx][0] === path[0][0] && path[idx][1] === path[0][1] )
{
path.pop();
}
// Now process them into p2 values
for (var p = 0; p < path.length; p++)
{
path[p][0] = this.px2pi(path[p][0]);
path[p][1] = this.px2pi(path[p][1]);
}
// console.log('addPolygon PATH POST');
// console.log(path[1]);
// console.table(path);
return this.data.fromPolygon(path, options);
},
/**
* Remove a shape from the body. Will automatically update the mass properties and bounding radius.
*
* @method Phaser.Physics.Body#removeShape
* @param {p2.Circle|p2.Rectangle|p2.Plane|p2.Line|p2.Particle} shape - The shape to remove from the body.
* @return {boolean} True if the shape was found and removed, else false.
*/
removeShape: function (shape) {
return this.data.removeShape(shape);
},
/**
* Clears any previously set shapes. Then creates a new Circle shape and adds it to this Body.
*
* @method Phaser.Physics.Body#setCircle
* @param {number} radius - The radius of this circle (in pixels)
* @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass.
* @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass.
* @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians.
*/
setCircle: function (radius, offsetX, offsetY, rotation) {
this.clearShapes();
this.addCircle(radius, offsetX, offsetY, rotation);
},
/**
* Clears any previously set shapes. The creates a new Rectangle shape at the given size and offset, and adds it to this Body.
* If you wish to create a Rectangle to match the size of a Sprite or Image see Body.setRectangleFromSprite.
*
* @method Phaser.Physics.Body#setRectangle
* @param {number} [width=16] - The width of the rectangle in pixels.
* @param {number} [height=16] - The height of the rectangle in pixels.
* @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass.
* @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass.
* @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians.
* @return {p2.Rectangle} The Rectangle shape that was added to the Body.
*/
setRectangle: function (width, height, offsetX, offsetY, rotation) {
if (typeof width === 'undefined') { width = 16; }
if (typeof height === 'undefined') { height = 16; }
this.clearShapes();
return this.addRectangle(width, height, offsetX, offsetY, rotation);
},
/**
* Clears any previously set shapes.
* Then creates a Rectangle shape sized to match the dimensions and orientation of the Sprite given.
* If no Sprite is given it defaults to using the parent of this Body.
*
* @method Phaser.Physics.Body#setRectangleFromSprite
* @param {Phaser.Sprite|Phaser.Image} [sprite] - The Sprite on which the Rectangle will get its dimensions.
* @return {p2.Rectangle} The Rectangle shape that was added to the Body.
*/
setRectangleFromSprite: function (sprite) {
if (typeof sprite === 'undefined') { sprite = this.sprite; }
this.clearShapes();
return this.addRectangle(sprite.width, sprite.height, 0, 0, sprite.rotation);
},
/**
* Adds the given Material to all Shapes that belong to this Body.
* If you only wish to apply it to a specific Shape in this Body then provide that as the 2nd parameter.
*
* @method Phaser.Physics.Body#setMaterial
* @param {Phaser.Physics.Material} material - The Material that will be applied.
* @param {p2.Shape} [shape] - An optional Shape. If not provided the Material will be added to all Shapes in this Body.
*/
setMaterial: function (material, shape) {
if (typeof shape === 'undefined')
{
for (var i = this.data.shapes.length - 1; i >= 0; i--)
{
this.data.shapes[i].material = material;
}
}
else
{
shape.material = material;
}
},
/**
* Reads the shape data from a physics data file stored in the Game.Cache and adds it as a polygon to this Body.
*
* @method Phaser.Physics.Body#loadPolygon
* @param {string} key - The key of the Physics Data file as stored in Game.Cache.
* @param {string} object - The key of the object within the Physics data file that you wish to load the shape data from.
* @param {object} options - An object containing the build options. Note that this isn't used if the data file contains multiple shapes.
* @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.
* @return {boolean} True on success, else false.
*/
loadPolygon: function (key, object, options) {
var data = this.game.cache.getPhysicsData(key, object);
if (data.length === 1)
{
var temp = [];
data = data.pop()
// We've a list of numbers
for (var i = 0, len = data.shape.length; i < len; i += 2)
{
temp.push([data.shape[i], data.shape[i + 1]]);
}
return this.addPolygon(options, temp);
}
else
{
// We've multiple Convex shapes, they should be CCW automatically
var cm = p2.vec2.create();
for (var i = 0; i < data.length; i++)
{
var vertices = [];
for (var s = 0; s < data[i].shape.length; s += 2)
{
vertices.push([ this.px2pi(data[i].shape[s]), this.px2pi(data[i].shape[s + 1]) ]);
}
var c = new p2.Convex(vertices);
// Move all vertices so its center of mass is in the local center of the convex
for (var j = 0; j !== c.vertices.length; j++)
{
var v = c.vertices[j];
p2.vec2.sub(v, v, c.centerOfMass);
}
p2.vec2.scale(cm, c.centerOfMass, 1);
cm[0] -= this.px2pi(this.sprite.width / 2);
cm[1] -= this.px2pi(this.sprite.height / 2);
c.updateTriangles();
c.updateCenterOfMass();
c.updateBoundingRadius();
this.data.addShape(c, cm);
}
// this.data.adjustCenterOfMass();
this.data.aabbNeedsUpdate = true;
return true;
}
return false;
},
/**
* Reads the physics data from a physics data file stored in the Game.Cache.
* It will add the shape data to this Body, as well as set the density (mass), friction and bounce (restitution) values.
*
* @method Phaser.Physics.Body#loadPolygon
* @param {string} key - The key of the Physics Data file as stored in Game.Cache.
* @param {string} object - The key of the object within the Physics data file that you wish to load the shape data from.
* @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.
* @return {boolean} True on success, else false.
*/
loadData: function (key, object, options) {
var data = game.cache.getPhysicsData(key, object);
if (data && data.shape)
{
this.mass = data.density;
// set friction + bounce here
this.loadPolygon(key, object);
}
},
/**
* Convert p2 physics value (meters) to pixel scale.
*
* @method Phaser.Physics.Body#p2px
* @param {number} v - The value to convert.
* @return {number} The scaled value.
*/
p2px: function (v) {
return v *= 20;
},
/**
* Convert pixel value to p2 physics scale (meters).
*
* @method Phaser.Physics.Body#px2p
* @param {number} v - The value to convert.
* @return {number} The scaled value.
*/
px2p: function (v) {
return v * 0.05;
},
/**
* Convert p2 physics value (meters) to pixel scale and inverses it.
*
* @method Phaser.Physics.Body#p2pxi
* @param {number} v - The value to convert.
* @return {number} The scaled value.
*/
p2pxi: function (v) {
return v *= -20;
},
/**
* Convert pixel value to p2 physics scale (meters) and inverses it.
*
* @method Phaser.Physics.Body#px2pi
* @param {number} v - The value to convert.
* @return {number} The scaled value.
*/
px2pi: function (v) {
return v * -0.05;
}
};
Phaser.Physics.Body.prototype.constructor = Phaser.Physics.Body;
/**
* @name Phaser.Physics.Body#static
* @property {boolean} static - Returns true if the Body is static. Setting Body.static to 'false' will make it dynamic.
*/
Object.defineProperty(Phaser.Physics.Body.prototype, "static", {
get: function () {
return (this.data.motionState === Phaser.STATIC);
},
set: function (value) {
if (value && this.data.motionState !== Phaser.STATIC)
{
this.data.motionState = Phaser.STATIC;
this.mass = 0;
}
else if (!value && this.data.motionState === Phaser.STATIC)
{
this.data.motionState = Phaser.DYNAMIC;
if (this.mass === 0)
{
this.mass = 1;
}
}
}
});
/**
* @name Phaser.Physics.Body#dynamic
* @property {boolean} dynamic - Returns true if the Body is dynamic. Setting Body.dynamic to 'false' will make it static.
*/
Object.defineProperty(Phaser.Physics.Body.prototype, "dynamic", {
get: function () {
return (this.data.motionState === Phaser.DYNAMIC);
},
set: function (value) {
if (value && this.data.motionState !== Phaser.DYNAMIC)
{
this.data.motionState = Phaser.DYNAMIC;
if (this.mass === 0)
{
this.mass = 1;
}
}
else if (!value && this.data.motionState === Phaser.DYNAMIC)
{
this.data.motionState = Phaser.STATIC;
this.mass = 0;
}
}
});
/**
* @name Phaser.Physics.Body#kinematic
* @property {boolean} kinematic - Returns true if the Body is kinematic. Setting Body.kinematic to 'false' will make it static.
*/
Object.defineProperty(Phaser.Physics.Body.prototype, "kinematic", {
get: function () {
return (this.data.motionState === Phaser.KINEMATIC);
},
set: function (value) {
if (value && this.data.motionState !== Phaser.KINEMATIC)
{
this.data.motionState = Phaser.KINEMATIC;
this.mass = 4;
}
else if (!value && this.data.motionState === Phaser.KINEMATIC)
{
this.data.motionState = Phaser.STATIC;
this.mass = 0;
}
}
});
/**
* @name Phaser.Physics.Body#allowSleep
* @property {boolean} allowSleep -
*/
Object.defineProperty(Phaser.Physics.Body.prototype, "allowSleep", {
get: function () {
return this.data.allowSleep;
},
set: function (value) {
if (value !== this.data.allowSleep)
{
this.data.allowSleep = value;
}
}
});
/**
* The angle of the Body in degrees from its original orientation. Values from 0 to 180 represent clockwise rotation; values from 0 to -180 represent counterclockwise rotation.
* Values outside this range are added to or subtracted from 360 to obtain a value within the range. For example, the statement Body.angle = 450 is the same as Body.angle = 90.
* If you wish to work in radians instead of degrees use the property Body.rotation instead. Working in radians is faster as it doesn't have to convert values.
*
* @name Phaser.Physics.Body#angle
* @property {number} angle - The angle of this Body in degrees.
*/
Object.defineProperty(Phaser.Physics.Body.prototype, "angle", {
get: function() {
return Phaser.Math.wrapAngle(Phaser.Math.radToDeg(this.data.angle));
},
set: function(value) {
this.data.angle = Phaser.Math.degToRad(Phaser.Math.wrapAngle(value));
}
});
/**
* Damping is specified as a value between 0 and 1, which is the proportion of velocity lost per second.
* @name Phaser.Physics.Body#angularDamping
* @property {number} angularDamping - The angular damping acting acting on the body.
*/
Object.defineProperty(Phaser.Physics.Body.prototype, "angularDamping", {
get: function () {
return this.data.angularDamping;
},
set: function (value) {
this.data.angularDamping = value;
}
});
/**
* @name Phaser.Physics.Body#angularForce
* @property {number} angularForce - The angular force acting on the body.
*/
Object.defineProperty(Phaser.Physics.Body.prototype, "angularForce", {
get: function () {
return this.data.angularForce;
},
set: function (value) {
this.data.angularForce = value;
}
});
/**
* @name Phaser.Physics.Body#angularVelocity
* @property {number} angularVelocity - The angular velocity of the body.
*/
Object.defineProperty(Phaser.Physics.Body.prototype, "angularVelocity", {
get: function () {
return this.data.angularVelocity;
},
set: function (value) {
this.data.angularVelocity = value;
}
});
/**
* Damping is specified as a value between 0 and 1, which is the proportion of velocity lost per second.
* @name Phaser.Physics.Body#damping
* @property {number} damping - The linear damping acting on the body in the velocity direction.
*/
Object.defineProperty(Phaser.Physics.Body.prototype, "damping", {
get: function () {
return this.data.damping;
},
set: function (value) {
this.data.damping = value;
}
});
/**
* @name Phaser.Physics.Body#fixedRotation
* @property {boolean} fixedRotation -
*/
Object.defineProperty(Phaser.Physics.Body.prototype, "fixedRotation", {
get: function () {
return this.data.fixedRotation;
},
set: function (value) {
if (value !== this.data.fixedRotation)
{
this.data.fixedRotation = value;
// update anything?
}
}
});
/**
* @name Phaser.Physics.Body#inertia
* @property {number} inertia - The inertia of the body around the Z axis..
*/
Object.defineProperty(Phaser.Physics.Body.prototype, "inertia", {
get: function () {
return this.data.inertia;
},
set: function (value) {
this.data.inertia = value;
}
});
/**
* @name Phaser.Physics.Body#mass
* @property {number} mass -
*/
Object.defineProperty(Phaser.Physics.Body.prototype, "mass", {
get: function () {
return this.data.mass;
},
set: function (value) {
if (value !== this.data.mass)
{
this.data.mass = value;
this.data.updateMassProperties();
if (value === 0)
{
// this.static = true;
}
}
}
});
/**
* @name Phaser.Physics.Body#motionState
* @property {number} motionState - The type of motion this body has. Should be one of: Body.STATIC (the body does not move), Body.DYNAMIC (body can move and respond to collisions) and Body.KINEMATIC (only moves according to its .velocity).
*/
Object.defineProperty(Phaser.Physics.Body.prototype, "motionState", {
get: function () {
return this.data.motionState;
},
set: function (value) {
if (value !== this.data.motionState)
{
this.data.motionState = value;
// update?
}
}
});
/**
* The angle of the Body in radians.
* If you wish to work in degrees instead of radians use the Body.angle property instead. Working in radians is faster as it doesn't have to convert values.
*
* @name Phaser.Physics.Body#rotation
* @property {number} rotation - The angle of this Body in radians.
*/
Object.defineProperty(Phaser.Physics.Body.prototype, "rotation", {
get: function() {
return this.data.angle;
},
set: function(value) {
this.data.angle = value;
}
});
/**
* @name Phaser.Physics.Body#sleepSpeedLimit
* @property {number} sleepSpeedLimit - .
*/
Object.defineProperty(Phaser.Physics.Body.prototype, "sleepSpeedLimit", {
get: function () {
return this.data.sleepSpeedLimit;
},
set: function (value) {
this.data.sleepSpeedLimit = value;
}
});
/**
* @name Phaser.Physics.Body#x
* @property {number} x - The x coordinate of this Body.
*/
Object.defineProperty(Phaser.Physics.Body.prototype, "x", {
get: function () {
return this.p2pxi(this.data.position[0]);
},
set: function (value) {
this.data.position[0] = this.px2pi(value);
}
});
/**
* @name Phaser.Physics.Body#y
* @property {number} y - The y coordinate of this Body.
*/
Object.defineProperty(Phaser.Physics.Body.prototype, "y", {
get: function () {
return this.p2pxi(this.data.position[1]);
},
set: function (value) {
this.data.position[1] = this.px2pi(value);
}
});
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2014 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* Creates a spring, connecting two bodies.
*
* @class Phaser.Physics.P2.Spring
* @classdesc Physics Spring Constructor
* @constructor
* @param {Phaser.Game} game - A reference to the current game.
* @param {p2.Body} bodyA - First connected body.
* @param {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, i.e. [32, 32].
* @param {Array} [worldB] - Where to hook the spring to body B, in world coordinates, i.e. [32, 32].
* @param {Array} [localA] - Where to hook the spring to body A, in local body coordinates.
* @param {Array} [localB] - Where to hook the spring to body B, in local body coordinates.
*/
Phaser.Physics.P2.Spring = function (game, bodyA, bodyB, restLength, stiffness, damping, worldA, worldB, localA, localB) {
/**
* @property {Phaser.Game} game - Local reference to game.
*/
this.game = game;
if (typeof restLength === 'undefined') { restLength = 1; }
if (typeof stiffness === 'undefined') { stiffness = 100; }
if (typeof damping === 'undefined') { damping = 1; }
var options = {
restLength: restLength,
stiffness: stiffness,
damping: damping
};
if (typeof worldA !== 'undefined' && worldA !== null)
{
options.worldAnchorA = [ game.math.px2p(worldA[0]), game.math.px2p(worldA[1]) ];
}
if (typeof worldB !== 'undefined' && worldB !== null)
{
options.worldAnchorB = [ game.math.px2p(worldB[0]), game.math.px2p(worldB[1]) ];
}
if (typeof localA !== 'undefined' && localA !== null)
{
options.localAnchorA = [ game.math.px2p(localA[0]), game.math.px2p(localA[1]) ];
}
if (typeof localB !== 'undefined' && localB !== null)
{
options.localAnchorB = [ game.math.px2p(localB[0]), game.math.px2p(localB[1]) ];
}
p2.Spring.call(this, bodyA, bodyB, options);
}
Phaser.Physics.P2.Spring.prototype = Object.create(p2.Spring.prototype);
Phaser.Physics.P2.Spring.prototype.constructor = Phaser.Physics.P2.Spring;
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2014 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* \o/ ~ "Because I'm a Material girl"
*
* @class Phaser.Physics.P2.Material
* @classdesc Physics Material Constructor
* @constructor
*/
Phaser.Physics.P2.Material = function (name) {
/**
* @property {string} name - The user defined name given to this Material.
* @default
*/
this.name = name;
p2.Material.call(this);
}
Phaser.Physics.P2.Material.prototype = Object.create(p2.Material.prototype);
Phaser.Physics.P2.Material.prototype.constructor = Phaser.Physics.P2.Material;
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2014 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* Defines a physics material
*
* @class Phaser.Physics.P2.ContactMaterial
* @classdesc Physics ContactMaterial Constructor
* @constructor
* @param {Phaser.Physics.P2.Material} materialA
* @param {Phaser.Physics.P2.Material} materialB
* @param {object} [options]
*/
Phaser.Physics.P2.ContactMaterial = function (materialA, materialB, options) {
/**
* @property {number} id - The contact material identifier.
*/
/**
* @property {Phaser.Physics.P2.Material} materialA - First material participating in the contact material.
*/
/**
* @property {Phaser.Physics.P2.Material} materialB - First second participating in the contact material.
*/
/**
* @property {number} [friction=0.3] - Friction to use in the contact of these two materials.
*/
/**
* @property {number} [restitution=0.0] - Restitution to use in the contact of these two materials.
*/
/**
* @property {number} [stiffness=1e7] - Stiffness of the resulting ContactEquation that this ContactMaterial generate.
*/
/**
* @property {number} [relaxation=3] - Relaxation of the resulting ContactEquation that this ContactMaterial generate.
*/
/**
* @property {number} [frictionStiffness=1e7] - Stiffness of the resulting FrictionEquation that this ContactMaterial generate.
*/
/**
* @property {number} [frictionRelaxation=3] - Relaxation of the resulting FrictionEquation that this ContactMaterial generate.
*/
/**
* @property {number} [surfaceVelocity=0] - Will add surface velocity to this material. If bodyA rests on top if bodyB, and the surface velocity is positive, bodyA will slide to the right.
*/
p2.ContactMaterial.call(this, materialA, materialB, options);
}
Phaser.Physics.P2.ContactMaterial.prototype = Object.create(p2.ContactMaterial.prototype);
Phaser.Physics.P2.ContactMaterial.prototype.constructor = Phaser.Physics.P2.ContactMaterial;
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2014 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* Collision Group
*
* @class Phaser.Physics.P2.CollisionGroup
* @classdesc Physics Collision Group Constructor
* @constructor
*/
Phaser.Physics.P2.CollisionGroup = function (bitmask) {
/**
* @property {number} mask - The CollisionGroup bitmask.
*/
this.mask = bitmask;
}