/build/custom/phaser-no-libs.js
JavaScript | 16212 lines | 7143 code | 3164 blank | 5905 comment | 1359 complexity | f8926a3df663dda348ed503c0eeb39a1 MD5 | raw file
- /**
- * @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://phaser.io
- *
- * v2.0.3 "Allorallen" - Built: Fri Apr 11 2014 13:08:30
- *
- * 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 rendering.
- *
- * 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 originate.
- *
- * 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;
- /* global Phaser: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}
- */
- /**
- * @namespace Phaser
- */
- var Phaser = Phaser || {
- VERSION: '<%= version %>',
- DEV_VERSION: '2.0.3',
- GAMES: [],
- AUTO: 0,
- CANVAS: 1,
- WEBGL: 2,
- HEADLESS: 3,
- NONE: 0,
- LEFT: 1,
- RIGHT: 2,
- UP: 3,
- DOWN: 4,
- 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,
- RETROFONT: 18,
- // 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 () {
- // 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 = new 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 = new Array(left+1).join(pad) + str + new Array(right+1).join(pad);
- break;
- default:
- str = str + new 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 && !({}).hasOwnProperty.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;
- },
- /**
- * 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') {
- /* jshint freeze: false */
- 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 polyfill for Array.isArray
- */
- if (!Array.isArray)
- {
- Array.isArray = function (arg)
- {
- return Object.prototype.toString.call(arg) == '[object Array]';
- };
- }
- /**
- * A polyfill for Array.forEach
- * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
- */
- if (!Array.prototype.forEach)
- {
- Array.prototype.forEach = function(fun /*, thisArg */)
- {
- "use strict";
- if (this === void 0 || this === null)
- {
- throw new TypeError();
- }
- var t = Object(this);
- var len = t.length >>> 0;
- if (typeof fun !== "function")
- {
- throw new TypeError();
- }
- var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
- for (var i = 0; i < len; i++)
- {
- if (i in t)
- {
- fun.call(thisArg, t[i], i, t);
- }
- }
- };
- }
- /**
- * @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));
- };
- /**
- * Calculates centroid (or midpoint) from an array of points. If only one point is provided, that point is returned.
- * @method Phaser.Point.centroid
- * @param {Phaser.Point[]} points - The array of one or more points.
- * @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.centroid = function (points, out) {
- if (typeof out === "undefined") { out = new Phaser.Point(); }
- if (Object.prototype.toString.call(points) !== '[object Array]')
- {
- throw new Error("Phaser.Point. Parameter 'points' must be an array");
- }
- var pointslength = points.length;
- if (pointslength < 1)
- {
- throw new Error("Phaser.Point. Parameter 'points' array must not be empty");
- }
- if (pointslength === 1)
- {
- out.copyFrom(points[0]);
- return out;
- }
- for (var i = 0; i < pointslength; i++)
- {
- Phaser.Point.add(out, points[i], out);
- }
- out.divide(pointslength, pointslength);
- return out;
- };
- // 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
- */
- Object.defineProperty(Phaser.Rectangle.prototype, "halfWidth", {
- get: function () {
- return Math.round(this.width / 2);
- }
- });
- /**
- * @name Phaser.Rectangle#halfHeight
- * @property {number} halfHeight - Half of the height of the Rectangle.
- * @readonly
- */
- Object.defineProperty(Phaser.Rectangle.prototype, "halfHeight", {
- get: function () {
- 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.
- */
- Object.defineProperty(Phaser.Rectangle.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);
- }
- }
- });
- /**
- * The location of the Rectangles bottom right corner as a Point object.
- * @name Phaser.Rectangle#bottom
- * @property {Phaser.Point} bottomRight - Gets or sets the location of the Rectangles bottom right corner as a Point object.
- */
- Object.defineProperty(Phaser.Rectangle.prototype, "bottomRight", {
- get: function () {
- return new Phaser.Point(this.right, this.bottom);
- },
- set: function (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.
- */
- Object.defineProperty(Phaser.Rectangle.prototype, "left", {
- get: function () {
- return this.x;
- },
- set: function (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.
- */
- Object.defineProperty(Phaser.Rectangle.prototype, "right", {
- get: function () {
- return this.x + this.width;
- },
- set: function (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
- */
- Object.defineProperty(Phaser.Rectangle.prototype, "volume", {
- get: function () {
- 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
- */
- Object.defineProperty(Phaser.Rectangle.prototype, "perimeter", {
- get: function () {
- 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.
- */
- Object.defineProperty(Phaser.Rectangle.prototype, "centerX", {
- get: function () {
- return this.x + this.halfWidth;
- },
- set: function (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.
- */
- Object.defineProperty(Phaser.Rectangle.prototype, "centerY", {
- get: function () {
- return this.y + this.halfHeight;
- },
- set: function (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.
- */
- Object.defineProperty(Phaser.Rectangle.prototype, "top", {
- get: function () {
- return this.y;
- },
- set: function (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.
- */
- Object.defineProperty(Phaser.Rectangle.prototype, "topLeft", {
- get: function () {
- return new Phaser.Point(this.x, this.y);
- },
- set: function (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.
- */
- Object.defineProperty(Phaser.Rectangle.prototype, "empty", {
- get: function () {
- return (!this.width || !this.height);
- },
- set: function (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=false] - If true it will use startSprite.center.x, if false startSprite.x. Note that Sprites don't have a center property by default, so only enable if you've over-ridden your Sprite with a custom class.
- * @return {Phaser.Line} This line object
- */
- fromSprite: function (startSprite, endSprite, useCenter) {
- if (typeof useCenter === 'undefined') { useCenter = false; }
- 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));
- },
- /**
- * Using Bresenham's line algorithm this will return an array of all coordinates on this line.
- * The start and end points are rounded before this runs as the algorithm works on integers.
- *
- * @method Phaser.Line#coordinatesOnLine
- * @param {number} [stepRate=1] - How many steps will we return? 1 = every coordinate on the line, 2 = every other coordinate, etc.
- * @param {array} [results] - The array to store the results in. If not provided a new one will be generated.
- * @return {array} An array of coordinates.
- */
- coordinatesOnLine: function (stepRate, results) {
- if (typeof stepRate === 'undefined') { stepRate = 1; }
- if (typeof results === 'undefined') { results = []; }
- var x1 = Math.round(this.start.x);
- var y1 = Math.round(this.start.y);
- var x2 = Math.round(this.end.x);
- var y2 = Math.round(this.end.y);
- var dx = Math.abs(x2 - x1);
- var dy = Math.abs(y2 - y1);
- var sx = (x1 < x2) ? 1 : -1;
- var sy = (y1 < y2) ? 1 : -1;
- var err = dx - dy;
- results.push([x1, y1]);
- var i = 1;
- while (!((x1 == x2) && (y1 == y2)))
- {
- var e2 = err << 1;
- if (e2 > -dy)
- {
- err -= dy;
- x1 += sx;
- }
- if (e2 < dx)
- {
- err += dx;
- y1 += sy;
- }
- if (i % stepRate === 0)
- {
- results.push([x1, y1]);
- }
- i++;
- }
- return results;
- }
- };
- /**
- * @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));
- }
- });
- /**
- * @name Phaser.Line#x
- * @property {number} x - Gets the x coordinate of the top left of the bounds around this line.
- * @readonly
- */
- Object.defineProperty(Phaser.Line.prototype, "x", {
- get: function () {
- return Math.min(this.start.x, this.end.x);
- }
- });
- /**
- * @name Phaser.Line#y
- * @property {number} y - Gets the y coordinate of the top left of the bounds around this line.
- * @readonly
- */
- Object.defineProperty(Phaser.Line.prototype, "y", {
- get: function () {
- return Math.min(this.start.y, this.end.y);
- }
- });
- /**
- * @name Phaser.Line#left
- * @property {number} left - Gets the left-most point of this line.
- * @readonly
- */
- Object.defineProperty(Phaser.Line.prototype, "left", {
- get: function () {
- return Math.min(this.start.x, this.end.x);
- }
- });
- /**
- * @name Phaser.Line#right
- * @property {number} right - Gets the right-most point of this line.
- * @readonly
- */
- Object.defineProperty(Phaser.Line.prototype, "right", {
- get: function () {
- return Math.max(this.start.x, this.end.x);
- }
- });
- /**
- * @name Phaser.Line#top
- * @property {number} top - Gets the top-most point of this line.
- * @readonly
- */
- Object.defineProperty(Phaser.Line.prototype, "top", {
- get: function () {
- return Math.min(this.start.y, this.end.y);
- }
- });
- /**
- * @name Phaser.Line#bottom
- * @property {number} bottom - Gets the bottom-most point of this line.
- * @readonly
- */
- Object.defineProperty(Phaser.Line.prototype, "bottom", {
- get: function () {
- return Math.max(this.start.y, this.end.y);
- }
- });
- /**
- * @name Phaser.Line#width
- * @property {number} width - Gets the width of this bounds of this line.
- * @readonly
- */
- Object.defineProperty(Phaser.Line.prototype, "width", {
- get: function () {
- return Math.abs(this.start.x - this.end.x);
- }
- });
- /**
- * @name Phaser.Line#height
- * @property {number} height - Gets the height of this bounds of this line.
- * @readonly
- */
- Object.defineProperty(Phaser.Line.prototype, "height", {
- get: function () {
- return Math.abs(this.start.y - this.end.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 + value;
- }
- }
- });
- /**
- * 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 Phaser.Ellipse.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.Time} time - Reference to the core 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} 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 shut down (i.e. you switch to another state from this one).
- * @method Phaser.State#shutdown
- */
- shutdown: 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);
- }
- }
- },
- /**
- * Restarts the current State. State.shutDown will be called (if it exists) before the State is restarted.
- *
- * @method Phaser.StateManager#restart
- * @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.
- */
- restart: function (clearWorld, clearCache) {
- if (typeof clearWorld === "undefined") { clearWorld = true; }
- if (typeof clearCache === "undefined") { clearCache = false; }
- // Place the state in the queue. It will be started the next time the game loop starts.
- this._pendingState = this.current;
- 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);
- this.game.tweens.removeAll();
- this.game.camera.reset();
- this.game.input.reset(true);
- this.game.physics.clear();
- this.game.time.removeAll();
- if (this._clearWorld)
- {
- this.game.world.shutdown();
- 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);
- }
- }
- },
- /**
- * Removes all StateManager callback references to the State object, nulls the game reference and clears the States object.
- * You don't recover from this without rebuilding the Phaser instance again.
- * @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}
- */
- /**
- * @class Phaser.SignalBinding
- * @classdesc 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.
- *
- * @author Miller Medeiros http://millermedeiros.github.com/js-signals/
- * @constructor
- * @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).
- */
- 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.
- */
- Phaser.PluginManager = function(game) {
- /**
- * @property {Phaser.Game} game - A reference to the currently running game.
- */
- this.game = game;
- /**
- * @property {array} plugins - An array of all the plugins being managed by this PluginManager.
- */
- this.plugins = [];
- /**
- * @property {number} _len - Internal cache var.
- * @private
- */
- this._len = 0;
- /**
- * @property {number} _i - Internal cache var.
- * @private
- */
- this._i = 0;
- };
- Phaser.PluginManager.prototype = {
- /**
- * Add a new Plugin into the PluginManager.
- * The Plugin must have 2 properties: game and parent. Plugin.game is set to ths game reference the PluginManager uses, and parent is set to the PluginManager.
- *
- * @method Phaser.PluginManager#add
- * @param {object|Phaser.Plugin} plugin - The Plugin to add into the PluginManager. This can be a function or an existing object.
- * @return {Phaser.Plugin} The Plugin that was added to the manager.
- */
- 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;
- }
- // 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._len = 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. It calls Plugin.destroy on the plugin before removing it from the manager.
- *
- * @method Phaser.PluginManager#remove
- * @param {Phaser.Plugin} plugin - The plugin to be removed.
- */
- remove: function (plugin) {
- this._i = this._len;
- while (this._i--)
- {
- if (this.plugins[this._i] === plugin)
- {
- plugin.destroy();
- this.plugins.splice(this._i, 1);
- this._len--;
- return;
- }
- }
- },
- /**
- * Remove all Plugins from the PluginManager. It calls Plugin.destroy on every plugin before removing it from the manager.
- *
- * @method Phaser.PluginManager#removeAll
- */
- removeAll: function() {
- this._i = this._len;
- while (this._i--)
- {
- this.plugins[this._i].destroy();
- }
- this.plugins.length = 0;
- this._len = 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 () {
- this._i = this._len;
- while (this._i--)
- {
- if (this.plugins[this._i].active && this.plugins[this._i].hasPreUpdate)
- {
- this.plugins[this._i].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 () {
- this._i = this._len;
- while (this._i--)
- {
- if (this.plugins[this._i].active && this.plugins[this._i].hasUpdate)
- {
- this.plugins[this._i].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 () {
- this._i = this._len;
- while (this._i--)
- {
- if (this.plugins[this._i].active && this.plugins[this._i].hasPostUpdate)
- {
- this.plugins[this._i].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 () {
- this._i = this._len;
- while (this._i--)
- {
- if (this.plugins[this._i].visible && this.plugins[this._i].hasRender)
- {
- this.plugins[this._i].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 () {
- this._i = this._len;
- while (this._i--)
- {
- if (this.plugins[this._i].visible && this.plugins[this._i].hasPostRender)
- {
- this.plugins[this._i].postRender();
- }
- }
- },
- /**
- * Clear down this PluginManager, calls destroy on every plugin and nulls out references.
- *
- * @method Phaser.PluginManager#destroy
- */
- destroy: function () {
- this.removeAll();
- this.game = 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 = 0x000000;
- 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);
- }
- 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.focusLoss(event);
- }
- else if (event.type === 'pageshow' || event.type === 'focus')
- {
- this.game.focusGain(event);
- }
- return;
- }
- if (document.hidden || document.mozHidden || document.msHidden || document.webkitHidden)
- {
- this.game.gamePaused(event);
- }
- else
- {
- this.game.gameResumed(event);
- }
- };
- /**
- * 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.
- * @param {boolean} [enableBody=false] - If true all Sprites created with `Group.create` or `Group.createMulitple` will have a physics body created on them. Change the body type with physicsBodyType.
- * @param {number} [physicsBodyType=0] - If 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.
- */
- Phaser.Group = function (game, parent, name, addToStage, enableBody, physicsBodyType) {
- if (typeof addToStage === 'undefined') { addToStage = false; }
- if (typeof enableBody === 'undefined') { enableBody = false; }
- if (typeof physicsBodyType === 'undefined') { physicsBodyType = Phaser.Physics.ARCADE; }
- /**
- * @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} z - The z-depth value of this object within its Group (remember the World is a Group as well). No two objects in a Group can have the same z value.
- */
- this.z = 0;
- /**
- * @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 by, or added to this Group, will have a physics body enabled on them. Change the body type with `Group.physicsBodyType`.
- * @default
- */
- this.enableBody = enableBody;
- /**
- * @property {boolean} enableBodyDebug - If true when a physics body is created (via Group.enableBody) it will create a physics debug object as well. Only works for P2 bodies.
- */
- this.enableBodyDebug = 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 = physicsBodyType;
- /**
- * @property {string} _sortProperty - The property on which children are sorted.
- * @private
- */
- this._sortProperty = 'z';
- /**
- * 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
- * 9 = sort order
- * @property {Array} _cache
- * @private
- */
- this._cache = [ 0, 0, 0, 0, 1, 0, 1, 0, 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)
- {
- if (this.enableBody)
- {
- this.game.physics.enable(child, this.physicsBodyType);
- }
- this.addChild(child);
- child.z = this.children.length;
- 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)
- {
- if (this.enableBody)
- {
- this.game.physics.enable(child, this.physicsBodyType);
- }
- this.addChildAt(child, index);
- this.updateZ();
- 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);
- if (this.enableBody)
- {
- this.game.physics.enable(child, this.physicsBodyType);
- }
- child.exists = exists;
- child.visible = exists;
- child.alive = exists;
- this.addChild(child);
- child.z = this.children.length;
- if (child.events)
- {
- child.events.onAddedToGroup.dispatch(child, this);
- }
- if (this.cursor === null)
- {
- this.cursor = child;
- }
- 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);
- }
- };
- /**
- * Internal method that re-applies all of the childrens Z values.
- *
- * @method Phaser.Group#updateZ
- * @protected
- */
- Phaser.Group.prototype.updateZ = function () {
- var i = this.children.length;
- while (i--)
- {
- this.children[i].z = i;
- }
- };
- /**
- * 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
- * @return {*} The child the cursor now points to.
- */
- Phaser.Group.prototype.next = function () {
- if (this.cursor)
- {
- // Wrap the cursor?
- if (this._cache[8] >= this.children.length - 1)
- {
- this._cache[8] = 0;
- }
- else
- {
- this._cache[8]++;
- }
- this.cursor = this.children[this._cache[8]];
- return this.cursor;
- }
- };
- /**
- * 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
- * @return {*} The child the cursor now points to.
- */
- 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]];
- return this.cursor;
- }
- };
- /**
- * 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) {
- var result = this.swapChildren(child1, child2);
- if (result)
- {
- this.updateZ();
- }
- return result;
- };
- /**
- * 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(child, 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(child, 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();
- this.updateZ();
- };
- /**
- * Get the index position of the given child in this Group. This should always match the childs z property.
- *
- * @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.
- * @return {*} Returns the oldChild that was replaced within 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);
- if (newChild.parent instanceof Phaser.Group)
- {
- newChild.parent.updateZ();
- }
- }
- var temp = oldChild;
- this.remove(temp);
- this.addAt(newChild, index);
- return temp;
- }
- };
- /**
- * 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.
- * This call doesn't descend down children, so if you have a Group inside of this Group, the property will be set on the Group but not its children.
- * If you need that ability please see `Group.setAllChildren`.
- *
- * 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. This includes any Groups that are children.
- * @param {boolean} [checkVisible=false] - If set then only children with visible=true will be updated. This includes any Groups that are children.
- * @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);
- }
- }
- };
- /**
- * This function allows you to quickly set the same property across all children of this Group, and any child Groups, to a new value.
- *
- * If this Group contains other Groups then the same property is set across their children as well, iterating down until it reaches the bottom.
- * Unlike with Group.setAll the property is NOT set on child Groups itself.
- *
- * The operation parameter controls how the new value is assigned to the property, from simple replacement to addition and multiplication.
- *
- * @method Phaser.Group#setAllChildren
- * @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. This includes any Groups that are children.
- * @param {boolean} [checkVisible=false] - If set then only children with visible=true will be updated. This includes any Groups that are children.
- * @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.setAllChildren = function (key, value, checkAlive, checkVisible, operation) {
- 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)))
- {
- if (this.children[i] instanceof Phaser.Group)
- {
- this.children[i].setAllChildren(key, value, checkAlive, checkVisible, operation);
- }
- else
- {
- this.setProperty(this.children[i], key.split('.'), 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=false] - 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='z'] - The `string` name of the property you want to sort on. Defaults to the objects z-depth value.
- * @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 (this.children.length < 2)
- {
- // Nothing to swap
- return;
- }
- if (typeof index === 'undefined') { index = 'z'; }
- if (typeof order === 'undefined') { order = Phaser.Group.SORT_ASCENDING; }
- this._sortProperty = index;
- if (order === Phaser.Group.SORT_ASCENDING)
- {
- this.children.sort(this.ascendingSortHandler.bind(this));
- }
- else
- {
- this.children.sort(this.descendingSortHandler.bind(this));
- }
- this.updateZ();
- };
- /**
- * This allows you to use your own sort handler function.
- * It will be sent two parameters: the two children involved in the comparison (a and b). It should return -1 if a > b, 1 if a < b or 0 if a === b.
- *
- * @method Phaser.Group#customSort
- * @param {function} sortHandler - Your sort handler function. It will be sent two parameters: the two children involved in the comparison. It must return -1, 1 or 0.
- * @param {object} context - The scope in which the sortHandler is called.
- */
- Phaser.Group.prototype.customSort = function (sortHandler, context) {
- if (this.children.length < 2)
- {
- // Nothing to swap
- return;
- }
- this.children.sort(sortHandler.bind(context));
- this.updateZ();
- };
- /**
- * An internal helper function for the sort process.
- *
- * @method Phaser.Group#ascendingSortHandler
- * @param {object} a - The first object being sorted.
- * @param {object} b - The second object being sorted.
- */
- Phaser.Group.prototype.ascendingSortHandler = function (a, b) {
- if (a[this._sortProperty] < b[this._sortProperty])
- {
- return -1;
- }
- else if (a[this._sortProperty] > b[this._sortProperty])
- {
- return 1;
- }
- else
- {
- if (a.z < b.z)
- {
- return -1;
- }
- else
- {
- return 1;
- }
- }
- };
- /**
- * An internal helper function for the sort process.
- *
- * @method Phaser.Group#descendingSortHandler
- * @param {object} a - The first object being sorted.
- * @param {object} b - The second object being sorted.
- */
- Phaser.Group.prototype.descendingSortHandler = function (a, b) {
- if (a[this._sortProperty] < b[this._sortProperty])
- {
- return 1;
- }
- else if (a[this._sortProperty] > b[this._sortProperty])
- {
- return -1;
- }
- else
- {
- return 0;
- }
- };
- /**
- * 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);
- };
- /**
- * Returns the child at the top of this Group. The top is the one being displayed (rendered) above every other child.
- *
- * @method Phaser.Group#getTop
- * @return {Any} The child at the top of the Group.
- */
- Phaser.Group.prototype.getTop = function () {
- if (this.children.length > 0)
- {
- return this.children[this.children.length - 1];
- }
- };
- /**
- * Returns the child at the bottom of this Group. The bottom is the one being displayed (rendered) below every other child.
- *
- * @method Phaser.Group#getBottom
- * @return {Any} The child at the bottom of the Group.
- */
- Phaser.Group.prototype.getBottom = function () {
- if (this.children.length > 0)
- {
- return this.children[0];
- }
- };
- /**
- * 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.
- * @param {boolean} [destroy=false] - You can optionally call destroy on the child that was removed.
- * @return {boolean} true if the child was removed from this Group, otherwise false.
- */
- Phaser.Group.prototype.remove = function (child, destroy) {
- if (typeof destroy === 'undefined') { destroy = false; }
- if (this.children.length === 0)
- {
- return false;
- }
- if (child.events)
- {
- child.events.onRemovedFromGroup.dispatch(child, this);
- }
- this.removeChild(child);
- this.updateZ();
- if (this.cursor === child)
- {
- this.next();
- }
- if (destroy)
- {
- child.destroy();
- }
- 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
- * @param {boolean} [destroy=false] - You can optionally call destroy on the child that was removed.
- */
- Phaser.Group.prototype.removeAll = function (destroy) {
- if (typeof destroy === 'undefined') { destroy = false; }
- 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]);
- if (destroy)
- {
- this.children[0].destroy();
- }
- }
- 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 at. Must be higher than startIndex. If undefined this method will remove all children between startIndex and the end of the Group.
- * @param {boolean} [destroy=false] - You can optionally call destroy on the child that was removed.
- */
- Phaser.Group.prototype.removeBetween = function (startIndex, endIndex, destroy) {
- if (typeof endIndex === 'undefined') { endIndex = this.children.length; }
- if (typeof destroy === 'undefined') { destroy = false; }
- if (this.children.length === 0)
- {
- return;
- }
- if (startIndex > endIndex || startIndex < 0 || endIndex > this.children.length)
- {
- return false;
- }
- var i = endIndex;
- while (i >= startIndex)
- {
- if (this.children[i].events)
- {
- this.children[i].events.onRemovedFromGroup.dispatch(this.children[i], this);
- }
- this.removeChild(this.children[i]);
- if (destroy)
- {
- this.children[i].destroy();
- }
- if (this.cursor === this.children[i])
- {
- this.cursor = null;
- }
- i--;
- }
- this.updateZ();
- };
- /**
- * 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?
- * @param {boolean} [soft=false] - A 'soft destroy' (set to true) doesn't remove this Group from its parent or null the game reference. Set to false and it does.
- */
- Phaser.Group.prototype.destroy = function (destroyChildren, soft) {
- if (this.game === null) { return; }
- if (typeof destroyChildren === 'undefined') { destroyChildren = true; }
- if (typeof soft === 'undefined') { soft = false; }
- 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.cursor = null;
- if (!soft)
- {
- this.parent.removeChild(this);
- this.game = null;
- this.exists = false;
- }
- };
- /**
- * @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);
- }
- this.game.physics.setBoundsToWorld();
- };
- /**
- * Destroyer of worlds.
- *
- * @method Phaser.World#shutdown
- */
- Phaser.World.prototype.shutdown = function () {
- // World is a Group, so run a soft destruction on this and all children.
- this.destroy(true, true);
- };
- /**
- * @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 Phaser.Image(this.game, this.game.width / 2, this.game.height / 2, PIXI.TextureCache[orientationImage]);
- this.orientationSprite.anchor.set(0.5);
- 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 {string|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 {PIXI.CanvasRenderer|PIXI.WebGLRenderer} renderer - The Pixi Renderer.
- */
- this.renderer = null;
- /**
- * @property {number} renderType - The Renderer this game will use. Either Phaser.AUTO, Phaser.CANVAS or Phaser.WEBGL.
- */
- this.renderType = Phaser.AUTO;
- /**
- * @property {Phaser.StateManager} 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.
- */
- 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.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.Time} time - Reference to the core 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.Camera} 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} pendingStep - 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 {Phaser.Signal} onPause - This event is fired when the game pauses.
- */
- this.onPause = null;
- /**
- * @property {Phaser.Signal} onResume - This event is fired when the game resumes from a paused state.
- */
- this.onResume = null;
- /**
- * @property {Phaser.Signal} onBlur - This event is fired when the game no longer has focus (typically on page hide).
- */
- this.onBlur = null;
- /**
- * @property {Phaser.Signal} onFocus - This event is fired when the game has focus (typically on page show).
- */
- this.onFocus = null;
- /**
- * @property {boolean} _paused - Is game paused?
- * @private
- */
- this._paused = false;
- /**
- * @property {boolean} _codePaused - Was the game paused via code or a visibility change?
- * @private
- */
- 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.rnd = new Phaser.RandomDataGenerator([(Date.now() * Math.random()).toString()]);
- 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 seed = [(Date.now() * Math.random()).toString()];
- if (config['seed'])
- {
- seed = config['seed'];
- }
- this.rnd = new Phaser.RandomDataGenerator(seed);
- 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.onBlur = new Phaser.Signal();
- this.onFocus = new Phaser.Signal();
- this.isBooted = true;
- this.device = new Phaser.Device(this);
- this.math = Phaser.Math;
- 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.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';
- var c = 1;
- if (this.renderType === Phaser.WEBGL)
- {
- r = 'WebGL';
- c++;
- }
- else if (this.renderType == Phaser.HEADLESS)
- {
- r = 'Headless';
- }
- if (this.device.webAudio)
- {
- a = 'WebAudio';
- c++;
- }
- if (this.device.chrome)
- {
- var args = [
- '%c %c %c Phaser v' + v + ' - ' + r + ' - ' + a + ' %c %c ' + ' http://phaser.io %c %c ♥%c♥%c♥ ',
- 'background: #0cf300',
- 'background: #00bc17',
- 'color: #ffffff; background: #00711f;',
- 'background: #00bc17',
- 'background: #0cf300',
- 'background: #00bc17'
- ];
- for (var i = 0; i < 3; i++)
- {
- if (i < c)
- {
- args.push('color: #ff2424; background: #fff');
- }
- else
- {
- args.push('color: #959595; background: #fff');
- }
- }
- console.log.apply(console, args);
- }
- else
- {
- console.log('Phaser v' + v + ' - Renderer: ' + r + ' - Audio: ' + a + ' - http://phaser.io');
- }
- },
- /**
- * 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;
- }
- if (this.renderType !== Phaser.HEADLESS)
- {
- this.stage.smoothed = this.antialias;
- Phaser.Canvas.addToDOM(this.canvas, this.parent, true);
- Phaser.Canvas.setTouchAction(this.canvas);
- }
- },
- /**
- * The core game loop when in a paused state.
- *
- * @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.pendingStep)
- {
- if (this.stepping)
- {
- this.pendingStep = true;
- }
- this.debug.preUpdate();
- this.physics.preUpdate();
- this.state.preUpdate();
- this.plugins.preUpdate();
- this.stage.preUpdate();
- this.state.update();
- 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();
- }
- else
- {
- this.debug.preUpdate();
- }
- 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 for 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.physics.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
- * @param {object} event - The DOM event that caused the game to pause, if any.
- * @protected
- */
- gamePaused: function (event) {
- // 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();
- this.sound.setMute();
- this.onPause.dispatch(event);
- }
- },
- /**
- * Called by the Stage visibility handler.
- *
- * @method Phaser.Game#gameResumed
- * @param {object} event - The DOM event that caused the game to pause, if any.
- * @protected
- */
- gameResumed: function (event) {
- // Game is paused, but wasn't paused via code, so resume it
- if (this._paused && !this._codePaused)
- {
- this._paused = false;
- this.time.gameResumed();
- this.input.reset();
- this.sound.unsetMute();
- this.onResume.dispatch(event);
- }
- },
- /**
- * Called by the Stage visibility handler.
- *
- * @method Phaser.Game#focusLoss
- * @param {object} event - The DOM event that caused the game to pause, if any.
- * @protected
- */
- focusLoss: function (event) {
- this.onBlur.dispatch(event);
- this.gamePaused(event);
- },
- /**
- * Called by the Stage visibility handler.
- *
- * @method Phaser.Game#focusGain
- * @param {object} event - The DOM event that caused the game to pause, if any.
- * @protected
- */
- focusGain: function (event) {
- this.onFocus.dispatch(event);
- this.gameResumed(event);
- }
- };
- 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 pointer hits the given object.
- *
- * @method Phaser.Input#hitTest
- * @param {DisplayObject} displayObject - The displayObject to test for a hit.
- * @param {Phaser.Pointer} pointer - The pointer to use for the test.
- * @param {Phaser.Point} localPoint - The local translated point.
- */
- 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} enabled - An enabled key processes its update and dispatches events. You can toggle this at run-time to disable a key without deleting it.
- * @default
- */
- this.enabled = true;
- /**
- * @property {object} event - Stores the most recent DOM event.
- * @readonly
- */
- this.event = null;
- /**
- * @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.enabled) { return; }
- 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.enabled) { return; }
- this.event = 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.enabled) { return; }
- this.event = 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. This sets isDown to false, isUp to true, resets the time to be the current time and clears any callbacks
- * associated with the onDown and onUp events and nulls the onHoldCallback if set.
- *
- * @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;
- this.enabled = true;
- this.onDown.removeAll();
- this.onUp.removeAll();
- this.onHoldCallback = null;
- this.onHoldContext = null;
- },
- /**
- * 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;
- /**
- * @property {number} _i - Internal cache var
- * @private
- */
- this._i = 0;
- };
- 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];
- },
- /**
- * Removes a Key object from the Keyboard manager.
- *
- * @method Phaser.Keyboard#removeKey
- * @param {number} keycode - The keycode of the key to remove, i.e. Phaser.Keyboard.UP or Phaser.Keyboard.SPACEBAR
- */
- removeKey: function (keycode) {
- if (this._keys[keycode])
- {
- this._keys[keycode] = null;
- this.removeKeyCapture(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 window.
- * This is called automatically by Phaser.Input and should not normally be invoked directly.
- *
- * @method Phaser.Keyboard#start
- */
- start: function () {
- if (this._onKeyDown !== null)
- {
- // Avoid setting multiple listeners
- return;
- }
- 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 window.
- *
- * @method Phaser.Keyboard#stop
- */
- stop: function () {
- window.removeEventListener('keydown', this._onKeyDown);
- window.removeEventListener('keyup', this._onKeyUp);
- this._onKeyDown = null;
- this._onKeyUp = null;
- },
- /**
- * Stops the Keyboard event listeners from running (keydown and keyup). They are removed from the window.
- * Also clears all key captures and currently created Key objects.
- *
- * @method Phaser.Keyboard#destroy
- */
- destroy: function () {
- this.stop();
- this.clearCaptures();
- this._keys.length = 0;
- this._i = 0;
- },
- /**
- * 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 () {
- this._i = this._keys.length;
- while (this._i--)
- {
- if (this._keys[this._i])
- {
- this._keys[this._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 () {
- 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;
- }
- if (this._onMouseDown !== null)
- {
- // Avoid setting multiple listeners
- return;
- }
- var _this = this;
- 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 () {
- if (this._onMSPointerDown !== null)
- {
- // Avoid setting multiple listeners
- return;
- }
- 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();
-
- /**
- * @property {Phaser.Point} positionUp - A Phaser.Point object containing the x/y values of the pointer when it was last released.
- */
- this.positionUp = 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 = [];
- 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.validForInput(this._highestInputPriorityID, 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;
-
- this.positionUp.setTo(this.x, this.y);
-
- 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 () {
- if (this._onTouchStart !== null)
- {
- // Avoid setting multiple listeners
- return;
- }
- 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 () {
- if (this._active)
- {
- // Avoid setting multiple listeners
- return;
- }
- 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.getGamepads || (navigator.webkitGetGamepads && navigator.webkitGetGamepads()) || navigator.webkitGamepads;
- 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} _setHandCursor - Did this Sprite trigger the hand cursor?
- * @private
- */
- this._setHandCursor = 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 {boolean} _wasEnabled - Internal cache var.
- * @private
- */
- this._wasEnabled = 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;
- this._wasEnabled = 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();
- }
- }
- this.sprite.events.onAddedToGroup.add(this.addedToGroup, this);
- this.sprite.events.onRemovedFromGroup.add(this.removedFromGroup, this);
- return this.sprite;
- },
- /**
- * Handles when the parent Sprite is added to a new Group.
- *
- * @method Phaser.InputHandler#addedToGroup
- * @private
- */
- addedToGroup: function () {
- if (this._wasEnabled && !this.enabled)
- {
- this.start();
- }
- },
- /**
- * Handles when the parent Sprite is removed from a Group.
- *
- * @method Phaser.InputHandler#removedFromGroup
- * @private
- */
- removedFromGroup: function () {
- if (this.enabled)
- {
- this._wasEnabled = true;
- this.stop();
- }
- else
- {
- this._wasEnabled = false;
- }
- },
- /**
- * 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)
- {
- if (this._setHandCursor)
- {
- this.game.canvas.style.cursor = "default";
- this._setHandCursor = false;
- }
- this.enabled = false;
- this.game.input.interactiveItems.remove(this);
- this._pointerData.length = 0;
- this.boundsRect = null;
- this.boundsSprite = null;
- this.sprite = null;
- }
- },
- /**
- * Checks if the object this InputHandler is bound to is valid for consideration in the Pointer move event.
- * This is called by Phaser.Pointer and shouldn't typically be called directly.
- *
- * @method Phaser.InputHandler#validForInput
- * @protected
- * @param {number} highestID - The highest ID currently processed by the Pointer.
- * @param {number} highestRenderID - The highest Render Order ID currently processed by the Pointer.
- * @return {boolean} True if the object this InputHandler is bound to should be considered as valid for input detection.
- */
- validForInput: function (highestID, highestRenderID) {
- if (this.sprite.scale.x === 0 || this.sprite.scale.y === 0)
- {
- return false;
- }
- if (this.pixelPerfectClick || this.pixelPerfectOver)
- {
- return true;
- }
- if (this.priorityID > highestID || (this.priorityID === highestID && this.sprite._cache[3] < highestRenderID))
- {
- return true;
- }
- return false;
- },
- /**
- * 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 || !this.sprite || !this.sprite.parent || !this.sprite.visible || !this.sprite.parent.visible)
- {
- 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 || !this.sprite || !this.sprite.parent || !this.sprite.visible || !this.sprite.parent.visible)
- {
- 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 || this.sprite.parent === undefined)
- {
- // 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._setHandCursor = false;
- }
- 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";
- this._setHandCursor = false;
- }
- 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";
- this._setHandCursor = false;
- }
- }
- // 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)
- {
- var bounds = this.sprite.getBounds();
- this.sprite.x = pointer.x + (this.sprite.x - bounds.centerX);
- this.sprite.y = pointer.y + (this.sprite.y - bounds.centerY);
- 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 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.onEnterBounds = 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.
- * @param {boolean} [enableBody=false] - If true all Sprites created with `Group.create` or `Group.createMulitple` will have a physics body created on them. Change the body type with physicsBodyType.
- * @param {number} [physicsBodyType=0] - If 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.
- * @return {Phaser.Group} The newly created group.
- */
- group: function (parent, name, addToStage, enableBody, physicsBodyType) {
- return new Phaser.Group(this.game, parent, name, addToStage, enableBody, physicsBodyType);
- },
- /**
- * A Group is a container for display objects that allows for fast pooling, recycling and collision checks.
- * A Physics Group is the same as an ordinary Group except that is has enableBody turned on by default, so any Sprites it creates
- * are automatically given a physics body.
- *
- * @method Phaser.GameObjectFactory#group
- * @param {number} [physicsBodyType=Phaser.Physics.ARCADE] - If 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.
- * @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.
- */
- physicsGroup: function (physicsBodyType, parent, name, addToStage) {
- return new Phaser.Group(this.game, parent, name, addToStage, true, physicsBodyType);
- },
- /**
- * 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, key, 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 {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.
- * @param {boolean} [enableBody=false] - If true all Sprites created with `Group.create` or `Group.createMulitple` will have a physics body created on them. Change the body type with physicsBodyType.
- * @param {number} [physicsBodyType=0] - If 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.
- * @return {Phaser.Group} The newly created group.
- */
- group: function (parent, name, addToStage, enableBody, physicsBodyType) {
- return new Phaser.Group(this.game, null, name, addToStage, enableBody, physicsBodyType);
- },
- /**
- * 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) {
- 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) {
- 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.
- * @return {Phaser.Graphics} The newly created graphics object.
- */
- graphics: function (x, y) {
- 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) {
- 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, key, 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