PageRenderTime 118ms CodeModel.GetById 27ms RepoModel.GetById 1ms app.codeStats 1ms

/build/custom/phaser-no-libs.js

https://gitlab.com/lobsterhands/phaser
JavaScript | 16212 lines | 7143 code | 3164 blank | 5905 comment | 1359 complexity | f8926a3df663dda348ed503c0eeb39a1 MD5 | raw file
  1. /**
  2. * @author Richard Davey <rich@photonstorm.com>
  3. * @copyright 2014 Photon Storm Ltd.
  4. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  5. *
  6. * @overview
  7. *
  8. * Phaser - http://phaser.io
  9. *
  10. * v2.0.3 "Allorallen" - Built: Fri Apr 11 2014 13:08:30
  11. *
  12. * By Richard Davey http://www.photonstorm.com @photonstorm
  13. *
  14. * Phaser is a fun, free and fast 2D game framework for making HTML5 games
  15. * for desktop and mobile web browsers, supporting Canvas and WebGL rendering.
  16. *
  17. * Phaser uses Pixi.js for rendering, created by Mat Groves http://matgroves.com @Doormat23
  18. * Phaser uses p2.js for full-body physics, created by Stefan Hedman https://github.com/schteppe/p2.js @schteppe
  19. * Phaser contains a port of N+ Physics, converted by Richard Davey, original by http://www.metanetsoftware.com
  20. *
  21. * Many thanks to Adam Saltsman (@ADAMATOMIC) for releasing Flixel, from which both Phaser
  22. * and my love of framework development originate.
  23. *
  24. * Follow development at http://phaser.io and on our forum
  25. *
  26. * "If you want your children to be intelligent, read them fairy tales."
  27. * "If you want them to be more intelligent, read them more fairy tales."
  28. * -- Albert Einstein
  29. */
  30. /**
  31. * @author Richard Davey <rich@photonstorm.com>
  32. * @copyright 2014 Photon Storm Ltd.
  33. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  34. */
  35. (function(){
  36. var root = this;
  37. /* global Phaser:true */
  38. /**
  39. * @author Richard Davey <rich@photonstorm.com>
  40. * @copyright 2014 Photon Storm Ltd.
  41. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  42. */
  43. /**
  44. * @namespace Phaser
  45. */
  46. var Phaser = Phaser || {
  47. VERSION: '<%= version %>',
  48. DEV_VERSION: '2.0.3',
  49. GAMES: [],
  50. AUTO: 0,
  51. CANVAS: 1,
  52. WEBGL: 2,
  53. HEADLESS: 3,
  54. NONE: 0,
  55. LEFT: 1,
  56. RIGHT: 2,
  57. UP: 3,
  58. DOWN: 4,
  59. SPRITE: 0,
  60. BUTTON: 1,
  61. IMAGE: 2,
  62. GRAPHICS: 3,
  63. TEXT: 4,
  64. TILESPRITE: 5,
  65. BITMAPTEXT: 6,
  66. GROUP: 7,
  67. RENDERTEXTURE: 8,
  68. TILEMAP: 9,
  69. TILEMAPLAYER: 10,
  70. EMITTER: 11,
  71. POLYGON: 12,
  72. BITMAPDATA: 13,
  73. CANVAS_FILTER: 14,
  74. WEBGL_FILTER: 15,
  75. ELLIPSE: 16,
  76. SPRITEBATCH: 17,
  77. RETROFONT: 18,
  78. // The various blend modes supported by pixi / phaser
  79. blendModes: {
  80. NORMAL:0,
  81. ADD:1,
  82. MULTIPLY:2,
  83. SCREEN:3,
  84. OVERLAY:4,
  85. DARKEN:5,
  86. LIGHTEN:6,
  87. COLOR_DODGE:7,
  88. COLOR_BURN:8,
  89. HARD_LIGHT:9,
  90. SOFT_LIGHT:10,
  91. DIFFERENCE:11,
  92. EXCLUSION:12,
  93. HUE:13,
  94. SATURATION:14,
  95. COLOR:15,
  96. LUMINOSITY:16
  97. },
  98. // The scale modes
  99. scaleModes: {
  100. DEFAULT:0,
  101. LINEAR:0,
  102. NEAREST:1
  103. }
  104. };
  105. PIXI.InteractionManager = function () {
  106. // We don't need this in Pixi, so we've removed it to save space
  107. // however the Stage object expects a reference to it, so here is a dummy entry.
  108. };
  109. /* jshint supernew: true */
  110. /**
  111. * @author Richard Davey <rich@photonstorm.com>
  112. * @copyright 2014 Photon Storm Ltd.
  113. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  114. */
  115. /**
  116. * @class Phaser.Utils
  117. * @static
  118. */
  119. Phaser.Utils = {
  120. /**
  121. * Get a unit dimension from a string.
  122. *
  123. * @method Phaser.Utils.parseDimension
  124. * @param {string|number} size - The size to parse.
  125. * @param {number} dimension - The window dimension to check.
  126. * @return {number} The parsed dimension.
  127. */
  128. parseDimension: function (size, dimension) {
  129. var f = 0;
  130. var px = 0;
  131. if (typeof size === 'string')
  132. {
  133. // %?
  134. if (size.substr(-1) === '%')
  135. {
  136. f = parseInt(size, 10) / 100;
  137. if (dimension === 0)
  138. {
  139. px = window.innerWidth * f;
  140. }
  141. else
  142. {
  143. px = window.innerHeight * f;
  144. }
  145. }
  146. else
  147. {
  148. px = parseInt(size, 10);
  149. }
  150. }
  151. else
  152. {
  153. px = size;
  154. }
  155. return px;
  156. },
  157. /**
  158. * A standard Fisher-Yates Array shuffle implementation.
  159. * @method Phaser.Utils.shuffle
  160. * @param {array} array - The array to shuffle.
  161. * @return {array} The shuffled array.
  162. */
  163. shuffle: function (array) {
  164. for (var i = array.length - 1; i > 0; i--)
  165. {
  166. var j = Math.floor(Math.random() * (i + 1));
  167. var temp = array[i];
  168. array[i] = array[j];
  169. array[j] = temp;
  170. }
  171. return array;
  172. },
  173. /**
  174. * Javascript string pad http://www.webtoolkit.info/.
  175. * pad = the string to pad it out with (defaults to a space)
  176. * dir = 1 (left), 2 (right), 3 (both)
  177. * @method Phaser.Utils.pad
  178. * @param {string} str - The target string.
  179. * @param {number} len - The number of characters to be added.
  180. * @param {number} pad - The string to pad it out with (defaults to a space).
  181. * @param {number} [dir=3] The direction dir = 1 (left), 2 (right), 3 (both).
  182. * @return {string} The padded string
  183. */
  184. pad: function (str, len, pad, dir) {
  185. if (typeof(len) == "undefined") { var len = 0; }
  186. if (typeof(pad) == "undefined") { var pad = ' '; }
  187. if (typeof(dir) == "undefined") { var dir = 3; }
  188. var padlen = 0;
  189. if (len + 1 >= str.length)
  190. {
  191. switch (dir)
  192. {
  193. case 1:
  194. str = new Array(len + 1 - str.length).join(pad) + str;
  195. break;
  196. case 3:
  197. var right = Math.ceil((padlen = len - str.length) / 2);
  198. var left = padlen - right;
  199. str = new Array(left+1).join(pad) + str + new Array(right+1).join(pad);
  200. break;
  201. default:
  202. str = str + new Array(len + 1 - str.length).join(pad);
  203. break;
  204. }
  205. }
  206. return str;
  207. },
  208. /**
  209. * This is a slightly modified version of jQuery.isPlainObject. A plain object is an object whose internal class property is [object Object].
  210. * @method Phaser.Utils.isPlainObject
  211. * @param {object} obj - The object to inspect.
  212. * @return {boolean} - true if the object is plain, otherwise false.
  213. */
  214. isPlainObject: function (obj) {
  215. // Not plain objects:
  216. // - Any object or value whose internal [[Class]] property is not "[object Object]"
  217. // - DOM nodes
  218. // - window
  219. if (typeof(obj) !== "object" || obj.nodeType || obj === obj.window)
  220. {
  221. return false;
  222. }
  223. // Support: Firefox <20
  224. // The try/catch suppresses exceptions thrown when attempting to access
  225. // the "constructor" property of certain host objects, ie. |window.location|
  226. // https://bugzilla.mozilla.org/show_bug.cgi?id=814622
  227. try {
  228. if (obj.constructor && !({}).hasOwnProperty.call(obj.constructor.prototype, "isPrototypeOf"))
  229. {
  230. return false;
  231. }
  232. } catch (e) {
  233. return false;
  234. }
  235. // If the function hasn't returned already, we're confident that
  236. // |obj| is a plain object, created by {} or constructed with new Object
  237. return true;
  238. },
  239. /**
  240. * This is a slightly modified version of http://api.jquery.com/jQuery.extend/
  241. * @method Phaser.Utils.extend
  242. * @param {boolean} deep - Perform a deep copy?
  243. * @param {object} target - The target object to copy to.
  244. * @return {object} The extended object.
  245. */
  246. extend: function () {
  247. var options, name, src, copy, copyIsArray, clone,
  248. target = arguments[0] || {},
  249. i = 1,
  250. length = arguments.length,
  251. deep = false;
  252. // Handle a deep copy situation
  253. if (typeof target === "boolean")
  254. {
  255. deep = target;
  256. target = arguments[1] || {};
  257. // skip the boolean and the target
  258. i = 2;
  259. }
  260. // extend Phaser if only one argument is passed
  261. if (length === i)
  262. {
  263. target = this;
  264. --i;
  265. }
  266. for (; i < length; i++)
  267. {
  268. // Only deal with non-null/undefined values
  269. if ((options = arguments[i]) != null)
  270. {
  271. // Extend the base object
  272. for (name in options)
  273. {
  274. src = target[name];
  275. copy = options[name];
  276. // Prevent never-ending loop
  277. if (target === copy)
  278. {
  279. continue;
  280. }
  281. // Recurse if we're merging plain objects or arrays
  282. if (deep && copy && (Phaser.Utils.isPlainObject(copy) || (copyIsArray = Array.isArray(copy))))
  283. {
  284. if (copyIsArray)
  285. {
  286. copyIsArray = false;
  287. clone = src && Array.isArray(src) ? src : [];
  288. }
  289. else
  290. {
  291. clone = src && Phaser.Utils.isPlainObject(src) ? src : {};
  292. }
  293. // Never move original objects, clone them
  294. target[name] = Phaser.Utils.extend(deep, clone, copy);
  295. // Don't bring in undefined values
  296. }
  297. else if (copy !== undefined)
  298. {
  299. target[name] = copy;
  300. }
  301. }
  302. }
  303. }
  304. // Return the modified object
  305. return target;
  306. }
  307. };
  308. /**
  309. * A polyfill for Function.prototype.bind
  310. */
  311. if (typeof Function.prototype.bind != 'function') {
  312. /* jshint freeze: false */
  313. Function.prototype.bind = (function () {
  314. var slice = Array.prototype.slice;
  315. return function (thisArg) {
  316. var target = this, boundArgs = slice.call(arguments, 1);
  317. if (typeof target != 'function')
  318. {
  319. throw new TypeError();
  320. }
  321. function bound() {
  322. var args = boundArgs.concat(slice.call(arguments));
  323. target.apply(this instanceof bound ? this : thisArg, args);
  324. }
  325. bound.prototype = (function F(proto) {
  326. if (proto)
  327. {
  328. F.prototype = proto;
  329. }
  330. if (!(this instanceof F))
  331. {
  332. return new F;
  333. }
  334. })(target.prototype);
  335. return bound;
  336. };
  337. })();
  338. }
  339. /**
  340. * A polyfill for Array.isArray
  341. */
  342. if (!Array.isArray)
  343. {
  344. Array.isArray = function (arg)
  345. {
  346. return Object.prototype.toString.call(arg) == '[object Array]';
  347. };
  348. }
  349. /**
  350. * A polyfill for Array.forEach
  351. * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
  352. */
  353. if (!Array.prototype.forEach)
  354. {
  355. Array.prototype.forEach = function(fun /*, thisArg */)
  356. {
  357. "use strict";
  358. if (this === void 0 || this === null)
  359. {
  360. throw new TypeError();
  361. }
  362. var t = Object(this);
  363. var len = t.length >>> 0;
  364. if (typeof fun !== "function")
  365. {
  366. throw new TypeError();
  367. }
  368. var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
  369. for (var i = 0; i < len; i++)
  370. {
  371. if (i in t)
  372. {
  373. fun.call(thisArg, t[i], i, t);
  374. }
  375. }
  376. };
  377. }
  378. /**
  379. * @author Richard Davey <rich@photonstorm.com>
  380. * @copyright 2014 Photon Storm Ltd.
  381. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  382. */
  383. /**
  384. * 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.
  385. * @class Circle
  386. * @classdesc Phaser - Circle
  387. * @constructor
  388. * @param {number} [x=0] - The x coordinate of the center of the circle.
  389. * @param {number} [y=0] - The y coordinate of the center of the circle.
  390. * @param {number} [diameter=0] - The diameter of the circle.
  391. * @return {Phaser.Circle} This circle object
  392. */
  393. Phaser.Circle = function (x, y, diameter) {
  394. x = x || 0;
  395. y = y || 0;
  396. diameter = diameter || 0;
  397. /**
  398. * @property {number} x - The x coordinate of the center of the circle.
  399. */
  400. this.x = x;
  401. /**
  402. * @property {number} y - The y coordinate of the center of the circle.
  403. */
  404. this.y = y;
  405. /**
  406. * @property {number} _diameter - The diameter of the circle.
  407. * @private
  408. */
  409. this._diameter = diameter;
  410. if (diameter > 0)
  411. {
  412. /**
  413. * @property {number} _radius - The radius of the circle.
  414. * @private
  415. */
  416. this._radius = diameter * 0.5;
  417. }
  418. else
  419. {
  420. this._radius = 0;
  421. }
  422. };
  423. Phaser.Circle.prototype = {
  424. /**
  425. * The circumference of the circle.
  426. * @method Phaser.Circle#circumference
  427. * @return {number}
  428. */
  429. circumference: function () {
  430. return 2 * (Math.PI * this._radius);
  431. },
  432. /**
  433. * Sets the members of Circle to the specified values.
  434. * @method Phaser.Circle#setTo
  435. * @param {number} x - The x coordinate of the center of the circle.
  436. * @param {number} y - The y coordinate of the center of the circle.
  437. * @param {number} diameter - The diameter of the circle in pixels.
  438. * @return {Circle} This circle object.
  439. */
  440. setTo: function (x, y, diameter) {
  441. this.x = x;
  442. this.y = y;
  443. this._diameter = diameter;
  444. this._radius = diameter * 0.5;
  445. return this;
  446. },
  447. /**
  448. * Copies the x, y and diameter properties from any given object to this Circle.
  449. * @method Phaser.Circle#copyFrom
  450. * @param {any} source - The object to copy from.
  451. * @return {Circle} This Circle object.
  452. */
  453. copyFrom: function (source) {
  454. return this.setTo(source.x, source.y, source.diameter);
  455. },
  456. /**
  457. * Copies the x, y and diameter properties from this Circle to any given object.
  458. * @method Phaser.Circle#copyTo
  459. * @param {any} dest - The object to copy to.
  460. * @return {Object} This dest object.
  461. */
  462. copyTo: function (dest) {
  463. dest.x = this.x;
  464. dest.y = this.y;
  465. dest.diameter = this._diameter;
  466. return dest;
  467. },
  468. /**
  469. * Returns the distance from the center of the Circle object to the given object
  470. * (can be Circle, Point or anything with x/y properties)
  471. * @method Phaser.Circle#distance
  472. * @param {object} dest - The target object. Must have visible x and y properties that represent the center of the object.
  473. * @param {boolean} [round] - Round the distance to the nearest integer (default false).
  474. * @return {number} The distance between this Point object and the destination Point object.
  475. */
  476. distance: function (dest, round) {
  477. if (typeof round === "undefined") { round = false; }
  478. if (round)
  479. {
  480. return Phaser.Math.distanceRound(this.x, this.y, dest.x, dest.y);
  481. }
  482. else
  483. {
  484. return Phaser.Math.distance(this.x, this.y, dest.x, dest.y);
  485. }
  486. },
  487. /**
  488. * Returns a new Circle object with the same values for the x, y, width, and height properties as this Circle object.
  489. * @method Phaser.Circle#clone
  490. * @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.
  491. * @return {Phaser.Circle} The cloned Circle object.
  492. */
  493. clone: function (out) {
  494. if (typeof out === "undefined")
  495. {
  496. out = new Phaser.Circle(this.x, this.y, this.diameter);
  497. }
  498. else
  499. {
  500. out.setTo(this.x, this.y, this.diameter);
  501. }
  502. return out;
  503. },
  504. /**
  505. * Return true if the given x/y coordinates are within this Circle object.
  506. * @method Phaser.Circle#contains
  507. * @param {number} x - The X value of the coordinate to test.
  508. * @param {number} y - The Y value of the coordinate to test.
  509. * @return {boolean} True if the coordinates are within this circle, otherwise false.
  510. */
  511. contains: function (x, y) {
  512. return Phaser.Circle.contains(this, x, y);
  513. },
  514. /**
  515. * Returns a Point object containing the coordinates of a point on the circumference of the Circle based on the given angle.
  516. * @method Phaser.Circle#circumferencePoint
  517. * @param {number} angle - The angle in radians (unless asDegrees is true) to return the point from.
  518. * @param {boolean} asDegrees - Is the given angle in radians (false) or degrees (true)?
  519. * @param {Phaser.Point} [out] - An optional Point object to put the result in to. If none specified a new Point object will be created.
  520. * @return {Phaser.Point} The Point object holding the result.
  521. */
  522. circumferencePoint: function (angle, asDegrees, out) {
  523. return Phaser.Circle.circumferencePoint(this, angle, asDegrees, out);
  524. },
  525. /**
  526. * Adjusts the location of the Circle object, as determined by its center coordinate, by the specified amounts.
  527. * @method Phaser.Circle#offset
  528. * @param {number} dx - Moves the x value of the Circle object by this amount.
  529. * @param {number} dy - Moves the y value of the Circle object by this amount.
  530. * @return {Circle} This Circle object.
  531. */
  532. offset: function (dx, dy) {
  533. this.x += dx;
  534. this.y += dy;
  535. return this;
  536. },
  537. /**
  538. * 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.
  539. * @method Phaser.Circle#offsetPoint
  540. * @param {Point} point A Point object to use to offset this Circle object (or any valid object with exposed x and y properties).
  541. * @return {Circle} This Circle object.
  542. */
  543. offsetPoint: function (point) {
  544. return this.offset(point.x, point.y);
  545. },
  546. /**
  547. * Returns a string representation of this object.
  548. * @method Phaser.Circle#toString
  549. * @return {string} a string representation of the instance.
  550. */
  551. toString: function () {
  552. return "[{Phaser.Circle (x=" + this.x + " y=" + this.y + " diameter=" + this.diameter + " radius=" + this.radius + ")}]";
  553. }
  554. };
  555. Phaser.Circle.prototype.constructor = Phaser.Circle;
  556. /**
  557. * The largest distance between any two points on the circle. The same as the radius * 2.
  558. * @name Phaser.Circle#diameter
  559. * @property {number} diameter - Gets or sets the diameter of the circle.
  560. */
  561. Object.defineProperty(Phaser.Circle.prototype, "diameter", {
  562. get: function () {
  563. return this._diameter;
  564. },
  565. set: function (value) {
  566. if (value > 0)
  567. {
  568. this._diameter = value;
  569. this._radius = value * 0.5;
  570. }
  571. }
  572. });
  573. /**
  574. * 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.
  575. * @name Phaser.Circle#radius
  576. * @property {number} radius - Gets or sets the radius of the circle.
  577. */
  578. Object.defineProperty(Phaser.Circle.prototype, "radius", {
  579. get: function () {
  580. return this._radius;
  581. },
  582. set: function (value) {
  583. if (value > 0)
  584. {
  585. this._radius = value;
  586. this._diameter = value * 2;
  587. }
  588. }
  589. });
  590. /**
  591. * 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.
  592. * @name Phaser.Circle#left
  593. * @propety {number} left - Gets or sets the value of the leftmost point of the circle.
  594. */
  595. Object.defineProperty(Phaser.Circle.prototype, "left", {
  596. get: function () {
  597. return this.x - this._radius;
  598. },
  599. set: function (value) {
  600. if (value > this.x)
  601. {
  602. this._radius = 0;
  603. this._diameter = 0;
  604. }
  605. else
  606. {
  607. this.radius = this.x - value;
  608. }
  609. }
  610. });
  611. /**
  612. * 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.
  613. * @name Phaser.Circle#right
  614. * @property {number} right - Gets or sets the value of the rightmost point of the circle.
  615. */
  616. Object.defineProperty(Phaser.Circle.prototype, "right", {
  617. get: function () {
  618. return this.x + this._radius;
  619. },
  620. set: function (value) {
  621. if (value < this.x)
  622. {
  623. this._radius = 0;
  624. this._diameter = 0;
  625. }
  626. else
  627. {
  628. this.radius = value - this.x;
  629. }
  630. }
  631. });
  632. /**
  633. * 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.
  634. * @name Phaser.Circle#top
  635. * @property {number} top - Gets or sets the top of the circle.
  636. */
  637. Object.defineProperty(Phaser.Circle.prototype, "top", {
  638. get: function () {
  639. return this.y - this._radius;
  640. },
  641. set: function (value) {
  642. if (value > this.y)
  643. {
  644. this._radius = 0;
  645. this._diameter = 0;
  646. }
  647. else
  648. {
  649. this.radius = this.y - value;
  650. }
  651. }
  652. });
  653. /**
  654. * 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.
  655. * @name Phaser.Circle#bottom
  656. * @property {number} bottom - Gets or sets the bottom of the circle.
  657. */
  658. Object.defineProperty(Phaser.Circle.prototype, "bottom", {
  659. get: function () {
  660. return this.y + this._radius;
  661. },
  662. set: function (value) {
  663. if (value < this.y)
  664. {
  665. this._radius = 0;
  666. this._diameter = 0;
  667. }
  668. else
  669. {
  670. this.radius = value - this.y;
  671. }
  672. }
  673. });
  674. /**
  675. * The area of this Circle.
  676. * @name Phaser.Circle#area
  677. * @property {number} area - The area of this circle.
  678. * @readonly
  679. */
  680. Object.defineProperty(Phaser.Circle.prototype, "area", {
  681. get: function () {
  682. if (this._radius > 0)
  683. {
  684. return Math.PI * this._radius * this._radius;
  685. }
  686. else
  687. {
  688. return 0;
  689. }
  690. }
  691. });
  692. /**
  693. * 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.
  694. * 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.
  695. * @name Phaser.Circle#empty
  696. * @property {boolean} empty - Gets or sets the empty state of the circle.
  697. */
  698. Object.defineProperty(Phaser.Circle.prototype, "empty", {
  699. get: function () {
  700. return (this._diameter === 0);
  701. },
  702. set: function (value) {
  703. if (value === true)
  704. {
  705. this.setTo(0, 0, 0);
  706. }
  707. }
  708. });
  709. /**
  710. * Return true if the given x/y coordinates are within the Circle object.
  711. * @method Phaser.Circle.contains
  712. * @param {Phaser.Circle} a - The Circle to be checked.
  713. * @param {number} x - The X value of the coordinate to test.
  714. * @param {number} y - The Y value of the coordinate to test.
  715. * @return {boolean} True if the coordinates are within this circle, otherwise false.
  716. */
  717. Phaser.Circle.contains = function (a, x, y) {
  718. // Check if x/y are within the bounds first
  719. if (a.radius > 0 && x >= a.left && x <= a.right && y >= a.top && y <= a.bottom)
  720. {
  721. var dx = (a.x - x) * (a.x - x);
  722. var dy = (a.y - y) * (a.y - y);
  723. return (dx + dy) <= (a.radius * a.radius);
  724. }
  725. else
  726. {
  727. return false;
  728. }
  729. };
  730. /**
  731. * Determines whether the two Circle objects match. This method compares the x, y and diameter properties.
  732. * @method Phaser.Circle.equals
  733. * @param {Phaser.Circle} a - The first Circle object.
  734. * @param {Phaser.Circle} b - The second Circle object.
  735. * @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.
  736. */
  737. Phaser.Circle.equals = function (a, b) {
  738. return (a.x == b.x && a.y == b.y && a.diameter == b.diameter);
  739. };
  740. /**
  741. * Determines whether the two Circle objects intersect.
  742. * This method checks the radius distances between the two Circle objects to see if they intersect.
  743. * @method Phaser.Circle.intersects
  744. * @param {Phaser.Circle} a - The first Circle object.
  745. * @param {Phaser.Circle} b - The second Circle object.
  746. * @return {boolean} A value of true if the specified object intersects with this Circle object; otherwise false.
  747. */
  748. Phaser.Circle.intersects = function (a, b) {
  749. return (Phaser.Math.distance(a.x, a.y, b.x, b.y) <= (a.radius + b.radius));
  750. };
  751. /**
  752. * Returns a Point object containing the coordinates of a point on the circumference of the Circle based on the given angle.
  753. * @method Phaser.Circle.circumferencePoint
  754. * @param {Phaser.Circle} a - The first Circle object.
  755. * @param {number} angle - The angle in radians (unless asDegrees is true) to return the point from.
  756. * @param {boolean} asDegrees - Is the given angle in radians (false) or degrees (true)?
  757. * @param {Phaser.Point} [out] - An optional Point object to put the result in to. If none specified a new Point object will be created.
  758. * @return {Phaser.Point} The Point object holding the result.
  759. */
  760. Phaser.Circle.circumferencePoint = function (a, angle, asDegrees, out) {
  761. if (typeof asDegrees === "undefined") { asDegrees = false; }
  762. if (typeof out === "undefined") { out = new Phaser.Point(); }
  763. if (asDegrees === true)
  764. {
  765. angle = Phaser.Math.degToRad(angle);
  766. }
  767. out.x = a.x + a.radius * Math.cos(angle);
  768. out.y = a.y + a.radius * Math.sin(angle);
  769. return out;
  770. };
  771. /**
  772. * Checks if the given Circle and Rectangle objects intersect.
  773. * @method Phaser.Circle.intersectsRectangle
  774. * @param {Phaser.Circle} c - The Circle object to test.
  775. * @param {Phaser.Rectangle} r - The Rectangle object to test.
  776. * @return {boolean} True if the two objects intersect, otherwise false.
  777. */
  778. Phaser.Circle.intersectsRectangle = function (c, r) {
  779. var cx = Math.abs(c.x - r.x - r.halfWidth);
  780. var xDist = r.halfWidth + c.radius;
  781. if (cx > xDist)
  782. {
  783. return false;
  784. }
  785. var cy = Math.abs(c.y - r.y - r.halfHeight);
  786. var yDist = r.halfHeight + c.radius;
  787. if (cy > yDist)
  788. {
  789. return false;
  790. }
  791. if (cx <= r.halfWidth || cy <= r.halfHeight)
  792. {
  793. return true;
  794. }
  795. var xCornerDist = cx - r.halfWidth;
  796. var yCornerDist = cy - r.halfHeight;
  797. var xCornerDistSq = xCornerDist * xCornerDist;
  798. var yCornerDistSq = yCornerDist * yCornerDist;
  799. var maxCornerDistSq = c.radius * c.radius;
  800. return xCornerDistSq + yCornerDistSq <= maxCornerDistSq;
  801. };
  802. // Because PIXI uses its own Circle, we'll replace it with ours to avoid duplicating code or confusion.
  803. PIXI.Circle = Phaser.Circle;
  804. /**
  805. * @author Richard Davey <rich@photonstorm.com>
  806. * @copyright 2014 Photon Storm Ltd.
  807. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  808. */
  809. /**
  810. * Creates a new Point. If you pass no parameters a Point is created set to (0,0).
  811. * @class Phaser.Point
  812. * @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.
  813. * @constructor
  814. * @param {number} x The horizontal position of this Point (default 0)
  815. * @param {number} y The vertical position of this Point (default 0)
  816. */
  817. Phaser.Point = function (x, y) {
  818. x = x || 0;
  819. y = y || 0;
  820. /**
  821. * @property {number} x - The x coordinate of the point.
  822. */
  823. this.x = x;
  824. /**
  825. * @property {number} y - The y coordinate of the point.
  826. */
  827. this.y = y;
  828. };
  829. Phaser.Point.prototype = {
  830. /**
  831. * Copies the x and y properties from any given object to this Point.
  832. * @method Phaser.Point#copyFrom
  833. * @param {any} source - The object to copy from.
  834. * @return {Point} This Point object.
  835. */
  836. copyFrom: function (source) {
  837. return this.setTo(source.x, source.y);
  838. },
  839. /**
  840. * Inverts the x and y values of this Point
  841. * @method Phaser.Point#invert
  842. * @return {Point} This Point object.
  843. */
  844. invert: function () {
  845. return this.setTo(this.y, this.x);
  846. },
  847. /**
  848. * Sets the x and y values of this Point object to the given coordinates.
  849. * @method Phaser.Point#setTo
  850. * @param {number} x - The horizontal position of this point.
  851. * @param {number} y - The vertical position of this point.
  852. * @return {Point} This Point object. Useful for chaining method calls.
  853. */
  854. setTo: function (x, y) {
  855. this.x = x || 0;
  856. this.y = y || ( (y !== 0) ? this.x : 0 );
  857. return this;
  858. },
  859. /**
  860. * Sets the x and y values of this Point object to the given coordinates.
  861. * @method Phaser.Point#set
  862. * @param {number} x - The horizontal position of this point.
  863. * @param {number} y - The vertical position of this point.
  864. * @return {Point} This Point object. Useful for chaining method calls.
  865. */
  866. set: function (x, y) {
  867. this.x = x || 0;
  868. this.y = y || ( (y !== 0) ? this.x : 0 );
  869. return this;
  870. },
  871. /**
  872. * Adds the given x and y values to this Point.
  873. * @method Phaser.Point#add
  874. * @param {number} x - The value to add to Point.x.
  875. * @param {number} y - The value to add to Point.y.
  876. * @return {Phaser.Point} This Point object. Useful for chaining method calls.
  877. */
  878. add: function (x, y) {
  879. this.x += x;
  880. this.y += y;
  881. return this;
  882. },
  883. /**
  884. * Subtracts the given x and y values from this Point.
  885. * @method Phaser.Point#subtract
  886. * @param {number} x - The value to subtract from Point.x.
  887. * @param {number} y - The value to subtract from Point.y.
  888. * @return {Phaser.Point} This Point object. Useful for chaining method calls.
  889. */
  890. subtract: function (x, y) {
  891. this.x -= x;
  892. this.y -= y;
  893. return this;
  894. },
  895. /**
  896. * Multiplies Point.x and Point.y by the given x and y values.
  897. * @method Phaser.Point#multiply
  898. * @param {number} x - The value to multiply Point.x by.
  899. * @param {number} y - The value to multiply Point.x by.
  900. * @return {Phaser.Point} This Point object. Useful for chaining method calls.
  901. */
  902. multiply: function (x, y) {
  903. this.x *= x;
  904. this.y *= y;
  905. return this;
  906. },
  907. /**
  908. * Divides Point.x and Point.y by the given x and y values.
  909. * @method Phaser.Point#divide
  910. * @param {number} x - The value to divide Point.x by.
  911. * @param {number} y - The value to divide Point.x by.
  912. * @return {Phaser.Point} This Point object. Useful for chaining method calls.
  913. */
  914. divide: function (x, y) {
  915. this.x /= x;
  916. this.y /= y;
  917. return this;
  918. },
  919. /**
  920. * Clamps the x value of this Point to be between the given min and max.
  921. * @method Phaser.Point#clampX
  922. * @param {number} min - The minimum value to clamp this Point to.
  923. * @param {number} max - The maximum value to clamp this Point to.
  924. * @return {Phaser.Point} This Point object.
  925. */
  926. clampX: function (min, max) {
  927. this.x = Phaser.Math.clamp(this.x, min, max);
  928. return this;
  929. },
  930. /**
  931. * Clamps the y value of this Point to be between the given min and max
  932. * @method Phaser.Point#clampY
  933. * @param {number} min - The minimum value to clamp this Point to.
  934. * @param {number} max - The maximum value to clamp this Point to.
  935. * @return {Phaser.Point} This Point object.
  936. */
  937. clampY: function (min, max) {
  938. this.y = Phaser.Math.clamp(this.y, min, max);
  939. return this;
  940. },
  941. /**
  942. * Clamps this Point object values to be between the given min and max.
  943. * @method Phaser.Point#clamp
  944. * @param {number} min - The minimum value to clamp this Point to.
  945. * @param {number} max - The maximum value to clamp this Point to.
  946. * @return {Phaser.Point} This Point object.
  947. */
  948. clamp: function (min, max) {
  949. this.x = Phaser.Math.clamp(this.x, min, max);
  950. this.y = Phaser.Math.clamp(this.y, min, max);
  951. return this;
  952. },
  953. /**
  954. * Creates a copy of the given Point.
  955. * @method Phaser.Point#clone
  956. * @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.
  957. * @return {Phaser.Point} The new Point object.
  958. */
  959. clone: function (output) {
  960. if (typeof output === "undefined")
  961. {
  962. output = new Phaser.Point(this.x, this.y);
  963. }
  964. else
  965. {
  966. output.setTo(this.x, this.y);
  967. }
  968. return output;
  969. },
  970. /**
  971. * Copies the x and y properties from this Point to any given object.
  972. * @method Phaser.Point#copyTo
  973. * @param {any} dest - The object to copy to.
  974. * @return {Object} The dest object.
  975. */
  976. copyTo: function(dest) {
  977. dest.x = this.x;
  978. dest.y = this.y;
  979. return dest;
  980. },
  981. /**
  982. * Returns the distance of this Point object to the given object (can be a Circle, Point or anything with x/y properties)
  983. * @method Phaser.Point#distance
  984. * @param {object} dest - The target object. Must have visible x and y properties that represent the center of the object.
  985. * @param {boolean} [round] - Round the distance to the nearest integer (default false).
  986. * @return {number} The distance between this Point object and the destination Point object.
  987. */
  988. distance: function (dest, round) {
  989. return Phaser.Point.distance(this, dest, round);
  990. },
  991. /**
  992. * Determines whether the given objects x/y values are equal to this Point object.
  993. * @method Phaser.Point#equals
  994. * @param {Phaser.Point} a - The first object to compare.
  995. * @return {boolean} A value of true if the Points are equal, otherwise false.
  996. */
  997. equals: function (a) {
  998. return (a.x == this.x && a.y == this.y);
  999. },
  1000. /**
  1001. * Rotates this Point around the x/y coordinates given to the desired angle.
  1002. * @method Phaser.Point#rotate
  1003. * @param {number} x - The x coordinate of the anchor point
  1004. * @param {number} y - The y coordinate of the anchor point
  1005. * @param {number} angle - The angle in radians (unless asDegrees is true) to rotate the Point to.
  1006. * @param {boolean} asDegrees - Is the given rotation in radians (false) or degrees (true)?
  1007. * @param {number} [distance] - An optional distance constraint between the Point and the anchor.
  1008. * @return {Phaser.Point} The modified point object.
  1009. */
  1010. rotate: function (x, y, angle, asDegrees, distance) {
  1011. return Phaser.Point.rotate(this, x, y, angle, asDegrees, distance);
  1012. },
  1013. /**
  1014. * Calculates the length of the vector
  1015. * @method Phaser.Point#getMagnitude
  1016. * @return {number} the length of the vector
  1017. */
  1018. getMagnitude: function() {
  1019. return Math.sqrt((this.x * this.x) + (this.y * this.y));
  1020. },
  1021. /**
  1022. * Alters the length of the vector without changing the direction
  1023. * @method Phaser.Point#setMagnitude
  1024. * @param {number} magnitude the desired magnitude of the resulting vector
  1025. * @return {Phaser.Point} the modified original vector
  1026. */
  1027. setMagnitude: function(magnitude) {
  1028. return this.normalize().multiply(magnitude, magnitude);
  1029. },
  1030. /**
  1031. * Alters the vector so that its length is 1, but it retains the same direction
  1032. * @method Phaser.Point#normalize
  1033. * @return {Phaser.Point} the modified original vector
  1034. */
  1035. normalize: function() {
  1036. if(!this.isZero()) {
  1037. var m = this.getMagnitude();
  1038. this.x /= m;
  1039. this.y /= m;
  1040. }
  1041. return this;
  1042. },
  1043. /**
  1044. * Determine if this point is at 0,0
  1045. * @method Phaser.Point#isZero
  1046. * @return {boolean} True if this Point is 0,0, otherwise false
  1047. */
  1048. isZero: function() {
  1049. return (this.x === 0 && this.y === 0);
  1050. },
  1051. /**
  1052. * Returns a string representation of this object.
  1053. * @method Phaser.Point#toString
  1054. * @return {string} A string representation of the instance.
  1055. */
  1056. toString: function () {
  1057. return '[{Point (x=' + this.x + ' y=' + this.y + ')}]';
  1058. }
  1059. };
  1060. Phaser.Point.prototype.constructor = Phaser.Point;
  1061. /**
  1062. * Adds the coordinates of two points together to create a new point.
  1063. * @method Phaser.Point.add
  1064. * @param {Phaser.Point} a - The first Point object.
  1065. * @param {Phaser.Point} b - The second Point object.
  1066. * @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created.
  1067. * @return {Phaser.Point} The new Point object.
  1068. */
  1069. Phaser.Point.add = function (a, b, out) {
  1070. if (typeof out === "undefined") { out = new Phaser.Point(); }
  1071. out.x = a.x + b.x;
  1072. out.y = a.y + b.y;
  1073. return out;
  1074. };
  1075. /**
  1076. * Subtracts the coordinates of two points to create a new point.
  1077. * @method Phaser.Point.subtract
  1078. * @param {Phaser.Point} a - The first Point object.
  1079. * @param {Phaser.Point} b - The second Point object.
  1080. * @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created.
  1081. * @return {Phaser.Point} The new Point object.
  1082. */
  1083. Phaser.Point.subtract = function (a, b, out) {
  1084. if (typeof out === "undefined") { out = new Phaser.Point(); }
  1085. out.x = a.x - b.x;
  1086. out.y = a.y - b.y;
  1087. return out;
  1088. };
  1089. /**
  1090. * Multiplies the coordinates of two points to create a new point.
  1091. * @method Phaser.Point.multiply
  1092. * @param {Phaser.Point} a - The first Point object.
  1093. * @param {Phaser.Point} b - The second Point object.
  1094. * @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created.
  1095. * @return {Phaser.Point} The new Point object.
  1096. */
  1097. Phaser.Point.multiply = function (a, b, out) {
  1098. if (typeof out === "undefined") { out = new Phaser.Point(); }
  1099. out.x = a.x * b.x;
  1100. out.y = a.y * b.y;
  1101. return out;
  1102. };
  1103. /**
  1104. * Divides the coordinates of two points to create a new point.
  1105. * @method Phaser.Point.divide
  1106. * @param {Phaser.Point} a - The first Point object.
  1107. * @param {Phaser.Point} b - The second Point object.
  1108. * @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created.
  1109. * @return {Phaser.Point} The new Point object.
  1110. */
  1111. Phaser.Point.divide = function (a, b, out) {
  1112. if (typeof out === "undefined") { out = new Phaser.Point(); }
  1113. out.x = a.x / b.x;
  1114. out.y = a.y / b.y;
  1115. return out;
  1116. };
  1117. /**
  1118. * Determines whether the two given Point objects are equal. They are considered equal if they have the same x and y values.
  1119. * @method Phaser.Point.equals
  1120. * @param {Phaser.Point} a - The first Point object.
  1121. * @param {Phaser.Point} b - The second Point object.
  1122. * @return {boolean} A value of true if the Points are equal, otherwise false.
  1123. */
  1124. Phaser.Point.equals = function (a, b) {
  1125. return (a.x == b.x && a.y == b.y);
  1126. };
  1127. /**
  1128. * Returns the distance of this Point object to the given object (can be a Circle, Point or anything with x/y properties).
  1129. * @method Phaser.Point.distance
  1130. * @param {object} a - The target object. Must have visible x and y properties that represent the center of the object.
  1131. * @param {object} b - The target object. Must have visible x and y properties that represent the center of the object.
  1132. * @param {boolean} [round] - Round the distance to the nearest integer (default false).
  1133. * @return {number} The distance between this Point object and the destination Point object.
  1134. */
  1135. Phaser.Point.distance = function (a, b, round) {
  1136. if (typeof round === "undefined") { round = false; }
  1137. if (round)
  1138. {
  1139. return Phaser.Math.distanceRound(a.x, a.y, b.x, b.y);
  1140. }
  1141. else
  1142. {
  1143. return Phaser.Math.distance(a.x, a.y, b.x, b.y);
  1144. }
  1145. };
  1146. /**
  1147. * Rotates a Point around the x/y coordinates given to the desired angle.
  1148. * @method Phaser.Point.rotate
  1149. * @param {Phaser.Point} a - The Point object to rotate.
  1150. * @param {number} x - The x coordinate of the anchor point
  1151. * @param {number} y - The y coordinate of the anchor point
  1152. * @param {number} angle - The angle in radians (unless asDegrees is true) to rotate the Point to.
  1153. * @param {boolean} asDegrees - Is the given rotation in radians (false) or degrees (true)?
  1154. * @param {number} distance - An optional distance constraint between the Point and the anchor.
  1155. * @return {Phaser.Point} The modified point object.
  1156. */
  1157. Phaser.Point.rotate = function (a, x, y, angle, asDegrees, distance) {
  1158. asDegrees = asDegrees || false;
  1159. distance = distance || null;
  1160. if (asDegrees)
  1161. {
  1162. angle = Phaser.Math.degToRad(angle);
  1163. }
  1164. // Get distance from origin (cx/cy) to this point
  1165. if (distance === null)
  1166. {
  1167. distance = Math.sqrt(((x - a.x) * (x - a.x)) + ((y - a.y) * (y - a.y)));
  1168. }
  1169. return a.setTo(x + distance * Math.cos(angle), y + distance * Math.sin(angle));
  1170. };
  1171. /**
  1172. * Calculates centroid (or midpoint) from an array of points. If only one point is provided, that point is returned.
  1173. * @method Phaser.Point.centroid
  1174. * @param {Phaser.Point[]} points - The array of one or more points.
  1175. * @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created.
  1176. * @return {Phaser.Point} The new Point object.
  1177. */
  1178. Phaser.Point.centroid = function (points, out) {
  1179. if (typeof out === "undefined") { out = new Phaser.Point(); }
  1180. if (Object.prototype.toString.call(points) !== '[object Array]')
  1181. {
  1182. throw new Error("Phaser.Point. Parameter 'points' must be an array");
  1183. }
  1184. var pointslength = points.length;
  1185. if (pointslength < 1)
  1186. {
  1187. throw new Error("Phaser.Point. Parameter 'points' array must not be empty");
  1188. }
  1189. if (pointslength === 1)
  1190. {
  1191. out.copyFrom(points[0]);
  1192. return out;
  1193. }
  1194. for (var i = 0; i < pointslength; i++)
  1195. {
  1196. Phaser.Point.add(out, points[i], out);
  1197. }
  1198. out.divide(pointslength, pointslength);
  1199. return out;
  1200. };
  1201. // Because PIXI uses its own Point, we'll replace it with ours to avoid duplicating code or confusion.
  1202. PIXI.Point = Phaser.Point;
  1203. /**
  1204. * @author Richard Davey <rich@photonstorm.com>
  1205. * @copyright 2014 Photon Storm Ltd.
  1206. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  1207. */
  1208. /**
  1209. * 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.
  1210. *
  1211. * @class Phaser.Rectangle
  1212. * @constructor
  1213. * @param {number} x - The x coordinate of the top-left corner of the Rectangle.
  1214. * @param {number} y - The y coordinate of the top-left corner of the Rectangle.
  1215. * @param {number} width - The width of the Rectangle.
  1216. * @param {number} height - The height of the Rectangle.
  1217. * @return {Phaser.Rectangle} This Rectangle object.
  1218. */
  1219. Phaser.Rectangle = function (x, y, width, height) {
  1220. x = x || 0;
  1221. y = y || 0;
  1222. width = width || 0;
  1223. height = height || 0;
  1224. /**
  1225. * @property {number} x - The x coordinate of the top-left corner of the Rectangle.
  1226. */
  1227. this.x = x;
  1228. /**
  1229. * @property {number} y - The y coordinate of the top-left corner of the Rectangle.
  1230. */
  1231. this.y = y;
  1232. /**
  1233. * @property {number} width - The width of the Rectangle.
  1234. */
  1235. this.width = width;
  1236. /**
  1237. * @property {number} height - The height of the Rectangle.
  1238. */
  1239. this.height = height;
  1240. };
  1241. Phaser.Rectangle.prototype = {
  1242. /**
  1243. * Adjusts the location of the Rectangle object, as determined by its top-left corner, by the specified amounts.
  1244. * @method Phaser.Rectangle#offset
  1245. * @param {number} dx - Moves the x value of the Rectangle object by this amount.
  1246. * @param {number} dy - Moves the y value of the Rectangle object by this amount.
  1247. * @return {Phaser.Rectangle} This Rectangle object.
  1248. */
  1249. offset: function (dx, dy) {
  1250. this.x += dx;
  1251. this.y += dy;
  1252. return this;
  1253. },
  1254. /**
  1255. * 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.
  1256. * @method Phaser.Rectangle#offsetPoint
  1257. * @param {Phaser.Point} point - A Point object to use to offset this Rectangle object.
  1258. * @return {Phaser.Rectangle} This Rectangle object.
  1259. */
  1260. offsetPoint: function (point) {
  1261. return this.offset(point.x, point.y);
  1262. },
  1263. /**
  1264. * Sets the members of Rectangle to the specified values.
  1265. * @method Phaser.Rectangle#setTo
  1266. * @param {number} x - The x coordinate of the top-left corner of the Rectangle.
  1267. * @param {number} y - The y coordinate of the top-left corner of the Rectangle.
  1268. * @param {number} width - The width of the Rectangle in pixels.
  1269. * @param {number} height - The height of the Rectangle in pixels.
  1270. * @return {Phaser.Rectangle} This Rectangle object
  1271. */
  1272. setTo: function (x, y, width, height) {
  1273. this.x = x;
  1274. this.y = y;
  1275. this.width = width;
  1276. this.height = height;
  1277. return this;
  1278. },
  1279. /**
  1280. * Runs Math.floor() on both the x and y values of this Rectangle.
  1281. * @method Phaser.Rectangle#floor
  1282. */
  1283. floor: function () {
  1284. this.x = Math.floor(this.x);
  1285. this.y = Math.floor(this.y);
  1286. },
  1287. /**
  1288. * Runs Math.floor() on the x, y, width and height values of this Rectangle.
  1289. * @method Phaser.Rectangle#floorAll
  1290. */
  1291. floorAll: function () {
  1292. this.x = Math.floor(this.x);
  1293. this.y = Math.floor(this.y);
  1294. this.width = Math.floor(this.width);
  1295. this.height = Math.floor(this.height);
  1296. },
  1297. /**
  1298. * Copies the x, y, width and height properties from any given object to this Rectangle.
  1299. * @method Phaser.Rectangle#copyFrom
  1300. * @param {any} source - The object to copy from.
  1301. * @return {Phaser.Rectangle} This Rectangle object.
  1302. */
  1303. copyFrom: function (source) {
  1304. return this.setTo(source.x, source.y, source.width, source.height);
  1305. },
  1306. /**
  1307. * Copies the x, y, width and height properties from this Rectangle to any given object.
  1308. * @method Phaser.Rectangle#copyTo
  1309. * @param {any} source - The object to copy to.
  1310. * @return {object} This object.
  1311. */
  1312. copyTo: function (dest) {
  1313. dest.x = this.x;
  1314. dest.y = this.y;
  1315. dest.width = this.width;
  1316. dest.height = this.height;
  1317. return dest;
  1318. },
  1319. /**
  1320. * 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.
  1321. * @method Phaser.Rectangle#inflate
  1322. * @param {number} dx - The amount to be added to the left side of the Rectangle.
  1323. * @param {number} dy - The amount to be added to the bottom side of the Rectangle.
  1324. * @return {Phaser.Rectangle} This Rectangle object.
  1325. */
  1326. inflate: function (dx, dy) {
  1327. return Phaser.Rectangle.inflate(this, dx, dy);
  1328. },
  1329. /**
  1330. * The size of the Rectangle object, expressed as a Point object with the values of the width and height properties.
  1331. * @method Phaser.Rectangle#size
  1332. * @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.
  1333. * @return {Phaser.Point} The size of the Rectangle object.
  1334. */
  1335. size: function (output) {
  1336. return Phaser.Rectangle.size(this, output);
  1337. },
  1338. /**
  1339. * Returns a new Rectangle object with the same values for the x, y, width, and height properties as the original Rectangle object.
  1340. * @method Phaser.Rectangle#clone
  1341. * @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.
  1342. * @return {Phaser.Rectangle}
  1343. */
  1344. clone: function (output) {
  1345. return Phaser.Rectangle.clone(this, output);
  1346. },
  1347. /**
  1348. * Determines whether the specified coordinates are contained within the region defined by this Rectangle object.
  1349. * @method Phaser.Rectangle#contains
  1350. * @param {number} x - The x coordinate of the point to test.
  1351. * @param {number} y - The y coordinate of the point to test.
  1352. * @return {boolean} A value of true if the Rectangle object contains the specified point; otherwise false.
  1353. */
  1354. contains: function (x, y) {
  1355. return Phaser.Rectangle.contains(this, x, y);
  1356. },
  1357. /**
  1358. * Determines whether the first Rectangle object is fully contained within the second Rectangle object.
  1359. * A Rectangle object is said to contain another if the second Rectangle object falls entirely within the boundaries of the first.
  1360. * @method Phaser.Rectangle#containsRect
  1361. * @param {Phaser.Rectangle} b - The second Rectangle object.
  1362. * @return {boolean} A value of true if the Rectangle object contains the specified point; otherwise false.
  1363. */
  1364. containsRect: function (b) {
  1365. return Phaser.Rectangle.containsRect(this, b);
  1366. },
  1367. /**
  1368. * Determines whether the two Rectangles are equal.
  1369. * This method compares the x, y, width and height properties of each Rectangle.
  1370. * @method Phaser.Rectangle#equals
  1371. * @param {Phaser.Rectangle} b - The second Rectangle object.
  1372. * @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.
  1373. */
  1374. equals: function (b) {
  1375. return Phaser.Rectangle.equals(this, b);
  1376. },
  1377. /**
  1378. * 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.
  1379. * @method Phaser.Rectangle#intersection
  1380. * @param {Phaser.Rectangle} b - The second Rectangle object.
  1381. * @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.
  1382. * @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.
  1383. */
  1384. intersection: function (b, out) {
  1385. return Phaser.Rectangle.intersection(this, b, out);
  1386. },
  1387. /**
  1388. * Determines whether the two Rectangles intersect with each other.
  1389. * This method checks the x, y, width, and height properties of the Rectangles.
  1390. * @method Phaser.Rectangle#intersects
  1391. * @param {Phaser.Rectangle} b - The second Rectangle object.
  1392. * @param {number} tolerance - A tolerance value to allow for an intersection test with padding, default to 0.
  1393. * @return {boolean} A value of true if the specified object intersects with this Rectangle object; otherwise false.
  1394. */
  1395. intersects: function (b, tolerance) {
  1396. return Phaser.Rectangle.intersects(this, b, tolerance);
  1397. },
  1398. /**
  1399. * Determines whether the object specified intersects (overlaps) with the given values.
  1400. * @method Phaser.Rectangle#intersectsRaw
  1401. * @param {number} left - Description.
  1402. * @param {number} right - Description.
  1403. * @param {number} top - Description.
  1404. * @param {number} bottomt - Description.
  1405. * @param {number} tolerance - A tolerance value to allow for an intersection test with padding, default to 0
  1406. * @return {boolean} A value of true if the specified object intersects with the Rectangle; otherwise false.
  1407. */
  1408. intersectsRaw: function (left, right, top, bottom, tolerance) {
  1409. return Phaser.Rectangle.intersectsRaw(this, left, right, top, bottom, tolerance);
  1410. },
  1411. /**
  1412. * Adds two Rectangles together to create a new Rectangle object, by filling in the horizontal and vertical space between the two Rectangles.
  1413. * @method Phaser.Rectangle#union
  1414. * @param {Phaser.Rectangle} b - The second Rectangle object.
  1415. * @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.
  1416. * @return {Phaser.Rectangle} A Rectangle object that is the union of the two Rectangles.
  1417. */
  1418. union: function (b, out) {
  1419. return Phaser.Rectangle.union(this, b, out);
  1420. },
  1421. /**
  1422. * Returns a string representation of this object.
  1423. * @method Phaser.Rectangle#toString
  1424. * @return {string} A string representation of the instance.
  1425. */
  1426. toString: function () {
  1427. return "[{Rectangle (x=" + this.x + " y=" + this.y + " width=" + this.width + " height=" + this.height + " empty=" + this.empty + ")}]";
  1428. }
  1429. };
  1430. /**
  1431. * @name Phaser.Rectangle#halfWidth
  1432. * @property {number} halfWidth - Half of the width of the Rectangle.
  1433. * @readonly
  1434. */
  1435. Object.defineProperty(Phaser.Rectangle.prototype, "halfWidth", {
  1436. get: function () {
  1437. return Math.round(this.width / 2);
  1438. }
  1439. });
  1440. /**
  1441. * @name Phaser.Rectangle#halfHeight
  1442. * @property {number} halfHeight - Half of the height of the Rectangle.
  1443. * @readonly
  1444. */
  1445. Object.defineProperty(Phaser.Rectangle.prototype, "halfHeight", {
  1446. get: function () {
  1447. return Math.round(this.height / 2);
  1448. }
  1449. });
  1450. /**
  1451. * 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.
  1452. * @name Phaser.Rectangle#bottom
  1453. * @property {number} bottom - The sum of the y and height properties.
  1454. */
  1455. Object.defineProperty(Phaser.Rectangle.prototype, "bottom", {
  1456. get: function () {
  1457. return this.y + this.height;
  1458. },
  1459. set: function (value) {
  1460. if (value <= this.y) {
  1461. this.height = 0;
  1462. } else {
  1463. this.height = (this.y - value);
  1464. }
  1465. }
  1466. });
  1467. /**
  1468. * The location of the Rectangles bottom right corner as a Point object.
  1469. * @name Phaser.Rectangle#bottom
  1470. * @property {Phaser.Point} bottomRight - Gets or sets the location of the Rectangles bottom right corner as a Point object.
  1471. */
  1472. Object.defineProperty(Phaser.Rectangle.prototype, "bottomRight", {
  1473. get: function () {
  1474. return new Phaser.Point(this.right, this.bottom);
  1475. },
  1476. set: function (value) {
  1477. this.right = value.x;
  1478. this.bottom = value.y;
  1479. }
  1480. });
  1481. /**
  1482. * 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.
  1483. * @name Phaser.Rectangle#left
  1484. * @property {number} left - The x coordinate of the left of the Rectangle.
  1485. */
  1486. Object.defineProperty(Phaser.Rectangle.prototype, "left", {
  1487. get: function () {
  1488. return this.x;
  1489. },
  1490. set: function (value) {
  1491. if (value >= this.right) {
  1492. this.width = 0;
  1493. } else {
  1494. this.width = this.right - value;
  1495. }
  1496. this.x = value;
  1497. }
  1498. });
  1499. /**
  1500. * 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.
  1501. * @name Phaser.Rectangle#right
  1502. * @property {number} right - The sum of the x and width properties.
  1503. */
  1504. Object.defineProperty(Phaser.Rectangle.prototype, "right", {
  1505. get: function () {
  1506. return this.x + this.width;
  1507. },
  1508. set: function (value) {
  1509. if (value <= this.x) {
  1510. this.width = 0;
  1511. } else {
  1512. this.width = this.x + value;
  1513. }
  1514. }
  1515. });
  1516. /**
  1517. * The volume of the Rectangle derived from width * height.
  1518. * @name Phaser.Rectangle#volume
  1519. * @property {number} volume - The volume of the Rectangle derived from width * height.
  1520. * @readonly
  1521. */
  1522. Object.defineProperty(Phaser.Rectangle.prototype, "volume", {
  1523. get: function () {
  1524. return this.width * this.height;
  1525. }
  1526. });
  1527. /**
  1528. * The perimeter size of the Rectangle. This is the sum of all 4 sides.
  1529. * @name Phaser.Rectangle#perimeter
  1530. * @property {number} perimeter - The perimeter size of the Rectangle. This is the sum of all 4 sides.
  1531. * @readonly
  1532. */
  1533. Object.defineProperty(Phaser.Rectangle.prototype, "perimeter", {
  1534. get: function () {
  1535. return (this.width * 2) + (this.height * 2);
  1536. }
  1537. });
  1538. /**
  1539. * The x coordinate of the center of the Rectangle.
  1540. * @name Phaser.Rectangle#centerX
  1541. * @property {number} centerX - The x coordinate of the center of the Rectangle.
  1542. */
  1543. Object.defineProperty(Phaser.Rectangle.prototype, "centerX", {
  1544. get: function () {
  1545. return this.x + this.halfWidth;
  1546. },
  1547. set: function (value) {
  1548. this.x = value - this.halfWidth;
  1549. }
  1550. });
  1551. /**
  1552. * The y coordinate of the center of the Rectangle.
  1553. * @name Phaser.Rectangle#centerY
  1554. * @property {number} centerY - The y coordinate of the center of the Rectangle.
  1555. */
  1556. Object.defineProperty(Phaser.Rectangle.prototype, "centerY", {
  1557. get: function () {
  1558. return this.y + this.halfHeight;
  1559. },
  1560. set: function (value) {
  1561. this.y = value - this.halfHeight;
  1562. }
  1563. });
  1564. /**
  1565. * 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.
  1566. * However it does affect the height property, whereas changing the y value does not affect the height property.
  1567. * @name Phaser.Rectangle#top
  1568. * @property {number} top - The y coordinate of the top of the Rectangle.
  1569. */
  1570. Object.defineProperty(Phaser.Rectangle.prototype, "top", {
  1571. get: function () {
  1572. return this.y;
  1573. },
  1574. set: function (value) {
  1575. if (value >= this.bottom) {
  1576. this.height = 0;
  1577. this.y = value;
  1578. } else {
  1579. this.height = (this.bottom - value);
  1580. }
  1581. }
  1582. });
  1583. /**
  1584. * The location of the Rectangles top left corner as a Point object.
  1585. * @name Phaser.Rectangle#topLeft
  1586. * @property {Phaser.Point} topLeft - The location of the Rectangles top left corner as a Point object.
  1587. */
  1588. Object.defineProperty(Phaser.Rectangle.prototype, "topLeft", {
  1589. get: function () {
  1590. return new Phaser.Point(this.x, this.y);
  1591. },
  1592. set: function (value) {
  1593. this.x = value.x;
  1594. this.y = value.y;
  1595. }
  1596. });
  1597. /**
  1598. * 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.
  1599. * If set to true then all of the Rectangle properties are set to 0.
  1600. * @name Phaser.Rectangle#empty
  1601. * @property {boolean} empty - Gets or sets the Rectangles empty state.
  1602. */
  1603. Object.defineProperty(Phaser.Rectangle.prototype, "empty", {
  1604. get: function () {
  1605. return (!this.width || !this.height);
  1606. },
  1607. set: function (value) {
  1608. if (value === true)
  1609. {
  1610. this.setTo(0, 0, 0, 0);
  1611. }
  1612. }
  1613. });
  1614. Phaser.Rectangle.prototype.constructor = Phaser.Rectangle;
  1615. /**
  1616. * 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.
  1617. * @method Phaser.Rectangle.inflate
  1618. * @param {Phaser.Rectangle} a - The Rectangle object.
  1619. * @param {number} dx - The amount to be added to the left side of the Rectangle.
  1620. * @param {number} dy - The amount to be added to the bottom side of the Rectangle.
  1621. * @return {Phaser.Rectangle} This Rectangle object.
  1622. */
  1623. Phaser.Rectangle.inflate = function (a, dx, dy) {
  1624. a.x -= dx;
  1625. a.width += 2 * dx;
  1626. a.y -= dy;
  1627. a.height += 2 * dy;
  1628. return a;
  1629. };
  1630. /**
  1631. * 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.
  1632. * @method Phaser.Rectangle.inflatePoint
  1633. * @param {Phaser.Rectangle} a - The Rectangle object.
  1634. * @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.
  1635. * @return {Phaser.Rectangle} The Rectangle object.
  1636. */
  1637. Phaser.Rectangle.inflatePoint = function (a, point) {
  1638. return Phaser.Rectangle.inflate(a, point.x, point.y);
  1639. };
  1640. /**
  1641. * The size of the Rectangle object, expressed as a Point object with the values of the width and height properties.
  1642. * @method Phaser.Rectangle.size
  1643. * @param {Phaser.Rectangle} a - The Rectangle object.
  1644. * @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.
  1645. * @return {Phaser.Point} The size of the Rectangle object
  1646. */
  1647. Phaser.Rectangle.size = function (a, output) {
  1648. if (typeof output === "undefined")
  1649. {
  1650. output = new Phaser.Point(a.width, a.height);
  1651. }
  1652. else
  1653. {
  1654. output.setTo(a.width, a.height);
  1655. }
  1656. return output;
  1657. };
  1658. /**
  1659. * Returns a new Rectangle object with the same values for the x, y, width, and height properties as the original Rectangle object.
  1660. * @method Phaser.Rectangle.clone
  1661. * @param {Phaser.Rectangle} a - The Rectangle object.
  1662. * @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.
  1663. * @return {Phaser.Rectangle}
  1664. */
  1665. Phaser.Rectangle.clone = function (a, output) {
  1666. if (typeof output === "undefined")
  1667. {
  1668. output = new Phaser.Rectangle(a.x, a.y, a.width, a.height);
  1669. }
  1670. else
  1671. {
  1672. output.setTo(a.x, a.y, a.width, a.height);
  1673. }
  1674. return output;
  1675. };
  1676. /**
  1677. * Determines whether the specified coordinates are contained within the region defined by this Rectangle object.
  1678. * @method Phaser.Rectangle.contains
  1679. * @param {Phaser.Rectangle} a - The Rectangle object.
  1680. * @param {number} x - The x coordinate of the point to test.
  1681. * @param {number} y - The y coordinate of the point to test.
  1682. * @return {boolean} A value of true if the Rectangle object contains the specified point; otherwise false.
  1683. */
  1684. Phaser.Rectangle.contains = function (a, x, y) {
  1685. if (a.width <= 0 || a.height <= 0)
  1686. {
  1687. return false;
  1688. }
  1689. return (x >= a.x && x <= a.right && y >= a.y && y <= a.bottom);
  1690. };
  1691. /**
  1692. * Determines whether the specified coordinates are contained within the region defined by the given raw values.
  1693. * @method Phaser.Rectangle.containsRaw
  1694. * @param {number} rx - The x coordinate of the top left of the area.
  1695. * @param {number} ry - The y coordinate of the top left of the area.
  1696. * @param {number} rw - The width of the area.
  1697. * @param {number} rh - The height of the area.
  1698. * @param {number} x - The x coordinate of the point to test.
  1699. * @param {number} y - The y coordinate of the point to test.
  1700. * @return {boolean} A value of true if the Rectangle object contains the specified point; otherwise false.
  1701. */
  1702. Phaser.Rectangle.containsRaw = function (rx, ry, rw, rh, x, y) {
  1703. return (x >= rx && x <= (rx + rw) && y >= ry && y <= (ry + rh));
  1704. };
  1705. /**
  1706. * 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.
  1707. * @method Phaser.Rectangle.containsPoint
  1708. * @param {Phaser.Rectangle} a - The Rectangle object.
  1709. * @param {Phaser.Point} point - The point object being checked. Can be Point or any object with .x and .y values.
  1710. * @return {boolean} A value of true if the Rectangle object contains the specified point; otherwise false.
  1711. */
  1712. Phaser.Rectangle.containsPoint = function (a, point) {
  1713. return Phaser.Rectangle.contains(a, point.x, point.y);
  1714. };
  1715. /**
  1716. * Determines whether the first Rectangle object is fully contained within the second Rectangle object.
  1717. * A Rectangle object is said to contain another if the second Rectangle object falls entirely within the boundaries of the first.
  1718. * @method Phaser.Rectangle.containsRect
  1719. * @param {Phaser.Rectangle} a - The first Rectangle object.
  1720. * @param {Phaser.Rectangle} b - The second Rectangle object.
  1721. * @return {boolean} A value of true if the Rectangle object contains the specified point; otherwise false.
  1722. */
  1723. Phaser.Rectangle.containsRect = function (a, b) {
  1724. // If the given rect has a larger volume than this one then it can never contain it
  1725. if (a.volume > b.volume)
  1726. {
  1727. return false;
  1728. }
  1729. return (a.x >= b.x && a.y >= b.y && a.right <= b.right && a.bottom <= b.bottom);
  1730. };
  1731. /**
  1732. * Determines whether the two Rectangles are equal.
  1733. * This method compares the x, y, width and height properties of each Rectangle.
  1734. * @method Phaser.Rectangle.equals
  1735. * @param {Phaser.Rectangle} a - The first Rectangle object.
  1736. * @param {Phaser.Rectangle} b - The second Rectangle object.
  1737. * @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.
  1738. */
  1739. Phaser.Rectangle.equals = function (a, b) {
  1740. return (a.x == b.x && a.y == b.y && a.width == b.width && a.height == b.height);
  1741. };
  1742. /**
  1743. * 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.
  1744. * @method Phaser.Rectangle.intersection
  1745. * @param {Phaser.Rectangle} a - The first Rectangle object.
  1746. * @param {Phaser.Rectangle} b - The second Rectangle object.
  1747. * @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.
  1748. * @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.
  1749. */
  1750. Phaser.Rectangle.intersection = function (a, b, output) {
  1751. if (typeof output === "undefined")
  1752. {
  1753. output = new Phaser.Rectangle();
  1754. }
  1755. if (Phaser.Rectangle.intersects(a, b))
  1756. {
  1757. output.x = Math.max(a.x, b.x);
  1758. output.y = Math.max(a.y, b.y);
  1759. output.width = Math.min(a.right, b.right) - output.x;
  1760. output.height = Math.min(a.bottom, b.bottom) - output.y;
  1761. }
  1762. return output;
  1763. };
  1764. /**
  1765. * Determines whether the two Rectangles intersect with each other.
  1766. * This method checks the x, y, width, and height properties of the Rectangles.
  1767. * @method Phaser.Rectangle.intersects
  1768. * @param {Phaser.Rectangle} a - The first Rectangle object.
  1769. * @param {Phaser.Rectangle} b - The second Rectangle object.
  1770. * @return {boolean} A value of true if the specified object intersects with this Rectangle object; otherwise false.
  1771. */
  1772. Phaser.Rectangle.intersects = function (a, b) {
  1773. if (a.width <= 0 || a.height <= 0 || b.width <= 0 || b.height <= 0)
  1774. {
  1775. return false;
  1776. }
  1777. return !(a.right < b.x || a.bottom < b.y || a.x > b.right || a.y > b.bottom);
  1778. };
  1779. /**
  1780. * Determines whether the object specified intersects (overlaps) with the given values.
  1781. * @method Phaser.Rectangle.intersectsRaw
  1782. * @param {number} left - Description.
  1783. * @param {number} right - Description.
  1784. * @param {number} top - Description.
  1785. * @param {number} bottom - Description.
  1786. * @param {number} tolerance - A tolerance value to allow for an intersection test with padding, default to 0
  1787. * @return {boolean} A value of true if the specified object intersects with the Rectangle; otherwise false.
  1788. */
  1789. Phaser.Rectangle.intersectsRaw = function (a, left, right, top, bottom, tolerance) {
  1790. if (typeof tolerance === "undefined") { tolerance = 0; }
  1791. return !(left > a.right + tolerance || right < a.left - tolerance || top > a.bottom + tolerance || bottom < a.top - tolerance);
  1792. };
  1793. /**
  1794. * Adds two Rectangles together to create a new Rectangle object, by filling in the horizontal and vertical space between the two Rectangles.
  1795. * @method Phaser.Rectangle.union
  1796. * @param {Phaser.Rectangle} a - The first Rectangle object.
  1797. * @param {Phaser.Rectangle} b - The second Rectangle object.
  1798. * @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.
  1799. * @return {Phaser.Rectangle} A Rectangle object that is the union of the two Rectangles.
  1800. */
  1801. Phaser.Rectangle.union = function (a, b, output) {
  1802. if (typeof output === "undefined")
  1803. {
  1804. output = new Phaser.Rectangle();
  1805. }
  1806. 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));
  1807. };
  1808. // Because PIXI uses its own Rectangle, we'll replace it with ours to avoid duplicating code or confusion.
  1809. PIXI.Rectangle = Phaser.Rectangle;
  1810. PIXI.EmptyRectangle = new Phaser.Rectangle(0, 0, 0, 0);
  1811. /**
  1812. * @author Richard Davey <rich@photonstorm.com>
  1813. * @copyright 2014 Photon Storm Ltd.
  1814. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  1815. */
  1816. /**
  1817. * Creates a new Line object with a start and an end point.
  1818. * @class Line
  1819. * @classdesc Phaser - Line
  1820. * @constructor
  1821. * @param {number} [x1=0] - The x coordinate of the start of the line.
  1822. * @param {number} [y1=0] - The y coordinate of the start of the line.
  1823. * @param {number} [x2=0] - The x coordinate of the end of the line.
  1824. * @param {number} [y2=0] - The y coordinate of the end of the line.
  1825. * @return {Phaser.Line} This line object
  1826. */
  1827. Phaser.Line = function (x1, y1, x2, y2) {
  1828. x1 = x1 || 0;
  1829. y1 = y1 || 0;
  1830. x2 = x2 || 0;
  1831. y2 = y2 || 0;
  1832. /**
  1833. * @property {Phaser.Point} start - The start point of the line.
  1834. */
  1835. this.start = new Phaser.Point(x1, y1);
  1836. /**
  1837. * @property {Phaser.Point} end - The end point of the line.
  1838. */
  1839. this.end = new Phaser.Point(x2, y2);
  1840. };
  1841. Phaser.Line.prototype = {
  1842. /**
  1843. * Sets the components of the Line to the specified values.
  1844. * @method Phaser.Line#setTo
  1845. * @param {number} [x1=0] - The x coordinate of the start of the line.
  1846. * @param {number} [y1=0] - The y coordinate of the start of the line.
  1847. * @param {number} [x2=0] - The x coordinate of the end of the line.
  1848. * @param {number} [y2=0] - The y coordinate of the end of the line.
  1849. * @return {Phaser.Line} This line object
  1850. */
  1851. setTo: function (x1, y1, x2, y2) {
  1852. this.start.setTo(x1, y1);
  1853. this.end.setTo(x2, y2);
  1854. return this;
  1855. },
  1856. /**
  1857. * Sets the line to match the x/y coordinates of the two given sprites.
  1858. * Can optionally be calculated from their center coordinates.
  1859. * @method Phaser.Line#fromSprite
  1860. * @param {Phaser.Sprite} startSprite - The coordinates of this Sprite will be set to the Line.start point.
  1861. * @param {Phaser.Sprite} endSprite - The coordinates of this Sprite will be set to the Line.start point.
  1862. * @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.
  1863. * @return {Phaser.Line} This line object
  1864. */
  1865. fromSprite: function (startSprite, endSprite, useCenter) {
  1866. if (typeof useCenter === 'undefined') { useCenter = false; }
  1867. if (useCenter)
  1868. {
  1869. return this.setTo(startSprite.center.x, startSprite.center.y, endSprite.center.x, endSprite.center.y);
  1870. }
  1871. else
  1872. {
  1873. return this.setTo(startSprite.x, startSprite.y, endSprite.x, endSprite.y);
  1874. }
  1875. },
  1876. /**
  1877. * Checks for intersection between this line and another Line.
  1878. * If asSegment is true it will check for segment intersection. If asSegment is false it will check for line intersection.
  1879. * Returns the intersection segment of AB and EF as a Point, or null if there is no intersection.
  1880. *
  1881. * @method Phaser.Line#intersects
  1882. * @param {Phaser.Line} line - The line to check against this one.
  1883. * @param {boolean} [asSegment=true] - If true it will check for segment intersection, otherwise full line intersection.
  1884. * @param {Phaser.Point} [result] - A Point object to store the result in, if not given a new one will be created.
  1885. * @return {Phaser.Point} The intersection segment of the two lines as a Point, or null if there is no intersection.
  1886. */
  1887. intersects: function (line, asSegment, result) {
  1888. return Phaser.Line.intersectsPoints(this.start, this.end, line.start, line.end, asSegment, result);
  1889. },
  1890. /**
  1891. * Tests if the given coordinates fall on this line. See pointOnSegment to test against just the line segment.
  1892. * @method Phaser.Line#pointOnLine
  1893. * @param {number} x - The line to check against this one.
  1894. * @param {number} y - The line to check against this one.
  1895. * @return {boolean} True if the point is on the line, false if not.
  1896. */
  1897. pointOnLine: function (x, y) {
  1898. return ((x - this.start.x) * (this.end.y - this.end.y) === (this.end.x - this.start.x) * (y - this.end.y));
  1899. },
  1900. /**
  1901. * Tests if the given coordinates fall on this line and within the segment. See pointOnLine to test against just the line.
  1902. * @method Phaser.Line#pointOnSegment
  1903. * @param {number} x - The line to check against this one.
  1904. * @param {number} y - The line to check against this one.
  1905. * @return {boolean} True if the point is on the line and segment, false if not.
  1906. */
  1907. pointOnSegment: function (x, y) {
  1908. var xMin = Math.min(this.start.x, this.end.x);
  1909. var xMax = Math.max(this.start.x, this.end.x);
  1910. var yMin = Math.min(this.start.y, this.end.y);
  1911. var yMax = Math.max(this.start.y, this.end.y);
  1912. return (this.pointOnLine(x, y) && (x >= xMin && x <= xMax) && (y >= yMin && y <= yMax));
  1913. },
  1914. /**
  1915. * Using Bresenham's line algorithm this will return an array of all coordinates on this line.
  1916. * The start and end points are rounded before this runs as the algorithm works on integers.
  1917. *
  1918. * @method Phaser.Line#coordinatesOnLine
  1919. * @param {number} [stepRate=1] - How many steps will we return? 1 = every coordinate on the line, 2 = every other coordinate, etc.
  1920. * @param {array} [results] - The array to store the results in. If not provided a new one will be generated.
  1921. * @return {array} An array of coordinates.
  1922. */
  1923. coordinatesOnLine: function (stepRate, results) {
  1924. if (typeof stepRate === 'undefined') { stepRate = 1; }
  1925. if (typeof results === 'undefined') { results = []; }
  1926. var x1 = Math.round(this.start.x);
  1927. var y1 = Math.round(this.start.y);
  1928. var x2 = Math.round(this.end.x);
  1929. var y2 = Math.round(this.end.y);
  1930. var dx = Math.abs(x2 - x1);
  1931. var dy = Math.abs(y2 - y1);
  1932. var sx = (x1 < x2) ? 1 : -1;
  1933. var sy = (y1 < y2) ? 1 : -1;
  1934. var err = dx - dy;
  1935. results.push([x1, y1]);
  1936. var i = 1;
  1937. while (!((x1 == x2) && (y1 == y2)))
  1938. {
  1939. var e2 = err << 1;
  1940. if (e2 > -dy)
  1941. {
  1942. err -= dy;
  1943. x1 += sx;
  1944. }
  1945. if (e2 < dx)
  1946. {
  1947. err += dx;
  1948. y1 += sy;
  1949. }
  1950. if (i % stepRate === 0)
  1951. {
  1952. results.push([x1, y1]);
  1953. }
  1954. i++;
  1955. }
  1956. return results;
  1957. }
  1958. };
  1959. /**
  1960. * @name Phaser.Line#length
  1961. * @property {number} length - Gets the length of the line segment.
  1962. * @readonly
  1963. */
  1964. Object.defineProperty(Phaser.Line.prototype, "length", {
  1965. get: function () {
  1966. 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));
  1967. }
  1968. });
  1969. /**
  1970. * @name Phaser.Line#angle
  1971. * @property {number} angle - Gets the angle of the line.
  1972. * @readonly
  1973. */
  1974. Object.defineProperty(Phaser.Line.prototype, "angle", {
  1975. get: function () {
  1976. return Math.atan2(this.end.x - this.start.x, this.end.y - this.start.y);
  1977. }
  1978. });
  1979. /**
  1980. * @name Phaser.Line#slope
  1981. * @property {number} slope - Gets the slope of the line (y/x).
  1982. * @readonly
  1983. */
  1984. Object.defineProperty(Phaser.Line.prototype, "slope", {
  1985. get: function () {
  1986. return (this.end.y - this.start.y) / (this.end.x - this.start.x);
  1987. }
  1988. });
  1989. /**
  1990. * @name Phaser.Line#perpSlope
  1991. * @property {number} perpSlope - Gets the perpendicular slope of the line (x/y).
  1992. * @readonly
  1993. */
  1994. Object.defineProperty(Phaser.Line.prototype, "perpSlope", {
  1995. get: function () {
  1996. return -((this.end.x - this.start.x) / (this.end.y - this.start.y));
  1997. }
  1998. });
  1999. /**
  2000. * @name Phaser.Line#x
  2001. * @property {number} x - Gets the x coordinate of the top left of the bounds around this line.
  2002. * @readonly
  2003. */
  2004. Object.defineProperty(Phaser.Line.prototype, "x", {
  2005. get: function () {
  2006. return Math.min(this.start.x, this.end.x);
  2007. }
  2008. });
  2009. /**
  2010. * @name Phaser.Line#y
  2011. * @property {number} y - Gets the y coordinate of the top left of the bounds around this line.
  2012. * @readonly
  2013. */
  2014. Object.defineProperty(Phaser.Line.prototype, "y", {
  2015. get: function () {
  2016. return Math.min(this.start.y, this.end.y);
  2017. }
  2018. });
  2019. /**
  2020. * @name Phaser.Line#left
  2021. * @property {number} left - Gets the left-most point of this line.
  2022. * @readonly
  2023. */
  2024. Object.defineProperty(Phaser.Line.prototype, "left", {
  2025. get: function () {
  2026. return Math.min(this.start.x, this.end.x);
  2027. }
  2028. });
  2029. /**
  2030. * @name Phaser.Line#right
  2031. * @property {number} right - Gets the right-most point of this line.
  2032. * @readonly
  2033. */
  2034. Object.defineProperty(Phaser.Line.prototype, "right", {
  2035. get: function () {
  2036. return Math.max(this.start.x, this.end.x);
  2037. }
  2038. });
  2039. /**
  2040. * @name Phaser.Line#top
  2041. * @property {number} top - Gets the top-most point of this line.
  2042. * @readonly
  2043. */
  2044. Object.defineProperty(Phaser.Line.prototype, "top", {
  2045. get: function () {
  2046. return Math.min(this.start.y, this.end.y);
  2047. }
  2048. });
  2049. /**
  2050. * @name Phaser.Line#bottom
  2051. * @property {number} bottom - Gets the bottom-most point of this line.
  2052. * @readonly
  2053. */
  2054. Object.defineProperty(Phaser.Line.prototype, "bottom", {
  2055. get: function () {
  2056. return Math.max(this.start.y, this.end.y);
  2057. }
  2058. });
  2059. /**
  2060. * @name Phaser.Line#width
  2061. * @property {number} width - Gets the width of this bounds of this line.
  2062. * @readonly
  2063. */
  2064. Object.defineProperty(Phaser.Line.prototype, "width", {
  2065. get: function () {
  2066. return Math.abs(this.start.x - this.end.x);
  2067. }
  2068. });
  2069. /**
  2070. * @name Phaser.Line#height
  2071. * @property {number} height - Gets the height of this bounds of this line.
  2072. * @readonly
  2073. */
  2074. Object.defineProperty(Phaser.Line.prototype, "height", {
  2075. get: function () {
  2076. return Math.abs(this.start.y - this.end.y);
  2077. }
  2078. });
  2079. /**
  2080. * Checks for intersection between two lines as defined by the given start and end points.
  2081. * If asSegment is true it will check for line segment intersection. If asSegment is false it will check for line intersection.
  2082. * Returns the intersection segment of AB and EF as a Point, or null if there is no intersection.
  2083. * Adapted from code by Keith Hair
  2084. *
  2085. * @method Phaser.Line.intersectsPoints
  2086. * @param {Phaser.Point} a - The start of the first Line to be checked.
  2087. * @param {Phaser.Point} b - The end of the first line to be checked.
  2088. * @param {Phaser.Point} e - The start of the second Line to be checked.
  2089. * @param {Phaser.Point} f - The end of the second line to be checked.
  2090. * @param {boolean} [asSegment=true] - If true it will check for segment intersection, otherwise full line intersection.
  2091. * @param {Phaser.Point} [result] - A Point object to store the result in, if not given a new one will be created.
  2092. * @return {Phaser.Point} The intersection segment of the two lines as a Point, or null if there is no intersection.
  2093. */
  2094. Phaser.Line.intersectsPoints = function (a, b, e, f, asSegment, result) {
  2095. if (typeof asSegment === 'undefined') { asSegment = true; }
  2096. if (typeof result === 'undefined') { result = new Phaser.Point(); }
  2097. var a1 = b.y - a.y;
  2098. var a2 = f.y - e.y;
  2099. var b1 = a.x - b.x;
  2100. var b2 = e.x - f.x;
  2101. var c1 = (b.x * a.y) - (a.x * b.y);
  2102. var c2 = (f.x * e.y) - (e.x * f.y);
  2103. var denom = (a1 * b2) - (a2 * b1);
  2104. if (denom === 0)
  2105. {
  2106. return null;
  2107. }
  2108. result.x = ((b1 * c2) - (b2 * c1)) / denom;
  2109. result.y = ((a2 * c1) - (a1 * c2)) / denom;
  2110. if (asSegment)
  2111. {
  2112. if (Math.pow((result.x - b.x) + (result.y - b.y), 2) > Math.pow((a.x - b.x) + (a.y - b.y), 2))
  2113. {
  2114. return null;
  2115. }
  2116. if (Math.pow((result.x - a.x) + (result.y - a.y), 2) > Math.pow((a.x - b.x) + (a.y - b.y), 2))
  2117. {
  2118. return null;
  2119. }
  2120. if (Math.pow((result.x - f.x) + (result.y - f.y), 2) > Math.pow((e.x - f.x) + (e.y - f.y), 2))
  2121. {
  2122. return null;
  2123. }
  2124. if (Math.pow((result.x - e.x) + (result.y - e.y), 2) > Math.pow((e.x - f.x) + (e.y - f.y), 2))
  2125. {
  2126. return null;
  2127. }
  2128. }
  2129. return result;
  2130. };
  2131. /**
  2132. * Checks for intersection between two lines.
  2133. * If asSegment is true it will check for segment intersection.
  2134. * If asSegment is false it will check for line intersection.
  2135. * Returns the intersection segment of AB and EF as a Point, or null if there is no intersection.
  2136. * Adapted from code by Keith Hair
  2137. *
  2138. * @method Phaser.Line.intersects
  2139. * @param {Phaser.Line} a - The first Line to be checked.
  2140. * @param {Phaser.Line} b - The second Line to be checked.
  2141. * @param {boolean} [asSegment=true] - If true it will check for segment intersection, otherwise full line intersection.
  2142. * @param {Phaser.Point} [result] - A Point object to store the result in, if not given a new one will be created.
  2143. * @return {Phaser.Point} The intersection segment of the two lines as a Point, or null if there is no intersection.
  2144. */
  2145. Phaser.Line.intersects = function (a, b, asSegment, result) {
  2146. return Phaser.Line.intersectsPoints(a.start, a.end, b.start, b.end, asSegment, result);
  2147. };
  2148. /**
  2149. * @author Richard Davey <rich@photonstorm.com>
  2150. * @author Chad Engler <chad@pantherdev.com>
  2151. * @copyright 2014 Photon Storm Ltd.
  2152. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  2153. */
  2154. /**
  2155. * Creates a Ellipse object. A curve on a plane surrounding two focal points.
  2156. * @class Ellipse
  2157. * @classdesc Phaser - Ellipse
  2158. * @constructor
  2159. * @param {number} [x=0] - The X coordinate of the upper-left corner of the framing rectangle of this ellipse.
  2160. * @param {number} [y=0] - The Y coordinate of the upper-left corner of the framing rectangle of this ellipse.
  2161. * @param {number} [width=0] - The overall width of this ellipse.
  2162. * @param {number} [height=0] - The overall height of this ellipse.
  2163. * @return {Phaser.Ellipse} This Ellipse object
  2164. */
  2165. Phaser.Ellipse = function (x, y, width, height) {
  2166. this.type = Phaser.ELLIPSE;
  2167. x = x || 0;
  2168. y = y || 0;
  2169. width = width || 0;
  2170. height = height || 0;
  2171. /**
  2172. * @property {number} x - The X coordinate of the upper-left corner of the framing rectangle of this ellipse.
  2173. */
  2174. this.x = x;
  2175. /**
  2176. * @property {number} y - The Y coordinate of the upper-left corner of the framing rectangle of this ellipse.
  2177. */
  2178. this.y = y;
  2179. /**
  2180. * @property {number} width - The overall width of this ellipse.
  2181. */
  2182. this.width = width;
  2183. /**
  2184. * @property {number} height - The overall height of this ellipse.
  2185. */
  2186. this.height = height;
  2187. };
  2188. Phaser.Ellipse.prototype = {
  2189. /**
  2190. * Sets the members of the Ellipse to the specified values.
  2191. * @method Phaser.Ellipse#setTo
  2192. * @param {number} x - The X coordinate of the upper-left corner of the framing rectangle of this ellipse.
  2193. * @param {number} y - The Y coordinate of the upper-left corner of the framing rectangle of this ellipse.
  2194. * @param {number} width - The overall width of this ellipse.
  2195. * @param {number} height - The overall height of this ellipse.
  2196. * @return {Phaser.Ellipse} This Ellipse object.
  2197. */
  2198. setTo: function (x, y, width, height) {
  2199. this.x = x;
  2200. this.y = y;
  2201. this.width = width;
  2202. this.height = height;
  2203. return this;
  2204. },
  2205. /**
  2206. * Copies the x, y, width and height properties from any given object to this Ellipse.
  2207. * @method Phaser.Ellipse#copyFrom
  2208. * @param {any} source - The object to copy from.
  2209. * @return {Phaser.Ellipse} This Ellipse object.
  2210. */
  2211. copyFrom: function (source) {
  2212. return this.setTo(source.x, source.y, source.width, source.height);
  2213. },
  2214. /**
  2215. * Copies the x, y and diameter properties from this Circle to any given object.
  2216. * @method Phaser.Ellipse#copyTo
  2217. * @param {any} dest - The object to copy to.
  2218. * @return {Object} This dest object.
  2219. */
  2220. copyTo: function(dest) {
  2221. dest.x = this.x;
  2222. dest.y = this.y;
  2223. dest.width = this.width;
  2224. dest.height = this.height;
  2225. return dest;
  2226. },
  2227. /**
  2228. * Returns a new Ellipse object with the same values for the x, y, width, and height properties as this Ellipse object.
  2229. * @method Phaser.Ellipse#clone
  2230. * @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.
  2231. * @return {Phaser.Ellipse} The cloned Ellipse object.
  2232. */
  2233. clone: function(out) {
  2234. if (typeof out === "undefined")
  2235. {
  2236. out = new Phaser.Ellipse(this.x, this.y, this.width, this.height);
  2237. }
  2238. else
  2239. {
  2240. out.setTo(this.x, this.y, this.width, this.height);
  2241. }
  2242. return out;
  2243. },
  2244. /**
  2245. * Return true if the given x/y coordinates are within this Ellipse object.
  2246. * @method Phaser.Ellipse#contains
  2247. * @param {number} x - The X value of the coordinate to test.
  2248. * @param {number} y - The Y value of the coordinate to test.
  2249. * @return {boolean} True if the coordinates are within this ellipse, otherwise false.
  2250. */
  2251. contains: function (x, y) {
  2252. return Phaser.Ellipse.contains(this, x, y);
  2253. },
  2254. /**
  2255. * Returns a string representation of this object.
  2256. * @method Phaser.Ellipse#toString
  2257. * @return {string} A string representation of the instance.
  2258. */
  2259. toString: function () {
  2260. return "[{Phaser.Ellipse (x=" + this.x + " y=" + this.y + " width=" + this.width + " height=" + this.height + ")}]";
  2261. }
  2262. };
  2263. Phaser.Ellipse.prototype.constructor = Phaser.Ellipse;
  2264. /**
  2265. * The left coordinate of the Ellipse. The same as the X coordinate.
  2266. * @name Phaser.Ellipse#left
  2267. * @propety {number} left - Gets or sets the value of the leftmost point of the ellipse.
  2268. */
  2269. Object.defineProperty(Phaser.Ellipse.prototype, "left", {
  2270. get: function () {
  2271. return this.x;
  2272. },
  2273. set: function (value) {
  2274. this.x = value;
  2275. }
  2276. });
  2277. /**
  2278. * 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.
  2279. * @name Phaser.Ellipse#right
  2280. * @property {number} right - Gets or sets the value of the rightmost point of the ellipse.
  2281. */
  2282. Object.defineProperty(Phaser.Ellipse.prototype, "right", {
  2283. get: function () {
  2284. return this.x + this.width;
  2285. },
  2286. set: function (value) {
  2287. if (value < this.x)
  2288. {
  2289. this.width = 0;
  2290. }
  2291. else
  2292. {
  2293. this.width = this.x + value;
  2294. }
  2295. }
  2296. });
  2297. /**
  2298. * The top of the Ellipse. The same as its y property.
  2299. * @name Phaser.Ellipse#top
  2300. * @property {number} top - Gets or sets the top of the ellipse.
  2301. */
  2302. Object.defineProperty(Phaser.Ellipse.prototype, "top", {
  2303. get: function () {
  2304. return this.y;
  2305. },
  2306. set: function (value) {
  2307. this.y = value;
  2308. }
  2309. });
  2310. /**
  2311. * 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.
  2312. * @name Phaser.Ellipse#bottom
  2313. * @property {number} bottom - Gets or sets the bottom of the ellipse.
  2314. */
  2315. Object.defineProperty(Phaser.Ellipse.prototype, "bottom", {
  2316. get: function () {
  2317. return this.y + this.height;
  2318. },
  2319. set: function (value) {
  2320. if (value < this.y)
  2321. {
  2322. this.height = 0;
  2323. }
  2324. else
  2325. {
  2326. this.height = this.y + value;
  2327. }
  2328. }
  2329. });
  2330. /**
  2331. * 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.
  2332. * 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.
  2333. * @name Phaser.Ellipse#empty
  2334. * @property {boolean} empty - Gets or sets the empty state of the ellipse.
  2335. */
  2336. Object.defineProperty(Phaser.Ellipse.prototype, "empty", {
  2337. get: function () {
  2338. return (this.width === 0 || this.height === 0);
  2339. },
  2340. set: function (value) {
  2341. if (value === true)
  2342. {
  2343. this.setTo(0, 0, 0, 0);
  2344. }
  2345. }
  2346. });
  2347. /**
  2348. * Return true if the given x/y coordinates are within the Ellipse object.
  2349. * @method Phaser.Ellipse.contains
  2350. * @param {Phaser.Ellipse} a - The Ellipse to be checked.
  2351. * @param {number} x - The X value of the coordinate to test.
  2352. * @param {number} y - The Y value of the coordinate to test.
  2353. * @return {boolean} True if the coordinates are within this ellipse, otherwise false.
  2354. */
  2355. Phaser.Ellipse.contains = function (a, x, y) {
  2356. if (a.width <= 0 || a.height <= 0)
  2357. {
  2358. return false;
  2359. }
  2360. // Normalize the coords to an ellipse with center 0,0 and a radius of 0.5
  2361. var normx = ((x - a.x) / a.width) - 0.5;
  2362. var normy = ((y - a.y) / a.height) - 0.5;
  2363. normx *= normx;
  2364. normy *= normy;
  2365. return (normx + normy < 0.25);
  2366. };
  2367. /**
  2368. * Returns the framing rectangle of the ellipse as a Phaser.Rectangle object.
  2369. *
  2370. * @method Phaser.Ellipse.getBounds
  2371. * @return {Phaser.Rectangle} The framing rectangle
  2372. */
  2373. Phaser.Ellipse.prototype.getBounds = function() {
  2374. return new Phaser.Rectangle(this.x, this.y, this.width, this.height);
  2375. };
  2376. // Because PIXI uses its own Ellipse, we'll replace it with ours to avoid duplicating code or confusion.
  2377. PIXI.Ellipse = Phaser.Ellipse;
  2378. /**
  2379. * @author Richard Davey <rich@photonstorm.com>
  2380. * @author Adrien Brault <adrien.brault@gmail.com>
  2381. * @copyright 2014 Photon Storm Ltd.
  2382. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  2383. */
  2384. /**
  2385. * Creates a new Polygon. You have to provide a list of points.
  2386. * 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, ...],
  2387. * 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
  2388. * 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.
  2389. *
  2390. * @class Phaser.Polygon
  2391. * @classdesc The polygon represents a list of orderded points in space
  2392. * @constructor
  2393. * @param {Array<Phaser.Point>|Array<number>} points - The array of Points.
  2394. */
  2395. Phaser.Polygon = function (points) {
  2396. /**
  2397. * @property {number} type - The base object type.
  2398. */
  2399. this.type = Phaser.POLYGON;
  2400. //if points isn't an array, use arguments as the array
  2401. if (!(points instanceof Array))
  2402. {
  2403. points = Array.prototype.slice.call(arguments);
  2404. }
  2405. //if this is a flat array of numbers, convert it to points
  2406. if (typeof points[0] === 'number')
  2407. {
  2408. var p = [];
  2409. for (var i = 0, len = points.length; i < len; i += 2)
  2410. {
  2411. p.push(new Phaser.Point(points[i], points[i + 1]));
  2412. }
  2413. points = p;
  2414. }
  2415. /**
  2416. * @property {array<Phaser.Point>|array<number>} points - The array of Points.
  2417. */
  2418. this.points = points;
  2419. };
  2420. Phaser.Polygon.prototype = {
  2421. /**
  2422. * Creates a clone of this polygon.
  2423. *
  2424. * @method Phaser.Polygon#clone
  2425. * @return {Phaser.Polygon} A copy of the polygon.
  2426. */
  2427. clone: function () {
  2428. var points = [];
  2429. for (var i=0; i < this.points.length; i++)
  2430. {
  2431. points.push(this.points[i].clone());
  2432. }
  2433. return new Phaser.Polygon(points);
  2434. },
  2435. /**
  2436. * Checks whether the x and y coordinates are contained within this polygon.
  2437. *
  2438. * @method Phaser.Polygon#contains
  2439. * @param {number} x - The X value of the coordinate to test.
  2440. * @param {number} y - The Y value of the coordinate to test.
  2441. * @return {boolean} True if the coordinates are within this polygon, otherwise false.
  2442. */
  2443. contains: function (x, y) {
  2444. var inside = false;
  2445. // use some raycasting to test hits https://github.com/substack/point-in-polygon/blob/master/index.js
  2446. for (var i = 0, j = this.points.length - 1; i < this.points.length; j = i++)
  2447. {
  2448. var xi = this.points[i].x;
  2449. var yi = this.points[i].y;
  2450. var xj = this.points[j].x;
  2451. var yj = this.points[j].y;
  2452. var intersect = ((yi > y) !== (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi);
  2453. if (intersect)
  2454. {
  2455. inside = true;
  2456. }
  2457. }
  2458. return inside;
  2459. }
  2460. };
  2461. Phaser.Polygon.prototype.constructor = Phaser.Polygon;
  2462. // Because PIXI uses its own Polygon, we'll replace it with ours to avoid duplicating code or confusion.
  2463. PIXI.Polygon = Phaser.Polygon;
  2464. /**
  2465. * @author Richard Davey <rich@photonstorm.com>
  2466. * @copyright 2014 Photon Storm Ltd.
  2467. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  2468. */
  2469. /**
  2470. * 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.
  2471. * The game automatically creates a single Stage sized camera on boot. Move the camera around the world with Phaser.Camera.x/y
  2472. *
  2473. * @class Phaser.Camera
  2474. * @constructor
  2475. * @param {Phaser.Game} game - Game reference to the currently running game.
  2476. * @param {number} id - Not being used at the moment, will be when Phaser supports multiple camera
  2477. * @param {number} x - Position of the camera on the X axis
  2478. * @param {number} y - Position of the camera on the Y axis
  2479. * @param {number} width - The width of the view rectangle
  2480. * @param {number} height - The height of the view rectangle
  2481. */
  2482. Phaser.Camera = function (game, id, x, y, width, height) {
  2483. /**
  2484. * @property {Phaser.Game} game - A reference to the currently running Game.
  2485. */
  2486. this.game = game;
  2487. /**
  2488. * @property {Phaser.World} world - A reference to the game world.
  2489. */
  2490. this.world = game.world;
  2491. /**
  2492. * @property {number} id - Reserved for future multiple camera set-ups.
  2493. * @default
  2494. */
  2495. this.id = 0;
  2496. /**
  2497. * Camera view.
  2498. * The view into the world we wish to render (by default the game dimensions).
  2499. * The x/y values are in world coordinates, not screen coordinates, the width/height is how many pixels to render.
  2500. * Objects outside of this view are not rendered if set to camera cull.
  2501. * @property {Phaser.Rectangle} view
  2502. */
  2503. this.view = new Phaser.Rectangle(x, y, width, height);
  2504. /**
  2505. * @property {Phaser.Rectangle} screenView - Used by Sprites to work out Camera culling.
  2506. */
  2507. this.screenView = new Phaser.Rectangle(x, y, width, height);
  2508. /**
  2509. * 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.
  2510. * 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
  2511. * 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.
  2512. * @property {Phaser.Rectangle} bounds - The Rectangle in which the Camera is bounded. Set to null to allow for movement anywhere.
  2513. */
  2514. this.bounds = new Phaser.Rectangle(x, y, width, height);
  2515. /**
  2516. * @property {Phaser.Rectangle} deadzone - Moving inside this Rectangle will not cause camera moving.
  2517. */
  2518. this.deadzone = null;
  2519. /**
  2520. * @property {boolean} visible - Whether this camera is visible or not.
  2521. * @default
  2522. */
  2523. this.visible = true;
  2524. /**
  2525. * @property {boolean} atLimit - Whether this camera is flush with the World Bounds or not.
  2526. */
  2527. this.atLimit = { x: false, y: false };
  2528. /**
  2529. * @property {Phaser.Sprite} target - If the camera is tracking a Sprite, this is a reference to it, otherwise null.
  2530. * @default
  2531. */
  2532. this.target = null;
  2533. /**
  2534. * @property {number} edge - Edge property.
  2535. * @private
  2536. * @default
  2537. */
  2538. this._edge = 0;
  2539. /**
  2540. * @property {PIXI.DisplayObject} displayObject - The display object to which all game objects are added. Set by World.boot
  2541. */
  2542. this.displayObject = null;
  2543. /**
  2544. * @property {Phaser.Point} scale - The scale of the display object to which all game objects are added. Set by World.boot
  2545. */
  2546. this.scale = null;
  2547. };
  2548. /**
  2549. * @constant
  2550. * @type {number}
  2551. */
  2552. Phaser.Camera.FOLLOW_LOCKON = 0;
  2553. /**
  2554. * @constant
  2555. * @type {number}
  2556. */
  2557. Phaser.Camera.FOLLOW_PLATFORMER = 1;
  2558. /**
  2559. * @constant
  2560. * @type {number}
  2561. */
  2562. Phaser.Camera.FOLLOW_TOPDOWN = 2;
  2563. /**
  2564. * @constant
  2565. * @type {number}
  2566. */
  2567. Phaser.Camera.FOLLOW_TOPDOWN_TIGHT = 3;
  2568. Phaser.Camera.prototype = {
  2569. /**
  2570. * Tells this camera which sprite to follow.
  2571. * @method Phaser.Camera#follow
  2572. * @param {Phaser.Sprite|Phaser.Image|Phaser.Text} target - The object you want the camera to track. Set to null to not follow anything.
  2573. * @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().
  2574. */
  2575. follow: function (target, style) {
  2576. if (typeof style === "undefined") { style = Phaser.Camera.FOLLOW_LOCKON; }
  2577. this.target = target;
  2578. var helper;
  2579. switch (style) {
  2580. case Phaser.Camera.FOLLOW_PLATFORMER:
  2581. var w = this.width / 8;
  2582. var h = this.height / 3;
  2583. this.deadzone = new Phaser.Rectangle((this.width - w) / 2, (this.height - h) / 2 - h * 0.25, w, h);
  2584. break;
  2585. case Phaser.Camera.FOLLOW_TOPDOWN:
  2586. helper = Math.max(this.width, this.height) / 4;
  2587. this.deadzone = new Phaser.Rectangle((this.width - helper) / 2, (this.height - helper) / 2, helper, helper);
  2588. break;
  2589. case Phaser.Camera.FOLLOW_TOPDOWN_TIGHT:
  2590. helper = Math.max(this.width, this.height) / 8;
  2591. this.deadzone = new Phaser.Rectangle((this.width - helper) / 2, (this.height - helper) / 2, helper, helper);
  2592. break;
  2593. case Phaser.Camera.FOLLOW_LOCKON:
  2594. this.deadzone = null;
  2595. break;
  2596. default:
  2597. this.deadzone = null;
  2598. break;
  2599. }
  2600. },
  2601. /**
  2602. * Move the camera focus on a display object instantly.
  2603. * @method Phaser.Camera#focusOn
  2604. * @param {any} displayObject - The display object to focus the camera on. Must have visible x/y properties.
  2605. */
  2606. focusOn: function (displayObject) {
  2607. this.setPosition(Math.round(displayObject.x - this.view.halfWidth), Math.round(displayObject.y - this.view.halfHeight));
  2608. },
  2609. /**
  2610. * Move the camera focus on a location instantly.
  2611. * @method Phaser.Camera#focusOnXY
  2612. * @param {number} x - X position.
  2613. * @param {number} y - Y position.
  2614. */
  2615. focusOnXY: function (x, y) {
  2616. this.setPosition(Math.round(x - this.view.halfWidth), Math.round(y - this.view.halfHeight));
  2617. },
  2618. /**
  2619. * Update focusing and scrolling.
  2620. * @method Phaser.Camera#update
  2621. */
  2622. update: function () {
  2623. if (this.target)
  2624. {
  2625. this.updateTarget();
  2626. }
  2627. if (this.bounds)
  2628. {
  2629. this.checkBounds();
  2630. }
  2631. this.displayObject.position.x = -this.view.x;
  2632. this.displayObject.position.y = -this.view.y;
  2633. },
  2634. /**
  2635. * Internal method
  2636. * @method Phaser.Camera#updateTarget
  2637. * @private
  2638. */
  2639. updateTarget: function () {
  2640. if (this.deadzone)
  2641. {
  2642. this._edge = this.target.x - this.deadzone.x;
  2643. if (this.view.x > this._edge)
  2644. {
  2645. this.view.x = this._edge;
  2646. }
  2647. this._edge = this.target.x + this.target.width - this.deadzone.x - this.deadzone.width;
  2648. if (this.view.x < this._edge)
  2649. {
  2650. this.view.x = this._edge;
  2651. }
  2652. this._edge = this.target.y - this.deadzone.y;
  2653. if (this.view.y > this._edge)
  2654. {
  2655. this.view.y = this._edge;
  2656. }
  2657. this._edge = this.target.y + this.target.height - this.deadzone.y - this.deadzone.height;
  2658. if (this.view.y < this._edge)
  2659. {
  2660. this.view.y = this._edge;
  2661. }
  2662. }
  2663. else
  2664. {
  2665. this.focusOnXY(this.target.x, this.target.y);
  2666. }
  2667. },
  2668. /**
  2669. * Update the Camera bounds to match the game world.
  2670. * @method Phaser.Camera#setBoundsToWorld
  2671. */
  2672. setBoundsToWorld: function () {
  2673. this.bounds.setTo(this.game.world.bounds.x, this.game.world.bounds.y, this.game.world.bounds.width, this.game.world.bounds.height);
  2674. },
  2675. /**
  2676. * Method called to ensure the camera doesn't venture outside of the game world.
  2677. * @method Phaser.Camera#checkWorldBounds
  2678. */
  2679. checkBounds: function () {
  2680. this.atLimit.x = false;
  2681. this.atLimit.y = false;
  2682. // Make sure we didn't go outside the cameras bounds
  2683. if (this.view.x <= this.bounds.x)
  2684. {
  2685. this.atLimit.x = true;
  2686. this.view.x = this.bounds.x;
  2687. }
  2688. if (this.view.right >= this.bounds.right)
  2689. {
  2690. this.atLimit.x = true;
  2691. this.view.x = this.bounds.right - this.width;
  2692. }
  2693. if (this.view.y <= this.bounds.top)
  2694. {
  2695. this.atLimit.y = true;
  2696. this.view.y = this.bounds.top;
  2697. }
  2698. if (this.view.bottom >= this.bounds.bottom)
  2699. {
  2700. this.atLimit.y = true;
  2701. this.view.y = this.bounds.bottom - this.height;
  2702. }
  2703. this.view.floor();
  2704. },
  2705. /**
  2706. * A helper function to set both the X and Y properties of the camera at once
  2707. * without having to use game.camera.x and game.camera.y.
  2708. *
  2709. * @method Phaser.Camera#setPosition
  2710. * @param {number} x - X position.
  2711. * @param {number} y - Y position.
  2712. */
  2713. setPosition: function (x, y) {
  2714. this.view.x = x;
  2715. this.view.y = y;
  2716. if (this.bounds)
  2717. {
  2718. this.checkBounds();
  2719. }
  2720. },
  2721. /**
  2722. * Sets the size of the view rectangle given the width and height in parameters.
  2723. *
  2724. * @method Phaser.Camera#setSize
  2725. * @param {number} width - The desired width.
  2726. * @param {number} height - The desired height.
  2727. */
  2728. setSize: function (width, height) {
  2729. this.view.width = width;
  2730. this.view.height = height;
  2731. },
  2732. /**
  2733. * Resets the camera back to 0,0 and un-follows any object it may have been tracking.
  2734. *
  2735. * @method Phaser.Camera#reset
  2736. */
  2737. reset: function () {
  2738. this.target = null;
  2739. this.view.x = 0;
  2740. this.view.y = 0;
  2741. }
  2742. };
  2743. Phaser.Camera.prototype.constructor = Phaser.Camera;
  2744. /**
  2745. * The Cameras x coordinate. This value is automatically clamped if it falls outside of the World bounds.
  2746. * @name Phaser.Camera#x
  2747. * @property {number} x - Gets or sets the cameras x position.
  2748. */
  2749. Object.defineProperty(Phaser.Camera.prototype, "x", {
  2750. get: function () {
  2751. return this.view.x;
  2752. },
  2753. set: function (value) {
  2754. this.view.x = value;
  2755. if (this.bounds)
  2756. {
  2757. this.checkBounds();
  2758. }
  2759. }
  2760. });
  2761. /**
  2762. * The Cameras y coordinate. This value is automatically clamped if it falls outside of the World bounds.
  2763. * @name Phaser.Camera#y
  2764. * @property {number} y - Gets or sets the cameras y position.
  2765. */
  2766. Object.defineProperty(Phaser.Camera.prototype, "y", {
  2767. get: function () {
  2768. return this.view.y;
  2769. },
  2770. set: function (value) {
  2771. this.view.y = value;
  2772. if (this.bounds)
  2773. {
  2774. this.checkBounds();
  2775. }
  2776. }
  2777. });
  2778. /**
  2779. * The Cameras width. By default this is the same as the Game size and should not be adjusted for now.
  2780. * @name Phaser.Camera#width
  2781. * @property {number} width - Gets or sets the cameras width.
  2782. */
  2783. Object.defineProperty(Phaser.Camera.prototype, "width", {
  2784. get: function () {
  2785. return this.view.width;
  2786. },
  2787. set: function (value) {
  2788. this.view.width = value;
  2789. }
  2790. });
  2791. /**
  2792. * The Cameras height. By default this is the same as the Game size and should not be adjusted for now.
  2793. * @name Phaser.Camera#height
  2794. * @property {number} height - Gets or sets the cameras height.
  2795. */
  2796. Object.defineProperty(Phaser.Camera.prototype, "height", {
  2797. get: function () {
  2798. return this.view.height;
  2799. },
  2800. set: function (value) {
  2801. this.view.height = value;
  2802. }
  2803. });
  2804. /**
  2805. * @author Richard Davey <rich@photonstorm.com>
  2806. * @copyright 2014 Photon Storm Ltd.
  2807. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  2808. */
  2809. /**
  2810. * This is a base State class which can be extended if you are creating your own game.
  2811. * It provides quick access to common functions such as the camera, cache, input, match, sound and more.
  2812. *
  2813. * @class Phaser.State
  2814. * @constructor
  2815. */
  2816. Phaser.State = function () {
  2817. /**
  2818. * @property {Phaser.Game} game - A reference to the currently running Game.
  2819. */
  2820. this.game = null;
  2821. /**
  2822. * @property {Phaser.GameObjectFactory} add - Reference to the GameObjectFactory.
  2823. */
  2824. this.add = null;
  2825. /**
  2826. * @property {Phaser.GameObjectCreator} make - Reference to the GameObjectCreator.
  2827. */
  2828. this.make = null;
  2829. /**
  2830. * @property {Phaser.Camera} camera - A handy reference to world.camera.
  2831. */
  2832. this.camera = null;
  2833. /**
  2834. * @property {Phaser.Cache} cache - Reference to the assets cache.
  2835. */
  2836. this.cache = null;
  2837. /**
  2838. * @property {Phaser.Input} input - Reference to the input manager
  2839. */
  2840. this.input = null;
  2841. /**
  2842. * @property {Phaser.Loader} load - Reference to the assets loader.
  2843. */
  2844. this.load = null;
  2845. /**
  2846. * @property {Phaser.Math} math - Reference to the math helper.
  2847. */
  2848. this.math = null;
  2849. /**
  2850. * @property {Phaser.SoundManager} sound - Reference to the sound manager.
  2851. */
  2852. this.sound = null;
  2853. /**
  2854. * @property {Phaser.ScaleManager} scale - Reference to the game scale manager.
  2855. */
  2856. this.scale = null;
  2857. /**
  2858. * @property {Phaser.Stage} stage - Reference to the stage.
  2859. */
  2860. this.stage = null;
  2861. /**
  2862. * @property {Phaser.Time} time - Reference to the core game clock.
  2863. */
  2864. this.time = null;
  2865. /**
  2866. * @property {Phaser.TweenManager} tweens - Reference to the tween manager.
  2867. */
  2868. this.tweens = null;
  2869. /**
  2870. * @property {Phaser.World} world - Reference to the world.
  2871. */
  2872. this.world = null;
  2873. /**
  2874. * @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.
  2875. */
  2876. this.particles = null;
  2877. /**
  2878. * @property {Phaser.Physics} physics - Reference to the physics manager.
  2879. */
  2880. this.physics = null;
  2881. /**
  2882. * @property {Phaser.RandomDataGenerator} rnd - Reference to the random data generator.
  2883. */
  2884. this.rnd = null;
  2885. };
  2886. Phaser.State.prototype = {
  2887. /**
  2888. * Override this method to add some load operations.
  2889. * If you need to use the loader, you may need to use them here.
  2890. *
  2891. * @method Phaser.State#preload
  2892. */
  2893. preload: function () {
  2894. },
  2895. /**
  2896. * Put update logic here.
  2897. *
  2898. * @method Phaser.State#loadUpdate
  2899. */
  2900. loadUpdate: function () {
  2901. },
  2902. /**
  2903. * Put render operations here.
  2904. *
  2905. * @method Phaser.State#loadRender
  2906. */
  2907. loadRender: function () {
  2908. },
  2909. /**
  2910. * This method is called after the game engine successfully switches states.
  2911. * Feel free to add any setup code here (do not load anything here, override preload() instead).
  2912. *
  2913. * @method Phaser.State#create
  2914. */
  2915. create: function () {
  2916. },
  2917. /**
  2918. * Put update logic here.
  2919. *
  2920. * @method Phaser.State#update
  2921. */
  2922. update: function () {
  2923. },
  2924. /**
  2925. * Put render operations here.
  2926. *
  2927. * @method Phaser.State#render
  2928. */
  2929. render: function () {
  2930. },
  2931. /**
  2932. * This method will be called when game paused.
  2933. *
  2934. * @method Phaser.State#paused
  2935. */
  2936. paused: function () {
  2937. },
  2938. /**
  2939. * This method will be called when the state is shut down (i.e. you switch to another state from this one).
  2940. * @method Phaser.State#shutdown
  2941. */
  2942. shutdown: function () {
  2943. }
  2944. };
  2945. Phaser.State.prototype.constructor = Phaser.State;
  2946. /* jshint newcap: false */
  2947. /**
  2948. * @author Richard Davey <rich@photonstorm.com>
  2949. * @copyright 2014 Photon Storm Ltd.
  2950. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  2951. */
  2952. /**
  2953. * The State Manager is responsible for loading, setting up and switching game states.
  2954. *
  2955. * @class Phaser.StateManager
  2956. * @constructor
  2957. * @param {Phaser.Game} game - A reference to the currently running game.
  2958. * @param {Phaser.State|Object} [pendingState=null] - A State object to seed the manager with.
  2959. */
  2960. Phaser.StateManager = function (game, pendingState) {
  2961. /**
  2962. * @property {Phaser.Game} game - A reference to the currently running game.
  2963. */
  2964. this.game = game;
  2965. /**
  2966. * @property {Object} states - The object containing Phaser.States.
  2967. */
  2968. this.states = {};
  2969. /**
  2970. * @property {Phaser.State} _pendingState - The state to be switched to in the next frame.
  2971. * @private
  2972. */
  2973. this._pendingState = null;
  2974. if (typeof pendingState !== 'undefined' && pendingState !== null)
  2975. {
  2976. this._pendingState = pendingState;
  2977. }
  2978. /**
  2979. * @property {boolean} _clearWorld - Clear the world when we switch state?
  2980. * @private
  2981. */
  2982. this._clearWorld = false;
  2983. /**
  2984. * @property {boolean} _clearCache - Clear the cache when we switch state?
  2985. * @private
  2986. */
  2987. this._clearCache = false;
  2988. /**
  2989. * @property {boolean} _created - Flag that sets if the State has been created or not.
  2990. * @private
  2991. */
  2992. this._created = false;
  2993. /**
  2994. * @property {array} _args - Temporary container when you pass vars from one State to another.
  2995. * @private
  2996. */
  2997. this._args = [];
  2998. /**
  2999. * @property {string} current - The current active State object (defaults to null).
  3000. */
  3001. this.current = '';
  3002. /**
  3003. * @property {function} onInitCallback - This will be called when the state is started (i.e. set as the current active state).
  3004. */
  3005. this.onInitCallback = null;
  3006. /**
  3007. * @property {function} onPreloadCallback - This will be called when init states (loading assets...).
  3008. */
  3009. this.onPreloadCallback = null;
  3010. /**
  3011. * @property {function} onCreateCallback - This will be called when create states (setup states...).
  3012. */
  3013. this.onCreateCallback = null;
  3014. /**
  3015. * @property {function} onUpdateCallback - This will be called when State is updated, this doesn't happen during load (@see onLoadUpdateCallback).
  3016. */
  3017. this.onUpdateCallback = null;
  3018. /**
  3019. * @property {function} onRenderCallback - This will be called when the State is rendered, this doesn't happen during load (see onLoadRenderCallback).
  3020. */
  3021. this.onRenderCallback = null;
  3022. /**
  3023. * @property {function} onPreRenderCallback - This will be called before the State is rendered and before the stage is cleared.
  3024. */
  3025. this.onPreRenderCallback = null;
  3026. /**
  3027. * @property {function} onLoadUpdateCallback - This will be called when the State is updated but only during the load process.
  3028. */
  3029. this.onLoadUpdateCallback = null;
  3030. /**
  3031. * @property {function} onLoadRenderCallback - This will be called when the State is rendered but only during the load process.
  3032. */
  3033. this.onLoadRenderCallback = null;
  3034. /**
  3035. * @property {function} onPausedCallback - This will be called when the state is paused.
  3036. */
  3037. this.onPausedCallback = null;
  3038. /**
  3039. * @property {function} onResumedCallback - This will be called when the state is resumed from a paused state.
  3040. */
  3041. this.onResumedCallback = null;
  3042. /**
  3043. * @property {function} onShutDownCallback - This will be called when the state is shut down (i.e. swapped to another state).
  3044. */
  3045. this.onShutDownCallback = null;
  3046. };
  3047. Phaser.StateManager.prototype = {
  3048. /**
  3049. * The Boot handler is called by Phaser.Game when it first starts up.
  3050. * @method Phaser.StateManager#boot
  3051. * @private
  3052. */
  3053. boot: function () {
  3054. this.game.onPause.add(this.pause, this);
  3055. this.game.onResume.add(this.resume, this);
  3056. this.game.load.onLoadComplete.add(this.loadComplete, this);
  3057. if (this._pendingState !== null)
  3058. {
  3059. if (typeof this._pendingState === 'string')
  3060. {
  3061. // State was already added, so just start it
  3062. this.start(this._pendingState, false, false);
  3063. }
  3064. else
  3065. {
  3066. this.add('default', this._pendingState, true);
  3067. }
  3068. }
  3069. },
  3070. /**
  3071. * Adds a new State into the StateManager. You must give each State a unique key by which you'll identify it.
  3072. * The State can be either a Phaser.State object (or an object that extends it), a plain JavaScript object or a function.
  3073. * If a function is given a new state object will be created by calling it.
  3074. *
  3075. * @method Phaser.StateManager#add
  3076. * @param {string} key - A unique key you use to reference this state, i.e. "MainMenu", "Level1".
  3077. * @param {Phaser.State|object|function} state - The state you want to switch to.
  3078. * @param {boolean} [autoStart=false] - If true the State will be started immediately after adding it.
  3079. */
  3080. add: function (key, state, autoStart) {
  3081. if (typeof autoStart === "undefined") { autoStart = false; }
  3082. var newState;
  3083. if (state instanceof Phaser.State)
  3084. {
  3085. newState = state;
  3086. }
  3087. else if (typeof state === 'object')
  3088. {
  3089. newState = state;
  3090. newState.game = this.game;
  3091. }
  3092. else if (typeof state === 'function')
  3093. {
  3094. newState = new state(this.game);
  3095. }
  3096. this.states[key] = newState;
  3097. if (autoStart)
  3098. {
  3099. if (this.game.isBooted)
  3100. {
  3101. this.start(key);
  3102. }
  3103. else
  3104. {
  3105. this._pendingState = key;
  3106. }
  3107. }
  3108. return newState;
  3109. },
  3110. /**
  3111. * Delete the given state.
  3112. * @method Phaser.StateManager#remove
  3113. * @param {string} key - A unique key you use to reference this state, i.e. "MainMenu", "Level1".
  3114. */
  3115. remove: function (key) {
  3116. if (this.current === key)
  3117. {
  3118. this.callbackContext = null;
  3119. this.onInitCallback = null;
  3120. this.onShutDownCallback = null;
  3121. this.onPreloadCallback = null;
  3122. this.onLoadRenderCallback = null;
  3123. this.onLoadUpdateCallback = null;
  3124. this.onCreateCallback = null;
  3125. this.onUpdateCallback = null;
  3126. this.onRenderCallback = null;
  3127. this.onPausedCallback = null;
  3128. this.onResumedCallback = null;
  3129. this.onDestroyCallback = null;
  3130. }
  3131. delete this.states[key];
  3132. },
  3133. /**
  3134. * 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.
  3135. *
  3136. * @method Phaser.StateManager#start
  3137. * @param {string} key - The key of the state you want to start.
  3138. * @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)
  3139. * @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.
  3140. * @param {...*} parameter - Additional parameters that will be passed to the State.init function (if it has one).
  3141. */
  3142. start: function (key, clearWorld, clearCache) {
  3143. if (typeof clearWorld === "undefined") { clearWorld = true; }
  3144. if (typeof clearCache === "undefined") { clearCache = false; }
  3145. if (this.checkState(key))
  3146. {
  3147. // Place the state in the queue. It will be started the next time the game loop starts.
  3148. this._pendingState = key;
  3149. this._clearWorld = clearWorld;
  3150. this._clearCache = clearCache;
  3151. if (arguments.length > 3)
  3152. {
  3153. this._args = Array.prototype.splice.call(arguments, 3);
  3154. }
  3155. }
  3156. },
  3157. /**
  3158. * Restarts the current State. State.shutDown will be called (if it exists) before the State is restarted.
  3159. *
  3160. * @method Phaser.StateManager#restart
  3161. * @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)
  3162. * @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.
  3163. * @param {...*} parameter - Additional parameters that will be passed to the State.init function if it has one.
  3164. */
  3165. restart: function (clearWorld, clearCache) {
  3166. if (typeof clearWorld === "undefined") { clearWorld = true; }
  3167. if (typeof clearCache === "undefined") { clearCache = false; }
  3168. // Place the state in the queue. It will be started the next time the game loop starts.
  3169. this._pendingState = this.current;
  3170. this._clearWorld = clearWorld;
  3171. this._clearCache = clearCache;
  3172. if (arguments.length > 3)
  3173. {
  3174. this._args = Array.prototype.splice.call(arguments, 3);
  3175. }
  3176. },
  3177. /**
  3178. * Used by onInit and onShutdown when those functions don't exist on the state
  3179. * @method Phaser.StateManager#dummy
  3180. * @private
  3181. */
  3182. dummy: function () {
  3183. },
  3184. /**
  3185. * preUpdate is called right at the start of the game loop. It is responsible for changing to a new state that was requested previously.
  3186. *
  3187. * @method Phaser.StateManager#preUpdate
  3188. */
  3189. preUpdate: function () {
  3190. if (this._pendingState && this.game.isBooted)
  3191. {
  3192. // Already got a state running?
  3193. if (this.current)
  3194. {
  3195. this.onShutDownCallback.call(this.callbackContext, this.game);
  3196. this.game.tweens.removeAll();
  3197. this.game.camera.reset();
  3198. this.game.input.reset(true);
  3199. this.game.physics.clear();
  3200. this.game.time.removeAll();
  3201. if (this._clearWorld)
  3202. {
  3203. this.game.world.shutdown();
  3204. if (this._clearCache === true)
  3205. {
  3206. this.game.cache.destroy();
  3207. }
  3208. }
  3209. }
  3210. this.setCurrentState(this._pendingState);
  3211. if (this.onPreloadCallback)
  3212. {
  3213. this.game.load.reset();
  3214. this.onPreloadCallback.call(this.callbackContext, this.game);
  3215. // Is the loader empty?
  3216. if (this.game.load.totalQueuedFiles() === 0)
  3217. {
  3218. this.loadComplete();
  3219. }
  3220. else
  3221. {
  3222. // Start the loader going as we have something in the queue
  3223. this.game.load.start();
  3224. }
  3225. }
  3226. else
  3227. {
  3228. // No init? Then there was nothing to load either
  3229. this.loadComplete();
  3230. }
  3231. if (this.current === this._pendingState)
  3232. {
  3233. this._pendingState = null;
  3234. }
  3235. }
  3236. },
  3237. /**
  3238. * 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.
  3239. *
  3240. * @method Phaser.StateManager#checkState
  3241. * @param {string} key - The key of the state you want to check.
  3242. * @return {boolean} true if the State has the required functions, otherwise false.
  3243. */
  3244. checkState: function (key) {
  3245. if (this.states[key])
  3246. {
  3247. var valid = false;
  3248. if (this.states[key]['preload']) { valid = true; }
  3249. if (this.states[key]['create']) { valid = true; }
  3250. if (this.states[key]['update']) { valid = true; }
  3251. if (this.states[key]['render']) { valid = true; }
  3252. if (valid === false)
  3253. {
  3254. console.warn("Invalid Phaser State object given. Must contain at least a one of the required functions: preload, create, update or render");
  3255. return false;
  3256. }
  3257. return true;
  3258. }
  3259. else
  3260. {
  3261. console.warn("Phaser.StateManager - No state found with the key: " + key);
  3262. return false;
  3263. }
  3264. },
  3265. /**
  3266. * Links game properties to the State given by the key.
  3267. * @method Phaser.StateManager#link
  3268. * @param {string} key - State key.
  3269. * @protected
  3270. */
  3271. link: function (key) {
  3272. this.states[key].game = this.game;
  3273. this.states[key].add = this.game.add;
  3274. this.states[key].make = this.game.make;
  3275. this.states[key].camera = this.game.camera;
  3276. this.states[key].cache = this.game.cache;
  3277. this.states[key].input = this.game.input;
  3278. this.states[key].load = this.game.load;
  3279. this.states[key].math = this.game.math;
  3280. this.states[key].sound = this.game.sound;
  3281. this.states[key].scale = this.game.scale;
  3282. this.states[key].state = this;
  3283. this.states[key].stage = this.game.stage;
  3284. this.states[key].time = this.game.time;
  3285. this.states[key].tweens = this.game.tweens;
  3286. this.states[key].world = this.game.world;
  3287. this.states[key].particles = this.game.particles;
  3288. this.states[key].rnd = this.game.rnd;
  3289. this.states[key].physics = this.game.physics;
  3290. },
  3291. /**
  3292. * Sets the current State. Should not be called directly (use StateManager.start)
  3293. * @method Phaser.StateManager#setCurrentState
  3294. * @param {string} key - State key.
  3295. * @private
  3296. */
  3297. setCurrentState: function (key) {
  3298. this.callbackContext = this.states[key];
  3299. this.link(key);
  3300. // Used when the state is set as being the current active state
  3301. this.onInitCallback = this.states[key]['init'] || this.dummy;
  3302. this.onPreloadCallback = this.states[key]['preload'] || null;
  3303. this.onLoadRenderCallback = this.states[key]['loadRender'] || null;
  3304. this.onLoadUpdateCallback = this.states[key]['loadUpdate'] || null;
  3305. this.onCreateCallback = this.states[key]['create'] || null;
  3306. this.onUpdateCallback = this.states[key]['update'] || null;
  3307. this.onPreRenderCallback = this.states[key]['preRender'] || null;
  3308. this.onRenderCallback = this.states[key]['render'] || null;
  3309. this.onPausedCallback = this.states[key]['paused'] || null;
  3310. this.onResumedCallback = this.states[key]['resumed'] || null;
  3311. // Used when the state is no longer the current active state
  3312. this.onShutDownCallback = this.states[key]['shutdown'] || this.dummy;
  3313. this.current = key;
  3314. this._created = false;
  3315. this.onInitCallback.apply(this.callbackContext, this._args);
  3316. this._args = [];
  3317. },
  3318. /**
  3319. * Gets the current State.
  3320. *
  3321. * @method Phaser.StateManager#getCurrentState
  3322. * @return Phaser.State
  3323. * @public
  3324. */
  3325. getCurrentState: function() {
  3326. return this.states[this.current];
  3327. },
  3328. /**
  3329. * @method Phaser.StateManager#loadComplete
  3330. * @protected
  3331. */
  3332. loadComplete: function () {
  3333. if (this._created === false && this.onCreateCallback)
  3334. {
  3335. this._created = true;
  3336. this.onCreateCallback.call(this.callbackContext, this.game);
  3337. }
  3338. else
  3339. {
  3340. this._created = true;
  3341. }
  3342. },
  3343. /**
  3344. * @method Phaser.StateManager#pause
  3345. * @protected
  3346. */
  3347. pause: function () {
  3348. if (this._created && this.onPausedCallback)
  3349. {
  3350. this.onPausedCallback.call(this.callbackContext, this.game);
  3351. }
  3352. },
  3353. /**
  3354. * @method Phaser.StateManager#resume
  3355. * @protected
  3356. */
  3357. resume: function () {
  3358. if (this._created && this.onResumedCallback)
  3359. {
  3360. this.onResumedCallback.call(this.callbackContext, this.game);
  3361. }
  3362. },
  3363. /**
  3364. * @method Phaser.StateManager#update
  3365. * @protected
  3366. */
  3367. update: function () {
  3368. if (this._created && this.onUpdateCallback)
  3369. {
  3370. this.onUpdateCallback.call(this.callbackContext, this.game);
  3371. }
  3372. else
  3373. {
  3374. if (this.onLoadUpdateCallback)
  3375. {
  3376. this.onLoadUpdateCallback.call(this.callbackContext, this.game);
  3377. }
  3378. }
  3379. },
  3380. /**
  3381. * @method Phaser.StateManager#preRender
  3382. * @protected
  3383. */
  3384. preRender: function () {
  3385. if (this.onPreRenderCallback)
  3386. {
  3387. this.onPreRenderCallback.call(this.callbackContext, this.game);
  3388. }
  3389. },
  3390. /**
  3391. * @method Phaser.StateManager#render
  3392. * @protected
  3393. */
  3394. render: function () {
  3395. if (this._created && this.onRenderCallback)
  3396. {
  3397. if (this.game.renderType === Phaser.CANVAS)
  3398. {
  3399. this.game.context.save();
  3400. this.game.context.setTransform(1, 0, 0, 1, 0, 0);
  3401. }
  3402. this.onRenderCallback.call(this.callbackContext, this.game);
  3403. if (this.game.renderType === Phaser.CANVAS)
  3404. {
  3405. this.game.context.restore();
  3406. }
  3407. }
  3408. else
  3409. {
  3410. if (this.onLoadRenderCallback)
  3411. {
  3412. this.onLoadRenderCallback.call(this.callbackContext, this.game);
  3413. }
  3414. }
  3415. },
  3416. /**
  3417. * Removes all StateManager callback references to the State object, nulls the game reference and clears the States object.
  3418. * You don't recover from this without rebuilding the Phaser instance again.
  3419. * @method Phaser.StateManager#destroy
  3420. */
  3421. destroy: function () {
  3422. this.callbackContext = null;
  3423. this.onInitCallback = null;
  3424. this.onShutDownCallback = null;
  3425. this.onPreloadCallback = null;
  3426. this.onLoadRenderCallback = null;
  3427. this.onLoadUpdateCallback = null;
  3428. this.onCreateCallback = null;
  3429. this.onUpdateCallback = null;
  3430. this.onRenderCallback = null;
  3431. this.onPausedCallback = null;
  3432. this.onResumedCallback = null;
  3433. this.onDestroyCallback = null;
  3434. this.game = null;
  3435. this.states = {};
  3436. this._pendingState = null;
  3437. }
  3438. };
  3439. Phaser.StateManager.prototype.constructor = Phaser.StateManager;
  3440. /**
  3441. * @author Richard Davey <rich@photonstorm.com>
  3442. * @copyright 2014 Photon Storm Ltd.
  3443. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  3444. */
  3445. /**
  3446. * A basic linked list data structure.
  3447. *
  3448. * @class Phaser.LinkedList
  3449. * @constructor
  3450. */
  3451. Phaser.LinkedList = function () {
  3452. /**
  3453. * @property {object} next - Next element in the list.
  3454. * @default
  3455. */
  3456. this.next = null;
  3457. /**
  3458. * @property {object} prev - Previous element in the list.
  3459. * @default
  3460. */
  3461. this.prev = null;
  3462. /**
  3463. * @property {object} first - First element in the list.
  3464. * @default
  3465. */
  3466. this.first = null;
  3467. /**
  3468. * @property {object} last - Last element in the list.
  3469. * @default
  3470. */
  3471. this.last = null;
  3472. /**
  3473. * @property {object} game - Number of elements in the list.
  3474. * @default
  3475. */
  3476. this.total = 0;
  3477. };
  3478. Phaser.LinkedList.prototype = {
  3479. /**
  3480. * Adds a new element to this linked list.
  3481. *
  3482. * @method Phaser.LinkedList#add
  3483. * @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.
  3484. * @return {object} The child that was added.
  3485. */
  3486. add: function (child) {
  3487. // If the list is empty
  3488. if (this.total === 0 && this.first == null && this.last == null)
  3489. {
  3490. this.first = child;
  3491. this.last = child;
  3492. this.next = child;
  3493. child.prev = this;
  3494. this.total++;
  3495. return child;
  3496. }
  3497. // 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)
  3498. this.last.next = child;
  3499. child.prev = this.last;
  3500. this.last = child;
  3501. this.total++;
  3502. return child;
  3503. },
  3504. /**
  3505. * Removes the given element from this linked list if it exists.
  3506. *
  3507. * @method Phaser.LinkedList#remove
  3508. * @param {object} child - The child to be removed from the list.
  3509. */
  3510. remove: function (child) {
  3511. if (child == this.first)
  3512. {
  3513. // It was 'first', make 'first' point to first.next
  3514. this.first = this.first.next;
  3515. }
  3516. else if (child == this.last)
  3517. {
  3518. // It was 'last', make 'last' point to last.prev
  3519. this.last = this.last.prev;
  3520. }
  3521. if (child.prev)
  3522. {
  3523. // make child.prev.next point to childs.next instead of child
  3524. child.prev.next = child.next;
  3525. }
  3526. if (child.next)
  3527. {
  3528. // make child.next.prev point to child.prev instead of child
  3529. child.next.prev = child.prev;
  3530. }
  3531. child.next = child.prev = null;
  3532. if (this.first == null )
  3533. {
  3534. this.last = null;
  3535. }
  3536. this.total--;
  3537. },
  3538. /**
  3539. * Calls a function on all members of this list, using the member as the context for the callback.
  3540. * The function must exist on the member.
  3541. *
  3542. * @method Phaser.LinkedList#callAll
  3543. * @param {function} callback - The function to call.
  3544. */
  3545. callAll: function (callback) {
  3546. if (!this.first || !this.last)
  3547. {
  3548. return;
  3549. }
  3550. var entity = this.first;
  3551. do
  3552. {
  3553. if (entity && entity[callback])
  3554. {
  3555. entity[callback].call(entity);
  3556. }
  3557. entity = entity.next;
  3558. }
  3559. while(entity != this.last.next);
  3560. }
  3561. };
  3562. Phaser.LinkedList.prototype.constructor = Phaser.LinkedList;
  3563. /**
  3564. * @author Richard Davey <rich@photonstorm.com>
  3565. * @copyright 2014 Photon Storm Ltd.
  3566. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  3567. */
  3568. /**
  3569. * @class Phaser.Signal
  3570. * @classdesc A Signal is used for object communication via a custom broadcaster instead of Events.
  3571. * @author Miller Medeiros http://millermedeiros.github.com/js-signals/
  3572. * @constructor
  3573. */
  3574. Phaser.Signal = function () {
  3575. /**
  3576. * @property {Array.<Phaser.SignalBinding>} _bindings - Internal variable.
  3577. * @private
  3578. */
  3579. this._bindings = [];
  3580. /**
  3581. * @property {any} _prevParams - Internal variable.
  3582. * @private
  3583. */
  3584. this._prevParams = null;
  3585. // enforce dispatch to aways work on same context (#47)
  3586. var self = this;
  3587. /**
  3588. * @property {function} dispatch - The dispatch function is what sends the Signal out.
  3589. */
  3590. this.dispatch = function(){
  3591. Phaser.Signal.prototype.dispatch.apply(self, arguments);
  3592. };
  3593. };
  3594. Phaser.Signal.prototype = {
  3595. /**
  3596. * If Signal should keep record of previously dispatched parameters and
  3597. * automatically execute listener during `add()`/`addOnce()` if Signal was
  3598. * already dispatched before.
  3599. * @property {boolean} memorize
  3600. */
  3601. memorize: false,
  3602. /**
  3603. * @property {boolean} _shouldPropagate
  3604. * @private
  3605. */
  3606. _shouldPropagate: true,
  3607. /**
  3608. * If Signal is active and should broadcast events.
  3609. * <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>
  3610. * @property {boolean} active
  3611. * @default
  3612. */
  3613. active: true,
  3614. /**
  3615. * @method Phaser.Signal#validateListener
  3616. * @param {function} listener - Signal handler function.
  3617. * @param {string} fnName - Function name.
  3618. * @private
  3619. */
  3620. validateListener: function (listener, fnName) {
  3621. if (typeof listener !== 'function') {
  3622. throw new Error('listener is a required param of {fn}() and should be a Function.'.replace('{fn}', fnName));
  3623. }
  3624. },
  3625. /**
  3626. * @method Phaser.Signal#_registerListener
  3627. * @param {function} listener - Signal handler function.
  3628. * @param {boolean} isOnce - Description.
  3629. * @param {object} [listenerContext] - Description.
  3630. * @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).
  3631. * @return {Phaser.SignalBinding} An Object representing the binding between the Signal and listener.
  3632. * @private
  3633. */
  3634. _registerListener: function (listener, isOnce, listenerContext, priority) {
  3635. var prevIndex = this._indexOfListener(listener, listenerContext),
  3636. binding;
  3637. if (prevIndex !== -1) {
  3638. binding = this._bindings[prevIndex];
  3639. if (binding.isOnce() !== isOnce) {
  3640. throw new Error('You cannot add' + (isOnce ? '' : 'Once') + '() then add' + (!isOnce ? '' : 'Once') + '() the same listener without removing the relationship first.');
  3641. }
  3642. } else {
  3643. binding = new Phaser.SignalBinding(this, listener, isOnce, listenerContext, priority);
  3644. this._addBinding(binding);
  3645. }
  3646. if (this.memorize && this._prevParams) {
  3647. binding.execute(this._prevParams);
  3648. }
  3649. return binding;
  3650. },
  3651. /**
  3652. * @method Phaser.Signal#_addBinding
  3653. * @param {Phaser.SignalBinding} binding - An Object representing the binding between the Signal and listener.
  3654. * @private
  3655. */
  3656. _addBinding: function (binding) {
  3657. //simplified insertion sort
  3658. var n = this._bindings.length;
  3659. do { --n; } while (this._bindings[n] && binding._priority <= this._bindings[n]._priority);
  3660. this._bindings.splice(n + 1, 0, binding);
  3661. },
  3662. /**
  3663. * @method Phaser.Signal#_indexOfListener
  3664. * @param {function} listener - Signal handler function.
  3665. * @return {number} Description.
  3666. * @private
  3667. */
  3668. _indexOfListener: function (listener, context) {
  3669. var n = this._bindings.length,
  3670. cur;
  3671. while (n--) {
  3672. cur = this._bindings[n];
  3673. if (cur._listener === listener && cur.context === context) {
  3674. return n;
  3675. }
  3676. }
  3677. return -1;
  3678. },
  3679. /**
  3680. * Check if listener was attached to Signal.
  3681. *
  3682. * @method Phaser.Signal#has
  3683. * @param {Function} listener - Signal handler function.
  3684. * @param {Object} [context] - Context on which listener will be executed (object that should represent the `this` variable inside listener function).
  3685. * @return {boolean} If Signal has the specified listener.
  3686. */
  3687. has: function (listener, context) {
  3688. return this._indexOfListener(listener, context) !== -1;
  3689. },
  3690. /**
  3691. * Add a listener to the signal.
  3692. *
  3693. * @method Phaser.Signal#add
  3694. * @param {function} listener - Signal handler function.
  3695. * @param {object} [listenerContext] Context on which listener will be executed (object that should represent the `this` variable inside listener function).
  3696. * @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).
  3697. * @return {Phaser.SignalBinding} An Object representing the binding between the Signal and listener.
  3698. */
  3699. add: function (listener, listenerContext, priority) {
  3700. this.validateListener(listener, 'add');
  3701. return this._registerListener(listener, false, listenerContext, priority);
  3702. },
  3703. /**
  3704. * Add listener to the signal that should be removed after first execution (will be executed only once).
  3705. *
  3706. * @method Phaser.Signal#addOnce
  3707. * @param {function} listener Signal handler function.
  3708. * @param {object} [listenerContext] Context on which listener will be executed (object that should represent the `this` variable inside listener function).
  3709. * @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)
  3710. * @return {Phaser.SignalBinding} An Object representing the binding between the Signal and listener.
  3711. */
  3712. addOnce: function (listener, listenerContext, priority) {
  3713. this.validateListener(listener, 'addOnce');
  3714. return this._registerListener(listener, true, listenerContext, priority);
  3715. },
  3716. /**
  3717. * Remove a single listener from the dispatch queue.
  3718. *
  3719. * @method Phaser.Signal#remove
  3720. * @param {function} listener Handler function that should be removed.
  3721. * @param {object} [context] Execution context (since you can add the same handler multiple times if executing in a different context).
  3722. * @return {function} Listener handler function.
  3723. */
  3724. remove: function (listener, context) {
  3725. this.validateListener(listener, 'remove');
  3726. var i = this._indexOfListener(listener, context);
  3727. if (i !== -1)
  3728. {
  3729. this._bindings[i]._destroy(); //no reason to a Phaser.SignalBinding exist if it isn't attached to a signal
  3730. this._bindings.splice(i, 1);
  3731. }
  3732. return listener;
  3733. },
  3734. /**
  3735. * Remove all listeners from the Signal.
  3736. *
  3737. * @method Phaser.Signal#removeAll
  3738. */
  3739. removeAll: function () {
  3740. var n = this._bindings.length;
  3741. while (n--) {
  3742. this._bindings[n]._destroy();
  3743. }
  3744. this._bindings.length = 0;
  3745. },
  3746. /**
  3747. * Gets the total number of listeneres attached to ths Signal.
  3748. *
  3749. * @method Phaser.Signal#getNumListeners
  3750. * @return {number} Number of listeners attached to the Signal.
  3751. */
  3752. getNumListeners: function () {
  3753. return this._bindings.length;
  3754. },
  3755. /**
  3756. * Stop propagation of the event, blocking the dispatch to next listeners on the queue.
  3757. * IMPORTANT: should be called only during signal dispatch, calling it before/after dispatch won't affect signal broadcast.
  3758. * @see Signal.prototype.disable
  3759. *
  3760. * @method Phaser.Signal#halt
  3761. */
  3762. halt: function () {
  3763. this._shouldPropagate = false;
  3764. },
  3765. /**
  3766. * Dispatch/Broadcast Signal to all listeners added to the queue.
  3767. *
  3768. * @method Phaser.Signal#dispatch
  3769. * @param {any} [params] - Parameters that should be passed to each handler.
  3770. */
  3771. dispatch: function () {
  3772. if (!this.active)
  3773. {
  3774. return;
  3775. }
  3776. var paramsArr = Array.prototype.slice.call(arguments);
  3777. var n = this._bindings.length;
  3778. var bindings;
  3779. if (this.memorize)
  3780. {
  3781. this._prevParams = paramsArr;
  3782. }
  3783. if (!n)
  3784. {
  3785. // Should come after memorize
  3786. return;
  3787. }
  3788. bindings = this._bindings.slice(); //clone array in case add/remove items during dispatch
  3789. this._shouldPropagate = true; //in case `halt` was called before dispatch or during the previous dispatch.
  3790. //execute all callbacks until end of the list or until a callback returns `false` or stops propagation
  3791. //reverse loop since listeners with higher priority will be added at the end of the list
  3792. do { n--; } while (bindings[n] && this._shouldPropagate && bindings[n].execute(paramsArr) !== false);
  3793. },
  3794. /**
  3795. * Forget memorized arguments.
  3796. * @see Signal.memorize
  3797. *
  3798. * @method Phaser.Signal#forget
  3799. */
  3800. forget: function(){
  3801. this._prevParams = null;
  3802. },
  3803. /**
  3804. * Remove all bindings from signal and destroy any reference to external objects (destroy Signal object).
  3805. * IMPORTANT: calling any method on the signal instance after calling dispose will throw errors.
  3806. *
  3807. * @method Phaser.Signal#dispose
  3808. */
  3809. dispose: function () {
  3810. this.removeAll();
  3811. delete this._bindings;
  3812. delete this._prevParams;
  3813. },
  3814. /**
  3815. *
  3816. * @method Phaser.Signal#toString
  3817. * @return {string} String representation of the object.
  3818. */
  3819. toString: function () {
  3820. return '[Phaser.Signal active:'+ this.active +' numListeners:'+ this.getNumListeners() +']';
  3821. }
  3822. };
  3823. Phaser.Signal.prototype.constructor = Phaser.Signal;
  3824. /**
  3825. * @author Richard Davey <rich@photonstorm.com>
  3826. * @copyright 2014 Photon Storm Ltd.
  3827. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  3828. */
  3829. /**
  3830. * @class Phaser.SignalBinding
  3831. * @classdesc Object that represents a binding between a Signal and a listener function.
  3832. * This is an internal constructor and shouldn't be called by regular users.
  3833. * Inspired by Joa Ebert AS3 SignalBinding and Robert Penner's Slot classes.
  3834. *
  3835. * @author Miller Medeiros http://millermedeiros.github.com/js-signals/
  3836. * @constructor
  3837. * @param {Phaser.Signal} signal - Reference to Signal object that listener is currently bound to.
  3838. * @param {function} listener - Handler function bound to the signal.
  3839. * @param {boolean} isOnce - If binding should be executed just once.
  3840. * @param {object} [listenerContext] - Context on which listener will be executed (object that should represent the `this` variable inside listener function).
  3841. * @param {number} [priority] - The priority level of the event listener. (default = 0).
  3842. */
  3843. Phaser.SignalBinding = function (signal, listener, isOnce, listenerContext, priority) {
  3844. /**
  3845. * @property {Phaser.Game} _listener - Handler function bound to the signal.
  3846. * @private
  3847. */
  3848. this._listener = listener;
  3849. /**
  3850. * @property {boolean} _isOnce - If binding should be executed just once.
  3851. * @private
  3852. */
  3853. this._isOnce = isOnce;
  3854. /**
  3855. * @property {object|undefined|null} context - Context on which listener will be executed (object that should represent the `this` variable inside listener function).
  3856. */
  3857. this.context = listenerContext;
  3858. /**
  3859. * @property {Phaser.Signal} _signal - Reference to Signal object that listener is currently bound to.
  3860. * @private
  3861. */
  3862. this._signal = signal;
  3863. /**
  3864. * @property {number} _priority - Listener priority.
  3865. * @private
  3866. */
  3867. this._priority = priority || 0;
  3868. };
  3869. Phaser.SignalBinding.prototype = {
  3870. /**
  3871. * If binding is active and should be executed.
  3872. * @property {boolean} active
  3873. * @default
  3874. */
  3875. active: true,
  3876. /**
  3877. * Default parameters passed to listener during `Signal.dispatch` and `SignalBinding.execute` (curried parameters).
  3878. * @property {array|null} params
  3879. * @default
  3880. */
  3881. params: null,
  3882. /**
  3883. * Call listener passing arbitrary parameters.
  3884. * 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.
  3885. * @method Phaser.SignalBinding#execute
  3886. * @param {array} [paramsArr] - Array of parameters that should be passed to the listener.
  3887. * @return {any} Value returned by the listener.
  3888. */
  3889. execute: function(paramsArr) {
  3890. var handlerReturn, params;
  3891. if (this.active && !!this._listener)
  3892. {
  3893. params = this.params ? this.params.concat(paramsArr) : paramsArr;
  3894. handlerReturn = this._listener.apply(this.context, params);
  3895. if (this._isOnce)
  3896. {
  3897. this.detach();
  3898. }
  3899. }
  3900. return handlerReturn;
  3901. },
  3902. /**
  3903. * Detach binding from signal.
  3904. * alias to: @see mySignal.remove(myBinding.getListener());
  3905. * @method Phaser.SignalBinding#detach
  3906. * @return {function|null} Handler function bound to the signal or `null` if binding was previously detached.
  3907. */
  3908. detach: function () {
  3909. return this.isBound() ? this._signal.remove(this._listener, this.context) : null;
  3910. },
  3911. /**
  3912. * @method Phaser.SignalBinding#isBound
  3913. * @return {boolean} True if binding is still bound to the signal and has a listener.
  3914. */
  3915. isBound: function () {
  3916. return (!!this._signal && !!this._listener);
  3917. },
  3918. /**
  3919. * @method Phaser.SignalBinding#isOnce
  3920. * @return {boolean} If SignalBinding will only be executed once.
  3921. */
  3922. isOnce: function () {
  3923. return this._isOnce;
  3924. },
  3925. /**
  3926. * @method Phaser.SignalBinding#getListener
  3927. * @return {Function} Handler function bound to the signal.
  3928. */
  3929. getListener: function () {
  3930. return this._listener;
  3931. },
  3932. /**
  3933. * @method Phaser.SignalBinding#getSignal
  3934. * @return {Signal} Signal that listener is currently bound to.
  3935. */
  3936. getSignal: function () {
  3937. return this._signal;
  3938. },
  3939. /**
  3940. * @method Phaser.SignalBinding#_destroy
  3941. * Delete instance properties
  3942. * @private
  3943. */
  3944. _destroy: function () {
  3945. delete this._signal;
  3946. delete this._listener;
  3947. delete this.context;
  3948. },
  3949. /**
  3950. * @method Phaser.SignalBinding#toString
  3951. * @return {string} String representation of the object.
  3952. */
  3953. toString: function () {
  3954. return '[Phaser.SignalBinding isOnce:' + this._isOnce +', isBound:'+ this.isBound() +', active:' + this.active + ']';
  3955. }
  3956. };
  3957. Phaser.SignalBinding.prototype.constructor = Phaser.SignalBinding;
  3958. /**
  3959. * @author Richard Davey <rich@photonstorm.com>
  3960. * @copyright 2014 Photon Storm Ltd.
  3961. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  3962. */
  3963. /**
  3964. * This is a base Filter template to use for any Phaser filter development.
  3965. *
  3966. * @class Phaser.Filter
  3967. * @classdesc Phaser - Filter
  3968. * @constructor
  3969. * @param {Phaser.Game} game - A reference to the currently running game.
  3970. * @param {Object} uniforms - Uniform mappings object
  3971. * @param {Array} fragmentSrc - The fragment shader code.
  3972. */
  3973. Phaser.Filter = function (game, uniforms, fragmentSrc) {
  3974. /**
  3975. * @property {Phaser.Game} game - A reference to the currently running game.
  3976. */
  3977. this.game = game;
  3978. /**
  3979. * @property {number} type - The const type of this object, either Phaser.WEBGL_FILTER or Phaser.CANVAS_FILTER.
  3980. * @default
  3981. */
  3982. this.type = Phaser.WEBGL_FILTER;
  3983. /**
  3984. * An array of passes - some filters contain a few steps this array simply stores the steps in a linear fashion.
  3985. * For example the blur filter has two passes blurX and blurY.
  3986. * @property {array} passes - An array of filter objects.
  3987. * @private
  3988. */
  3989. this.passes = [this];
  3990. /**
  3991. * @property {array} shaders - Array an array of shaders.
  3992. * @private
  3993. */
  3994. this.shaders = [];
  3995. /**
  3996. * @property {boolean} dirty - Internal PIXI var.
  3997. * @default
  3998. */
  3999. this.dirty = true;
  4000. /**
  4001. * @property {number} padding - Internal PIXI var.
  4002. * @default
  4003. */
  4004. this.padding = 0;
  4005. /**
  4006. * @property {object} uniforms - Default uniform mappings.
  4007. */
  4008. this.uniforms = {
  4009. time: { type: '1f', value: 0 },
  4010. resolution: { type: '2f', value: { x: 256, y: 256 }},
  4011. mouse: { type: '2f', value: { x: 0.0, y: 0.0 }}
  4012. };
  4013. /**
  4014. * @property {array} fragmentSrc - The fragment shader code.
  4015. */
  4016. this.fragmentSrc = fragmentSrc || [];
  4017. };
  4018. Phaser.Filter.prototype = {
  4019. /**
  4020. * Should be over-ridden.
  4021. * @method Phaser.Filter#init
  4022. */
  4023. init: function () {
  4024. // This should be over-ridden. Will receive a variable number of arguments.
  4025. },
  4026. /**
  4027. * Set the resolution uniforms on the filter.
  4028. * @method Phaser.Filter#setResolution
  4029. * @param {number} width - The width of the display.
  4030. * @param {number} height - The height of the display.
  4031. */
  4032. setResolution: function (width, height) {
  4033. this.uniforms.resolution.value.x = width;
  4034. this.uniforms.resolution.value.y = height;
  4035. },
  4036. /**
  4037. * Updates the filter.
  4038. * @method Phaser.Filter#update
  4039. * @param {Phaser.Pointer} [pointer] - A Pointer object to use for the filter. The coordinates are mapped to the mouse uniform.
  4040. */
  4041. update: function (pointer) {
  4042. if (typeof pointer !== 'undefined')
  4043. {
  4044. if (pointer.x > 0)
  4045. {
  4046. this.uniforms.mouse.x = pointer.x.toFixed(2);
  4047. }
  4048. if (pointer.y > 0)
  4049. {
  4050. this.uniforms.mouse.y = pointer.y.toFixed(2);
  4051. }
  4052. }
  4053. this.uniforms.time.value = this.game.time.totalElapsedSeconds();
  4054. },
  4055. /**
  4056. * Clear down this Filter and null out references
  4057. * @method Phaser.Filter#destroy
  4058. */
  4059. destroy: function () {
  4060. this.game = null;
  4061. }
  4062. };
  4063. Phaser.Filter.prototype.constructor = Phaser.Filter;
  4064. /**
  4065. * @name Phaser.Filter#width
  4066. * @property {number} width - The width (resolution uniform)
  4067. */
  4068. Object.defineProperty(Phaser.Filter.prototype, 'width', {
  4069. get: function() {
  4070. return this.uniforms.resolution.value.x;
  4071. },
  4072. set: function(value) {
  4073. this.uniforms.resolution.value.x = value;
  4074. }
  4075. });
  4076. /**
  4077. * @name Phaser.Filter#height
  4078. * @property {number} height - The height (resolution uniform)
  4079. */
  4080. Object.defineProperty(Phaser.Filter.prototype, 'height', {
  4081. get: function() {
  4082. return this.uniforms.resolution.value.y;
  4083. },
  4084. set: function(value) {
  4085. this.uniforms.resolution.value.y = value;
  4086. }
  4087. });
  4088. /**
  4089. * @author Richard Davey <rich@photonstorm.com>
  4090. * @copyright 2014 Photon Storm Ltd.
  4091. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  4092. */
  4093. /**
  4094. * This is a base Plugin template to use for any Phaser plugin development.
  4095. *
  4096. * @class Phaser.Plugin
  4097. * @classdesc Phaser - Plugin
  4098. * @constructor
  4099. * @param {Phaser.Game} game - A reference to the currently running game.
  4100. * @param {Any} parent - The object that owns this plugin, usually Phaser.PluginManager.
  4101. */
  4102. Phaser.Plugin = function (game, parent) {
  4103. if (typeof parent === 'undefined') { parent = null; }
  4104. /**
  4105. * @property {Phaser.Game} game - A reference to the currently running game.
  4106. */
  4107. this.game = game;
  4108. /**
  4109. * @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.
  4110. */
  4111. this.parent = parent;
  4112. /**
  4113. * @property {boolean} active - A Plugin with active=true has its preUpdate and update methods called by the parent, otherwise they are skipped.
  4114. * @default
  4115. */
  4116. this.active = false;
  4117. /**
  4118. * @property {boolean} visible - A Plugin with visible=true has its render and postRender methods called by the parent, otherwise they are skipped.
  4119. * @default
  4120. */
  4121. this.visible = false;
  4122. /**
  4123. * @property {boolean} hasPreUpdate - A flag to indicate if this plugin has a preUpdate method.
  4124. * @default
  4125. */
  4126. this.hasPreUpdate = false;
  4127. /**
  4128. * @property {boolean} hasUpdate - A flag to indicate if this plugin has an update method.
  4129. * @default
  4130. */
  4131. this.hasUpdate = false;
  4132. /**
  4133. * @property {boolean} hasPostUpdate - A flag to indicate if this plugin has a postUpdate method.
  4134. * @default
  4135. */
  4136. this.hasPostUpdate = false;
  4137. /**
  4138. * @property {boolean} hasRender - A flag to indicate if this plugin has a render method.
  4139. * @default
  4140. */
  4141. this.hasRender = false;
  4142. /**
  4143. * @property {boolean} hasPostRender - A flag to indicate if this plugin has a postRender method.
  4144. * @default
  4145. */
  4146. this.hasPostRender = false;
  4147. };
  4148. Phaser.Plugin.prototype = {
  4149. /**
  4150. * Pre-update is called at the very start of the update cycle, before any other subsystems have been updated (including Physics).
  4151. * It is only called if active is set to true.
  4152. * @method Phaser.Plugin#preUpdate
  4153. */
  4154. preUpdate: function () {
  4155. },
  4156. /**
  4157. * Update is called after all the core subsystems (Input, Tweens, Sound, etc) and the State have updated, but before the render.
  4158. * It is only called if active is set to true.
  4159. * @method Phaser.Plugin#update
  4160. */
  4161. update: function () {
  4162. },
  4163. /**
  4164. * Render is called right after the Game Renderer completes, but before the State.render.
  4165. * It is only called if visible is set to true.
  4166. * @method Phaser.Plugin#render
  4167. */
  4168. render: function () {
  4169. },
  4170. /**
  4171. * Post-render is called after the Game Renderer and State.render have run.
  4172. * It is only called if visible is set to true.
  4173. * @method Phaser.Plugin#postRender
  4174. */
  4175. postRender: function () {
  4176. },
  4177. /**
  4178. * Clear down this Plugin and null out references
  4179. * @method Phaser.Plugin#destroy
  4180. */
  4181. destroy: function () {
  4182. this.game = null;
  4183. this.parent = null;
  4184. this.active = false;
  4185. this.visible = false;
  4186. }
  4187. };
  4188. Phaser.Plugin.prototype.constructor = Phaser.Plugin;
  4189. /* jshint newcap: false */
  4190. /**
  4191. * @author Richard Davey <rich@photonstorm.com>
  4192. * @copyright 2014 Photon Storm Ltd.
  4193. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  4194. */
  4195. /**
  4196. * The Plugin Manager is responsible for the loading, running and unloading of Phaser Plugins.
  4197. *
  4198. * @class Phaser.PluginManager
  4199. * @classdesc Phaser - PluginManager
  4200. * @constructor
  4201. * @param {Phaser.Game} game - A reference to the currently running game.
  4202. */
  4203. Phaser.PluginManager = function(game) {
  4204. /**
  4205. * @property {Phaser.Game} game - A reference to the currently running game.
  4206. */
  4207. this.game = game;
  4208. /**
  4209. * @property {array} plugins - An array of all the plugins being managed by this PluginManager.
  4210. */
  4211. this.plugins = [];
  4212. /**
  4213. * @property {number} _len - Internal cache var.
  4214. * @private
  4215. */
  4216. this._len = 0;
  4217. /**
  4218. * @property {number} _i - Internal cache var.
  4219. * @private
  4220. */
  4221. this._i = 0;
  4222. };
  4223. Phaser.PluginManager.prototype = {
  4224. /**
  4225. * Add a new Plugin into the PluginManager.
  4226. * 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.
  4227. *
  4228. * @method Phaser.PluginManager#add
  4229. * @param {object|Phaser.Plugin} plugin - The Plugin to add into the PluginManager. This can be a function or an existing object.
  4230. * @return {Phaser.Plugin} The Plugin that was added to the manager.
  4231. */
  4232. add: function (plugin) {
  4233. var result = false;
  4234. // Prototype?
  4235. if (typeof plugin === 'function')
  4236. {
  4237. plugin = new plugin(this.game, this._parent);
  4238. }
  4239. else
  4240. {
  4241. plugin.game = this.game;
  4242. plugin.parent = this;
  4243. }
  4244. // Check for methods now to avoid having to do this every loop
  4245. if (typeof plugin['preUpdate'] === 'function')
  4246. {
  4247. plugin.hasPreUpdate = true;
  4248. result = true;
  4249. }
  4250. if (typeof plugin['update'] === 'function')
  4251. {
  4252. plugin.hasUpdate = true;
  4253. result = true;
  4254. }
  4255. if (typeof plugin['postUpdate'] === 'function')
  4256. {
  4257. plugin.hasPostUpdate = true;
  4258. result = true;
  4259. }
  4260. if (typeof plugin['render'] === 'function')
  4261. {
  4262. plugin.hasRender = true;
  4263. result = true;
  4264. }
  4265. if (typeof plugin['postRender'] === 'function')
  4266. {
  4267. plugin.hasPostRender = true;
  4268. result = true;
  4269. }
  4270. // The plugin must have at least one of the above functions to be added to the PluginManager.
  4271. if (result)
  4272. {
  4273. if (plugin.hasPreUpdate || plugin.hasUpdate || plugin.hasPostUpdate)
  4274. {
  4275. plugin.active = true;
  4276. }
  4277. if (plugin.hasRender || plugin.hasPostRender)
  4278. {
  4279. plugin.visible = true;
  4280. }
  4281. this._len = this.plugins.push(plugin);
  4282. // Allows plugins to run potentially destructive code outside of the constructor, and only if being added to the PluginManager
  4283. if (typeof plugin['init'] === 'function')
  4284. {
  4285. plugin.init();
  4286. }
  4287. return plugin;
  4288. }
  4289. else
  4290. {
  4291. return null;
  4292. }
  4293. },
  4294. /**
  4295. * Remove a Plugin from the PluginManager. It calls Plugin.destroy on the plugin before removing it from the manager.
  4296. *
  4297. * @method Phaser.PluginManager#remove
  4298. * @param {Phaser.Plugin} plugin - The plugin to be removed.
  4299. */
  4300. remove: function (plugin) {
  4301. this._i = this._len;
  4302. while (this._i--)
  4303. {
  4304. if (this.plugins[this._i] === plugin)
  4305. {
  4306. plugin.destroy();
  4307. this.plugins.splice(this._i, 1);
  4308. this._len--;
  4309. return;
  4310. }
  4311. }
  4312. },
  4313. /**
  4314. * Remove all Plugins from the PluginManager. It calls Plugin.destroy on every plugin before removing it from the manager.
  4315. *
  4316. * @method Phaser.PluginManager#removeAll
  4317. */
  4318. removeAll: function() {
  4319. this._i = this._len;
  4320. while (this._i--)
  4321. {
  4322. this.plugins[this._i].destroy();
  4323. }
  4324. this.plugins.length = 0;
  4325. this._len = 0;
  4326. },
  4327. /**
  4328. * Pre-update is called at the very start of the update cycle, before any other subsystems have been updated (including Physics).
  4329. * It only calls plugins who have active=true.
  4330. *
  4331. * @method Phaser.PluginManager#preUpdate
  4332. */
  4333. preUpdate: function () {
  4334. this._i = this._len;
  4335. while (this._i--)
  4336. {
  4337. if (this.plugins[this._i].active && this.plugins[this._i].hasPreUpdate)
  4338. {
  4339. this.plugins[this._i].preUpdate();
  4340. }
  4341. }
  4342. },
  4343. /**
  4344. * Update is called after all the core subsystems (Input, Tweens, Sound, etc) and the State have updated, but before the render.
  4345. * It only calls plugins who have active=true.
  4346. *
  4347. * @method Phaser.PluginManager#update
  4348. */
  4349. update: function () {
  4350. this._i = this._len;
  4351. while (this._i--)
  4352. {
  4353. if (this.plugins[this._i].active && this.plugins[this._i].hasUpdate)
  4354. {
  4355. this.plugins[this._i].update();
  4356. }
  4357. }
  4358. },
  4359. /**
  4360. * PostUpdate is the last thing to be called before the world render.
  4361. * In particular, it is called after the world postUpdate, which means the camera has been adjusted.
  4362. * It only calls plugins who have active=true.
  4363. *
  4364. * @method Phaser.PluginManager#postUpdate
  4365. */
  4366. postUpdate: function () {
  4367. this._i = this._len;
  4368. while (this._i--)
  4369. {
  4370. if (this.plugins[this._i].active && this.plugins[this._i].hasPostUpdate)
  4371. {
  4372. this.plugins[this._i].postUpdate();
  4373. }
  4374. }
  4375. },
  4376. /**
  4377. * Render is called right after the Game Renderer completes, but before the State.render.
  4378. * It only calls plugins who have visible=true.
  4379. *
  4380. * @method Phaser.PluginManager#render
  4381. */
  4382. render: function () {
  4383. this._i = this._len;
  4384. while (this._i--)
  4385. {
  4386. if (this.plugins[this._i].visible && this.plugins[this._i].hasRender)
  4387. {
  4388. this.plugins[this._i].render();
  4389. }
  4390. }
  4391. },
  4392. /**
  4393. * Post-render is called after the Game Renderer and State.render have run.
  4394. * It only calls plugins who have visible=true.
  4395. *
  4396. * @method Phaser.PluginManager#postRender
  4397. */
  4398. postRender: function () {
  4399. this._i = this._len;
  4400. while (this._i--)
  4401. {
  4402. if (this.plugins[this._i].visible && this.plugins[this._i].hasPostRender)
  4403. {
  4404. this.plugins[this._i].postRender();
  4405. }
  4406. }
  4407. },
  4408. /**
  4409. * Clear down this PluginManager, calls destroy on every plugin and nulls out references.
  4410. *
  4411. * @method Phaser.PluginManager#destroy
  4412. */
  4413. destroy: function () {
  4414. this.removeAll();
  4415. this.game = null;
  4416. }
  4417. };
  4418. Phaser.PluginManager.prototype.constructor = Phaser.PluginManager;
  4419. /**
  4420. * @author Richard Davey <rich@photonstorm.com>
  4421. * @copyright 2014 Photon Storm Ltd.
  4422. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  4423. */
  4424. /**
  4425. * The Stage controls the canvas on which everything is displayed. It handles display within the browser,
  4426. * focus handling, game resizing, scaling and the pause, boot and orientation screens.
  4427. *
  4428. * @class Phaser.Stage
  4429. * @extends PIXI.Stage
  4430. * @constructor
  4431. * @param {Phaser.Game} game - Game reference to the currently running game.
  4432. * @param {number} width - Width of the canvas element.
  4433. * @param {number} height - Height of the canvas element.
  4434. */
  4435. Phaser.Stage = function (game, width, height) {
  4436. /**
  4437. * @property {Phaser.Game} game - A reference to the currently running Game.
  4438. */
  4439. this.game = game;
  4440. /**
  4441. * @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)
  4442. */
  4443. this.offset = new Phaser.Point();
  4444. PIXI.Stage.call(this, 0x000000, false);
  4445. /**
  4446. * @property {string} name - The name of this object.
  4447. * @default
  4448. */
  4449. this.name = '_stage_root';
  4450. this.interactive = false;
  4451. /**
  4452. * @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.
  4453. * @default
  4454. */
  4455. this.disableVisibilityChange = false;
  4456. /**
  4457. * @property {number|false} checkOffsetInterval - The time (in ms) between which the stage should check to see if it has moved.
  4458. * @default
  4459. */
  4460. this.checkOffsetInterval = 2500;
  4461. /**
  4462. * @property {boolean} exists - If exists is true the Stage and all children are updated, otherwise it is skipped.
  4463. * @default
  4464. */
  4465. this.exists = true;
  4466. /**
  4467. * @property {number} currentRenderOrderID - Reset each frame, keeps a count of the total number of objects updated.
  4468. */
  4469. this.currentRenderOrderID = 0;
  4470. /**
  4471. * @property {string} hiddenVar - The page visibility API event name.
  4472. * @private
  4473. */
  4474. this._hiddenVar = 'hidden';
  4475. /**
  4476. * @property {number} _nextOffsetCheck - The time to run the next offset check.
  4477. * @private
  4478. */
  4479. this._nextOffsetCheck = 0;
  4480. /**
  4481. * @property {number} _backgroundColor - Stage background color.
  4482. * @private
  4483. */
  4484. this._backgroundColor = 0x000000;
  4485. if (game.config)
  4486. {
  4487. this.parseConfig(game.config);
  4488. }
  4489. else
  4490. {
  4491. this.game.canvas = Phaser.Canvas.create(width, height);
  4492. this.game.canvas.style['-webkit-full-screen'] = 'width: 100%; height: 100%';
  4493. }
  4494. };
  4495. Phaser.Stage.prototype = Object.create(PIXI.Stage.prototype);
  4496. Phaser.Stage.prototype.constructor = Phaser.Stage;
  4497. /**
  4498. * This is called automatically after the plugins preUpdate and before the State.update.
  4499. * Most objects have preUpdate methods and it's where initial movement and positioning is done.
  4500. *
  4501. * @method Phaser.Stage#preUpdate
  4502. */
  4503. Phaser.Stage.prototype.preUpdate = function () {
  4504. this.currentRenderOrderID = 0;
  4505. // This can't loop in reverse, we need the orderID to be in sequence
  4506. var len = this.children.length;
  4507. for (var i = 0; i < len; i++)
  4508. {
  4509. this.children[i].preUpdate();
  4510. }
  4511. };
  4512. /**
  4513. * This is called automatically after the State.update, but before particles or plugins update.
  4514. *
  4515. * @method Phaser.Stage#update
  4516. */
  4517. Phaser.Stage.prototype.update = function () {
  4518. var i = this.children.length;
  4519. while (i--)
  4520. {
  4521. this.children[i].update();
  4522. }
  4523. };
  4524. /**
  4525. * This is called automatically before the renderer runs and after the plugins have updated.
  4526. * In postUpdate this is where all the final physics calculatations and object positioning happens.
  4527. * The objects are processed in the order of the display list.
  4528. * The only exception to this is if the camera is following an object, in which case that is updated first.
  4529. *
  4530. * @method Phaser.Stage#postUpdate
  4531. */
  4532. Phaser.Stage.prototype.postUpdate = function () {
  4533. if (this.game.world.camera.target)
  4534. {
  4535. this.game.world.camera.target.postUpdate();
  4536. this.game.world.camera.update();
  4537. var i = this.children.length;
  4538. while (i--)
  4539. {
  4540. if (this.children[i] !== this.game.world.camera.target)
  4541. {
  4542. this.children[i].postUpdate();
  4543. }
  4544. }
  4545. }
  4546. else
  4547. {
  4548. this.game.world.camera.update();
  4549. var i = this.children.length;
  4550. while (i--)
  4551. {
  4552. this.children[i].postUpdate();
  4553. }
  4554. }
  4555. if (this.checkOffsetInterval !== false)
  4556. {
  4557. if (this.game.time.now > this._nextOffsetCheck)
  4558. {
  4559. Phaser.Canvas.getOffset(this.game.canvas, this.offset);
  4560. this._nextOffsetCheck = this.game.time.now + this.checkOffsetInterval;
  4561. }
  4562. }
  4563. };
  4564. /**
  4565. * Parses a Game configuration object.
  4566. *
  4567. * @method Phaser.Stage#parseConfig
  4568. * @protected
  4569. */
  4570. Phaser.Stage.prototype.parseConfig = function (config) {
  4571. if (config['canvasID'])
  4572. {
  4573. this.game.canvas = Phaser.Canvas.create(this.game.width, this.game.height, config['canvasID']);
  4574. }
  4575. else
  4576. {
  4577. this.game.canvas = Phaser.Canvas.create(this.game.width, this.game.height);
  4578. }
  4579. if (config['canvasStyle'])
  4580. {
  4581. this.game.canvas.stlye = config['canvasStyle'];
  4582. }
  4583. else
  4584. {
  4585. this.game.canvas.style['-webkit-full-screen'] = 'width: 100%; height: 100%';
  4586. }
  4587. if (config['checkOffsetInterval'])
  4588. {
  4589. this.checkOffsetInterval = config['checkOffsetInterval'];
  4590. }
  4591. if (config['disableVisibilityChange'])
  4592. {
  4593. this.disableVisibilityChange = config['disableVisibilityChange'];
  4594. }
  4595. if (config['fullScreenScaleMode'])
  4596. {
  4597. this.fullScreenScaleMode = config['fullScreenScaleMode'];
  4598. }
  4599. if (config['scaleMode'])
  4600. {
  4601. this.scaleMode = config['scaleMode'];
  4602. }
  4603. if (config['backgroundColor'])
  4604. {
  4605. this.backgroundColor = config['backgroundColor'];
  4606. }
  4607. };
  4608. /**
  4609. * Initialises the stage and adds the event listeners.
  4610. * @method Phaser.Stage#boot
  4611. * @private
  4612. */
  4613. Phaser.Stage.prototype.boot = function () {
  4614. Phaser.Canvas.getOffset(this.game.canvas, this.offset);
  4615. this.bounds = new Phaser.Rectangle(this.offset.x, this.offset.y, this.game.width, this.game.height);
  4616. var _this = this;
  4617. this._onChange = function (event) {
  4618. return _this.visibilityChange(event);
  4619. };
  4620. Phaser.Canvas.setUserSelect(this.game.canvas, 'none');
  4621. Phaser.Canvas.setTouchAction(this.game.canvas, 'none');
  4622. this.checkVisibility();
  4623. };
  4624. /**
  4625. * Starts a page visibility event listener running, or window.blur/focus if not supported by the browser.
  4626. * @method Phaser.Stage#checkVisibility
  4627. */
  4628. Phaser.Stage.prototype.checkVisibility = function () {
  4629. if (document.webkitHidden !== undefined)
  4630. {
  4631. this._hiddenVar = 'webkitvisibilitychange';
  4632. }
  4633. else if (document.mozHidden !== undefined)
  4634. {
  4635. this._hiddenVar = 'mozvisibilitychange';
  4636. }
  4637. else if (document.msHidden !== undefined)
  4638. {
  4639. this._hiddenVar = 'msvisibilitychange';
  4640. }
  4641. else if (document.hidden !== undefined)
  4642. {
  4643. this._hiddenVar = 'visibilitychange';
  4644. }
  4645. else
  4646. {
  4647. this._hiddenVar = null;
  4648. }
  4649. // Does browser support it? If not (like in IE9 or old Android) we need to fall back to blur/focus
  4650. if (this._hiddenVar)
  4651. {
  4652. document.addEventListener(this._hiddenVar, this._onChange, false);
  4653. }
  4654. window.onpagehide = this._onChange;
  4655. window.onpageshow = this._onChange;
  4656. window.onblur = this._onChange;
  4657. window.onfocus = this._onChange;
  4658. };
  4659. /**
  4660. * This method is called when the document visibility is changed.
  4661. * @method Phaser.Stage#visibilityChange
  4662. * @param {Event} event - Its type will be used to decide whether the game should be paused or not.
  4663. */
  4664. Phaser.Stage.prototype.visibilityChange = function (event) {
  4665. if (this.disableVisibilityChange)
  4666. {
  4667. return;
  4668. }
  4669. if (event.type === 'pagehide' || event.type === 'blur' || event.type === 'pageshow' || event.type === 'focus')
  4670. {
  4671. if (event.type === 'pagehide' || event.type === 'blur')
  4672. {
  4673. this.game.focusLoss(event);
  4674. }
  4675. else if (event.type === 'pageshow' || event.type === 'focus')
  4676. {
  4677. this.game.focusGain(event);
  4678. }
  4679. return;
  4680. }
  4681. if (document.hidden || document.mozHidden || document.msHidden || document.webkitHidden)
  4682. {
  4683. this.game.gamePaused(event);
  4684. }
  4685. else
  4686. {
  4687. this.game.gameResumed(event);
  4688. }
  4689. };
  4690. /**
  4691. * Sets the background color for the stage.
  4692. *
  4693. * @name Phaser.Stage#setBackgroundColor
  4694. * @param {number} backgroundColor - The color of the background, easiest way to pass this in is in hex format like: 0xFFFFFF for white.
  4695. */
  4696. Phaser.Stage.prototype.setBackgroundColor = function(backgroundColor)
  4697. {
  4698. this._backgroundColor = backgroundColor || 0x000000;
  4699. this.backgroundColorSplit = PIXI.hex2rgb(this.backgroundColor);
  4700. var hex = this._backgroundColor.toString(16);
  4701. hex = '000000'.substr(0, 6 - hex.length) + hex;
  4702. this.backgroundColorString = '#' + hex;
  4703. };
  4704. /**
  4705. * @name Phaser.Stage#backgroundColor
  4706. * @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'
  4707. */
  4708. Object.defineProperty(Phaser.Stage.prototype, "backgroundColor", {
  4709. get: function () {
  4710. return this._backgroundColor;
  4711. },
  4712. set: function (color) {
  4713. this._backgroundColor = color;
  4714. if (this.game.transparent === false)
  4715. {
  4716. if (typeof color === 'string')
  4717. {
  4718. color = Phaser.Color.hexToRGB(color);
  4719. }
  4720. this.setBackgroundColor(color);
  4721. }
  4722. }
  4723. });
  4724. /**
  4725. * Enable or disable texture smoothing for all objects on this Stage. Only works for bitmap/image textures. Smoothing is enabled by default.
  4726. *
  4727. * @name Phaser.Stage#smoothed
  4728. * @property {boolean} smoothed - Set to true to smooth all sprites rendered on this Stage, or false to disable smoothing (great for pixel art)
  4729. */
  4730. Object.defineProperty(Phaser.Stage.prototype, "smoothed", {
  4731. get: function () {
  4732. return !PIXI.scaleModes.LINEAR;
  4733. },
  4734. set: function (value) {
  4735. if (value)
  4736. {
  4737. PIXI.scaleModes.LINEAR = 0;
  4738. }
  4739. else
  4740. {
  4741. PIXI.scaleModes.LINEAR = 1;
  4742. }
  4743. }
  4744. });
  4745. /**
  4746. * @author Richard Davey <rich@photonstorm.com>
  4747. * @copyright 2014 Photon Storm Ltd.
  4748. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  4749. */
  4750. /**
  4751. * Phaser Group constructor.
  4752. * @class Phaser.Group
  4753. * @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.
  4754. * @constructor
  4755. * @param {Phaser.Game} game - A reference to the currently running game.
  4756. * @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.
  4757. * @param {string} [name=group] - A name for this Group. Not used internally but useful for debugging.
  4758. * @param {boolean} [addToStage=false] - If set to true this Group will be added directly to the Game.Stage instead of Game.World.
  4759. * @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.
  4760. * @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.
  4761. */
  4762. Phaser.Group = function (game, parent, name, addToStage, enableBody, physicsBodyType) {
  4763. if (typeof addToStage === 'undefined') { addToStage = false; }
  4764. if (typeof enableBody === 'undefined') { enableBody = false; }
  4765. if (typeof physicsBodyType === 'undefined') { physicsBodyType = Phaser.Physics.ARCADE; }
  4766. /**
  4767. * @property {Phaser.Game} game - A reference to the currently running Game.
  4768. */
  4769. this.game = game;
  4770. if (typeof parent === 'undefined')
  4771. {
  4772. parent = game.world;
  4773. }
  4774. /**
  4775. * @property {string} name - A name for this Group. Not used internally but useful for debugging.
  4776. */
  4777. this.name = name || 'group';
  4778. PIXI.DisplayObjectContainer.call(this);
  4779. if (addToStage)
  4780. {
  4781. this.game.stage.addChild(this);
  4782. }
  4783. else
  4784. {
  4785. if (parent)
  4786. {
  4787. parent.addChild(this);
  4788. }
  4789. }
  4790. /**
  4791. * @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.
  4792. */
  4793. this.z = 0;
  4794. /**
  4795. * @property {number} type - Internal Phaser Type value.
  4796. * @protected
  4797. */
  4798. this.type = Phaser.GROUP;
  4799. /**
  4800. * @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.
  4801. * @default
  4802. */
  4803. this.alive = true;
  4804. /**
  4805. * @property {boolean} exists - If exists is true the Group is updated, otherwise it is skipped.
  4806. * @default
  4807. */
  4808. this.exists = true;
  4809. /**
  4810. * @property {Phaser.Group|Phaser.Sprite} parent - The parent of this Group.
  4811. */
  4812. /**
  4813. * @property {Phaser.Point} scale - The scale of the Group container.
  4814. */
  4815. this.scale = new Phaser.Point(1, 1);
  4816. /**
  4817. * @property {Phaser.Point} pivot - The pivot point of the Group container.
  4818. */
  4819. /**
  4820. * The cursor is a simple way to iterate through the objects in a Group using the Group.next and Group.previous functions.
  4821. * 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.
  4822. * @property {any} cursor - The current display object that the Group cursor is pointing to.
  4823. */
  4824. this.cursor = null;
  4825. /**
  4826. * @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.
  4827. */
  4828. this.cameraOffset = new Phaser.Point();
  4829. /**
  4830. * @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`.
  4831. * @default
  4832. */
  4833. this.enableBody = enableBody;
  4834. /**
  4835. * @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.
  4836. */
  4837. this.enableBodyDebug = false;
  4838. /**
  4839. * @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.
  4840. */
  4841. this.physicsBodyType = physicsBodyType;
  4842. /**
  4843. * @property {string} _sortProperty - The property on which children are sorted.
  4844. * @private
  4845. */
  4846. this._sortProperty = 'z';
  4847. /**
  4848. * A small internal cache:
  4849. * 0 = previous position.x
  4850. * 1 = previous position.y
  4851. * 2 = previous rotation
  4852. * 3 = renderID
  4853. * 4 = fresh? (0 = no, 1 = yes)
  4854. * 5 = outOfBoundsFired (0 = no, 1 = yes)
  4855. * 6 = exists (0 = no, 1 = yes)
  4856. * 7 = fixed to camera (0 = no, 1 = yes)
  4857. * 8 = cursor index
  4858. * 9 = sort order
  4859. * @property {Array} _cache
  4860. * @private
  4861. */
  4862. this._cache = [ 0, 0, 0, 0, 1, 0, 1, 0, 0, 0 ];
  4863. };
  4864. Phaser.Group.prototype = Object.create(PIXI.DisplayObjectContainer.prototype);
  4865. Phaser.Group.prototype.constructor = Phaser.Group;
  4866. /**
  4867. * @constant
  4868. * @type {number}
  4869. */
  4870. Phaser.Group.RETURN_NONE = 0;
  4871. /**
  4872. * @constant
  4873. * @type {number}
  4874. */
  4875. Phaser.Group.RETURN_TOTAL = 1;
  4876. /**
  4877. * @constant
  4878. * @type {number}
  4879. */
  4880. Phaser.Group.RETURN_CHILD = 2;
  4881. /**
  4882. * @constant
  4883. * @type {number}
  4884. */
  4885. Phaser.Group.SORT_ASCENDING = -1;
  4886. /**
  4887. * @constant
  4888. * @type {number}
  4889. */
  4890. Phaser.Group.SORT_DESCENDING = 1;
  4891. /**
  4892. * Adds an existing object to this Group. The object can be an instance of Phaser.Sprite, Phaser.Button or any other display object.
  4893. * 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
  4894. * that then see the addAt method.
  4895. *
  4896. * @see Phaser.Group#create
  4897. * @see Phaser.Group#addAt
  4898. * @method Phaser.Group#add
  4899. * @param {*} child - An instance of Phaser.Sprite, Phaser.Button or any other display object..
  4900. * @return {*} The child that was added to the Group.
  4901. */
  4902. Phaser.Group.prototype.add = function (child) {
  4903. if (child.parent !== this)
  4904. {
  4905. if (this.enableBody)
  4906. {
  4907. this.game.physics.enable(child, this.physicsBodyType);
  4908. }
  4909. this.addChild(child);
  4910. child.z = this.children.length;
  4911. if (child.events)
  4912. {
  4913. child.events.onAddedToGroup.dispatch(child, this);
  4914. }
  4915. if (this.cursor === null)
  4916. {
  4917. this.cursor = child;
  4918. }
  4919. }
  4920. return child;
  4921. };
  4922. /**
  4923. * Adds an existing object to this Group. The object can be an instance of Phaser.Sprite, Phaser.Button or any other display object.
  4924. * The child is added to the Group at the location specified by the index value, this allows you to control child ordering.
  4925. *
  4926. * @method Phaser.Group#addAt
  4927. * @param {*} child - An instance of Phaser.Sprite, Phaser.Button or any other display object..
  4928. * @param {number} index - The index within the Group to insert the child to.
  4929. * @return {*} The child that was added to the Group.
  4930. */
  4931. Phaser.Group.prototype.addAt = function (child, index) {
  4932. if (child.parent !== this)
  4933. {
  4934. if (this.enableBody)
  4935. {
  4936. this.game.physics.enable(child, this.physicsBodyType);
  4937. }
  4938. this.addChildAt(child, index);
  4939. this.updateZ();
  4940. if (child.events)
  4941. {
  4942. child.events.onAddedToGroup.dispatch(child, this);
  4943. }
  4944. if (this.cursor === null)
  4945. {
  4946. this.cursor = child;
  4947. }
  4948. }
  4949. return child;
  4950. };
  4951. /**
  4952. * Returns the child found at the given index within this Group.
  4953. *
  4954. * @method Phaser.Group#getAt
  4955. * @param {number} index - The index to return the child from.
  4956. * @return {*} The child that was found at the given index. If the index was out of bounds then this will return -1.
  4957. */
  4958. Phaser.Group.prototype.getAt = function (index) {
  4959. if (index < 0 || index >= this.children.length)
  4960. {
  4961. return -1;
  4962. }
  4963. else
  4964. {
  4965. return this.getChildAt(index);
  4966. }
  4967. };
  4968. /**
  4969. * Automatically creates a new Phaser.Sprite object and adds it to the top of this Group.
  4970. * Useful if you don't need to create the Sprite instances before-hand.
  4971. *
  4972. * @method Phaser.Group#create
  4973. * @param {number} x - The x coordinate to display the newly created Sprite at. The value is in relation to the Group.x point.
  4974. * @param {number} y - The y coordinate to display the newly created Sprite at. The value is in relation to the Group.y point.
  4975. * @param {string} key - The Game.cache key of the image that this Sprite will use.
  4976. * @param {number|string} [frame] - If the Sprite image contains multiple frames you can specify which one to use here.
  4977. * @param {boolean} [exists=true] - The default exists state of the Sprite.
  4978. * @return {Phaser.Sprite} The child that was created.
  4979. */
  4980. Phaser.Group.prototype.create = function (x, y, key, frame, exists) {
  4981. if (typeof exists === 'undefined') { exists = true; }
  4982. var child = new Phaser.Sprite(this.game, x, y, key, frame);
  4983. if (this.enableBody)
  4984. {
  4985. this.game.physics.enable(child, this.physicsBodyType);
  4986. }
  4987. child.exists = exists;
  4988. child.visible = exists;
  4989. child.alive = exists;
  4990. this.addChild(child);
  4991. child.z = this.children.length;
  4992. if (child.events)
  4993. {
  4994. child.events.onAddedToGroup.dispatch(child, this);
  4995. }
  4996. if (this.cursor === null)
  4997. {
  4998. this.cursor = child;
  4999. }
  5000. return child;
  5001. };
  5002. /**
  5003. * Automatically creates multiple Phaser.Sprite objects and adds them to the top of this Group.
  5004. * 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
  5005. * and will be positioned at 0, 0 (relative to the Group.x/y)
  5006. *
  5007. * @method Phaser.Group#createMultiple
  5008. * @param {number} quantity - The number of Sprites to create.
  5009. * @param {string} key - The Game.cache key of the image that this Sprite will use.
  5010. * @param {number|string} [frame] - If the Sprite image contains multiple frames you can specify which one to use here.
  5011. * @param {boolean} [exists=false] - The default exists state of the Sprite.
  5012. */
  5013. Phaser.Group.prototype.createMultiple = function (quantity, key, frame, exists) {
  5014. if (typeof exists === 'undefined') { exists = false; }
  5015. for (var i = 0; i < quantity; i++)
  5016. {
  5017. this.create(0, 0, key, frame, exists);
  5018. }
  5019. };
  5020. /**
  5021. * Internal method that re-applies all of the childrens Z values.
  5022. *
  5023. * @method Phaser.Group#updateZ
  5024. * @protected
  5025. */
  5026. Phaser.Group.prototype.updateZ = function () {
  5027. var i = this.children.length;
  5028. while (i--)
  5029. {
  5030. this.children[i].z = i;
  5031. }
  5032. };
  5033. /**
  5034. * 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.
  5035. *
  5036. * @method Phaser.Group#next
  5037. * @return {*} The child the cursor now points to.
  5038. */
  5039. Phaser.Group.prototype.next = function () {
  5040. if (this.cursor)
  5041. {
  5042. // Wrap the cursor?
  5043. if (this._cache[8] >= this.children.length - 1)
  5044. {
  5045. this._cache[8] = 0;
  5046. }
  5047. else
  5048. {
  5049. this._cache[8]++;
  5050. }
  5051. this.cursor = this.children[this._cache[8]];
  5052. return this.cursor;
  5053. }
  5054. };
  5055. /**
  5056. * 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.
  5057. *
  5058. * @method Phaser.Group#previous
  5059. * @return {*} The child the cursor now points to.
  5060. */
  5061. Phaser.Group.prototype.previous = function () {
  5062. if (this.cursor)
  5063. {
  5064. // Wrap the cursor?
  5065. if (this._cache[8] === 0)
  5066. {
  5067. this._cache[8] = this.children.length - 1;
  5068. }
  5069. else
  5070. {
  5071. this._cache[8]--;
  5072. }
  5073. this.cursor = this.children[this._cache[8]];
  5074. return this.cursor;
  5075. }
  5076. };
  5077. /**
  5078. * Swaps the position of two children in this Group. Both children must be in this Group.
  5079. * You cannot swap a child with itself, or swap un-parented children, doing so will return false.
  5080. *
  5081. * @method Phaser.Group#swap
  5082. * @param {*} child1 - The first child to swap.
  5083. * @param {*} child2 - The second child to swap.
  5084. */
  5085. Phaser.Group.prototype.swap = function (child1, child2) {
  5086. var result = this.swapChildren(child1, child2);
  5087. if (result)
  5088. {
  5089. this.updateZ();
  5090. }
  5091. return result;
  5092. };
  5093. /**
  5094. * Brings the given child to the top of this Group so it renders above all other children.
  5095. *
  5096. * @method Phaser.Group#bringToTop
  5097. * @param {*} child - The child to bring to the top of this Group.
  5098. * @return {*} The child that was moved.
  5099. */
  5100. Phaser.Group.prototype.bringToTop = function (child) {
  5101. if (child.parent === this && this.getIndex(child) < this.children.length)
  5102. {
  5103. this.remove(child);
  5104. this.add(child);
  5105. }
  5106. return child;
  5107. };
  5108. /**
  5109. * Sends the given child to the bottom of this Group so it renders below all other children.
  5110. *
  5111. * @method Phaser.Group#sendToBack
  5112. * @param {*} child - The child to send to the bottom of this Group.
  5113. * @return {*} The child that was moved.
  5114. */
  5115. Phaser.Group.prototype.sendToBack = function (child) {
  5116. if (child.parent === this && this.getIndex(child) > 0)
  5117. {
  5118. this.remove(child);
  5119. this.addAt(child, 0);
  5120. }
  5121. return child;
  5122. };
  5123. /**
  5124. * Moves the given child up one place in this Group unless it's already at the top.
  5125. *
  5126. * @method Phaser.Group#moveUp
  5127. * @param {*} child - The child to move up in the Group.
  5128. * @return {*} The child that was moved.
  5129. */
  5130. Phaser.Group.prototype.moveUp = function (child) {
  5131. if (child.parent === this && this.getIndex(child) < this.children.length - 1)
  5132. {
  5133. var a = this.getIndex(child);
  5134. var b = this.getAt(a + 1);
  5135. if (b)
  5136. {
  5137. this.swap(child, b);
  5138. }
  5139. }
  5140. return child;
  5141. };
  5142. /**
  5143. * Moves the given child down one place in this Group unless it's already at the top.
  5144. *
  5145. * @method Phaser.Group#moveDown
  5146. * @param {*} child - The child to move down in the Group.
  5147. * @return {*} The child that was moved.
  5148. */
  5149. Phaser.Group.prototype.moveDown = function (child) {
  5150. if (child.parent === this && this.getIndex(child) > 0)
  5151. {
  5152. var a = this.getIndex(child);
  5153. var b = this.getAt(a - 1);
  5154. if (b)
  5155. {
  5156. this.swap(child, b);
  5157. }
  5158. }
  5159. return child;
  5160. };
  5161. /**
  5162. * Positions the child found at the given index within this Group to the given x and y coordinates.
  5163. *
  5164. * @method Phaser.Group#xy
  5165. * @param {number} index - The index of the child in the Group to set the position of.
  5166. * @param {number} x - The new x position of the child.
  5167. * @param {number} y - The new y position of the child.
  5168. */
  5169. Phaser.Group.prototype.xy = function (index, x, y) {
  5170. if (index < 0 || index > this.children.length)
  5171. {
  5172. return -1;
  5173. }
  5174. else
  5175. {
  5176. this.getChildAt(index).x = x;
  5177. this.getChildAt(index).y = y;
  5178. }
  5179. };
  5180. /**
  5181. * Reverses all children in this Group. Note that this does not propagate, only direct children are re-ordered.
  5182. *
  5183. * @method Phaser.Group#reverse
  5184. */
  5185. Phaser.Group.prototype.reverse = function () {
  5186. this.children.reverse();
  5187. this.updateZ();
  5188. };
  5189. /**
  5190. * Get the index position of the given child in this Group. This should always match the childs z property.
  5191. *
  5192. * @method Phaser.Group#getIndex
  5193. * @param {*} child - The child to get the index for.
  5194. * @return {number} The index of the child or -1 if it's not a member of this Group.
  5195. */
  5196. Phaser.Group.prototype.getIndex = function (child) {
  5197. return this.children.indexOf(child);
  5198. };
  5199. /**
  5200. * Replaces a child of this Group with the given newChild. The newChild cannot be a member of this Group.
  5201. *
  5202. * @method Phaser.Group#replace
  5203. * @param {*} oldChild - The child in this Group that will be replaced.
  5204. * @param {*} newChild - The child to be inserted into this Group.
  5205. * @return {*} Returns the oldChild that was replaced within this Group.
  5206. */
  5207. Phaser.Group.prototype.replace = function (oldChild, newChild) {
  5208. var index = this.getIndex(oldChild);
  5209. if (index !== -1)
  5210. {
  5211. if (newChild.parent !== undefined)
  5212. {
  5213. newChild.events.onRemovedFromGroup.dispatch(newChild, this);
  5214. newChild.parent.removeChild(newChild);
  5215. if (newChild.parent instanceof Phaser.Group)
  5216. {
  5217. newChild.parent.updateZ();
  5218. }
  5219. }
  5220. var temp = oldChild;
  5221. this.remove(temp);
  5222. this.addAt(newChild, index);
  5223. return temp;
  5224. }
  5225. };
  5226. /**
  5227. * Sets the given property to the given value on the child. The operation controls the assignment of the value.
  5228. *
  5229. * @method Phaser.Group#setProperty
  5230. * @param {*} child - The child to set the property value on.
  5231. * @param {array} key - An array of strings that make up the property that will be set.
  5232. * @param {*} value - The value that will be set.
  5233. * @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.
  5234. */
  5235. Phaser.Group.prototype.setProperty = function (child, key, value, operation) {
  5236. operation = operation || 0;
  5237. // As ugly as this approach looks, and although it's limited to a depth of only 4, it's extremely fast.
  5238. // Much faster than a for loop or object iteration. There are no checks, so if the key isn't valid then it'll fail
  5239. // but as you are likely to call this from inner loops that have to perform well, I'll take that trade off.
  5240. // 0 = Equals
  5241. // 1 = Add
  5242. // 2 = Subtract
  5243. // 3 = Multiply
  5244. // 4 = Divide
  5245. var len = key.length;
  5246. if (len == 1)
  5247. {
  5248. if (operation === 0) { child[key[0]] = value; }
  5249. else if (operation == 1) { child[key[0]] += value; }
  5250. else if (operation == 2) { child[key[0]] -= value; }
  5251. else if (operation == 3) { child[key[0]] *= value; }
  5252. else if (operation == 4) { child[key[0]] /= value; }
  5253. }
  5254. else if (len == 2)
  5255. {
  5256. if (operation === 0) { child[key[0]][key[1]] = value; }
  5257. else if (operation == 1) { child[key[0]][key[1]] += value; }
  5258. else if (operation == 2) { child[key[0]][key[1]] -= value; }
  5259. else if (operation == 3) { child[key[0]][key[1]] *= value; }
  5260. else if (operation == 4) { child[key[0]][key[1]] /= value; }
  5261. }
  5262. else if (len == 3)
  5263. {
  5264. if (operation === 0) { child[key[0]][key[1]][key[2]] = value; }
  5265. else if (operation == 1) { child[key[0]][key[1]][key[2]] += value; }
  5266. else if (operation == 2) { child[key[0]][key[1]][key[2]] -= value; }
  5267. else if (operation == 3) { child[key[0]][key[1]][key[2]] *= value; }
  5268. else if (operation == 4) { child[key[0]][key[1]][key[2]] /= value; }
  5269. }
  5270. else if (len == 4)
  5271. {
  5272. if (operation === 0) { child[key[0]][key[1]][key[2]][key[3]] = value; }
  5273. else if (operation == 1) { child[key[0]][key[1]][key[2]][key[3]] += value; }
  5274. else if (operation == 2) { child[key[0]][key[1]][key[2]][key[3]] -= value; }
  5275. else if (operation == 3) { child[key[0]][key[1]][key[2]][key[3]] *= value; }
  5276. else if (operation == 4) { child[key[0]][key[1]][key[2]][key[3]] /= value; }
  5277. }
  5278. };
  5279. /**
  5280. * This function allows you to quickly set a property on a single child of this Group to a new value.
  5281. * The operation parameter controls how the new value is assigned to the property, from simple replacement to addition and multiplication.
  5282. *
  5283. * @method Phaser.Group#set
  5284. * @param {Phaser.Sprite} child - The child to set the property on.
  5285. * @param {string} key - The property, as a string, to be set. For example: 'body.velocity.x'
  5286. * @param {*} value - The value that will be set.
  5287. * @param {boolean} [checkAlive=false] - If set then the child will only be updated if alive=true.
  5288. * @param {boolean} [checkVisible=false] - If set then the child will only be updated if visible=true.
  5289. * @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.
  5290. */
  5291. Phaser.Group.prototype.set = function (child, key, value, checkAlive, checkVisible, operation) {
  5292. key = key.split('.');
  5293. if (typeof checkAlive === 'undefined') { checkAlive = false; }
  5294. if (typeof checkVisible === 'undefined') { checkVisible = false; }
  5295. if ((checkAlive === false || (checkAlive && child.alive)) && (checkVisible === false || (checkVisible && child.visible)))
  5296. {
  5297. this.setProperty(child, key, value, operation);
  5298. }
  5299. };
  5300. /**
  5301. * This function allows you to quickly set the same property across all children of this Group to a new value.
  5302. * 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.
  5303. * If you need that ability please see `Group.setAllChildren`.
  5304. *
  5305. * The operation parameter controls how the new value is assigned to the property, from simple replacement to addition and multiplication.
  5306. *
  5307. * @method Phaser.Group#setAll
  5308. * @param {string} key - The property, as a string, to be set. For example: 'body.velocity.x'
  5309. * @param {*} value - The value that will be set.
  5310. * @param {boolean} [checkAlive=false] - If set then only children with alive=true will be updated. This includes any Groups that are children.
  5311. * @param {boolean} [checkVisible=false] - If set then only children with visible=true will be updated. This includes any Groups that are children.
  5312. * @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.
  5313. */
  5314. Phaser.Group.prototype.setAll = function (key, value, checkAlive, checkVisible, operation) {
  5315. key = key.split('.');
  5316. if (typeof checkAlive === 'undefined') { checkAlive = false; }
  5317. if (typeof checkVisible === 'undefined') { checkVisible = false; }
  5318. operation = operation || 0;
  5319. for (var i = 0, len = this.children.length; i < len; i++)
  5320. {
  5321. if ((!checkAlive || (checkAlive && this.children[i].alive)) && (!checkVisible || (checkVisible && this.children[i].visible)))
  5322. {
  5323. this.setProperty(this.children[i], key, value, operation);
  5324. }
  5325. }
  5326. };
  5327. /**
  5328. * This function allows you to quickly set the same property across all children of this Group, and any child Groups, to a new value.
  5329. *
  5330. * If this Group contains other Groups then the same property is set across their children as well, iterating down until it reaches the bottom.
  5331. * Unlike with Group.setAll the property is NOT set on child Groups itself.
  5332. *
  5333. * The operation parameter controls how the new value is assigned to the property, from simple replacement to addition and multiplication.
  5334. *
  5335. * @method Phaser.Group#setAllChildren
  5336. * @param {string} key - The property, as a string, to be set. For example: 'body.velocity.x'
  5337. * @param {*} value - The value that will be set.
  5338. * @param {boolean} [checkAlive=false] - If set then only children with alive=true will be updated. This includes any Groups that are children.
  5339. * @param {boolean} [checkVisible=false] - If set then only children with visible=true will be updated. This includes any Groups that are children.
  5340. * @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.
  5341. */
  5342. Phaser.Group.prototype.setAllChildren = function (key, value, checkAlive, checkVisible, operation) {
  5343. if (typeof checkAlive === 'undefined') { checkAlive = false; }
  5344. if (typeof checkVisible === 'undefined') { checkVisible = false; }
  5345. operation = operation || 0;
  5346. for (var i = 0, len = this.children.length; i < len; i++)
  5347. {
  5348. if ((!checkAlive || (checkAlive && this.children[i].alive)) && (!checkVisible || (checkVisible && this.children[i].visible)))
  5349. {
  5350. if (this.children[i] instanceof Phaser.Group)
  5351. {
  5352. this.children[i].setAllChildren(key, value, checkAlive, checkVisible, operation);
  5353. }
  5354. else
  5355. {
  5356. this.setProperty(this.children[i], key.split('.'), value, operation);
  5357. }
  5358. }
  5359. }
  5360. };
  5361. /**
  5362. * Adds the amount to the given property on all children in this Group.
  5363. * Group.addAll('x', 10) will add 10 to the child.x value.
  5364. *
  5365. * @method Phaser.Group#addAll
  5366. * @param {string} property - The property to increment, for example 'body.velocity.x' or 'angle'.
  5367. * @param {number} amount - The amount to increment the property by. If child.x = 10 then addAll('x', 40) would make child.x = 50.
  5368. * @param {boolean} checkAlive - If true the property will only be changed if the child is alive.
  5369. * @param {boolean} checkVisible - If true the property will only be changed if the child is visible.
  5370. */
  5371. Phaser.Group.prototype.addAll = function (property, amount, checkAlive, checkVisible) {
  5372. this.setAll(property, amount, checkAlive, checkVisible, 1);
  5373. };
  5374. /**
  5375. * Subtracts the amount from the given property on all children in this Group.
  5376. * Group.subAll('x', 10) will minus 10 from the child.x value.
  5377. *
  5378. * @method Phaser.Group#subAll
  5379. * @param {string} property - The property to decrement, for example 'body.velocity.x' or 'angle'.
  5380. * @param {number} amount - The amount to subtract from the property. If child.x = 50 then subAll('x', 40) would make child.x = 10.
  5381. * @param {boolean} checkAlive - If true the property will only be changed if the child is alive.
  5382. * @param {boolean} checkVisible - If true the property will only be changed if the child is visible.
  5383. */
  5384. Phaser.Group.prototype.subAll = function (property, amount, checkAlive, checkVisible) {
  5385. this.setAll(property, amount, checkAlive, checkVisible, 2);
  5386. };
  5387. /**
  5388. * Multiplies the given property by the amount on all children in this Group.
  5389. * Group.multiplyAll('x', 2) will x2 the child.x value.
  5390. *
  5391. * @method Phaser.Group#multiplyAll
  5392. * @param {string} property - The property to multiply, for example 'body.velocity.x' or 'angle'.
  5393. * @param {number} amount - The amount to multiply the property by. If child.x = 10 then multiplyAll('x', 2) would make child.x = 20.
  5394. * @param {boolean} checkAlive - If true the property will only be changed if the child is alive.
  5395. * @param {boolean} checkVisible - If true the property will only be changed if the child is visible.
  5396. */
  5397. Phaser.Group.prototype.multiplyAll = function (property, amount, checkAlive, checkVisible) {
  5398. this.setAll(property, amount, checkAlive, checkVisible, 3);
  5399. };
  5400. /**
  5401. * Divides the given property by the amount on all children in this Group.
  5402. * Group.divideAll('x', 2) will half the child.x value.
  5403. *
  5404. * @method Phaser.Group#divideAll
  5405. * @param {string} property - The property to divide, for example 'body.velocity.x' or 'angle'.
  5406. * @param {number} amount - The amount to divide the property by. If child.x = 100 then divideAll('x', 2) would make child.x = 50.
  5407. * @param {boolean} checkAlive - If true the property will only be changed if the child is alive.
  5408. * @param {boolean} checkVisible - If true the property will only be changed if the child is visible.
  5409. */
  5410. Phaser.Group.prototype.divideAll = function (property, amount, checkAlive, checkVisible) {
  5411. this.setAll(property, amount, checkAlive, checkVisible, 4);
  5412. };
  5413. /**
  5414. * Calls a function on all of the children that have exists=true in this Group.
  5415. * After the existsValue parameter you can add as many parameters as you like, which will all be passed to the child callback.
  5416. *
  5417. * @method Phaser.Group#callAllExists
  5418. * @param {function} callback - The function that exists on the children that will be called.
  5419. * @param {boolean} existsValue - Only children with exists=existsValue will be called.
  5420. * @param {...*} parameter - Additional parameters that will be passed to the callback.
  5421. */
  5422. Phaser.Group.prototype.callAllExists = function (callback, existsValue) {
  5423. var args = Array.prototype.splice.call(arguments, 2);
  5424. for (var i = 0, len = this.children.length; i < len; i++)
  5425. {
  5426. if (this.children[i].exists === existsValue && this.children[i][callback])
  5427. {
  5428. this.children[i][callback].apply(this.children[i], args);
  5429. }
  5430. }
  5431. };
  5432. /**
  5433. * Returns a reference to a function that exists on a child of the Group based on the given callback array.
  5434. *
  5435. * @method Phaser.Group#callbackFromArray
  5436. * @param {object} child - The object to inspect.
  5437. * @param {array} callback - The array of function names.
  5438. * @param {number} length - The size of the array (pre-calculated in callAll).
  5439. * @protected
  5440. */
  5441. Phaser.Group.prototype.callbackFromArray = function (child, callback, length) {
  5442. // Kinda looks like a Christmas tree
  5443. if (length == 1)
  5444. {
  5445. if (child[callback[0]])
  5446. {
  5447. return child[callback[0]];
  5448. }
  5449. }
  5450. else if (length == 2)
  5451. {
  5452. if (child[callback[0]][callback[1]])
  5453. {
  5454. return child[callback[0]][callback[1]];
  5455. }
  5456. }
  5457. else if (length == 3)
  5458. {
  5459. if (child[callback[0]][callback[1]][callback[2]])
  5460. {
  5461. return child[callback[0]][callback[1]][callback[2]];
  5462. }
  5463. }
  5464. else if (length == 4)
  5465. {
  5466. if (child[callback[0]][callback[1]][callback[2]][callback[3]])
  5467. {
  5468. return child[callback[0]][callback[1]][callback[2]][callback[3]];
  5469. }
  5470. }
  5471. else
  5472. {
  5473. if (child[callback])
  5474. {
  5475. return child[callback];
  5476. }
  5477. }
  5478. return false;
  5479. };
  5480. /**
  5481. * Calls a function on all of the children regardless if they are dead or alive (see callAllExists if you need control over that)
  5482. * After the method parameter and context you can add as many extra parameters as you like, which will all be passed to the child.
  5483. *
  5484. * @method Phaser.Group#callAll
  5485. * @param {string} method - A string containing the name of the function that will be called. The function must exist on the child.
  5486. * @param {string} [context=null] - A string containing the context under which the method will be executed. Set to null to default to the child.
  5487. * @param {...*} parameter - Additional parameters that will be passed to the method.
  5488. */
  5489. Phaser.Group.prototype.callAll = function (method, context) {
  5490. if (typeof method === 'undefined')
  5491. {
  5492. return;
  5493. }
  5494. // Extract the method into an array
  5495. method = method.split('.');
  5496. var methodLength = method.length;
  5497. if (typeof context === 'undefined' || context === null || context === '')
  5498. {
  5499. context = null;
  5500. }
  5501. else
  5502. {
  5503. // Extract the context into an array
  5504. if (typeof context === 'string')
  5505. {
  5506. context = context.split('.');
  5507. var contextLength = context.length;
  5508. }
  5509. }
  5510. var args = Array.prototype.splice.call(arguments, 2);
  5511. var callback = null;
  5512. var callbackContext = null;
  5513. for (var i = 0, len = this.children.length; i < len; i++)
  5514. {
  5515. callback = this.callbackFromArray(this.children[i], method, methodLength);
  5516. if (context && callback)
  5517. {
  5518. callbackContext = this.callbackFromArray(this.children[i], context, contextLength);
  5519. if (callback)
  5520. {
  5521. callback.apply(callbackContext, args);
  5522. }
  5523. }
  5524. else if (callback)
  5525. {
  5526. callback.apply(this.children[i], args);
  5527. }
  5528. }
  5529. };
  5530. /**
  5531. * The core preUpdate - as called by World.
  5532. * @method Phaser.Group#preUpdate
  5533. * @protected
  5534. */
  5535. Phaser.Group.prototype.preUpdate = function () {
  5536. if (!this.exists || !this.parent.exists)
  5537. {
  5538. this.renderOrderID = -1;
  5539. return false;
  5540. }
  5541. var i = this.children.length;
  5542. while (i--)
  5543. {
  5544. this.children[i].preUpdate();
  5545. }
  5546. return true;
  5547. };
  5548. /**
  5549. * The core update - as called by World.
  5550. * @method Phaser.Group#update
  5551. * @protected
  5552. */
  5553. Phaser.Group.prototype.update = function () {
  5554. var i = this.children.length;
  5555. while (i--)
  5556. {
  5557. this.children[i].update();
  5558. }
  5559. };
  5560. /**
  5561. * The core postUpdate - as called by World.
  5562. * @method Phaser.Group#postUpdate
  5563. * @protected
  5564. */
  5565. Phaser.Group.prototype.postUpdate = function () {
  5566. // Fixed to Camera?
  5567. if (this._cache[7] === 1)
  5568. {
  5569. this.x = this.game.camera.view.x + this.cameraOffset.x;
  5570. this.y = this.game.camera.view.y + this.cameraOffset.y;
  5571. }
  5572. var i = this.children.length;
  5573. while (i--)
  5574. {
  5575. this.children[i].postUpdate();
  5576. }
  5577. };
  5578. /**
  5579. * 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.
  5580. * 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.
  5581. * For example: Group.forEach(awardBonusGold, this, true, 100, 500)
  5582. * Note: Currently this will skip any children which are Groups themselves.
  5583. *
  5584. * @method Phaser.Group#forEach
  5585. * @param {function} callback - The function that will be called. Each child of the Group will be passed to it as its first parameter.
  5586. * @param {Object} callbackContext - The context in which the function should be called (usually 'this').
  5587. * @param {boolean} [checkExists=false] - If set only children with exists=true will be passed to the callback, otherwise all children will be passed.
  5588. */
  5589. Phaser.Group.prototype.forEach = function (callback, callbackContext, checkExists) {
  5590. if (typeof checkExists === 'undefined') { checkExists = false; }
  5591. var args = Array.prototype.splice.call(arguments, 3);
  5592. args.unshift(null);
  5593. for (var i = 0, len = this.children.length; i < len; i++)
  5594. {
  5595. if (!checkExists || (checkExists && this.children[i].exists))
  5596. {
  5597. args[0] = this.children[i];
  5598. callback.apply(callbackContext, args);
  5599. }
  5600. }
  5601. };
  5602. /**
  5603. * 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.
  5604. * You can add as many parameters as you like, which will all be passed to the callback along with the child.
  5605. * For example: Group.forEachExists(causeDamage, this, 500)
  5606. *
  5607. * @method Phaser.Group#forEachExists
  5608. * @param {function} callback - The function that will be called. Each child of the Group will be passed to it as its first parameter.
  5609. * @param {Object} callbackContext - The context in which the function should be called (usually 'this').
  5610. */
  5611. Phaser.Group.prototype.forEachExists = function (callback, callbackContext) {
  5612. var args = Array.prototype.splice.call(arguments, 2);
  5613. args.unshift(null);
  5614. this.iterate('exists', true, Phaser.Group.RETURN_TOTAL, callback, callbackContext, args);
  5615. };
  5616. /**
  5617. * 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.
  5618. * You can add as many parameters as you like, which will all be passed to the callback along with the child.
  5619. * For example: Group.forEachAlive(causeDamage, this, 500)
  5620. *
  5621. * @method Phaser.Group#forEachAlive
  5622. * @param {function} callback - The function that will be called. Each child of the Group will be passed to it as its first parameter.
  5623. * @param {Object} callbackContext - The context in which the function should be called (usually 'this').
  5624. */
  5625. Phaser.Group.prototype.forEachAlive = function (callback, callbackContext) {
  5626. var args = Array.prototype.splice.call(arguments, 2);
  5627. args.unshift(null);
  5628. this.iterate('alive', true, Phaser.Group.RETURN_TOTAL, callback, callbackContext, args);
  5629. };
  5630. /**
  5631. * 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.
  5632. * You can add as many parameters as you like, which will all be passed to the callback along with the child.
  5633. * For example: Group.forEachDead(bringToLife, this)
  5634. *
  5635. * @method Phaser.Group#forEachDead
  5636. * @param {function} callback - The function that will be called. Each child of the Group will be passed to it as its first parameter.
  5637. * @param {Object} callbackContext - The context in which the function should be called (usually 'this').
  5638. */
  5639. Phaser.Group.prototype.forEachDead = function (callback, callbackContext) {
  5640. var args = Array.prototype.splice.call(arguments, 2);
  5641. args.unshift(null);
  5642. this.iterate('alive', false, Phaser.Group.RETURN_TOTAL, callback, callbackContext, args);
  5643. };
  5644. /**
  5645. * Call this function to sort the group according to a particular value and order.
  5646. * 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()`.
  5647. *
  5648. * @method Phaser.Group#sort
  5649. * @param {string} [index='z'] - The `string` name of the property you want to sort on. Defaults to the objects z-depth value.
  5650. * @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.
  5651. */
  5652. Phaser.Group.prototype.sort = function (index, order) {
  5653. if (this.children.length < 2)
  5654. {
  5655. // Nothing to swap
  5656. return;
  5657. }
  5658. if (typeof index === 'undefined') { index = 'z'; }
  5659. if (typeof order === 'undefined') { order = Phaser.Group.SORT_ASCENDING; }
  5660. this._sortProperty = index;
  5661. if (order === Phaser.Group.SORT_ASCENDING)
  5662. {
  5663. this.children.sort(this.ascendingSortHandler.bind(this));
  5664. }
  5665. else
  5666. {
  5667. this.children.sort(this.descendingSortHandler.bind(this));
  5668. }
  5669. this.updateZ();
  5670. };
  5671. /**
  5672. * This allows you to use your own sort handler function.
  5673. * 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.
  5674. *
  5675. * @method Phaser.Group#customSort
  5676. * @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.
  5677. * @param {object} context - The scope in which the sortHandler is called.
  5678. */
  5679. Phaser.Group.prototype.customSort = function (sortHandler, context) {
  5680. if (this.children.length < 2)
  5681. {
  5682. // Nothing to swap
  5683. return;
  5684. }
  5685. this.children.sort(sortHandler.bind(context));
  5686. this.updateZ();
  5687. };
  5688. /**
  5689. * An internal helper function for the sort process.
  5690. *
  5691. * @method Phaser.Group#ascendingSortHandler
  5692. * @param {object} a - The first object being sorted.
  5693. * @param {object} b - The second object being sorted.
  5694. */
  5695. Phaser.Group.prototype.ascendingSortHandler = function (a, b) {
  5696. if (a[this._sortProperty] < b[this._sortProperty])
  5697. {
  5698. return -1;
  5699. }
  5700. else if (a[this._sortProperty] > b[this._sortProperty])
  5701. {
  5702. return 1;
  5703. }
  5704. else
  5705. {
  5706. if (a.z < b.z)
  5707. {
  5708. return -1;
  5709. }
  5710. else
  5711. {
  5712. return 1;
  5713. }
  5714. }
  5715. };
  5716. /**
  5717. * An internal helper function for the sort process.
  5718. *
  5719. * @method Phaser.Group#descendingSortHandler
  5720. * @param {object} a - The first object being sorted.
  5721. * @param {object} b - The second object being sorted.
  5722. */
  5723. Phaser.Group.prototype.descendingSortHandler = function (a, b) {
  5724. if (a[this._sortProperty] < b[this._sortProperty])
  5725. {
  5726. return 1;
  5727. }
  5728. else if (a[this._sortProperty] > b[this._sortProperty])
  5729. {
  5730. return -1;
  5731. }
  5732. else
  5733. {
  5734. return 0;
  5735. }
  5736. };
  5737. /**
  5738. * 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.
  5739. * Matched children can be sent to the optional callback, or simply returned or counted.
  5740. * 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.
  5741. *
  5742. * @method Phaser.Group#iterate
  5743. * @param {string} key - The child property to check, i.e. 'exists', 'alive', 'health'
  5744. * @param {any} value - If child.key === this value it will be considered a match. Note that a strict comparison is used.
  5745. * @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.
  5746. * @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.
  5747. * @param {Object} [callbackContext] - The context in which the function should be called (usually 'this').
  5748. * @return {any} Returns either a numeric total (if RETURN_TOTAL was specified) or the child object.
  5749. */
  5750. Phaser.Group.prototype.iterate = function (key, value, returnType, callback, callbackContext, args) {
  5751. if (returnType === Phaser.Group.RETURN_TOTAL && this.children.length === 0)
  5752. {
  5753. return 0;
  5754. }
  5755. if (typeof callback === 'undefined')
  5756. {
  5757. callback = false;
  5758. }
  5759. var total = 0;
  5760. for (var i = 0, len = this.children.length; i < len; i++)
  5761. {
  5762. if (this.children[i][key] === value)
  5763. {
  5764. total++;
  5765. if (callback)
  5766. {
  5767. args[0] = this.children[i];
  5768. callback.apply(callbackContext, args);
  5769. }
  5770. if (returnType === Phaser.Group.RETURN_CHILD)
  5771. {
  5772. return this.children[i];
  5773. }
  5774. }
  5775. }
  5776. if (returnType === Phaser.Group.RETURN_TOTAL)
  5777. {
  5778. return total;
  5779. }
  5780. else if (returnType === Phaser.Group.RETURN_CHILD)
  5781. {
  5782. return null;
  5783. }
  5784. };
  5785. /**
  5786. * Call this function to retrieve the first object with exists == (the given state) in the Group.
  5787. *
  5788. * @method Phaser.Group#getFirstExists
  5789. * @param {boolean} state - True or false.
  5790. * @return {Any} The first child, or null if none found.
  5791. */
  5792. Phaser.Group.prototype.getFirstExists = function (state) {
  5793. if (typeof state !== 'boolean')
  5794. {
  5795. state = true;
  5796. }
  5797. return this.iterate('exists', state, Phaser.Group.RETURN_CHILD);
  5798. };
  5799. /**
  5800. * Call this function to retrieve the first object with alive === true in the group.
  5801. * This is handy for checking if everything has been wiped out, or choosing a squad leader, etc.
  5802. *
  5803. * @method Phaser.Group#getFirstAlive
  5804. * @return {Any} The first alive child, or null if none found.
  5805. */
  5806. Phaser.Group.prototype.getFirstAlive = function () {
  5807. return this.iterate('alive', true, Phaser.Group.RETURN_CHILD);
  5808. };
  5809. /**
  5810. * Call this function to retrieve the first object with alive === false in the group.
  5811. * This is handy for checking if everything has been wiped out, or choosing a squad leader, etc.
  5812. *
  5813. * @method Phaser.Group#getFirstDead
  5814. * @return {Any} The first dead child, or null if none found.
  5815. */
  5816. Phaser.Group.prototype.getFirstDead = function () {
  5817. return this.iterate('alive', false, Phaser.Group.RETURN_CHILD);
  5818. };
  5819. /**
  5820. * Returns the child at the top of this Group. The top is the one being displayed (rendered) above every other child.
  5821. *
  5822. * @method Phaser.Group#getTop
  5823. * @return {Any} The child at the top of the Group.
  5824. */
  5825. Phaser.Group.prototype.getTop = function () {
  5826. if (this.children.length > 0)
  5827. {
  5828. return this.children[this.children.length - 1];
  5829. }
  5830. };
  5831. /**
  5832. * Returns the child at the bottom of this Group. The bottom is the one being displayed (rendered) below every other child.
  5833. *
  5834. * @method Phaser.Group#getBottom
  5835. * @return {Any} The child at the bottom of the Group.
  5836. */
  5837. Phaser.Group.prototype.getBottom = function () {
  5838. if (this.children.length > 0)
  5839. {
  5840. return this.children[0];
  5841. }
  5842. };
  5843. /**
  5844. * Call this function to find out how many members of the group are alive.
  5845. *
  5846. * @method Phaser.Group#countLiving
  5847. * @return {number} The number of children flagged as alive.
  5848. */
  5849. Phaser.Group.prototype.countLiving = function () {
  5850. return this.iterate('alive', true, Phaser.Group.RETURN_TOTAL);
  5851. };
  5852. /**
  5853. * Call this function to find out how many members of the group are dead.
  5854. *
  5855. * @method Phaser.Group#countDead
  5856. * @return {number} The number of children flagged as dead.
  5857. */
  5858. Phaser.Group.prototype.countDead = function () {
  5859. return this.iterate('alive', false, Phaser.Group.RETURN_TOTAL);
  5860. };
  5861. /**
  5862. * Returns a member at random from the group.
  5863. *
  5864. * @method Phaser.Group#getRandom
  5865. * @param {number} startIndex - Optional offset off the front of the array. Default value is 0, or the beginning of the array.
  5866. * @param {number} length - Optional restriction on the number of values you want to randomly select from.
  5867. * @return {Any} A random child of this Group.
  5868. */
  5869. Phaser.Group.prototype.getRandom = function (startIndex, length) {
  5870. if (this.children.length === 0)
  5871. {
  5872. return null;
  5873. }
  5874. startIndex = startIndex || 0;
  5875. length = length || this.children.length;
  5876. return this.game.math.getRandom(this.children, startIndex, length);
  5877. };
  5878. /**
  5879. * Removes the given child from this Group and sets its group property to null.
  5880. *
  5881. * @method Phaser.Group#remove
  5882. * @param {Any} child - The child to remove.
  5883. * @param {boolean} [destroy=false] - You can optionally call destroy on the child that was removed.
  5884. * @return {boolean} true if the child was removed from this Group, otherwise false.
  5885. */
  5886. Phaser.Group.prototype.remove = function (child, destroy) {
  5887. if (typeof destroy === 'undefined') { destroy = false; }
  5888. if (this.children.length === 0)
  5889. {
  5890. return false;
  5891. }
  5892. if (child.events)
  5893. {
  5894. child.events.onRemovedFromGroup.dispatch(child, this);
  5895. }
  5896. this.removeChild(child);
  5897. this.updateZ();
  5898. if (this.cursor === child)
  5899. {
  5900. this.next();
  5901. }
  5902. if (destroy)
  5903. {
  5904. child.destroy();
  5905. }
  5906. return true;
  5907. };
  5908. /**
  5909. * Removes all children from this Group, setting all group properties to null.
  5910. * The Group container remains on the display list.
  5911. *
  5912. * @method Phaser.Group#removeAll
  5913. * @param {boolean} [destroy=false] - You can optionally call destroy on the child that was removed.
  5914. */
  5915. Phaser.Group.prototype.removeAll = function (destroy) {
  5916. if (typeof destroy === 'undefined') { destroy = false; }
  5917. if (this.children.length === 0)
  5918. {
  5919. return;
  5920. }
  5921. do
  5922. {
  5923. if (this.children[0].events)
  5924. {
  5925. this.children[0].events.onRemovedFromGroup.dispatch(this.children[0], this);
  5926. }
  5927. this.removeChild(this.children[0]);
  5928. if (destroy)
  5929. {
  5930. this.children[0].destroy();
  5931. }
  5932. }
  5933. while (this.children.length > 0);
  5934. this.cursor = null;
  5935. };
  5936. /**
  5937. * Removes all children from this Group whos index falls beteen the given startIndex and endIndex values.
  5938. *
  5939. * @method Phaser.Group#removeBetween
  5940. * @param {number} startIndex - The index to start removing children from.
  5941. * @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.
  5942. * @param {boolean} [destroy=false] - You can optionally call destroy on the child that was removed.
  5943. */
  5944. Phaser.Group.prototype.removeBetween = function (startIndex, endIndex, destroy) {
  5945. if (typeof endIndex === 'undefined') { endIndex = this.children.length; }
  5946. if (typeof destroy === 'undefined') { destroy = false; }
  5947. if (this.children.length === 0)
  5948. {
  5949. return;
  5950. }
  5951. if (startIndex > endIndex || startIndex < 0 || endIndex > this.children.length)
  5952. {
  5953. return false;
  5954. }
  5955. var i = endIndex;
  5956. while (i >= startIndex)
  5957. {
  5958. if (this.children[i].events)
  5959. {
  5960. this.children[i].events.onRemovedFromGroup.dispatch(this.children[i], this);
  5961. }
  5962. this.removeChild(this.children[i]);
  5963. if (destroy)
  5964. {
  5965. this.children[i].destroy();
  5966. }
  5967. if (this.cursor === this.children[i])
  5968. {
  5969. this.cursor = null;
  5970. }
  5971. i--;
  5972. }
  5973. this.updateZ();
  5974. };
  5975. /**
  5976. * Destroys this Group. Removes all children, then removes the container from the display list and nulls references.
  5977. *
  5978. * @method Phaser.Group#destroy
  5979. * @param {boolean} [destroyChildren=true] - Should every child of this Group have its destroy method called?
  5980. * @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.
  5981. */
  5982. Phaser.Group.prototype.destroy = function (destroyChildren, soft) {
  5983. if (this.game === null) { return; }
  5984. if (typeof destroyChildren === 'undefined') { destroyChildren = true; }
  5985. if (typeof soft === 'undefined') { soft = false; }
  5986. if (destroyChildren)
  5987. {
  5988. if (this.children.length > 0)
  5989. {
  5990. do
  5991. {
  5992. if (this.children[0].parent)
  5993. {
  5994. this.children[0].destroy(destroyChildren);
  5995. }
  5996. }
  5997. while (this.children.length > 0);
  5998. }
  5999. }
  6000. else
  6001. {
  6002. this.removeAll();
  6003. }
  6004. this.cursor = null;
  6005. if (!soft)
  6006. {
  6007. this.parent.removeChild(this);
  6008. this.game = null;
  6009. this.exists = false;
  6010. }
  6011. };
  6012. /**
  6013. * @name Phaser.Group#total
  6014. * @property {number} total - The total number of children in this Group who have a state of exists = true.
  6015. * @readonly
  6016. */
  6017. Object.defineProperty(Phaser.Group.prototype, "total", {
  6018. get: function () {
  6019. return this.iterate('exists', true, Phaser.Group.RETURN_TOTAL);
  6020. }
  6021. });
  6022. /**
  6023. * @name Phaser.Group#length
  6024. * @property {number} length - The total number of children in this Group, regardless of their exists/alive status.
  6025. * @readonly
  6026. */
  6027. Object.defineProperty(Phaser.Group.prototype, "length", {
  6028. get: function () {
  6029. return this.children.length;
  6030. }
  6031. });
  6032. /**
  6033. * The angle of rotation of the Group container. This will adjust the Group container itself by modifying its rotation.
  6034. * This will have no impact on the rotation value of its children, but it will update their worldTransform and on-screen position.
  6035. * @name Phaser.Group#angle
  6036. * @property {number} angle - The angle of rotation given in degrees, where 0 degrees = to the right.
  6037. */
  6038. Object.defineProperty(Phaser.Group.prototype, "angle", {
  6039. get: function() {
  6040. return Phaser.Math.radToDeg(this.rotation);
  6041. },
  6042. set: function(value) {
  6043. this.rotation = Phaser.Math.degToRad(value);
  6044. }
  6045. });
  6046. /**
  6047. * 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.
  6048. * Note that the cameraOffset values are in addition to any parent in the display list.
  6049. * So if this Group was in a Group that has x: 200, then this will be added to the cameraOffset.x
  6050. *
  6051. * @name Phaser.Group#fixedToCamera
  6052. * @property {boolean} fixedToCamera - Set to true to fix this Group to the Camera at its current world coordinates.
  6053. */
  6054. Object.defineProperty(Phaser.Group.prototype, "fixedToCamera", {
  6055. get: function () {
  6056. return !!this._cache[7];
  6057. },
  6058. set: function (value) {
  6059. if (value)
  6060. {
  6061. this._cache[7] = 1;
  6062. this.cameraOffset.set(this.x, this.y);
  6063. }
  6064. else
  6065. {
  6066. this._cache[7] = 0;
  6067. }
  6068. }
  6069. });
  6070. // Documentation stubs
  6071. /**
  6072. * The x coordinate of the Group container. You can adjust the Group container itself by modifying its coordinates.
  6073. * This will have no impact on the x/y coordinates of its children, but it will update their worldTransform and on-screen position.
  6074. * @name Phaser.Group#x
  6075. * @property {number} x - The x coordinate of the Group container.
  6076. */
  6077. /**
  6078. * The y coordinate of the Group container. You can adjust the Group container itself by modifying its coordinates.
  6079. * This will have no impact on the x/y coordinates of its children, but it will update their worldTransform and on-screen position.
  6080. * @name Phaser.Group#y
  6081. * @property {number} y - The y coordinate of the Group container.
  6082. */
  6083. /**
  6084. * The angle of rotation of the Group container. This will adjust the Group container itself by modifying its rotation.
  6085. * This will have no impact on the rotation value of its children, but it will update their worldTransform and on-screen position.
  6086. * @name Phaser.Group#rotation
  6087. * @property {number} rotation - The angle of rotation given in radians.
  6088. */
  6089. /**
  6090. * @name Phaser.Group#visible
  6091. * @property {boolean} visible - The visible state of the Group. Non-visible Groups and all of their children are not rendered.
  6092. */
  6093. /**
  6094. * @name Phaser.Group#alpha
  6095. * @property {number} alpha - The alpha value of the Group container.
  6096. */
  6097. /**
  6098. * @author Richard Davey <rich@photonstorm.com>
  6099. * @copyright 2014 Photon Storm Ltd.
  6100. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  6101. */
  6102. /**
  6103. * "This world is but a canvas to our imagination." - Henry David Thoreau
  6104. *
  6105. * A game has only one world. The world is an abstract place in which all game objects live. It is not bound
  6106. * by stage limits and can be any size. You look into the world via cameras. All game objects live within
  6107. * the world at world-based coordinates. By default a world is created the same size as your Stage.
  6108. *
  6109. * @class Phaser.World
  6110. * @extends Phaser.Group
  6111. * @constructor
  6112. * @param {Phaser.Game} game - Reference to the current game instance.
  6113. */
  6114. Phaser.World = function (game) {
  6115. Phaser.Group.call(this, game, null, '__world', false);
  6116. /**
  6117. * 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.
  6118. * 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.
  6119. * 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.
  6120. * 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.
  6121. * @property {Phaser.Rectangle} bounds - Bound of this world that objects can not escape from.
  6122. */
  6123. this.bounds = new Phaser.Rectangle(0, 0, game.width, game.height);
  6124. /**
  6125. * @property {Phaser.Camera} camera - Camera instance.
  6126. */
  6127. this.camera = null;
  6128. };
  6129. Phaser.World.prototype = Object.create(Phaser.Group.prototype);
  6130. Phaser.World.prototype.constructor = Phaser.World;
  6131. /**
  6132. * Initialises the game world.
  6133. *
  6134. * @method Phaser.World#boot
  6135. * @protected
  6136. */
  6137. Phaser.World.prototype.boot = function () {
  6138. this.camera = new Phaser.Camera(this.game, 0, 0, 0, this.game.width, this.game.height);
  6139. this.camera.displayObject = this;
  6140. this.camera.scale = this.scale;
  6141. this.game.camera = this.camera;
  6142. this.game.stage.addChild(this);
  6143. };
  6144. /**
  6145. * Updates the size of this world. Note that this doesn't modify the world x/y coordinates, just the width and height.
  6146. *
  6147. * @method Phaser.World#setBounds
  6148. * @param {number} x - Top left most corner of the world.
  6149. * @param {number} y - Top left most corner of the world.
  6150. * @param {number} width - New width of the world. Can never be smaller than the Game.width.
  6151. * @param {number} height - New height of the world. Can never be smaller than the Game.height.
  6152. */
  6153. Phaser.World.prototype.setBounds = function (x, y, width, height) {
  6154. if (width < this.game.width)
  6155. {
  6156. width = this.game.width;
  6157. }
  6158. if (height < this.game.height)
  6159. {
  6160. height = this.game.height;
  6161. }
  6162. this.bounds.setTo(x, y, width, height);
  6163. if (this.camera.bounds)
  6164. {
  6165. // The Camera can never be smaller than the game size
  6166. this.camera.bounds.setTo(x, y, width, height);
  6167. }
  6168. this.game.physics.setBoundsToWorld();
  6169. };
  6170. /**
  6171. * Destroyer of worlds.
  6172. *
  6173. * @method Phaser.World#shutdown
  6174. */
  6175. Phaser.World.prototype.shutdown = function () {
  6176. // World is a Group, so run a soft destruction on this and all children.
  6177. this.destroy(true, true);
  6178. };
  6179. /**
  6180. * @name Phaser.World#width
  6181. * @property {number} width - Gets or sets the current width of the game world.
  6182. */
  6183. Object.defineProperty(Phaser.World.prototype, "width", {
  6184. get: function () {
  6185. return this.bounds.width;
  6186. },
  6187. set: function (value) {
  6188. this.bounds.width = value;
  6189. }
  6190. });
  6191. /**
  6192. * @name Phaser.World#height
  6193. * @property {number} height - Gets or sets the current height of the game world.
  6194. */
  6195. Object.defineProperty(Phaser.World.prototype, "height", {
  6196. get: function () {
  6197. return this.bounds.height;
  6198. },
  6199. set: function (value) {
  6200. this.bounds.height = value;
  6201. }
  6202. });
  6203. /**
  6204. * @name Phaser.World#centerX
  6205. * @property {number} centerX - Gets the X position corresponding to the center point of the world.
  6206. * @readonly
  6207. */
  6208. Object.defineProperty(Phaser.World.prototype, "centerX", {
  6209. get: function () {
  6210. return this.bounds.halfWidth;
  6211. }
  6212. });
  6213. /**
  6214. * @name Phaser.World#centerY
  6215. * @property {number} centerY - Gets the Y position corresponding to the center point of the world.
  6216. * @readonly
  6217. */
  6218. Object.defineProperty(Phaser.World.prototype, "centerY", {
  6219. get: function () {
  6220. return this.bounds.halfHeight;
  6221. }
  6222. });
  6223. /**
  6224. * @name Phaser.World#randomX
  6225. * @property {number} randomX - Gets a random integer which is lesser than or equal to the current width of the game world.
  6226. * @readonly
  6227. */
  6228. Object.defineProperty(Phaser.World.prototype, "randomX", {
  6229. get: function () {
  6230. if (this.bounds.x < 0)
  6231. {
  6232. return this.game.rnd.integerInRange(this.bounds.x, (this.bounds.width - Math.abs(this.bounds.x)));
  6233. }
  6234. else
  6235. {
  6236. return this.game.rnd.integerInRange(this.bounds.x, this.bounds.width);
  6237. }
  6238. }
  6239. });
  6240. /**
  6241. * @name Phaser.World#randomY
  6242. * @property {number} randomY - Gets a random integer which is lesser than or equal to the current height of the game world.
  6243. * @readonly
  6244. */
  6245. Object.defineProperty(Phaser.World.prototype, "randomY", {
  6246. get: function () {
  6247. if (this.bounds.y < 0)
  6248. {
  6249. return this.game.rnd.integerInRange(this.bounds.y, (this.bounds.height - Math.abs(this.bounds.y)));
  6250. }
  6251. else
  6252. {
  6253. return this.game.rnd.integerInRange(this.bounds.y, this.bounds.height);
  6254. }
  6255. }
  6256. });
  6257. /**
  6258. * @author Richard Davey <rich@photonstorm.com>
  6259. * @copyright 2014 Photon Storm Ltd.
  6260. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  6261. */
  6262. /**
  6263. * The ScaleManager object is responsible for helping you manage the scaling, resizing and alignment of your game within the browser.
  6264. *
  6265. * @class Phaser.ScaleManager
  6266. * @constructor
  6267. * @param {Phaser.Game} game - A reference to the currently running game.
  6268. * @param {number} width - The native width of the game.
  6269. * @param {number} height - The native height of the game.
  6270. */
  6271. Phaser.ScaleManager = function (game, width, height) {
  6272. /**
  6273. * @property {Phaser.Game} game - A reference to the currently running game.
  6274. */
  6275. this.game = game;
  6276. /**
  6277. * @property {number} width - Width of the stage after calculation.
  6278. */
  6279. this.width = width;
  6280. /**
  6281. * @property {number} height - Height of the stage after calculation.
  6282. */
  6283. this.height = height;
  6284. /**
  6285. * @property {number} minWidth - Minimum width the canvas should be scaled to (in pixels).
  6286. */
  6287. this.minWidth = null;
  6288. /**
  6289. * @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.
  6290. */
  6291. this.maxWidth = null;
  6292. /**
  6293. * @property {number} minHeight - Minimum height the canvas should be scaled to (in pixels).
  6294. */
  6295. this.minHeight = null;
  6296. /**
  6297. * @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.
  6298. */
  6299. this.maxHeight = null;
  6300. /**
  6301. * @property {boolean} forceLandscape - If the game should be forced to use Landscape mode, this is set to true by Game.Stage
  6302. * @default
  6303. */
  6304. this.forceLandscape = false;
  6305. /**
  6306. * @property {boolean} forcePortrait - If the game should be forced to use Portrait mode, this is set to true by Game.Stage
  6307. * @default
  6308. */
  6309. this.forcePortrait = false;
  6310. /**
  6311. * @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.
  6312. * @default
  6313. */
  6314. this.incorrectOrientation = false;
  6315. /**
  6316. * @property {boolean} pageAlignHorizontally - If you wish to align your game in the middle of the page then you can set this value to true.
  6317. * It will place a re-calculated margin-left pixel value onto the canvas element which is updated on orientation/resizing.
  6318. * It doesn't care about any other DOM element that may be on the page, it literally just sets the margin.
  6319. * @default
  6320. */
  6321. this.pageAlignHorizontally = false;
  6322. /**
  6323. * @property {boolean} pageAlignVertically - If you wish to align your game in the middle of the page then you can set this value to true.
  6324. * It will place a re-calculated margin-left pixel value onto the canvas element which is updated on orientation/resizing.
  6325. * It doesn't care about any other DOM element that may be on the page, it literally just sets the margin.
  6326. * @default
  6327. */
  6328. this.pageAlignVertically = false;
  6329. /**
  6330. * @property {number} maxIterations - The maximum number of times it will try to resize the canvas to fill the browser.
  6331. * @default
  6332. */
  6333. this.maxIterations = 5;
  6334. /**
  6335. * @property {PIXI.Sprite} orientationSprite - The Sprite that is optionally displayed if the browser enters an unsupported orientation.
  6336. */
  6337. this.orientationSprite = null;
  6338. /**
  6339. * @property {Phaser.Signal} enterLandscape - The event that is dispatched when the browser enters landscape orientation.
  6340. */
  6341. this.enterLandscape = new Phaser.Signal();
  6342. /**
  6343. * @property {Phaser.Signal} enterPortrait - The event that is dispatched when the browser enters horizontal orientation.
  6344. */
  6345. this.enterPortrait = new Phaser.Signal();
  6346. /**
  6347. * @property {Phaser.Signal} enterIncorrectOrientation - The event that is dispatched when the browser enters an incorrect orientation, as defined by forceOrientation.
  6348. */
  6349. this.enterIncorrectOrientation = new Phaser.Signal();
  6350. /**
  6351. * @property {Phaser.Signal} leaveIncorrectOrientation - The event that is dispatched when the browser leaves an incorrect orientation, as defined by forceOrientation.
  6352. */
  6353. this.leaveIncorrectOrientation = new Phaser.Signal();
  6354. /**
  6355. * @property {Phaser.Signal} hasResized - The event that is dispatched when the game scale changes.
  6356. */
  6357. this.hasResized = new Phaser.Signal();
  6358. /**
  6359. * 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.
  6360. * 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.
  6361. * Note that if you use a scale property of EXACT_FIT then fullScreenTarget will have its width and height style set to 100%.
  6362. * @property {any} fullScreenTarget
  6363. */
  6364. this.fullScreenTarget = this.game.canvas;
  6365. /**
  6366. * @property {Phaser.Signal} enterFullScreen - The event that is dispatched when the browser enters full screen mode (if it supports the FullScreen API).
  6367. */
  6368. this.enterFullScreen = new Phaser.Signal();
  6369. /**
  6370. * @property {Phaser.Signal} leaveFullScreen - The event that is dispatched when the browser leaves full screen mode (if it supports the FullScreen API).
  6371. */
  6372. this.leaveFullScreen = new Phaser.Signal();
  6373. /**
  6374. * @property {number} orientation - The orientation value of the game (as defined by window.orientation if set). 90 = landscape. 0 = portrait.
  6375. */
  6376. this.orientation = 0;
  6377. if (window['orientation'])
  6378. {
  6379. this.orientation = window['orientation'];
  6380. }
  6381. else
  6382. {
  6383. if (window.outerWidth > window.outerHeight)
  6384. {
  6385. this.orientation = 90;
  6386. }
  6387. }
  6388. /**
  6389. * @property {Phaser.Point} scaleFactor - The scale factor based on the game dimensions vs. the scaled dimensions.
  6390. * @readonly
  6391. */
  6392. this.scaleFactor = new Phaser.Point(1, 1);
  6393. /**
  6394. * @property {Phaser.Point} scaleFactorInversed - The inversed scale factor. The displayed dimensions divided by the game dimensions.
  6395. * @readonly
  6396. */
  6397. this.scaleFactorInversed = new Phaser.Point(1, 1);
  6398. /**
  6399. * @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.
  6400. * @readonly
  6401. */
  6402. this.margin = new Phaser.Point(0, 0);
  6403. /**
  6404. * @property {number} aspectRatio - The aspect ratio of the scaled game.
  6405. * @readonly
  6406. */
  6407. this.aspectRatio = 0;
  6408. /**
  6409. * @property {number} sourceAspectRatio - The aspect ratio (width / height) of the original game dimensions.
  6410. * @readonly
  6411. */
  6412. this.sourceAspectRatio = width / height;
  6413. /**
  6414. * @property {any} event- The native browser events from full screen API changes.
  6415. */
  6416. this.event = null;
  6417. /**
  6418. * @property {number} scaleMode - The current scaleMode.
  6419. */
  6420. this.scaleMode = Phaser.ScaleManager.NO_SCALE;
  6421. /*
  6422. * @property {number} fullScreenScaleMode - Scale mode to be used in fullScreen
  6423. */
  6424. this.fullScreenScaleMode = Phaser.ScaleManager.NO_SCALE;
  6425. /**
  6426. * @property {number} _startHeight - Internal cache var. Stage height when starting the game.
  6427. * @private
  6428. */
  6429. this._startHeight = 0;
  6430. /**
  6431. * @property {number} _width - Cached stage width for full screen mode.
  6432. * @private
  6433. */
  6434. this._width = 0;
  6435. /**
  6436. * @property {number} _height - Cached stage height for full screen mode.
  6437. * @private
  6438. */
  6439. this._height = 0;
  6440. var _this = this;
  6441. window.addEventListener('orientationchange', function (event) {
  6442. return _this.checkOrientation(event);
  6443. }, false);
  6444. window.addEventListener('resize', function (event) {
  6445. return _this.checkResize(event);
  6446. }, false);
  6447. document.addEventListener('webkitfullscreenchange', function (event) {
  6448. return _this.fullScreenChange(event);
  6449. }, false);
  6450. document.addEventListener('mozfullscreenchange', function (event) {
  6451. return _this.fullScreenChange(event);
  6452. }, false);
  6453. document.addEventListener('fullscreenchange', function (event) {
  6454. return _this.fullScreenChange(event);
  6455. }, false);
  6456. };
  6457. /**
  6458. * @constant
  6459. * @type {number}
  6460. */
  6461. Phaser.ScaleManager.EXACT_FIT = 0;
  6462. /**
  6463. * @constant
  6464. * @type {number}
  6465. */
  6466. Phaser.ScaleManager.NO_SCALE = 1;
  6467. /**
  6468. * @constant
  6469. * @type {number}
  6470. */
  6471. Phaser.ScaleManager.SHOW_ALL = 2;
  6472. Phaser.ScaleManager.prototype = {
  6473. /**
  6474. * Tries to enter the browser into full screen mode.
  6475. * 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.
  6476. * @method Phaser.ScaleManager#startFullScreen
  6477. * @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)
  6478. */
  6479. startFullScreen: function (antialias) {
  6480. if (this.isFullScreen || !this.game.device.fullscreen)
  6481. {
  6482. return;
  6483. }
  6484. if (typeof antialias !== 'undefined' && this.game.renderType === Phaser.CANVAS)
  6485. {
  6486. this.game.stage.smoothed = antialias;
  6487. }
  6488. this._width = this.width;
  6489. this._height = this.height;
  6490. if (this.game.device.fullscreenKeyboard)
  6491. {
  6492. this.fullScreenTarget[this.game.device.requestFullscreen](Element.ALLOW_KEYBOARD_INPUT);
  6493. }
  6494. else
  6495. {
  6496. this.fullScreenTarget[this.game.device.requestFullscreen]();
  6497. }
  6498. },
  6499. /**
  6500. * Stops full screen mode if the browser is in it.
  6501. * @method Phaser.ScaleManager#stopFullScreen
  6502. */
  6503. stopFullScreen: function () {
  6504. this.fullScreenTarget[this.game.device.cancelFullscreen]();
  6505. },
  6506. /**
  6507. * Called automatically when the browser enters of leaves full screen mode.
  6508. * @method Phaser.ScaleManager#fullScreenChange
  6509. * @param {Event} event - The fullscreenchange event
  6510. * @protected
  6511. */
  6512. fullScreenChange: function (event) {
  6513. this.event = event;
  6514. if (this.isFullScreen)
  6515. {
  6516. if (this.fullScreenScaleMode === Phaser.ScaleManager.EXACT_FIT)
  6517. {
  6518. this.fullScreenTarget.style['width'] = '100%';
  6519. this.fullScreenTarget.style['height'] = '100%';
  6520. this.width = window.outerWidth;
  6521. this.height = window.outerHeight;
  6522. this.game.input.scale.setTo(this.game.width / this.width, this.game.height / this.height);
  6523. this.aspectRatio = this.width / this.height;
  6524. this.scaleFactor.x = this.game.width / this.width;
  6525. this.scaleFactor.y = this.game.height / this.height;
  6526. this.checkResize();
  6527. }
  6528. else if (this.fullScreenScaleMode === Phaser.ScaleManager.SHOW_ALL)
  6529. {
  6530. this.setShowAll();
  6531. this.refresh();
  6532. }
  6533. this.enterFullScreen.dispatch(this.width, this.height);
  6534. }
  6535. else
  6536. {
  6537. this.fullScreenTarget.style['width'] = this.game.width + 'px';
  6538. this.fullScreenTarget.style['height'] = this.game.height + 'px';
  6539. this.width = this._width;
  6540. this.height = this._height;
  6541. this.game.input.scale.setTo(this.game.width / this.width, this.game.height / this.height);
  6542. this.aspectRatio = this.width / this.height;
  6543. this.scaleFactor.x = this.game.width / this.width;
  6544. this.scaleFactor.y = this.game.height / this.height;
  6545. this.leaveFullScreen.dispatch(this.width, this.height);
  6546. }
  6547. },
  6548. /**
  6549. * If you need your game to run in only one orientation you can force that to happen.
  6550. * The optional orientationImage is displayed when the game is in the incorrect orientation.
  6551. * @method Phaser.ScaleManager#forceOrientation
  6552. * @param {boolean} forceLandscape - true if the game should run in landscape mode only.
  6553. * @param {boolean} [forcePortrait=false] - true if the game should run in portrait mode only.
  6554. * @param {string} [orientationImage=''] - The string of an image in the Phaser.Cache to display when this game is in the incorrect orientation.
  6555. */
  6556. forceOrientation: function (forceLandscape, forcePortrait, orientationImage) {
  6557. if (typeof forcePortrait === 'undefined') { forcePortrait = false; }
  6558. this.forceLandscape = forceLandscape;
  6559. this.forcePortrait = forcePortrait;
  6560. if (typeof orientationImage !== 'undefined')
  6561. {
  6562. if (orientationImage == null || this.game.cache.checkImageKey(orientationImage) === false)
  6563. {
  6564. orientationImage = '__default';
  6565. }
  6566. this.orientationSprite = new Phaser.Image(this.game, this.game.width / 2, this.game.height / 2, PIXI.TextureCache[orientationImage]);
  6567. this.orientationSprite.anchor.set(0.5);
  6568. this.checkOrientationState();
  6569. if (this.incorrectOrientation)
  6570. {
  6571. this.orientationSprite.visible = true;
  6572. this.game.world.visible = false;
  6573. }
  6574. else
  6575. {
  6576. this.orientationSprite.visible = false;
  6577. this.game.world.visible = true;
  6578. }
  6579. this.game.stage.addChild(this.orientationSprite);
  6580. }
  6581. },
  6582. /**
  6583. * Checks if the browser is in the correct orientation for your game (if forceLandscape or forcePortrait have been set)
  6584. * @method Phaser.ScaleManager#checkOrientationState
  6585. */
  6586. checkOrientationState: function () {
  6587. // They are in the wrong orientation
  6588. if (this.incorrectOrientation)
  6589. {
  6590. if ((this.forceLandscape && window.innerWidth > window.innerHeight) || (this.forcePortrait && window.innerHeight > window.innerWidth))
  6591. {
  6592. // Back to normal
  6593. this.incorrectOrientation = false;
  6594. this.leaveIncorrectOrientation.dispatch();
  6595. if (this.orientationSprite)
  6596. {
  6597. this.orientationSprite.visible = false;
  6598. this.game.world.visible = true;
  6599. }
  6600. if (this.scaleMode !== Phaser.ScaleManager.NO_SCALE)
  6601. {
  6602. this.refresh();
  6603. }
  6604. }
  6605. }
  6606. else
  6607. {
  6608. if ((this.forceLandscape && window.innerWidth < window.innerHeight) || (this.forcePortrait && window.innerHeight < window.innerWidth))
  6609. {
  6610. // Show orientation screen
  6611. this.incorrectOrientation = true;
  6612. this.enterIncorrectOrientation.dispatch();
  6613. if (this.orientationSprite && this.orientationSprite.visible === false)
  6614. {
  6615. this.orientationSprite.visible = true;
  6616. this.game.world.visible = false;
  6617. }
  6618. if (this.scaleMode !== Phaser.ScaleManager.NO_SCALE)
  6619. {
  6620. this.refresh();
  6621. }
  6622. }
  6623. }
  6624. },
  6625. /**
  6626. * Handle window.orientationchange events
  6627. * @method Phaser.ScaleManager#checkOrientation
  6628. * @param {Event} event - The orientationchange event data.
  6629. */
  6630. checkOrientation: function (event) {
  6631. this.event = event;
  6632. this.orientation = window['orientation'];
  6633. if (this.isLandscape)
  6634. {
  6635. this.enterLandscape.dispatch(this.orientation, true, false);
  6636. }
  6637. else
  6638. {
  6639. this.enterPortrait.dispatch(this.orientation, false, true);
  6640. }
  6641. if (this.scaleMode !== Phaser.ScaleManager.NO_SCALE)
  6642. {
  6643. this.refresh();
  6644. }
  6645. },
  6646. /**
  6647. * Handle window.resize events
  6648. * @method Phaser.ScaleManager#checkResize
  6649. * @param {Event} event - The resize event data.
  6650. */
  6651. checkResize: function (event) {
  6652. this.event = event;
  6653. if (window.outerWidth > window.outerHeight)
  6654. {
  6655. this.orientation = 90;
  6656. }
  6657. else
  6658. {
  6659. this.orientation = 0;
  6660. }
  6661. if (this.isLandscape)
  6662. {
  6663. this.enterLandscape.dispatch(this.orientation, true, false);
  6664. }
  6665. else
  6666. {
  6667. this.enterPortrait.dispatch(this.orientation, false, true);
  6668. }
  6669. if (this.scaleMode !== Phaser.ScaleManager.NO_SCALE)
  6670. {
  6671. this.refresh();
  6672. }
  6673. this.checkOrientationState();
  6674. },
  6675. /**
  6676. * Re-calculate scale mode and update screen size.
  6677. * @method Phaser.ScaleManager#refresh
  6678. */
  6679. refresh: function () {
  6680. // We can't do anything about the status bars in iPads, web apps or desktops
  6681. if (this.game.device.iPad === false && this.game.device.webApp === false && this.game.device.desktop === false)
  6682. {
  6683. if (this.game.device.android && this.game.device.chrome === false)
  6684. {
  6685. window.scrollTo(0, 1);
  6686. }
  6687. else
  6688. {
  6689. window.scrollTo(0, 0);
  6690. }
  6691. }
  6692. if (this._check == null && this.maxIterations > 0)
  6693. {
  6694. this._iterations = this.maxIterations;
  6695. var _this = this;
  6696. this._check = window.setInterval(function () {
  6697. return _this.setScreenSize();
  6698. }, 10);
  6699. this.setScreenSize();
  6700. }
  6701. },
  6702. /**
  6703. * Set screen size automatically based on the scaleMode.
  6704. * @param {boolean} force - If force is true it will try to resize the game regardless of the document dimensions.
  6705. */
  6706. setScreenSize: function (force) {
  6707. if (typeof force == 'undefined')
  6708. {
  6709. force = false;
  6710. }
  6711. if (this.game.device.iPad === false && this.game.device.webApp === false && this.game.device.desktop === false)
  6712. {
  6713. if (this.game.device.android && this.game.device.chrome === false)
  6714. {
  6715. window.scrollTo(0, 1);
  6716. }
  6717. else
  6718. {
  6719. window.scrollTo(0, 0);
  6720. }
  6721. }
  6722. this._iterations--;
  6723. if (force || window.innerHeight > this._startHeight || this._iterations < 0)
  6724. {
  6725. // Set minimum height of content to new window height
  6726. document.documentElement['style'].minHeight = window.innerHeight + 'px';
  6727. if (this.incorrectOrientation === true)
  6728. {
  6729. this.setMaximum();
  6730. }
  6731. else if (!this.isFullScreen)
  6732. {
  6733. if (this.scaleMode == Phaser.ScaleManager.EXACT_FIT)
  6734. {
  6735. this.setExactFit();
  6736. }
  6737. else if (this.scaleMode == Phaser.ScaleManager.SHOW_ALL)
  6738. {
  6739. this.setShowAll();
  6740. }
  6741. }
  6742. else
  6743. {
  6744. if (this.fullScreenScaleMode == Phaser.ScaleManager.EXACT_FIT)
  6745. {
  6746. this.setExactFit();
  6747. }
  6748. else if (this.fullScreenScaleMode == Phaser.ScaleManager.SHOW_ALL)
  6749. {
  6750. this.setShowAll();
  6751. }
  6752. }
  6753. this.setSize();
  6754. clearInterval(this._check);
  6755. this._check = null;
  6756. }
  6757. },
  6758. /**
  6759. * Sets the canvas style width and height values based on minWidth/Height and maxWidth/Height.
  6760. * @method Phaser.ScaleManager#setSize
  6761. */
  6762. setSize: function () {
  6763. if (this.incorrectOrientation === false)
  6764. {
  6765. if (this.maxWidth && this.width > this.maxWidth)
  6766. {
  6767. this.width = this.maxWidth;
  6768. }
  6769. if (this.maxHeight && this.height > this.maxHeight)
  6770. {
  6771. this.height = this.maxHeight;
  6772. }
  6773. if (this.minWidth && this.width < this.minWidth)
  6774. {
  6775. this.width = this.minWidth;
  6776. }
  6777. if (this.minHeight && this.height < this.minHeight)
  6778. {
  6779. this.height = this.minHeight;
  6780. }
  6781. }
  6782. this.game.canvas.style.width = this.width + 'px';
  6783. this.game.canvas.style.height = this.height + 'px';
  6784. this.game.input.scale.setTo(this.game.width / this.width, this.game.height / this.height);
  6785. if (this.pageAlignHorizontally)
  6786. {
  6787. if (this.width < window.innerWidth && this.incorrectOrientation === false)
  6788. {
  6789. this.margin.x = Math.round((window.innerWidth - this.width) / 2);
  6790. this.game.canvas.style.marginLeft = this.margin.x + 'px';
  6791. }
  6792. else
  6793. {
  6794. this.margin.x = 0;
  6795. this.game.canvas.style.marginLeft = '0px';
  6796. }
  6797. }
  6798. if (this.pageAlignVertically)
  6799. {
  6800. if (this.height < window.innerHeight && this.incorrectOrientation === false)
  6801. {
  6802. this.margin.y = Math.round((window.innerHeight - this.height) / 2);
  6803. this.game.canvas.style.marginTop = this.margin.y + 'px';
  6804. }
  6805. else
  6806. {
  6807. this.margin.y = 0;
  6808. this.game.canvas.style.marginTop = '0px';
  6809. }
  6810. }
  6811. Phaser.Canvas.getOffset(this.game.canvas, this.game.stage.offset);
  6812. this.aspectRatio = this.width / this.height;
  6813. this.scaleFactor.x = this.game.width / this.width;
  6814. this.scaleFactor.y = this.game.height / this.height;
  6815. this.scaleFactorInversed.x = this.width / this.game.width;
  6816. this.scaleFactorInversed.y = this.height / this.game.height;
  6817. this.hasResized.dispatch(this.width, this.height);
  6818. this.checkOrientationState();
  6819. },
  6820. /**
  6821. * Sets this.width equal to window.innerWidth and this.height equal to window.innerHeight
  6822. * @method Phaser.ScaleManager#setMaximum
  6823. */
  6824. setMaximum: function () {
  6825. this.width = window.innerWidth;
  6826. this.height = window.innerHeight;
  6827. },
  6828. /**
  6829. * Calculates the multiplier needed to scale the game proportionally.
  6830. * @method Phaser.ScaleManager#setShowAll
  6831. */
  6832. setShowAll: function () {
  6833. var multiplier = Math.min((window.innerHeight / this.game.height), (window.innerWidth / this.game.width));
  6834. this.width = Math.round(this.game.width * multiplier);
  6835. this.height = Math.round(this.game.height * multiplier);
  6836. },
  6837. /**
  6838. * Sets the width and height values of the canvas, no larger than the maxWidth/Height.
  6839. * @method Phaser.ScaleManager#setExactFit
  6840. */
  6841. setExactFit: function () {
  6842. var availableWidth = window.innerWidth;
  6843. var availableHeight = window.innerHeight;
  6844. if (this.maxWidth && availableWidth > this.maxWidth)
  6845. {
  6846. this.width = this.maxWidth;
  6847. }
  6848. else
  6849. {
  6850. this.width = availableWidth;
  6851. }
  6852. if (this.maxHeight && availableHeight > this.maxHeight)
  6853. {
  6854. this.height = this.maxHeight;
  6855. }
  6856. else
  6857. {
  6858. this.height = availableHeight;
  6859. }
  6860. }
  6861. };
  6862. Phaser.ScaleManager.prototype.constructor = Phaser.ScaleManager;
  6863. /**
  6864. * @name Phaser.ScaleManager#isFullScreen
  6865. * @property {boolean} isFullScreen - Returns true if the browser is in full screen mode, otherwise false.
  6866. * @readonly
  6867. */
  6868. Object.defineProperty(Phaser.ScaleManager.prototype, "isFullScreen", {
  6869. get: function () {
  6870. return (document['fullscreenElement'] || document['mozFullScreenElement'] || document['webkitFullscreenElement']);
  6871. }
  6872. });
  6873. /**
  6874. * @name Phaser.ScaleManager#isPortrait
  6875. * @property {boolean} isPortrait - Returns true if the browser dimensions match a portrait display.
  6876. * @readonly
  6877. */
  6878. Object.defineProperty(Phaser.ScaleManager.prototype, "isPortrait", {
  6879. get: function () {
  6880. return this.orientation === 0 || this.orientation == 180;
  6881. }
  6882. });
  6883. /**
  6884. * @name Phaser.ScaleManager#isLandscape
  6885. * @property {boolean} isLandscape - Returns true if the browser dimensions match a landscape display.
  6886. * @readonly
  6887. */
  6888. Object.defineProperty(Phaser.ScaleManager.prototype, "isLandscape", {
  6889. get: function () {
  6890. return this.orientation === 90 || this.orientation === -90;
  6891. }
  6892. });
  6893. /**
  6894. * @author Richard Davey <rich@photonstorm.com>
  6895. * @copyright 2014 Photon Storm Ltd.
  6896. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  6897. */
  6898. /**
  6899. * Game constructor
  6900. *
  6901. * Instantiate a new <code>Phaser.Game</code> object.
  6902. * @class Phaser.Game
  6903. * @classdesc This is where the magic happens. The Game object is the heart of your game,
  6904. * providing quick access to common functions and handling the boot process.
  6905. * "Hell, there are no rules here - we're trying to accomplish something."
  6906. * Thomas A. Edison
  6907. * @constructor
  6908. * @param {number} [width=800] - The width of your game in game pixels.
  6909. * @param {number} [height=600] - The height of your game in game pixels.
  6910. * @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).
  6911. * @param {string|HTMLElement} [parent=''] - The DOM element into which this games canvas will be injected. Either a DOM ID (string) or the element itself.
  6912. * @param {object} [state=null] - The default state object. A object consisting of Phaser.State functions (preload, create, update, render) or null.
  6913. * @param {boolean} [transparent=false] - Use a transparent canvas background or not.
  6914. * @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.
  6915. * @param {object} [physicsConfig=null] - A physics configuration object to pass to the Physics world on creation.
  6916. */
  6917. Phaser.Game = function (width, height, renderer, parent, state, transparent, antialias, physicsConfig) {
  6918. /**
  6919. * @property {number} id - Phaser Game ID (for when Pixi supports multiple instances).
  6920. */
  6921. this.id = Phaser.GAMES.push(this) - 1;
  6922. /**
  6923. * @property {object} config - The Phaser.Game configuration object.
  6924. */
  6925. this.config = null;
  6926. /**
  6927. * @property {object} physicsConfig - The Phaser.Physics.World configuration object.
  6928. */
  6929. this.physicsConfig = physicsConfig;
  6930. /**
  6931. * @property {string|HTMLElement} parent - The Games DOM parent.
  6932. * @default
  6933. */
  6934. this.parent = '';
  6935. /**
  6936. * @property {number} width - The Game width (in pixels).
  6937. * @default
  6938. */
  6939. this.width = 800;
  6940. /**
  6941. * @property {number} height - The Game height (in pixels).
  6942. * @default
  6943. */
  6944. this.height = 600;
  6945. /**
  6946. * @property {boolean} transparent - Use a transparent canvas background or not.
  6947. * @default
  6948. */
  6949. this.transparent = false;
  6950. /**
  6951. * @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.
  6952. * @default
  6953. */
  6954. this.antialias = true;
  6955. /**
  6956. * @property {PIXI.CanvasRenderer|PIXI.WebGLRenderer} renderer - The Pixi Renderer.
  6957. */
  6958. this.renderer = null;
  6959. /**
  6960. * @property {number} renderType - The Renderer this game will use. Either Phaser.AUTO, Phaser.CANVAS or Phaser.WEBGL.
  6961. */
  6962. this.renderType = Phaser.AUTO;
  6963. /**
  6964. * @property {Phaser.StateManager} state - The StateManager.
  6965. */
  6966. this.state = null;
  6967. /**
  6968. * @property {boolean} isBooted - Whether the game engine is booted, aka available.
  6969. * @default
  6970. */
  6971. this.isBooted = false;
  6972. /**
  6973. * @property {boolean} id -Is game running or paused?
  6974. * @default
  6975. */
  6976. this.isRunning = false;
  6977. /**
  6978. * @property {Phaser.RequestAnimationFrame} raf - Automatically handles the core game loop via requestAnimationFrame or setTimeout
  6979. */
  6980. this.raf = null;
  6981. /**
  6982. * @property {Phaser.GameObjectFactory} add - Reference to the Phaser.GameObjectFactory.
  6983. */
  6984. this.add = null;
  6985. /**
  6986. * @property {Phaser.GameObjectCreator} make - Reference to the GameObject Creator.
  6987. */
  6988. this.make = null;
  6989. /**
  6990. * @property {Phaser.Cache} cache - Reference to the assets cache.
  6991. */
  6992. this.cache = null;
  6993. /**
  6994. * @property {Phaser.Input} input - Reference to the input manager
  6995. */
  6996. this.input = null;
  6997. /**
  6998. * @property {Phaser.Loader} load - Reference to the assets loader.
  6999. */
  7000. this.load = null;
  7001. /**
  7002. * @property {Phaser.Math} math - Reference to the math helper.
  7003. */
  7004. this.math = null;
  7005. /**
  7006. * @property {Phaser.Net} net - Reference to the network class.
  7007. */
  7008. this.net = null;
  7009. /**
  7010. * @property {Phaser.ScaleManager} scale - The game scale manager.
  7011. */
  7012. this.scale = null;
  7013. /**
  7014. * @property {Phaser.SoundManager} sound - Reference to the sound manager.
  7015. */
  7016. this.sound = null;
  7017. /**
  7018. * @property {Phaser.Stage} stage - Reference to the stage.
  7019. */
  7020. this.stage = null;
  7021. /**
  7022. * @property {Phaser.Time} time - Reference to the core game clock.
  7023. */
  7024. this.time = null;
  7025. /**
  7026. * @property {Phaser.TweenManager} tweens - Reference to the tween manager.
  7027. */
  7028. this.tweens = null;
  7029. /**
  7030. * @property {Phaser.World} world - Reference to the world.
  7031. */
  7032. this.world = null;
  7033. /**
  7034. * @property {Phaser.Physics} physics - Reference to the physics manager.
  7035. */
  7036. this.physics = null;
  7037. /**
  7038. * @property {Phaser.RandomDataGenerator} rnd - Instance of repeatable random data generator helper.
  7039. */
  7040. this.rnd = null;
  7041. /**
  7042. * @property {Phaser.Device} device - Contains device information and capabilities.
  7043. */
  7044. this.device = null;
  7045. /**
  7046. * @property {Phaser.Camera} camera - A handy reference to world.camera.
  7047. */
  7048. this.camera = null;
  7049. /**
  7050. * @property {HTMLCanvasElement} canvas - A handy reference to renderer.view, the canvas that the game is being rendered in to.
  7051. */
  7052. this.canvas = null;
  7053. /**
  7054. * @property {CanvasRenderingContext2D} context - A handy reference to renderer.context (only set for CANVAS games, not WebGL)
  7055. */
  7056. this.context = null;
  7057. /**
  7058. * @property {Phaser.Utils.Debug} debug - A set of useful debug utilitie.
  7059. */
  7060. this.debug = null;
  7061. /**
  7062. * @property {Phaser.Particles} particles - The Particle Manager.
  7063. */
  7064. this.particles = null;
  7065. /**
  7066. * @property {boolean} stepping - Enable core loop stepping with Game.enableStep().
  7067. * @default
  7068. * @readonly
  7069. */
  7070. this.stepping = false;
  7071. /**
  7072. * @property {boolean} pendingStep - An internal property used by enableStep, but also useful to query from your own game objects.
  7073. * @default
  7074. * @readonly
  7075. */
  7076. this.pendingStep = false;
  7077. /**
  7078. * @property {number} stepCount - When stepping is enabled this contains the current step cycle.
  7079. * @default
  7080. * @readonly
  7081. */
  7082. this.stepCount = 0;
  7083. /**
  7084. * @property {Phaser.Signal} onPause - This event is fired when the game pauses.
  7085. */
  7086. this.onPause = null;
  7087. /**
  7088. * @property {Phaser.Signal} onResume - This event is fired when the game resumes from a paused state.
  7089. */
  7090. this.onResume = null;
  7091. /**
  7092. * @property {Phaser.Signal} onBlur - This event is fired when the game no longer has focus (typically on page hide).
  7093. */
  7094. this.onBlur = null;
  7095. /**
  7096. * @property {Phaser.Signal} onFocus - This event is fired when the game has focus (typically on page show).
  7097. */
  7098. this.onFocus = null;
  7099. /**
  7100. * @property {boolean} _paused - Is game paused?
  7101. * @private
  7102. */
  7103. this._paused = false;
  7104. /**
  7105. * @property {boolean} _codePaused - Was the game paused via code or a visibility change?
  7106. * @private
  7107. */
  7108. this._codePaused = false;
  7109. // Parse the configuration object (if any)
  7110. if (arguments.length === 1 && typeof arguments[0] === 'object')
  7111. {
  7112. this.parseConfig(arguments[0]);
  7113. }
  7114. else
  7115. {
  7116. if (typeof width !== 'undefined')
  7117. {
  7118. this.width = width;
  7119. }
  7120. if (typeof height !== 'undefined')
  7121. {
  7122. this.height = height;
  7123. }
  7124. if (typeof renderer !== 'undefined')
  7125. {
  7126. this.renderer = renderer;
  7127. this.renderType = renderer;
  7128. }
  7129. if (typeof parent !== 'undefined')
  7130. {
  7131. this.parent = parent;
  7132. }
  7133. if (typeof transparent !== 'undefined')
  7134. {
  7135. this.transparent = transparent;
  7136. }
  7137. if (typeof antialias !== 'undefined')
  7138. {
  7139. this.antialias = antialias;
  7140. }
  7141. this.rnd = new Phaser.RandomDataGenerator([(Date.now() * Math.random()).toString()]);
  7142. this.state = new Phaser.StateManager(this, state);
  7143. }
  7144. var _this = this;
  7145. this._onBoot = function () {
  7146. return _this.boot();
  7147. };
  7148. if (document.readyState === 'complete' || document.readyState === 'interactive')
  7149. {
  7150. window.setTimeout(this._onBoot, 0);
  7151. }
  7152. else
  7153. {
  7154. document.addEventListener('DOMContentLoaded', this._onBoot, false);
  7155. window.addEventListener('load', this._onBoot, false);
  7156. }
  7157. return this;
  7158. };
  7159. Phaser.Game.prototype = {
  7160. /**
  7161. * Parses a Game configuration object.
  7162. *
  7163. * @method Phaser.Game#parseConfig
  7164. * @protected
  7165. */
  7166. parseConfig: function (config) {
  7167. this.config = config;
  7168. if (config['width'])
  7169. {
  7170. this.width = Phaser.Utils.parseDimension(config['width'], 0);
  7171. }
  7172. if (config['height'])
  7173. {
  7174. this.height = Phaser.Utils.parseDimension(config['height'], 1);
  7175. }
  7176. if (config['renderer'])
  7177. {
  7178. this.renderer = config['renderer'];
  7179. this.renderType = config['renderer'];
  7180. }
  7181. if (config['parent'])
  7182. {
  7183. this.parent = config['parent'];
  7184. }
  7185. if (config['transparent'])
  7186. {
  7187. this.transparent = config['transparent'];
  7188. }
  7189. if (config['antialias'])
  7190. {
  7191. this.antialias = config['antialias'];
  7192. }
  7193. if (config['physicsConfig'])
  7194. {
  7195. this.physicsConfig = config['physicsConfig'];
  7196. }
  7197. var seed = [(Date.now() * Math.random()).toString()];
  7198. if (config['seed'])
  7199. {
  7200. seed = config['seed'];
  7201. }
  7202. this.rnd = new Phaser.RandomDataGenerator(seed);
  7203. var state = null;
  7204. if (config['state'])
  7205. {
  7206. state = config['state'];
  7207. }
  7208. this.state = new Phaser.StateManager(this, state);
  7209. },
  7210. /**
  7211. * Initialize engine sub modules and start the game.
  7212. *
  7213. * @method Phaser.Game#boot
  7214. * @protected
  7215. */
  7216. boot: function () {
  7217. if (this.isBooted)
  7218. {
  7219. return;
  7220. }
  7221. if (!document.body)
  7222. {
  7223. window.setTimeout(this._onBoot, 20);
  7224. }
  7225. else
  7226. {
  7227. document.removeEventListener('DOMContentLoaded', this._onBoot);
  7228. window.removeEventListener('load', this._onBoot);
  7229. this.onPause = new Phaser.Signal();
  7230. this.onResume = new Phaser.Signal();
  7231. this.onBlur = new Phaser.Signal();
  7232. this.onFocus = new Phaser.Signal();
  7233. this.isBooted = true;
  7234. this.device = new Phaser.Device(this);
  7235. this.math = Phaser.Math;
  7236. this.stage = new Phaser.Stage(this, this.width, this.height);
  7237. this.scale = new Phaser.ScaleManager(this, this.width, this.height);
  7238. this.setUpRenderer();
  7239. this.device.checkFullScreenSupport();
  7240. this.world = new Phaser.World(this);
  7241. this.add = new Phaser.GameObjectFactory(this);
  7242. this.make = new Phaser.GameObjectCreator(this);
  7243. this.cache = new Phaser.Cache(this);
  7244. this.load = new Phaser.Loader(this);
  7245. this.time = new Phaser.Time(this);
  7246. this.tweens = new Phaser.TweenManager(this);
  7247. this.input = new Phaser.Input(this);
  7248. this.sound = new Phaser.SoundManager(this);
  7249. this.physics = new Phaser.Physics(this, this.physicsConfig);
  7250. this.particles = new Phaser.Particles(this);
  7251. this.plugins = new Phaser.PluginManager(this);
  7252. this.net = new Phaser.Net(this);
  7253. this.debug = new Phaser.Utils.Debug(this);
  7254. this.time.boot();
  7255. this.stage.boot();
  7256. this.world.boot();
  7257. this.input.boot();
  7258. this.sound.boot();
  7259. this.state.boot();
  7260. this.debug.boot();
  7261. this.showDebugHeader();
  7262. this.isRunning = true;
  7263. if (this.config && this.config['forceSetTimeOut'])
  7264. {
  7265. this.raf = new Phaser.RequestAnimationFrame(this, this.config['forceSetTimeOut']);
  7266. }
  7267. else
  7268. {
  7269. this.raf = new Phaser.RequestAnimationFrame(this, false);
  7270. }
  7271. this.raf.start();
  7272. }
  7273. },
  7274. /**
  7275. * Displays a Phaser version debug header in the console.
  7276. *
  7277. * @method Phaser.Game#showDebugHeader
  7278. * @protected
  7279. */
  7280. showDebugHeader: function () {
  7281. var v = Phaser.DEV_VERSION;
  7282. var r = 'Canvas';
  7283. var a = 'HTML Audio';
  7284. var c = 1;
  7285. if (this.renderType === Phaser.WEBGL)
  7286. {
  7287. r = 'WebGL';
  7288. c++;
  7289. }
  7290. else if (this.renderType == Phaser.HEADLESS)
  7291. {
  7292. r = 'Headless';
  7293. }
  7294. if (this.device.webAudio)
  7295. {
  7296. a = 'WebAudio';
  7297. c++;
  7298. }
  7299. if (this.device.chrome)
  7300. {
  7301. var args = [
  7302. '%c %c %c Phaser v' + v + ' - ' + r + ' - ' + a + ' %c %c ' + ' http://phaser.io %c %c ♥%c♥%c♥ ',
  7303. 'background: #0cf300',
  7304. 'background: #00bc17',
  7305. 'color: #ffffff; background: #00711f;',
  7306. 'background: #00bc17',
  7307. 'background: #0cf300',
  7308. 'background: #00bc17'
  7309. ];
  7310. for (var i = 0; i < 3; i++)
  7311. {
  7312. if (i < c)
  7313. {
  7314. args.push('color: #ff2424; background: #fff');
  7315. }
  7316. else
  7317. {
  7318. args.push('color: #959595; background: #fff');
  7319. }
  7320. }
  7321. console.log.apply(console, args);
  7322. }
  7323. else
  7324. {
  7325. console.log('Phaser v' + v + ' - Renderer: ' + r + ' - Audio: ' + a + ' - http://phaser.io');
  7326. }
  7327. },
  7328. /**
  7329. * Checks if the device is capable of using the requested renderer and sets it up or an alternative if not.
  7330. *
  7331. * @method Phaser.Game#setUpRenderer
  7332. * @protected
  7333. */
  7334. setUpRenderer: function () {
  7335. if (this.device.trident)
  7336. {
  7337. // Pixi WebGL renderer on IE11 doesn't work correctly at the moment, the pre-multiplied alpha gets all washed out.
  7338. // 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?
  7339. this.renderType = Phaser.CANVAS;
  7340. }
  7341. if (this.renderType === Phaser.HEADLESS || this.renderType === Phaser.CANVAS || (this.renderType === Phaser.AUTO && this.device.webGL === false))
  7342. {
  7343. if (this.device.canvas)
  7344. {
  7345. if (this.renderType === Phaser.AUTO)
  7346. {
  7347. this.renderType = Phaser.CANVAS;
  7348. }
  7349. this.renderer = new PIXI.CanvasRenderer(this.width, this.height, this.canvas, this.transparent);
  7350. this.context = this.renderer.context;
  7351. }
  7352. else
  7353. {
  7354. throw new Error('Phaser.Game - cannot create Canvas or WebGL context, aborting.');
  7355. }
  7356. }
  7357. else
  7358. {
  7359. // They requested WebGL, and their browser supports it
  7360. this.renderType = Phaser.WEBGL;
  7361. this.renderer = new PIXI.WebGLRenderer(this.width, this.height, this.canvas, this.transparent, this.antialias);
  7362. this.context = null;
  7363. }
  7364. if (this.renderType !== Phaser.HEADLESS)
  7365. {
  7366. this.stage.smoothed = this.antialias;
  7367. Phaser.Canvas.addToDOM(this.canvas, this.parent, true);
  7368. Phaser.Canvas.setTouchAction(this.canvas);
  7369. }
  7370. },
  7371. /**
  7372. * The core game loop when in a paused state.
  7373. *
  7374. * @method Phaser.Game#update
  7375. * @protected
  7376. * @param {number} time - The current time as provided by RequestAnimationFrame.
  7377. */
  7378. update: function (time) {
  7379. this.time.update(time);
  7380. if (!this._paused && !this.pendingStep)
  7381. {
  7382. if (this.stepping)
  7383. {
  7384. this.pendingStep = true;
  7385. }
  7386. this.debug.preUpdate();
  7387. this.physics.preUpdate();
  7388. this.state.preUpdate();
  7389. this.plugins.preUpdate();
  7390. this.stage.preUpdate();
  7391. this.state.update();
  7392. this.stage.update();
  7393. this.tweens.update();
  7394. this.sound.update();
  7395. this.input.update();
  7396. // this.state.update();
  7397. this.physics.update();
  7398. this.particles.update();
  7399. this.plugins.update();
  7400. this.stage.postUpdate();
  7401. this.plugins.postUpdate();
  7402. }
  7403. else
  7404. {
  7405. this.debug.preUpdate();
  7406. }
  7407. if (this.renderType != Phaser.HEADLESS)
  7408. {
  7409. this.renderer.render(this.stage);
  7410. this.plugins.render();
  7411. this.state.render();
  7412. this.plugins.postRender();
  7413. }
  7414. },
  7415. /**
  7416. * Enable core game loop stepping. When enabled you must call game.step() directly (perhaps via a DOM button?)
  7417. * Calling step will advance the game loop by one frame. This is extremely useful for hard to track down errors!
  7418. *
  7419. * @method Phaser.Game#enableStep
  7420. */
  7421. enableStep: function () {
  7422. this.stepping = true;
  7423. this.pendingStep = false;
  7424. this.stepCount = 0;
  7425. },
  7426. /**
  7427. * Disables core game loop stepping.
  7428. *
  7429. * @method Phaser.Game#disableStep
  7430. */
  7431. disableStep: function () {
  7432. this.stepping = false;
  7433. this.pendingStep = false;
  7434. },
  7435. /**
  7436. * When stepping is enabled you must call this function directly (perhaps via a DOM button?) to advance the game loop by one frame.
  7437. * This is extremely useful to hard to track down errors! Use the internal stepCount property to monitor progress.
  7438. *
  7439. * @method Phaser.Game#step
  7440. */
  7441. step: function () {
  7442. this.pendingStep = false;
  7443. this.stepCount++;
  7444. },
  7445. /**
  7446. * Nuke the entire game from orbit
  7447. *
  7448. * @method Phaser.Game#destroy
  7449. */
  7450. destroy: function () {
  7451. this.raf.stop();
  7452. this.input.destroy();
  7453. this.state.destroy();
  7454. this.physics.destroy();
  7455. this.state = null;
  7456. this.cache = null;
  7457. this.input = null;
  7458. this.load = null;
  7459. this.sound = null;
  7460. this.stage = null;
  7461. this.time = null;
  7462. this.world = null;
  7463. this.isBooted = false;
  7464. },
  7465. /**
  7466. * Called by the Stage visibility handler.
  7467. *
  7468. * @method Phaser.Game#gamePaused
  7469. * @param {object} event - The DOM event that caused the game to pause, if any.
  7470. * @protected
  7471. */
  7472. gamePaused: function (event) {
  7473. // If the game is already paused it was done via game code, so don't re-pause it
  7474. if (!this._paused)
  7475. {
  7476. this._paused = true;
  7477. this.time.gamePaused();
  7478. this.sound.setMute();
  7479. this.onPause.dispatch(event);
  7480. }
  7481. },
  7482. /**
  7483. * Called by the Stage visibility handler.
  7484. *
  7485. * @method Phaser.Game#gameResumed
  7486. * @param {object} event - The DOM event that caused the game to pause, if any.
  7487. * @protected
  7488. */
  7489. gameResumed: function (event) {
  7490. // Game is paused, but wasn't paused via code, so resume it
  7491. if (this._paused && !this._codePaused)
  7492. {
  7493. this._paused = false;
  7494. this.time.gameResumed();
  7495. this.input.reset();
  7496. this.sound.unsetMute();
  7497. this.onResume.dispatch(event);
  7498. }
  7499. },
  7500. /**
  7501. * Called by the Stage visibility handler.
  7502. *
  7503. * @method Phaser.Game#focusLoss
  7504. * @param {object} event - The DOM event that caused the game to pause, if any.
  7505. * @protected
  7506. */
  7507. focusLoss: function (event) {
  7508. this.onBlur.dispatch(event);
  7509. this.gamePaused(event);
  7510. },
  7511. /**
  7512. * Called by the Stage visibility handler.
  7513. *
  7514. * @method Phaser.Game#focusGain
  7515. * @param {object} event - The DOM event that caused the game to pause, if any.
  7516. * @protected
  7517. */
  7518. focusGain: function (event) {
  7519. this.onFocus.dispatch(event);
  7520. this.gameResumed(event);
  7521. }
  7522. };
  7523. Phaser.Game.prototype.constructor = Phaser.Game;
  7524. /**
  7525. * The paused state of the Game. A paused game doesn't update any of its subsystems.
  7526. * When a game is paused the onPause event is dispatched. When it is resumed the onResume event is dispatched.
  7527. * @name Phaser.Game#paused
  7528. * @property {boolean} paused - Gets and sets the paused state of the Game.
  7529. */
  7530. Object.defineProperty(Phaser.Game.prototype, "paused", {
  7531. get: function () {
  7532. return this._paused;
  7533. },
  7534. set: function (value) {
  7535. if (value === true)
  7536. {
  7537. if (this._paused === false)
  7538. {
  7539. this._paused = true;
  7540. this._codePaused = true;
  7541. this.sound.mute = true;
  7542. this.time.gamePaused();
  7543. this.onPause.dispatch(this);
  7544. }
  7545. }
  7546. else
  7547. {
  7548. if (this._paused)
  7549. {
  7550. this._paused = false;
  7551. this._codePaused = false;
  7552. this.input.reset();
  7553. this.sound.mute = false;
  7554. this.time.gameResumed();
  7555. this.onResume.dispatch(this);
  7556. }
  7557. }
  7558. }
  7559. });
  7560. /**
  7561. * "Deleted code is debugged code." - Jeff Sickel
  7562. */
  7563. /**
  7564. * @author Richard Davey <rich@photonstorm.com>
  7565. * @copyright 2014 Photon Storm Ltd.
  7566. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  7567. */
  7568. /**
  7569. * Phaser.Input is the Input Manager for all types of Input across Phaser, including mouse, keyboard, touch and MSPointer.
  7570. * The Input manager is updated automatically by the core game loop.
  7571. *
  7572. * @class Phaser.Input
  7573. * @constructor
  7574. * @param {Phaser.Game} game - Current game instance.
  7575. */
  7576. Phaser.Input = function (game) {
  7577. /**
  7578. * @property {Phaser.Game} game - A reference to the currently running game.
  7579. */
  7580. this.game = game;
  7581. /**
  7582. * @property {HTMLCanvasElement} hitCanvas - The canvas to which single pixels are drawn in order to perform pixel-perfect hit detection.
  7583. * @default
  7584. */
  7585. this.hitCanvas = null;
  7586. /**
  7587. * @property {CanvasRenderingContext2D} hitContext - The context of the pixel perfect hit canvas.
  7588. * @default
  7589. */
  7590. this.hitContext = null;
  7591. /**
  7592. * @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.
  7593. */
  7594. this.moveCallback = null;
  7595. /**
  7596. * @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.
  7597. */
  7598. this.moveCallbackContext = this;
  7599. /**
  7600. * @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.
  7601. * @default
  7602. */
  7603. this.pollRate = 0;
  7604. /**
  7605. * You can disable all Input by setting Input.disabled = true. While set all new input related events will be ignored.
  7606. * If you need to disable just one type of input; for example mouse; use Input.mouse.disabled = true instead
  7607. * @property {boolean} disabled
  7608. * @default
  7609. */
  7610. this.disabled = false;
  7611. /**
  7612. * @property {number} multiInputOverride - Controls the expected behaviour when using a mouse and touch together on a multi-input device.
  7613. * @default
  7614. */
  7615. this.multiInputOverride = Phaser.Input.MOUSE_TOUCH_COMBINE;
  7616. /**
  7617. * @property {Phaser.Point} position - A point object representing the current position of the Pointer.
  7618. * @default
  7619. */
  7620. this.position = null;
  7621. /**
  7622. * @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.
  7623. */
  7624. this.speed = null;
  7625. /**
  7626. * A Circle object centered on the x/y screen coordinates of the Input.
  7627. * Default size of 44px (Apples recommended "finger tip" size) but can be changed to anything.
  7628. * @property {Phaser.Circle} circle
  7629. */
  7630. this.circle = null;
  7631. /**
  7632. * @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.
  7633. */
  7634. this.scale = null;
  7635. /**
  7636. * @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.
  7637. * @default
  7638. */
  7639. this.maxPointers = 10;
  7640. /**
  7641. * @property {number} currentPointers - The current number of active Pointers.
  7642. * @default
  7643. */
  7644. this.currentPointers = 0;
  7645. /**
  7646. * @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.
  7647. * @default
  7648. */
  7649. this.tapRate = 200;
  7650. /**
  7651. * @property {number} doubleTapRate - The number of milliseconds between taps of the same Pointer for it to be considered a double tap / click.
  7652. * @default
  7653. */
  7654. this.doubleTapRate = 300;
  7655. /**
  7656. * @property {number} holdRate - The number of milliseconds that the Pointer has to be pressed down for it to fire a onHold event.
  7657. * @default
  7658. */
  7659. this.holdRate = 2000;
  7660. /**
  7661. * @property {number} justPressedRate - The number of milliseconds below which the Pointer is considered justPressed.
  7662. * @default
  7663. */
  7664. this.justPressedRate = 200;
  7665. /**
  7666. * @property {number} justReleasedRate - The number of milliseconds below which the Pointer is considered justReleased .
  7667. * @default
  7668. */
  7669. this.justReleasedRate = 200;
  7670. /**
  7671. * Sets if the Pointer objects should record a history of x/y coordinates they have passed through.
  7672. * The history is cleared each time the Pointer is pressed down.
  7673. * The history is updated at the rate specified in Input.pollRate
  7674. * @property {boolean} recordPointerHistory
  7675. * @default
  7676. */
  7677. this.recordPointerHistory = false;
  7678. /**
  7679. * @property {number} recordRate - The rate in milliseconds at which the Pointer objects should update their tracking history.
  7680. * @default
  7681. */
  7682. this.recordRate = 100;
  7683. /**
  7684. * The total number of entries that can be recorded into the Pointer objects tracking history.
  7685. * If the Pointer is tracking one event every 100ms; then a trackLimit of 100 would store the last 10 seconds worth of history.
  7686. * @property {number} recordLimit
  7687. * @default
  7688. */
  7689. this.recordLimit = 100;
  7690. /**
  7691. * @property {Phaser.Pointer} pointer1 - A Pointer object.
  7692. */
  7693. this.pointer1 = null;
  7694. /**
  7695. * @property {Phaser.Pointer} pointer2 - A Pointer object.
  7696. */
  7697. this.pointer2 = null;
  7698. /**
  7699. * @property {Phaser.Pointer} pointer3 - A Pointer object.
  7700. */
  7701. this.pointer3 = null;
  7702. /**
  7703. * @property {Phaser.Pointer} pointer4 - A Pointer object.
  7704. */
  7705. this.pointer4 = null;
  7706. /**
  7707. * @property {Phaser.Pointer} pointer5 - A Pointer object.
  7708. */
  7709. this.pointer5 = null;
  7710. /**
  7711. * @property {Phaser.Pointer} pointer6 - A Pointer object.
  7712. */
  7713. this.pointer6 = null;
  7714. /**
  7715. * @property {Phaser.Pointer} pointer7 - A Pointer object.
  7716. */
  7717. this.pointer7 = null;
  7718. /**
  7719. * @property {Phaser.Pointer} pointer8 - A Pointer object.
  7720. */
  7721. this.pointer8 = null;
  7722. /**
  7723. * @property {Phaser.Pointer} pointer9 - A Pointer object.
  7724. */
  7725. this.pointer9 = null;
  7726. /**
  7727. * @property {Phaser.Pointer} pointer10 - A Pointer object.
  7728. */
  7729. this.pointer10 = null;
  7730. /**
  7731. * The most recently active Pointer object.
  7732. * When you've limited max pointers to 1 this will accurately be either the first finger touched or mouse.
  7733. * @property {Phaser.Pointer} activePointer
  7734. */
  7735. this.activePointer = null;
  7736. /**
  7737. * @property {Pointer} mousePointer - The mouse has its own unique Phaser.Pointer object which you can use if making a desktop specific game.
  7738. */
  7739. this.mousePointer = null;
  7740. /**
  7741. * @property {Phaser.Mouse} mouse - The Mouse Input manager.
  7742. */
  7743. this.mouse = null;
  7744. /**
  7745. * @property {Phaser.Keyboard} keyboard - The Keyboard Input manager.
  7746. */
  7747. this.keyboard = null;
  7748. /**
  7749. * @property {Phaser.Touch} touch - the Touch Input manager.
  7750. */
  7751. this.touch = null;
  7752. /**
  7753. * @property {Phaser.MSPointer} mspointer - The MSPointer Input manager.
  7754. */
  7755. this.mspointer = null;
  7756. /**
  7757. * @property {Phaser.Gamepad} gamepad - The Gamepad Input manager.
  7758. */
  7759. this.gamepad = null;
  7760. /**
  7761. * @property {Phaser.Gestures} gestures - The Gestures manager.
  7762. */
  7763. // this.gestures = null;
  7764. /**
  7765. * @property {Phaser.Signal} onDown - A Signal that is dispatched each time a pointer is pressed down.
  7766. */
  7767. this.onDown = null;
  7768. /**
  7769. * @property {Phaser.Signal} onUp - A Signal that is dispatched each time a pointer is released.
  7770. */
  7771. this.onUp = null;
  7772. /**
  7773. * @property {Phaser.Signal} onTap - A Signal that is dispatched each time a pointer is tapped.
  7774. */
  7775. this.onTap = null;
  7776. /**
  7777. * @property {Phaser.Signal} onHold - A Signal that is dispatched each time a pointer is held down.
  7778. */
  7779. this.onHold = null;
  7780. /**
  7781. * A linked list of interactive objects; the InputHandler components (belonging to Sprites) register themselves with this.
  7782. * @property {Phaser.LinkedList} interactiveItems
  7783. */
  7784. this.interactiveItems = new Phaser.LinkedList();
  7785. /**
  7786. * @property {Phaser.Point} _localPoint - Internal cache var.
  7787. * @private
  7788. */
  7789. this._localPoint = new Phaser.Point();
  7790. /**
  7791. * @property {number} _pollCounter - Internal var holding the current poll counter.
  7792. * @private
  7793. */
  7794. this._pollCounter = 0;
  7795. /**
  7796. * @property {Phaser.Point} _oldPosition - A point object representing the previous position of the Pointer.
  7797. * @private
  7798. */
  7799. this._oldPosition = null;
  7800. /**
  7801. * @property {number} _x - x coordinate of the most recent Pointer event
  7802. * @private
  7803. */
  7804. this._x = 0;
  7805. /**
  7806. * @property {number} _y - Y coordinate of the most recent Pointer event
  7807. * @private
  7808. */
  7809. this._y = 0;
  7810. };
  7811. /**
  7812. * @constant
  7813. * @type {number}
  7814. */
  7815. Phaser.Input.MOUSE_OVERRIDES_TOUCH = 0;
  7816. /**
  7817. * @constant
  7818. * @type {number}
  7819. */
  7820. Phaser.Input.TOUCH_OVERRIDES_MOUSE = 1;
  7821. /**
  7822. * @constant
  7823. * @type {number}
  7824. */
  7825. Phaser.Input.MOUSE_TOUCH_COMBINE = 2;
  7826. Phaser.Input.prototype = {
  7827. /**
  7828. * Starts the Input Manager running.
  7829. * @method Phaser.Input#boot
  7830. * @protected
  7831. */
  7832. boot: function () {
  7833. this.mousePointer = new Phaser.Pointer(this.game, 0);
  7834. this.pointer1 = new Phaser.Pointer(this.game, 1);
  7835. this.pointer2 = new Phaser.Pointer(this.game, 2);
  7836. this.mouse = new Phaser.Mouse(this.game);
  7837. this.keyboard = new Phaser.Keyboard(this.game);
  7838. this.touch = new Phaser.Touch(this.game);
  7839. this.mspointer = new Phaser.MSPointer(this.game);
  7840. this.gamepad = new Phaser.Gamepad(this.game);
  7841. // this.gestures = new Phaser.Gestures(this.game);
  7842. this.onDown = new Phaser.Signal();
  7843. this.onUp = new Phaser.Signal();
  7844. this.onTap = new Phaser.Signal();
  7845. this.onHold = new Phaser.Signal();
  7846. this.scale = new Phaser.Point(1, 1);
  7847. this.speed = new Phaser.Point();
  7848. this.position = new Phaser.Point();
  7849. this._oldPosition = new Phaser.Point();
  7850. this.circle = new Phaser.Circle(0, 0, 44);
  7851. this.activePointer = this.mousePointer;
  7852. this.currentPointers = 0;
  7853. this.hitCanvas = document.createElement('canvas');
  7854. this.hitCanvas.width = 1;
  7855. this.hitCanvas.height = 1;
  7856. this.hitContext = this.hitCanvas.getContext('2d');
  7857. this.mouse.start();
  7858. this.keyboard.start();
  7859. this.touch.start();
  7860. this.mspointer.start();
  7861. this.mousePointer.active = true;
  7862. },
  7863. /**
  7864. * Stops all of the Input Managers from running.
  7865. * @method Phaser.Input#destroy
  7866. */
  7867. destroy: function () {
  7868. this.mouse.stop();
  7869. this.keyboard.stop();
  7870. this.touch.stop();
  7871. this.mspointer.stop();
  7872. this.gamepad.stop();
  7873. // this.gestures.stop();
  7874. this.moveCallback = null;
  7875. },
  7876. /**
  7877. * Sets a callback that is fired every time the activePointer receives a DOM move event such as a mousemove or touchmove.
  7878. * 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
  7879. * to only use if you've limited input to a single pointer (i.e. mouse or touch)
  7880. * @method Phaser.Input#setMoveCallback
  7881. * @param {function} callback - The callback that will be called each time the activePointer receives a DOM move event.
  7882. * @param {object} callbackContext - The context in which the callback will be called.
  7883. */
  7884. setMoveCallback: function (callback, callbackContext) {
  7885. this.moveCallback = callback;
  7886. this.moveCallbackContext = callbackContext;
  7887. },
  7888. /**
  7889. * Add a new Pointer object to the Input Manager. By default Input creates 3 pointer objects: mousePointer, pointer1 and pointer2.
  7890. * If you need more then use this to create a new one, up to a maximum of 10.
  7891. * @method Phaser.Input#addPointer
  7892. * @return {Phaser.Pointer} A reference to the new Pointer object that was created.
  7893. */
  7894. addPointer: function () {
  7895. var next = 0;
  7896. for (var i = 10; i > 0; i--)
  7897. {
  7898. if (this['pointer' + i] === null)
  7899. {
  7900. next = i;
  7901. }
  7902. }
  7903. if (next === 0)
  7904. {
  7905. console.warn("You can only have 10 Pointer objects");
  7906. return null;
  7907. }
  7908. else
  7909. {
  7910. this['pointer' + next] = new Phaser.Pointer(this.game, next);
  7911. return this['pointer' + next];
  7912. }
  7913. },
  7914. /**
  7915. * Updates the Input Manager. Called by the core Game loop.
  7916. * @method Phaser.Input#update
  7917. * @protected
  7918. */
  7919. update: function () {
  7920. this.keyboard.update();
  7921. if (this.pollRate > 0 && this._pollCounter < this.pollRate)
  7922. {
  7923. this._pollCounter++;
  7924. return;
  7925. }
  7926. this.speed.x = this.position.x - this._oldPosition.x;
  7927. this.speed.y = this.position.y - this._oldPosition.y;
  7928. this._oldPosition.copyFrom(this.position);
  7929. this.mousePointer.update();
  7930. if (this.gamepad.active) { this.gamepad.update(); }
  7931. this.pointer1.update();
  7932. this.pointer2.update();
  7933. if (this.pointer3) { this.pointer3.update(); }
  7934. if (this.pointer4) { this.pointer4.update(); }
  7935. if (this.pointer5) { this.pointer5.update(); }
  7936. if (this.pointer6) { this.pointer6.update(); }
  7937. if (this.pointer7) { this.pointer7.update(); }
  7938. if (this.pointer8) { this.pointer8.update(); }
  7939. if (this.pointer9) { this.pointer9.update(); }
  7940. if (this.pointer10) { this.pointer10.update(); }
  7941. this._pollCounter = 0;
  7942. // if (this.gestures.active) { this.gestures.update(); }
  7943. },
  7944. /**
  7945. * Reset all of the Pointers and Input states
  7946. * @method Phaser.Input#reset
  7947. * @param {boolean} hard - A soft reset (hard = false) won't reset any Signals that might be bound. A hard reset will.
  7948. */
  7949. reset: function (hard) {
  7950. if (this.game.isBooted === false)
  7951. {
  7952. return;
  7953. }
  7954. if (typeof hard == 'undefined') { hard = false; }
  7955. this.keyboard.reset();
  7956. this.mousePointer.reset();
  7957. this.gamepad.reset();
  7958. for (var i = 1; i <= 10; i++)
  7959. {
  7960. if (this['pointer' + i])
  7961. {
  7962. this['pointer' + i].reset();
  7963. }
  7964. }
  7965. this.currentPointers = 0;
  7966. if (this.game.canvas.style.cursor !== 'none')
  7967. {
  7968. this.game.canvas.style.cursor = 'inherit';
  7969. }
  7970. if (hard === true)
  7971. {
  7972. this.onDown.dispose();
  7973. this.onUp.dispose();
  7974. this.onTap.dispose();
  7975. this.onHold.dispose();
  7976. this.onDown = new Phaser.Signal();
  7977. this.onUp = new Phaser.Signal();
  7978. this.onTap = new Phaser.Signal();
  7979. this.onHold = new Phaser.Signal();
  7980. this.interactiveItems.callAll('reset');
  7981. }
  7982. this._pollCounter = 0;
  7983. },
  7984. /**
  7985. * Resets the speed and old position properties.
  7986. * @method Phaser.Input#resetSpeed
  7987. * @param {number} x - Sets the oldPosition.x value.
  7988. * @param {number} y - Sets the oldPosition.y value.
  7989. */
  7990. resetSpeed: function (x, y) {
  7991. this._oldPosition.setTo(x, y);
  7992. this.speed.setTo(0, 0);
  7993. },
  7994. /**
  7995. * Find the first free Pointer object and start it, passing in the event data. This is called automatically by Phaser.Touch and Phaser.MSPointer.
  7996. * @method Phaser.Input#startPointer
  7997. * @param {Any} event - The event data from the Touch event.
  7998. * @return {Phaser.Pointer} The Pointer object that was started or null if no Pointer object is available.
  7999. */
  8000. startPointer: function (event) {
  8001. if (this.maxPointers < 10 && this.totalActivePointers == this.maxPointers)
  8002. {
  8003. return null;
  8004. }
  8005. if (this.pointer1.active === false)
  8006. {
  8007. return this.pointer1.start(event);
  8008. }
  8009. else if (this.pointer2.active === false)
  8010. {
  8011. return this.pointer2.start(event);
  8012. }
  8013. else
  8014. {
  8015. for (var i = 3; i <= 10; i++)
  8016. {
  8017. if (this['pointer' + i] && this['pointer' + i].active === false)
  8018. {
  8019. return this['pointer' + i].start(event);
  8020. }
  8021. }
  8022. }
  8023. return null;
  8024. },
  8025. /**
  8026. * Updates the matching Pointer object, passing in the event data. This is called automatically and should not normally need to be invoked.
  8027. * @method Phaser.Input#updatePointer
  8028. * @param {Any} event - The event data from the Touch event.
  8029. * @return {Phaser.Pointer} The Pointer object that was updated or null if no Pointer object is available.
  8030. */
  8031. updatePointer: function (event) {
  8032. if (this.pointer1.active && this.pointer1.identifier == event.identifier)
  8033. {
  8034. return this.pointer1.move(event);
  8035. }
  8036. else if (this.pointer2.active && this.pointer2.identifier == event.identifier)
  8037. {
  8038. return this.pointer2.move(event);
  8039. }
  8040. else
  8041. {
  8042. for (var i = 3; i <= 10; i++)
  8043. {
  8044. if (this['pointer' + i] && this['pointer' + i].active && this['pointer' + i].identifier == event.identifier)
  8045. {
  8046. return this['pointer' + i].move(event);
  8047. }
  8048. }
  8049. }
  8050. return null;
  8051. },
  8052. /**
  8053. * Stops the matching Pointer object, passing in the event data.
  8054. * @method Phaser.Input#stopPointer
  8055. * @param {Any} event - The event data from the Touch event.
  8056. * @return {Phaser.Pointer} The Pointer object that was stopped or null if no Pointer object is available.
  8057. */
  8058. stopPointer: function (event) {
  8059. if (this.pointer1.active && this.pointer1.identifier == event.identifier)
  8060. {
  8061. return this.pointer1.stop(event);
  8062. }
  8063. else if (this.pointer2.active && this.pointer2.identifier == event.identifier)
  8064. {
  8065. return this.pointer2.stop(event);
  8066. }
  8067. else
  8068. {
  8069. for (var i = 3; i <= 10; i++)
  8070. {
  8071. if (this['pointer' + i] && this['pointer' + i].active && this['pointer' + i].identifier == event.identifier)
  8072. {
  8073. return this['pointer' + i].stop(event);
  8074. }
  8075. }
  8076. }
  8077. return null;
  8078. },
  8079. /**
  8080. * Get the next Pointer object whos active property matches the given state
  8081. * @method Phaser.Input#getPointer
  8082. * @param {boolean} state - The state the Pointer should be in (false for inactive, true for active).
  8083. * @return {Phaser.Pointer} A Pointer object or null if no Pointer object matches the requested state.
  8084. */
  8085. getPointer: function (state) {
  8086. state = state || false;
  8087. if (this.pointer1.active == state)
  8088. {
  8089. return this.pointer1;
  8090. }
  8091. else if (this.pointer2.active == state)
  8092. {
  8093. return this.pointer2;
  8094. }
  8095. else
  8096. {
  8097. for (var i = 3; i <= 10; i++)
  8098. {
  8099. if (this['pointer' + i] && this['pointer' + i].active == state)
  8100. {
  8101. return this['pointer' + i];
  8102. }
  8103. }
  8104. }
  8105. return null;
  8106. },
  8107. /**
  8108. * Get the Pointer object whos identified property matches the given identifier value.
  8109. * @method Phaser.Input#getPointerFromIdentifier
  8110. * @param {number} identifier - The Pointer.identifier value to search for.
  8111. * @return {Phaser.Pointer} A Pointer object or null if no Pointer object matches the requested identifier.
  8112. */
  8113. getPointerFromIdentifier: function (identifier) {
  8114. if (this.pointer1.identifier == identifier)
  8115. {
  8116. return this.pointer1;
  8117. }
  8118. else if (this.pointer2.identifier == identifier)
  8119. {
  8120. return this.pointer2;
  8121. }
  8122. else
  8123. {
  8124. for (var i = 3; i <= 10; i++)
  8125. {
  8126. if (this['pointer' + i] && this['pointer' + i].identifier == identifier)
  8127. {
  8128. return this['pointer' + i];
  8129. }
  8130. }
  8131. }
  8132. return null;
  8133. },
  8134. /**
  8135. * This will return the local coordinates of the specified displayObject based on the given Pointer.
  8136. * @method Phaser.Input#getLocalPosition
  8137. * @param {Phaser.Sprite|Phaser.Image} displayObject - The DisplayObject to get the local coordinates for.
  8138. * @param {Phaser.Pointer} pointer - The Pointer to use in the check against the displayObject.
  8139. * @return {Phaser.Point} A point containing the coordinates of the Pointer position relative to the DisplayObject.
  8140. */
  8141. getLocalPosition: function (displayObject, pointer, output) {
  8142. if (typeof output === 'undefined') { output = new Phaser.Point(); }
  8143. var wt = displayObject.worldTransform;
  8144. var id = 1 / (wt.a * wt.d + wt.b * -wt.c);
  8145. return output.setTo(
  8146. wt.d * id * pointer.x + -wt.b * id * pointer.y + (wt.ty * wt.b - wt.tx * wt.d) * id,
  8147. wt.a * id * pointer.y + -wt.c * id * pointer.x + (-wt.ty * wt.a + wt.tx * wt.c) * id
  8148. );
  8149. },
  8150. /**
  8151. * Tests if the pointer hits the given object.
  8152. *
  8153. * @method Phaser.Input#hitTest
  8154. * @param {DisplayObject} displayObject - The displayObject to test for a hit.
  8155. * @param {Phaser.Pointer} pointer - The pointer to use for the test.
  8156. * @param {Phaser.Point} localPoint - The local translated point.
  8157. */
  8158. hitTest: function (displayObject, pointer, localPoint) {
  8159. if (!displayObject.worldVisible)
  8160. {
  8161. return false;
  8162. }
  8163. this.getLocalPosition(displayObject, pointer, this._localPoint);
  8164. localPoint.copyFrom(this._localPoint);
  8165. if (displayObject.hitArea && displayObject.hitArea.contains)
  8166. {
  8167. if (displayObject.hitArea.contains(this._localPoint.x, this._localPoint.y))
  8168. {
  8169. return true;
  8170. }
  8171. return false;
  8172. }
  8173. else if (displayObject instanceof Phaser.TileSprite)
  8174. {
  8175. var width = displayObject.width;
  8176. var height = displayObject.height;
  8177. var x1 = -width * displayObject.anchor.x;
  8178. if (this._localPoint.x > x1 && this._localPoint.x < x1 + width)
  8179. {
  8180. var y1 = -height * displayObject.anchor.y;
  8181. if (this._localPoint.y > y1 && this._localPoint.y < y1 + height)
  8182. {
  8183. return true;
  8184. }
  8185. }
  8186. }
  8187. else if (displayObject instanceof PIXI.Sprite)
  8188. {
  8189. var width = displayObject.texture.frame.width;
  8190. var height = displayObject.texture.frame.height;
  8191. var x1 = -width * displayObject.anchor.x;
  8192. if (this._localPoint.x > x1 && this._localPoint.x < x1 + width)
  8193. {
  8194. var y1 = -height * displayObject.anchor.y;
  8195. if (this._localPoint.y > y1 && this._localPoint.y < y1 + height)
  8196. {
  8197. return true;
  8198. }
  8199. }
  8200. }
  8201. for (var i = 0, len = displayObject.children.length; i < len; i++)
  8202. {
  8203. if (this.hitTest(displayObject.children[i], pointer, localPoint))
  8204. {
  8205. return true;
  8206. }
  8207. }
  8208. return false;
  8209. }
  8210. };
  8211. Phaser.Input.prototype.constructor = Phaser.Input;
  8212. /**
  8213. * The X coordinate of the most recently active pointer. This value takes game scaling into account automatically. See Pointer.screenX/clientX for source values.
  8214. * @name Phaser.Input#x
  8215. * @property {number} x - The X coordinate of the most recently active pointer.
  8216. */
  8217. Object.defineProperty(Phaser.Input.prototype, "x", {
  8218. get: function () {
  8219. return this._x;
  8220. },
  8221. set: function (value) {
  8222. this._x = Math.floor(value);
  8223. }
  8224. });
  8225. /**
  8226. * The Y coordinate of the most recently active pointer. This value takes game scaling into account automatically. See Pointer.screenY/clientY for source values.
  8227. * @name Phaser.Input#y
  8228. * @property {number} y - The Y coordinate of the most recently active pointer.
  8229. */
  8230. Object.defineProperty(Phaser.Input.prototype, "y", {
  8231. get: function () {
  8232. return this._y;
  8233. },
  8234. set: function (value) {
  8235. this._y = Math.floor(value);
  8236. }
  8237. });
  8238. /**
  8239. * @name Phaser.Input#pollLocked
  8240. * @property {boolean} pollLocked - True if the Input is currently poll rate locked.
  8241. * @readonly
  8242. */
  8243. Object.defineProperty(Phaser.Input.prototype, "pollLocked", {
  8244. get: function () {
  8245. return (this.pollRate > 0 && this._pollCounter < this.pollRate);
  8246. }
  8247. });
  8248. /**
  8249. * The total number of inactive Pointers
  8250. * @name Phaser.Input#totalInactivePointers
  8251. * @property {number} totalInactivePointers - The total number of inactive Pointers.
  8252. * @readonly
  8253. */
  8254. Object.defineProperty(Phaser.Input.prototype, "totalInactivePointers", {
  8255. get: function () {
  8256. return 10 - this.currentPointers;
  8257. }
  8258. });
  8259. /**
  8260. * The total number of active Pointers
  8261. * @name Phaser.Input#totalActivePointers
  8262. * @property {number} totalActivePointers - The total number of active Pointers.
  8263. * @readonly
  8264. */
  8265. Object.defineProperty(Phaser.Input.prototype, "totalActivePointers", {
  8266. get: function () {
  8267. this.currentPointers = 0;
  8268. for (var i = 1; i <= 10; i++)
  8269. {
  8270. if (this['pointer' + i] && this['pointer' + i].active)
  8271. {
  8272. this.currentPointers++;
  8273. }
  8274. }
  8275. return this.currentPointers;
  8276. }
  8277. });
  8278. /**
  8279. * The world X coordinate of the most recently active pointer.
  8280. * @name Phaser.Input#worldX
  8281. * @property {number} worldX - The world X coordinate of the most recently active pointer.
  8282. */
  8283. Object.defineProperty(Phaser.Input.prototype, "worldX", {
  8284. get: function () {
  8285. return this.game.camera.view.x + this.x;
  8286. }
  8287. });
  8288. /**
  8289. * The world Y coordinate of the most recently active pointer.
  8290. * @name Phaser.Input#worldY
  8291. * @property {number} worldY - The world Y coordinate of the most recently active pointer.
  8292. */
  8293. Object.defineProperty(Phaser.Input.prototype, "worldY", {
  8294. get: function () {
  8295. return this.game.camera.view.y + this.y;
  8296. }
  8297. });
  8298. /**
  8299. * @author Richard Davey <rich@photonstorm.com>
  8300. * @copyright 2014 Photon Storm Ltd.
  8301. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  8302. */
  8303. /**
  8304. * @class Phaser.Key
  8305. * @classdesc If you need more fine-grained control over the handling of specific keys you can create and use Phaser.Key objects.
  8306. * @constructor
  8307. * @param {Phaser.Game} game - Current game instance.
  8308. * @param {number} keycode - The key code this Key is responsible for.
  8309. */
  8310. Phaser.Key = function (game, keycode) {
  8311. /**
  8312. * @property {Phaser.Game} game - A reference to the currently running game.
  8313. */
  8314. this.game = game;
  8315. /**
  8316. * @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.
  8317. * @default
  8318. */
  8319. this.enabled = true;
  8320. /**
  8321. * @property {object} event - Stores the most recent DOM event.
  8322. * @readonly
  8323. */
  8324. this.event = null;
  8325. /**
  8326. * @property {boolean} isDown - The "down" state of the key.
  8327. * @default
  8328. */
  8329. this.isDown = false;
  8330. /**
  8331. * @property {boolean} isUp - The "up" state of the key.
  8332. * @default
  8333. */
  8334. this.isUp = true;
  8335. /**
  8336. * @property {boolean} altKey - The down state of the ALT key, if pressed at the same time as this key.
  8337. * @default
  8338. */
  8339. this.altKey = false;
  8340. /**
  8341. * @property {boolean} ctrlKey - The down state of the CTRL key, if pressed at the same time as this key.
  8342. * @default
  8343. */
  8344. this.ctrlKey = false;
  8345. /**
  8346. * @property {boolean} shiftKey - The down state of the SHIFT key, if pressed at the same time as this key.
  8347. * @default
  8348. */
  8349. this.shiftKey = false;
  8350. /**
  8351. * @property {number} timeDown - The timestamp when the key was last pressed down. This is based on Game.time.now.
  8352. */
  8353. this.timeDown = 0;
  8354. /**
  8355. * If the key is down this value holds the duration of that key press and is constantly updated.
  8356. * If the key is up it holds the duration of the previous down session.
  8357. * @property {number} duration - The number of milliseconds this key has been held down for.
  8358. * @default
  8359. */
  8360. this.duration = 0;
  8361. /**
  8362. * @property {number} timeUp - The timestamp when the key was last released. This is based on Game.time.now.
  8363. * @default
  8364. */
  8365. this.timeUp = -2500;
  8366. /**
  8367. * @property {number} repeats - If a key is held down this holds down the number of times the key has 'repeated'.
  8368. * @default
  8369. */
  8370. this.repeats = 0;
  8371. /**
  8372. * @property {number} keyCode - The keycode of this key.
  8373. */
  8374. this.keyCode = keycode;
  8375. /**
  8376. * @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).
  8377. */
  8378. this.onDown = new Phaser.Signal();
  8379. /**
  8380. * @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.
  8381. */
  8382. this.onHoldCallback = null;
  8383. /**
  8384. * @property {object} onHoldContext - The context under which the onHoldCallback will be called.
  8385. */
  8386. this.onHoldContext = null;
  8387. /**
  8388. * @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).
  8389. */
  8390. this.onUp = new Phaser.Signal();
  8391. };
  8392. Phaser.Key.prototype = {
  8393. update: function () {
  8394. if (!this.enabled) { return; }
  8395. if (this.isDown)
  8396. {
  8397. this.duration = this.game.time.now - this.timeDown;
  8398. this.repeats++;
  8399. if (this.onHoldCallback)
  8400. {
  8401. this.onHoldCallback.call(this.onHoldContext, this);
  8402. }
  8403. }
  8404. },
  8405. /**
  8406. * Called automatically by Phaser.Keyboard.
  8407. * @method Phaser.Key#processKeyDown
  8408. * @param {KeyboardEvent} event.
  8409. * @protected
  8410. */
  8411. processKeyDown: function (event) {
  8412. if (!this.enabled) { return; }
  8413. this.event = event;
  8414. if (this.isDown)
  8415. {
  8416. return;
  8417. }
  8418. this.altKey = event.altKey;
  8419. this.ctrlKey = event.ctrlKey;
  8420. this.shiftKey = event.shiftKey;
  8421. this.isDown = true;
  8422. this.isUp = false;
  8423. this.timeDown = this.game.time.now;
  8424. this.duration = 0;
  8425. this.repeats = 0;
  8426. this.onDown.dispatch(this);
  8427. },
  8428. /**
  8429. * Called automatically by Phaser.Keyboard.
  8430. * @method Phaser.Key#processKeyUp
  8431. * @param {KeyboardEvent} event.
  8432. * @protected
  8433. */
  8434. processKeyUp: function (event) {
  8435. if (!this.enabled) { return; }
  8436. this.event = event;
  8437. if (this.isUp)
  8438. {
  8439. return;
  8440. }
  8441. this.isDown = false;
  8442. this.isUp = true;
  8443. this.timeUp = this.game.time.now;
  8444. this.duration = this.game.time.now - this.timeDown;
  8445. this.onUp.dispatch(this);
  8446. },
  8447. /**
  8448. * 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
  8449. * associated with the onDown and onUp events and nulls the onHoldCallback if set.
  8450. *
  8451. * @method Phaser.Key#reset
  8452. */
  8453. reset: function () {
  8454. this.isDown = false;
  8455. this.isUp = true;
  8456. this.timeUp = this.game.time.now;
  8457. this.duration = this.game.time.now - this.timeDown;
  8458. this.enabled = true;
  8459. this.onDown.removeAll();
  8460. this.onUp.removeAll();
  8461. this.onHoldCallback = null;
  8462. this.onHoldContext = null;
  8463. },
  8464. /**
  8465. * 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)
  8466. * @method Phaser.Key#justPressed
  8467. * @param {number} [duration=250] - The duration below which the key is considered as being just pressed.
  8468. * @return {boolean} True if the key is just pressed otherwise false.
  8469. */
  8470. justPressed: function (duration) {
  8471. if (typeof duration === "undefined") { duration = 2500; }
  8472. return (this.isDown && this.duration < duration);
  8473. },
  8474. /**
  8475. * 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)
  8476. * @method Phaser.Key#justReleased
  8477. * @param {number} [duration=250] - The duration below which the key is considered as being just released.
  8478. * @return {boolean} True if the key is just released otherwise false.
  8479. */
  8480. justReleased: function (duration) {
  8481. if (typeof duration === "undefined") { duration = 2500; }
  8482. return (!this.isDown && ((this.game.time.now - this.timeUp) < duration));
  8483. }
  8484. };
  8485. Phaser.Key.prototype.constructor = Phaser.Key;
  8486. /**
  8487. * @author Richard Davey <rich@photonstorm.com>
  8488. * @copyright 2014 Photon Storm Ltd.
  8489. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  8490. */
  8491. /**
  8492. * The Keyboard class handles looking after keyboard input for your game. It will recognise and respond to key presses and dispatch the required events.
  8493. *
  8494. * @class Phaser.Keyboard
  8495. * @constructor
  8496. * @param {Phaser.Game} game - A reference to the currently running game.
  8497. */
  8498. Phaser.Keyboard = function (game) {
  8499. /**
  8500. * @property {Phaser.Game} game - Local reference to game.
  8501. */
  8502. this.game = game;
  8503. /**
  8504. * You can disable all Keyboard Input by setting disabled to true. While true all new input related events will be ignored.
  8505. * @property {boolean} disabled - The disabled state of the Keyboard.
  8506. * @default
  8507. */
  8508. this.disabled = false;
  8509. /**
  8510. * @property {Object} event - The most recent DOM event. This is updated every time a new key is pressed or released.
  8511. */
  8512. this.event = null;
  8513. /**
  8514. * @property {Object} callbackContext - The context under which the callbacks are run.
  8515. */
  8516. this.callbackContext = this;
  8517. /**
  8518. * @property {function} onDownCallback - This callback is invoked every time a key is pressed down.
  8519. */
  8520. this.onDownCallback = null;
  8521. /**
  8522. * @property {function} onUpCallback - This callback is invoked every time a key is released.
  8523. */
  8524. this.onUpCallback = null;
  8525. /**
  8526. * @property {array<Phaser.Key>} _keys - The array the Phaser.Key objects are stored in.
  8527. * @private
  8528. */
  8529. this._keys = [];
  8530. /**
  8531. * @property {array} _capture - The array the key capture values are stored in.
  8532. * @private
  8533. */
  8534. this._capture = [];
  8535. /**
  8536. * @property {function} _onKeyDown
  8537. * @private
  8538. * @default
  8539. */
  8540. this._onKeyDown = null;
  8541. /**
  8542. * @property {function} _onKeyUp
  8543. * @private
  8544. * @default
  8545. */
  8546. this._onKeyUp = null;
  8547. /**
  8548. * @property {number} _i - Internal cache var
  8549. * @private
  8550. */
  8551. this._i = 0;
  8552. };
  8553. Phaser.Keyboard.prototype = {
  8554. /**
  8555. * Add callbacks to the Keyboard handler so that each time a key is pressed down or released the callbacks are activated.
  8556. *
  8557. * @method Phaser.Keyboard#addCallbacks
  8558. * @param {Object} context - The context under which the callbacks are run.
  8559. * @param {function} onDown - This callback is invoked every time a key is pressed down.
  8560. * @param {function} [onUp=null] - This callback is invoked every time a key is released.
  8561. */
  8562. addCallbacks: function (context, onDown, onUp) {
  8563. this.callbackContext = context;
  8564. this.onDownCallback = onDown;
  8565. if (typeof onUp !== 'undefined')
  8566. {
  8567. this.onUpCallback = onUp;
  8568. }
  8569. },
  8570. /**
  8571. * If you need more fine-grained control over a Key you can create a new Phaser.Key object via this method.
  8572. * The Key object can then be polled, have events attached to it, etc.
  8573. *
  8574. * @method Phaser.Keyboard#addKey
  8575. * @param {number} keycode - The keycode of the key, i.e. Phaser.Keyboard.UP or Phaser.Keyboard.SPACEBAR
  8576. * @return {Phaser.Key} The Key object which you can store locally and reference directly.
  8577. */
  8578. addKey: function (keycode) {
  8579. if (!this._keys[keycode])
  8580. {
  8581. this._keys[keycode] = new Phaser.Key(this.game, keycode);
  8582. this.addKeyCapture(keycode);
  8583. }
  8584. return this._keys[keycode];
  8585. },
  8586. /**
  8587. * Removes a Key object from the Keyboard manager.
  8588. *
  8589. * @method Phaser.Keyboard#removeKey
  8590. * @param {number} keycode - The keycode of the key to remove, i.e. Phaser.Keyboard.UP or Phaser.Keyboard.SPACEBAR
  8591. */
  8592. removeKey: function (keycode) {
  8593. if (this._keys[keycode])
  8594. {
  8595. this._keys[keycode] = null;
  8596. this.removeKeyCapture(keycode);
  8597. }
  8598. },
  8599. /**
  8600. * Creates and returns an object containing 4 hotkeys for Up, Down, Left and Right.
  8601. *
  8602. * @method Phaser.Keyboard#createCursorKeys
  8603. * @return {object} An object containing properties: up, down, left and right. Which can be polled like any other Phaser.Key object.
  8604. */
  8605. createCursorKeys: function () {
  8606. return {
  8607. up: this.addKey(Phaser.Keyboard.UP),
  8608. down: this.addKey(Phaser.Keyboard.DOWN),
  8609. left: this.addKey(Phaser.Keyboard.LEFT),
  8610. right: this.addKey(Phaser.Keyboard.RIGHT)
  8611. };
  8612. },
  8613. /**
  8614. * Starts the Keyboard event listeners running (keydown and keyup). They are attached to the window.
  8615. * This is called automatically by Phaser.Input and should not normally be invoked directly.
  8616. *
  8617. * @method Phaser.Keyboard#start
  8618. */
  8619. start: function () {
  8620. if (this._onKeyDown !== null)
  8621. {
  8622. // Avoid setting multiple listeners
  8623. return;
  8624. }
  8625. var _this = this;
  8626. this._onKeyDown = function (event) {
  8627. return _this.processKeyDown(event);
  8628. };
  8629. this._onKeyUp = function (event) {
  8630. return _this.processKeyUp(event);
  8631. };
  8632. window.addEventListener('keydown', this._onKeyDown, false);
  8633. window.addEventListener('keyup', this._onKeyUp, false);
  8634. },
  8635. /**
  8636. * Stops the Keyboard event listeners from running (keydown and keyup). They are removed from the window.
  8637. *
  8638. * @method Phaser.Keyboard#stop
  8639. */
  8640. stop: function () {
  8641. window.removeEventListener('keydown', this._onKeyDown);
  8642. window.removeEventListener('keyup', this._onKeyUp);
  8643. this._onKeyDown = null;
  8644. this._onKeyUp = null;
  8645. },
  8646. /**
  8647. * Stops the Keyboard event listeners from running (keydown and keyup). They are removed from the window.
  8648. * Also clears all key captures and currently created Key objects.
  8649. *
  8650. * @method Phaser.Keyboard#destroy
  8651. */
  8652. destroy: function () {
  8653. this.stop();
  8654. this.clearCaptures();
  8655. this._keys.length = 0;
  8656. this._i = 0;
  8657. },
  8658. /**
  8659. * By default when a key is pressed Phaser will not stop the event from propagating up to the browser.
  8660. * There are some keys this can be annoying for, like the arrow keys or space bar, which make the browser window scroll.
  8661. * You can use addKeyCapture to consume the keyboard event for specific keys so it doesn't bubble up to the the browser.
  8662. * Pass in either a single keycode or an array/hash of keycodes.
  8663. *
  8664. * @method Phaser.Keyboard#addKeyCapture
  8665. * @param {Any} keycode - Either a single numeric keycode or an array/hash of keycodes: [65, 67, 68].
  8666. */
  8667. addKeyCapture: function (keycode) {
  8668. if (typeof keycode === 'object')
  8669. {
  8670. for (var key in keycode)
  8671. {
  8672. this._capture[keycode[key]] = true;
  8673. }
  8674. }
  8675. else
  8676. {
  8677. this._capture[keycode] = true;
  8678. }
  8679. },
  8680. /**
  8681. * Removes an existing key capture.
  8682. *
  8683. * @method Phaser.Keyboard#removeKeyCapture
  8684. * @param {number} keycode
  8685. */
  8686. removeKeyCapture: function (keycode) {
  8687. delete this._capture[keycode];
  8688. },
  8689. /**
  8690. * Clear all set key captures.
  8691. *
  8692. * @method Phaser.Keyboard#clearCaptures
  8693. */
  8694. clearCaptures: function () {
  8695. this._capture = {};
  8696. },
  8697. /**
  8698. * Updates all currently defined keys.
  8699. *
  8700. * @method Phaser.Keyboard#update
  8701. */
  8702. update: function () {
  8703. this._i = this._keys.length;
  8704. while (this._i--)
  8705. {
  8706. if (this._keys[this._i])
  8707. {
  8708. this._keys[this._i].update();
  8709. }
  8710. }
  8711. },
  8712. /**
  8713. * Process the keydown event.
  8714. *
  8715. * @method Phaser.Keyboard#processKeyDown
  8716. * @param {KeyboardEvent} event
  8717. * @protected
  8718. */
  8719. processKeyDown: function (event) {
  8720. this.event = event;
  8721. if (this.game.input.disabled || this.disabled)
  8722. {
  8723. return;
  8724. }
  8725. // The event is being captured but another hotkey may need it
  8726. if (this._capture[event.keyCode])
  8727. {
  8728. event.preventDefault();
  8729. }
  8730. if (this.onDownCallback)
  8731. {
  8732. this.onDownCallback.call(this.callbackContext, event);
  8733. }
  8734. if (!this._keys[event.keyCode])
  8735. {
  8736. this._keys[event.keyCode] = new Phaser.Key(this.game, event.keyCode);
  8737. }
  8738. this._keys[event.keyCode].processKeyDown(event);
  8739. },
  8740. /**
  8741. * Process the keyup event.
  8742. *
  8743. * @method Phaser.Keyboard#processKeyUp
  8744. * @param {KeyboardEvent} event
  8745. * @protected
  8746. */
  8747. processKeyUp: function (event) {
  8748. this.event = event;
  8749. if (this.game.input.disabled || this.disabled)
  8750. {
  8751. return;
  8752. }
  8753. if (this._capture[event.keyCode])
  8754. {
  8755. event.preventDefault();
  8756. }
  8757. if (this.onUpCallback)
  8758. {
  8759. this.onUpCallback.call(this.callbackContext, event);
  8760. }
  8761. if (!this._keys[event.keyCode])
  8762. {
  8763. this._keys[event.keyCode] = new Phaser.Key(this.game, event.keyCode);
  8764. }
  8765. this._keys[event.keyCode].processKeyUp(event);
  8766. },
  8767. /**
  8768. * Resets all Keys.
  8769. *
  8770. * @method Phaser.Keyboard#reset
  8771. */
  8772. reset: function () {
  8773. this.event = null;
  8774. var i = this._keys.length;
  8775. while (i--)
  8776. {
  8777. if (this._keys[i])
  8778. {
  8779. this._keys[i].reset();
  8780. }
  8781. }
  8782. },
  8783. /**
  8784. * 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)
  8785. *
  8786. * @method Phaser.Keyboard#justPressed
  8787. * @param {number} keycode - The keycode of the key to remove, i.e. Phaser.Keyboard.UP or Phaser.Keyboard.SPACEBAR
  8788. * @param {number} [duration=250] - The duration below which the key is considered as being just pressed.
  8789. * @return {boolean} True if the key is just pressed otherwise false.
  8790. */
  8791. justPressed: function (keycode, duration) {
  8792. if (this._keys[keycode])
  8793. {
  8794. return this._keys[keycode].justPressed(duration);
  8795. }
  8796. else
  8797. {
  8798. return false;
  8799. }
  8800. },
  8801. /**
  8802. * 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)
  8803. *
  8804. * @method Phaser.Keyboard#justReleased
  8805. * @param {number} keycode - The keycode of the key to remove, i.e. Phaser.Keyboard.UP or Phaser.Keyboard.SPACEBAR
  8806. * @param {number} [duration=250] - The duration below which the key is considered as being just released.
  8807. * @return {boolean} True if the key is just released otherwise false.
  8808. */
  8809. justReleased: function (keycode, duration) {
  8810. if (this._keys[keycode])
  8811. {
  8812. return this._keys[keycode].justReleased(duration);
  8813. }
  8814. else
  8815. {
  8816. return false;
  8817. }
  8818. },
  8819. /**
  8820. * Returns true of the key is currently pressed down. Note that it can only detect key presses on the web browser.
  8821. *
  8822. * @method Phaser.Keyboard#isDown
  8823. * @param {number} keycode - The keycode of the key to remove, i.e. Phaser.Keyboard.UP or Phaser.Keyboard.SPACEBAR
  8824. * @return {boolean} True if the key is currently down.
  8825. */
  8826. isDown: function (keycode) {
  8827. if (this._keys[keycode])
  8828. {
  8829. return this._keys[keycode].isDown;
  8830. }
  8831. return false;
  8832. }
  8833. };
  8834. Phaser.Keyboard.prototype.constructor = Phaser.Keyboard;
  8835. Phaser.Keyboard.A = "A".charCodeAt(0);
  8836. Phaser.Keyboard.B = "B".charCodeAt(0);
  8837. Phaser.Keyboard.C = "C".charCodeAt(0);
  8838. Phaser.Keyboard.D = "D".charCodeAt(0);
  8839. Phaser.Keyboard.E = "E".charCodeAt(0);
  8840. Phaser.Keyboard.F = "F".charCodeAt(0);
  8841. Phaser.Keyboard.G = "G".charCodeAt(0);
  8842. Phaser.Keyboard.H = "H".charCodeAt(0);
  8843. Phaser.Keyboard.I = "I".charCodeAt(0);
  8844. Phaser.Keyboard.J = "J".charCodeAt(0);
  8845. Phaser.Keyboard.K = "K".charCodeAt(0);
  8846. Phaser.Keyboard.L = "L".charCodeAt(0);
  8847. Phaser.Keyboard.M = "M".charCodeAt(0);
  8848. Phaser.Keyboard.N = "N".charCodeAt(0);
  8849. Phaser.Keyboard.O = "O".charCodeAt(0);
  8850. Phaser.Keyboard.P = "P".charCodeAt(0);
  8851. Phaser.Keyboard.Q = "Q".charCodeAt(0);
  8852. Phaser.Keyboard.R = "R".charCodeAt(0);
  8853. Phaser.Keyboard.S = "S".charCodeAt(0);
  8854. Phaser.Keyboard.T = "T".charCodeAt(0);
  8855. Phaser.Keyboard.U = "U".charCodeAt(0);
  8856. Phaser.Keyboard.V = "V".charCodeAt(0);
  8857. Phaser.Keyboard.W = "W".charCodeAt(0);
  8858. Phaser.Keyboard.X = "X".charCodeAt(0);
  8859. Phaser.Keyboard.Y = "Y".charCodeAt(0);
  8860. Phaser.Keyboard.Z = "Z".charCodeAt(0);
  8861. Phaser.Keyboard.ZERO = "0".charCodeAt(0);
  8862. Phaser.Keyboard.ONE = "1".charCodeAt(0);
  8863. Phaser.Keyboard.TWO = "2".charCodeAt(0);
  8864. Phaser.Keyboard.THREE = "3".charCodeAt(0);
  8865. Phaser.Keyboard.FOUR = "4".charCodeAt(0);
  8866. Phaser.Keyboard.FIVE = "5".charCodeAt(0);
  8867. Phaser.Keyboard.SIX = "6".charCodeAt(0);
  8868. Phaser.Keyboard.SEVEN = "7".charCodeAt(0);
  8869. Phaser.Keyboard.EIGHT = "8".charCodeAt(0);
  8870. Phaser.Keyboard.NINE = "9".charCodeAt(0);
  8871. Phaser.Keyboard.NUMPAD_0 = 96;
  8872. Phaser.Keyboard.NUMPAD_1 = 97;
  8873. Phaser.Keyboard.NUMPAD_2 = 98;
  8874. Phaser.Keyboard.NUMPAD_3 = 99;
  8875. Phaser.Keyboard.NUMPAD_4 = 100;
  8876. Phaser.Keyboard.NUMPAD_5 = 101;
  8877. Phaser.Keyboard.NUMPAD_6 = 102;
  8878. Phaser.Keyboard.NUMPAD_7 = 103;
  8879. Phaser.Keyboard.NUMPAD_8 = 104;
  8880. Phaser.Keyboard.NUMPAD_9 = 105;
  8881. Phaser.Keyboard.NUMPAD_MULTIPLY = 106;
  8882. Phaser.Keyboard.NUMPAD_ADD = 107;
  8883. Phaser.Keyboard.NUMPAD_ENTER = 108;
  8884. Phaser.Keyboard.NUMPAD_SUBTRACT = 109;
  8885. Phaser.Keyboard.NUMPAD_DECIMAL = 110;
  8886. Phaser.Keyboard.NUMPAD_DIVIDE = 111;
  8887. Phaser.Keyboard.F1 = 112;
  8888. Phaser.Keyboard.F2 = 113;
  8889. Phaser.Keyboard.F3 = 114;
  8890. Phaser.Keyboard.F4 = 115;
  8891. Phaser.Keyboard.F5 = 116;
  8892. Phaser.Keyboard.F6 = 117;
  8893. Phaser.Keyboard.F7 = 118;
  8894. Phaser.Keyboard.F8 = 119;
  8895. Phaser.Keyboard.F9 = 120;
  8896. Phaser.Keyboard.F10 = 121;
  8897. Phaser.Keyboard.F11 = 122;
  8898. Phaser.Keyboard.F12 = 123;
  8899. Phaser.Keyboard.F13 = 124;
  8900. Phaser.Keyboard.F14 = 125;
  8901. Phaser.Keyboard.F15 = 126;
  8902. Phaser.Keyboard.COLON = 186;
  8903. Phaser.Keyboard.EQUALS = 187;
  8904. Phaser.Keyboard.UNDERSCORE = 189;
  8905. Phaser.Keyboard.QUESTION_MARK = 191;
  8906. Phaser.Keyboard.TILDE = 192;
  8907. Phaser.Keyboard.OPEN_BRACKET = 219;
  8908. Phaser.Keyboard.BACKWARD_SLASH = 220;
  8909. Phaser.Keyboard.CLOSED_BRACKET = 221;
  8910. Phaser.Keyboard.QUOTES = 222;
  8911. Phaser.Keyboard.BACKSPACE = 8;
  8912. Phaser.Keyboard.TAB = 9;
  8913. Phaser.Keyboard.CLEAR = 12;
  8914. Phaser.Keyboard.ENTER = 13;
  8915. Phaser.Keyboard.SHIFT = 16;
  8916. Phaser.Keyboard.CONTROL = 17;
  8917. Phaser.Keyboard.ALT = 18;
  8918. Phaser.Keyboard.CAPS_LOCK = 20;
  8919. Phaser.Keyboard.ESC = 27;
  8920. Phaser.Keyboard.SPACEBAR = 32;
  8921. Phaser.Keyboard.PAGE_UP = 33;
  8922. Phaser.Keyboard.PAGE_DOWN = 34;
  8923. Phaser.Keyboard.END = 35;
  8924. Phaser.Keyboard.HOME = 36;
  8925. Phaser.Keyboard.LEFT = 37;
  8926. Phaser.Keyboard.UP = 38;
  8927. Phaser.Keyboard.RIGHT = 39;
  8928. Phaser.Keyboard.DOWN = 40;
  8929. Phaser.Keyboard.INSERT = 45;
  8930. Phaser.Keyboard.DELETE = 46;
  8931. Phaser.Keyboard.HELP = 47;
  8932. Phaser.Keyboard.NUM_LOCK = 144;
  8933. /**
  8934. * @author Richard Davey <rich@photonstorm.com>
  8935. * @copyright 2014 Photon Storm Ltd.
  8936. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  8937. */
  8938. /**
  8939. * Phaser.Mouse is responsible for handling all aspects of mouse interaction with the browser. It captures and processes mouse events.
  8940. *
  8941. * @class Phaser.Mouse
  8942. * @constructor
  8943. * @param {Phaser.Game} game - A reference to the currently running game.
  8944. */
  8945. Phaser.Mouse = function (game) {
  8946. /**
  8947. * @property {Phaser.Game} game - A reference to the currently running game.
  8948. */
  8949. this.game = game;
  8950. /**
  8951. * @property {Object} callbackContext - The context under which callbacks are called.
  8952. */
  8953. this.callbackContext = this.game;
  8954. /**
  8955. * @property {function} mouseDownCallback - A callback that can be fired when the mouse is pressed down.
  8956. */
  8957. this.mouseDownCallback = null;
  8958. /**
  8959. * @property {function} mouseMoveCallback - A callback that can be fired when the mouse is moved while pressed down.
  8960. */
  8961. this.mouseMoveCallback = null;
  8962. /**
  8963. * @property {function} mouseUpCallback - A callback that can be fired when the mouse is released from a pressed down state.
  8964. */
  8965. this.mouseUpCallback = null;
  8966. /**
  8967. * @property {boolean} capture - If true the DOM mouse events will have event.preventDefault applied to them, if false they will propogate fully.
  8968. */
  8969. this.capture = false;
  8970. /**
  8971. * @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.
  8972. * @default
  8973. */
  8974. this.button = -1;
  8975. /**
  8976. * @property {boolean} disabled - You can disable all Input by setting disabled = true. While set all new input related events will be ignored.
  8977. * @default
  8978. */
  8979. this.disabled = false;
  8980. /**
  8981. * @property {boolean} locked - If the mouse has been Pointer Locked successfully this will be set to true.
  8982. * @default
  8983. */
  8984. this.locked = false;
  8985. /**
  8986. * @property {Phaser.Signal} pointerLock - This event is dispatched when the browser enters or leaves pointer lock state.
  8987. * @default
  8988. */
  8989. this.pointerLock = new Phaser.Signal();
  8990. /**
  8991. * @property {MouseEvent} event - The browser mouse DOM event. Will be set to null if no mouse event has ever been received.
  8992. * @default
  8993. */
  8994. this.event = null;
  8995. /**
  8996. * @property {function} _onMouseDown - Internal event handler reference.
  8997. * @private
  8998. */
  8999. this._onMouseDown = null;
  9000. /**
  9001. * @property {function} _onMouseMove - Internal event handler reference.
  9002. * @private
  9003. */
  9004. this._onMouseMove = null;
  9005. /**
  9006. * @property {function} _onMouseUp - Internal event handler reference.
  9007. * @private
  9008. */
  9009. this._onMouseUp = null;
  9010. };
  9011. /**
  9012. * @constant
  9013. * @type {number}
  9014. */
  9015. Phaser.Mouse.NO_BUTTON = -1;
  9016. /**
  9017. * @constant
  9018. * @type {number}
  9019. */
  9020. Phaser.Mouse.LEFT_BUTTON = 0;
  9021. /**
  9022. * @constant
  9023. * @type {number}
  9024. */
  9025. Phaser.Mouse.MIDDLE_BUTTON = 1;
  9026. /**
  9027. * @constant
  9028. * @type {number}
  9029. */
  9030. Phaser.Mouse.RIGHT_BUTTON = 2;
  9031. Phaser.Mouse.prototype = {
  9032. /**
  9033. * Starts the event listeners running.
  9034. * @method Phaser.Mouse#start
  9035. */
  9036. start: function () {
  9037. if (this.game.device.android && this.game.device.chrome === false)
  9038. {
  9039. // Android stock browser fires mouse events even if you preventDefault on the touchStart, so ...
  9040. return;
  9041. }
  9042. if (this._onMouseDown !== null)
  9043. {
  9044. // Avoid setting multiple listeners
  9045. return;
  9046. }
  9047. var _this = this;
  9048. this._onMouseDown = function (event) {
  9049. return _this.onMouseDown(event);
  9050. };
  9051. this._onMouseMove = function (event) {
  9052. return _this.onMouseMove(event);
  9053. };
  9054. this._onMouseUp = function (event) {
  9055. return _this.onMouseUp(event);
  9056. };
  9057. this.game.canvas.addEventListener('mousedown', this._onMouseDown, true);
  9058. this.game.canvas.addEventListener('mousemove', this._onMouseMove, true);
  9059. this.game.canvas.addEventListener('mouseup', this._onMouseUp, true);
  9060. },
  9061. /**
  9062. * The internal method that handles the mouse down event from the browser.
  9063. * @method Phaser.Mouse#onMouseDown
  9064. * @param {MouseEvent} event - The native event from the browser. This gets stored in Mouse.event.
  9065. */
  9066. onMouseDown: function (event) {
  9067. this.event = event;
  9068. if (this.capture)
  9069. {
  9070. event.preventDefault();
  9071. }
  9072. this.button = event.button;
  9073. if (this.mouseDownCallback)
  9074. {
  9075. this.mouseDownCallback.call(this.callbackContext, event);
  9076. }
  9077. if (this.game.input.disabled || this.disabled)
  9078. {
  9079. return;
  9080. }
  9081. event['identifier'] = 0;
  9082. this.game.input.mousePointer.start(event);
  9083. },
  9084. /**
  9085. * The internal method that handles the mouse move event from the browser.
  9086. * @method Phaser.Mouse#onMouseMove
  9087. * @param {MouseEvent} event - The native event from the browser. This gets stored in Mouse.event.
  9088. */
  9089. onMouseMove: function (event) {
  9090. this.event = event;
  9091. if (this.capture)
  9092. {
  9093. event.preventDefault();
  9094. }
  9095. if (this.mouseMoveCallback)
  9096. {
  9097. this.mouseMoveCallback.call(this.callbackContext, event);
  9098. }
  9099. if (this.game.input.disabled || this.disabled)
  9100. {
  9101. return;
  9102. }
  9103. event['identifier'] = 0;
  9104. this.game.input.mousePointer.move(event);
  9105. },
  9106. /**
  9107. * The internal method that handles the mouse up event from the browser.
  9108. * @method Phaser.Mouse#onMouseUp
  9109. * @param {MouseEvent} event - The native event from the browser. This gets stored in Mouse.event.
  9110. */
  9111. onMouseUp: function (event) {
  9112. this.event = event;
  9113. if (this.capture)
  9114. {
  9115. event.preventDefault();
  9116. }
  9117. this.button = Phaser.Mouse.NO_BUTTON;
  9118. if (this.mouseUpCallback)
  9119. {
  9120. this.mouseUpCallback.call(this.callbackContext, event);
  9121. }
  9122. if (this.game.input.disabled || this.disabled)
  9123. {
  9124. return;
  9125. }
  9126. event['identifier'] = 0;
  9127. this.game.input.mousePointer.stop(event);
  9128. },
  9129. /**
  9130. * If the browser supports it you can request that the pointer be locked to the browser window.
  9131. * This is classically known as 'FPS controls', where the pointer can't leave the browser until the user presses an exit key.
  9132. * If the browser successfully enters a locked state the event Phaser.Mouse.pointerLock will be dispatched and the first parameter will be 'true'.
  9133. * @method Phaser.Mouse#requestPointerLock
  9134. */
  9135. requestPointerLock: function () {
  9136. if (this.game.device.pointerLock)
  9137. {
  9138. var element = this.game.canvas;
  9139. element.requestPointerLock = element.requestPointerLock || element.mozRequestPointerLock || element.webkitRequestPointerLock;
  9140. element.requestPointerLock();
  9141. var _this = this;
  9142. this._pointerLockChange = function (event) {
  9143. return _this.pointerLockChange(event);
  9144. };
  9145. document.addEventListener('pointerlockchange', this._pointerLockChange, true);
  9146. document.addEventListener('mozpointerlockchange', this._pointerLockChange, true);
  9147. document.addEventListener('webkitpointerlockchange', this._pointerLockChange, true);
  9148. }
  9149. },
  9150. /**
  9151. * Internal pointerLockChange handler.
  9152. * @method Phaser.Mouse#pointerLockChange
  9153. * @param {pointerlockchange} event - The native event from the browser. This gets stored in Mouse.event.
  9154. */
  9155. pointerLockChange: function (event) {
  9156. var element = this.game.canvas;
  9157. if (document.pointerLockElement === element || document.mozPointerLockElement === element || document.webkitPointerLockElement === element)
  9158. {
  9159. // Pointer was successfully locked
  9160. this.locked = true;
  9161. this.pointerLock.dispatch(true, event);
  9162. }
  9163. else
  9164. {
  9165. // Pointer was unlocked
  9166. this.locked = false;
  9167. this.pointerLock.dispatch(false, event);
  9168. }
  9169. },
  9170. /**
  9171. * Internal release pointer lock handler.
  9172. * @method Phaser.Mouse#releasePointerLock
  9173. */
  9174. releasePointerLock: function () {
  9175. document.exitPointerLock = document.exitPointerLock || document.mozExitPointerLock || document.webkitExitPointerLock;
  9176. document.exitPointerLock();
  9177. document.removeEventListener('pointerlockchange', this._pointerLockChange, true);
  9178. document.removeEventListener('mozpointerlockchange', this._pointerLockChange, true);
  9179. document.removeEventListener('webkitpointerlockchange', this._pointerLockChange, true);
  9180. },
  9181. /**
  9182. * Stop the event listeners.
  9183. * @method Phaser.Mouse#stop
  9184. */
  9185. stop: function () {
  9186. this.game.canvas.removeEventListener('mousedown', this._onMouseDown, true);
  9187. this.game.canvas.removeEventListener('mousemove', this._onMouseMove, true);
  9188. this.game.canvas.removeEventListener('mouseup', this._onMouseUp, true);
  9189. }
  9190. };
  9191. Phaser.Mouse.prototype.constructor = Phaser.Mouse;
  9192. /**
  9193. * @author Richard Davey <rich@photonstorm.com>
  9194. * @copyright 2014 Photon Storm Ltd.
  9195. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  9196. */
  9197. /**
  9198. * Phaser - MSPointer constructor.
  9199. *
  9200. * @class Phaser.MSPointer
  9201. * @classdesc The MSPointer class handles touch interactions with the game and the resulting Pointer objects.
  9202. * It will work only in Internet Explorer 10 and Windows Store or Windows Phone 8 apps using JavaScript.
  9203. * http://msdn.microsoft.com/en-us/library/ie/hh673557(v=vs.85).aspx
  9204. * @constructor
  9205. * @param {Phaser.Game} game - A reference to the currently running game.
  9206. */
  9207. Phaser.MSPointer = function (game) {
  9208. /**
  9209. * @property {Phaser.Game} game - A reference to the currently running game.
  9210. */
  9211. this.game = game;
  9212. /**
  9213. * @property {Object} callbackContext - The context under which callbacks are called (defaults to game).
  9214. */
  9215. this.callbackContext = this.game;
  9216. /**
  9217. * You can disable all Input by setting disabled = true. While set all new input related events will be ignored.
  9218. * @property {boolean} disabled
  9219. */
  9220. this.disabled = false;
  9221. /**
  9222. * @property {function} _onMSPointerDown - Internal function to handle MSPointer events.
  9223. * @private
  9224. */
  9225. this._onMSPointerDown = null;
  9226. /**
  9227. * @property {function} _onMSPointerMove - Internal function to handle MSPointer events.
  9228. * @private
  9229. */
  9230. this._onMSPointerMove = null;
  9231. /**
  9232. * @property {function} _onMSPointerUp - Internal function to handle MSPointer events.
  9233. * @private
  9234. */
  9235. this._onMSPointerUp = null;
  9236. };
  9237. Phaser.MSPointer.prototype = {
  9238. /**
  9239. * Starts the event listeners running.
  9240. * @method Phaser.MSPointer#start
  9241. */
  9242. start: function () {
  9243. if (this._onMSPointerDown !== null)
  9244. {
  9245. // Avoid setting multiple listeners
  9246. return;
  9247. }
  9248. var _this = this;
  9249. if (this.game.device.mspointer === true)
  9250. {
  9251. this._onMSPointerDown = function (event) {
  9252. return _this.onPointerDown(event);
  9253. };
  9254. this._onMSPointerMove = function (event) {
  9255. return _this.onPointerMove(event);
  9256. };
  9257. this._onMSPointerUp = function (event) {
  9258. return _this.onPointerUp(event);
  9259. };
  9260. this.game.renderer.view.addEventListener('MSPointerDown', this._onMSPointerDown, false);
  9261. this.game.renderer.view.addEventListener('MSPointerMove', this._onMSPointerMove, false);
  9262. this.game.renderer.view.addEventListener('MSPointerUp', this._onMSPointerUp, false);
  9263. // IE11+ uses non-prefix events
  9264. this.game.renderer.view.addEventListener('pointerDown', this._onMSPointerDown, false);
  9265. this.game.renderer.view.addEventListener('pointerMove', this._onMSPointerMove, false);
  9266. this.game.renderer.view.addEventListener('pointerUp', this._onMSPointerUp, false);
  9267. this.game.renderer.view.style['-ms-content-zooming'] = 'none';
  9268. this.game.renderer.view.style['-ms-touch-action'] = 'none';
  9269. }
  9270. },
  9271. /**
  9272. * The function that handles the PointerDown event.
  9273. * @method Phaser.MSPointer#onPointerDown
  9274. * @param {PointerEvent} event
  9275. */
  9276. onPointerDown: function (event) {
  9277. if (this.game.input.disabled || this.disabled)
  9278. {
  9279. return;
  9280. }
  9281. event.preventDefault();
  9282. event.identifier = event.pointerId;
  9283. this.game.input.startPointer(event);
  9284. },
  9285. /**
  9286. * The function that handles the PointerMove event.
  9287. * @method Phaser.MSPointer#onPointerMove
  9288. * @param {PointerEvent } event
  9289. */
  9290. onPointerMove: function (event) {
  9291. if (this.game.input.disabled || this.disabled)
  9292. {
  9293. return;
  9294. }
  9295. event.preventDefault();
  9296. event.identifier = event.pointerId;
  9297. this.game.input.updatePointer(event);
  9298. },
  9299. /**
  9300. * The function that handles the PointerUp event.
  9301. * @method Phaser.MSPointer#onPointerUp
  9302. * @param {PointerEvent} event
  9303. */
  9304. onPointerUp: function (event) {
  9305. if (this.game.input.disabled || this.disabled)
  9306. {
  9307. return;
  9308. }
  9309. event.preventDefault();
  9310. event.identifier = event.pointerId;
  9311. this.game.input.stopPointer(event);
  9312. },
  9313. /**
  9314. * Stop the event listeners.
  9315. * @method Phaser.MSPointer#stop
  9316. */
  9317. stop: function () {
  9318. this.game.canvas.removeEventListener('MSPointerDown', this._onMSPointerDown);
  9319. this.game.canvas.removeEventListener('MSPointerMove', this._onMSPointerMove);
  9320. this.game.canvas.removeEventListener('MSPointerUp', this._onMSPointerUp);
  9321. this.game.canvas.removeEventListener('pointerDown', this._onMSPointerDown);
  9322. this.game.canvas.removeEventListener('pointerMove', this._onMSPointerMove);
  9323. this.game.canvas.removeEventListener('pointerUp', this._onMSPointerUp);
  9324. }
  9325. };
  9326. Phaser.MSPointer.prototype.constructor = Phaser.MSPointer;
  9327. /**
  9328. * @author Richard Davey <rich@photonstorm.com>
  9329. * @copyright 2014 Photon Storm Ltd.
  9330. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  9331. */
  9332. /**
  9333. * Phaser - Pointer constructor.
  9334. *
  9335. * @class Phaser.Pointer
  9336. * @classdesc A Pointer object is used by the Mouse, Touch and MSPoint managers and represents a single finger on the touch screen.
  9337. * @constructor
  9338. * @param {Phaser.Game} game - A reference to the currently running game.
  9339. * @param {number} id - The ID of the Pointer object within the game. Each game can have up to 10 active pointers.
  9340. */
  9341. Phaser.Pointer = function (game, id) {
  9342. /**
  9343. * @property {Phaser.Game} game - A reference to the currently running game.
  9344. */
  9345. this.game = game;
  9346. /**
  9347. * @property {number} id - The ID of the Pointer object within the game. Each game can have up to 10 active pointers.
  9348. */
  9349. this.id = id;
  9350. /**
  9351. * @property {boolean} _holdSent - Local private variable to store the status of dispatching a hold event.
  9352. * @private
  9353. * @default
  9354. */
  9355. this._holdSent = false;
  9356. /**
  9357. * @property {array} _history - Local private variable storing the short-term history of pointer movements.
  9358. * @private
  9359. */
  9360. this._history = [];
  9361. /**
  9362. * @property {number} _lastDrop - Local private variable storing the time at which the next history drop should occur.
  9363. * @private
  9364. * @default
  9365. */
  9366. this._nextDrop = 0;
  9367. /**
  9368. * @property {boolean} _stateReset - Monitor events outside of a state reset loop.
  9369. * @private
  9370. * @default
  9371. */
  9372. this._stateReset = false;
  9373. /**
  9374. * @property {boolean} withinGame - true if the Pointer is within the game area, otherwise false.
  9375. */
  9376. this.withinGame = false;
  9377. /**
  9378. * @property {number} clientX - The horizontal coordinate of point relative to the viewport in pixels, excluding any scroll offset.
  9379. * @default
  9380. */
  9381. this.clientX = -1;
  9382. /**
  9383. * @property {number} clientY - The vertical coordinate of point relative to the viewport in pixels, excluding any scroll offset.
  9384. * @default
  9385. */
  9386. this.clientY = -1;
  9387. /**
  9388. * @property {number} pageX - The horizontal coordinate of point relative to the viewport in pixels, including any scroll offset.
  9389. * @default
  9390. */
  9391. this.pageX = -1;
  9392. /**
  9393. * @property {number} pageY - The vertical coordinate of point relative to the viewport in pixels, including any scroll offset.
  9394. * @default
  9395. */
  9396. this.pageY = -1;
  9397. /**
  9398. * @property {number} screenX - The horizontal coordinate of point relative to the screen in pixels.
  9399. * @default
  9400. */
  9401. this.screenX = -1;
  9402. /**
  9403. * @property {number} screenY - The vertical coordinate of point relative to the screen in pixels.
  9404. * @default
  9405. */
  9406. this.screenY = -1;
  9407. /**
  9408. * @property {number} x - The horizontal coordinate of point relative to the game element. This value is automatically scaled based on game size.
  9409. * @default
  9410. */
  9411. this.x = -1;
  9412. /**
  9413. * @property {number} y - The vertical coordinate of point relative to the game element. This value is automatically scaled based on game size.
  9414. * @default
  9415. */
  9416. this.y = -1;
  9417. /**
  9418. * @property {boolean} isMouse - If the Pointer is a mouse this is true, otherwise false.
  9419. * @default
  9420. */
  9421. this.isMouse = false;
  9422. /**
  9423. * @property {boolean} isDown - If the Pointer is touching the touchscreen, or the mouse button is held down, isDown is set to true.
  9424. * @default
  9425. */
  9426. this.isDown = false;
  9427. /**
  9428. * @property {boolean} isUp - If the Pointer is not touching the touchscreen, or the mouse button is up, isUp is set to true.
  9429. * @default
  9430. */
  9431. this.isUp = true;
  9432. /**
  9433. * @property {number} timeDown - A timestamp representing when the Pointer first touched the touchscreen.
  9434. * @default
  9435. */
  9436. this.timeDown = 0;
  9437. /**
  9438. * @property {number} timeUp - A timestamp representing when the Pointer left the touchscreen.
  9439. * @default
  9440. */
  9441. this.timeUp = 0;
  9442. /**
  9443. * @property {number} previousTapTime - A timestamp representing when the Pointer was last tapped or clicked.
  9444. * @default
  9445. */
  9446. this.previousTapTime = 0;
  9447. /**
  9448. * @property {number} totalTouches - The total number of times this Pointer has been touched to the touchscreen.
  9449. * @default
  9450. */
  9451. this.totalTouches = 0;
  9452. /**
  9453. * @property {number} msSinceLastClick - The number of miliseconds since the last click.
  9454. * @default
  9455. */
  9456. this.msSinceLastClick = Number.MAX_VALUE;
  9457. /**
  9458. * @property {any} targetObject - The Game Object this Pointer is currently over / touching / dragging.
  9459. * @default
  9460. */
  9461. this.targetObject = null;
  9462. /**
  9463. * @property {boolean} active - An active pointer is one that is currently pressed down on the display. A Mouse is always active.
  9464. * @default
  9465. */
  9466. this.active = false;
  9467. /**
  9468. * @property {Phaser.Point} position - A Phaser.Point object containing the current x/y values of the pointer on the display.
  9469. */
  9470. this.position = new Phaser.Point();
  9471. /**
  9472. * @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.
  9473. */
  9474. this.positionDown = new Phaser.Point();
  9475. /**
  9476. * @property {Phaser.Point} positionUp - A Phaser.Point object containing the x/y values of the pointer when it was last released.
  9477. */
  9478. this.positionUp = new Phaser.Point();
  9479. /**
  9480. * A Phaser.Circle that is centered on the x/y coordinates of this pointer, useful for hit detection.
  9481. * The Circle size is 44px (Apples recommended "finger tip" size).
  9482. * @property {Phaser.Circle} circle
  9483. */
  9484. this.circle = new Phaser.Circle(0, 0, 44);
  9485. if (id === 0)
  9486. {
  9487. this.isMouse = true;
  9488. }
  9489. };
  9490. Phaser.Pointer.prototype = {
  9491. /**
  9492. * Called when the Pointer is pressed onto the touchscreen.
  9493. * @method Phaser.Pointer#start
  9494. * @param {Any} event
  9495. */
  9496. start: function (event) {
  9497. this.identifier = event.identifier;
  9498. this.target = event.target;
  9499. if (typeof event.button !== 'undefined')
  9500. {
  9501. this.button = event.button;
  9502. }
  9503. this._history = [];
  9504. this.active = true;
  9505. this.withinGame = true;
  9506. this.isDown = true;
  9507. this.isUp = false;
  9508. // Work out how long it has been since the last click
  9509. this.msSinceLastClick = this.game.time.now - this.timeDown;
  9510. this.timeDown = this.game.time.now;
  9511. this._holdSent = false;
  9512. // This sets the x/y and other local values
  9513. this.move(event, true);
  9514. // x and y are the old values here?
  9515. this.positionDown.setTo(this.x, this.y);
  9516. 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))
  9517. {
  9518. this.game.input.x = this.x;
  9519. this.game.input.y = this.y;
  9520. this.game.input.position.setTo(this.x, this.y);
  9521. this.game.input.onDown.dispatch(this, event);
  9522. this.game.input.resetSpeed(this.x, this.y);
  9523. }
  9524. this._stateReset = false;
  9525. this.totalTouches++;
  9526. if (!this.isMouse)
  9527. {
  9528. this.game.input.currentPointers++;
  9529. }
  9530. if (this.targetObject !== null)
  9531. {
  9532. this.targetObject._touchedHandler(this);
  9533. }
  9534. return this;
  9535. },
  9536. /**
  9537. * Called by the Input Manager.
  9538. * @method Phaser.Pointer#update
  9539. */
  9540. update: function () {
  9541. if (this.active)
  9542. {
  9543. if (this._holdSent === false && this.duration >= this.game.input.holdRate)
  9544. {
  9545. 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))
  9546. {
  9547. this.game.input.onHold.dispatch(this);
  9548. }
  9549. this._holdSent = true;
  9550. }
  9551. // Update the droppings history
  9552. if (this.game.input.recordPointerHistory && this.game.time.now >= this._nextDrop)
  9553. {
  9554. this._nextDrop = this.game.time.now + this.game.input.recordRate;
  9555. this._history.push({
  9556. x: this.position.x,
  9557. y: this.position.y
  9558. });
  9559. if (this._history.length > this.game.input.recordLimit)
  9560. {
  9561. this._history.shift();
  9562. }
  9563. }
  9564. }
  9565. },
  9566. /**
  9567. * Called when the Pointer is moved.
  9568. * @method Phaser.Pointer#move
  9569. * @param {MouseEvent|PointerEvent|TouchEvent} event - The event passed up from the input handler.
  9570. * @param {boolean} [fromClick=false] - Was this called from the click event?
  9571. */
  9572. move: function (event, fromClick) {
  9573. if (this.game.input.pollLocked)
  9574. {
  9575. return;
  9576. }
  9577. if (typeof fromClick === 'undefined') { fromClick = false; }
  9578. if (typeof event.button !== 'undefined')
  9579. {
  9580. this.button = event.button;
  9581. }
  9582. this.clientX = event.clientX;
  9583. this.clientY = event.clientY;
  9584. this.pageX = event.pageX;
  9585. this.pageY = event.pageY;
  9586. this.screenX = event.screenX;
  9587. this.screenY = event.screenY;
  9588. this.x = (this.pageX - this.game.stage.offset.x) * this.game.input.scale.x;
  9589. this.y = (this.pageY - this.game.stage.offset.y) * this.game.input.scale.y;
  9590. this.position.setTo(this.x, this.y);
  9591. this.circle.x = this.x;
  9592. this.circle.y = this.y;
  9593. 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))
  9594. {
  9595. this.game.input.activePointer = this;
  9596. this.game.input.x = this.x;
  9597. this.game.input.y = this.y;
  9598. this.game.input.position.setTo(this.game.input.x, this.game.input.y);
  9599. this.game.input.circle.x = this.game.input.x;
  9600. this.game.input.circle.y = this.game.input.y;
  9601. }
  9602. // If the game is paused we don't process any target objects or callbacks
  9603. if (this.game.paused)
  9604. {
  9605. return this;
  9606. }
  9607. if (this.game.input.moveCallback)
  9608. {
  9609. this.game.input.moveCallback.call(this.game.input.moveCallbackContext, this, this.x, this.y);
  9610. }
  9611. // Easy out if we're dragging something and it still exists
  9612. if (this.targetObject !== null && this.targetObject.isDragged === true)
  9613. {
  9614. if (this.targetObject.update(this) === false)
  9615. {
  9616. this.targetObject = null;
  9617. }
  9618. return this;
  9619. }
  9620. // Work out which object is on the top
  9621. this._highestRenderOrderID = Number.MAX_SAFE_INTEGER;
  9622. this._highestRenderObject = null;
  9623. this._highestInputPriorityID = -1;
  9624. // Just run through the linked list
  9625. if (this.game.input.interactiveItems.total > 0)
  9626. {
  9627. var currentNode = this.game.input.interactiveItems.next;
  9628. do
  9629. {
  9630. // 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
  9631. if (currentNode.validForInput(this._highestInputPriorityID, this._highestRenderOrderID))
  9632. {
  9633. if ((!fromClick && currentNode.checkPointerOver(this)) || (fromClick && currentNode.checkPointerDown(this)))
  9634. {
  9635. this._highestRenderOrderID = currentNode.sprite._cache[3]; // renderOrderID
  9636. this._highestInputPriorityID = currentNode.priorityID;
  9637. this._highestRenderObject = currentNode;
  9638. }
  9639. }
  9640. currentNode = currentNode.next;
  9641. }
  9642. while (currentNode != null);
  9643. }
  9644. if (this._highestRenderObject === null)
  9645. {
  9646. // The pointer isn't currently over anything, check if we've got a lingering previous target
  9647. if (this.targetObject)
  9648. {
  9649. // console.log("The pointer isn't currently over anything, check if we've got a lingering previous target");
  9650. this.targetObject._pointerOutHandler(this);
  9651. this.targetObject = null;
  9652. }
  9653. }
  9654. else
  9655. {
  9656. if (this.targetObject === null)
  9657. {
  9658. // And now set the new one
  9659. // console.log('And now set the new one');
  9660. this.targetObject = this._highestRenderObject;
  9661. this._highestRenderObject._pointerOverHandler(this);
  9662. }
  9663. else
  9664. {
  9665. // We've got a target from the last update
  9666. // console.log("We've got a target from the last update");
  9667. if (this.targetObject === this._highestRenderObject)
  9668. {
  9669. // Same target as before, so update it
  9670. // console.log("Same target as before, so update it");
  9671. if (this._highestRenderObject.update(this) === false)
  9672. {
  9673. this.targetObject = null;
  9674. }
  9675. }
  9676. else
  9677. {
  9678. // The target has changed, so tell the old one we've left it
  9679. // console.log("The target has changed, so tell the old one we've left it");
  9680. this.targetObject._pointerOutHandler(this);
  9681. // And now set the new one
  9682. this.targetObject = this._highestRenderObject;
  9683. this.targetObject._pointerOverHandler(this);
  9684. }
  9685. }
  9686. }
  9687. return this;
  9688. },
  9689. /**
  9690. * Called when the Pointer leaves the target area.
  9691. * @method Phaser.Pointer#leave
  9692. * @param {MouseEvent|PointerEvent|TouchEvent} event - The event passed up from the input handler.
  9693. */
  9694. leave: function (event) {
  9695. this.withinGame = false;
  9696. this.move(event, false);
  9697. },
  9698. /**
  9699. * Called when the Pointer leaves the touchscreen.
  9700. * @method Phaser.Pointer#stop
  9701. * @param {MouseEvent|PointerEvent|TouchEvent} event - The event passed up from the input handler.
  9702. */
  9703. stop: function (event) {
  9704. if (this._stateReset)
  9705. {
  9706. event.preventDefault();
  9707. return;
  9708. }
  9709. this.timeUp = this.game.time.now;
  9710. 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))
  9711. {
  9712. this.game.input.onUp.dispatch(this, event);
  9713. // Was it a tap?
  9714. if (this.duration >= 0 && this.duration <= this.game.input.tapRate)
  9715. {
  9716. // Was it a double-tap?
  9717. if (this.timeUp - this.previousTapTime < this.game.input.doubleTapRate)
  9718. {
  9719. // Yes, let's dispatch the signal then with the 2nd parameter set to true
  9720. this.game.input.onTap.dispatch(this, true);
  9721. }
  9722. else
  9723. {
  9724. // Wasn't a double-tap, so dispatch a single tap signal
  9725. this.game.input.onTap.dispatch(this, false);
  9726. }
  9727. this.previousTapTime = this.timeUp;
  9728. }
  9729. }
  9730. // Mouse is always active
  9731. if (this.id > 0)
  9732. {
  9733. this.active = false;
  9734. }
  9735. this.withinGame = false;
  9736. this.isDown = false;
  9737. this.isUp = true;
  9738. this.positionUp.setTo(this.x, this.y);
  9739. if (this.isMouse === false)
  9740. {
  9741. this.game.input.currentPointers--;
  9742. }
  9743. if (this.game.input.interactiveItems.total > 0)
  9744. {
  9745. var currentNode = this.game.input.interactiveItems.next;
  9746. do
  9747. {
  9748. if (currentNode)
  9749. {
  9750. currentNode._releasedHandler(this);
  9751. }
  9752. currentNode = currentNode.next;
  9753. }
  9754. while (currentNode != null);
  9755. }
  9756. if (this.targetObject)
  9757. {
  9758. this.targetObject._releasedHandler(this);
  9759. }
  9760. this.targetObject = null;
  9761. return this;
  9762. },
  9763. /**
  9764. * The Pointer is considered justPressed if the time it was pressed onto the touchscreen or clicked is less than justPressedRate.
  9765. * 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.
  9766. * If you wish to check if the Pointer was pressed down just once then see the Sprite.events.onInputDown event.
  9767. * @method Phaser.Pointer#justPressed
  9768. * @param {number} [duration] - The time to check against. If none given it will use InputManager.justPressedRate.
  9769. * @return {boolean} true if the Pointer was pressed down within the duration given.
  9770. */
  9771. justPressed: function (duration) {
  9772. duration = duration || this.game.input.justPressedRate;
  9773. return (this.isDown === true && (this.timeDown + duration) > this.game.time.now);
  9774. },
  9775. /**
  9776. * The Pointer is considered justReleased if the time it left the touchscreen is less than justReleasedRate.
  9777. * 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.
  9778. * If you wish to check if the Pointer was released just once then see the Sprite.events.onInputUp event.
  9779. * @method Phaser.Pointer#justReleased
  9780. * @param {number} [duration] - The time to check against. If none given it will use InputManager.justReleasedRate.
  9781. * @return {boolean} true if the Pointer was released within the duration given.
  9782. */
  9783. justReleased: function (duration) {
  9784. duration = duration || this.game.input.justReleasedRate;
  9785. return (this.isUp === true && (this.timeUp + duration) > this.game.time.now);
  9786. },
  9787. /**
  9788. * Resets the Pointer properties. Called by InputManager.reset when you perform a State change.
  9789. * @method Phaser.Pointer#reset
  9790. */
  9791. reset: function () {
  9792. if (this.isMouse === false)
  9793. {
  9794. this.active = false;
  9795. }
  9796. this.identifier = null;
  9797. this.isDown = false;
  9798. this.isUp = true;
  9799. this.totalTouches = 0;
  9800. this._holdSent = false;
  9801. this._history.length = 0;
  9802. this._stateReset = true;
  9803. if (this.targetObject)
  9804. {
  9805. this.targetObject._releasedHandler(this);
  9806. }
  9807. this.targetObject = null;
  9808. }
  9809. };
  9810. Phaser.Pointer.prototype.constructor = Phaser.Pointer;
  9811. /**
  9812. * How long the Pointer has been depressed on the touchscreen. If not currently down it returns -1.
  9813. * @name Phaser.Pointer#duration
  9814. * @property {number} duration - How long the Pointer has been depressed on the touchscreen. If not currently down it returns -1.
  9815. * @readonly
  9816. */
  9817. Object.defineProperty(Phaser.Pointer.prototype, "duration", {
  9818. get: function () {
  9819. if (this.isUp)
  9820. {
  9821. return -1;
  9822. }
  9823. return this.game.time.now - this.timeDown;
  9824. }
  9825. });
  9826. /**
  9827. * Gets the X value of this Pointer in world coordinates based on the world camera.
  9828. * @name Phaser.Pointer#worldX
  9829. * @property {number} duration - The X value of this Pointer in world coordinates based on the world camera.
  9830. * @readonly
  9831. */
  9832. Object.defineProperty(Phaser.Pointer.prototype, "worldX", {
  9833. get: function () {
  9834. return this.game.world.camera.x + this.x;
  9835. }
  9836. });
  9837. /**
  9838. * Gets the Y value of this Pointer in world coordinates based on the world camera.
  9839. * @name Phaser.Pointer#worldY
  9840. * @property {number} duration - The Y value of this Pointer in world coordinates based on the world camera.
  9841. * @readonly
  9842. */
  9843. Object.defineProperty(Phaser.Pointer.prototype, "worldY", {
  9844. get: function () {
  9845. return this.game.world.camera.y + this.y;
  9846. }
  9847. });
  9848. /**
  9849. * @author Richard Davey <rich@photonstorm.com>
  9850. * @copyright 2014 Photon Storm Ltd.
  9851. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  9852. */
  9853. /**
  9854. * Phaser.Touch handles touch events with your game. Note: Android 2.x only supports 1 touch event at once, no multi-touch.
  9855. *
  9856. * @class Phaser.Touch
  9857. * @classdesc The Touch class handles touch interactions with the game and the resulting Pointer objects.
  9858. * @constructor
  9859. * @param {Phaser.Game} game - A reference to the currently running game.
  9860. */
  9861. Phaser.Touch = function (game) {
  9862. /**
  9863. * @property {Phaser.Game} game - A reference to the currently running game.
  9864. */
  9865. this.game = game;
  9866. /**
  9867. * @property {boolean} disabled - You can disable all Touch events by setting disabled = true. While set all new touch events will be ignored.
  9868. * @return {boolean}
  9869. */
  9870. this.disabled = false;
  9871. /**
  9872. * @property {Object} callbackContext - The context under which callbacks are called.
  9873. */
  9874. this.callbackContext = this.game;
  9875. /**
  9876. * @property {function} touchStartCallback - A callback that can be fired on a touchStart event.
  9877. */
  9878. this.touchStartCallback = null;
  9879. /**
  9880. * @property {function} touchMoveCallback - A callback that can be fired on a touchMove event.
  9881. */
  9882. this.touchMoveCallback = null;
  9883. /**
  9884. * @property {function} touchEndCallback - A callback that can be fired on a touchEnd event.
  9885. */
  9886. this.touchEndCallback = null;
  9887. /**
  9888. * @property {function} touchEnterCallback - A callback that can be fired on a touchEnter event.
  9889. */
  9890. this.touchEnterCallback = null;
  9891. /**
  9892. * @property {function} touchLeaveCallback - A callback that can be fired on a touchLeave event.
  9893. */
  9894. this.touchLeaveCallback = null;
  9895. /**
  9896. * @property {function} touchCancelCallback - A callback that can be fired on a touchCancel event.
  9897. */
  9898. this.touchCancelCallback = null;
  9899. /**
  9900. * @property {boolean} preventDefault - If true the TouchEvent will have prevent.default called on it.
  9901. * @default
  9902. */
  9903. this.preventDefault = true;
  9904. /**
  9905. * @property {TouchEvent} event - The browser touch DOM event. Will be set to null if no touch event has ever been received.
  9906. * @default
  9907. */
  9908. this.event = null;
  9909. /**
  9910. * @property {function} _onTouchStart - Internal event handler reference.
  9911. * @private
  9912. */
  9913. this._onTouchStart = null;
  9914. /**
  9915. * @property {function} _onTouchMove - Internal event handler reference.
  9916. * @private
  9917. */
  9918. this._onTouchMove = null;
  9919. /**
  9920. * @property {function} _onTouchEnd - Internal event handler reference.
  9921. * @private
  9922. */
  9923. this._onTouchEnd = null;
  9924. /**
  9925. * @property {function} _onTouchEnter - Internal event handler reference.
  9926. * @private
  9927. */
  9928. this._onTouchEnter = null;
  9929. /**
  9930. * @property {function} _onTouchLeave - Internal event handler reference.
  9931. * @private
  9932. */
  9933. this._onTouchLeave = null;
  9934. /**
  9935. * @property {function} _onTouchCancel - Internal event handler reference.
  9936. * @private
  9937. */
  9938. this._onTouchCancel = null;
  9939. /**
  9940. * @property {function} _onTouchMove - Internal event handler reference.
  9941. * @private
  9942. */
  9943. this._onTouchMove = null;
  9944. };
  9945. Phaser.Touch.prototype = {
  9946. /**
  9947. * Starts the event listeners running.
  9948. * @method Phaser.Touch#start
  9949. */
  9950. start: function () {
  9951. if (this._onTouchStart !== null)
  9952. {
  9953. // Avoid setting multiple listeners
  9954. return;
  9955. }
  9956. var _this = this;
  9957. if (this.game.device.touch)
  9958. {
  9959. this._onTouchStart = function (event) {
  9960. return _this.onTouchStart(event);
  9961. };
  9962. this._onTouchMove = function (event) {
  9963. return _this.onTouchMove(event);
  9964. };
  9965. this._onTouchEnd = function (event) {
  9966. return _this.onTouchEnd(event);
  9967. };
  9968. this._onTouchEnter = function (event) {
  9969. return _this.onTouchEnter(event);
  9970. };
  9971. this._onTouchLeave = function (event) {
  9972. return _this.onTouchLeave(event);
  9973. };
  9974. this._onTouchCancel = function (event) {
  9975. return _this.onTouchCancel(event);
  9976. };
  9977. this.game.canvas.addEventListener('touchstart', this._onTouchStart, false);
  9978. this.game.canvas.addEventListener('touchmove', this._onTouchMove, false);
  9979. this.game.canvas.addEventListener('touchend', this._onTouchEnd, false);
  9980. this.game.canvas.addEventListener('touchenter', this._onTouchEnter, false);
  9981. this.game.canvas.addEventListener('touchleave', this._onTouchLeave, false);
  9982. this.game.canvas.addEventListener('touchcancel', this._onTouchCancel, false);
  9983. }
  9984. },
  9985. /**
  9986. * Consumes all touchmove events on the document (only enable this if you know you need it!).
  9987. * @method Phaser.Touch#consumeTouchMove
  9988. */
  9989. consumeDocumentTouches: function () {
  9990. this._documentTouchMove = function (event) {
  9991. event.preventDefault();
  9992. };
  9993. document.addEventListener('touchmove', this._documentTouchMove, false);
  9994. },
  9995. /**
  9996. * The internal method that handles the touchstart event from the browser.
  9997. * @method Phaser.Touch#onTouchStart
  9998. * @param {TouchEvent} event - The native event from the browser. This gets stored in Touch.event.
  9999. */
  10000. onTouchStart: function (event) {
  10001. this.event = event;
  10002. if (this.touchStartCallback)
  10003. {
  10004. this.touchStartCallback.call(this.callbackContext, event);
  10005. }
  10006. if (this.game.input.disabled || this.disabled)
  10007. {
  10008. return;
  10009. }
  10010. if (this.preventDefault)
  10011. {
  10012. event.preventDefault();
  10013. }
  10014. // event.targetTouches = list of all touches on the TARGET ELEMENT (i.e. game dom element)
  10015. // event.touches = list of all touches on the ENTIRE DOCUMENT, not just the target element
  10016. // event.changedTouches = the touches that CHANGED in this event, not the total number of them
  10017. for (var i = 0; i < event.changedTouches.length; i++)
  10018. {
  10019. this.game.input.startPointer(event.changedTouches[i]);
  10020. }
  10021. },
  10022. /**
  10023. * Touch cancel - touches that were disrupted (perhaps by moving into a plugin or browser chrome).
  10024. * Occurs for example on iOS when you put down 4 fingers and the app selector UI appears.
  10025. * @method Phaser.Touch#onTouchCancel
  10026. * @param {TouchEvent} event - The native event from the browser. This gets stored in Touch.event.
  10027. */
  10028. onTouchCancel: function (event) {
  10029. this.event = event;
  10030. if (this.touchCancelCallback)
  10031. {
  10032. this.touchCancelCallback.call(this.callbackContext, event);
  10033. }
  10034. if (this.game.input.disabled || this.disabled)
  10035. {
  10036. return;
  10037. }
  10038. if (this.preventDefault)
  10039. {
  10040. event.preventDefault();
  10041. }
  10042. // Touch cancel - touches that were disrupted (perhaps by moving into a plugin or browser chrome)
  10043. // http://www.w3.org/TR/touch-events/#dfn-touchcancel
  10044. for (var i = 0; i < event.changedTouches.length; i++)
  10045. {
  10046. this.game.input.stopPointer(event.changedTouches[i]);
  10047. }
  10048. },
  10049. /**
  10050. * For touch enter and leave its a list of the touch points that have entered or left the target.
  10051. * Doesn't appear to be supported by most browsers on a canvas element yet.
  10052. * @method Phaser.Touch#onTouchEnter
  10053. * @param {TouchEvent} event - The native event from the browser. This gets stored in Touch.event.
  10054. */
  10055. onTouchEnter: function (event) {
  10056. this.event = event;
  10057. if (this.touchEnterCallback)
  10058. {
  10059. this.touchEnterCallback.call(this.callbackContext, event);
  10060. }
  10061. if (this.game.input.disabled || this.disabled)
  10062. {
  10063. return;
  10064. }
  10065. if (this.preventDefault)
  10066. {
  10067. event.preventDefault();
  10068. }
  10069. },
  10070. /**
  10071. * For touch enter and leave its a list of the touch points that have entered or left the target.
  10072. * Doesn't appear to be supported by most browsers on a canvas element yet.
  10073. * @method Phaser.Touch#onTouchLeave
  10074. * @param {TouchEvent} event - The native event from the browser. This gets stored in Touch.event.
  10075. */
  10076. onTouchLeave: function (event) {
  10077. this.event = event;
  10078. if (this.touchLeaveCallback)
  10079. {
  10080. this.touchLeaveCallback.call(this.callbackContext, event);
  10081. }
  10082. if (this.preventDefault)
  10083. {
  10084. event.preventDefault();
  10085. }
  10086. },
  10087. /**
  10088. * The handler for the touchmove events.
  10089. * @method Phaser.Touch#onTouchMove
  10090. * @param {TouchEvent} event - The native event from the browser. This gets stored in Touch.event.
  10091. */
  10092. onTouchMove: function (event) {
  10093. this.event = event;
  10094. if (this.touchMoveCallback)
  10095. {
  10096. this.touchMoveCallback.call(this.callbackContext, event);
  10097. }
  10098. if (this.preventDefault)
  10099. {
  10100. event.preventDefault();
  10101. }
  10102. for (var i = 0; i < event.changedTouches.length; i++)
  10103. {
  10104. this.game.input.updatePointer(event.changedTouches[i]);
  10105. }
  10106. },
  10107. /**
  10108. * The handler for the touchend events.
  10109. * @method Phaser.Touch#onTouchEnd
  10110. * @param {TouchEvent} event - The native event from the browser. This gets stored in Touch.event.
  10111. */
  10112. onTouchEnd: function (event) {
  10113. this.event = event;
  10114. if (this.touchEndCallback)
  10115. {
  10116. this.touchEndCallback.call(this.callbackContext, event);
  10117. }
  10118. if (this.preventDefault)
  10119. {
  10120. event.preventDefault();
  10121. }
  10122. // For touch end its a list of the touch points that have been removed from the surface
  10123. // https://developer.mozilla.org/en-US/docs/DOM/TouchList
  10124. // event.changedTouches = the touches that CHANGED in this event, not the total number of them
  10125. for (var i = 0; i < event.changedTouches.length; i++)
  10126. {
  10127. this.game.input.stopPointer(event.changedTouches[i]);
  10128. }
  10129. },
  10130. /**
  10131. * Stop the event listeners.
  10132. * @method Phaser.Touch#stop
  10133. */
  10134. stop: function () {
  10135. if (this.game.device.touch)
  10136. {
  10137. this.game.canvas.removeEventListener('touchstart', this._onTouchStart);
  10138. this.game.canvas.removeEventListener('touchmove', this._onTouchMove);
  10139. this.game.canvas.removeEventListener('touchend', this._onTouchEnd);
  10140. this.game.canvas.removeEventListener('touchenter', this._onTouchEnter);
  10141. this.game.canvas.removeEventListener('touchleave', this._onTouchLeave);
  10142. this.game.canvas.removeEventListener('touchcancel', this._onTouchCancel);
  10143. }
  10144. }
  10145. };
  10146. Phaser.Touch.prototype.constructor = Phaser.Touch;
  10147. /**
  10148. * @author @karlmacklin <tacklemcclean@gmail.com>
  10149. * @copyright 2014 Photon Storm Ltd.
  10150. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  10151. */
  10152. /**
  10153. * The Gamepad class handles looking after gamepad input for your game.
  10154. * Remember to call gamepad.start(); expecting input!
  10155. *
  10156. * HTML5 GAMEPAD API SUPPORT IS AT AN EXPERIMENTAL STAGE!
  10157. * At moment of writing this (end of 2013) only Chrome supports parts of it out of the box. Firefox supports it
  10158. * via prefs flags (about:config, search gamepad). The browsers map the same controllers differently.
  10159. * This class has constans for Windows 7 Chrome mapping of
  10160. * XBOX 360 controller.
  10161. *
  10162. * @class Phaser.Gamepad
  10163. * @constructor
  10164. * @param {Phaser.Game} game - A reference to the currently running game.
  10165. */
  10166. Phaser.Gamepad = function (game) {
  10167. /**
  10168. * @property {Phaser.Game} game - Local reference to game.
  10169. */
  10170. this.game = game;
  10171. /**
  10172. * @property {Array<Phaser.SinglePad>} _gamepads - The four Phaser Gamepads.
  10173. * @private
  10174. */
  10175. this._gamepads = [
  10176. new Phaser.SinglePad(game, this),
  10177. new Phaser.SinglePad(game, this),
  10178. new Phaser.SinglePad(game, this),
  10179. new Phaser.SinglePad(game, this)
  10180. ];
  10181. /**
  10182. * @property {Object} _gamepadIndexMap - Maps the browsers gamepad indices to our Phaser Gamepads
  10183. * @private
  10184. */
  10185. this._gamepadIndexMap = {};
  10186. /**
  10187. * @property {Array} _rawPads - The raw state of the gamepads from the browser
  10188. * @private
  10189. */
  10190. this._rawPads = [];
  10191. /**
  10192. * @property {boolean} _active - Private flag for whether or not the API is polled
  10193. * @private
  10194. * @default
  10195. */
  10196. this._active = false;
  10197. /**
  10198. * You can disable all Gamepad Input by setting disabled to true. While true all new input related events will be ignored.
  10199. * @property {boolean} disabled - The disabled state of the Gamepad.
  10200. * @default
  10201. */
  10202. this.disabled = false;
  10203. /**
  10204. * 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.
  10205. * @property {boolean} _gamepadSupportAvailable - Are gamepads supported in this browser or not?
  10206. * @private
  10207. */
  10208. this._gamepadSupportAvailable = !!navigator.webkitGetGamepads || !!navigator.webkitGamepads || (navigator.userAgent.indexOf('Firefox/') != -1) || !!navigator.getGamepads;
  10209. /**
  10210. * Used to check for differences between earlier polls and current state of gamepads.
  10211. * @property {Array} _prevRawGamepadTypes
  10212. * @private
  10213. * @default
  10214. */
  10215. this._prevRawGamepadTypes = [];
  10216. /**
  10217. * Used to check for differences between earlier polls and current state of gamepads.
  10218. * @property {Array} _prevTimestamps
  10219. * @private
  10220. * @default
  10221. */
  10222. this._prevTimestamps = [];
  10223. /**
  10224. * @property {Object} callbackContext - The context under which the callbacks are run.
  10225. */
  10226. this.callbackContext = this;
  10227. /**
  10228. * @property {function} onConnectCallback - This callback is invoked every time any gamepad is connected
  10229. */
  10230. this.onConnectCallback = null;
  10231. /**
  10232. * @property {function} onDisconnectCallback - This callback is invoked every time any gamepad is disconnected
  10233. */
  10234. this.onDisconnectCallback = null;
  10235. /**
  10236. * @property {function} onDownCallback - This callback is invoked every time any gamepad button is pressed down.
  10237. */
  10238. this.onDownCallback = null;
  10239. /**
  10240. * @property {function} onUpCallback - This callback is invoked every time any gamepad button is released.
  10241. */
  10242. this.onUpCallback = null;
  10243. /**
  10244. * @property {function} onAxisCallback - This callback is invoked every time any gamepad axis is changed.
  10245. */
  10246. this.onAxisCallback = null;
  10247. /**
  10248. * @property {function} onFloatCallback - This callback is invoked every time any gamepad button is changed to a value where value > 0 and value < 1.
  10249. */
  10250. this.onFloatCallback = null;
  10251. /**
  10252. * @property {function} _ongamepadconnected - Private callback for Firefox gamepad connection handling
  10253. * @private
  10254. */
  10255. this._ongamepadconnected = null;
  10256. /**
  10257. * @property {function} _gamepaddisconnected - Private callback for Firefox gamepad connection handling
  10258. * @private
  10259. */
  10260. this._gamepaddisconnected = null;
  10261. };
  10262. Phaser.Gamepad.prototype = {
  10263. /**
  10264. * Add callbacks to the main Gamepad handler to handle connect/disconnect/button down/button up/axis change/float value buttons
  10265. * @method Phaser.Gamepad#addCallbacks
  10266. * @param {Object} context - The context under which the callbacks are run.
  10267. * @param {Object} callbacks - Object that takes six different callback methods:
  10268. * onConnectCallback, onDisconnectCallback, onDownCallback, onUpCallback, onAxisCallback, onFloatCallback
  10269. */
  10270. addCallbacks: function (context, callbacks) {
  10271. if (typeof callbacks !== 'undefined')
  10272. {
  10273. this.onConnectCallback = (typeof callbacks.onConnect === 'function') ? callbacks.onConnect : this.onConnectCallback;
  10274. this.onDisconnectCallback = (typeof callbacks.onDisconnect === 'function') ? callbacks.onDisconnect : this.onDisconnectCallback;
  10275. this.onDownCallback = (typeof callbacks.onDown === 'function') ? callbacks.onDown : this.onDownCallback;
  10276. this.onUpCallback = (typeof callbacks.onUp === 'function') ? callbacks.onUp : this.onUpCallback;
  10277. this.onAxisCallback = (typeof callbacks.onAxis === 'function') ? callbacks.onAxis : this.onAxisCallback;
  10278. this.onFloatCallback = (typeof callbacks.onFloat === 'function') ? callbacks.onFloat : this.onFloatCallback;
  10279. }
  10280. },
  10281. /**
  10282. * Starts the Gamepad event handling.
  10283. * This MUST be called manually before Phaser will start polling the Gamepad API.
  10284. *
  10285. * @method Phaser.Gamepad#start
  10286. */
  10287. start: function () {
  10288. if (this._active)
  10289. {
  10290. // Avoid setting multiple listeners
  10291. return;
  10292. }
  10293. this._active = true;
  10294. var _this = this;
  10295. this._ongamepadconnected = function(event) {
  10296. var newPad = event.gamepad;
  10297. _this._rawPads.push(newPad);
  10298. _this._gamepads[newPad.index].connect(newPad);
  10299. };
  10300. window.addEventListener('gamepadconnected', this._ongamepadconnected, false);
  10301. this._ongamepaddisconnected = function(event) {
  10302. var removedPad = event.gamepad;
  10303. for (var i in _this._rawPads)
  10304. {
  10305. if (_this._rawPads[i].index === removedPad.index)
  10306. {
  10307. _this._rawPads.splice(i,1);
  10308. }
  10309. }
  10310. _this._gamepads[removedPad.index].disconnect();
  10311. };
  10312. window.addEventListener('gamepaddisconnected', this._ongamepaddisconnected, false);
  10313. },
  10314. /**
  10315. * Main gamepad update loop. Should not be called manually.
  10316. * @method Phaser.Gamepad#update
  10317. * @private
  10318. */
  10319. update: function () {
  10320. this._pollGamepads();
  10321. for (var i = 0; i < this._gamepads.length; i++)
  10322. {
  10323. if (this._gamepads[i]._connected)
  10324. {
  10325. this._gamepads[i].pollStatus();
  10326. }
  10327. }
  10328. },
  10329. /**
  10330. * Updating connected gamepads (for Google Chrome).
  10331. * Should not be called manually.
  10332. * @method Phaser.Gamepad#_pollGamepads
  10333. * @private
  10334. */
  10335. _pollGamepads: function () {
  10336. var rawGamepads = navigator.getGamepads || (navigator.webkitGetGamepads && navigator.webkitGetGamepads()) || navigator.webkitGamepads;
  10337. if (rawGamepads)
  10338. {
  10339. this._rawPads = [];
  10340. var gamepadsChanged = false;
  10341. for (var i = 0; i < rawGamepads.length; i++)
  10342. {
  10343. if (typeof rawGamepads[i] !== this._prevRawGamepadTypes[i])
  10344. {
  10345. gamepadsChanged = true;
  10346. this._prevRawGamepadTypes[i] = typeof rawGamepads[i];
  10347. }
  10348. if (rawGamepads[i])
  10349. {
  10350. this._rawPads.push(rawGamepads[i]);
  10351. }
  10352. // Support max 4 pads at the moment
  10353. if (i === 3)
  10354. {
  10355. break;
  10356. }
  10357. }
  10358. if (gamepadsChanged)
  10359. {
  10360. var validConnections = { rawIndices: {}, padIndices: {} };
  10361. var singlePad;
  10362. for (var j = 0; j < this._gamepads.length; j++)
  10363. {
  10364. singlePad = this._gamepads[j];
  10365. if (singlePad.connected)
  10366. {
  10367. for (var k = 0; k < this._rawPads.length; k++)
  10368. {
  10369. if (this._rawPads[k].index === singlePad.index)
  10370. {
  10371. validConnections.rawIndices[singlePad.index] = true;
  10372. validConnections.padIndices[j] = true;
  10373. }
  10374. }
  10375. }
  10376. }
  10377. for (var l = 0; l < this._gamepads.length; l++)
  10378. {
  10379. singlePad = this._gamepads[l];
  10380. if (validConnections.padIndices[l])
  10381. {
  10382. continue;
  10383. }
  10384. if (this._rawPads.length < 1)
  10385. {
  10386. singlePad.disconnect();
  10387. }
  10388. for (var m = 0; m < this._rawPads.length; m++)
  10389. {
  10390. if (validConnections.padIndices[l])
  10391. {
  10392. break;
  10393. }
  10394. var rawPad = this._rawPads[m];
  10395. if (rawPad)
  10396. {
  10397. if (validConnections.rawIndices[rawPad.index])
  10398. {
  10399. singlePad.disconnect();
  10400. continue;
  10401. }
  10402. else
  10403. {
  10404. singlePad.connect(rawPad);
  10405. validConnections.rawIndices[rawPad.index] = true;
  10406. validConnections.padIndices[l] = true;
  10407. }
  10408. }
  10409. else
  10410. {
  10411. singlePad.disconnect();
  10412. }
  10413. }
  10414. }
  10415. }
  10416. }
  10417. },
  10418. /**
  10419. * Sets the deadZone variable for all four gamepads
  10420. * @method Phaser.Gamepad#setDeadZones
  10421. */
  10422. setDeadZones: function (value) {
  10423. for (var i = 0; i < this._gamepads.length; i++)
  10424. {
  10425. this._gamepads[i].deadZone = value;
  10426. }
  10427. },
  10428. /**
  10429. * Stops the Gamepad event handling.
  10430. *
  10431. * @method Phaser.Gamepad#stop
  10432. */
  10433. stop: function () {
  10434. this._active = false;
  10435. window.removeEventListener('gamepadconnected', this._ongamepadconnected);
  10436. window.removeEventListener('gamepaddisconnected', this._ongamepaddisconnected);
  10437. },
  10438. /**
  10439. * Reset all buttons/axes of all gamepads
  10440. * @method Phaser.Gamepad#reset
  10441. */
  10442. reset: function () {
  10443. this.update();
  10444. for (var i = 0; i < this._gamepads.length; i++)
  10445. {
  10446. this._gamepads[i].reset();
  10447. }
  10448. },
  10449. /**
  10450. * 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).
  10451. * @method Phaser.Gamepad#justPressed
  10452. * @param {number} buttonCode - The buttonCode of the button to check for.
  10453. * @param {number} [duration=250] - The duration below which the button is considered as being just pressed.
  10454. * @return {boolean} True if the button is just pressed otherwise false.
  10455. */
  10456. justPressed: function (buttonCode, duration) {
  10457. for (var i = 0; i < this._gamepads.length; i++)
  10458. {
  10459. if (this._gamepads[i].justPressed(buttonCode, duration) === true)
  10460. {
  10461. return true;
  10462. }
  10463. }
  10464. return false;
  10465. },
  10466. /**
  10467. * 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).
  10468. * @method Phaser.Gamepad#justPressed
  10469. * @param {number} buttonCode - The buttonCode of the button to check for.
  10470. * @param {number} [duration=250] - The duration below which the button is considered as being just released.
  10471. * @return {boolean} True if the button is just released otherwise false.
  10472. */
  10473. justReleased: function (buttonCode, duration) {
  10474. for (var i = 0; i < this._gamepads.length; i++)
  10475. {
  10476. if (this._gamepads[i].justReleased(buttonCode, duration) === true)
  10477. {
  10478. return true;
  10479. }
  10480. }
  10481. return false;
  10482. },
  10483. /**
  10484. * Returns true if the button is currently pressed down, on ANY gamepad.
  10485. * @method Phaser.Gamepad#isDown
  10486. * @param {number} buttonCode - The buttonCode of the button to check for.
  10487. * @return {boolean} True if a button is currently down.
  10488. */
  10489. isDown: function (buttonCode) {
  10490. for (var i = 0; i < this._gamepads.length; i++)
  10491. {
  10492. if (this._gamepads[i].isDown(buttonCode) === true)
  10493. {
  10494. return true;
  10495. }
  10496. }
  10497. return false;
  10498. }
  10499. };
  10500. Phaser.Gamepad.prototype.constructor = Phaser.Gamepad;
  10501. /**
  10502. * If the gamepad input is active or not - if not active it should not be updated from Input.js
  10503. * @name Phaser.Gamepad#active
  10504. * @property {boolean} active - If the gamepad input is active or not.
  10505. * @readonly
  10506. */
  10507. Object.defineProperty(Phaser.Gamepad.prototype, "active", {
  10508. get: function () {
  10509. return this._active;
  10510. }
  10511. });
  10512. /**
  10513. * Whether or not gamepads are supported in current browser.
  10514. * @name Phaser.Gamepad#supported
  10515. * @property {boolean} supported - Whether or not gamepads are supported in current browser.
  10516. * @readonly
  10517. */
  10518. Object.defineProperty(Phaser.Gamepad.prototype, "supported", {
  10519. get: function () {
  10520. return this._gamepadSupportAvailable;
  10521. }
  10522. });
  10523. /**
  10524. * How many live gamepads are currently connected.
  10525. * @name Phaser.Gamepad#padsConnected
  10526. * @property {boolean} padsConnected - How many live gamepads are currently connected.
  10527. * @readonly
  10528. */
  10529. Object.defineProperty(Phaser.Gamepad.prototype, "padsConnected", {
  10530. get: function () {
  10531. return this._rawPads.length;
  10532. }
  10533. });
  10534. /**
  10535. * Gamepad #1
  10536. * @name Phaser.Gamepad#pad1
  10537. * @property {boolean} pad1 - Gamepad #1;
  10538. * @readonly
  10539. */
  10540. Object.defineProperty(Phaser.Gamepad.prototype, "pad1", {
  10541. get: function () {
  10542. return this._gamepads[0];
  10543. }
  10544. });
  10545. /**
  10546. * Gamepad #2
  10547. * @name Phaser.Gamepad#pad2
  10548. * @property {boolean} pad2 - Gamepad #2
  10549. * @readonly
  10550. */
  10551. Object.defineProperty(Phaser.Gamepad.prototype, "pad2", {
  10552. get: function () {
  10553. return this._gamepads[1];
  10554. }
  10555. });
  10556. /**
  10557. * Gamepad #3
  10558. * @name Phaser.Gamepad#pad3
  10559. * @property {boolean} pad3 - Gamepad #3
  10560. * @readonly
  10561. */
  10562. Object.defineProperty(Phaser.Gamepad.prototype, "pad3", {
  10563. get: function () {
  10564. return this._gamepads[2];
  10565. }
  10566. });
  10567. /**
  10568. * Gamepad #4
  10569. * @name Phaser.Gamepad#pad4
  10570. * @property {boolean} pad4 - Gamepad #4
  10571. * @readonly
  10572. */
  10573. Object.defineProperty(Phaser.Gamepad.prototype, "pad4", {
  10574. get: function () {
  10575. return this._gamepads[3];
  10576. }
  10577. });
  10578. Phaser.Gamepad.BUTTON_0 = 0;
  10579. Phaser.Gamepad.BUTTON_1 = 1;
  10580. Phaser.Gamepad.BUTTON_2 = 2;
  10581. Phaser.Gamepad.BUTTON_3 = 3;
  10582. Phaser.Gamepad.BUTTON_4 = 4;
  10583. Phaser.Gamepad.BUTTON_5 = 5;
  10584. Phaser.Gamepad.BUTTON_6 = 6;
  10585. Phaser.Gamepad.BUTTON_7 = 7;
  10586. Phaser.Gamepad.BUTTON_8 = 8;
  10587. Phaser.Gamepad.BUTTON_9 = 9;
  10588. Phaser.Gamepad.BUTTON_10 = 10;
  10589. Phaser.Gamepad.BUTTON_11 = 11;
  10590. Phaser.Gamepad.BUTTON_12 = 12;
  10591. Phaser.Gamepad.BUTTON_13 = 13;
  10592. Phaser.Gamepad.BUTTON_14 = 14;
  10593. Phaser.Gamepad.BUTTON_15 = 15;
  10594. Phaser.Gamepad.AXIS_0 = 0;
  10595. Phaser.Gamepad.AXIS_1 = 1;
  10596. Phaser.Gamepad.AXIS_2 = 2;
  10597. Phaser.Gamepad.AXIS_3 = 3;
  10598. Phaser.Gamepad.AXIS_4 = 4;
  10599. Phaser.Gamepad.AXIS_5 = 5;
  10600. Phaser.Gamepad.AXIS_6 = 6;
  10601. Phaser.Gamepad.AXIS_7 = 7;
  10602. Phaser.Gamepad.AXIS_8 = 8;
  10603. Phaser.Gamepad.AXIS_9 = 9;
  10604. // Below mapping applies to XBOX 360 Wired and Wireless controller on Google Chrome (tested on Windows 7).
  10605. // - Firefox uses different map! Separate amount of buttons and axes. DPAD = axis and not a button.
  10606. // In other words - discrepancies when using gamepads.
  10607. Phaser.Gamepad.XBOX360_A = 0;
  10608. Phaser.Gamepad.XBOX360_B = 1;
  10609. Phaser.Gamepad.XBOX360_X = 2;
  10610. Phaser.Gamepad.XBOX360_Y = 3;
  10611. Phaser.Gamepad.XBOX360_LEFT_BUMPER = 4;
  10612. Phaser.Gamepad.XBOX360_RIGHT_BUMPER = 5;
  10613. Phaser.Gamepad.XBOX360_LEFT_TRIGGER = 6;
  10614. Phaser.Gamepad.XBOX360_RIGHT_TRIGGER = 7;
  10615. Phaser.Gamepad.XBOX360_BACK = 8;
  10616. Phaser.Gamepad.XBOX360_START = 9;
  10617. Phaser.Gamepad.XBOX360_STICK_LEFT_BUTTON = 10;
  10618. Phaser.Gamepad.XBOX360_STICK_RIGHT_BUTTON = 11;
  10619. Phaser.Gamepad.XBOX360_DPAD_LEFT = 14;
  10620. Phaser.Gamepad.XBOX360_DPAD_RIGHT = 15;
  10621. Phaser.Gamepad.XBOX360_DPAD_UP = 12;
  10622. Phaser.Gamepad.XBOX360_DPAD_DOWN = 13;
  10623. Phaser.Gamepad.XBOX360_STICK_LEFT_X = 0;
  10624. Phaser.Gamepad.XBOX360_STICK_LEFT_Y = 1;
  10625. Phaser.Gamepad.XBOX360_STICK_RIGHT_X = 2;
  10626. Phaser.Gamepad.XBOX360_STICK_RIGHT_Y = 3;
  10627. /**
  10628. * @author @karlmacklin <tacklemcclean@gmail.com>
  10629. * @copyright 2014 Photon Storm Ltd.
  10630. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  10631. */
  10632. /**
  10633. * @class Phaser.SinglePad
  10634. * @classdesc A single Phaser Gamepad
  10635. * @constructor
  10636. * @param {Phaser.Game} game - Current game instance.
  10637. * @param {Object} padParent - The parent Phaser.Gamepad object (all gamepads reside under this)
  10638. */
  10639. Phaser.SinglePad = function (game, padParent) {
  10640. /**
  10641. * @property {Phaser.Game} game - Local reference to game.
  10642. */
  10643. this.game = game;
  10644. /**
  10645. * @property {Phaser.Gamepad} padParent - Main Phaser Gamepad object
  10646. */
  10647. this._padParent = padParent;
  10648. /**
  10649. * @property {number} index - The gamepad index as per browsers data
  10650. * @default
  10651. */
  10652. this._index = null;
  10653. /**
  10654. * @property {Object} _rawPad - The 'raw' gamepad data.
  10655. * @private
  10656. */
  10657. this._rawPad = null;
  10658. /**
  10659. * @property {boolean} _connected - Is this pad connected or not.
  10660. * @private
  10661. */
  10662. this._connected = false;
  10663. /**
  10664. * @property {number} _prevTimestamp - Used to check for differences between earlier polls and current state of gamepads.
  10665. * @private
  10666. */
  10667. this._prevTimestamp = null;
  10668. /**
  10669. * @property {Array} _rawButtons - The 'raw' button state.
  10670. * @private
  10671. */
  10672. this._rawButtons = [];
  10673. /**
  10674. * @property {Array} _buttons - Current Phaser state of the buttons.
  10675. * @private
  10676. */
  10677. this._buttons = [];
  10678. /**
  10679. * @property {Array} _axes - Current axes state.
  10680. * @private
  10681. */
  10682. this._axes = [];
  10683. /**
  10684. * @property {Array} _hotkeys - Hotkey buttons.
  10685. * @private
  10686. */
  10687. this._hotkeys = [];
  10688. /**
  10689. * @property {Object} callbackContext - The context under which the callbacks are run.
  10690. */
  10691. this.callbackContext = this;
  10692. /**
  10693. * @property {function} onConnectCallback - This callback is invoked every time this gamepad is connected
  10694. */
  10695. this.onConnectCallback = null;
  10696. /**
  10697. * @property {function} onDisconnectCallback - This callback is invoked every time this gamepad is disconnected
  10698. */
  10699. this.onDisconnectCallback = null;
  10700. /**
  10701. * @property {function} onDownCallback - This callback is invoked every time a button is pressed down.
  10702. */
  10703. this.onDownCallback = null;
  10704. /**
  10705. * @property {function} onUpCallback - This callback is invoked every time a gamepad button is released.
  10706. */
  10707. this.onUpCallback = null;
  10708. /**
  10709. * @property {function} onAxisCallback - This callback is invoked every time an axis is changed.
  10710. */
  10711. this.onAxisCallback = null;
  10712. /**
  10713. * @property {function} onFloatCallback - This callback is invoked every time a button is changed to a value where value > 0 and value < 1.
  10714. */
  10715. this.onFloatCallback = null;
  10716. /**
  10717. * @property {number} deadZone - Dead zone for axis feedback - within this value you won't trigger updates.
  10718. */
  10719. this.deadZone = 0.26;
  10720. };
  10721. Phaser.SinglePad.prototype = {
  10722. /**
  10723. * Add callbacks to the this Gamepad to handle connect/disconnect/button down/button up/axis change/float value buttons
  10724. * @method Phaser.SinglePad#addCallbacks
  10725. * @param {Object} context - The context under which the callbacks are run.
  10726. * @param {Object} callbacks - Object that takes six different callbak methods:
  10727. * onConnectCallback, onDisconnectCallback, onDownCallback, onUpCallback, onAxisCallback, onFloatCallback
  10728. */
  10729. addCallbacks: function (context, callbacks) {
  10730. if (typeof callbacks !== 'undefined')
  10731. {
  10732. this.onConnectCallback = (typeof callbacks.onConnect === 'function') ? callbacks.onConnect : this.onConnectCallback;
  10733. this.onDisconnectCallback = (typeof callbacks.onDisconnect === 'function') ? callbacks.onDisconnect : this.onDisconnectCallback;
  10734. this.onDownCallback = (typeof callbacks.onDown === 'function') ? callbacks.onDown : this.onDownCallback;
  10735. this.onUpCallback = (typeof callbacks.onUp === 'function') ? callbacks.onUp : this.onUpCallback;
  10736. this.onAxisCallback = (typeof callbacks.onAxis === 'function') ? callbacks.onAxis : this.onAxisCallback;
  10737. this.onFloatCallback = (typeof callbacks.onFloat === 'function') ? callbacks.onFloat : this.onFloatCallback;
  10738. }
  10739. },
  10740. /**
  10741. * If you need more fine-grained control over a Key you can create a new Phaser.Key object via this method.
  10742. * The Key object can then be polled, have events attached to it, etc.
  10743. *
  10744. * @method Phaser.SinglePad#addButton
  10745. * @param {number} buttonCode - The buttonCode of the button, i.e. Phaser.Gamepad.BUTTON_0 or Phaser.Gamepad.BUTTON_1
  10746. * @return {Phaser.GamepadButton} The GamepadButton object which you can store locally and reference directly.
  10747. */
  10748. addButton: function (buttonCode) {
  10749. this._hotkeys[buttonCode] = new Phaser.GamepadButton(this.game, buttonCode);
  10750. return this._hotkeys[buttonCode];
  10751. },
  10752. /**
  10753. * Main update function, should be called by Phaser.Gamepad
  10754. * @method Phaser.SinglePad#pollStatus
  10755. */
  10756. pollStatus: function () {
  10757. if (this._rawPad.timestamp && (this._rawPad.timestamp == this._prevTimestamp))
  10758. {
  10759. return;
  10760. }
  10761. for (var i = 0; i < this._rawPad.buttons.length; i += 1)
  10762. {
  10763. var buttonValue = this._rawPad.buttons[i];
  10764. if (this._rawButtons[i] !== buttonValue)
  10765. {
  10766. if (buttonValue === 1)
  10767. {
  10768. this.processButtonDown(i, buttonValue);
  10769. }
  10770. else if (buttonValue === 0)
  10771. {
  10772. this.processButtonUp(i, buttonValue);
  10773. }
  10774. else
  10775. {
  10776. this.processButtonFloat(i, buttonValue);
  10777. }
  10778. this._rawButtons[i] = buttonValue;
  10779. }
  10780. }
  10781. var axes = this._rawPad.axes;
  10782. for (var j = 0; j < axes.length; j += 1)
  10783. {
  10784. var axis = axes[j];
  10785. if (axis > 0 && axis > this.deadZone || axis < 0 && axis < -this.deadZone)
  10786. {
  10787. this.processAxisChange({axis: j, value: axis});
  10788. }
  10789. else
  10790. {
  10791. this.processAxisChange({axis: j, value: 0});
  10792. }
  10793. }
  10794. this._prevTimestamp = this._rawPad.timestamp;
  10795. },
  10796. /**
  10797. * Gamepad connect function, should be called by Phaser.Gamepad
  10798. * @method Phaser.SinglePad#connect
  10799. * @param {Object} rawPad - The raw gamepad object
  10800. */
  10801. connect: function (rawPad) {
  10802. var triggerCallback = !this._connected;
  10803. this._index = rawPad.index;
  10804. this._connected = true;
  10805. this._rawPad = rawPad;
  10806. this._rawButtons = rawPad.buttons;
  10807. this._axes = rawPad.axes;
  10808. if (triggerCallback && this._padParent.onConnectCallback)
  10809. {
  10810. this._padParent.onConnectCallback.call(this._padParent.callbackContext, this._index);
  10811. }
  10812. if (triggerCallback && this.onConnectCallback)
  10813. {
  10814. this.onConnectCallback.call(this.callbackContext);
  10815. }
  10816. },
  10817. /**
  10818. * Gamepad disconnect function, should be called by Phaser.Gamepad
  10819. * @method Phaser.SinglePad#disconnect
  10820. */
  10821. disconnect: function () {
  10822. var triggerCallback = this._connected;
  10823. this._connected = false;
  10824. this._rawPad = undefined;
  10825. this._rawButtons = [];
  10826. this._buttons = [];
  10827. var disconnectingIndex = this._index;
  10828. this._index = null;
  10829. if (triggerCallback && this._padParent.onDisconnectCallback)
  10830. {
  10831. this._padParent.onDisconnectCallback.call(this._padParent.callbackContext, disconnectingIndex);
  10832. }
  10833. if (triggerCallback && this.onDisconnectCallback)
  10834. {
  10835. this.onDisconnectCallback.call(this.callbackContext);
  10836. }
  10837. },
  10838. /**
  10839. * Handles changes in axis
  10840. * @method Phaser.SinglePad#processAxisChange
  10841. * @param {Object} axisState - State of the relevant axis
  10842. */
  10843. processAxisChange: function (axisState) {
  10844. if (this.game.input.disabled || this.game.input.gamepad.disabled)
  10845. {
  10846. return;
  10847. }
  10848. if (this._axes[axisState.axis] === axisState.value)
  10849. {
  10850. return;
  10851. }
  10852. this._axes[axisState.axis] = axisState.value;
  10853. if (this._padParent.onAxisCallback)
  10854. {
  10855. this._padParent.onAxisCallback.call(this._padParent.callbackContext, axisState, this._index);
  10856. }
  10857. if (this.onAxisCallback)
  10858. {
  10859. this.onAxisCallback.call(this.callbackContext, axisState);
  10860. }
  10861. },
  10862. /**
  10863. * Handles button down press
  10864. * @method Phaser.SinglePad#processButtonDown
  10865. * @param {number} buttonCode - Which buttonCode of this button
  10866. * @param {Object} value - Button value
  10867. */
  10868. processButtonDown: function (buttonCode, value) {
  10869. if (this.game.input.disabled || this.game.input.gamepad.disabled)
  10870. {
  10871. return;
  10872. }
  10873. if (this._padParent.onDownCallback)
  10874. {
  10875. this._padParent.onDownCallback.call(this._padParent.callbackContext, buttonCode, value, this._index);
  10876. }
  10877. if (this.onDownCallback)
  10878. {
  10879. this.onDownCallback.call(this.callbackContext, buttonCode, value);
  10880. }
  10881. if (this._buttons[buttonCode] && this._buttons[buttonCode].isDown)
  10882. {
  10883. // Key already down and still down, so update
  10884. this._buttons[buttonCode].duration = this.game.time.now - this._buttons[buttonCode].timeDown;
  10885. }
  10886. else
  10887. {
  10888. if (!this._buttons[buttonCode])
  10889. {
  10890. // Not used this button before, so register it
  10891. this._buttons[buttonCode] = {
  10892. isDown: true,
  10893. timeDown: this.game.time.now,
  10894. timeUp: 0,
  10895. duration: 0,
  10896. value: value
  10897. };
  10898. }
  10899. else
  10900. {
  10901. // Button used before but freshly down
  10902. this._buttons[buttonCode].isDown = true;
  10903. this._buttons[buttonCode].timeDown = this.game.time.now;
  10904. this._buttons[buttonCode].duration = 0;
  10905. this._buttons[buttonCode].value = value;
  10906. }
  10907. }
  10908. if (this._hotkeys[buttonCode])
  10909. {
  10910. this._hotkeys[buttonCode].processButtonDown(value);
  10911. }
  10912. },
  10913. /**
  10914. * Handles button release
  10915. * @method Phaser.SinglePad#processButtonUp
  10916. * @param {number} buttonCode - Which buttonCode of this button
  10917. * @param {Object} value - Button value
  10918. */
  10919. processButtonUp: function (buttonCode, value) {
  10920. if (this.game.input.disabled || this.game.input.gamepad.disabled)
  10921. {
  10922. return;
  10923. }
  10924. if (this._padParent.onUpCallback)
  10925. {
  10926. this._padParent.onUpCallback.call(this._padParent.callbackContext, buttonCode, value, this._index);
  10927. }
  10928. if (this.onUpCallback)
  10929. {
  10930. this.onUpCallback.call(this.callbackContext, buttonCode, value);
  10931. }
  10932. if (this._hotkeys[buttonCode])
  10933. {
  10934. this._hotkeys[buttonCode].processButtonUp(value);
  10935. }
  10936. if (this._buttons[buttonCode])
  10937. {
  10938. this._buttons[buttonCode].isDown = false;
  10939. this._buttons[buttonCode].timeUp = this.game.time.now;
  10940. this._buttons[buttonCode].value = value;
  10941. }
  10942. else
  10943. {
  10944. // Not used this button before, so register it
  10945. this._buttons[buttonCode] = {
  10946. isDown: false,
  10947. timeDown: this.game.time.now,
  10948. timeUp: this.game.time.now,
  10949. duration: 0,
  10950. value: value
  10951. };
  10952. }
  10953. },
  10954. /**
  10955. * Handles buttons with floating values (like analog buttons that acts almost like an axis but still registers like a button)
  10956. * @method Phaser.SinglePad#processButtonFloat
  10957. * @param {number} buttonCode - Which buttonCode of this button
  10958. * @param {Object} value - Button value (will range somewhere between 0 and 1, but not specifically 0 or 1.
  10959. */
  10960. processButtonFloat: function (buttonCode, value) {
  10961. if (this.game.input.disabled || this.game.input.gamepad.disabled)
  10962. {
  10963. return;
  10964. }
  10965. if (this._padParent.onFloatCallback)
  10966. {
  10967. this._padParent.onFloatCallback.call(this._padParent.callbackContext, buttonCode, value, this._index);
  10968. }
  10969. if (this.onFloatCallback)
  10970. {
  10971. this.onFloatCallback.call(this.callbackContext, buttonCode, value);
  10972. }
  10973. if (!this._buttons[buttonCode])
  10974. {
  10975. // Not used this button before, so register it
  10976. this._buttons[buttonCode] = { value: value };
  10977. }
  10978. else
  10979. {
  10980. // Button used before but freshly down
  10981. this._buttons[buttonCode].value = value;
  10982. }
  10983. if (this._hotkeys[buttonCode])
  10984. {
  10985. this._hotkeys[buttonCode].processButtonFloat(value);
  10986. }
  10987. },
  10988. /**
  10989. * Returns value of requested axis
  10990. * @method Phaser.SinglePad#axis
  10991. * @param {number} axisCode - The index of the axis to check
  10992. * @return {number} Axis value if available otherwise false
  10993. */
  10994. axis: function (axisCode) {
  10995. if (this._axes[axisCode])
  10996. {
  10997. return this._axes[axisCode];
  10998. }
  10999. return false;
  11000. },
  11001. /**
  11002. * Returns true if the button is currently pressed down.
  11003. * @method Phaser.SinglePad#isDown
  11004. * @param {number} buttonCode - The buttonCode of the key to check.
  11005. * @return {boolean} True if the key is currently down.
  11006. */
  11007. isDown: function (buttonCode) {
  11008. if (this._buttons[buttonCode])
  11009. {
  11010. return this._buttons[buttonCode].isDown;
  11011. }
  11012. return false;
  11013. },
  11014. /**
  11015. * 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).
  11016. * @method Phaser.SinglePad#justReleased
  11017. * @param {number} buttonCode - The buttonCode of the button to check for.
  11018. * @param {number} [duration=250] - The duration below which the button is considered as being just released.
  11019. * @return {boolean} True if the button is just released otherwise false.
  11020. */
  11021. justReleased: function (buttonCode, duration) {
  11022. if (typeof duration === "undefined") { duration = 250; }
  11023. return (this._buttons[buttonCode] && this._buttons[buttonCode].isDown === false && (this.game.time.now - this._buttons[buttonCode].timeUp < duration));
  11024. },
  11025. /**
  11026. * 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).
  11027. * @method Phaser.SinglePad#justPressed
  11028. * @param {number} buttonCode - The buttonCode of the button to check for.
  11029. * @param {number} [duration=250] - The duration below which the button is considered as being just pressed.
  11030. * @return {boolean} True if the button is just pressed otherwise false.
  11031. */
  11032. justPressed: function (buttonCode, duration) {
  11033. if (typeof duration === "undefined") { duration = 250; }
  11034. return (this._buttons[buttonCode] && this._buttons[buttonCode].isDown && this._buttons[buttonCode].duration < duration);
  11035. },
  11036. /**
  11037. * Returns the value of a gamepad button. Intended mainly for cases when you have floating button values, for example
  11038. * analog trigger buttons on the XBOX 360 controller
  11039. * @method Phaser.SinglePad#buttonValue
  11040. * @param {number} buttonCode - The buttonCode of the button to check.
  11041. * @return {boolean} Button value if available otherwise false.
  11042. */
  11043. buttonValue: function (buttonCode) {
  11044. if (this._buttons[buttonCode])
  11045. {
  11046. return this._buttons[buttonCode].value;
  11047. }
  11048. return false;
  11049. },
  11050. /**
  11051. * Reset all buttons/axes of this gamepad
  11052. * @method Phaser.SinglePad#reset
  11053. */
  11054. reset: function () {
  11055. for (var i = 0; i < this._buttons.length; i++)
  11056. {
  11057. this._buttons[i] = 0;
  11058. }
  11059. for (var j = 0; j < this._axes.length; j++)
  11060. {
  11061. this._axes[j] = 0;
  11062. }
  11063. }
  11064. };
  11065. Phaser.SinglePad.prototype.constructor = Phaser.SinglePad;
  11066. /**
  11067. * Whether or not this particular gamepad is connected or not.
  11068. * @name Phaser.SinglePad#connected
  11069. * @property {boolean} connected - Whether or not this particular gamepad is connected or not.
  11070. * @readonly
  11071. */
  11072. Object.defineProperty(Phaser.SinglePad.prototype, "connected", {
  11073. get: function () {
  11074. return this._connected;
  11075. }
  11076. });
  11077. /**
  11078. * Gamepad index as per browser data
  11079. * @name Phaser.SinglePad#index
  11080. * @property {number} index - The gamepad index, used to identify specific gamepads in the browser
  11081. * @readonly
  11082. */
  11083. Object.defineProperty(Phaser.SinglePad.prototype, "index", {
  11084. get: function () {
  11085. return this._index;
  11086. }
  11087. });
  11088. /**
  11089. * @author @karlmacklin <tacklemcclean@gmail.com>
  11090. * @copyright 2014 Photon Storm Ltd.
  11091. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  11092. */
  11093. /**
  11094. * @class Phaser.GamepadButton
  11095. * @classdesc If you need more fine-grained control over the handling of specific buttons you can create and use Phaser.GamepadButton objects.
  11096. * @constructor
  11097. * @param {Phaser.Game} game - Current game instance.
  11098. * @param {number} buttoncode - The button code this GamepadButton is responsible for.
  11099. */
  11100. Phaser.GamepadButton = function (game, buttoncode) {
  11101. /**
  11102. * @property {Phaser.Game} game - A reference to the currently running game.
  11103. */
  11104. this.game = game;
  11105. /**
  11106. * @property {boolean} isDown - The "down" state of the button.
  11107. * @default
  11108. */
  11109. this.isDown = false;
  11110. /**
  11111. * @property {boolean} isUp - The "up" state of the button.
  11112. * @default
  11113. */
  11114. this.isUp = true;
  11115. /**
  11116. * @property {number} timeDown - The timestamp when the button was last pressed down.
  11117. * @default
  11118. */
  11119. this.timeDown = 0;
  11120. /**
  11121. * If the button is down this value holds the duration of that button press and is constantly updated.
  11122. * If the button is up it holds the duration of the previous down session.
  11123. * @property {number} duration - The number of milliseconds this button has been held down for.
  11124. * @default
  11125. */
  11126. this.duration = 0;
  11127. /**
  11128. * @property {number} timeUp - The timestamp when the button was last released.
  11129. * @default
  11130. */
  11131. this.timeUp = 0;
  11132. /**
  11133. * @property {number} repeats - If a button is held down this holds down the number of times the button has 'repeated'.
  11134. * @default
  11135. */
  11136. this.repeats = 0;
  11137. /**
  11138. * @property {number} value - Button value. Mainly useful for checking analog buttons (like shoulder triggers)
  11139. * @default
  11140. */
  11141. this.value = 0;
  11142. /**
  11143. * @property {number} buttonCode - The buttoncode of this button.
  11144. */
  11145. this.buttonCode = buttoncode;
  11146. /**
  11147. * @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).
  11148. */
  11149. this.onDown = new Phaser.Signal();
  11150. /**
  11151. * @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).
  11152. */
  11153. this.onUp = new Phaser.Signal();
  11154. /**
  11155. * @property {Phaser.Signal} onFloat - This Signal is dispatched every time this GamepadButton changes floating value (between (but not exactly) 0 and 1)
  11156. */
  11157. this.onFloat = new Phaser.Signal();
  11158. };
  11159. Phaser.GamepadButton.prototype = {
  11160. /**
  11161. * Called automatically by Phaser.SinglePad.
  11162. * @method Phaser.GamepadButton#processButtonDown
  11163. * @param {Object} value - Button value
  11164. * @protected
  11165. */
  11166. processButtonDown: function (value) {
  11167. if (this.isDown)
  11168. {
  11169. this.duration = this.game.time.now - this.timeDown;
  11170. this.repeats++;
  11171. }
  11172. else
  11173. {
  11174. this.isDown = true;
  11175. this.isUp = false;
  11176. this.timeDown = this.game.time.now;
  11177. this.duration = 0;
  11178. this.repeats = 0;
  11179. this.value = value;
  11180. this.onDown.dispatch(this, value);
  11181. }
  11182. },
  11183. /**
  11184. * Called automatically by Phaser.SinglePad.
  11185. * @method Phaser.GamepadButton#processButtonUp
  11186. * @param {Object} value - Button value
  11187. * @protected
  11188. */
  11189. processButtonUp: function (value) {
  11190. this.isDown = false;
  11191. this.isUp = true;
  11192. this.timeUp = this.game.time.now;
  11193. this.value = value;
  11194. this.onUp.dispatch(this, value);
  11195. },
  11196. /**
  11197. * Called automatically by Phaser.Gamepad.
  11198. * @method Phaser.GamepadButton#processButtonFloat
  11199. * @param {Object} value - Button value
  11200. * @protected
  11201. */
  11202. processButtonFloat: function (value) {
  11203. this.value = value;
  11204. this.onFloat.dispatch(this, value);
  11205. },
  11206. /**
  11207. * 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).
  11208. * @method Phaser.GamepadButton#justPressed
  11209. * @param {number} [duration=250] - The duration below which the button is considered as being just pressed.
  11210. * @return {boolean} True if the button is just pressed otherwise false.
  11211. */
  11212. justPressed: function (duration) {
  11213. if (typeof duration === "undefined") { duration = 250; }
  11214. return (this.isDown && this.duration < duration);
  11215. },
  11216. /**
  11217. * 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).
  11218. * @method Phaser.GamepadButton#justPressed
  11219. * @param {number} [duration=250] - The duration below which the button is considered as being just released.
  11220. * @return {boolean} True if the button is just pressed otherwise false.
  11221. */
  11222. justReleased: function (duration) {
  11223. if (typeof duration === "undefined") { duration = 250; }
  11224. return (this.isDown === false && (this.game.time.now - this.timeUp < duration));
  11225. }
  11226. };
  11227. Phaser.GamepadButton.prototype.constructor = Phaser.GamepadButton;
  11228. /**
  11229. * @author Richard Davey <rich@photonstorm.com>
  11230. * @copyright 2014 Photon Storm Ltd.
  11231. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  11232. */
  11233. /**
  11234. * The Input Handler is bound to a specific Sprite and is responsible for managing all Input events on that Sprite.
  11235. * @class Phaser.InputHandler
  11236. * @constructor
  11237. * @param {Phaser.Sprite} sprite - The Sprite object to which this Input Handler belongs.
  11238. */
  11239. Phaser.InputHandler = function (sprite) {
  11240. /**
  11241. * @property {Phaser.Sprite} sprite - The Sprite object to which this Input Handler belongs.
  11242. */
  11243. this.sprite = sprite;
  11244. /**
  11245. * @property {Phaser.Game} game - A reference to the currently running game.
  11246. */
  11247. this.game = sprite.game;
  11248. /**
  11249. * @property {boolean} enabled - If enabled the Input Handler will process input requests and monitor pointer activity.
  11250. * @default
  11251. */
  11252. this.enabled = false;
  11253. /**
  11254. * @property {number} priorityID - The PriorityID controls which Sprite receives an Input event first if they should overlap.
  11255. * @default
  11256. */
  11257. this.priorityID = 0;
  11258. /**
  11259. * @property {boolean} useHandCursor - On a desktop browser you can set the 'hand' cursor to appear when moving over the Sprite.
  11260. * @default
  11261. */
  11262. this.useHandCursor = false;
  11263. /**
  11264. * @property {boolean} _setHandCursor - Did this Sprite trigger the hand cursor?
  11265. * @private
  11266. */
  11267. this._setHandCursor = false;
  11268. /**
  11269. * @property {boolean} isDragged - true if the Sprite is being currently dragged.
  11270. * @default
  11271. */
  11272. this.isDragged = false;
  11273. /**
  11274. * @property {boolean} allowHorizontalDrag - Controls if the Sprite is allowed to be dragged horizontally.
  11275. * @default
  11276. */
  11277. this.allowHorizontalDrag = true;
  11278. /**
  11279. * @property {boolean} allowVerticalDrag - Controls if the Sprite is allowed to be dragged vertically.
  11280. * @default
  11281. */
  11282. this.allowVerticalDrag = true;
  11283. /**
  11284. * @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.
  11285. * @default
  11286. */
  11287. this.bringToTop = false;
  11288. /**
  11289. * @property {Phaser.Point} snapOffset - A Point object that contains by how far the Sprite snap is offset.
  11290. * @default
  11291. */
  11292. this.snapOffset = null;
  11293. /**
  11294. * @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.
  11295. * @default
  11296. */
  11297. this.snapOnDrag = false;
  11298. /**
  11299. * @property {boolean} snapOnRelease - When the Sprite is dragged this controls if the Sprite will be snapped on release.
  11300. * @default
  11301. */
  11302. this.snapOnRelease = false;
  11303. /**
  11304. * @property {number} snapX - When a Sprite has snapping enabled this holds the width of the snap grid.
  11305. * @default
  11306. */
  11307. this.snapX = 0;
  11308. /**
  11309. * @property {number} snapY - When a Sprite has snapping enabled this holds the height of the snap grid.
  11310. * @default
  11311. */
  11312. this.snapY = 0;
  11313. /**
  11314. * @property {number} snapOffsetX - This defines the top-left X coordinate of the snap grid.
  11315. * @default
  11316. */
  11317. this.snapOffsetX = 0;
  11318. /**
  11319. * @property {number} snapOffsetY - This defines the top-left Y coordinate of the snap grid..
  11320. * @default
  11321. */
  11322. this.snapOffsetY = 0;
  11323. /**
  11324. * Set to true to use pixel perfect hit detection when checking if the pointer is over this Sprite.
  11325. * The x/y coordinates of the pointer are tested against the image in combination with the InputHandler.pixelPerfectAlpha value.
  11326. * 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.
  11327. * @property {number} pixelPerfectOver - Use a pixel perfect check when testing for pointer over.
  11328. * @default
  11329. */
  11330. this.pixelPerfectOver = false;
  11331. /**
  11332. * Set to true to use pixel perfect hit detection when checking if the pointer is over this Sprite when it's clicked or touched.
  11333. * The x/y coordinates of the pointer are tested against the image in combination with the InputHandler.pixelPerfectAlpha value.
  11334. * Warning: This is expensive so only enable if you really need it.
  11335. * @property {number} pixelPerfectClick - Use a pixel perfect check when testing for clicks or touches on the Sprite.
  11336. * @default
  11337. */
  11338. this.pixelPerfectClick = false;
  11339. /**
  11340. * @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.
  11341. * @default
  11342. */
  11343. this.pixelPerfectAlpha = 255;
  11344. /**
  11345. * @property {boolean} draggable - Is this sprite allowed to be dragged by the mouse? true = yes, false = no
  11346. * @default
  11347. */
  11348. this.draggable = false;
  11349. /**
  11350. * @property {Phaser.Rectangle} boundsRect - A region of the game world within which the sprite is restricted during drag.
  11351. * @default
  11352. */
  11353. this.boundsRect = null;
  11354. /**
  11355. * @property {Phaser.Sprite} boundsSprite - A Sprite the bounds of which this sprite is restricted during drag.
  11356. * @default
  11357. */
  11358. this.boundsSprite = null;
  11359. /**
  11360. * If this object is set to consume the pointer event then it will stop all propogation from this object on.
  11361. * 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.
  11362. * @property {boolean} consumePointerEvent
  11363. * @default
  11364. */
  11365. this.consumePointerEvent = false;
  11366. /**
  11367. * @property {boolean} _wasEnabled - Internal cache var.
  11368. * @private
  11369. */
  11370. this._wasEnabled = false;
  11371. /**
  11372. * @property {Phaser.Point} _tempPoint - Internal cache var.
  11373. * @private
  11374. */
  11375. this._tempPoint = new Phaser.Point();
  11376. /**
  11377. * @property {array} _pointerData - Internal cache var.
  11378. * @private
  11379. */
  11380. this._pointerData = [];
  11381. this._pointerData.push({
  11382. id: 0,
  11383. x: 0,
  11384. y: 0,
  11385. isDown: false,
  11386. isUp: false,
  11387. isOver: false,
  11388. isOut: false,
  11389. timeOver: 0,
  11390. timeOut: 0,
  11391. timeDown: 0,
  11392. timeUp: 0,
  11393. downDuration: 0,
  11394. isDragged: false
  11395. });
  11396. };
  11397. Phaser.InputHandler.prototype = {
  11398. /**
  11399. * 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.
  11400. * @method Phaser.InputHandler#start
  11401. * @param {number} priority - Higher priority sprites take click priority over low-priority sprites when they are stacked on-top of each other.
  11402. * @param {boolean} useHandCursor - If true the Sprite will show the hand cursor on mouse-over (doesn't apply to mobile browsers)
  11403. * @return {Phaser.Sprite} The Sprite object to which the Input Handler is bound.
  11404. */
  11405. start: function (priority, useHandCursor) {
  11406. priority = priority || 0;
  11407. if (typeof useHandCursor == 'undefined') { useHandCursor = false; }
  11408. // Turning on
  11409. if (this.enabled === false)
  11410. {
  11411. // Register, etc
  11412. this.game.input.interactiveItems.add(this);
  11413. this.useHandCursor = useHandCursor;
  11414. this.priorityID = priority;
  11415. for (var i = 0; i < 10; i++)
  11416. {
  11417. this._pointerData[i] = {
  11418. id: i,
  11419. x: 0,
  11420. y: 0,
  11421. isDown: false,
  11422. isUp: false,
  11423. isOver: false,
  11424. isOut: false,
  11425. timeOver: 0,
  11426. timeOut: 0,
  11427. timeDown: 0,
  11428. timeUp: 0,
  11429. downDuration: 0,
  11430. isDragged: false
  11431. };
  11432. }
  11433. this.snapOffset = new Phaser.Point();
  11434. this.enabled = true;
  11435. this._wasEnabled = true;
  11436. // Create the signals the Input component will emit
  11437. if (this.sprite.events && this.sprite.events.onInputOver === null)
  11438. {
  11439. this.sprite.events.onInputOver = new Phaser.Signal();
  11440. this.sprite.events.onInputOut = new Phaser.Signal();
  11441. this.sprite.events.onInputDown = new Phaser.Signal();
  11442. this.sprite.events.onInputUp = new Phaser.Signal();
  11443. this.sprite.events.onDragStart = new Phaser.Signal();
  11444. this.sprite.events.onDragStop = new Phaser.Signal();
  11445. }
  11446. }
  11447. this.sprite.events.onAddedToGroup.add(this.addedToGroup, this);
  11448. this.sprite.events.onRemovedFromGroup.add(this.removedFromGroup, this);
  11449. return this.sprite;
  11450. },
  11451. /**
  11452. * Handles when the parent Sprite is added to a new Group.
  11453. *
  11454. * @method Phaser.InputHandler#addedToGroup
  11455. * @private
  11456. */
  11457. addedToGroup: function () {
  11458. if (this._wasEnabled && !this.enabled)
  11459. {
  11460. this.start();
  11461. }
  11462. },
  11463. /**
  11464. * Handles when the parent Sprite is removed from a Group.
  11465. *
  11466. * @method Phaser.InputHandler#removedFromGroup
  11467. * @private
  11468. */
  11469. removedFromGroup: function () {
  11470. if (this.enabled)
  11471. {
  11472. this._wasEnabled = true;
  11473. this.stop();
  11474. }
  11475. else
  11476. {
  11477. this._wasEnabled = false;
  11478. }
  11479. },
  11480. /**
  11481. * Resets the Input Handler and disables it.
  11482. * @method Phaser.InputHandler#reset
  11483. */
  11484. reset: function () {
  11485. this.enabled = false;
  11486. for (var i = 0; i < 10; i++)
  11487. {
  11488. this._pointerData[i] = {
  11489. id: i,
  11490. x: 0,
  11491. y: 0,
  11492. isDown: false,
  11493. isUp: false,
  11494. isOver: false,
  11495. isOut: false,
  11496. timeOver: 0,
  11497. timeOut: 0,
  11498. timeDown: 0,
  11499. timeUp: 0,
  11500. downDuration: 0,
  11501. isDragged: false
  11502. };
  11503. }
  11504. },
  11505. /**
  11506. * Stops the Input Handler from running.
  11507. * @method Phaser.InputHandler#stop
  11508. */
  11509. stop: function () {
  11510. // Turning off
  11511. if (this.enabled === false)
  11512. {
  11513. return;
  11514. }
  11515. else
  11516. {
  11517. // De-register, etc
  11518. this.enabled = false;
  11519. this.game.input.interactiveItems.remove(this);
  11520. }
  11521. },
  11522. /**
  11523. * Clean up memory.
  11524. * @method Phaser.InputHandler#destroy
  11525. */
  11526. destroy: function () {
  11527. if (this.enabled)
  11528. {
  11529. if (this._setHandCursor)
  11530. {
  11531. this.game.canvas.style.cursor = "default";
  11532. this._setHandCursor = false;
  11533. }
  11534. this.enabled = false;
  11535. this.game.input.interactiveItems.remove(this);
  11536. this._pointerData.length = 0;
  11537. this.boundsRect = null;
  11538. this.boundsSprite = null;
  11539. this.sprite = null;
  11540. }
  11541. },
  11542. /**
  11543. * Checks if the object this InputHandler is bound to is valid for consideration in the Pointer move event.
  11544. * This is called by Phaser.Pointer and shouldn't typically be called directly.
  11545. *
  11546. * @method Phaser.InputHandler#validForInput
  11547. * @protected
  11548. * @param {number} highestID - The highest ID currently processed by the Pointer.
  11549. * @param {number} highestRenderID - The highest Render Order ID currently processed by the Pointer.
  11550. * @return {boolean} True if the object this InputHandler is bound to should be considered as valid for input detection.
  11551. */
  11552. validForInput: function (highestID, highestRenderID) {
  11553. if (this.sprite.scale.x === 0 || this.sprite.scale.y === 0)
  11554. {
  11555. return false;
  11556. }
  11557. if (this.pixelPerfectClick || this.pixelPerfectOver)
  11558. {
  11559. return true;
  11560. }
  11561. if (this.priorityID > highestID || (this.priorityID === highestID && this.sprite._cache[3] < highestRenderID))
  11562. {
  11563. return true;
  11564. }
  11565. return false;
  11566. },
  11567. /**
  11568. * The x coordinate of the Input pointer, relative to the top-left of the parent Sprite.
  11569. * This value is only set when the pointer is over this Sprite.
  11570. * @method Phaser.InputHandler#pointerX
  11571. * @param {Phaser.Pointer} pointer
  11572. * @return {number} The x coordinate of the Input pointer.
  11573. */
  11574. pointerX: function (pointer) {
  11575. pointer = pointer || 0;
  11576. return this._pointerData[pointer].x;
  11577. },
  11578. /**
  11579. * The y coordinate of the Input pointer, relative to the top-left of the parent Sprite
  11580. * This value is only set when the pointer is over this Sprite.
  11581. * @method Phaser.InputHandler#pointerY
  11582. * @param {Phaser.Pointer} pointer
  11583. * @return {number} The y coordinate of the Input pointer.
  11584. */
  11585. pointerY: function (pointer) {
  11586. pointer = pointer || 0;
  11587. return this._pointerData[pointer].y;
  11588. },
  11589. /**
  11590. * If the Pointer is touching the touchscreen, or the mouse button is held down, isDown is set to true.
  11591. * @method Phaser.InputHandler#pointerDown
  11592. * @param {Phaser.Pointer} pointer
  11593. * @return {boolean}
  11594. */
  11595. pointerDown: function (pointer) {
  11596. pointer = pointer || 0;
  11597. return this._pointerData[pointer].isDown;
  11598. },
  11599. /**
  11600. * If the Pointer is not touching the touchscreen, or the mouse button is up, isUp is set to true
  11601. * @method Phaser.InputHandler#pointerUp
  11602. * @param {Phaser.Pointer} pointer
  11603. * @return {boolean}
  11604. */
  11605. pointerUp: function (pointer) {
  11606. pointer = pointer || 0;
  11607. return this._pointerData[pointer].isUp;
  11608. },
  11609. /**
  11610. * A timestamp representing when the Pointer first touched the touchscreen.
  11611. * @method Phaser.InputHandler#pointerTimeDown
  11612. * @param {Phaser.Pointer} pointer
  11613. * @return {number}
  11614. */
  11615. pointerTimeDown: function (pointer) {
  11616. pointer = pointer || 0;
  11617. return this._pointerData[pointer].timeDown;
  11618. },
  11619. /**
  11620. * A timestamp representing when the Pointer left the touchscreen.
  11621. * @method Phaser.InputHandler#pointerTimeUp
  11622. * @param {Phaser.Pointer} pointer
  11623. * @return {number}
  11624. */
  11625. pointerTimeUp: function (pointer) {
  11626. pointer = pointer || 0;
  11627. return this._pointerData[pointer].timeUp;
  11628. },
  11629. /**
  11630. * Is the Pointer over this Sprite?
  11631. * @method Phaser.InputHandler#pointerOver
  11632. * @param {number} [index] - The ID number of a Pointer to check. If you don't provide a number it will check all Pointers.
  11633. * @return {boolean} True if the given pointer (if a index was given, or any pointer if not) is over this object.
  11634. */
  11635. pointerOver: function (index) {
  11636. if (this.enabled)
  11637. {
  11638. if (typeof index === 'undefined')
  11639. {
  11640. for (var i = 0; i < 10; i++)
  11641. {
  11642. if (this._pointerData[i].isOver)
  11643. {
  11644. return true;
  11645. }
  11646. }
  11647. }
  11648. else
  11649. {
  11650. return this._pointerData[index].isOver;
  11651. }
  11652. }
  11653. return false;
  11654. },
  11655. /**
  11656. * Is the Pointer outside of this Sprite?
  11657. * @method Phaser.InputHandler#pointerOut
  11658. * @param {number} [index] - The ID number of a Pointer to check. If you don't provide a number it will check all Pointers.
  11659. * @return {boolean} True if the given pointer (if a index was given, or any pointer if not) is out of this object.
  11660. */
  11661. pointerOut: function (index) {
  11662. if (this.enabled)
  11663. {
  11664. if (typeof index === 'undefined')
  11665. {
  11666. for (var i = 0; i < 10; i++)
  11667. {
  11668. if (this._pointerData[i].isOut)
  11669. {
  11670. return true;
  11671. }
  11672. }
  11673. }
  11674. else
  11675. {
  11676. return this._pointerData[index].isOut;
  11677. }
  11678. }
  11679. return false;
  11680. },
  11681. /**
  11682. * A timestamp representing when the Pointer first touched the touchscreen.
  11683. * @method Phaser.InputHandler#pointerTimeOver
  11684. * @param {Phaser.Pointer} pointer
  11685. * @return {number}
  11686. */
  11687. pointerTimeOver: function (pointer) {
  11688. pointer = pointer || 0;
  11689. return this._pointerData[pointer].timeOver;
  11690. },
  11691. /**
  11692. * A timestamp representing when the Pointer left the touchscreen.
  11693. * @method Phaser.InputHandler#pointerTimeOut
  11694. * @param {Phaser.Pointer} pointer
  11695. * @return {number}
  11696. */
  11697. pointerTimeOut: function (pointer) {
  11698. pointer = pointer || 0;
  11699. return this._pointerData[pointer].timeOut;
  11700. },
  11701. /**
  11702. * Is this sprite being dragged by the mouse or not?
  11703. * @method Phaser.InputHandler#pointerDragged
  11704. * @param {Phaser.Pointer} pointer
  11705. * @return {boolean} True if the pointer is dragging an object, otherwise false.
  11706. */
  11707. pointerDragged: function (pointer) {
  11708. pointer = pointer || 0;
  11709. return this._pointerData[pointer].isDragged;
  11710. },
  11711. /**
  11712. * Checks if the given pointer is over this Sprite and can click it.
  11713. * @method Phaser.InputHandler#checkPointerDown
  11714. * @param {Phaser.Pointer} pointer
  11715. * @return {boolean} True if the pointer is down, otherwise false.
  11716. */
  11717. checkPointerDown: function (pointer) {
  11718. if (!this.enabled || !this.sprite || !this.sprite.parent || !this.sprite.visible || !this.sprite.parent.visible)
  11719. {
  11720. return false;
  11721. }
  11722. // Need to pass it a temp point, in case we need it again for the pixel check
  11723. if (this.game.input.hitTest(this.sprite, pointer, this._tempPoint))
  11724. {
  11725. if (this.pixelPerfectClick)
  11726. {
  11727. return this.checkPixel(this._tempPoint.x, this._tempPoint.y);
  11728. }
  11729. else
  11730. {
  11731. return true;
  11732. }
  11733. }
  11734. return false;
  11735. },
  11736. /**
  11737. * Checks if the given pointer is over this Sprite.
  11738. * @method Phaser.InputHandler#checkPointerOver
  11739. * @param {Phaser.Pointer} pointer
  11740. * @return {boolean}
  11741. */
  11742. checkPointerOver: function (pointer) {
  11743. if (!this.enabled || !this.sprite || !this.sprite.parent || !this.sprite.visible || !this.sprite.parent.visible)
  11744. {
  11745. return false;
  11746. }
  11747. // Need to pass it a temp point, in case we need it again for the pixel check
  11748. if (this.game.input.hitTest(this.sprite, pointer, this._tempPoint))
  11749. {
  11750. if (this.pixelPerfectOver)
  11751. {
  11752. return this.checkPixel(this._tempPoint.x, this._tempPoint.y);
  11753. }
  11754. else
  11755. {
  11756. return true;
  11757. }
  11758. }
  11759. return false;
  11760. },
  11761. /**
  11762. * Runs a pixel perfect check against the given x/y coordinates of the Sprite this InputHandler is bound to.
  11763. * It compares the alpha value of the pixel and if >= InputHandler.pixelPerfectAlpha it returns true.
  11764. * @method Phaser.InputHandler#checkPixel
  11765. * @param {number} x - The x coordinate to check.
  11766. * @param {number} y - The y coordinate to check.
  11767. * @param {Phaser.Pointer} [pointer] - The pointer to get the x/y coordinate from if not passed as the first two parameters.
  11768. * @return {boolean} true if there is the alpha of the pixel is >= InputHandler.pixelPerfectAlpha
  11769. */
  11770. checkPixel: function (x, y, pointer) {
  11771. // Grab a pixel from our image into the hitCanvas and then test it
  11772. if (this.sprite.texture.baseTexture.source)
  11773. {
  11774. this.game.input.hitContext.clearRect(0, 0, 1, 1);
  11775. if (x === null && y === null)
  11776. {
  11777. // Use the pointer parameter
  11778. this.game.input.getLocalPosition(this.sprite, pointer, this._tempPoint);
  11779. var x = this._tempPoint.x;
  11780. var y = this._tempPoint.y;
  11781. }
  11782. if (this.sprite.anchor.x !== 0)
  11783. {
  11784. x -= -this.sprite.texture.frame.width * this.sprite.anchor.x;
  11785. }
  11786. if (this.sprite.anchor.y !== 0)
  11787. {
  11788. y -= -this.sprite.texture.frame.height * this.sprite.anchor.y;
  11789. }
  11790. x += this.sprite.texture.frame.x;
  11791. y += this.sprite.texture.frame.y;
  11792. this.game.input.hitContext.drawImage(this.sprite.texture.baseTexture.source, x, y, 1, 1, 0, 0, 1, 1);
  11793. var rgb = this.game.input.hitContext.getImageData(0, 0, 1, 1);
  11794. if (rgb.data[3] >= this.pixelPerfectAlpha)
  11795. {
  11796. return true;
  11797. }
  11798. }
  11799. return false;
  11800. },
  11801. /**
  11802. * Update.
  11803. * @method Phaser.InputHandler#update
  11804. * @protected
  11805. * @param {Phaser.Pointer} pointer
  11806. */
  11807. update: function (pointer) {
  11808. if (this.sprite === null || this.sprite.parent === undefined)
  11809. {
  11810. // Abort. We've been destroyed.
  11811. return;
  11812. }
  11813. if (!this.enabled || !this.sprite.visible || !this.sprite.parent.visible)
  11814. {
  11815. this._pointerOutHandler(pointer);
  11816. return false;
  11817. }
  11818. if (this.draggable && this._draggedPointerID == pointer.id)
  11819. {
  11820. return this.updateDrag(pointer);
  11821. }
  11822. else if (this._pointerData[pointer.id].isOver === true)
  11823. {
  11824. if (this.checkPointerOver(pointer))
  11825. {
  11826. this._pointerData[pointer.id].x = pointer.x - this.sprite.x;
  11827. this._pointerData[pointer.id].y = pointer.y - this.sprite.y;
  11828. return true;
  11829. }
  11830. else
  11831. {
  11832. this._pointerOutHandler(pointer);
  11833. return false;
  11834. }
  11835. }
  11836. },
  11837. /**
  11838. * Internal method handling the pointer over event.
  11839. * @method Phaser.InputHandler#_pointerOverHandler
  11840. * @private
  11841. * @param {Phaser.Pointer} pointer
  11842. */
  11843. _pointerOverHandler: function (pointer) {
  11844. if (this.sprite === null)
  11845. {
  11846. // Abort. We've been destroyed.
  11847. return;
  11848. }
  11849. if (this._pointerData[pointer.id].isOver === false)
  11850. {
  11851. this._pointerData[pointer.id].isOver = true;
  11852. this._pointerData[pointer.id].isOut = false;
  11853. this._pointerData[pointer.id].timeOver = this.game.time.now;
  11854. this._pointerData[pointer.id].x = pointer.x - this.sprite.x;
  11855. this._pointerData[pointer.id].y = pointer.y - this.sprite.y;
  11856. if (this.useHandCursor && this._pointerData[pointer.id].isDragged === false)
  11857. {
  11858. this.game.canvas.style.cursor = "pointer";
  11859. this._setHandCursor = false;
  11860. }
  11861. this.sprite.events.onInputOver.dispatch(this.sprite, pointer);
  11862. }
  11863. },
  11864. /**
  11865. * Internal method handling the pointer out event.
  11866. * @method Phaser.InputHandler#_pointerOutHandler
  11867. * @private
  11868. * @param {Phaser.Pointer} pointer
  11869. */
  11870. _pointerOutHandler: function (pointer) {
  11871. if (this.sprite === null)
  11872. {
  11873. // Abort. We've been destroyed.
  11874. return;
  11875. }
  11876. this._pointerData[pointer.id].isOver = false;
  11877. this._pointerData[pointer.id].isOut = true;
  11878. this._pointerData[pointer.id].timeOut = this.game.time.now;
  11879. if (this.useHandCursor && this._pointerData[pointer.id].isDragged === false)
  11880. {
  11881. this.game.canvas.style.cursor = "default";
  11882. this._setHandCursor = false;
  11883. }
  11884. if (this.sprite && this.sprite.events)
  11885. {
  11886. this.sprite.events.onInputOut.dispatch(this.sprite, pointer);
  11887. }
  11888. },
  11889. /**
  11890. * Internal method handling the touched event.
  11891. * @method Phaser.InputHandler#_touchedHandler
  11892. * @private
  11893. * @param {Phaser.Pointer} pointer
  11894. */
  11895. _touchedHandler: function (pointer) {
  11896. if (this.sprite === null)
  11897. {
  11898. // Abort. We've been destroyed.
  11899. return;
  11900. }
  11901. if (this._pointerData[pointer.id].isDown === false && this._pointerData[pointer.id].isOver === true)
  11902. {
  11903. if (this.pixelPerfectClick && !this.checkPixel(null, null, pointer))
  11904. {
  11905. return;
  11906. }
  11907. this._pointerData[pointer.id].isDown = true;
  11908. this._pointerData[pointer.id].isUp = false;
  11909. this._pointerData[pointer.id].timeDown = this.game.time.now;
  11910. this.sprite.events.onInputDown.dispatch(this.sprite, pointer);
  11911. // Start drag
  11912. if (this.draggable && this.isDragged === false)
  11913. {
  11914. this.startDrag(pointer);
  11915. }
  11916. if (this.bringToTop)
  11917. {
  11918. this.sprite.bringToTop();
  11919. }
  11920. }
  11921. // Consume the event?
  11922. return this.consumePointerEvent;
  11923. },
  11924. /**
  11925. * Internal method handling the pointer released event.
  11926. * @method Phaser.InputHandler#_releasedHandler
  11927. * @private
  11928. * @param {Phaser.Pointer} pointer
  11929. */
  11930. _releasedHandler: function (pointer) {
  11931. if (this.sprite === null)
  11932. {
  11933. // Abort. We've been destroyed.
  11934. return;
  11935. }
  11936. // If was previously touched by this Pointer, check if still is AND still over this item
  11937. if (this._pointerData[pointer.id].isDown && pointer.isUp)
  11938. {
  11939. this._pointerData[pointer.id].isDown = false;
  11940. this._pointerData[pointer.id].isUp = true;
  11941. this._pointerData[pointer.id].timeUp = this.game.time.now;
  11942. this._pointerData[pointer.id].downDuration = this._pointerData[pointer.id].timeUp - this._pointerData[pointer.id].timeDown;
  11943. // Only release the InputUp signal if the pointer is still over this sprite
  11944. if (this.checkPointerOver(pointer))
  11945. {
  11946. // Release the inputUp signal and provide optional parameter if pointer is still over the sprite or not
  11947. this.sprite.events.onInputUp.dispatch(this.sprite, pointer, true);
  11948. }
  11949. else
  11950. {
  11951. // Release the inputUp signal and provide optional parameter if pointer is still over the sprite or not
  11952. this.sprite.events.onInputUp.dispatch(this.sprite, pointer, false);
  11953. // Pointer outside the sprite? Reset the cursor
  11954. if (this.useHandCursor)
  11955. {
  11956. this.game.canvas.style.cursor = "default";
  11957. this._setHandCursor = false;
  11958. }
  11959. }
  11960. // Stop drag
  11961. if (this.draggable && this.isDragged && this._draggedPointerID == pointer.id)
  11962. {
  11963. this.stopDrag(pointer);
  11964. }
  11965. }
  11966. },
  11967. /**
  11968. * Updates the Pointer drag on this Sprite.
  11969. * @method Phaser.InputHandler#updateDrag
  11970. * @param {Phaser.Pointer} pointer
  11971. * @return {boolean}
  11972. */
  11973. updateDrag: function (pointer) {
  11974. if (pointer.isUp)
  11975. {
  11976. this.stopDrag(pointer);
  11977. return false;
  11978. }
  11979. if (this.sprite.fixedToCamera)
  11980. {
  11981. if (this.allowHorizontalDrag)
  11982. {
  11983. this.sprite.cameraOffset.x = pointer.x + this._dragPoint.x + this.dragOffset.x;
  11984. }
  11985. if (this.allowVerticalDrag)
  11986. {
  11987. this.sprite.cameraOffset.y = pointer.y + this._dragPoint.y + this.dragOffset.y;
  11988. }
  11989. if (this.boundsRect)
  11990. {
  11991. this.checkBoundsRect();
  11992. }
  11993. if (this.boundsSprite)
  11994. {
  11995. this.checkBoundsSprite();
  11996. }
  11997. if (this.snapOnDrag)
  11998. {
  11999. this.sprite.cameraOffset.x = Math.round((this.sprite.cameraOffset.x - (this.snapOffsetX % this.snapX)) / this.snapX) * this.snapX + (this.snapOffsetX % this.snapX);
  12000. this.sprite.cameraOffset.y = Math.round((this.sprite.cameraOffset.y - (this.snapOffsetY % this.snapY)) / this.snapY) * this.snapY + (this.snapOffsetY % this.snapY);
  12001. }
  12002. }
  12003. else
  12004. {
  12005. if (this.allowHorizontalDrag)
  12006. {
  12007. this.sprite.x = pointer.x + this._dragPoint.x + this.dragOffset.x;
  12008. }
  12009. if (this.allowVerticalDrag)
  12010. {
  12011. this.sprite.y = pointer.y + this._dragPoint.y + this.dragOffset.y;
  12012. }
  12013. if (this.boundsRect)
  12014. {
  12015. this.checkBoundsRect();
  12016. }
  12017. if (this.boundsSprite)
  12018. {
  12019. this.checkBoundsSprite();
  12020. }
  12021. if (this.snapOnDrag)
  12022. {
  12023. this.sprite.x = Math.round((this.sprite.x - (this.snapOffsetX % this.snapX)) / this.snapX) * this.snapX + (this.snapOffsetX % this.snapX);
  12024. this.sprite.y = Math.round((this.sprite.y - (this.snapOffsetY % this.snapY)) / this.snapY) * this.snapY + (this.snapOffsetY % this.snapY);
  12025. }
  12026. }
  12027. return true;
  12028. },
  12029. /**
  12030. * Returns true if the pointer has entered the Sprite within the specified delay time (defaults to 500ms, half a second)
  12031. * @method Phaser.InputHandler#justOver
  12032. * @param {Phaser.Pointer} pointer
  12033. * @param {number} delay - The time below which the pointer is considered as just over.
  12034. * @return {boolean}
  12035. */
  12036. justOver: function (pointer, delay) {
  12037. pointer = pointer || 0;
  12038. delay = delay || 500;
  12039. return (this._pointerData[pointer].isOver && this.overDuration(pointer) < delay);
  12040. },
  12041. /**
  12042. * Returns true if the pointer has left the Sprite within the specified delay time (defaults to 500ms, half a second)
  12043. * @method Phaser.InputHandler#justOut
  12044. * @param {Phaser.Pointer} pointer
  12045. * @param {number} delay - The time below which the pointer is considered as just out.
  12046. * @return {boolean}
  12047. */
  12048. justOut: function (pointer, delay) {
  12049. pointer = pointer || 0;
  12050. delay = delay || 500;
  12051. return (this._pointerData[pointer].isOut && (this.game.time.now - this._pointerData[pointer].timeOut < delay));
  12052. },
  12053. /**
  12054. * Returns true if the pointer has touched or clicked on the Sprite within the specified delay time (defaults to 500ms, half a second)
  12055. * @method Phaser.InputHandler#justPressed
  12056. * @param {Phaser.Pointer} pointer
  12057. * @param {number} delay - The time below which the pointer is considered as just over.
  12058. * @return {boolean}
  12059. */
  12060. justPressed: function (pointer, delay) {
  12061. pointer = pointer || 0;
  12062. delay = delay || 500;
  12063. return (this._pointerData[pointer].isDown && this.downDuration(pointer) < delay);
  12064. },
  12065. /**
  12066. * Returns true if the pointer was touching this Sprite, but has been released within the specified delay time (defaults to 500ms, half a second)
  12067. * @method Phaser.InputHandler#justReleased
  12068. * @param {Phaser.Pointer} pointer
  12069. * @param {number} delay - The time below which the pointer is considered as just out.
  12070. * @return {boolean}
  12071. */
  12072. justReleased: function (pointer, delay) {
  12073. pointer = pointer || 0;
  12074. delay = delay || 500;
  12075. return (this._pointerData[pointer].isUp && (this.game.time.now - this._pointerData[pointer].timeUp < delay));
  12076. },
  12077. /**
  12078. * If the pointer is currently over this Sprite this returns how long it has been there for in milliseconds.
  12079. * @method Phaser.InputHandler#overDuration
  12080. * @param {Phaser.Pointer} pointer
  12081. * @return {number} The number of milliseconds the pointer has been over the Sprite, or -1 if not over.
  12082. */
  12083. overDuration: function (pointer) {
  12084. pointer = pointer || 0;
  12085. if (this._pointerData[pointer].isOver)
  12086. {
  12087. return this.game.time.now - this._pointerData[pointer].timeOver;
  12088. }
  12089. return -1;
  12090. },
  12091. /**
  12092. * If the pointer is currently over this Sprite this returns how long it has been there for in milliseconds.
  12093. * @method Phaser.InputHandler#downDuration
  12094. * @param {Phaser.Pointer} pointer
  12095. * @return {number} The number of milliseconds the pointer has been pressed down on the Sprite, or -1 if not over.
  12096. */
  12097. downDuration: function (pointer) {
  12098. pointer = pointer || 0;
  12099. if (this._pointerData[pointer].isDown)
  12100. {
  12101. return this.game.time.now - this._pointerData[pointer].timeDown;
  12102. }
  12103. return -1;
  12104. },
  12105. /**
  12106. * Make this Sprite draggable by the mouse. You can also optionally set mouseStartDragCallback and mouseStopDragCallback
  12107. * @method Phaser.InputHandler#enableDrag
  12108. * @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.
  12109. * @param {boolean} [bringToTop=false] - If true the Sprite will be bought to the top of the rendering list in its current Group.
  12110. * @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.
  12111. * @param {boolean} [alphaThreshold=255] - If using pixel perfect collision this specifies the alpha level from 0 to 255 above which a collision is processed.
  12112. * @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.
  12113. * @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.
  12114. */
  12115. enableDrag: function (lockCenter, bringToTop, pixelPerfect, alphaThreshold, boundsRect, boundsSprite) {
  12116. if (typeof lockCenter == 'undefined') { lockCenter = false; }
  12117. if (typeof bringToTop == 'undefined') { bringToTop = false; }
  12118. if (typeof pixelPerfect == 'undefined') { pixelPerfect = false; }
  12119. if (typeof alphaThreshold == 'undefined') { alphaThreshold = 255; }
  12120. if (typeof boundsRect == 'undefined') { boundsRect = null; }
  12121. if (typeof boundsSprite == 'undefined') { boundsSprite = null; }
  12122. this._dragPoint = new Phaser.Point();
  12123. this.draggable = true;
  12124. this.bringToTop = bringToTop;
  12125. this.dragOffset = new Phaser.Point();
  12126. this.dragFromCenter = lockCenter;
  12127. this.pixelPerfect = pixelPerfect;
  12128. this.pixelPerfectAlpha = alphaThreshold;
  12129. if (boundsRect)
  12130. {
  12131. this.boundsRect = boundsRect;
  12132. }
  12133. if (boundsSprite)
  12134. {
  12135. this.boundsSprite = boundsSprite;
  12136. }
  12137. },
  12138. /**
  12139. * 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.
  12140. * @method Phaser.InputHandler#disableDrag
  12141. */
  12142. disableDrag: function () {
  12143. if (this._pointerData)
  12144. {
  12145. for (var i = 0; i < 10; i++)
  12146. {
  12147. this._pointerData[i].isDragged = false;
  12148. }
  12149. }
  12150. this.draggable = false;
  12151. this.isDragged = false;
  12152. this._draggedPointerID = -1;
  12153. },
  12154. /**
  12155. * Called by Pointer when drag starts on this Sprite. Should not usually be called directly.
  12156. * @method Phaser.InputHandler#startDrag
  12157. * @param {Phaser.Pointer} pointer
  12158. */
  12159. startDrag: function (pointer) {
  12160. this.isDragged = true;
  12161. this._draggedPointerID = pointer.id;
  12162. this._pointerData[pointer.id].isDragged = true;
  12163. if (this.sprite.fixedToCamera)
  12164. {
  12165. if (this.dragFromCenter)
  12166. {
  12167. this.sprite.centerOn(pointer.x, pointer.y);
  12168. this._dragPoint.setTo(this.sprite.cameraOffset.x - pointer.x, this.sprite.cameraOffset.y - pointer.y);
  12169. }
  12170. else
  12171. {
  12172. this._dragPoint.setTo(this.sprite.cameraOffset.x - pointer.x, this.sprite.cameraOffset.y - pointer.y);
  12173. }
  12174. }
  12175. else
  12176. {
  12177. if (this.dragFromCenter)
  12178. {
  12179. var bounds = this.sprite.getBounds();
  12180. this.sprite.x = pointer.x + (this.sprite.x - bounds.centerX);
  12181. this.sprite.y = pointer.y + (this.sprite.y - bounds.centerY);
  12182. this._dragPoint.setTo(this.sprite.x - pointer.x, this.sprite.y - pointer.y);
  12183. }
  12184. else
  12185. {
  12186. this._dragPoint.setTo(this.sprite.x - pointer.x, this.sprite.y - pointer.y);
  12187. }
  12188. }
  12189. this.updateDrag(pointer);
  12190. if (this.bringToTop)
  12191. {
  12192. this.sprite.bringToTop();
  12193. }
  12194. this.sprite.events.onDragStart.dispatch(this.sprite, pointer);
  12195. },
  12196. /**
  12197. * Called by Pointer when drag is stopped on this Sprite. Should not usually be called directly.
  12198. * @method Phaser.InputHandler#stopDrag
  12199. * @param {Phaser.Pointer} pointer
  12200. */
  12201. stopDrag: function (pointer) {
  12202. this.isDragged = false;
  12203. this._draggedPointerID = -1;
  12204. this._pointerData[pointer.id].isDragged = false;
  12205. if (this.snapOnRelease)
  12206. {
  12207. if (this.sprite.fixedToCamera)
  12208. {
  12209. this.sprite.cameraOffset.x = Math.round((this.sprite.cameraOffset.x - (this.snapOffsetX % this.snapX)) / this.snapX) * this.snapX + (this.snapOffsetX % this.snapX);
  12210. this.sprite.cameraOffset.y = Math.round((this.sprite.cameraOffset.y - (this.snapOffsetY % this.snapY)) / this.snapY) * this.snapY + (this.snapOffsetY % this.snapY);
  12211. }
  12212. else
  12213. {
  12214. this.sprite.x = Math.round((this.sprite.x - (this.snapOffsetX % this.snapX)) / this.snapX) * this.snapX + (this.snapOffsetX % this.snapX);
  12215. this.sprite.y = Math.round((this.sprite.y - (this.snapOffsetY % this.snapY)) / this.snapY) * this.snapY + (this.snapOffsetY % this.snapY);
  12216. }
  12217. }
  12218. this.sprite.events.onDragStop.dispatch(this.sprite, pointer);
  12219. if (this.checkPointerOver(pointer) === false)
  12220. {
  12221. this._pointerOutHandler(pointer);
  12222. }
  12223. },
  12224. /**
  12225. * Restricts this sprite to drag movement only on the given axis. Note: If both are set to false the sprite will never move!
  12226. * @method Phaser.InputHandler#setDragLock
  12227. * @param {boolean} [allowHorizontal=true] - To enable the sprite to be dragged horizontally set to true, otherwise false.
  12228. * @param {boolean} [allowVertical=true] - To enable the sprite to be dragged vertically set to true, otherwise false.
  12229. */
  12230. setDragLock: function (allowHorizontal, allowVertical) {
  12231. if (typeof allowHorizontal == 'undefined') { allowHorizontal = true; }
  12232. if (typeof allowVertical == 'undefined') { allowVertical = true; }
  12233. this.allowHorizontalDrag = allowHorizontal;
  12234. this.allowVerticalDrag = allowVertical;
  12235. },
  12236. /**
  12237. * Make this Sprite snap to the given grid either during drag or when it's released.
  12238. * For example 16x16 as the snapX and snapY would make the sprite snap to every 16 pixels.
  12239. * @method Phaser.InputHandler#enableSnap
  12240. * @param {number} snapX - The width of the grid cell to snap to.
  12241. * @param {number} snapY - The height of the grid cell to snap to.
  12242. * @param {boolean} [onDrag=true] - If true the sprite will snap to the grid while being dragged.
  12243. * @param {boolean} [onRelease=false] - If true the sprite will snap to the grid when released.
  12244. * @param {number} [snapOffsetX=0] - Used to offset the top-left starting point of the snap grid.
  12245. * @param {number} [snapOffsetX=0] - Used to offset the top-left starting point of the snap grid.
  12246. */
  12247. enableSnap: function (snapX, snapY, onDrag, onRelease, snapOffsetX, snapOffsetY) {
  12248. if (typeof onDrag == 'undefined') { onDrag = true; }
  12249. if (typeof onRelease == 'undefined') { onRelease = false; }
  12250. if (typeof snapOffsetX == 'undefined') { snapOffsetX = 0; }
  12251. if (typeof snapOffsetY == 'undefined') { snapOffsetY = 0; }
  12252. this.snapX = snapX;
  12253. this.snapY = snapY;
  12254. this.snapOffsetX = snapOffsetX;
  12255. this.snapOffsetY = snapOffsetY;
  12256. this.snapOnDrag = onDrag;
  12257. this.snapOnRelease = onRelease;
  12258. },
  12259. /**
  12260. * Stops the sprite from snapping to a grid during drag or release.
  12261. * @method Phaser.InputHandler#disableSnap
  12262. */
  12263. disableSnap: function () {
  12264. this.snapOnDrag = false;
  12265. this.snapOnRelease = false;
  12266. },
  12267. /**
  12268. * Bounds Rect check for the sprite drag
  12269. * @method Phaser.InputHandler#checkBoundsRect
  12270. */
  12271. checkBoundsRect: function () {
  12272. if (this.sprite.fixedToCamera)
  12273. {
  12274. if (this.sprite.cameraOffset.x < this.boundsRect.left)
  12275. {
  12276. this.sprite.cameraOffset.x = this.boundsRect.cameraOffset.x;
  12277. }
  12278. else if ((this.sprite.cameraOffset.x + this.sprite.width) > this.boundsRect.right)
  12279. {
  12280. this.sprite.cameraOffset.x = this.boundsRect.right - this.sprite.width;
  12281. }
  12282. if (this.sprite.cameraOffset.y < this.boundsRect.top)
  12283. {
  12284. this.sprite.cameraOffset.y = this.boundsRect.top;
  12285. }
  12286. else if ((this.sprite.cameraOffset.y + this.sprite.height) > this.boundsRect.bottom)
  12287. {
  12288. this.sprite.cameraOffset.y = this.boundsRect.bottom - this.sprite.height;
  12289. }
  12290. }
  12291. else
  12292. {
  12293. if (this.sprite.x < this.boundsRect.left)
  12294. {
  12295. this.sprite.x = this.boundsRect.x;
  12296. }
  12297. else if ((this.sprite.x + this.sprite.width) > this.boundsRect.right)
  12298. {
  12299. this.sprite.x = this.boundsRect.right - this.sprite.width;
  12300. }
  12301. if (this.sprite.y < this.boundsRect.top)
  12302. {
  12303. this.sprite.y = this.boundsRect.top;
  12304. }
  12305. else if ((this.sprite.y + this.sprite.height) > this.boundsRect.bottom)
  12306. {
  12307. this.sprite.y = this.boundsRect.bottom - this.sprite.height;
  12308. }
  12309. }
  12310. },
  12311. /**
  12312. * Parent Sprite Bounds check for the sprite drag.
  12313. * @method Phaser.InputHandler#checkBoundsSprite
  12314. */
  12315. checkBoundsSprite: function () {
  12316. if (this.sprite.fixedToCamera && this.boundsSprite.fixedToCamera)
  12317. {
  12318. if (this.sprite.cameraOffset.x < this.boundsSprite.camerOffset.x)
  12319. {
  12320. this.sprite.cameraOffset.x = this.boundsSprite.camerOffset.x;
  12321. }
  12322. else if ((this.sprite.cameraOffset.x + this.sprite.width) > (this.boundsSprite.camerOffset.x + this.boundsSprite.width))
  12323. {
  12324. this.sprite.cameraOffset.x = (this.boundsSprite.camerOffset.x + this.boundsSprite.width) - this.sprite.width;
  12325. }
  12326. if (this.sprite.cameraOffset.y < this.boundsSprite.camerOffset.y)
  12327. {
  12328. this.sprite.cameraOffset.y = this.boundsSprite.camerOffset.y;
  12329. }
  12330. else if ((this.sprite.cameraOffset.y + this.sprite.height) > (this.boundsSprite.camerOffset.y + this.boundsSprite.height))
  12331. {
  12332. this.sprite.cameraOffset.y = (this.boundsSprite.camerOffset.y + this.boundsSprite.height) - this.sprite.height;
  12333. }
  12334. }
  12335. else
  12336. {
  12337. if (this.sprite.x < this.boundsSprite.x)
  12338. {
  12339. this.sprite.x = this.boundsSprite.x;
  12340. }
  12341. else if ((this.sprite.x + this.sprite.width) > (this.boundsSprite.x + this.boundsSprite.width))
  12342. {
  12343. this.sprite.x = (this.boundsSprite.x + this.boundsSprite.width) - this.sprite.width;
  12344. }
  12345. if (this.sprite.y < this.boundsSprite.y)
  12346. {
  12347. this.sprite.y = this.boundsSprite.y;
  12348. }
  12349. else if ((this.sprite.y + this.sprite.height) > (this.boundsSprite.y + this.boundsSprite.height))
  12350. {
  12351. this.sprite.y = (this.boundsSprite.y + this.boundsSprite.height) - this.sprite.height;
  12352. }
  12353. }
  12354. }
  12355. };
  12356. Phaser.InputHandler.prototype.constructor = Phaser.InputHandler;
  12357. /**
  12358. * @author Richard Davey <rich@photonstorm.com>
  12359. * @copyright 2014 Photon Storm Ltd.
  12360. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  12361. */
  12362. /**
  12363. * @class Phaser.Events
  12364. *
  12365. * @classdesc The Events component is a collection of events fired by the parent game object.
  12366. *
  12367. * For example to tell when a Sprite has been added to a new group:
  12368. *
  12369. * `sprite.events.onAddedToGroup.add(yourFunction, this);`
  12370. *
  12371. * Where `yourFunction` is the function you want called when this event occurs.
  12372. *
  12373. * Note that the Input related events only exist if the Sprite has had `inputEnabled` set to `true`.
  12374. *
  12375. * @constructor
  12376. *
  12377. * @param {Phaser.Sprite} sprite - A reference to Description.
  12378. */
  12379. Phaser.Events = function (sprite) {
  12380. this.parent = sprite;
  12381. this.onAddedToGroup = new Phaser.Signal();
  12382. this.onRemovedFromGroup = new Phaser.Signal();
  12383. this.onKilled = new Phaser.Signal();
  12384. this.onRevived = new Phaser.Signal();
  12385. this.onOutOfBounds = new Phaser.Signal();
  12386. this.onEnterBounds = new Phaser.Signal();
  12387. this.onInputOver = null;
  12388. this.onInputOut = null;
  12389. this.onInputDown = null;
  12390. this.onInputUp = null;
  12391. this.onDragStart = null;
  12392. this.onDragStop = null;
  12393. this.onAnimationStart = null;
  12394. this.onAnimationComplete = null;
  12395. this.onAnimationLoop = null;
  12396. };
  12397. Phaser.Events.prototype = {
  12398. destroy: function () {
  12399. this.parent = null;
  12400. this.onAddedToGroup.dispose();
  12401. this.onRemovedFromGroup.dispose();
  12402. this.onKilled.dispose();
  12403. this.onRevived.dispose();
  12404. this.onOutOfBounds.dispose();
  12405. if (this.onInputOver)
  12406. {
  12407. this.onInputOver.dispose();
  12408. this.onInputOut.dispose();
  12409. this.onInputDown.dispose();
  12410. this.onInputUp.dispose();
  12411. this.onDragStart.dispose();
  12412. this.onDragStop.dispose();
  12413. }
  12414. if (this.onAnimationStart)
  12415. {
  12416. this.onAnimationStart.dispose();
  12417. this.onAnimationComplete.dispose();
  12418. this.onAnimationLoop.dispose();
  12419. }
  12420. }
  12421. };
  12422. Phaser.Events.prototype.constructor = Phaser.Events;
  12423. /**
  12424. * @author Richard Davey <rich@photonstorm.com>
  12425. * @copyright 2014 Photon Storm Ltd.
  12426. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  12427. */
  12428. /**
  12429. * The Game Object Factory is a quick way to create all of the different sorts of core objects that Phaser uses.
  12430. *
  12431. * @class Phaser.GameObjectFactory
  12432. * @constructor
  12433. * @param {Phaser.Game} game - A reference to the currently running game.
  12434. */
  12435. Phaser.GameObjectFactory = function (game) {
  12436. /**
  12437. * @property {Phaser.Game} game - A reference to the currently running Game.
  12438. */
  12439. this.game = game;
  12440. /**
  12441. * @property {Phaser.World} world - A reference to the game world.
  12442. */
  12443. this.world = this.game.world;
  12444. };
  12445. Phaser.GameObjectFactory.prototype = {
  12446. /**
  12447. * Adds an existing object to the game world.
  12448. * @method Phaser.GameObjectFactory#existing
  12449. * @param {*} object - An instance of Phaser.Sprite, Phaser.Button or any other display object..
  12450. * @return {*} The child that was added to the Group.
  12451. */
  12452. existing: function (object) {
  12453. return this.world.add(object);
  12454. },
  12455. /**
  12456. * 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.
  12457. * It can still rotate, scale, crop and receive input events. This makes it perfect for logos, backgrounds, simple buttons and other non-Sprite graphics.
  12458. *
  12459. * @method Phaser.GameObjectFactory#image
  12460. * @param {number} x - X position of the image.
  12461. * @param {number} y - Y position of the image.
  12462. * @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.
  12463. * @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.
  12464. * @param {Phaser.Group} [group] - Optional Group to add the object to. If not specified it will be added to the World group.
  12465. * @returns {Phaser.Sprite} the newly created sprite object.
  12466. */
  12467. image: function (x, y, key, frame, group) {
  12468. if (typeof group === 'undefined') { group = this.world; }
  12469. return group.add(new Phaser.Image(this.game, x, y, key, frame));
  12470. },
  12471. /**
  12472. * Create a new Sprite with specific position and sprite sheet key.
  12473. *
  12474. * @method Phaser.GameObjectFactory#sprite
  12475. * @param {number} x - X position of the new sprite.
  12476. * @param {number} y - Y position of the new sprite.
  12477. * @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.
  12478. * @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.
  12479. * @param {Phaser.Group} [group] - Optional Group to add the object to. If not specified it will be added to the World group.
  12480. * @returns {Phaser.Sprite} the newly created sprite object.
  12481. */
  12482. sprite: function (x, y, key, frame, group) {
  12483. if (typeof group === 'undefined') { group = this.world; }
  12484. return group.create(x, y, key, frame);
  12485. },
  12486. /**
  12487. * Create a tween object for a specific object. The object can be any JavaScript object or Phaser object such as Sprite.
  12488. *
  12489. * @method Phaser.GameObjectFactory#tween
  12490. * @param {object} obj - Object the tween will be run on.
  12491. * @return {Phaser.Tween} The newly created Phaser.Tween object.
  12492. */
  12493. tween: function (obj) {
  12494. return this.game.tweens.create(obj);
  12495. },
  12496. /**
  12497. * A Group is a container for display objects that allows for fast pooling, recycling and collision checks.
  12498. *
  12499. * @method Phaser.GameObjectFactory#group
  12500. * @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.
  12501. * @param {string} [name='group'] - A name for this Group. Not used internally but useful for debugging.
  12502. * @param {boolean} [addToStage=false] - If set to true this Group will be added directly to the Game.Stage instead of Game.World.
  12503. * @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.
  12504. * @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.
  12505. * @return {Phaser.Group} The newly created group.
  12506. */
  12507. group: function (parent, name, addToStage, enableBody, physicsBodyType) {
  12508. return new Phaser.Group(this.game, parent, name, addToStage, enableBody, physicsBodyType);
  12509. },
  12510. /**
  12511. * A Group is a container for display objects that allows for fast pooling, recycling and collision checks.
  12512. * A Physics Group is the same as an ordinary Group except that is has enableBody turned on by default, so any Sprites it creates
  12513. * are automatically given a physics body.
  12514. *
  12515. * @method Phaser.GameObjectFactory#group
  12516. * @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.
  12517. * @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.
  12518. * @param {string} [name='group'] - A name for this Group. Not used internally but useful for debugging.
  12519. * @param {boolean} [addToStage=false] - If set to true this Group will be added directly to the Game.Stage instead of Game.World.
  12520. * @return {Phaser.Group} The newly created group.
  12521. */
  12522. physicsGroup: function (physicsBodyType, parent, name, addToStage) {
  12523. return new Phaser.Group(this.game, parent, name, addToStage, true, physicsBodyType);
  12524. },
  12525. /**
  12526. * A Group is a container for display objects that allows for fast pooling, recycling and collision checks.
  12527. *
  12528. * @method Phaser.GameObjectFactory#spriteBatch
  12529. * @param {any} parent - The parent Group or DisplayObjectContainer that will hold this group, if any.
  12530. * @param {string} [name='group'] - A name for this Group. Not used internally but useful for debugging.
  12531. * @param {boolean} [addToStage=false] - If set to true this Group will be added directly to the Game.Stage instead of Game.World.
  12532. * @return {Phaser.Group} The newly created group.
  12533. */
  12534. spriteBatch: function (parent, name, addToStage) {
  12535. if (typeof name === 'undefined') { name = 'group'; }
  12536. if (typeof addToStage === 'undefined') { addToStage = false; }
  12537. return new Phaser.SpriteBatch(this.game, parent, name, addToStage);
  12538. },
  12539. /**
  12540. * Creates a new Sound object.
  12541. *
  12542. * @method Phaser.GameObjectFactory#audio
  12543. * @param {string} key - The Game.cache key of the sound that this object will use.
  12544. * @param {number} [volume=1] - The volume at which the sound will be played.
  12545. * @param {boolean} [loop=false] - Whether or not the sound will loop.
  12546. * @param {boolean} [connect=true] - Controls if the created Sound object will connect to the master gainNode of the SoundManager when running under WebAudio.
  12547. * @return {Phaser.Sound} The newly created text object.
  12548. */
  12549. audio: function (key, volume, loop, connect) {
  12550. return this.game.sound.add(key, volume, loop, connect);
  12551. },
  12552. /**
  12553. * Creates a new Sound object.
  12554. *
  12555. * @method Phaser.GameObjectFactory#sound
  12556. * @param {string} key - The Game.cache key of the sound that this object will use.
  12557. * @param {number} [volume=1] - The volume at which the sound will be played.
  12558. * @param {boolean} [loop=false] - Whether or not the sound will loop.
  12559. * @param {boolean} [connect=true] - Controls if the created Sound object will connect to the master gainNode of the SoundManager when running under WebAudio.
  12560. * @return {Phaser.Sound} The newly created text object.
  12561. */
  12562. sound: function (key, volume, loop, connect) {
  12563. return this.game.sound.add(key, volume, loop, connect);
  12564. },
  12565. /**
  12566. * Creates a new TileSprite object.
  12567. *
  12568. * @method Phaser.GameObjectFactory#tileSprite
  12569. * @param {number} x - The x coordinate (in world space) to position the TileSprite at.
  12570. * @param {number} y - The y coordinate (in world space) to position the TileSprite at.
  12571. * @param {number} width - The width of the TileSprite.
  12572. * @param {number} height - The height of the TileSprite.
  12573. * @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.
  12574. * @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.
  12575. * @param {Phaser.Group} [group] - Optional Group to add the object to. If not specified it will be added to the World group.
  12576. * @return {Phaser.TileSprite} The newly created tileSprite object.
  12577. */
  12578. tileSprite: function (x, y, width, height, key, frame, group) {
  12579. if (typeof group === 'undefined') { group = this.world; }
  12580. return group.add(new Phaser.TileSprite(this.game, x, y, width, height, key, frame));
  12581. },
  12582. /**
  12583. * Creates a new Text object.
  12584. *
  12585. * @method Phaser.GameObjectFactory#text
  12586. * @param {number} x - X position of the new text object.
  12587. * @param {number} y - Y position of the new text object.
  12588. * @param {string} text - The actual text that will be written.
  12589. * @param {object} style - The style object containing style attributes like font, font size , etc.
  12590. * @param {Phaser.Group} [group] - Optional Group to add the object to. If not specified it will be added to the World group.
  12591. * @return {Phaser.Text} The newly created text object.
  12592. */
  12593. text: function (x, y, text, style, group) {
  12594. if (typeof group === 'undefined') { group = this.world; }
  12595. return group.add(new Phaser.Text(this.game, x, y, text, style));
  12596. },
  12597. /**
  12598. * Creates a new Button object.
  12599. *
  12600. * @method Phaser.GameObjectFactory#button
  12601. * @param {number} [x] X position of the new button object.
  12602. * @param {number} [y] Y position of the new button object.
  12603. * @param {string} [key] The image key as defined in the Game.Cache to use as the texture for this button.
  12604. * @param {function} [callback] The function to call when this button is pressed
  12605. * @param {object} [callbackContext] The context in which the callback will be called (usually 'this')
  12606. * @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.
  12607. * @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.
  12608. * @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.
  12609. * @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.
  12610. * @param {Phaser.Group} [group] - Optional Group to add the object to. If not specified it will be added to the World group.
  12611. * @return {Phaser.Button} The newly created button object.
  12612. */
  12613. button: function (x, y, key, callback, callbackContext, overFrame, outFrame, downFrame, upFrame, group) {
  12614. if (typeof group === 'undefined') { group = this.world; }
  12615. return group.add(new Phaser.Button(this.game, x, y, key, callback, callbackContext, overFrame, outFrame, downFrame, upFrame));
  12616. },
  12617. /**
  12618. * Creates a new Graphics object.
  12619. *
  12620. * @method Phaser.GameObjectFactory#graphics
  12621. * @param {number} x - X position of the new graphics object.
  12622. * @param {number} y - Y position of the new graphics object.
  12623. * @param {Phaser.Group} [group] - Optional Group to add the object to. If not specified it will be added to the World group.
  12624. * @return {Phaser.Graphics} The newly created graphics object.
  12625. */
  12626. graphics: function (x, y, group) {
  12627. if (typeof group === 'undefined') { group = this.world; }
  12628. return group.add(new Phaser.Graphics(this.game, x, y));
  12629. },
  12630. /**
  12631. * Emitter is a lightweight particle emitter. It can be used for one-time explosions or for
  12632. * continuous effects like rain and fire. All it really does is launch Particle objects out
  12633. * at set intervals, and fixes their positions and velocities accorindgly.
  12634. *
  12635. * @method Phaser.GameObjectFactory#emitter
  12636. * @param {number} [x=0] - The x coordinate within the Emitter that the particles are emitted from.
  12637. * @param {number} [y=0] - The y coordinate within the Emitter that the particles are emitted from.
  12638. * @param {number} [maxParticles=50] - The total number of particles in this emitter.
  12639. * @return {Phaser.Emitter} The newly created emitter object.
  12640. */
  12641. emitter: function (x, y, maxParticles) {
  12642. return this.game.particles.add(new Phaser.Particles.Arcade.Emitter(this.game, x, y, maxParticles));
  12643. },
  12644. /**
  12645. * Create a new RetroFont object to be used as a texture for an Image or Sprite and optionally add it to the Cache.
  12646. * A RetroFont uses a bitmap which contains fixed with characters for the font set. You use character spacing to define the set.
  12647. * If you need variable width character support then use a BitmapText object instead. The main difference between a RetroFont and a BitmapText
  12648. * 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.
  12649. * 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,
  12650. * i.e. if you need each Image to have different text in it, then you need to create multiple RetroFont objects.
  12651. *
  12652. * @method Phaser.GameObjectFactory#retroFont
  12653. * @param {string} font - The key of the image in the Game.Cache that the RetroFont will use.
  12654. * @param {number} characterWidth - The width of each character in the font set.
  12655. * @param {number} characterHeight - The height of each character in the font set.
  12656. * @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.
  12657. * @param {number} charsPerRow - The number of characters per row in the font set.
  12658. * @param {number} [xSpacing=0] - If the characters in the font set have horizontal spacing between them set the required amount here.
  12659. * @param {number} [ySpacing=0] - If the characters in the font set have vertical spacing between them set the required amount here.
  12660. * @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.
  12661. * @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.
  12662. * @return {Phaser.RetroFont} The newly created RetroFont texture which can be applied to an Image or Sprite.
  12663. */
  12664. retroFont: function (font, characterWidth, characterHeight, chars, charsPerRow, xSpacing, ySpacing, xOffset, yOffset) {
  12665. return new Phaser.RetroFont(this.game, font, characterWidth, characterHeight, chars, charsPerRow, xSpacing, ySpacing, xOffset, yOffset);
  12666. },
  12667. /**
  12668. * Create a new BitmapText object.
  12669. *
  12670. * @method Phaser.GameObjectFactory#bitmapText
  12671. * @param {number} x - X position of the new bitmapText object.
  12672. * @param {number} y - Y position of the new bitmapText object.
  12673. * @param {string} font - The key of the BitmapText font as stored in Game.Cache.
  12674. * @param {string} [text] - The actual text that will be rendered. Can be set later via BitmapText.text.
  12675. * @param {number} [size] - The size the font will be rendered in, in pixels.
  12676. * @param {Phaser.Group} [group] - Optional Group to add the object to. If not specified it will be added to the World group.
  12677. * @return {Phaser.BitmapText} The newly created bitmapText object.
  12678. */
  12679. bitmapText: function (x, y, font, text, size, group) {
  12680. if (typeof group === 'undefined') { group = this.world; }
  12681. return group.add(new Phaser.BitmapText(this.game, x, y, font, text, size));
  12682. },
  12683. /**
  12684. * Creates a new Phaser.Tilemap object. The map can either be populated with data from a Tiled JSON file or from a CSV file.
  12685. * To do this pass the Cache key as the first parameter. When using Tiled data you need only provide the key.
  12686. * When using CSV data you must provide the key and the tileWidth and tileHeight parameters.
  12687. * 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.
  12688. * 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.
  12689. *
  12690. * @method Phaser.GameObjectFactory#tilemap
  12691. * @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`.
  12692. * @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.
  12693. * @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.
  12694. * @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.
  12695. * @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.
  12696. * @return {Phaser.Tilemap} The newly created tilemap object.
  12697. */
  12698. tilemap: function (key, tileWidth, tileHeight, width, height) {
  12699. return new Phaser.Tilemap(this.game, key, tileWidth, tileHeight, width, height);
  12700. },
  12701. /**
  12702. * A dynamic initially blank canvas to which images can be drawn.
  12703. *
  12704. * @method Phaser.GameObjectFactory#renderTexture
  12705. * @param {number} [width=100] - the width of the RenderTexture.
  12706. * @param {number} [height=100] - the height of the RenderTexture.
  12707. * @param {string} [key=''] - Asset key for the RenderTexture when stored in the Cache (see addToCache parameter).
  12708. * @param {boolean} [addToCache=false] - Should this RenderTexture be added to the Game.Cache? If so you can retrieve it with Cache.getTexture(key)
  12709. * @return {Phaser.RenderTexture} The newly created RenderTexture object.
  12710. */
  12711. renderTexture: function (width, height, key, addToCache) {
  12712. if (typeof key === 'undefined' || key === '') { key = this.game.rnd.uuid(); }
  12713. if (typeof addToCache === 'undefined') { addToCache = false; }
  12714. var texture = new Phaser.RenderTexture(this.game, width, height, key);
  12715. if (addToCache)
  12716. {
  12717. this.game.cache.addRenderTexture(key, texture);
  12718. }
  12719. return texture;
  12720. },
  12721. /**
  12722. * A BitmapData object which can be manipulated and drawn to like a traditional Canvas object and used to texture Sprites.
  12723. *
  12724. * @method Phaser.GameObjectFactory#bitmapData
  12725. * @param {number} [width=100] - The width of the BitmapData in pixels.
  12726. * @param {number} [height=100] - The height of the BitmapData in pixels.
  12727. * @param {string} [key=''] - Asset key for the BitmapData when stored in the Cache (see addToCache parameter).
  12728. * @param {boolean} [addToCache=false] - Should this BitmapData be added to the Game.Cache? If so you can retrieve it with Cache.getBitmapData(key)
  12729. * @return {Phaser.BitmapData} The newly created BitmapData object.
  12730. */
  12731. bitmapData: function (width, height, key, addToCache) {
  12732. if (typeof addToCache === 'undefined') { addToCache = false; }
  12733. if (typeof key === 'undefined' || key === '') { key = this.game.rnd.uuid(); }
  12734. var texture = new Phaser.BitmapData(this.game, key, width, height);
  12735. if (addToCache)
  12736. {
  12737. this.game.cache.addBitmapData(key, texture);
  12738. }
  12739. return texture;
  12740. },
  12741. /**
  12742. * A WebGL shader/filter that can be applied to Sprites.
  12743. *
  12744. * @method Phaser.GameObjectFactory#filter
  12745. * @param {string} filter - The name of the filter you wish to create, for example HueRotate or SineWave.
  12746. * @param {any} - Whatever parameters are needed to be passed to the filter init function.
  12747. * @return {Phaser.Filter} The newly created Phaser.Filter object.
  12748. */
  12749. filter: function (filter) {
  12750. var args = Array.prototype.splice.call(arguments, 1);
  12751. var filter = new Phaser.Filter[filter](this.game);
  12752. filter.init.apply(filter, args);
  12753. return filter;
  12754. }
  12755. };
  12756. Phaser.GameObjectFactory.prototype.constructor = Phaser.GameObjectFactory;
  12757. /**
  12758. * @author Richard Davey <rich@photonstorm.com>
  12759. * @copyright 2014 Photon Storm Ltd.
  12760. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  12761. */
  12762. /**
  12763. * 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.
  12764. * Use the GameObjectFactory to create and add the objects into the world.
  12765. *
  12766. * @class Phaser.GameObjectCreator
  12767. * @constructor
  12768. * @param {Phaser.Game} game - A reference to the currently running game.
  12769. */
  12770. Phaser.GameObjectCreator = function (game) {
  12771. /**
  12772. * @property {Phaser.Game} game - A reference to the currently running Game.
  12773. */
  12774. this.game = game;
  12775. /**
  12776. * @property {Phaser.World} world - A reference to the game world.
  12777. */
  12778. this.world = this.game.world;
  12779. };
  12780. Phaser.GameObjectCreator.prototype = {
  12781. /**
  12782. * 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.
  12783. * It can still rotate, scale, crop and receive input events. This makes it perfect for logos, backgrounds, simple buttons and other non-Sprite graphics.
  12784. *
  12785. * @method Phaser.GameObjectCreator#image
  12786. * @param {number} x - X position of the image.
  12787. * @param {number} y - Y position of the image.
  12788. * @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.
  12789. * @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.
  12790. * @returns {Phaser.Sprite} the newly created sprite object.
  12791. */
  12792. image: function (x, y, key, frame) {
  12793. return new Phaser.Image(this.game, x, y, key, frame);
  12794. },
  12795. /**
  12796. * Create a new Sprite with specific position and sprite sheet key.
  12797. *
  12798. * @method Phaser.GameObjectCreator#sprite
  12799. * @param {number} x - X position of the new sprite.
  12800. * @param {number} y - Y position of the new sprite.
  12801. * @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.
  12802. * @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.
  12803. * @returns {Phaser.Sprite} the newly created sprite object.
  12804. */
  12805. sprite: function (x, y, key, frame) {
  12806. return new Phaser.Sprite(this.game, x, y, key, frame);
  12807. },
  12808. /**
  12809. * Create a tween object for a specific object. The object can be any JavaScript object or Phaser object such as Sprite.
  12810. *
  12811. * @method Phaser.GameObjectCreator#tween
  12812. * @param {object} obj - Object the tween will be run on.
  12813. * @return {Phaser.Tween} The Tween object.
  12814. */
  12815. tween: function (obj) {
  12816. return new Phaser.Tween(obj, this.game);
  12817. },
  12818. /**
  12819. * A Group is a container for display objects that allows for fast pooling, recycling and collision checks.
  12820. *
  12821. * @method Phaser.GameObjectCreator#group
  12822. * @param {string} [name='group'] - A name for this Group. Not used internally but useful for debugging.
  12823. * @param {boolean} [addToStage=false] - If set to true this Group will be added directly to the Game.Stage instead of Game.World.
  12824. * @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.
  12825. * @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.
  12826. * @return {Phaser.Group} The newly created group.
  12827. */
  12828. group: function (parent, name, addToStage, enableBody, physicsBodyType) {
  12829. return new Phaser.Group(this.game, null, name, addToStage, enableBody, physicsBodyType);
  12830. },
  12831. /**
  12832. * A Group is a container for display objects that allows for fast pooling, recycling and collision checks.
  12833. *
  12834. * @method Phaser.GameObjectCreator#spriteBatch
  12835. * @param {any} parent - The parent Group or DisplayObjectContainer that will hold this group, if any.
  12836. * @param {string} [name='group'] - A name for this Group. Not used internally but useful for debugging.
  12837. * @param {boolean} [addToStage=false] - If set to true this Group will be added directly to the Game.Stage instead of Game.World.
  12838. * @return {Phaser.Group} The newly created group.
  12839. */
  12840. spriteBatch: function (parent, name, addToStage) {
  12841. if (typeof name === 'undefined') { name = 'group'; }
  12842. if (typeof addToStage === 'undefined') { addToStage = false; }
  12843. return new Phaser.SpriteBatch(this.game, parent, name, addToStage);
  12844. },
  12845. /**
  12846. * Creates a new Sound object.
  12847. *
  12848. * @method Phaser.GameObjectCreator#audio
  12849. * @param {string} key - The Game.cache key of the sound that this object will use.
  12850. * @param {number} [volume=1] - The volume at which the sound will be played.
  12851. * @param {boolean} [loop=false] - Whether or not the sound will loop.
  12852. * @param {boolean} [connect=true] - Controls if the created Sound object will connect to the master gainNode of the SoundManager when running under WebAudio.
  12853. * @return {Phaser.Sound} The newly created text object.
  12854. */
  12855. audio: function (key, volume, loop, connect) {
  12856. return this.game.sound.add(key, volume, loop, connect);
  12857. },
  12858. /**
  12859. * Creates a new Sound object.
  12860. *
  12861. * @method Phaser.GameObjectCreator#sound
  12862. * @param {string} key - The Game.cache key of the sound that this object will use.
  12863. * @param {number} [volume=1] - The volume at which the sound will be played.
  12864. * @param {boolean} [loop=false] - Whether or not the sound will loop.
  12865. * @param {boolean} [connect=true] - Controls if the created Sound object will connect to the master gainNode of the SoundManager when running under WebAudio.
  12866. * @return {Phaser.Sound} The newly created text object.
  12867. */
  12868. sound: function (key, volume, loop, connect) {
  12869. return this.game.sound.add(key, volume, loop, connect);
  12870. },
  12871. /**
  12872. * Creates a new TileSprite object.
  12873. *
  12874. * @method Phaser.GameObjectCreator#tileSprite
  12875. * @param {number} x - The x coordinate (in world space) to position the TileSprite at.
  12876. * @param {number} y - The y coordinate (in world space) to position the TileSprite at.
  12877. * @param {number} width - The width of the TileSprite.
  12878. * @param {number} height - The height of the TileSprite.
  12879. * @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.
  12880. * @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.
  12881. * @return {Phaser.TileSprite} The newly created tileSprite object.
  12882. */
  12883. tileSprite: function (x, y, width, height, key, frame) {
  12884. return new Phaser.TileSprite(this.game, x, y, width, height, key, frame);
  12885. },
  12886. /**
  12887. * Creates a new Text object.
  12888. *
  12889. * @method Phaser.GameObjectCreator#text
  12890. * @param {number} x - X position of the new text object.
  12891. * @param {number} y - Y position of the new text object.
  12892. * @param {string} text - The actual text that will be written.
  12893. * @param {object} style - The style object containing style attributes like font, font size , etc.
  12894. * @return {Phaser.Text} The newly created text object.
  12895. */
  12896. text: function (x, y, text, style) {
  12897. return new Phaser.Text(this.game, x, y, text, style);
  12898. },
  12899. /**
  12900. * Creates a new Button object.
  12901. *
  12902. * @method Phaser.GameObjectCreator#button
  12903. * @param {number} [x] X position of the new button object.
  12904. * @param {number} [y] Y position of the new button object.
  12905. * @param {string} [key] The image key as defined in the Game.Cache to use as the texture for this button.
  12906. * @param {function} [callback] The function to call when this button is pressed
  12907. * @param {object} [callbackContext] The context in which the callback will be called (usually 'this')
  12908. * @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.
  12909. * @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.
  12910. * @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.
  12911. * @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.
  12912. * @return {Phaser.Button} The newly created button object.
  12913. */
  12914. button: function (x, y, key, callback, callbackContext, overFrame, outFrame, downFrame, upFrame) {
  12915. return new Phaser.Button(this.game, x, y, key, callback, callbackContext, overFrame, outFrame, downFrame, upFrame);
  12916. },
  12917. /**
  12918. * Creates a new Graphics object.
  12919. *
  12920. * @method Phaser.GameObjectCreator#graphics
  12921. * @param {number} x - X position of the new graphics object.
  12922. * @param {number} y - Y position of the new graphics object.
  12923. * @return {Phaser.Graphics} The newly created graphics object.
  12924. */
  12925. graphics: function (x, y) {
  12926. return new Phaser.Graphics(this.game, x, y);
  12927. },
  12928. /**
  12929. * Emitter is a lightweight particle emitter. It can be used for one-time explosions or for
  12930. * continuous effects like rain and fire. All it really does is launch Particle objects out
  12931. * at set intervals, and fixes their positions and velocities accorindgly.
  12932. *
  12933. * @method Phaser.GameObjectCreator#emitter
  12934. * @param {number} [x=0] - The x coordinate within the Emitter that the particles are emitted from.
  12935. * @param {number} [y=0] - The y coordinate within the Emitter that the particles are emitted from.
  12936. * @param {number} [maxParticles=50] - The total number of particles in this emitter.
  12937. * @return {Phaser.Emitter} The newly created emitter object.
  12938. */
  12939. emitter: function (x, y, maxParticles) {
  12940. return new Phaser.Particles.Arcade.Emitter(this.game, x, y, maxParticles);
  12941. },
  12942. /**
  12943. * Create a new RetroFont object to be used as a texture for an Image or Sprite and optionally add it to the Cache.
  12944. * A RetroFont uses a bitmap which contains fixed with characters for the font set. You use character spacing to define the set.
  12945. * If you need variable width character support then use a BitmapText object instead. The main difference between a RetroFont and a BitmapText
  12946. * 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.
  12947. * 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,
  12948. * i.e. if you need each Image to have different text in it, then you need to create multiple RetroFont objects.
  12949. *
  12950. * @method Phaser.GameObjectCreator#retroFont
  12951. * @param {string} font - The key of the image in the Game.Cache that the RetroFont will use.
  12952. * @param {number} characterWidth - The width of each character in the font set.
  12953. * @param {number} characterHeight - The height of each character in the font set.
  12954. * @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.
  12955. * @param {number} charsPerRow - The number of characters per row in the font set.
  12956. * @param {number} [xSpacing=0] - If the characters in the font set have horizontal spacing between them set the required amount here.
  12957. * @param {number} [ySpacing=0] - If the characters in the font set have vertical spacing between them set the required amount here.
  12958. * @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.
  12959. * @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.
  12960. * @return {Phaser.RetroFont} The newly created RetroFont texture which can be applied to an Image or Sprite.
  12961. */
  12962. retroFont: function (font, characterWidth, characterHeight, chars, charsPerRow, xSpacing, ySpacing, xOffset, yOffset) {
  12963. return new Phaser.RetroFont(this.game, font, characterWidth, characterHeight, chars, charsPerRow, xSpacing, ySpacing, xOffset, yOffset);
  12964. },
  12965. /**
  12966. * Create a new BitmapText object.
  12967. *
  12968. * @method Phaser.GameObjectCreator#bitmapText
  12969. * @param {number} x - X position of the new bitmapText object.
  12970. * @param {number} y - Y position of the new bitmapText object.
  12971. * @param {string} font - The key of the BitmapText font as stored in Game.Cache.
  12972. * @param {string} [text] - The actual text that will be rendered. Can be set later via BitmapText.text.
  12973. * @param {number} [size] - The size the font will be rendered in, in pixels.
  12974. * @return {Phaser.BitmapText} The newly created bitmapText object.
  12975. */
  12976. bitmapText: function (x, y, font, text, size) {
  12977. return new Phaser.BitmapText(this.game, x, y, font, text, size);
  12978. },
  12979. /**
  12980. * Creates a new Phaser.Tilemap object. The map can either be populated with data from a Tiled JSON file or from a CSV file.
  12981. * To do this pass the Cache key as the first parameter. When using Tiled data you need only provide the key.
  12982. * When using CSV data you must provide the key and the tileWidth and tileHeight parameters.
  12983. * 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.
  12984. * 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.
  12985. *
  12986. * @method Phaser.GameObjectCreator#tilemap
  12987. * @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`.
  12988. * @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.
  12989. * @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.
  12990. * @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.
  12991. * @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.
  12992. */
  12993. tilemap: function (key, tileWidth, tileHeight, width, height) {
  12994. return new Phaser.Tilemap(this.game, key, tileWidth, tileHeight, width, height);
  12995. },
  12996. /**
  12997. * A dynamic initially blank canvas to which images can be drawn.
  12998. *
  12999. * @method Phaser.GameObjectCreator#renderTexture
  13000. * @param {number} [width=100] - the width of the RenderTexture.
  13001. * @param {number} [height=100] - the height of the RenderTexture.
  13002. * @param {string} [key=''] - Asset key for the RenderTexture when stored in the Cache (see addToCache parameter).
  13003. * @param {boolean} [addToCache=false] - Should this RenderTexture be added to the Game.Cache? If so you can retrieve it with Cache.getTexture(key)
  13004. * @return {Phaser.RenderTexture} The newly created RenderTexture object.
  13005. */
  13006. renderTexture: function (width, height, key, addToCache) {
  13007. if (typeof key === 'undefined' || key === '') { key = this.game.rnd.uuid(); }
  13008. if (typeof addToCache === 'undefined') { addToCache = false; }
  13009. var texture = new Phaser.RenderTexture(this.game, width, height, key);
  13010. if (addToCache)
  13011. {
  13012. this.game.cache.addRenderTexture(key, texture);
  13013. }
  13014. return texture;
  13015. },
  13016. /**
  13017. * A BitmapData object which can be manipulated and drawn to like a traditional Canvas object and used to texture Sprites.
  13018. *
  13019. * @method Phaser.GameObjectCreator#bitmapData
  13020. * @param {number} [width=100] - The width of the BitmapData in pixels.
  13021. * @param {number} [height=100] - The height of the BitmapData in pixels.
  13022. * @param {string} [key=''] - Asset key for the BitmapData when stored in the Cache (see addToCache parameter).
  13023. * @param {boolean} [addToCache=false] - Should this BitmapData be added to the Game.Cache? If so you can retrieve it with Cache.getBitmapData(key)
  13024. * @return {Phaser.BitmapData} The newly created BitmapData object.
  13025. */
  13026. bitmapData: function (width, height, key, addToCache) {
  13027. if (typeof addToCache === 'undefined') { addToCache = false; }
  13028. if (typeof key === 'undefined' || key === '') { key = this.game.rnd.uuid(); }
  13029. var texture = new Phaser.BitmapData(this.game, key, width, height);
  13030. if (addToCache)
  13031. {
  13032. this.game.cache.addBitmapData(key, texture);
  13033. }
  13034. return texture;
  13035. },
  13036. /**
  13037. * A WebGL shader/filter that can be applied to Sprites.
  13038. *
  13039. * @method Phaser.GameObjectCreator#filter
  13040. * @param {string} filter - The name of the filter you wish to create, for example HueRotate or SineWave.
  13041. * @param {any} - Whatever parameters are needed to be passed to the filter init function.
  13042. * @return {Phaser.Filter} The newly created Phaser.Filter object.
  13043. */
  13044. filter: function (filter) {
  13045. var args = Array.prototype.splice.call(arguments, 1);
  13046. var filter = new Phaser.Filter[filter](this.game);
  13047. filter.init.apply(filter, args);
  13048. return filter