From d623f3abe9537181e5cec88e123517cd300a8ade Mon Sep 17 00:00:00 2001 From: samme Date: Fri, 15 May 2020 10:07:24 -0700 Subject: [PATCH] Reformat --- src/Phaser.js | 618 ++-- src/PixiDefaults.js | 8 +- src/animation/Animation.js | 454 ++- src/animation/AnimationManager.js | 340 +- src/animation/AnimationParser.js | 114 +- src/animation/Frame.js | 174 +- src/animation/FrameData.js | 166 +- src/core/Camera.js | 654 ++-- src/core/Create.js | 94 +- src/core/Filter.js | 228 +- src/core/FlexGrid.js | 106 +- src/core/FlexLayer.js | 84 +- src/core/Game.js | 934 +++--- src/core/Group.js | 2736 ++++++++--------- src/core/Plugin.js | 138 +- src/core/PluginManager.js | 155 +- src/core/ScaleManager.js | 2030 ++++++------ src/core/Signal.js | 452 ++- src/core/SignalBinding.js | 154 +- src/core/Stage.js | 293 +- src/core/State.js | 302 +- src/core/StateManager.js | 452 ++- src/core/World.js | 242 +- src/gameobjects/BitmapData.js | 1659 +++++----- src/gameobjects/BitmapText.js | 437 ++- src/gameobjects/Button.js | 515 ++-- src/gameobjects/Creature.js | 428 ++- src/gameobjects/GameObjectCreator.js | 514 ++-- src/gameobjects/GameObjectFactory.js | 722 ++--- src/gameobjects/Graphics.js | 287 +- src/gameobjects/GraphicsData.js | 4 - src/gameobjects/Image.js | 86 +- src/gameobjects/Particle.js | 138 +- src/gameobjects/RenderTexture.js | 274 +- src/gameobjects/RetroFont.js | 400 ++- src/gameobjects/Rope.js | 323 +- src/gameobjects/Sprite.js | 108 +- src/gameobjects/SpriteBatch.js | 90 +- src/gameobjects/Text.js | 1107 +++---- src/gameobjects/TileSprite.js | 394 ++- src/gameobjects/Video.js | 581 ++-- src/gameobjects/components/Angle.js | 44 +- src/gameobjects/components/Animation.js | 46 +- src/gameobjects/components/AutoCull.js | 52 +- src/gameobjects/components/Bounds.js | 290 +- src/gameobjects/components/BringToTop.js | 96 +- src/gameobjects/components/Component.js | 8 +- src/gameobjects/components/Core.js | 278 +- src/gameobjects/components/Crop.js | 82 +- src/gameobjects/components/Delta.js | 60 +- src/gameobjects/components/Destroy.js | 52 +- src/gameobjects/components/Events.js | 392 ++- src/gameobjects/components/FixedToCamera.js | 70 +- src/gameobjects/components/Health.js | 94 +- src/gameobjects/components/InCamera.js | 36 +- src/gameobjects/components/InWorld.js | 82 +- src/gameobjects/components/InputEnabled.js | 64 +- src/gameobjects/components/LifeSpan.js | 110 +- src/gameobjects/components/LoadTexture.js | 170 +- src/gameobjects/components/Overlap.js | 42 +- src/gameobjects/components/PhysicsBody.js | 82 +- src/gameobjects/components/Reset.js | 48 +- src/gameobjects/components/ScaleMinMax.js | 60 +- src/gameobjects/components/Smoothed.js | 35 +- src/geom/Circle.js | 403 ++- src/geom/Ellipse.js | 260 +- src/geom/Hermite.js | 386 +-- src/geom/Line.js | 571 ++-- src/geom/Matrix.js | 304 +- src/geom/Point.js | 1026 +++---- src/geom/Polygon.js | 103 +- src/geom/Rectangle.js | 837 +++-- src/geom/RoundedRectangle.js | 88 +- src/input/DeviceButton.js | 314 +- src/input/Gamepad.js | 340 +- src/input/Input.js | 927 +++--- src/input/InputHandler.js | 981 +++--- src/input/Key.js | 319 +- src/input/Keyboard.js | 475 ++- src/input/MSPointer.js | 280 +- src/input/Mouse.js | 308 +- src/input/MouseWheel.js | 154 +- src/input/Pointer.js | 832 +++-- src/input/PointerLock.js | 152 +- src/input/SinglePad.js | 335 +- src/input/Touch.js | 240 +- src/input/WheelEventProxy.js | 46 +- src/loader/Cache.js | 2048 ++++++------ src/loader/Loader.js | 2607 ++++++++-------- src/loader/LoaderParser.js | 336 +- src/math/Math.js | 1188 ++++--- src/math/QuadTree.js | 233 +- src/math/RandomDataGenerator.js | 317 +- src/net/Net.js | 109 +- src/particles/Particles.js | 54 +- src/particles/arcade/ArcadeParticles.js | 16 +- src/particles/arcade/Emitter.js | 749 +++-- src/physics/Physics.js | 264 +- src/physics/arcade/Body.js | 1151 ++++--- src/physics/arcade/TilemapCollision.js | 166 +- src/physics/arcade/World.js | 1248 ++++---- src/pixi/display/DisplayObject.js | 637 ++-- src/pixi/display/DisplayObjectContainer.js | 101 +- src/pixi/display/Sprite.js | 84 +- src/pixi/renderers/canvas/CanvasGraphics.js | 7 - src/pixi/renderers/canvas/CanvasRenderer.js | 24 +- .../canvas/utils/CanvasMaskManager.js | 1 - .../renderers/canvas/utils/CanvasTinter.js | 1 - src/pixi/renderers/webgl/WebGLRenderer.js | 65 +- .../webgl/shaders/ComplexPrimitiveShader.js | 24 +- .../renderers/webgl/shaders/PixiFastShader.js | 23 +- .../renderers/webgl/shaders/PixiShader.js | 126 +- .../webgl/shaders/PrimitiveShader.js | 24 +- .../renderers/webgl/shaders/StripShader.js | 42 +- .../renderers/webgl/utils/FilterTexture.js | 30 +- .../webgl/utils/WebGLBlendModeManager.js | 26 +- .../webgl/utils/WebGLFastSpriteBatch.js | 11 +- .../webgl/utils/WebGLFilterManager.js | 128 +- .../renderers/webgl/utils/WebGLGraphics.js | 26 +- .../renderers/webgl/utils/WebGLMaskManager.js | 51 +- .../webgl/utils/WebGLShaderManager.js | 47 +- .../renderers/webgl/utils/WebGLShaderUtils.js | 62 +- .../renderers/webgl/utils/WebGLSpriteBatch.js | 46 +- .../webgl/utils/WebGLStencilManager.js | 51 +- src/pixi/textures/BaseTexture.js | 2 - src/pixi/textures/Texture.js | 4 - src/polyfills.js | 32 +- src/sound/AudioSprite.js | 14 +- src/sound/Sound.js | 598 ++-- src/sound/SoundManager.js | 460 ++- src/stubs/Color.js | 174 +- src/stubs/Create.js | 8 +- src/stubs/DOM.js | 78 +- src/stubs/Debug.js | 18 +- src/stubs/Net.js | 18 +- src/stubs/ScaleManager.js | 24 +- src/stubs/SoundManager.js | 14 +- src/stubs/TweenManager.js | 14 +- src/tilemap/ImageCollection.js | 137 +- src/tilemap/Tile.js | 314 +- src/tilemap/Tilemap.js | 1162 ++++--- src/tilemap/TilemapLayer.js | 772 +++-- src/tilemap/TilemapParser.js | 134 +- src/tilemap/Tileset.js | 224 +- src/time/Time.js | 684 ++--- src/time/Timer.js | 538 ++-- src/time/TimerEvent.js | 92 +- src/tween/Easing.js | 546 ++-- src/tween/Tween.js | 745 +++-- src/tween/TweenData.js | 321 +- src/tween/TweenManager.js | 228 +- src/utils/ArraySet.js | 212 +- src/utils/ArrayUtils.js | 318 +- src/utils/Canvas.js | 228 +- src/utils/CanvasPool.js | 124 +- src/utils/Color.js | 1462 +++++---- src/utils/DOM.js | 326 +- src/utils/Debug.js | 781 +++-- src/utils/Device.js | 833 +++-- src/utils/EarCut.js | 65 +- src/utils/LinkedList.js | 121 +- src/utils/RequestAnimationFrame.js | 104 +- src/utils/Utils.js | 252 +- 163 files changed, 25575 insertions(+), 29698 deletions(-) diff --git a/src/Phaser.js b/src/Phaser.js index 4a71c4339..bbf04ee6c 100644 --- a/src/Phaser.js +++ b/src/Phaser.js @@ -1,508 +1,508 @@ /** -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* @namespace Phaser -*/ + * @namespace Phaser + */ var Phaser = Phaser || { // jshint ignore:line /** - * The Phaser version number. - * @constant Phaser.VERSION - * @type {string} - */ + * The Phaser version number. + * @constant Phaser.VERSION + * @type {string} + */ VERSION: '2.15.0', /** - * An array of Phaser game instances. - * @constant Phaser.GAMES - * @type {array} - */ + * An array of Phaser game instances. + * @constant Phaser.GAMES + * @type {array} + */ GAMES: [], /** - * AUTO renderer - picks between WebGL or Canvas based on device. - * @constant Phaser.AUTO - * @type {integer} - */ + * AUTO renderer - picks between WebGL or Canvas based on device. + * @constant Phaser.AUTO + * @type {integer} + */ AUTO: 0, /** - * Canvas Renderer. - * @constant Phaser.CANVAS - * @type {integer} - */ + * Canvas Renderer. + * @constant Phaser.CANVAS + * @type {integer} + */ CANVAS: 1, /** - * WebGL Renderer. - * @constant Phaser.WEBGL - * @type {integer} - */ + * WebGL Renderer. + * @constant Phaser.WEBGL + * @type {integer} + */ WEBGL: 2, /** - * Headless renderer (not visual output) - * @constant Phaser.HEADLESS - * @type {integer} - */ + * Headless renderer (not visual output) + * @constant Phaser.HEADLESS + * @type {integer} + */ HEADLESS: 3, /** - * WebGL Renderer with MultiTexture support enabled. - * @constant Phaser.WEBGL_MULTI - * @type {integer} - */ + * WebGL Renderer with MultiTexture support enabled. + * @constant Phaser.WEBGL_MULTI + * @type {integer} + */ WEBGL_MULTI: 4, /** - * Direction constant. - * @constant Phaser.NONE - * @type {integer} - */ + * Direction constant. + * @constant Phaser.NONE + * @type {integer} + */ NONE: 0, /** - * Direction constant. - * @constant Phaser.LEFT - * @type {integer} - */ + * Direction constant. + * @constant Phaser.LEFT + * @type {integer} + */ LEFT: 1, /** - * Direction constant. - * @constant Phaser.RIGHT - * @type {integer} - */ + * Direction constant. + * @constant Phaser.RIGHT + * @type {integer} + */ RIGHT: 2, /** - * Direction constant. - * @constant Phaser.UP - * @type {integer} - */ + * Direction constant. + * @constant Phaser.UP + * @type {integer} + */ UP: 3, /** - * Direction constant. - * @constant Phaser.DOWN - * @type {integer} - */ + * Direction constant. + * @constant Phaser.DOWN + * @type {integer} + */ DOWN: 4, /** - * Game Object type. - * @constant Phaser.SPRITE - * @type {integer} - */ + * Game Object type. + * @constant Phaser.SPRITE + * @type {integer} + */ SPRITE: 0, /** - * Game Object type. - * @constant Phaser.BUTTON - * @type {integer} - */ + * Game Object type. + * @constant Phaser.BUTTON + * @type {integer} + */ BUTTON: 1, /** - * Game Object type. - * @constant Phaser.IMAGE - * @type {integer} - */ + * Game Object type. + * @constant Phaser.IMAGE + * @type {integer} + */ IMAGE: 2, /** - * Game Object type. - * @constant Phaser.GRAPHICS - * @type {integer} - */ + * Game Object type. + * @constant Phaser.GRAPHICS + * @type {integer} + */ GRAPHICS: 3, /** - * Game Object type. - * @constant Phaser.TEXT - * @type {integer} - */ + * Game Object type. + * @constant Phaser.TEXT + * @type {integer} + */ TEXT: 4, /** - * Game Object type. - * @constant Phaser.TILESPRITE - * @type {integer} - */ + * Game Object type. + * @constant Phaser.TILESPRITE + * @type {integer} + */ TILESPRITE: 5, /** - * Game Object type. - * @constant Phaser.BITMAPTEXT - * @type {integer} - */ + * Game Object type. + * @constant Phaser.BITMAPTEXT + * @type {integer} + */ BITMAPTEXT: 6, /** - * Game Object type. - * @constant Phaser.GROUP - * @type {integer} - */ + * Game Object type. + * @constant Phaser.GROUP + * @type {integer} + */ GROUP: 7, /** - * Game Object type. - * @constant Phaser.RENDERTEXTURE - * @type {integer} - */ + * Game Object type. + * @constant Phaser.RENDERTEXTURE + * @type {integer} + */ RENDERTEXTURE: 8, /** - * Game Object type. - * @constant Phaser.TILEMAP - * @type {integer} - */ + * Game Object type. + * @constant Phaser.TILEMAP + * @type {integer} + */ TILEMAP: 9, /** - * Game Object type. - * @constant Phaser.TILEMAPLAYER - * @type {integer} - */ + * Game Object type. + * @constant Phaser.TILEMAPLAYER + * @type {integer} + */ TILEMAPLAYER: 10, /** - * Game Object type. - * @constant Phaser.EMITTER - * @type {integer} - */ + * Game Object type. + * @constant Phaser.EMITTER + * @type {integer} + */ EMITTER: 11, /** - * Game Object type. - * @constant Phaser.POLYGON - * @type {integer} - */ + * Game Object type. + * @constant Phaser.POLYGON + * @type {integer} + */ POLYGON: 12, /** - * Game Object type. - * @constant Phaser.BITMAPDATA - * @type {integer} - */ + * Game Object type. + * @constant Phaser.BITMAPDATA + * @type {integer} + */ BITMAPDATA: 13, /** - * Game Object type. - * @constant Phaser.CANVAS_FILTER - * @type {integer} - */ + * Game Object type. + * @constant Phaser.CANVAS_FILTER + * @type {integer} + */ CANVAS_FILTER: 14, /** - * Game Object type. - * @constant Phaser.WEBGL_FILTER - * @type {integer} - */ + * Game Object type. + * @constant Phaser.WEBGL_FILTER + * @type {integer} + */ WEBGL_FILTER: 15, /** - * Game Object type. - * @constant Phaser.ELLIPSE - * @type {integer} - */ + * Game Object type. + * @constant Phaser.ELLIPSE + * @type {integer} + */ ELLIPSE: 16, /** - * Game Object type. - * @constant Phaser.SPRITEBATCH - * @type {integer} - */ + * Game Object type. + * @constant Phaser.SPRITEBATCH + * @type {integer} + */ SPRITEBATCH: 17, /** - * Game Object type. - * @constant Phaser.RETROFONT - * @type {integer} - */ + * Game Object type. + * @constant Phaser.RETROFONT + * @type {integer} + */ RETROFONT: 18, /** - * Game Object type. - * @constant Phaser.POINTER - * @type {integer} - */ + * Game Object type. + * @constant Phaser.POINTER + * @type {integer} + */ POINTER: 19, /** - * Game Object type. - * @constant Phaser.ROPE - * @type {integer} - */ + * Game Object type. + * @constant Phaser.ROPE + * @type {integer} + */ ROPE: 20, /** - * Game Object type. - * @constant Phaser.CIRCLE - * @type {integer} - */ + * Game Object type. + * @constant Phaser.CIRCLE + * @type {integer} + */ CIRCLE: 21, /** - * Game Object type. - * @constant Phaser.RECTANGLE - * @type {integer} - */ + * Game Object type. + * @constant Phaser.RECTANGLE + * @type {integer} + */ RECTANGLE: 22, /** - * Game Object type. - * @constant Phaser.LINE - * @type {integer} - */ + * Game Object type. + * @constant Phaser.LINE + * @type {integer} + */ LINE: 23, /** - * Game Object type. - * @constant Phaser.MATRIX - * @type {integer} - */ + * Game Object type. + * @constant Phaser.MATRIX + * @type {integer} + */ MATRIX: 24, /** - * Game Object type. - * @constant Phaser.POINT - * @type {integer} - */ + * Game Object type. + * @constant Phaser.POINT + * @type {integer} + */ POINT: 25, /** - * Game Object type. - * @constant Phaser.ROUNDEDRECTANGLE - * @type {integer} - */ + * Game Object type. + * @constant Phaser.ROUNDEDRECTANGLE + * @type {integer} + */ ROUNDEDRECTANGLE: 26, /** - * Game Object type. - * @constant Phaser.CREATURE - * @type {integer} - */ + * Game Object type. + * @constant Phaser.CREATURE + * @type {integer} + */ CREATURE: 27, /** - * Game Object type. - * @constant Phaser.VIDEO - * @type {integer} - */ + * Game Object type. + * @constant Phaser.VIDEO + * @type {integer} + */ VIDEO: 28, /** - * Game Object type. - * @constant Phaser.PENDING_ATLAS - * @type {integer} - */ + * Game Object type. + * @constant Phaser.PENDING_ATLAS + * @type {integer} + */ PENDING_ATLAS: -1, /** - * A horizontal orientation - * @constant Phaser.HORIZONTAL - * @type {integer} - */ + * A horizontal orientation + * @constant Phaser.HORIZONTAL + * @type {integer} + */ HORIZONTAL: 0, /** - * A vertical orientation - * @constant Phaser.VERTICAL - * @type {integer} - */ + * A vertical orientation + * @constant Phaser.VERTICAL + * @type {integer} + */ VERTICAL: 1, /** - * A landscape orientation - * @constant Phaser.LANDSCAPE - * @type {integer} - */ + * A landscape orientation + * @constant Phaser.LANDSCAPE + * @type {integer} + */ LANDSCAPE: 0, /** - * A portrait orientation - * @constant Phaser.PORTRAIT - * @type {integer} - */ + * A portrait orientation + * @constant Phaser.PORTRAIT + * @type {integer} + */ PORTRAIT: 1, /** - * The Angle (in degrees) a Game Object needs to be set to in order to face up. - * @constant Phaser.ANGLE_UP - * @type {integer} - */ + * The Angle (in degrees) a Game Object needs to be set to in order to face up. + * @constant Phaser.ANGLE_UP + * @type {integer} + */ ANGLE_UP: 270, /** - * The Angle (in degrees) a Game Object needs to be set to in order to face down. - * @constant Phaser.ANGLE_DOWN - * @type {integer} - */ + * The Angle (in degrees) a Game Object needs to be set to in order to face down. + * @constant Phaser.ANGLE_DOWN + * @type {integer} + */ ANGLE_DOWN: 90, /** - * The Angle (in degrees) a Game Object needs to be set to in order to face left. - * @constant Phaser.ANGLE_LEFT - * @type {integer} - */ + * The Angle (in degrees) a Game Object needs to be set to in order to face left. + * @constant Phaser.ANGLE_LEFT + * @type {integer} + */ ANGLE_LEFT: 180, /** - * The Angle (in degrees) a Game Object needs to be set to in order to face right. - * @constant Phaser.ANGLE_RIGHT - * @type {integer} - */ + * The Angle (in degrees) a Game Object needs to be set to in order to face right. + * @constant Phaser.ANGLE_RIGHT + * @type {integer} + */ ANGLE_RIGHT: 0, /** - * The Angle (in degrees) a Game Object needs to be set to in order to face north east. - * @constant Phaser.ANGLE_NORTH_EAST - * @type {integer} - */ + * The Angle (in degrees) a Game Object needs to be set to in order to face north east. + * @constant Phaser.ANGLE_NORTH_EAST + * @type {integer} + */ ANGLE_NORTH_EAST: 315, /** - * The Angle (in degrees) a Game Object needs to be set to in order to face north west. - * @constant Phaser.ANGLE_NORTH_WEST - * @type {integer} - */ + * The Angle (in degrees) a Game Object needs to be set to in order to face north west. + * @constant Phaser.ANGLE_NORTH_WEST + * @type {integer} + */ ANGLE_NORTH_WEST: 225, /** - * The Angle (in degrees) a Game Object needs to be set to in order to face south east. - * @constant Phaser.ANGLE_SOUTH_EAST - * @type {integer} - */ + * The Angle (in degrees) a Game Object needs to be set to in order to face south east. + * @constant Phaser.ANGLE_SOUTH_EAST + * @type {integer} + */ ANGLE_SOUTH_EAST: 45, /** - * The Angle (in degrees) a Game Object needs to be set to in order to face south west. - * @constant Phaser.ANGLE_SOUTH_WEST - * @type {integer} - */ + * The Angle (in degrees) a Game Object needs to be set to in order to face south west. + * @constant Phaser.ANGLE_SOUTH_WEST + * @type {integer} + */ ANGLE_SOUTH_WEST: 135, /** - * A constant representing a top-left alignment or position. - * @constant Phaser.TOP_LEFT - * @type {integer} - */ + * A constant representing a top-left alignment or position. + * @constant Phaser.TOP_LEFT + * @type {integer} + */ TOP_LEFT: 0, /** - * A constant representing a top-center alignment or position. - * @constant Phaser.TOP_CENTER - * @type {integer} - */ + * A constant representing a top-center alignment or position. + * @constant Phaser.TOP_CENTER + * @type {integer} + */ TOP_CENTER: 1, /** - * A constant representing a top-right alignment or position. - * @constant Phaser.TOP_RIGHT - * @type {integer} - */ + * A constant representing a top-right alignment or position. + * @constant Phaser.TOP_RIGHT + * @type {integer} + */ TOP_RIGHT: 2, /** - * A constant representing a left-top alignment or position. - * @constant Phaser.LEFT_TOP - * @type {integer} - */ + * A constant representing a left-top alignment or position. + * @constant Phaser.LEFT_TOP + * @type {integer} + */ LEFT_TOP: 3, /** - * A constant representing a left-center alignment or position. - * @constant Phaser.LEFT_CENTER - * @type {integer} - */ + * A constant representing a left-center alignment or position. + * @constant Phaser.LEFT_CENTER + * @type {integer} + */ LEFT_CENTER: 4, /** - * A constant representing a left-bottom alignment or position. - * @constant Phaser.LEFT_BOTTOM - * @type {integer} - */ + * A constant representing a left-bottom alignment or position. + * @constant Phaser.LEFT_BOTTOM + * @type {integer} + */ LEFT_BOTTOM: 5, /** - * A constant representing a center alignment or position. - * @constant Phaser.CENTER - * @type {integer} - */ + * A constant representing a center alignment or position. + * @constant Phaser.CENTER + * @type {integer} + */ CENTER: 6, /** - * A constant representing a right-top alignment or position. - * @constant Phaser.RIGHT_TOP - * @type {integer} - */ + * A constant representing a right-top alignment or position. + * @constant Phaser.RIGHT_TOP + * @type {integer} + */ RIGHT_TOP: 7, /** - * A constant representing a right-center alignment or position. - * @constant Phaser.RIGHT_CENTER - * @type {integer} - */ + * A constant representing a right-center alignment or position. + * @constant Phaser.RIGHT_CENTER + * @type {integer} + */ RIGHT_CENTER: 8, /** - * A constant representing a right-bottom alignment or position. - * @constant Phaser.RIGHT_BOTTOM - * @type {integer} - */ + * A constant representing a right-bottom alignment or position. + * @constant Phaser.RIGHT_BOTTOM + * @type {integer} + */ RIGHT_BOTTOM: 9, /** - * A constant representing a bottom-left alignment or position. - * @constant Phaser.BOTTOM_LEFT - * @type {integer} - */ + * A constant representing a bottom-left alignment or position. + * @constant Phaser.BOTTOM_LEFT + * @type {integer} + */ BOTTOM_LEFT: 10, /** - * A constant representing a bottom-center alignment or position. - * @constant Phaser.BOTTOM_CENTER - * @type {integer} - */ + * A constant representing a bottom-center alignment or position. + * @constant Phaser.BOTTOM_CENTER + * @type {integer} + */ BOTTOM_CENTER: 11, /** - * A constant representing a bottom-right alignment or position. - * @constant Phaser.BOTTOM_RIGHT - * @type {integer} - */ + * A constant representing a bottom-right alignment or position. + * @constant Phaser.BOTTOM_RIGHT + * @type {integer} + */ BOTTOM_RIGHT: 12, /** - * Various blend modes supported by Pixi. See the samples in {@link https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Compositing Canvas Tutorial: Compositing}. - * - * IMPORTANT: The WebGL renderer only supports the NORMAL, ADD, MULTIPLY and SCREEN blend modes. - * - * @constant {Object} Phaser.blendModes - * @property {Number} blendModes.NORMAL - Draws new shapes on top of the existing content. This is the default setting. - * @property {Number} blendModes.ADD - Where both shapes overlap the color is determined by adding color values. - * @property {Number} blendModes.MULTIPLY - The pixels of the top layer are multiplied with the corresponding pixel of the bottom layer, making a darker picture. - * @property {Number} blendModes.SCREEN - The pixels are inverted, multiplied, and inverted again, making a lighter picture. - * @property {Number} blendModes.OVERLAY - * @property {Number} blendModes.DARKEN - * @property {Number} blendModes.LIGHTEN - * @property {Number} blendModes.COLOR_DODGE - * @property {Number} blendModes.COLOR_BURN - * @property {Number} blendModes.HARD_LIGHT - * @property {Number} blendModes.SOFT_LIGHT - * @property {Number} blendModes.DIFFERENCE - * @property {Number} blendModes.EXCLUSION - * @property {Number} blendModes.HUE - * @property {Number} blendModes.SATURATION - * @property {Number} blendModes.COLOR - * @property {Number} blendModes.LUMINOSITY - * @static - */ + * Various blend modes supported by Pixi. See the samples in {@link https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Compositing Canvas Tutorial: Compositing}. + * + * IMPORTANT: The WebGL renderer only supports the NORMAL, ADD, MULTIPLY and SCREEN blend modes. + * + * @constant {Object} Phaser.blendModes + * @property {Number} blendModes.NORMAL - Draws new shapes on top of the existing content. This is the default setting. + * @property {Number} blendModes.ADD - Where both shapes overlap the color is determined by adding color values. + * @property {Number} blendModes.MULTIPLY - The pixels of the top layer are multiplied with the corresponding pixel of the bottom layer, making a darker picture. + * @property {Number} blendModes.SCREEN - The pixels are inverted, multiplied, and inverted again, making a lighter picture. + * @property {Number} blendModes.OVERLAY + * @property {Number} blendModes.DARKEN + * @property {Number} blendModes.LIGHTEN + * @property {Number} blendModes.COLOR_DODGE + * @property {Number} blendModes.COLOR_BURN + * @property {Number} blendModes.HARD_LIGHT + * @property {Number} blendModes.SOFT_LIGHT + * @property {Number} blendModes.DIFFERENCE + * @property {Number} blendModes.EXCLUSION + * @property {Number} blendModes.HUE + * @property {Number} blendModes.SATURATION + * @property {Number} blendModes.COLOR + * @property {Number} blendModes.LUMINOSITY + * @static + */ blendModes: { NORMAL: 0, ADD: 1, @@ -524,17 +524,17 @@ var Phaser = Phaser || { // jshint ignore:line }, /** - * The scale modes that are supported by Pixi. - * - * The DEFAULT scale mode affects the default scaling mode of future operations. - * It can be re-assigned to either LINEAR or NEAREST, depending upon suitability. - * - * @constant {Object} Phaser.scaleModes - * @property {Number} Phaser.scaleModes.DEFAULT=LINEAR - * @property {Number} Phaser.scaleModes.LINEAR Smooth scaling - * @property {Number} Phaser.scaleModes.NEAREST Pixelating scaling - * @static - */ + * The scale modes that are supported by Pixi. + * + * The DEFAULT scale mode affects the default scaling mode of future operations. + * It can be re-assigned to either LINEAR or NEAREST, depending upon suitability. + * + * @constant {Object} Phaser.scaleModes + * @property {Number} Phaser.scaleModes.DEFAULT=LINEAR + * @property {Number} Phaser.scaleModes.LINEAR Smooth scaling + * @property {Number} Phaser.scaleModes.NEAREST Pixelating scaling + * @static + */ scaleModes: { DEFAULT: 0, LINEAR: 0, diff --git a/src/PixiDefaults.js b/src/PixiDefaults.js index 33c6a153f..a3bd46771 100644 --- a/src/PixiDefaults.js +++ b/src/PixiDefaults.js @@ -1,9 +1,9 @@ /* global Phaser:true */ /** -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ // Pixi expects these globals to exist diff --git a/src/animation/Animation.js b/src/animation/Animation.js index 5c220d23f..afbad7923 100644 --- a/src/animation/Animation.js +++ b/src/animation/Animation.js @@ -1,154 +1,153 @@ /** -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* An Animation instance contains a single animation and the controls to play it. -* -* It is created by the AnimationManager, consists of Animation.Frame objects and belongs to a single Game Object such as a Sprite. -* -* @class Phaser.Animation -* @constructor -* @param {Phaser.Game} game - A reference to the currently running game. -* @param {Phaser.Sprite} parent - A reference to the owner of this Animation. -* @param {string} name - The unique name for this animation, used in playback commands. -* @param {Phaser.FrameData} frameData - The FrameData object that contains all frames used by this Animation. -* @param {number[]|string[]} frames - An array of numbers or strings indicating which frames to play in which order. -* @param {number} [frameRate=60] - The speed at which the animation should play. The speed is given in frames per second. -* @param {boolean} [loop=false] - Whether or not the animation is looped or just plays once. -*/ + * An Animation instance contains a single animation and the controls to play it. + * + * It is created by the AnimationManager, consists of Animation.Frame objects and belongs to a single Game Object such as a Sprite. + * + * @class Phaser.Animation + * @constructor + * @param {Phaser.Game} game - A reference to the currently running game. + * @param {Phaser.Sprite} parent - A reference to the owner of this Animation. + * @param {string} name - The unique name for this animation, used in playback commands. + * @param {Phaser.FrameData} frameData - The FrameData object that contains all frames used by this Animation. + * @param {number[]|string[]} frames - An array of numbers or strings indicating which frames to play in which order. + * @param {number} [frameRate=60] - The speed at which the animation should play. The speed is given in frames per second. + * @param {boolean} [loop=false] - Whether or not the animation is looped or just plays once. + */ Phaser.Animation = function (game, parent, name, frameData, frames, frameRate, loop) { - if (loop === undefined) { loop = false; } /** - * @property {Phaser.Game} game - A reference to the currently running Game. - */ + * @property {Phaser.Game} game - A reference to the currently running Game. + */ this.game = game; /** - * @property {Phaser.Sprite} _parent - A reference to the parent Sprite that owns this Animation. - * @private - */ + * @property {Phaser.Sprite} _parent - A reference to the parent Sprite that owns this Animation. + * @private + */ this._parent = parent; /** - * @property {Phaser.FrameData} _frameData - The FrameData the Animation uses. - * @private - */ + * @property {Phaser.FrameData} _frameData - The FrameData the Animation uses. + * @private + */ this._frameData = frameData; /** - * @property {string} name - The user defined name given to this Animation. - */ + * @property {string} name - The user defined name given to this Animation. + */ this.name = name; /** - * @property {array} _frames - * @private - */ + * @property {array} _frames + * @private + */ this._frames = []; this._frames = this._frames.concat(frames); /** - * @property {number} delay - The delay in ms between each frame of the Animation, based on the given frameRate. - */ + * @property {number} delay - The delay in ms between each frame of the Animation, based on the given frameRate. + */ this.delay = 1000 / frameRate; /** - * @property {boolean} loop - The loop state of the Animation. - */ + * @property {boolean} loop - The loop state of the Animation. + */ this.loop = loop; /** - * @property {number} loopCount - The number of times the animation has looped since it was last started. - */ + * @property {number} loopCount - The number of times the animation has looped since it was last started. + */ this.loopCount = 0; /** - * @property {boolean} killOnComplete - Should the parent of this Animation be killed when the animation completes? - * @default - */ + * @property {boolean} killOnComplete - Should the parent of this Animation be killed when the animation completes? + * @default + */ this.killOnComplete = false; /** - * @property {boolean} isFinished - The finished state of the Animation. Set to true once playback completes, false during playback. - * @default - */ + * @property {boolean} isFinished - The finished state of the Animation. Set to true once playback completes, false during playback. + * @default + */ this.isFinished = false; /** - * @property {boolean} isPlaying - The playing state of the Animation. Set to false once playback completes, true during playback. - * @default - */ + * @property {boolean} isPlaying - The playing state of the Animation. Set to false once playback completes, true during playback. + * @default + */ this.isPlaying = false; /** - * @property {boolean} isPaused - The paused state of the Animation. - * @default - */ + * @property {boolean} isPaused - The paused state of the Animation. + * @default + */ this.isPaused = false; /** - * @property {boolean} _pauseStartTime - The time the animation paused. - * @private - * @default - */ + * @property {boolean} _pauseStartTime - The time the animation paused. + * @private + * @default + */ this._pauseStartTime = 0; /** - * @property {number} _frameIndex - * @private - * @default - */ + * @property {number} _frameIndex + * @private + * @default + */ this._frameIndex = 0; /** - * @property {number} _frameDiff - * @private - * @default - */ + * @property {number} _frameDiff + * @private + * @default + */ this._frameDiff = 0; /** - * @property {number} _frameSkip - * @private - * @default - */ + * @property {number} _frameSkip + * @private + * @default + */ this._frameSkip = 1; /** - * @property {Phaser.Frame} currentFrame - The currently displayed frame of the Animation. - */ + * @property {Phaser.Frame} currentFrame - The currently displayed frame of the Animation. + */ this.currentFrame = this._frameData.getFrame(this._frames[this._frameIndex]); /** - * @property {Phaser.Signal} onStart - This event is dispatched when this Animation starts playback. - */ + * @property {Phaser.Signal} onStart - This event is dispatched when this Animation starts playback. + */ this.onStart = new Phaser.Signal(); /** - * This event is dispatched when the Animation changes frame. - * By default this event is disabled due to its intensive nature. Enable it with: `Animation.enableUpdate = true`. - * Note that the event is only dispatched with the current frame. In a low-FPS environment Animations - * will automatically frame-skip to try and claw back time, so do not base your code on expecting to - * receive a perfectly sequential set of frames from this event. - * @property {Phaser.Signal|null} onUpdate - * @default - */ + * This event is dispatched when the Animation changes frame. + * By default this event is disabled due to its intensive nature. Enable it with: `Animation.enableUpdate = true`. + * Note that the event is only dispatched with the current frame. In a low-FPS environment Animations + * will automatically frame-skip to try and claw back time, so do not base your code on expecting to + * receive a perfectly sequential set of frames from this event. + * @property {Phaser.Signal|null} onUpdate + * @default + */ this.onUpdate = null; /** - * @property {Phaser.Signal} onComplete - This event is dispatched when this Animation completes playback. If the animation is set to loop this is never fired, listen for onLoop instead. - */ + * @property {Phaser.Signal} onComplete - This event is dispatched when this Animation completes playback. If the animation is set to loop this is never fired, listen for onLoop instead. + */ this.onComplete = new Phaser.Signal(); /** - * @property {Phaser.Signal} onLoop - This event is dispatched when this Animation loops. - */ + * @property {Phaser.Signal} onLoop - This event is dispatched when this Animation loops. + */ this.onLoop = new Phaser.Signal(); /** @@ -160,26 +159,24 @@ Phaser.Animation = function (game, parent, name, frameData, frames, frameRate, l // Set-up some event listeners this.game.onPause.add(this.onPause, this); this.game.onResume.add(this.onResume, this); - }; Phaser.Animation.prototype = { /** - * Plays this animation. - * - * If you need to jump to a specific frame of this animation, then call `play` and immediately after it, - * set the frame you require (i.e. `animation.play(); animation.frame = 4`). - * - * @method Phaser.Animation#play - * @param {number} [frameRate=null] - The framerate to play the animation at. The speed is given in frames per second. If not provided the previously set frameRate of the Animation is used. - * @param {boolean} [loop=false] - Should the animation be looped after playback. If not provided the previously set loop value of the Animation is used. - * @param {boolean} [killOnComplete=false] - If set to true when the animation completes (only happens if loop=false) the parent Sprite will be killed. - * @return {Phaser.Animation} - A reference to this Animation instance. - */ + * Plays this animation. + * + * If you need to jump to a specific frame of this animation, then call `play` and immediately after it, + * set the frame you require (i.e. `animation.play(); animation.frame = 4`). + * + * @method Phaser.Animation#play + * @param {number} [frameRate=null] - The framerate to play the animation at. The speed is given in frames per second. If not provided the previously set frameRate of the Animation is used. + * @param {boolean} [loop=false] - Should the animation be looped after playback. If not provided the previously set loop value of the Animation is used. + * @param {boolean} [killOnComplete=false] - If set to true when the animation completes (only happens if loop=false) the parent Sprite will be killed. + * @return {Phaser.Animation} - A reference to this Animation instance. + */ play: function (frameRate, loop, killOnComplete) { - if (typeof frameRate === 'number') { // If they set a new frame rate then use it, otherwise use the one set on creation @@ -217,17 +214,15 @@ Phaser.Animation.prototype = { this._parent.animations.currentFrame = this.currentFrame; return this; - }, /** - * Sets this animation back to the first frame and restarts the animation. - * - * @method Phaser.Animation#restart - */ + * Sets this animation back to the first frame and restarts the animation. + * + * @method Phaser.Animation#restart + */ restart: function () { - this.isPlaying = true; this.isFinished = false; this.paused = false; @@ -246,51 +241,45 @@ Phaser.Animation.prototype = { this._parent.animations.currentFrame = this.currentFrame; this.onStart.dispatch(this._parent, this); - }, /** - * Reverses the animation direction. - * - * @method Phaser.Animation#reverse - * @return {Phaser.Animation} The animation instance. - */ + * Reverses the animation direction. + * + * @method Phaser.Animation#reverse + * @return {Phaser.Animation} The animation instance. + */ reverse: function () { - this.reversed = !this.reversed; return this; - }, /** - * Reverses the animation direction for the current/next animation only - * Once the onComplete event is called this method will be called again and revert - * the reversed state. - * - * @method Phaser.Animation#reverseOnce - * @return {Phaser.Animation} The animation instance. - */ + * Reverses the animation direction for the current/next animation only + * Once the onComplete event is called this method will be called again and revert + * the reversed state. + * + * @method Phaser.Animation#reverseOnce + * @return {Phaser.Animation} The animation instance. + */ reverseOnce: function () { - this.onComplete.addOnce(this.reverse, this); return this.reverse(); - }, /** - * Sets this animations playback to a given frame with the given ID. - * - * @method Phaser.Animation#setFrame - * @param {string|number} [frameId] - The identifier of the frame to set. Can be the name of the frame, the sprite index of the frame, or the animation-local frame index. - * @param {boolean} [useLocalFrameIndex=false] - If you provide a number for frameId, should it use the numeric indexes of the frameData, or the 0-indexed frame index local to the animation. - */ + * Sets this animations playback to a given frame with the given ID. + * + * @method Phaser.Animation#setFrame + * @param {string|number} [frameId] - The identifier of the frame to set. Can be the name of the frame, the sprite index of the frame, or the animation-local frame index. + * @param {boolean} [useLocalFrameIndex=false] - If you provide a number for frameId, should it use the numeric indexes of the frameData, or the 0-indexed frame index local to the animation. + */ setFrame: function (frameId, useLocalFrameIndex) { - var frameIndex; if (useLocalFrameIndex === undefined) @@ -338,20 +327,18 @@ Phaser.Animation.prototype = { this.update(); } - }, /** - * Stops playback of this animation and set it to a finished state. If a resetFrame is provided it will stop playback and set frame to the first in the animation. - * If `dispatchComplete` is true it will dispatch the complete events, otherwise they'll be ignored. - * - * @method Phaser.Animation#stop - * @param {boolean} [resetFrame=false] - If true after the animation stops the currentFrame value will be set to the first frame in this animation. - * @param {boolean} [dispatchComplete=false] - Dispatch the Animation.onComplete and parent.onAnimationComplete events? - */ + * Stops playback of this animation and set it to a finished state. If a resetFrame is provided it will stop playback and set frame to the first in the animation. + * If `dispatchComplete` is true it will dispatch the complete events, otherwise they'll be ignored. + * + * @method Phaser.Animation#stop + * @param {boolean} [resetFrame=false] - If true after the animation stops the currentFrame value will be set to the first frame in this animation. + * @param {boolean} [dispatchComplete=false] - Dispatch the Animation.onComplete and parent.onAnimationComplete events? + */ stop: function (resetFrame, dispatchComplete) { - if (resetFrame === undefined) { resetFrame = false; } if (dispatchComplete === undefined) { dispatchComplete = false; } @@ -370,47 +357,41 @@ Phaser.Animation.prototype = { this._parent.events.onAnimationComplete$dispatch(this._parent, this); this.onComplete.dispatch(this._parent, this); } - }, /** - * Called when the Game enters a paused state. - * - * @method Phaser.Animation#onPause - */ + * Called when the Game enters a paused state. + * + * @method Phaser.Animation#onPause + */ onPause: function () { - if (this.isPlaying) { this._frameDiff = this._timeNextFrame - this.game.time.time; } - }, /** - * Called when the Game resumes from a paused state. - * - * @method Phaser.Animation#onResume - */ + * Called when the Game resumes from a paused state. + * + * @method Phaser.Animation#onResume + */ onResume: function () { - if (this.isPlaying) { this._timeNextFrame = this.game.time.time + this._frameDiff; } - }, /** - * Updates this animation. Called automatically by the AnimationManager. - * - * @method Phaser.Animation#update - */ + * Updates this animation. Called automatically by the AnimationManager. + * + * @method Phaser.Animation#update + */ update: function () { - if (this.isPaused) { return false; @@ -493,24 +474,22 @@ Phaser.Animation.prototype = { } return false; - }, /** - * Changes the currentFrame per the _frameIndex, updates the display state, - * and triggers the update signal. - * - * Returns true if the current frame update was 'successful', false otherwise. - * - * @method Phaser.Animation#updateCurrentFrame - * @private - * @param {boolean} signalUpdate - If true the `Animation.onUpdate` signal will be dispatched. - * @param {boolean} fromPlay - Was this call made from the playing of a new animation? - * @return {boolean} True if the current frame was updated, otherwise false. - */ + * Changes the currentFrame per the _frameIndex, updates the display state, + * and triggers the update signal. + * + * Returns true if the current frame update was 'successful', false otherwise. + * + * @method Phaser.Animation#updateCurrentFrame + * @private + * @param {boolean} signalUpdate - If true the `Animation.onUpdate` signal will be dispatched. + * @param {boolean} fromPlay - Was this call made from the playing of a new animation? + * @return {boolean} True if the current frame was updated, otherwise false. + */ updateCurrentFrame: function (signalUpdate, fromPlay) { - if (fromPlay === undefined) { fromPlay = false; } if (!this._frameData) @@ -540,18 +519,16 @@ Phaser.Animation.prototype = { { return true; } - }, /** - * Advances by the given number of frames in the Animation, taking the loop value into consideration. - * - * @method Phaser.Animation#next - * @param {number} [quantity=1] - The number of frames to advance. - */ + * Advances by the given number of frames in the Animation, taking the loop value into consideration. + * + * @method Phaser.Animation#next + * @param {number} [quantity=1] - The number of frames to advance. + */ next: function (quantity) { - if (quantity === undefined) { quantity = 1; } var frame = this._frameIndex + quantity; @@ -573,18 +550,16 @@ Phaser.Animation.prototype = { this._frameIndex = frame; this.updateCurrentFrame(true); } - }, /** - * Moves backwards the given number of frames in the Animation, taking the loop value into consideration. - * - * @method Phaser.Animation#previous - * @param {number} [quantity=1] - The number of frames to move back. - */ + * Moves backwards the given number of frames in the Animation, taking the loop value into consideration. + * + * @method Phaser.Animation#previous + * @param {number} [quantity=1] - The number of frames to move back. + */ previous: function (quantity) { - if (quantity === undefined) { quantity = 1; } var frame = this._frameIndex - quantity; @@ -606,31 +581,27 @@ Phaser.Animation.prototype = { this._frameIndex = frame; this.updateCurrentFrame(true); } - }, /** - * Changes the FrameData object this Animation is using. - * - * @method Phaser.Animation#updateFrameData - * @param {Phaser.FrameData} frameData - The FrameData object that contains all frames used by this Animation. - */ + * Changes the FrameData object this Animation is using. + * + * @method Phaser.Animation#updateFrameData + * @param {Phaser.FrameData} frameData - The FrameData object that contains all frames used by this Animation. + */ updateFrameData: function (frameData) { - this._frameData = frameData; this.currentFrame = this._frameData ? this._frameData.getFrame(this._frames[this._frameIndex % this._frames.length]) : null; - }, /** - * Cleans up this animation ready for deletion. Nulls all values and references. - * - * @method Phaser.Animation#destroy - */ + * Cleans up this animation ready for deletion. Nulls all values and references. + * + * @method Phaser.Animation#destroy + */ destroy: function () { - if (!this._frameData) { // Already destroyed @@ -655,18 +626,16 @@ Phaser.Animation.prototype = { { this.onUpdate.dispose(); } - }, /** - * Called internally when the animation finishes playback. - * Sets the isPlaying and isFinished states and dispatches the onAnimationComplete event if it exists on the parent and local onComplete event. - * - * @method Phaser.Animation#complete - */ + * Called internally when the animation finishes playback. + * Sets the isPlaying and isFinished states and dispatches the onAnimationComplete event if it exists on the parent and local onComplete event. + * + * @method Phaser.Animation#complete + */ complete: function () { - this._frameIndex = this._frames.length - 1; this.currentFrame = this._frameData.getFrame(this._frames[this._frameIndex]); this.updateCurrentFrame(false); @@ -683,7 +652,6 @@ Phaser.Animation.prototype = { { this._parent.kill(); } - } }; @@ -691,21 +659,18 @@ Phaser.Animation.prototype = { Phaser.Animation.prototype.constructor = Phaser.Animation; /** -* @name Phaser.Animation#paused -* @property {boolean} paused - Gets and sets the paused state of this Animation. -*/ + * @name Phaser.Animation#paused + * @property {boolean} paused - Gets and sets the paused state of this Animation. + */ Object.defineProperty(Phaser.Animation.prototype, 'paused', { get: function () { - return this.isPaused; - }, set: function (value) { - this.isPaused = value; if (value) @@ -721,38 +686,33 @@ Object.defineProperty(Phaser.Animation.prototype, 'paused', { this._timeNextFrame = this.game.time.time + this.delay; } } - } }); /** -* @name Phaser.Animation#reversed -* @property {boolean} reversed - Gets and sets the isReversed state of this Animation. -*/ + * @name Phaser.Animation#reversed + * @property {boolean} reversed - Gets and sets the isReversed state of this Animation. + */ Object.defineProperty(Phaser.Animation.prototype, 'reversed', { get: function () { - return this.isReversed; - }, set: function (value) { - this.isReversed = value; - } }); /** -* @name Phaser.Animation#frameTotal -* @property {number} frameTotal - The total number of frames in the currently loaded FrameData, or -1 if no FrameData is loaded. -* @readonly -*/ + * @name Phaser.Animation#frameTotal + * @property {number} frameTotal - The total number of frames in the currently loaded FrameData, or -1 if no FrameData is loaded. + * @readonly + */ Object.defineProperty(Phaser.Animation.prototype, 'frameTotal', { get: function () @@ -763,14 +723,13 @@ Object.defineProperty(Phaser.Animation.prototype, 'frameTotal', { }); /** -* @name Phaser.Animation#frame -* @property {number} frame - Gets or sets the current frame index and updates the Texture Cache for display. -*/ + * @name Phaser.Animation#frame + * @property {number} frame - Gets or sets the current frame index and updates the Texture Cache for display. + */ Object.defineProperty(Phaser.Animation.prototype, 'frame', { get: function () { - if (this.currentFrame !== null) { return this.currentFrame.index; @@ -779,12 +738,10 @@ Object.defineProperty(Phaser.Animation.prototype, 'frame', { { return this._frameIndex; } - }, set: function (value) { - this.currentFrame = this._frameData.getFrame(this._frames[value]); if (this.currentFrame !== null) @@ -797,52 +754,44 @@ Object.defineProperty(Phaser.Animation.prototype, 'frame', { this.onUpdate.dispatch(this, this.currentFrame); } } - } }); /** -* @name Phaser.Animation#speed -* @property {number} speed - Gets or sets the current speed of the animation in frames per second. Changing this in a playing animation will take effect from the next frame. Value must be greater than 0. -*/ + * @name Phaser.Animation#speed + * @property {number} speed - Gets or sets the current speed of the animation in frames per second. Changing this in a playing animation will take effect from the next frame. Value must be greater than 0. + */ Object.defineProperty(Phaser.Animation.prototype, 'speed', { get: function () { - return 1000 / this.delay; - }, set: function (value) { - if (value > 0) { this.delay = 1000 / value; } - } }); /** -* @name Phaser.Animation#enableUpdate -* @property {boolean} enableUpdate - Gets or sets if this animation will dispatch the onUpdate events upon changing frame. -*/ + * @name Phaser.Animation#enableUpdate + * @property {boolean} enableUpdate - Gets or sets if this animation will dispatch the onUpdate events upon changing frame. + */ Object.defineProperty(Phaser.Animation.prototype, 'enableUpdate', { get: function () { - return (this.onUpdate !== null); - }, set: function (value) { - if (value && this.onUpdate === null) { this.onUpdate = new Phaser.Signal(); @@ -852,28 +801,26 @@ Object.defineProperty(Phaser.Animation.prototype, 'enableUpdate', { this.onUpdate.dispose(); this.onUpdate = null; } - } }); /** -* Really handy function for when you are creating arrays of animation data but it's using frame names and not numbers. -* For example imagine you've got 30 frames named: 'explosion_0001-large' to 'explosion_0030-large' -* You could use this function to generate those by doing: Phaser.Animation.generateFrameNames('explosion_', 1, 30, '-large', 4); -* -* @method Phaser.Animation.generateFrameNames -* @static -* @param {string} prefix - The start of the filename. If the filename was 'explosion_0001-large' the prefix would be 'explosion_'. -* @param {number} start - The number to start sequentially counting from. If your frames are named 'explosion_0001' to 'explosion_0034' the start is 1. -* @param {number} stop - The number to count to. If your frames are named 'explosion_0001' to 'explosion_0034' the stop value is 34. -* @param {string} [suffix=''] - The end of the filename. If the filename was 'explosion_0001-large' the suffix would be '-large'. -* @param {number} [zeroPad=0] - The number of zeros to pad the min and max values with. If your frames are named 'explosion_0001' to 'explosion_0034' then the zeroPad is 4. -* @return {string[]} An array of framenames. -*/ + * Really handy function for when you are creating arrays of animation data but it's using frame names and not numbers. + * For example imagine you've got 30 frames named: 'explosion_0001-large' to 'explosion_0030-large' + * You could use this function to generate those by doing: Phaser.Animation.generateFrameNames('explosion_', 1, 30, '-large', 4); + * + * @method Phaser.Animation.generateFrameNames + * @static + * @param {string} prefix - The start of the filename. If the filename was 'explosion_0001-large' the prefix would be 'explosion_'. + * @param {number} start - The number to start sequentially counting from. If your frames are named 'explosion_0001' to 'explosion_0034' the start is 1. + * @param {number} stop - The number to count to. If your frames are named 'explosion_0001' to 'explosion_0034' the stop value is 34. + * @param {string} [suffix=''] - The end of the filename. If the filename was 'explosion_0001-large' the suffix would be '-large'. + * @param {number} [zeroPad=0] - The number of zeros to pad the min and max values with. If your frames are named 'explosion_0001' to 'explosion_0034' then the zeroPad is 4. + * @return {string[]} An array of framenames. + */ Phaser.Animation.generateFrameNames = function (prefix, start, stop, suffix, zeroPad) { - if (suffix === undefined) { suffix = ''; } var output = []; @@ -919,5 +866,4 @@ Phaser.Animation.generateFrameNames = function (prefix, start, stop, suffix, zer } return output; - }; diff --git a/src/animation/AnimationManager.js b/src/animation/AnimationManager.js index eee55110d..fbfa985a8 100644 --- a/src/animation/AnimationManager.js +++ b/src/animation/AnimationManager.js @@ -1,93 +1,90 @@ /** -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* The Animation Manager is used to add, play and update Phaser Animations. -* Any Game Object such as Phaser.Sprite that supports animation contains a single AnimationManager instance. -* -* @class Phaser.AnimationManager -* @constructor -* @param {Phaser.Sprite} sprite - A reference to the Game Object that owns this AnimationManager. -*/ + * The Animation Manager is used to add, play and update Phaser Animations. + * Any Game Object such as Phaser.Sprite that supports animation contains a single AnimationManager instance. + * + * @class Phaser.AnimationManager + * @constructor + * @param {Phaser.Sprite} sprite - A reference to the Game Object that owns this AnimationManager. + */ Phaser.AnimationManager = function (sprite) { - /** - * @property {Phaser.Sprite} sprite - A reference to the parent Sprite that owns this AnimationManager. - */ + * @property {Phaser.Sprite} sprite - A reference to the parent Sprite that owns this AnimationManager. + */ this.sprite = sprite; /** - * @property {Phaser.Game} game - A reference to the currently running Game. - */ + * @property {Phaser.Game} game - A reference to the currently running Game. + */ this.game = sprite.game; /** - * The currently displayed Frame of animation, if any. - * This property is only set once an Animation starts playing. Until that point it remains set as `null`. - * - * @property {Phaser.Frame} currentFrame - * @default - */ + * The currently displayed Frame of animation, if any. + * This property is only set once an Animation starts playing. Until that point it remains set as `null`. + * + * @property {Phaser.Frame} currentFrame + * @default + */ this.currentFrame = null; /** - * @property {Phaser.Animation} currentAnim - The currently displayed animation, if any. - * @default - */ + * @property {Phaser.Animation} currentAnim - The currently displayed animation, if any. + * @default + */ this.currentAnim = null; /** - * @property {boolean} updateIfVisible - Update the animation data only while the the sprite is {@link Phaser.Sprite#visible}. Set to `false` to continue updating while the sprite is invisible. - * @default - */ + * @property {boolean} updateIfVisible - Update the animation data only while the the sprite is {@link Phaser.Sprite#visible}. Set to `false` to continue updating while the sprite is invisible. + * @default + */ this.updateIfVisible = true; /** - * @property {boolean} isLoaded - Set to true once animation data has been loaded. - * @default - */ + * @property {boolean} isLoaded - Set to true once animation data has been loaded. + * @default + */ this.isLoaded = false; /** - * @property {Phaser.FrameData} _frameData - A temp. var for holding the currently playing Animations FrameData. - * @private - * @default - */ + * @property {Phaser.FrameData} _frameData - A temp. var for holding the currently playing Animations FrameData. + * @private + * @default + */ this._frameData = null; /** - * @property {object} _anims - An internal object that stores all of the Animation instances. - * @private - */ + * @property {object} _anims - An internal object that stores all of the Animation instances. + * @private + */ this._anims = {}; /** - * @property {object} _outputFrames - An internal object to help avoid gc. - * @private - */ + * @property {object} _outputFrames - An internal object to help avoid gc. + * @private + */ this._outputFrames = []; - }; Phaser.AnimationManager.prototype = { /** - * Loads FrameData into the internal temporary vars and resets the frame index to zero. - * This is called automatically when a new Sprite is created. - * - * @method Phaser.AnimationManager#loadFrameData - * @private - * @param {Phaser.FrameData} frameData - The FrameData set to load. - * @param {string|number} frame - The frame to default to. - * @return {boolean} Returns `true` if the frame data was loaded successfully, otherwise `false` - */ + * Loads FrameData into the internal temporary vars and resets the frame index to zero. + * This is called automatically when a new Sprite is created. + * + * @method Phaser.AnimationManager#loadFrameData + * @private + * @param {Phaser.FrameData} frameData - The FrameData set to load. + * @param {string|number} frame - The frame to default to. + * @return {boolean} Returns `true` if the frame data was loaded successfully, otherwise `false` + */ loadFrameData: function (frameData, frame) { - if (frameData === undefined) { return false; @@ -124,18 +121,17 @@ Phaser.AnimationManager.prototype = { }, /** - * Loads FrameData into the internal temporary vars and resets the frame index to zero. - * This is called automatically when a new Sprite is created. - * - * @method Phaser.AnimationManager#copyFrameData - * @private - * @param {Phaser.FrameData} frameData - The FrameData set to load. - * @param {string|number} frame - The frame to default to. - * @return {boolean} Returns `true` if the frame data was loaded successfully, otherwise `false` - */ + * Loads FrameData into the internal temporary vars and resets the frame index to zero. + * This is called automatically when a new Sprite is created. + * + * @method Phaser.AnimationManager#copyFrameData + * @private + * @param {Phaser.FrameData} frameData - The FrameData set to load. + * @param {string|number} frame - The frame to default to. + * @return {boolean} Returns `true` if the frame data was loaded successfully, otherwise `false` + */ copyFrameData: function (frameData, frame) { - this._frameData = frameData.clone(); if (this.isLoaded) @@ -167,20 +163,19 @@ Phaser.AnimationManager.prototype = { }, /** - * Adds a new animation under the given key. Optionally set the frames, frame rate and loop. - * Animations added in this way are played back with the play function. - * - * @method Phaser.AnimationManager#add - * @param {string} name - The unique (within this Sprite) name for the animation, i.e. "run", "fire", "walk". - * @param {Array} [frames=null] - An array of numbers/strings that correspond to the frames to add to this animation and in which order. e.g. [1, 2, 3] or ['run0', 'run1', run2]). If null then all frames will be used. - * @param {number} [frameRate=60] - The speed at which the animation should play. The speed is given in frames per second. - * @param {boolean} [loop=false] - Whether or not the animation is looped or just plays once. - * @param {boolean} [useNumericIndex=true] - Are the given frames using numeric indexes (default) or strings? - * @return {Phaser.Animation} The Animation object that was created. - */ + * Adds a new animation under the given key. Optionally set the frames, frame rate and loop. + * Animations added in this way are played back with the play function. + * + * @method Phaser.AnimationManager#add + * @param {string} name - The unique (within this Sprite) name for the animation, i.e. "run", "fire", "walk". + * @param {Array} [frames=null] - An array of numbers/strings that correspond to the frames to add to this animation and in which order. e.g. [1, 2, 3] or ['run0', 'run1', run2]). If null then all frames will be used. + * @param {number} [frameRate=60] - The speed at which the animation should play. The speed is given in frames per second. + * @param {boolean} [loop=false] - Whether or not the animation is looped or just plays once. + * @param {boolean} [useNumericIndex=true] - Are the given frames using numeric indexes (default) or strings? + * @return {Phaser.Animation} The Animation object that was created. + */ add: function (name, frames, frameRate, loop, useNumericIndex) { - frames = frames || []; frameRate = frameRate || 60; @@ -213,20 +208,18 @@ Phaser.AnimationManager.prototype = { } return this._anims[name]; - }, /** - * Check whether the frames in the given array are valid and exist. - * - * @method Phaser.AnimationManager#validateFrames - * @param {Array} frames - An array of frames to be validated. - * @param {boolean} [useNumericIndex=true] - Validate the frames based on their numeric index (true) or string index (false) - * @return {boolean} True if all given Frames are valid, otherwise false. - */ + * Check whether the frames in the given array are valid and exist. + * + * @method Phaser.AnimationManager#validateFrames + * @param {Array} frames - An array of frames to be validated. + * @param {boolean} [useNumericIndex=true] - Validate the frames based on their numeric index (true) or string index (false) + * @return {boolean} True if all given Frames are valid, otherwise false. + */ validateFrames: function (frames, useNumericIndex) { - if (useNumericIndex === undefined) { useNumericIndex = true; } for (var i = 0; i < frames.length; i++) @@ -246,28 +239,26 @@ Phaser.AnimationManager.prototype = { } return true; - }, /** - * Play an animation based on the given key. The animation should previously have been added via `animations.add` - * - * If the requested animation is already playing this request will be ignored. - * If you need to reset an already running animation do so directly on the Animation object itself. - * - * If you need to jump to a specific frame of this animation, then call `play` and immediately after it, - * set the frame you require (i.e. `animation.play(); animation.frame = 4`). - * - * @method Phaser.AnimationManager#play - * @param {string} name - The name of the animation to be played, e.g. "fire", "walk", "jump". - * @param {number} [frameRate=null] - The framerate to play the animation at. The speed is given in frames per second. If not provided the previously set frameRate of the Animation is used. - * @param {boolean} [loop=false] - Should the animation be looped after playback. If not provided the previously set loop value of the Animation is used. - * @param {boolean} [killOnComplete=false] - If set to true when the animation completes (only happens if loop=false) the parent Sprite will be killed. - * @return {Phaser.Animation} A reference to playing Animation instance. - */ + * Play an animation based on the given key. The animation should previously have been added via `animations.add` + * + * If the requested animation is already playing this request will be ignored. + * If you need to reset an already running animation do so directly on the Animation object itself. + * + * If you need to jump to a specific frame of this animation, then call `play` and immediately after it, + * set the frame you require (i.e. `animation.play(); animation.frame = 4`). + * + * @method Phaser.AnimationManager#play + * @param {string} name - The name of the animation to be played, e.g. "fire", "walk", "jump". + * @param {number} [frameRate=null] - The framerate to play the animation at. The speed is given in frames per second. If not provided the previously set frameRate of the Animation is used. + * @param {boolean} [loop=false] - Should the animation be looped after playback. If not provided the previously set loop value of the Animation is used. + * @param {boolean} [killOnComplete=false] - If set to true when the animation completes (only happens if loop=false) the parent Sprite will be killed. + * @return {Phaser.Animation} A reference to playing Animation instance. + */ play: function (name, frameRate, loop, killOnComplete) { - if (this._anims[name]) { if (this.currentAnim === this._anims[name]) @@ -293,39 +284,35 @@ Phaser.AnimationManager.prototype = { return this.currentAnim.play(frameRate, loop, killOnComplete); } } - }, /** - * Stop playback of an animation. If a name is given that specific animation is stopped, otherwise the current animation is stopped. - * The currentAnim property of the AnimationManager is automatically set to the animation given. - * - * @method Phaser.AnimationManager#stop - * @param {string} [name=null] - The name of the animation to be stopped, e.g. "fire". If none is given the currently running animation is stopped. - * @param {boolean} [resetFrame=false] - When the animation is stopped should the currentFrame be set to the first frame of the animation (true) or paused on the last frame displayed (false) - */ + * Stop playback of an animation. If a name is given that specific animation is stopped, otherwise the current animation is stopped. + * The currentAnim property of the AnimationManager is automatically set to the animation given. + * + * @method Phaser.AnimationManager#stop + * @param {string} [name=null] - The name of the animation to be stopped, e.g. "fire". If none is given the currently running animation is stopped. + * @param {boolean} [resetFrame=false] - When the animation is stopped should the currentFrame be set to the first frame of the animation (true) or paused on the last frame displayed (false) + */ stop: function (name, resetFrame) { - if (resetFrame === undefined) { resetFrame = false; } if (this.currentAnim && (typeof name !== 'string' || name === this.currentAnim.name)) { this.currentAnim.stop(resetFrame); } - }, /** - * The main update function is called by the Sprites update loop. It's responsible for updating animation frames and firing related events. - * - * @method Phaser.AnimationManager#update - * @protected - * @return {boolean} True if a new animation frame has been set, otherwise false. - */ + * The main update function is called by the Sprites update loop. It's responsible for updating animation frames and firing related events. + * + * @method Phaser.AnimationManager#update + * @protected + * @return {boolean} True if a new animation frame has been set, otherwise false. + */ update: function () { - if (this.updateIfVisible && !this.sprite.visible) { return false; @@ -338,53 +325,47 @@ Phaser.AnimationManager.prototype = { } return false; - }, /** - * Advances by the given number of frames in the current animation, taking the loop value into consideration. - * - * @method Phaser.AnimationManager#next - * @param {number} [quantity=1] - The number of frames to advance. - */ + * Advances by the given number of frames in the current animation, taking the loop value into consideration. + * + * @method Phaser.AnimationManager#next + * @param {number} [quantity=1] - The number of frames to advance. + */ next: function (quantity) { - if (this.currentAnim) { this.currentAnim.next(quantity); this.currentFrame = this.currentAnim.currentFrame; } - }, /** - * Moves backwards the given number of frames in the current animation, taking the loop value into consideration. - * - * @method Phaser.AnimationManager#previous - * @param {number} [quantity=1] - The number of frames to move back. - */ + * Moves backwards the given number of frames in the current animation, taking the loop value into consideration. + * + * @method Phaser.AnimationManager#previous + * @param {number} [quantity=1] - The number of frames to move back. + */ previous: function (quantity) { - if (this.currentAnim) { this.currentAnim.previous(quantity); this.currentFrame = this.currentAnim.currentFrame; } - }, /** - * Returns an animation that was previously added by name. - * - * @method Phaser.AnimationManager#getAnimation - * @param {string} name - The name of the animation to be returned, e.g. "fire". - * @return {Phaser.Animation} The Animation instance, if found, otherwise null. - */ + * Returns an animation that was previously added by name. + * + * @method Phaser.AnimationManager#getAnimation + * @param {string} name - The name of the animation to be returned, e.g. "fire". + * @return {Phaser.Animation} The Animation instance, if found, otherwise null. + */ getAnimation: function (name) { - if (typeof name === 'string') { if (this._anims[name]) @@ -394,31 +375,31 @@ Phaser.AnimationManager.prototype = { } return null; - }, /** - * Refreshes the current frame data back to the parent Sprite and also resets the texture data. - * - * @method Phaser.AnimationManager#refreshFrame - */ + * Refreshes the current frame data back to the parent Sprite and also resets the texture data. + * + * @method Phaser.AnimationManager#refreshFrame + */ refreshFrame: function () { - // TODO - // this.sprite.setTexture(PIXI.TextureCache[this.currentFrame.uuid]); + /* + * TODO + * this.sprite.setTexture(PIXI.TextureCache[this.currentFrame.uuid]); + */ }, /** - * Destroys all references this AnimationManager contains. - * Iterates through the list of animations stored in this manager and calls destroy on each of them. - * - * @method Phaser.AnimationManager#destroy - */ + * Destroys all references this AnimationManager contains. + * Iterates through the list of animations stored in this manager and calls destroy on each of them. + * + * @method Phaser.AnimationManager#destroy + */ destroy: function () { - var anim = null; for (var anim in this._anims) @@ -436,7 +417,6 @@ Phaser.AnimationManager.prototype = { this.currentFrame = null; this.sprite = null; this.game = null; - } }; @@ -444,10 +424,10 @@ Phaser.AnimationManager.prototype = { Phaser.AnimationManager.prototype.constructor = Phaser.AnimationManager; /** -* @name Phaser.AnimationManager#frameData -* @property {Phaser.FrameData} frameData - The current animations FrameData. -* @readonly -*/ + * @name Phaser.AnimationManager#frameData + * @property {Phaser.FrameData} frameData - The current animations FrameData. + * @readonly + */ Object.defineProperty(Phaser.AnimationManager.prototype, 'frameData', { get: function () @@ -458,73 +438,63 @@ Object.defineProperty(Phaser.AnimationManager.prototype, 'frameData', { }); /** -* @name Phaser.AnimationManager#frameTotal -* @property {number} frameTotal - The total number of frames in the currently loaded FrameData, or -1 if no FrameData is loaded. -* @readonly -*/ + * @name Phaser.AnimationManager#frameTotal + * @property {number} frameTotal - The total number of frames in the currently loaded FrameData, or -1 if no FrameData is loaded. + * @readonly + */ Object.defineProperty(Phaser.AnimationManager.prototype, 'frameTotal', { get: function () { - return this._frameData.total; } }); /** -* @name Phaser.AnimationManager#paused -* @property {boolean} paused - Gets and sets the paused state of the current animation. -*/ + * @name Phaser.AnimationManager#paused + * @property {boolean} paused - Gets and sets the paused state of the current animation. + */ Object.defineProperty(Phaser.AnimationManager.prototype, 'paused', { get: function () { - return this.currentAnim.isPaused; - }, set: function (value) { - this.currentAnim.paused = value; - } }); /** -* @name Phaser.AnimationManager#name -* @property {string} name - Gets the current animation name, if set. -*/ + * @name Phaser.AnimationManager#name + * @property {string} name - Gets the current animation name, if set. + */ Object.defineProperty(Phaser.AnimationManager.prototype, 'name', { get: function () { - return (this.currentAnim) ? this.currentAnim.name : undefined; - } }); /** -* @name Phaser.AnimationManager#frame -* @property {number} frame - Gets or sets the current frame index and updates the Texture Cache for display. -*/ + * @name Phaser.AnimationManager#frame + * @property {number} frame - Gets or sets the current frame index and updates the Texture Cache for display. + */ Object.defineProperty(Phaser.AnimationManager.prototype, 'frame', { get: function () { - return (this.currentFrame) ? this.currentFrame.index : undefined; - }, set: function (value) { - var gotFrame; if (typeof value === 'number' && this._frameData && (gotFrame = this._frameData.getFrame(value))) @@ -532,27 +502,23 @@ Object.defineProperty(Phaser.AnimationManager.prototype, 'frame', { this.currentFrame = gotFrame; this.sprite.setFrame(this.currentFrame); } - } }); /** -* @name Phaser.AnimationManager#frameName -* @property {string} frameName - Gets or sets the current frame name and updates the Texture Cache for display. -*/ + * @name Phaser.AnimationManager#frameName + * @property {string} frameName - Gets or sets the current frame name and updates the Texture Cache for display. + */ Object.defineProperty(Phaser.AnimationManager.prototype, 'frameName', { get: function () { - return (this.currentFrame) ? this.currentFrame.name : undefined; - }, set: function (value) { - var gotFrame; if (typeof value === 'string' && this._frameData && (gotFrame = this._frameData.getFrameByName(value))) diff --git a/src/animation/AnimationParser.js b/src/animation/AnimationParser.js index 902b665ae..673ec37d8 100644 --- a/src/animation/AnimationParser.js +++ b/src/animation/AnimationParser.js @@ -1,36 +1,35 @@ /** -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* Responsible for parsing sprite sheet and JSON data into the internal FrameData format that Phaser uses for animations. -* -* @class Phaser.AnimationParser -* @static -*/ + * Responsible for parsing sprite sheet and JSON data into the internal FrameData format that Phaser uses for animations. + * + * @class Phaser.AnimationParser + * @static + */ Phaser.AnimationParser = { /** - * Parse a Sprite Sheet and extract the animation frame data from it. - * - * @method Phaser.AnimationParser.spriteSheet - * @param {Phaser.Game} game - A reference to the currently running game. - * @param {string|Image} key - The Game.Cache asset key of the Sprite Sheet image or an actual HTML Image element. - * @param {number} frameWidth - The fixed width of each frame of the animation. - * @param {number} frameHeight - The fixed height of each frame of the animation. - * @param {number} [frameMax=-1] - The total number of animation frames to extract from the Sprite Sheet. The default value of -1 means "extract all frames". - * @param {number} [margin=0] - If the frames have been drawn with a margin, specify the amount here. - * @param {number} [spacing=0] - If the frames have been drawn with spacing between them, specify the amount here. - * @param {number} [skipFrames=0] - Skip a number of frames. Useful when there are multiple sprite sheets in one image. - * @return {Phaser.FrameData} A FrameData object containing the parsed frames. - * - * @see Phaser.Loader#spritesheet - */ + * Parse a Sprite Sheet and extract the animation frame data from it. + * + * @method Phaser.AnimationParser.spriteSheet + * @param {Phaser.Game} game - A reference to the currently running game. + * @param {string|Image} key - The Game.Cache asset key of the Sprite Sheet image or an actual HTML Image element. + * @param {number} frameWidth - The fixed width of each frame of the animation. + * @param {number} frameHeight - The fixed height of each frame of the animation. + * @param {number} [frameMax=-1] - The total number of animation frames to extract from the Sprite Sheet. The default value of -1 means "extract all frames". + * @param {number} [margin=0] - If the frames have been drawn with a margin, specify the amount here. + * @param {number} [spacing=0] - If the frames have been drawn with spacing between them, specify the amount here. + * @param {number} [skipFrames=0] - Skip a number of frames. Useful when there are multiple sprite sheets in one image. + * @return {Phaser.FrameData} A FrameData object containing the parsed frames. + * + * @see Phaser.Loader#spritesheet + */ spriteSheet: function (game, key, frameWidth, frameHeight, frameMax, margin, spacing, skipFrames) { - if (frameMax === undefined) { frameMax = -1; } if (margin === undefined) { margin = 0; } if (spacing === undefined) { spacing = 0; } @@ -176,20 +175,18 @@ Phaser.AnimationParser = { } return data; - }, /** - * Parse the JSON data and extract the animation frame data from it. - * - * @method Phaser.AnimationParser.JSONData - * @param {Phaser.Game} game - A reference to the currently running game. - * @param {object} json - The JSON data from the Texture Atlas. Must be in Array format. - * @return {Phaser.FrameData} A FrameData object containing the parsed frames. - */ + * Parse the JSON data and extract the animation frame data from it. + * + * @method Phaser.AnimationParser.JSONData + * @param {Phaser.Game} game - A reference to the currently running game. + * @param {object} json - The JSON data from the Texture Atlas. Must be in Array format. + * @return {Phaser.FrameData} A FrameData object containing the parsed frames. + */ JSONData: function (game, json) { - // Malformed? if (!json.frames) { @@ -236,20 +233,18 @@ Phaser.AnimationParser = { } return data; - }, /** - * Parse the JSON data and extract the animation frame data from it. - * - * @method Phaser.AnimationParser.JSONDataPyxel - * @param {Phaser.Game} game - A reference to the currently running game. - * @param {object} json - The JSON data from the Texture Atlas. Must be in Pyxel JSON format. - * @return {Phaser.FrameData} A FrameData object containing the parsed frames. - */ + * Parse the JSON data and extract the animation frame data from it. + * + * @method Phaser.AnimationParser.JSONDataPyxel + * @param {Phaser.Game} game - A reference to the currently running game. + * @param {object} json - The JSON data from the Texture Atlas. Must be in Pyxel JSON format. + * @return {Phaser.FrameData} A FrameData object containing the parsed frames. + */ JSONDataPyxel: function (game, json) { - // Malformed? There are a few keys to check here. var signature = [ 'layers', 'tilewidth','tileheight','tileswide', 'tileshigh' ]; @@ -295,20 +290,18 @@ Phaser.AnimationParser = { } return data; - }, /** - * Parse the JSON data and extract the animation frame data from it. - * - * @method Phaser.AnimationParser.JSONDataHash - * @param {Phaser.Game} game - A reference to the currently running game. - * @param {object} json - The JSON data from the Texture Atlas. Must be in JSON Hash format. - * @return {Phaser.FrameData} A FrameData object containing the parsed frames. - */ + * Parse the JSON data and extract the animation frame data from it. + * + * @method Phaser.AnimationParser.JSONDataHash + * @param {Phaser.Game} game - A reference to the currently running game. + * @param {object} json - The JSON data from the Texture Atlas. Must be in JSON Hash format. + * @return {Phaser.FrameData} A FrameData object containing the parsed frames. + */ JSONDataHash: function (game, json) { - // Malformed? if (!json.frames) { @@ -358,20 +351,18 @@ Phaser.AnimationParser = { } return data; - }, /** - * Parse the XML data and extract the animation frame data from it. - * - * @method Phaser.AnimationParser.XMLData - * @param {Phaser.Game} game - A reference to the currently running game. - * @param {object} xml - The XML data from the Texture Atlas. Must be in Starling XML format. - * @return {Phaser.FrameData} A FrameData object containing the parsed frames. - */ + * Parse the XML data and extract the animation frame data from it. + * + * @method Phaser.AnimationParser.XMLData + * @param {Phaser.Game} game - A reference to the currently running game. + * @param {object} xml - The XML data from the Texture Atlas. Must be in Starling XML format. + * @return {Phaser.FrameData} A FrameData object containing the parsed frames. + */ XMLData: function (game, xml) { - // Malformed? if (!xml.getElementsByTagName('TextureAtlas')) { @@ -426,7 +417,6 @@ Phaser.AnimationParser = { } return data; - } }; diff --git a/src/animation/Frame.js b/src/animation/Frame.js index 39b64addd..bcec5a399 100644 --- a/src/animation/Frame.js +++ b/src/animation/Frame.js @@ -1,47 +1,46 @@ /** -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* A Frame is a single frame of an animation and is part of a FrameData collection. -* -* @class Phaser.Frame -* @constructor -* @param {number} index - The index of this Frame within the FrameData set it is being added to. -* @param {number} x - X position of the frame within the texture image. -* @param {number} y - Y position of the frame within the texture image. -* @param {number} width - Width of the frame within the texture image. -* @param {number} height - Height of the frame within the texture image. -* @param {string} name - The name of the frame. In Texture Atlas data this is usually set to the filename. -*/ + * A Frame is a single frame of an animation and is part of a FrameData collection. + * + * @class Phaser.Frame + * @constructor + * @param {number} index - The index of this Frame within the FrameData set it is being added to. + * @param {number} x - X position of the frame within the texture image. + * @param {number} y - Y position of the frame within the texture image. + * @param {number} width - Width of the frame within the texture image. + * @param {number} height - Height of the frame within the texture image. + * @param {string} name - The name of the frame. In Texture Atlas data this is usually set to the filename. + */ Phaser.Frame = function (index, x, y, width, height, name) { - /** - * @property {number} index - The index of this Frame within the FrameData set it is being added to. - */ + * @property {number} index - The index of this Frame within the FrameData set it is being added to. + */ this.index = index; /** - * @property {number} x - X position within the image to cut from. - */ + * @property {number} x - X position within the image to cut from. + */ this.x = x; /** - * @property {number} y - Y position within the image to cut from. - */ + * @property {number} y - Y position within the image to cut from. + */ this.y = y; /** - * @property {number} width - Width of the frame. - */ + * @property {number} width - Width of the frame. + */ this.width = width; /** - * @property {number} height - Height of the frame. - */ + * @property {number} height - Height of the frame. + */ this.height = height; if (this.width === 0 || this.height === 0) @@ -50,95 +49,93 @@ Phaser.Frame = function (index, x, y, width, height, name) } /** - * @property {string} name - Useful for Texture Atlas files (is set to the filename value). - */ + * @property {string} name - Useful for Texture Atlas files (is set to the filename value). + */ this.name = name; /** - * @property {number} centerX - Center X position within the image to cut from. - */ + * @property {number} centerX - Center X position within the image to cut from. + */ this.centerX = Math.floor(width / 2); /** - * @property {number} centerY - Center Y position within the image to cut from. - */ + * @property {number} centerY - Center Y position within the image to cut from. + */ this.centerY = Math.floor(height / 2); /** - * @property {number} distance - The distance from the top left to the bottom-right of this Frame. - */ + * @property {number} distance - The distance from the top left to the bottom-right of this Frame. + */ this.distance = Phaser.Math.distance(0, 0, width, height); /** - * @property {boolean} rotated - Is the frame rotated in the source texture? - * @default - */ + * @property {boolean} rotated - Is the frame rotated in the source texture? + * @default + */ this.rotated = false; /** - * @property {boolean} trimmed - Was it trimmed when packed? - * @default - */ + * @property {boolean} trimmed - Was it trimmed when packed? + * @default + */ this.trimmed = false; /** - * @property {number} sourceSizeW - Width of the original sprite before it was trimmed. - */ + * @property {number} sourceSizeW - Width of the original sprite before it was trimmed. + */ this.sourceSizeW = width; /** - * @property {number} sourceSizeH - Height of the original sprite before it was trimmed. - */ + * @property {number} sourceSizeH - Height of the original sprite before it was trimmed. + */ this.sourceSizeH = height; /** - * @property {number} spriteSourceSizeX - X position of the trimmed sprite inside original sprite. - * @default - */ + * @property {number} spriteSourceSizeX - X position of the trimmed sprite inside original sprite. + * @default + */ this.spriteSourceSizeX = 0; /** - * @property {number} spriteSourceSizeY - Y position of the trimmed sprite inside original sprite. - * @default - */ + * @property {number} spriteSourceSizeY - Y position of the trimmed sprite inside original sprite. + * @default + */ this.spriteSourceSizeY = 0; /** - * @property {number} spriteSourceSizeW - Width of the trimmed sprite. - * @default - */ + * @property {number} spriteSourceSizeW - Width of the trimmed sprite. + * @default + */ this.spriteSourceSizeW = 0; /** - * @property {number} spriteSourceSizeH - Height of the trimmed sprite. - * @default - */ + * @property {number} spriteSourceSizeH - Height of the trimmed sprite. + * @default + */ this.spriteSourceSizeH = 0; /** - * @property {number} right - The right of the Frame (x + width). - */ + * @property {number} right - The right of the Frame (x + width). + */ this.right = this.x + this.width; /** - * @property {number} bottom - The bottom of the frame (y + height). - */ + * @property {number} bottom - The bottom of the frame (y + height). + */ this.bottom = this.y + this.height; - }; Phaser.Frame.prototype = { /** - * Adjusts of all the Frame properties based on the given width and height values. - * - * @method Phaser.Frame#resize - * @param {integer} width - The new width of the Frame. - * @param {integer} height - The new height of the Frame. - */ + * Adjusts of all the Frame properties based on the given width and height values. + * + * @method Phaser.Frame#resize + * @param {integer} width - The new width of the Frame. + * @param {integer} height - The new height of the Frame. + */ resize: function (width, height) { - this.width = width; this.height = height; this.centerX = Math.floor(width / 2); @@ -148,24 +145,22 @@ Phaser.Frame.prototype = { this.sourceSizeH = height; this.right = this.x + width; this.bottom = this.y + height; - }, /** - * If the frame was trimmed when added to the Texture Atlas this records the trim and source data. - * - * @method Phaser.Frame#setTrim - * @param {boolean} trimmed - If this frame was trimmed or not. - * @param {number} actualWidth - The width of the frame before being trimmed. - * @param {number} actualHeight - The height of the frame before being trimmed. - * @param {number} destX - The destination X position of the trimmed frame for display. - * @param {number} destY - The destination Y position of the trimmed frame for display. - * @param {number} destWidth - The destination width of the trimmed frame for display. - * @param {number} destHeight - The destination height of the trimmed frame for display. - */ + * If the frame was trimmed when added to the Texture Atlas this records the trim and source data. + * + * @method Phaser.Frame#setTrim + * @param {boolean} trimmed - If this frame was trimmed or not. + * @param {number} actualWidth - The width of the frame before being trimmed. + * @param {number} actualHeight - The height of the frame before being trimmed. + * @param {number} destX - The destination X position of the trimmed frame for display. + * @param {number} destY - The destination Y position of the trimmed frame for display. + * @param {number} destWidth - The destination width of the trimmed frame for display. + * @param {number} destHeight - The destination height of the trimmed frame for display. + */ setTrim: function (trimmed, actualWidth, actualHeight, destX, destY, destWidth, destHeight) { - this.trimmed = trimmed; if (trimmed) @@ -179,7 +174,6 @@ Phaser.Frame.prototype = { this.spriteSourceSizeW = destWidth; this.spriteSourceSizeH = destHeight; } - }, /** @@ -191,7 +185,6 @@ Phaser.Frame.prototype = { */ clone: function () { - var output = new Phaser.Frame(this.index, this.x, this.y, this.width, this.height, this.name); for (var prop in this) @@ -203,19 +196,17 @@ Phaser.Frame.prototype = { } return output; - }, /** - * Returns a Rectangle set to the dimensions of this Frame. - * - * @method Phaser.Frame#getRect - * @param {Phaser.Rectangle} [out] - A rectangle to copy the frame dimensions to. - * @return {Phaser.Rectangle} A rectangle. - */ + * Returns a Rectangle set to the dimensions of this Frame. + * + * @method Phaser.Frame#getRect + * @param {Phaser.Rectangle} [out] - A rectangle to copy the frame dimensions to. + * @return {Phaser.Rectangle} A rectangle. + */ getRect: function (out) { - if (out === undefined) { out = new Phaser.Rectangle(this.x, this.y, this.width, this.height); @@ -226,7 +217,6 @@ Phaser.Frame.prototype = { } return out; - } }; diff --git a/src/animation/FrameData.js b/src/animation/FrameData.js index f2be74a26..e22722c56 100644 --- a/src/animation/FrameData.js +++ b/src/animation/FrameData.js @@ -1,44 +1,41 @@ /** -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* FrameData is a container for Frame objects, which are the internal representation of animation data in Phaser. -* -* @class Phaser.FrameData -* @constructor -*/ + * FrameData is a container for Frame objects, which are the internal representation of animation data in Phaser. + * + * @class Phaser.FrameData + * @constructor + */ Phaser.FrameData = function () { - /** - * @property {Array} _frames - Local array of frames. - * @private - */ + * @property {Array} _frames - Local array of frames. + * @private + */ this._frames = []; /** - * @property {Array} _frameNames - Local array of frame names for name to index conversions. - * @private - */ + * @property {Array} _frameNames - Local array of frame names for name to index conversions. + * @private + */ this._frameNames = []; - }; Phaser.FrameData.prototype = { /** - * Adds a new Frame to this FrameData collection. Typically called by the Animation.Parser and not directly. - * - * @method Phaser.FrameData#addFrame - * @param {Phaser.Frame} frame - The frame to add to this FrameData set. - * @return {Phaser.Frame} The frame that was just added. - */ + * Adds a new Frame to this FrameData collection. Typically called by the Animation.Parser and not directly. + * + * @method Phaser.FrameData#addFrame + * @param {Phaser.Frame} frame - The frame to add to this FrameData set. + * @return {Phaser.Frame} The frame that was just added. + */ addFrame: function (frame) { - frame.index = this._frames.length; this._frames.push(frame); @@ -49,64 +46,57 @@ Phaser.FrameData.prototype = { } return frame; - }, /** - * Get a Frame by its numerical index. - * - * @method Phaser.FrameData#getFrame - * @param {number} index - The index of the frame you want to get. - * @return {Phaser.Frame} The frame, if found, or undefined. - */ + * Get a Frame by its numerical index. + * + * @method Phaser.FrameData#getFrame + * @param {number} index - The index of the frame you want to get. + * @return {Phaser.Frame} The frame, if found, or undefined. + */ getFrame: function (index) { - if (index >= this._frames.length) { index = 0; } return this._frames[index]; - }, /** - * Get a Frame by its frame name. - * - * @method Phaser.FrameData#getFrameByName - * @param {string} name - The name of the frame you want to get. - * @return {Phaser.Frame} The frame, if found, or null. - */ + * Get a Frame by its frame name. + * + * @method Phaser.FrameData#getFrameByName + * @param {string} name - The name of the frame you want to get. + * @return {Phaser.Frame} The frame, if found, or null. + */ getFrameByName: function (name) { - if (typeof this._frameNames[name] === 'number') { return this._frames[this._frameNames[name]]; } return null; - }, /** - * Check if there is a Frame with the given name. - * - * @method Phaser.FrameData#checkFrameName - * @param {string} name - The name of the frame you want to check. - * @return {boolean} True if the frame is found, otherwise false. - */ + * Check if there is a Frame with the given name. + * + * @method Phaser.FrameData#checkFrameName + * @param {string} name - The name of the frame you want to check. + * @return {boolean} True if the frame is found, otherwise false. + */ checkFrameName: function (name) { - if (this._frameNames[name] == null) { return false; } return true; - }, /** @@ -117,7 +107,6 @@ Phaser.FrameData.prototype = { */ clone: function () { - var output = new Phaser.FrameData(); // No input array, so we loop through all frames @@ -135,21 +124,19 @@ Phaser.FrameData.prototype = { } return output; - }, /** - * Returns a range of frames based on the given start and end frame indexes and returns them in an Array. - * - * @method Phaser.FrameData#getFrameRange - * @param {number} start - The starting frame index. - * @param {number} end - The ending frame index. - * @param {Array} [output] - If given the results will be appended to the end of this array otherwise a new array will be created. - * @return {Array} An array of Frames between the start and end index values, or an empty array if none were found. - */ + * Returns a range of frames based on the given start and end frame indexes and returns them in an Array. + * + * @method Phaser.FrameData#getFrameRange + * @param {number} start - The starting frame index. + * @param {number} end - The ending frame index. + * @param {Array} [output] - If given the results will be appended to the end of this array otherwise a new array will be created. + * @return {Array} An array of Frames between the start and end index values, or an empty array if none were found. + */ getFrameRange: function (start, end, output) { - if (output === undefined) { output = []; } for (var i = start; i <= end; i++) @@ -158,22 +145,20 @@ Phaser.FrameData.prototype = { } return output; - }, /** - * Returns all of the Frames in this FrameData set where the frame index is found in the input array. - * The frames are returned in the output array, or if none is provided in a new Array object. - * - * @method Phaser.FrameData#getFrames - * @param {Array} [frames] - An Array containing the indexes of the frames to retrieve. If the array is empty or undefined then all frames in the FrameData are returned. - * @param {boolean} [useNumericIndex=true] - Are the given frames using numeric indexes (default) or strings? (false) - * @param {Array} [output] - If given the results will be appended to the end of this array otherwise a new array will be created. - * @return {Array} An array of all Frames in this FrameData set matching the given names or IDs. - */ + * Returns all of the Frames in this FrameData set where the frame index is found in the input array. + * The frames are returned in the output array, or if none is provided in a new Array object. + * + * @method Phaser.FrameData#getFrames + * @param {Array} [frames] - An Array containing the indexes of the frames to retrieve. If the array is empty or undefined then all frames in the FrameData are returned. + * @param {boolean} [useNumericIndex=true] - Are the given frames using numeric indexes (default) or strings? (false) + * @param {Array} [output] - If given the results will be appended to the end of this array otherwise a new array will be created. + * @return {Array} An array of all Frames in this FrameData set matching the given names or IDs. + */ getFrames: function (frames, useNumericIndex, output) { - if (useNumericIndex === undefined) { useNumericIndex = true; } if (output === undefined) { output = []; } @@ -206,22 +191,20 @@ Phaser.FrameData.prototype = { } return output; - }, /** - * Returns all of the Frame indexes in this FrameData set. - * The frames indexes are returned in the output array, or if none is provided in a new Array object. - * - * @method Phaser.FrameData#getFrameIndexes - * @param {Array} [frames] - An Array containing the indexes of the frames to retrieve. If undefined or the array is empty then all frames in the FrameData are returned. - * @param {boolean} [useNumericIndex=true] - Are the given frames using numeric indexes (default) or strings? (false) - * @param {Array} [output] - If given the results will be appended to the end of this array otherwise a new array will be created. - * @return {Array} An array of all Frame indexes matching the given names or IDs. - */ + * Returns all of the Frame indexes in this FrameData set. + * The frames indexes are returned in the output array, or if none is provided in a new Array object. + * + * @method Phaser.FrameData#getFrameIndexes + * @param {Array} [frames] - An Array containing the indexes of the frames to retrieve. If undefined or the array is empty then all frames in the FrameData are returned. + * @param {boolean} [useNumericIndex=true] - Are the given frames using numeric indexes (default) or strings? (false) + * @param {Array} [output] - If given the results will be appended to the end of this array otherwise a new array will be created. + * @return {Array} An array of all Frame indexes matching the given names or IDs. + */ getFrameIndexes: function (frames, useNumericIndex, output) { - if (useNumericIndex === undefined) { useNumericIndex = true; } if (output === undefined) { output = []; } @@ -252,20 +235,17 @@ Phaser.FrameData.prototype = { } return output; - }, /** - * Destroys this FrameData collection by nulling the _frames and _frameNames arrays. - * - * @method Phaser.FrameData#destroy - */ + * Destroys this FrameData collection by nulling the _frames and _frameNames arrays. + * + * @method Phaser.FrameData#destroy + */ destroy: function () { - this._frames = null; this._frameNames = null; - } }; @@ -273,10 +253,10 @@ Phaser.FrameData.prototype = { Phaser.FrameData.prototype.constructor = Phaser.FrameData; /** -* @name Phaser.FrameData#total -* @property {number} total - The total number of frames in this FrameData set. -* @readonly -*/ + * @name Phaser.FrameData#total + * @property {number} total - The total number of frames in this FrameData set. + * @readonly + */ Object.defineProperty(Phaser.FrameData.prototype, 'total', { get: function () diff --git a/src/core/Camera.js b/src/core/Camera.js index c1bcacd2f..a1d2be965 100644 --- a/src/core/Camera.js +++ b/src/core/Camera.js @@ -1,164 +1,163 @@ /** -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* A Camera is your view into the game world. It has a position and size and renders only those objects within its field of view. -* The game automatically creates a single Stage sized camera on boot. Move the camera around the world with Phaser.Camera.x/y -* -* @class Phaser.Camera -* @constructor -* @param {Phaser.Game} game - Game reference to the currently running game. -* @param {number} id - Not being used at the moment, will be when Phaser supports multiple camera -* @param {number} x - Position of the camera on the X axis -* @param {number} y - Position of the camera on the Y axis -* @param {number} width - The width of the view rectangle -* @param {number} height - The height of the view rectangle -*/ + * A Camera is your view into the game world. It has a position and size and renders only those objects within its field of view. + * The game automatically creates a single Stage sized camera on boot. Move the camera around the world with Phaser.Camera.x/y + * + * @class Phaser.Camera + * @constructor + * @param {Phaser.Game} game - Game reference to the currently running game. + * @param {number} id - Not being used at the moment, will be when Phaser supports multiple camera + * @param {number} x - Position of the camera on the X axis + * @param {number} y - Position of the camera on the Y axis + * @param {number} width - The width of the view rectangle + * @param {number} height - The height of the view rectangle + */ Phaser.Camera = function (game, id, x, y, width, height) { - /** - * @property {Phaser.Game} game - A reference to the currently running Game. - */ + * @property {Phaser.Game} game - A reference to the currently running Game. + */ this.game = game; /** - * @property {Phaser.World} world - A reference to the game world. - */ + * @property {Phaser.World} world - A reference to the game world. + */ this.world = game.world; /** - * @property {number} id - Reserved for future multiple camera set-ups. - * @default - */ + * @property {number} id - Reserved for future multiple camera set-ups. + * @default + */ this.id = 0; /** - * Camera view. - * The view into the world we wish to render (by default the game dimensions). - * The x/y values are in world coordinates, not screen coordinates, the width/height is how many pixels to render. - * Sprites outside of this view are not rendered if Sprite.autoCull is set to `true`. Otherwise they are always rendered. - * @property {Phaser.Rectangle} view - */ + * Camera view. + * The view into the world we wish to render (by default the game dimensions). + * The x/y values are in world coordinates, not screen coordinates, the width/height is how many pixels to render. + * Sprites outside of this view are not rendered if Sprite.autoCull is set to `true`. Otherwise they are always rendered. + * @property {Phaser.Rectangle} view + */ this.view = new Phaser.Rectangle(x, y, width, height); /** - * The Camera is bound to this Rectangle and cannot move outside of it. By default it is enabled and set to the size of the World. - * The Rectangle can be located anywhere in the world and updated as often as you like. If you don't wish the Camera to be bound - * at all then set this to null. The values can be anything and are in World coordinates, with 0,0 being the top-left of the world. - * - * @property {Phaser.Rectangle} bounds - The Rectangle in which the Camera is bounded. Set to null to allow for movement anywhere. - */ + * The Camera is bound to this Rectangle and cannot move outside of it. By default it is enabled and set to the size of the World. + * The Rectangle can be located anywhere in the world and updated as often as you like. If you don't wish the Camera to be bound + * at all then set this to null. The values can be anything and are in World coordinates, with 0,0 being the top-left of the world. + * + * @property {Phaser.Rectangle} bounds - The Rectangle in which the Camera is bounded. Set to null to allow for movement anywhere. + */ this.bounds = new Phaser.Rectangle(x, y, width, height); /** - * @property {Phaser.Rectangle} deadzone - Moving inside this Rectangle will not cause the camera to move. - */ + * @property {Phaser.Rectangle} deadzone - Moving inside this Rectangle will not cause the camera to move. + */ this.deadzone = null; /** - * @property {boolean} visible - Whether this camera is visible or not. - * @default - */ + * @property {boolean} visible - Whether this camera is visible or not. + * @default + */ this.visible = true; /** - * @property {boolean} roundPx - If a Camera has roundPx set to `true` it will call `view.floor` as part of its update loop, keeping its boundary to integer values. Set this to `false` to disable this from happening. - * @default - */ + * @property {boolean} roundPx - If a Camera has roundPx set to `true` it will call `view.floor` as part of its update loop, keeping its boundary to integer values. Set this to `false` to disable this from happening. + * @default + */ this.roundPx = true; /** - * @property {boolean} atLimit - Whether this camera is flush with the World Bounds or not. - */ + * @property {boolean} atLimit - Whether this camera is flush with the World Bounds or not. + */ this.atLimit = { x: false, y: false }; /** - * @property {Phaser.Sprite} target - If the camera is tracking a Sprite, this is a reference to it, otherwise null. - * @default - */ + * @property {Phaser.Sprite} target - If the camera is tracking a Sprite, this is a reference to it, otherwise null. + * @default + */ this.target = null; /** - * @property {PIXI.DisplayObject} displayObject - The display object to which all game objects are added. Set by World.boot. - */ + * @property {PIXI.DisplayObject} displayObject - The display object to which all game objects are added. Set by World.boot. + */ this.displayObject = null; /** - * @property {Phaser.Point} scale - The scale of the display object to which all game objects are added. Set by World.boot. - */ + * @property {Phaser.Point} scale - The scale of the display object to which all game objects are added. Set by World.boot. + */ this.scale = null; /** - * @property {number} totalInView - The total number of Sprites with `autoCull` set to `true` that are visible by this Camera. - * @readonly - */ + * @property {number} totalInView - The total number of Sprites with `autoCull` set to `true` that are visible by this Camera. + * @readonly + */ this.totalInView = 0; /** - * The linear interpolation value to use when following a target. - * The default values of 1 means the camera will instantly snap to the target coordinates. - * A lower value, such as 0.1 means the camera will more slowly track the target, giving - * a smooth transition. You can set the horizontal and vertical values independently, and also - * adjust this value in real-time during your game. - * @property {Phaser.Point} lerp - * @default - */ + * The linear interpolation value to use when following a target. + * The default values of 1 means the camera will instantly snap to the target coordinates. + * A lower value, such as 0.1 means the camera will more slowly track the target, giving + * a smooth transition. You can set the horizontal and vertical values independently, and also + * adjust this value in real-time during your game. + * @property {Phaser.Point} lerp + * @default + */ this.lerp = new Phaser.Point(1, 1); /** - * @property {Phaser.Signal} onShakeComplete - This signal is dispatched when the camera shake effect completes. - */ + * @property {Phaser.Signal} onShakeComplete - This signal is dispatched when the camera shake effect completes. + */ this.onShakeComplete = new Phaser.Signal(); /** - * @property {Phaser.Signal} onFlashComplete - This signal is dispatched when the camera flash effect completes. - */ + * @property {Phaser.Signal} onFlashComplete - This signal is dispatched when the camera flash effect completes. + */ this.onFlashComplete = new Phaser.Signal(); /** - * This signal is dispatched when the camera fade effect completes. - * When the fade effect completes you will be left with the screen black (or whatever - * color you faded to). In order to reset this call `Camera.resetFX`. This is called - * automatically when you change State. - * @property {Phaser.Signal} onFadeComplete - */ + * This signal is dispatched when the camera fade effect completes. + * When the fade effect completes you will be left with the screen black (or whatever + * color you faded to). In order to reset this call `Camera.resetFX`. This is called + * automatically when you change State. + * @property {Phaser.Signal} onFadeComplete + */ this.onFadeComplete = new Phaser.Signal(); /** - * The Graphics object used to handle camera fx such as fade and flash. - * @property {Phaser.Graphics} fx - * @protected - */ + * The Graphics object used to handle camera fx such as fade and flash. + * @property {Phaser.Graphics} fx + * @protected + */ this.fx = null; /** - * @property {Phaser.Point} _targetPosition - Internal point used to calculate target position. - * @private - */ + * @property {Phaser.Point} _targetPosition - Internal point used to calculate target position. + * @private + */ this._targetPosition = new Phaser.Point(); /** - * @property {number} edge - Edge property. - * @private - * @default - */ + * @property {number} edge - Edge property. + * @private + * @default + */ this._edge = 0; /** - * @property {Phaser.Point} position - Current position of the camera in world. - * @private - * @default - */ + * @property {Phaser.Point} position - Current position of the camera in world. + * @private + * @default + */ this._position = new Phaser.Point(); /** - * @property {Object} _shake - The shake effect container. - * @private - */ + * @property {Object} _shake - The shake effect container. + * @private + */ this._shake = { intensity: 0, duration: 0, @@ -170,92 +169,90 @@ Phaser.Camera = function (game, id, x, y, width, height) }; /** - * @property {number} _fxDuration - FX duration timer. - * @private - */ + * @property {number} _fxDuration - FX duration timer. + * @private + */ this._fxDuration = 0; /** - * @property {number} _fxType - The FX type running. - * @private - */ + * @property {number} _fxType - The FX type running. + * @private + */ this._fxType = 0; /** - * @property {Phaser.Rectangle} - * @private - */ + * @property {Phaser.Rectangle} + * @private + */ this._fixedView = new Phaser.Rectangle(); - }; /** -* A follow style that uses no deadzone. -* -* @constant -* @type {number} -*/ + * A follow style that uses no deadzone. + * + * @constant + * @type {number} + */ Phaser.Camera.FOLLOW_LOCKON = 0; /** -* A follow style that uses a tall, narrow deadzone (0.33 x 0.125) with a center slightly above the view center. -* -* @constant -* @type {number} -*/ + * A follow style that uses a tall, narrow deadzone (0.33 x 0.125) with a center slightly above the view center. + * + * @constant + * @type {number} + */ Phaser.Camera.FOLLOW_PLATFORMER = 1; /** -* A follow style that uses a square deadzone (0.25 of the larger view edge). -* -* @constant -* @type {number} -*/ + * A follow style that uses a square deadzone (0.25 of the larger view edge). + * + * @constant + * @type {number} + */ Phaser.Camera.FOLLOW_TOPDOWN = 2; /** -* A follow style that uses a small square deadzone (0.125 of the larger view edge). -* -* @constant -* @type {number} -*/ + * A follow style that uses a small square deadzone (0.125 of the larger view edge). + * + * @constant + * @type {number} + */ Phaser.Camera.FOLLOW_TOPDOWN_TIGHT = 3; /** -* @constant -* @type {number} -*/ + * @constant + * @type {number} + */ Phaser.Camera.SHAKE_BOTH = 4; /** -* @constant -* @type {number} -*/ + * @constant + * @type {number} + */ Phaser.Camera.SHAKE_HORIZONTAL = 5; /** -* @constant -* @type {number} -*/ + * @constant + * @type {number} + */ Phaser.Camera.SHAKE_VERTICAL = 6; /** -* @constant -* @type {boolean} -*/ + * @constant + * @type {boolean} + */ Phaser.Camera.ENABLE_FX = true; Phaser.Camera.prototype = { /** - * Called automatically by Phaser.World. - * - * @method Phaser.Camera#boot - * @private - */ + * Called automatically by Phaser.World. + * + * @method Phaser.Camera#boot + * @private + */ boot: function () { - this.displayObject = this.game.world; this.scale = this.game.world.scale; @@ -268,39 +265,35 @@ Phaser.Camera.prototype = { this.game.stage.addChild(this.fx); } - }, /** - * Camera preUpdate. Sets the total view counter to zero. - * - * @method Phaser.Camera#preUpdate - */ + * Camera preUpdate. Sets the total view counter to zero. + * + * @method Phaser.Camera#preUpdate + */ preUpdate: function () { - this.totalInView = 0; - }, /** - * Tell the camera which sprite to follow. - * - * You can set the follow type and a linear interpolation value. - * Use low lerp values (such as 0.1) to automatically smooth the camera motion. - * - * If you find you're getting a slight "jitter" effect when following a Sprite it's probably to do with sub-pixel rendering of the Sprite position. - * This can be disabled by setting `game.renderer.renderSession.roundPixels = true` to force full pixel rendering. - * - * @method Phaser.Camera#follow - * @param {Phaser.Sprite|Phaser.Image|Phaser.Text} target - The object you want the camera to track. Set to null to not follow anything. - * @param {number} [style] - Leverage one of the existing {@link deadzone} presets. If you use a custom deadzone, ignore this parameter and manually specify the deadzone after calling follow(). - * @param {float} [lerpX=1] - A value between 0 and 1. This value specifies the amount of linear interpolation to use when horizontally tracking the target. The closer the value to 1, the faster the camera will track. - * @param {float} [lerpY=1] - A value between 0 and 1. This value specifies the amount of linear interpolation to use when vertically tracking the target. The closer the value to 1, the faster the camera will track. - */ + * Tell the camera which sprite to follow. + * + * You can set the follow type and a linear interpolation value. + * Use low lerp values (such as 0.1) to automatically smooth the camera motion. + * + * If you find you're getting a slight "jitter" effect when following a Sprite it's probably to do with sub-pixel rendering of the Sprite position. + * This can be disabled by setting `game.renderer.renderSession.roundPixels = true` to force full pixel rendering. + * + * @method Phaser.Camera#follow + * @param {Phaser.Sprite|Phaser.Image|Phaser.Text} target - The object you want the camera to track. Set to null to not follow anything. + * @param {number} [style] - Leverage one of the existing {@link deadzone} presets. If you use a custom deadzone, ignore this parameter and manually specify the deadzone after calling follow(). + * @param {float} [lerpX=1] - A value between 0 and 1. This value specifies the amount of linear interpolation to use when horizontally tracking the target. The closer the value to 1, the faster the camera will track. + * @param {float} [lerpY=1] - A value between 0 and 1. This value specifies the amount of linear interpolation to use when vertically tracking the target. The closer the value to 1, the faster the camera will track. + */ follow: function (target, style, lerpX, lerpY) { - if (style === undefined) { style = Phaser.Camera.FOLLOW_LOCKON; } if (lerpX === undefined) { lerpX = 1; } if (lerpY === undefined) { lerpY = 1; } @@ -312,7 +305,6 @@ Phaser.Camera.prototype = { switch (style) { - case Phaser.Camera.FOLLOW_PLATFORMER: var w = this.width / 8; var h = this.height / 3; @@ -337,64 +329,56 @@ Phaser.Camera.prototype = { this.deadzone = null; break; } - }, /** - * Sets the Camera follow target to null, stopping it from following an object if it's doing so. - * - * @method Phaser.Camera#unfollow - */ + * Sets the Camera follow target to null, stopping it from following an object if it's doing so. + * + * @method Phaser.Camera#unfollow + */ unfollow: function () { - this.target = null; - }, /** - * Move the camera focus on a display object instantly. - * @method Phaser.Camera#focusOn - * @param {any} displayObject - The display object to focus the camera on. Must have visible x/y properties. - */ + * Move the camera focus on a display object instantly. + * @method Phaser.Camera#focusOn + * @param {any} displayObject - The display object to focus the camera on. Must have visible x/y properties. + */ focusOn: function (displayObject) { - this.setPosition(Math.round(displayObject.x - this.view.halfWidth), Math.round(displayObject.y - this.view.halfHeight)); - }, /** - * Move the camera focus on a location instantly. - * @method Phaser.Camera#focusOnXY - * @param {number} x - X position. - * @param {number} y - Y position. - */ + * Move the camera focus on a location instantly. + * @method Phaser.Camera#focusOnXY + * @param {number} x - X position. + * @param {number} y - Y position. + */ focusOnXY: function (x, y) { - this.setPosition(Math.round(x - this.view.halfWidth), Math.round(y - this.view.halfHeight)); - }, /** - * This creates a camera shake effect. It works by applying a random amount of additional - * spacing on the x and y axis each frame. You can control the intensity and duration - * of the effect, and if it should effect both axis or just one. - * - * When the shake effect ends the signal Camera.onShakeComplete is dispatched. - * - * @method Phaser.Camera#shake - * @param {float} [intensity=0.05] - The intensity of the camera shake. Given as a percentage of the camera size representing the maximum distance that the camera can move while shaking. - * @param {number} [duration=500] - The duration of the shake effect in milliseconds. - * @param {boolean} [force=true] - If a camera shake effect is already running and force is true it will replace the previous effect, resetting the duration. - * @param {number} [direction=Phaser.Camera.SHAKE_BOTH] - The directions in which the camera can shake. Either Phaser.Camera.SHAKE_BOTH, Phaser.Camera.SHAKE_HORIZONTAL or Phaser.Camera.SHAKE_VERTICAL. - * @param {boolean} [shakeBounds=true] - Is the effect allowed to shake the camera beyond its bounds (if set?). - * @return {boolean} True if the shake effect was started, otherwise false. - */ + * This creates a camera shake effect. It works by applying a random amount of additional + * spacing on the x and y axis each frame. You can control the intensity and duration + * of the effect, and if it should effect both axis or just one. + * + * When the shake effect ends the signal Camera.onShakeComplete is dispatched. + * + * @method Phaser.Camera#shake + * @param {float} [intensity=0.05] - The intensity of the camera shake. Given as a percentage of the camera size representing the maximum distance that the camera can move while shaking. + * @param {number} [duration=500] - The duration of the shake effect in milliseconds. + * @param {boolean} [force=true] - If a camera shake effect is already running and force is true it will replace the previous effect, resetting the duration. + * @param {number} [direction=Phaser.Camera.SHAKE_BOTH] - The directions in which the camera can shake. Either Phaser.Camera.SHAKE_BOTH, Phaser.Camera.SHAKE_HORIZONTAL or Phaser.Camera.SHAKE_VERTICAL. + * @param {boolean} [shakeBounds=true] - Is the effect allowed to shake the camera beyond its bounds (if set?). + * @return {boolean} True if the shake effect was started, otherwise false. + */ shake: function (intensity, duration, force, direction, shakeBounds) { - if (intensity === undefined) { intensity = 0.05; } if (duration === undefined) { duration = 500; } if (force === undefined) { force = true; } @@ -418,27 +402,25 @@ Phaser.Camera.prototype = { this._shake.vertical = (direction === Phaser.Camera.SHAKE_BOTH || direction === Phaser.Camera.SHAKE_VERTICAL); return true; - }, /** - * This creates a camera flash effect. It works by filling the game with the solid fill - * color specified, and then fading it away to alpha 0 over the duration given. - * - * You can use this for things such as hit feedback effects. - * - * When the effect ends the signal Camera.onFlashComplete is dispatched. - * - * @method Phaser.Camera#flash - * @param {numer} [color=0xffffff] - The color of the flash effect. I.e. 0xffffff for white, 0xff0000 for red, etc. - * @param {number} [duration=500] - The duration of the flash effect in milliseconds. - * @param {boolean} [force=false] - If a camera flash or fade effect is already running and force is true it will replace the previous effect, resetting the duration. - * @param {numer} [alpha=1] - The alpha value of the color applied to the flash effect. - * @return {boolean} True if the effect was started, otherwise false. - */ + * This creates a camera flash effect. It works by filling the game with the solid fill + * color specified, and then fading it away to alpha 0 over the duration given. + * + * You can use this for things such as hit feedback effects. + * + * When the effect ends the signal Camera.onFlashComplete is dispatched. + * + * @method Phaser.Camera#flash + * @param {numer} [color=0xffffff] - The color of the flash effect. I.e. 0xffffff for white, 0xff0000 for red, etc. + * @param {number} [duration=500] - The duration of the flash effect in milliseconds. + * @param {boolean} [force=false] - If a camera flash or fade effect is already running and force is true it will replace the previous effect, resetting the duration. + * @param {numer} [alpha=1] - The alpha value of the color applied to the flash effect. + * @return {boolean} True if the effect was started, otherwise false. + */ flash: function (color, duration, force, alpha) { - if (color === undefined) { color = 0xffffff; } if (duration === undefined) { duration = 500; } if (force === undefined) { force = false; } @@ -461,32 +443,30 @@ Phaser.Camera.prototype = { this._fxType = 0; return true; - }, /** - * This creates a camera fade effect. It works by filling the game with the - * color specified, over the duration given, ending with a solid fill. - * - * You can use this for things such as transitioning to a new scene. - * - * The game will be left 'filled' at the end of this effect, likely obscuring - * everything. In order to reset it you can call `Camera.resetFX` and it will clear the - * fade. Or you can call `Camera.flash` with the same color as the fade, and it will - * reverse the process, bringing the game back into view again. - * - * When the effect ends the signal Camera.onFadeComplete is dispatched. - * - * @method Phaser.Camera#fade - * @param {numer} [color=0x000000] - The color the game will fade to. I.e. 0x000000 for black, 0xff0000 for red, etc. - * @param {number} [duration=500] - The duration of the fade in milliseconds. - * @param {boolean} [force=false] - If a camera flash or fade effect is already running and force is true it will replace the previous effect, resetting the duration. - * @param {numer} [alpha=1] - The alpha value of the color applied to the fade effect. - * @return {boolean} True if the effect was started, otherwise false. - */ + * This creates a camera fade effect. It works by filling the game with the + * color specified, over the duration given, ending with a solid fill. + * + * You can use this for things such as transitioning to a new scene. + * + * The game will be left 'filled' at the end of this effect, likely obscuring + * everything. In order to reset it you can call `Camera.resetFX` and it will clear the + * fade. Or you can call `Camera.flash` with the same color as the fade, and it will + * reverse the process, bringing the game back into view again. + * + * When the effect ends the signal Camera.onFadeComplete is dispatched. + * + * @method Phaser.Camera#fade + * @param {numer} [color=0x000000] - The color the game will fade to. I.e. 0x000000 for black, 0xff0000 for red, etc. + * @param {number} [duration=500] - The duration of the fade in milliseconds. + * @param {boolean} [force=false] - If a camera flash or fade effect is already running and force is true it will replace the previous effect, resetting the duration. + * @param {numer} [alpha=1] - The alpha value of the color applied to the fade effect. + * @return {boolean} True if the effect was started, otherwise false. + */ fade: function (color, duration, force, alpha) { - if (color === undefined) { color = 0x000000; } if (duration === undefined) { duration = 500; } if (force === undefined) { force = false; } @@ -509,18 +489,16 @@ Phaser.Camera.prototype = { this._fxType = 1; return true; - }, /** - * The camera update loop. This is called automatically by the core game loop. - * - * @method Phaser.Camera#update - * @protected - */ + * The camera update loop. This is called automatically by the core game loop. + * + * @method Phaser.Camera#update + * @protected + */ update: function () { - if (this._fxDuration > 0) { this.updateFX(); @@ -545,18 +523,16 @@ Phaser.Camera.prototype = { this.displayObject.position.x = -this.view.x; this.displayObject.position.y = -this.view.y; - }, /** - * Update the camera flash and fade effects. - * - * @method Phaser.Camera#updateFX - * @private - */ + * Update the camera flash and fade effects. + * + * @method Phaser.Camera#updateFX + * @private + */ updateFX: function () { - if (this._fxType === 0) { // flash @@ -581,18 +557,16 @@ Phaser.Camera.prototype = { this.onFadeComplete.dispatch(); } } - }, /** - * Update the camera shake effect. - * - * @method Phaser.Camera#updateShake - * @private - */ + * Update the camera shake effect. + * + * @method Phaser.Camera#updateShake + * @private + */ updateShake: function () { - this._shake.duration -= this.game.time.elapsedMS; if (this._shake.duration <= 0) @@ -613,18 +587,16 @@ Phaser.Camera.prototype = { this._shake.y = this.game.rnd.frac() * this._shake.intensity * this.view.height * 2 - this._shake.intensity * this.view.height; } } - }, /** - * Internal method that handles tracking a sprite. - * - * @method Phaser.Camera#updateTarget - * @private - */ + * Internal method that handles tracking a sprite. + * + * @method Phaser.Camera#updateTarget + * @private + */ updateTarget: function () { - this._targetPosition.x = this.view.x + this.target.worldPosition.x; this._targetPosition.y = this.view.y + this.target.worldPosition.y; @@ -670,34 +642,30 @@ Phaser.Camera.prototype = { this.displayObject.position.x = -this.view.x; this.displayObject.position.y = -this.view.y; - }, /** - * Update the Camera bounds to match the game world. - * - * @method Phaser.Camera#setBoundsToWorld - */ + * Update the Camera bounds to match the game world. + * + * @method Phaser.Camera#setBoundsToWorld + */ setBoundsToWorld: function () { - if (this.bounds) { this.bounds.copyFrom(this.game.world.bounds); } - }, /** - * Method called to ensure the camera doesn't venture outside of the game world. - * Called automatically by Camera.update. - * - * @method Phaser.Camera#checkBounds - * @protected - */ + * Method called to ensure the camera doesn't venture outside of the game world. + * Called automatically by Camera.update. + * + * @method Phaser.Camera#checkBounds + * @protected + */ checkBounds: function () { - this.atLimit.x = false; this.atLimit.y = false; @@ -752,20 +720,18 @@ Phaser.Camera.prototype = { this._shake.y = 0; } } - }, /** - * A helper function to set both the X and Y properties of the camera at once - * without having to use game.camera.x and game.camera.y. - * - * @method Phaser.Camera#setPosition - * @param {number} x - X position. - * @param {number} y - Y position. - */ + * A helper function to set both the X and Y properties of the camera at once + * without having to use game.camera.x and game.camera.y. + * + * @method Phaser.Camera#setPosition + * @param {number} x - X position. + * @param {number} y - Y position. + */ setPosition: function (x, y) { - this.view.x = x; this.view.y = y; @@ -773,34 +739,30 @@ Phaser.Camera.prototype = { { this.checkBounds(); } - }, /** - * Sets the size of the view rectangle given the width and height in parameters. - * - * @method Phaser.Camera#setSize - * @param {number} width - The desired width. - * @param {number} height - The desired height. - */ + * Sets the size of the view rectangle given the width and height in parameters. + * + * @method Phaser.Camera#setSize + * @param {number} width - The desired width. + * @param {number} height - The desired height. + */ setSize: function (width, height) { - this.view.width = width; this.view.height = height; - }, /** - * Resets the camera back to 0,0 and un-follows any object it may have been tracking. - * Also immediately resets any camera effects that may have been running such as - * shake, flash or fade. - * - * @method Phaser.Camera#reset - */ + * Resets the camera back to 0,0 and un-follows any object it may have been tracking. + * Also immediately resets any camera effects that may have been running such as + * shake, flash or fade. + * + * @method Phaser.Camera#reset + */ reset: function () { - this.target = null; this.view.x = 0; @@ -811,18 +773,16 @@ Phaser.Camera.prototype = { this._shake.y = 0; this.resetFX(); - }, /** - * Resets any active FX, such as a fade or flash and immediately clears it. - * Useful to calling after a fade in order to remove the fade from the Stage. - * - * @method Phaser.Camera#resetFX - */ + * Resets any active FX, such as a fade or flash and immediately clears it. + * Useful to calling after a fade in order to remove the fade from the Stage. + * + * @method Phaser.Camera#resetFX + */ resetFX: function () { - if (this.fx) { this.fx.clear(); @@ -830,7 +790,6 @@ Phaser.Camera.prototype = { } this._fxDuration = 0; - } }; @@ -838,22 +797,19 @@ Phaser.Camera.prototype = { Phaser.Camera.prototype.constructor = Phaser.Camera; /** -* The Cameras x coordinate. This value is automatically clamped if it falls outside of the World bounds. -* @name Phaser.Camera#x -* @property {number} x - Gets or sets the cameras x position. -*/ + * The Cameras x coordinate. This value is automatically clamped if it falls outside of the World bounds. + * @name Phaser.Camera#x + * @property {number} x - Gets or sets the cameras x position. + */ Object.defineProperty(Phaser.Camera.prototype, 'x', { get: function () { - return this.view.x; - }, set: function (value) { - this.view.x = value; if (this.bounds) @@ -865,22 +821,19 @@ Object.defineProperty(Phaser.Camera.prototype, 'x', { }); /** -* The Cameras y coordinate. This value is automatically clamped if it falls outside of the World bounds. -* @name Phaser.Camera#y -* @property {number} y - Gets or sets the cameras y position. -*/ + * The Cameras y coordinate. This value is automatically clamped if it falls outside of the World bounds. + * @name Phaser.Camera#y + * @property {number} y - Gets or sets the cameras y position. + */ Object.defineProperty(Phaser.Camera.prototype, 'y', { get: function () { - return this.view.y; - }, set: function (value) { - this.view.y = value; if (this.bounds) @@ -892,24 +845,21 @@ Object.defineProperty(Phaser.Camera.prototype, 'y', { }); /** -* The Cameras position. This value is automatically clamped if it falls outside of the World bounds. -* @name Phaser.Camera#position -* @property {Phaser.Point} position - Gets or sets the cameras xy position using Phaser.Point object. -*/ + * The Cameras position. This value is automatically clamped if it falls outside of the World bounds. + * @name Phaser.Camera#position + * @property {Phaser.Point} position - Gets or sets the cameras xy position using Phaser.Point object. + */ Object.defineProperty(Phaser.Camera.prototype, 'position', { get: function () { - this._position.set(this.view.x, this.view.y); return this._position; - }, set: function (value) { - if (typeof value.x !== 'undefined') { this.view.x = value.x; } if (typeof value.y !== 'undefined') { this.view.y = value.y; } @@ -922,71 +872,59 @@ Object.defineProperty(Phaser.Camera.prototype, 'position', { }); /** -* The Cameras width. By default this is the same as the Game size and should not be adjusted for now. -* @name Phaser.Camera#width -* @property {number} width - Gets or sets the cameras width. -*/ + * The Cameras width. By default this is the same as the Game size and should not be adjusted for now. + * @name Phaser.Camera#width + * @property {number} width - Gets or sets the cameras width. + */ Object.defineProperty(Phaser.Camera.prototype, 'width', { get: function () { - return this.view.width; - }, set: function (value) { - this.view.width = value; - } }); /** -* The Cameras height. By default this is the same as the Game size and should not be adjusted for now. -* @name Phaser.Camera#height -* @property {number} height - Gets or sets the cameras height. -*/ + * The Cameras height. By default this is the same as the Game size and should not be adjusted for now. + * @name Phaser.Camera#height + * @property {number} height - Gets or sets the cameras height. + */ Object.defineProperty(Phaser.Camera.prototype, 'height', { get: function () { - return this.view.height; - }, set: function (value) { - this.view.height = value; - } }); /** -* The Cameras shake intensity. -* @name Phaser.Camera#shakeIntensity -* @property {number} shakeIntensity - Gets or sets the cameras shake intensity. -*/ + * The Cameras shake intensity. + * @name Phaser.Camera#shakeIntensity + * @property {number} shakeIntensity - Gets or sets the cameras shake intensity. + */ Object.defineProperty(Phaser.Camera.prototype, 'shakeIntensity', { get: function () { - return this._shake.intensity; - }, set: function (value) { - this._shake.intensity = value; - } }); @@ -1002,11 +940,9 @@ Object.defineProperty(Phaser.Camera.prototype, 'fixedView', { get: function () { - this._fixedView.setTo(0, 0, this.view.width, this.view.height); return this._fixedView; - } }); @@ -1021,9 +957,7 @@ Object.defineProperty(Phaser.Camera.prototype, 'centerX', { get: function () { - return (this.x + (0.5 * this.width)); - } }); @@ -1038,9 +972,7 @@ Object.defineProperty(Phaser.Camera.prototype, 'centerY', { get: function () { - return (this.y + (0.5 * this.height)); - } }); diff --git a/src/core/Create.js b/src/core/Create.js index 38ddd9ad0..cf4e37257 100644 --- a/src/core/Create.js +++ b/src/core/Create.js @@ -1,46 +1,45 @@ /** -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* The Phaser.Create class is a collection of smaller helper methods that allow you to generate game content -* quickly and easily, without the need for any external files. You can create textures for sprites and in -* coming releases we'll add dynamic sound effect generation support as well (like sfxr). -* -* Access this via `Game.create` (`this.game.create` from within a State object). -* -* @class Phaser.Create -* @constructor -* @param {Phaser.Game} game - Game reference to the currently running game. + * The Phaser.Create class is a collection of smaller helper methods that allow you to generate game content + * quickly and easily, without the need for any external files. You can create textures for sprites and in + * coming releases we'll add dynamic sound effect generation support as well (like sfxr). + * + * Access this via `Game.create` (`this.game.create` from within a State object). + * + * @class Phaser.Create + * @constructor + * @param {Phaser.Game} game - Game reference to the currently running game. */ Phaser.Create = function (game) { - /** - * @property {Phaser.Game} game - A reference to the currently running Game. - */ + * @property {Phaser.Game} game - A reference to the currently running Game. + */ this.game = game; /** - * @property {Phaser.BitmapData} bmd - The internal BitmapData Create uses to generate textures from. - */ + * @property {Phaser.BitmapData} bmd - The internal BitmapData Create uses to generate textures from. + */ this.bmd = null; /** - * @property {HTMLCanvasElement} canvas - The canvas the BitmapData uses. - */ + * @property {HTMLCanvasElement} canvas - The canvas the BitmapData uses. + */ this.canvas = null; /** - * @property {CanvasRenderingContext2D} context - The 2d context of the canvas. - */ + * @property {CanvasRenderingContext2D} context - The 2d context of the canvas. + */ this.ctx = null; /** - * @property {array} palettes - A range of 16 color palettes for use with sprite generation. - */ + * @property {array} palettes - A range of 16 color palettes for use with sprite generation. + */ this.palettes = [ { 0: '#000', 1: '#9D9D9D', 2: '#FFF', 3: '#BE2633', 4: '#E06F8B', 5: '#493C2B', 6: '#A46422', 7: '#EB8931', 8: '#F7E26B', 9: '#2F484E', A: '#44891A', B: '#A3CE27', C: '#1B2632', D: '#005784', E: '#31A2F2', F: '#B2DCEF' }, { 0: '#000', 1: '#191028', 2: '#46af45', 3: '#a1d685', 4: '#453e78', 5: '#7664fe', 6: '#833129', 7: '#9ec2e8', 8: '#dc534b', 9: '#e18d79', A: '#d6b97b', B: '#e9d8a1', C: '#216c4b', D: '#d365c8', E: '#afaab9', F: '#f5f4eb' }, @@ -48,42 +47,41 @@ Phaser.Create = function (game) { 0: '#000', 1: '#fff', 2: '#8b4131', 3: '#7bbdc5', 4: '#8b41ac', 5: '#6aac41', 6: '#3931a4', 7: '#d5de73', 8: '#945a20', 9: '#5a4100', A: '#bd736a', B: '#525252', C: '#838383', D: '#acee8b', E: '#7b73de', F: '#acacac' }, { 0: '#000', 1: '#191028', 2: '#46af45', 3: '#a1d685', 4: '#453e78', 5: '#7664fe', 6: '#833129', 7: '#9ec2e8', 8: '#dc534b', 9: '#e18d79', A: '#d6b97b', B: '#e9d8a1', C: '#216c4b', D: '#d365c8', E: '#afaab9', F: '#fff' } ]; - }; /** -* A 16 color palette by [Arne](http://androidarts.com/palette/16pal.htm) -* @constant -* @type {number} -*/ + * A 16 color palette by [Arne](http://androidarts.com/palette/16pal.htm) + * @constant + * @type {number} + */ Phaser.Create.PALETTE_ARNE = 0; /** -* A 16 color JMP inspired palette. -* @constant -* @type {number} -*/ + * A 16 color JMP inspired palette. + * @constant + * @type {number} + */ Phaser.Create.PALETTE_JMP = 1; /** -* A 16 color CGA inspired palette. -* @constant -* @type {number} -*/ + * A 16 color CGA inspired palette. + * @constant + * @type {number} + */ Phaser.Create.PALETTE_CGA = 2; /** -* A 16 color C64 inspired palette. -* @constant -* @type {number} -*/ + * A 16 color C64 inspired palette. + * @constant + * @type {number} + */ Phaser.Create.PALETTE_C64 = 3; /** -* A 16 color palette inspired by Japanese computers like the MSX. -* @constant -* @type {number} -*/ + * A 16 color palette inspired by Japanese computers like the MSX. + * @constant + * @type {number} + */ Phaser.Create.PALETTE_JAPANESE_MACHINE = 4; Phaser.Create.prototype = { @@ -126,7 +124,6 @@ Phaser.Create.prototype = { */ texture: function (key, data, pixelWidth, pixelHeight, palette, generateTexture, callback, callbackContext) { - if (pixelWidth === undefined) { pixelWidth = 8; } if (pixelHeight === undefined) { pixelHeight = pixelWidth; } if (palette === undefined) { palette = 0; } @@ -166,7 +163,6 @@ Phaser.Create.prototype = { return generateTexture ? this.bmd.generateTexture(key, callback, callbackContext) : this.copy(); - }, /** @@ -188,7 +184,6 @@ Phaser.Create.prototype = { */ grid: function (key, width, height, cellWidth, cellHeight, color, generateTexture, callback, callbackContext) { - if (generateTexture === undefined) { generateTexture = true; } // No bmd? Let's make one @@ -216,7 +211,6 @@ Phaser.Create.prototype = { return generateTexture ? this.bmd.generateTexture(key, callback, callbackContext) : this.copy(); - }, /** @@ -233,13 +227,11 @@ Phaser.Create.prototype = { */ copy: function (dest, x, y, width, height, blendMode, roundPx) { - if (dest == null) { dest = this.game.make.bitmapData(); } dest.resize(this.bmd.width, this.bmd.height); return dest.draw(this.bmd, x, y, width, height, blendMode, roundPx); - } }; diff --git a/src/core/Filter.js b/src/core/Filter.js index df7821230..1563a31a1 100644 --- a/src/core/Filter.js +++ b/src/core/Filter.js @@ -1,91 +1,90 @@ /** -* @author Richard Davey -* @author Mat Groves (@Doormat23) -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @author Mat Groves (@Doormat23) + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* This is a base Filter class to use for any Phaser filter development. -* If you want to make a custom filter, this should be your base class. -* -* The default uniforms, types and values for all Filters are: -* -* ```javascript -* resolution: { type: '2f', value: { x: 256, y: 256 }} -* time: { type: '1f', value: 0 } -* mouse: { type: '2f', value: { x: 0.0, y: 0.0 } } -* date: { type: '4fv', value: [ d.getFullYear(), d.getMonth(), d.getDate(), d.getHours() *60 * 60 + d.getMinutes() * 60 + d.getSeconds() ] } -* sampleRate: { type: '1f', value: 44100.0 } -* iChannel0: { type: 'sampler2D', value: null, textureData: { repeat: true } } -* iChannel1: { type: 'sampler2D', value: null, textureData: { repeat: true } } -* iChannel2: { type: 'sampler2D', value: null, textureData: { repeat: true } } -* iChannel3: { type: 'sampler2D', value: null, textureData: { repeat: true } } -* ``` -* -* The vast majority of filters (including all of those that ship with Phaser) use fragment shaders, and -* therefore only work in WebGL and are not supported by Canvas at all. -* -* @class Phaser.Filter -* @constructor -* @param {Phaser.Game} game - A reference to the currently running game. -* @param {object} [uniforms] - Uniform mappings object. The uniforms are added on the default uniforms, or replace them if the keys are the same. -* @param {Array|string} [fragmentSrc] - The fragment shader code. Either an array, one element per line of code, or a string. -*/ + * This is a base Filter class to use for any Phaser filter development. + * If you want to make a custom filter, this should be your base class. + * + * The default uniforms, types and values for all Filters are: + * + * ```javascript + * resolution: { type: '2f', value: { x: 256, y: 256 }} + * time: { type: '1f', value: 0 } + * mouse: { type: '2f', value: { x: 0.0, y: 0.0 } } + * date: { type: '4fv', value: [ d.getFullYear(), d.getMonth(), d.getDate(), d.getHours() *60 * 60 + d.getMinutes() * 60 + d.getSeconds() ] } + * sampleRate: { type: '1f', value: 44100.0 } + * iChannel0: { type: 'sampler2D', value: null, textureData: { repeat: true } } + * iChannel1: { type: 'sampler2D', value: null, textureData: { repeat: true } } + * iChannel2: { type: 'sampler2D', value: null, textureData: { repeat: true } } + * iChannel3: { type: 'sampler2D', value: null, textureData: { repeat: true } } + * ``` + * + * The vast majority of filters (including all of those that ship with Phaser) use fragment shaders, and + * therefore only work in WebGL and are not supported by Canvas at all. + * + * @class Phaser.Filter + * @constructor + * @param {Phaser.Game} game - A reference to the currently running game. + * @param {object} [uniforms] - Uniform mappings object. The uniforms are added on the default uniforms, or replace them if the keys are the same. + * @param {Array|string} [fragmentSrc] - The fragment shader code. Either an array, one element per line of code, or a string. + */ Phaser.Filter = function (game, uniforms, fragmentSrc) { - /** - * @property {Phaser.Game} game - A reference to the currently running game. - */ + * @property {Phaser.Game} game - A reference to the currently running game. + */ this.game = game; /** - * @property {number} type - The const type of this object, either Phaser.WEBGL_FILTER or Phaser.CANVAS_FILTER. - * @default - */ + * @property {number} type - The const type of this object, either Phaser.WEBGL_FILTER or Phaser.CANVAS_FILTER. + * @default + */ this.type = Phaser.WEBGL_FILTER; /** - * An array of passes - some filters contain a few steps this array simply stores the steps in a linear fashion. - * For example the blur filter has two passes blurX and blurY. - * @property {array} passes - An array of filter objects. - * @private - */ + * An array of passes - some filters contain a few steps this array simply stores the steps in a linear fashion. + * For example the blur filter has two passes blurX and blurY. + * @property {array} passes - An array of filter objects. + * @private + */ this.passes = [ this ]; /** - * @property {array} shaders - Array an array of shaders. - * @private - */ + * @property {array} shaders - Array an array of shaders. + * @private + */ this.shaders = []; /** - * @property {boolean} dirty - Internal PIXI var. - * @default - */ + * @property {boolean} dirty - Internal PIXI var. + * @default + */ this.dirty = true; /** - * @property {number} padding - Internal PIXI var. - * @default - */ + * @property {number} padding - Internal PIXI var. + * @default + */ this.padding = 0; /** - * @property {Phaser.Point} prevPoint - The previous position of the pointer (we don't update the uniform if the same) - */ + * @property {Phaser.Point} prevPoint - The previous position of the pointer (we don't update the uniform if the same) + */ this.prevPoint = new Phaser.Point(); /* - * The supported types are: 1f, 1fv, 1i, 2f, 2fv, 2i, 2iv, 3f, 3fv, 3i, 3iv, 4f, 4fv, 4i, 4iv, mat2, mat3, mat4 and sampler2D. - */ + * The supported types are: 1f, 1fv, 1i, 2f, 2fv, 2i, 2iv, 3f, 3fv, 3i, 3iv, 4f, 4fv, 4i, 4iv, mat2, mat3, mat4 and sampler2D. + */ var d = new Date(); /** - * @property {object} uniforms - Default uniform mappings. Compatible with ShaderToy and GLSLSandbox. - */ + * @property {object} uniforms - Default uniform mappings. Compatible with ShaderToy and GLSLSandbox. + */ this.uniforms = { resolution: { type: '2f', value: { x: 256, y: 256 }}, @@ -116,19 +115,18 @@ Phaser.Filter = function (game, uniforms, fragmentSrc) } /** - * @property {array|string} fragmentSrc - The fragment shader code. - */ + * @property {array|string} fragmentSrc - The fragment shader code. + */ this.fragmentSrc = fragmentSrc || []; - }; Phaser.Filter.prototype = { /** - * This should be over-ridden. Will receive a variable number of arguments. - * - * @method Phaser.Filter#init - */ + * This should be over-ridden. Will receive a variable number of arguments. + * + * @method Phaser.Filter#init + */ init: function () { @@ -137,29 +135,26 @@ Phaser.Filter.prototype = { }, /** - * Set the resolution uniforms on the filter. - * - * @method Phaser.Filter#setResolution - * @param {number} width - The width of the display. - * @param {number} height - The height of the display. - */ + * Set the resolution uniforms on the filter. + * + * @method Phaser.Filter#setResolution + * @param {number} width - The width of the display. + * @param {number} height - The height of the display. + */ setResolution: function (width, height) { - this.uniforms.resolution.value.x = width; this.uniforms.resolution.value.y = height; - }, /** - * Updates the filter. - * - * @method Phaser.Filter#update - * @param {Phaser.Pointer} [pointer] - A Pointer object to use for the filter. The coordinates are mapped to the mouse uniform. - */ + * Updates the filter. + * + * @method Phaser.Filter#update + * @param {Phaser.Pointer} [pointer] - A Pointer object to use for the filter. The coordinates are mapped to the mouse uniform. + */ update: function (pointer) { - if (pointer) { var x = pointer.x / this.game.width; @@ -174,30 +169,28 @@ Phaser.Filter.prototype = { } this.uniforms.time.value = this.game.time.totalElapsedSeconds(); - }, /** - * Creates a new Phaser.Image object using a blank texture and assigns - * this Filter to it. The image is then added to the world. - * - * If you don't provide width and height values then Filter.width and Filter.height are used. - * - * If you do provide width and height values then this filter will be resized to match those - * values. - * - * @method Phaser.Filter#addToWorld - * @param {number} [x=0] - The x coordinate to place the Image at. - * @param {number} [y=0] - The y coordinate to place the Image at. - * @param {number} [width] - The width of the Image. If not specified (or null) it will use Filter.width. If specified Filter.width will be set to this value. - * @param {number} [height] - The height of the Image. If not specified (or null) it will use Filter.height. If specified Filter.height will be set to this value. - * @param {number} [anchorX=0] - Set the x anchor point of the Image. A value between 0 and 1, where 0 is the top-left and 1 is bottom-right. - * @param {number} [anchorY=0] - Set the y anchor point of the Image. A value between 0 and 1, where 0 is the top-left and 1 is bottom-right. - * @return {Phaser.Image} The newly added Image object. - */ + * Creates a new Phaser.Image object using a blank texture and assigns + * this Filter to it. The image is then added to the world. + * + * If you don't provide width and height values then Filter.width and Filter.height are used. + * + * If you do provide width and height values then this filter will be resized to match those + * values. + * + * @method Phaser.Filter#addToWorld + * @param {number} [x=0] - The x coordinate to place the Image at. + * @param {number} [y=0] - The y coordinate to place the Image at. + * @param {number} [width] - The width of the Image. If not specified (or null) it will use Filter.width. If specified Filter.width will be set to this value. + * @param {number} [height] - The height of the Image. If not specified (or null) it will use Filter.height. If specified Filter.height will be set to this value. + * @param {number} [anchorX=0] - Set the x anchor point of the Image. A value between 0 and 1, where 0 is the top-left and 1 is bottom-right. + * @param {number} [anchorY=0] - Set the y anchor point of the Image. A value between 0 and 1, where 0 is the top-left and 1 is bottom-right. + * @return {Phaser.Image} The newly added Image object. + */ addToWorld: function (x, y, width, height, anchorX, anchorY) { - if (anchorX === undefined) { anchorX = 0; } if (anchorY === undefined) { anchorY = 0; } @@ -229,32 +222,28 @@ Phaser.Filter.prototype = { image.filters = [ this ]; return image; - }, /** - * Syncs the uniforms between the class object and the shaders. - * - * @method Phaser.Filter#syncUniforms - */ + * Syncs the uniforms between the class object and the shaders. + * + * @method Phaser.Filter#syncUniforms + */ syncUniforms: function () { - for (var i = 0; i < this.shaders.length; i++) { this.shaders[i].dirty = true; } - }, /** - * Clear down this Filter and null out references to game. - * - * @method Phaser.Filter#destroy - */ + * Clear down this Filter and null out references to game. + * + * @method Phaser.Filter#destroy + */ destroy: function () { - this.passes.length = 0; this.shaders.length = 0; this.fragmentSrc.length = 0; @@ -262,7 +251,6 @@ Phaser.Filter.prototype = { this.game = null; this.uniforms = null; this.prevPoint = null; - } }; @@ -270,45 +258,37 @@ Phaser.Filter.prototype = { Phaser.Filter.prototype.constructor = Phaser.Filter; /** -* @name Phaser.Filter#width -* @property {number} width - The width (resolution uniform) -*/ + * @name Phaser.Filter#width + * @property {number} width - The width (resolution uniform) + */ Object.defineProperty(Phaser.Filter.prototype, 'width', { get: function () { - return this.uniforms.resolution.value.x; - }, set: function (value) { - this.uniforms.resolution.value.x = value; - } }); /** -* @name Phaser.Filter#height -* @property {number} height - The height (resolution uniform) -*/ + * @name Phaser.Filter#height + * @property {number} height - The height (resolution uniform) + */ Object.defineProperty(Phaser.Filter.prototype, 'height', { get: function () { - return this.uniforms.resolution.value.y; - }, set: function (value) { - this.uniforms.resolution.value.y = value; - } }); diff --git a/src/core/FlexGrid.js b/src/core/FlexGrid.js index 6095a9ca6..4f561e940 100644 --- a/src/core/FlexGrid.js +++ b/src/core/FlexGrid.js @@ -1,34 +1,33 @@ /** -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* WARNING: This is an EXPERIMENTAL class. The API will change significantly in the coming versions and is incomplete. -* Please try to avoid using in production games with a long time to build. -* This is also why the documentation is incomplete. -* -* FlexGrid is a a responsive grid manager that works in conjunction with the ScaleManager RESIZE scaling mode and FlexLayers -* to provide for game object positioning in a responsive manner. -* -* @class Phaser.FlexGrid -* @constructor -* @param {Phaser.ScaleManager} manager - The ScaleManager. -* @param {number} width - The width of the game. -* @param {number} height - The height of the game. -*/ + * WARNING: This is an EXPERIMENTAL class. The API will change significantly in the coming versions and is incomplete. + * Please try to avoid using in production games with a long time to build. + * This is also why the documentation is incomplete. + * + * FlexGrid is a a responsive grid manager that works in conjunction with the ScaleManager RESIZE scaling mode and FlexLayers + * to provide for game object positioning in a responsive manner. + * + * @class Phaser.FlexGrid + * @constructor + * @param {Phaser.ScaleManager} manager - The ScaleManager. + * @param {number} width - The width of the game. + * @param {number} height - The height of the game. + */ Phaser.FlexGrid = function (manager, width, height) { - /** - * @property {Phaser.Game} game - A reference to the currently running Game. - */ + * @property {Phaser.Game} game - A reference to the currently running Game. + */ this.game = manager.game; /** - * @property {Phaser.ScaleManager} manager - A reference to the ScaleManager. - */ + * @property {Phaser.ScaleManager} manager - A reference to the ScaleManager. + */ this.manager = manager; // The perfect dimensions on which everything else is based @@ -41,18 +40,18 @@ Phaser.FlexGrid = function (manager, width, height) this.boundsNone = new Phaser.Rectangle(0, 0, width, height); /** - * @property {Phaser.Point} position - - * @readonly - */ + * @property {Phaser.Point} position - + * @readonly + */ this.positionCustom = new Phaser.Point(0, 0); this.positionFluid = new Phaser.Point(0, 0); this.positionFull = new Phaser.Point(0, 0); this.positionNone = new Phaser.Point(0, 0); /** - * @property {Phaser.Point} scaleFactor - The scale factor based on the game dimensions vs. the scaled dimensions. - * @readonly - */ + * @property {Phaser.Point} scaleFactor - The scale factor based on the game dimensions vs. the scaled dimensions. + * @readonly + */ this.scaleCustom = new Phaser.Point(1, 1); this.scaleFluid = new Phaser.Point(1, 1); this.scaleFluidInversed = new Phaser.Point(1, 1); @@ -70,7 +69,6 @@ Phaser.FlexGrid = function (manager, width, height) this.multiplier = 0; this.layers = []; - }; Phaser.FlexGrid.prototype = { @@ -84,7 +82,6 @@ Phaser.FlexGrid.prototype = { */ setSize: function (width, height) { - // These are locked and don't change until setSize is called again this.width = width; this.height = height; @@ -98,7 +95,6 @@ Phaser.FlexGrid.prototype = { this.boundsNone.height = this.height; this.refresh(); - }, // Need ability to create your own layers with custom scaling, etc. @@ -114,7 +110,6 @@ Phaser.FlexGrid.prototype = { */ createCustomLayer: function (width, height, children, addToWorld) { - if (addToWorld === undefined) { addToWorld = true; } this.customWidth = width; @@ -138,7 +133,6 @@ Phaser.FlexGrid.prototype = { } return layer; - }, /** @@ -150,7 +144,6 @@ Phaser.FlexGrid.prototype = { */ createFluidLayer: function (children, addToWorld) { - if (addToWorld === undefined) { addToWorld = true; } var layer = new Phaser.FlexLayer(this, this.positionFluid, this.boundsFluid, this.scaleFluid); @@ -168,7 +161,6 @@ Phaser.FlexGrid.prototype = { } return layer; - }, /** @@ -180,7 +172,6 @@ Phaser.FlexGrid.prototype = { */ createFullLayer: function (children) { - var layer = new Phaser.FlexLayer(this, this.positionFull, this.boundsFull, this.scaleFluid); this.game.world.add(layer); @@ -193,7 +184,6 @@ Phaser.FlexGrid.prototype = { } return layer; - }, /** @@ -205,7 +195,6 @@ Phaser.FlexGrid.prototype = { */ createFixedLayer: function (children) { - var layer = new Phaser.FlexLayer(this, this.positionNone, this.boundsNone, this.scaleNone); this.game.world.add(layer); @@ -218,7 +207,6 @@ Phaser.FlexGrid.prototype = { } return layer; - }, /** @@ -228,7 +216,6 @@ Phaser.FlexGrid.prototype = { */ reset: function () { - var i = this.layers.length; while (i--) @@ -241,7 +228,6 @@ Phaser.FlexGrid.prototype = { this.layers.slice(i, 1); } } - }, /** @@ -253,12 +239,10 @@ Phaser.FlexGrid.prototype = { */ onResize: function (width, height) { - this.ratioH = width / height; this.ratioV = height / width; this.refresh(width, height); - }, /** @@ -268,7 +252,6 @@ Phaser.FlexGrid.prototype = { */ refresh: function () { - this.multiplier = Math.min((this.manager.height / this.height), (this.manager.width / this.width)); this.boundsFluid.width = Math.round(this.width * this.multiplier); @@ -287,7 +270,6 @@ Phaser.FlexGrid.prototype = { this.positionFluid.set(this.boundsFluid.x, this.boundsFluid.y); this.positionNone.set(this.boundsNone.x, this.boundsNone.y); - }, /** @@ -298,12 +280,10 @@ Phaser.FlexGrid.prototype = { */ fitSprite: function (sprite) { - this.manager.scaleSprite(sprite); sprite.x = this.manager.bounds.centerX; sprite.y = this.manager.bounds.centerY; - }, /** @@ -313,24 +293,30 @@ Phaser.FlexGrid.prototype = { */ debug: function () { - - // for (var i = 0; i < this.layers.length; i++) - // { - // this.layers[i].debug(); - // } - - // this.game.debug.text(this.boundsFull.width + ' x ' + this.boundsFull.height, this.boundsFull.x + 4, this.boundsFull.y + 16); - // this.game.debug.geom(this.boundsFull, 'rgba(0,0,255,0.9', false); + /* + * for (var i = 0; i < this.layers.length; i++) + * { + * this.layers[i].debug(); + * } + */ + + /* + * this.game.debug.text(this.boundsFull.width + ' x ' + this.boundsFull.height, this.boundsFull.x + 4, this.boundsFull.y + 16); + * this.game.debug.geom(this.boundsFull, 'rgba(0,0,255,0.9', false); + */ this.game.debug.text(this.boundsFluid.width + ' x ' + this.boundsFluid.height, this.boundsFluid.x + 4, this.boundsFluid.y + 16); this.game.debug.geom(this.boundsFluid, 'rgba(255,0,0,0.9', false); - // this.game.debug.text(this.boundsNone.width + ' x ' + this.boundsNone.height, this.boundsNone.x + 4, this.boundsNone.y + 16); - // this.game.debug.geom(this.boundsNone, 'rgba(0,255,0,0.9', false); - - // this.game.debug.text(this.boundsCustom.width + ' x ' + this.boundsCustom.height, this.boundsCustom.x + 4, this.boundsCustom.y + 16); - // this.game.debug.geom(this.boundsCustom, 'rgba(255,255,0,0.9', false); + /* + * this.game.debug.text(this.boundsNone.width + ' x ' + this.boundsNone.height, this.boundsNone.x + 4, this.boundsNone.y + 16); + * this.game.debug.geom(this.boundsNone, 'rgba(0,255,0,0.9', false); + */ + /* + * this.game.debug.text(this.boundsCustom.width + ' x ' + this.boundsCustom.height, this.boundsCustom.x + 4, this.boundsCustom.y + 16); + * this.game.debug.geom(this.boundsCustom, 'rgba(255,255,0,0.9', false); + */ } }; diff --git a/src/core/FlexLayer.js b/src/core/FlexLayer.js index df07558be..d56910b3e 100644 --- a/src/core/FlexLayer.js +++ b/src/core/FlexLayer.js @@ -1,37 +1,36 @@ /** -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* WARNING: This is an EXPERIMENTAL class. The API will change significantly in the coming versions and is incomplete. -* Please try to avoid using in production games with a long time to build. -* This is also why the documentation is incomplete. -* -* A responsive grid layer. -* -* @class Phaser.FlexLayer -* @extends Phaser.Group -* @constructor -* @param {Phaser.FlexGrid} manager - The FlexGrid that owns this FlexLayer. -* @param {Phaser.Point} position - A reference to the Point object used for positioning. -* @param {Phaser.Rectangle} bounds - A reference to the Rectangle used for the layer bounds. -* @param {Phaser.Point} scale - A reference to the Point object used for layer scaling. -*/ + * WARNING: This is an EXPERIMENTAL class. The API will change significantly in the coming versions and is incomplete. + * Please try to avoid using in production games with a long time to build. + * This is also why the documentation is incomplete. + * + * A responsive grid layer. + * + * @class Phaser.FlexLayer + * @extends Phaser.Group + * @constructor + * @param {Phaser.FlexGrid} manager - The FlexGrid that owns this FlexLayer. + * @param {Phaser.Point} position - A reference to the Point object used for positioning. + * @param {Phaser.Rectangle} bounds - A reference to the Rectangle used for the layer bounds. + * @param {Phaser.Point} scale - A reference to the Point object used for layer scaling. + */ Phaser.FlexLayer = function (manager, position, bounds, scale) { - Phaser.Group.call(this, manager.game, null, '__flexLayer' + manager.game.rnd.uuid(), false); /** - * @property {Phaser.ScaleManager} scale - A reference to the ScaleManager. - */ + * @property {Phaser.ScaleManager} scale - A reference to the ScaleManager. + */ this.manager = manager.manager; /** - * @property {Phaser.FlexGrid} grid - A reference to the FlexGrid that owns this layer. - */ + * @property {Phaser.FlexGrid} grid - A reference to the FlexGrid that owns this layer. + */ this.grid = manager; /** @@ -42,50 +41,49 @@ Phaser.FlexLayer = function (manager, position, bounds, scale) this.persist = false; /** - * @property {Phaser.Point} position - */ + * @property {Phaser.Point} position + */ this.position = position; /** - * @property {Phaser.Rectangle} bounds - */ + * @property {Phaser.Rectangle} bounds + */ this.bounds = bounds; /** - * @property {Phaser.Point} scale - */ + * @property {Phaser.Point} scale + */ this.scale = scale; /** - * @property {Phaser.Point} topLeft - */ + * @property {Phaser.Point} topLeft + */ this.topLeft = bounds.topLeft; /** - * @property {Phaser.Point} topMiddle - */ + * @property {Phaser.Point} topMiddle + */ this.topMiddle = new Phaser.Point(bounds.halfWidth, 0); /** - * @property {Phaser.Point} topRight - */ + * @property {Phaser.Point} topRight + */ this.topRight = bounds.topRight; /** - * @property {Phaser.Point} bottomLeft - */ + * @property {Phaser.Point} bottomLeft + */ this.bottomLeft = bounds.bottomLeft; /** - * @property {Phaser.Point} bottomMiddle - */ + * @property {Phaser.Point} bottomMiddle + */ this.bottomMiddle = new Phaser.Point(bounds.halfWidth, bounds.bottom); /** - * @property {Phaser.Point} bottomRight - */ + * @property {Phaser.Point} bottomRight + */ this.bottomRight = bounds.bottomRight; - }; Phaser.FlexLayer.prototype = Object.create(Phaser.Group.prototype); @@ -107,12 +105,10 @@ Phaser.FlexLayer.prototype.resize = function () */ Phaser.FlexLayer.prototype.debug = function () { - this.game.debug.text(this.bounds.width + ' x ' + this.bounds.height, this.bounds.x + 4, this.bounds.y + 16); this.game.debug.geom(this.bounds, 'rgba(0,0,255,0.9', false); this.game.debug.geom(this.topLeft, 'rgba(255,255,255,0.9'); this.game.debug.geom(this.topMiddle, 'rgba(255,255,255,0.9'); this.game.debug.geom(this.topRight, 'rgba(255,255,255,0.9'); - }; diff --git a/src/core/Game.js b/src/core/Game.js index 42bf781d6..757de1bfd 100644 --- a/src/core/Game.js +++ b/src/core/Game.js @@ -1,494 +1,493 @@ /** -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* The Phaser.Game object is the main controller for the entire Phaser game. It is responsible -* for handling the boot process, parsing the configuration values, creating the renderer, -* and setting-up all of the Phaser systems, such as physics, sound and input. -* Once that is complete it will start the default State, and then begin the main game loop. -* -* You can access lots of the Phaser systems via the properties on the `game` object. For -* example `game.renderer` is the Renderer, `game.sound` is the Sound Manager, and so on. -* -* Anywhere you can access the `game` property, you can access all of these core systems. -* For example a Sprite has a `game` property, allowing you to talk to the various parts -* of Phaser directly, without having to look after your own references. -* -* In its most simplest form, a Phaser game can be created by providing the arguments -* to the constructor: -* -* ```javascript -* var game = new Phaser.Game(800, 600, Phaser.AUTO, '', { preload: preload, create: create }); -* ``` -* -* In the example above it is passing in a State object directly. You can also use the State -* Manager to do this: -* -* ```javascript -* var game = new Phaser.Game(800, 600, Phaser.AUTO); -* game.state.add('Boot', BasicGame.Boot); -* game.state.add('Preloader', BasicGame.Preloader); -* game.state.add('MainMenu', BasicGame.MainMenu); -* game.state.add('Game', BasicGame.Game); -* game.state.start('Boot'); -* ``` -* -* In the example above, 4 States are added to the State Manager, and Phaser is told to -* start running the `Boot` state when it has finished initializing. There are example -* project templates you can use in the Phaser GitHub repo, inside the `resources` folder. -* -* Instead of specifying arguments you can also pass {@link GameConfig a single object} instead: -* -* ```javascript -* var config = { -* width: 800, -* height: 600, -* renderer: Phaser.AUTO, -* antialias: true, -* multiTexture: true, -* state: { -* preload: preload, -* create: create, -* update: update -* } -* } -* -* var game = new Phaser.Game(config); -* ``` -* -* @class Phaser.Game -* @constructor -* @param {number|string|GameConfig} [width=800] - The width of your game in game pixels. If given as a string the value must be between 0 and 100 and will be used as the percentage width of the parent container, or the browser window if no parent is given. -* @param {number|string} [height=600] - The height of your game in game pixels. If given as a string the value must be between 0 and 100 and will be used as the percentage height of the parent container, or the browser window if no parent is given. -* @param {number} [renderer=Phaser.AUTO] - Which renderer to use: Phaser.AUTO will auto-detect, Phaser.WEBGL, Phaser.WEBGL_MULTI, Phaser.CANVAS or Phaser.HEADLESS (no rendering at all). -* @param {string|HTMLElement} [parent=''] - The DOM element into which this game canvas will be injected. Either a DOM `id` (string) or the element itself. If omitted (or no such element exists), the game canvas is appended to the document body. -* @param {object} [state=null] - The default state object. A object consisting of Phaser.State functions (preload, create, update, render) or null. -* @param {boolean} [transparent=false] - Use a transparent canvas background or not. -* @param {boolean} [antialias=true] - Draw all image textures anti-aliased or not. The default is for smooth textures, but disable if your game features pixel art. -* @param {object} [physicsConfig=null] - A physics configuration object to pass to the Physics world on creation. -*/ + * The Phaser.Game object is the main controller for the entire Phaser game. It is responsible + * for handling the boot process, parsing the configuration values, creating the renderer, + * and setting-up all of the Phaser systems, such as physics, sound and input. + * Once that is complete it will start the default State, and then begin the main game loop. + * + * You can access lots of the Phaser systems via the properties on the `game` object. For + * example `game.renderer` is the Renderer, `game.sound` is the Sound Manager, and so on. + * + * Anywhere you can access the `game` property, you can access all of these core systems. + * For example a Sprite has a `game` property, allowing you to talk to the various parts + * of Phaser directly, without having to look after your own references. + * + * In its most simplest form, a Phaser game can be created by providing the arguments + * to the constructor: + * + * ```javascript + * var game = new Phaser.Game(800, 600, Phaser.AUTO, '', { preload: preload, create: create }); + * ``` + * + * In the example above it is passing in a State object directly. You can also use the State + * Manager to do this: + * + * ```javascript + * var game = new Phaser.Game(800, 600, Phaser.AUTO); + * game.state.add('Boot', BasicGame.Boot); + * game.state.add('Preloader', BasicGame.Preloader); + * game.state.add('MainMenu', BasicGame.MainMenu); + * game.state.add('Game', BasicGame.Game); + * game.state.start('Boot'); + * ``` + * + * In the example above, 4 States are added to the State Manager, and Phaser is told to + * start running the `Boot` state when it has finished initializing. There are example + * project templates you can use in the Phaser GitHub repo, inside the `resources` folder. + * + * Instead of specifying arguments you can also pass {@link GameConfig a single object} instead: + * + * ```javascript + * var config = { + * width: 800, + * height: 600, + * renderer: Phaser.AUTO, + * antialias: true, + * multiTexture: true, + * state: { + * preload: preload, + * create: create, + * update: update + * } + * } + * + * var game = new Phaser.Game(config); + * ``` + * + * @class Phaser.Game + * @constructor + * @param {number|string|GameConfig} [width=800] - The width of your game in game pixels. If given as a string the value must be between 0 and 100 and will be used as the percentage width of the parent container, or the browser window if no parent is given. + * @param {number|string} [height=600] - The height of your game in game pixels. If given as a string the value must be between 0 and 100 and will be used as the percentage height of the parent container, or the browser window if no parent is given. + * @param {number} [renderer=Phaser.AUTO] - Which renderer to use: Phaser.AUTO will auto-detect, Phaser.WEBGL, Phaser.WEBGL_MULTI, Phaser.CANVAS or Phaser.HEADLESS (no rendering at all). + * @param {string|HTMLElement} [parent=''] - The DOM element into which this game canvas will be injected. Either a DOM `id` (string) or the element itself. If omitted (or no such element exists), the game canvas is appended to the document body. + * @param {object} [state=null] - The default state object. A object consisting of Phaser.State functions (preload, create, update, render) or null. + * @param {boolean} [transparent=false] - Use a transparent canvas background or not. + * @param {boolean} [antialias=true] - Draw all image textures anti-aliased or not. The default is for smooth textures, but disable if your game features pixel art. + * @param {object} [physicsConfig=null] - A physics configuration object to pass to the Physics world on creation. + */ Phaser.Game = function (width, height, renderer, parent, state, transparent, antialias, physicsConfig) { - /** - * @property {number} id - Phaser Game ID - * @readonly - */ + * @property {number} id - Phaser Game ID + * @readonly + */ this.id = Phaser.GAMES.push(this) - 1; /** - * @property {object} config - The Phaser.Game configuration object. - */ + * @property {object} config - The Phaser.Game configuration object. + */ this.config = null; /** - * @property {object} physicsConfig - The Phaser.Physics.World configuration object. - */ + * @property {object} physicsConfig - The Phaser.Physics.World configuration object. + */ this.physicsConfig = physicsConfig; /** - * @property {string|HTMLElement} parent - The Game's DOM parent (or name thereof), if any, as set when the game was created. The actual parent can be found in `game.canvas.parentNode`. Setting this has no effect after {@link Phaser.ScaleManager} is booted. - * @readonly - * @default - */ + * @property {string|HTMLElement} parent - The Game's DOM parent (or name thereof), if any, as set when the game was created. The actual parent can be found in `game.canvas.parentNode`. Setting this has no effect after {@link Phaser.ScaleManager} is booted. + * @readonly + * @default + */ this.parent = ''; /** - * The current Game Width in pixels. - * - * _Do not modify this property directly:_ use {@link Phaser.ScaleManager#setGameSize} - e.g. `game.scale.setGameSize(width, height)` - instead. - * - * @property {integer} width - * @readonly - * @default - */ + * The current Game Width in pixels. + * + * _Do not modify this property directly:_ use {@link Phaser.ScaleManager#setGameSize} - e.g. `game.scale.setGameSize(width, height)` - instead. + * + * @property {integer} width + * @readonly + * @default + */ this.width = 800; /** - * The current Game Height in pixels. - * - * _Do not modify this property directly:_ use {@link Phaser.ScaleManager#setGameSize} - e.g. `game.scale.setGameSize(width, height)` - instead. - * - * @property {integer} height - * @readonly - * @default - */ + * The current Game Height in pixels. + * + * _Do not modify this property directly:_ use {@link Phaser.ScaleManager#setGameSize} - e.g. `game.scale.setGameSize(width, height)` - instead. + * + * @property {integer} height + * @readonly + * @default + */ this.height = 600; /** - * The resolution of your game, as a ratio of canvas pixels to game pixels. This value is read only, but can be changed at start time it via a game configuration object. - * - * @property {integer} resolution - * @readonly - * @default - */ + * The resolution of your game, as a ratio of canvas pixels to game pixels. This value is read only, but can be changed at start time it via a game configuration object. + * + * @property {integer} resolution + * @readonly + * @default + */ this.resolution = 1; /** - * @property {integer} _width - Private internal var. - * @private - */ + * @property {integer} _width - Private internal var. + * @private + */ this._width = 800; /** - * @property {integer} _height - Private internal var. - * @private - */ + * @property {integer} _height - Private internal var. + * @private + */ this._height = 600; /** - * @property {boolean} transparent - Use a transparent canvas background or not. - * @default - */ + * @property {boolean} transparent - Use a transparent canvas background or not. + * @default + */ this.transparent = false; /** - * @property {boolean} antialias - Anti-alias graphics (as set when the Game is created). By default scaled and rotated images are smoothed in Canvas and WebGL; set `antialias` to false to disable this globally. After the game boots, use `game.stage.smoothed` instead. - * @readonly - * @default - */ + * @property {boolean} antialias - Anti-alias graphics (as set when the Game is created). By default scaled and rotated images are smoothed in Canvas and WebGL; set `antialias` to false to disable this globally. After the game boots, use `game.stage.smoothed` instead. + * @readonly + * @default + */ this.antialias = true; /** - * Has support for Multiple bound Textures in WebGL been enabled? This is a read-only property. - * To set it you need to either specify `Phaser.WEBGL_MULTI` as the renderer type, or use the Game - * Configuration object with the property `multiTexture` set to true. It has to be enabled before - * Pixi boots, and cannot be changed after the game is running. Once enabled, take advantage of it - * via the `game.renderer.setTexturePriority` method. - * - * @property {boolean} multiTexture - * @readonly - * @default - */ + * Has support for Multiple bound Textures in WebGL been enabled? This is a read-only property. + * To set it you need to either specify `Phaser.WEBGL_MULTI` as the renderer type, or use the Game + * Configuration object with the property `multiTexture` set to true. It has to be enabled before + * Pixi boots, and cannot be changed after the game is running. Once enabled, take advantage of it + * via the `game.renderer.setTexturePriority` method. + * + * @property {boolean} multiTexture + * @readonly + * @default + */ this.multiTexture = false; /** - * @property {boolean} preserveDrawingBuffer - The value of the preserveDrawingBuffer flag affects whether or not the contents of the stencil buffer is retained after rendering. - * @default - */ + * @property {boolean} preserveDrawingBuffer - The value of the preserveDrawingBuffer flag affects whether or not the contents of the stencil buffer is retained after rendering. + * @default + */ this.preserveDrawingBuffer = false; /** - * Clear the Canvas each frame before rendering the display list. - * You can set this to `false` to gain some performance if your game always contains a background that completely fills the display. - * This must be `true` to show any {@link Phaser.Stage#backgroundColor} set on the Stage. - * This is effectively **read-only after the game has booted**. - * Use the {@link GameConfig} setting `clearBeforeRender` when creating the game, or set `game.renderer.clearBeforeRender` afterwards. - * @property {boolean} clearBeforeRender - * @default - */ + * Clear the Canvas each frame before rendering the display list. + * You can set this to `false` to gain some performance if your game always contains a background that completely fills the display. + * This must be `true` to show any {@link Phaser.Stage#backgroundColor} set on the Stage. + * This is effectively **read-only after the game has booted**. + * Use the {@link GameConfig} setting `clearBeforeRender` when creating the game, or set `game.renderer.clearBeforeRender` afterwards. + * @property {boolean} clearBeforeRender + * @default + */ this.clearBeforeRender = true; /** - * @property {PIXI.CanvasRenderer|PIXI.WebGLRenderer} renderer - The Pixi Renderer. - * @protected - */ + * @property {PIXI.CanvasRenderer|PIXI.WebGLRenderer} renderer - The Pixi Renderer. + * @protected + */ this.renderer = null; /** - * @property {number} renderType - The Renderer this game will use. Either Phaser.AUTO, Phaser.CANVAS, Phaser.WEBGL, Phaser.WEBGL_MULTI or Phaser.HEADLESS. After the game boots, renderType reflects the renderer in use: AUTO changes to CANVAS or WEBGL and WEBGL_MULTI changes to WEBGL. HEADLESS skips `preRender`, `render`, and `postRender` hooks, just like {@link #lockRender}. - * @readonly - */ + * @property {number} renderType - The Renderer this game will use. Either Phaser.AUTO, Phaser.CANVAS, Phaser.WEBGL, Phaser.WEBGL_MULTI or Phaser.HEADLESS. After the game boots, renderType reflects the renderer in use: AUTO changes to CANVAS or WEBGL and WEBGL_MULTI changes to WEBGL. HEADLESS skips `preRender`, `render`, and `postRender` hooks, just like {@link #lockRender}. + * @readonly + */ this.renderType = Phaser.AUTO; /** - * @property {Phaser.StateManager} state - The StateManager. - */ + * @property {Phaser.StateManager} state - The StateManager. + */ this.state = null; /** - * @property {boolean} isBooted - Whether the game engine is booted, aka available. - * @readonly - */ + * @property {boolean} isBooted - Whether the game engine is booted, aka available. + * @readonly + */ this.isBooted = false; /** - * @property {boolean} isRunning - Is game running or paused? - * @readonly - */ + * @property {boolean} isRunning - Is game running or paused? + * @readonly + */ this.isRunning = false; /** - * @property {Phaser.RequestAnimationFrame} raf - Automatically handles the core game loop via requestAnimationFrame or setTimeout - * @protected - */ + * @property {Phaser.RequestAnimationFrame} raf - Automatically handles the core game loop via requestAnimationFrame or setTimeout + * @protected + */ this.raf = null; /** - * @property {Phaser.GameObjectFactory} add - Reference to the Phaser.GameObjectFactory. - */ + * @property {Phaser.GameObjectFactory} add - Reference to the Phaser.GameObjectFactory. + */ this.add = null; /** - * @property {Phaser.GameObjectCreator} make - Reference to the GameObject Creator. - */ + * @property {Phaser.GameObjectCreator} make - Reference to the GameObject Creator. + */ this.make = null; /** - * @property {Phaser.Cache} cache - Reference to the assets cache. - */ + * @property {Phaser.Cache} cache - Reference to the assets cache. + */ this.cache = null; /** - * @property {Phaser.Input} input - Reference to the input manager - */ + * @property {Phaser.Input} input - Reference to the input manager + */ this.input = null; /** - * @property {Phaser.Loader} load - Reference to the assets loader. - */ + * @property {Phaser.Loader} load - Reference to the assets loader. + */ this.load = null; /** - * @property {Phaser.Math} math - Reference to the math helper. - */ + * @property {Phaser.Math} math - Reference to the math helper. + */ this.math = null; /** - * @property {Phaser.Net} net - Reference to the network class. - */ + * @property {Phaser.Net} net - Reference to the network class. + */ this.net = null; /** - * @property {Phaser.ScaleManager} scale - The game scale manager. - */ + * @property {Phaser.ScaleManager} scale - The game scale manager. + */ this.scale = null; /** - * @property {Phaser.SoundManager} sound - Reference to the sound manager. - */ + * @property {Phaser.SoundManager} sound - Reference to the sound manager. + */ this.sound = null; /** - * @property {Phaser.Stage} stage - Reference to the stage. - */ + * @property {Phaser.Stage} stage - Reference to the stage. + */ this.stage = null; /** - * @property {Phaser.Time} time - Reference to the core game clock. - */ + * @property {Phaser.Time} time - Reference to the core game clock. + */ this.time = null; /** - * @property {Phaser.TweenManager} tweens - Reference to the tween manager. - */ + * @property {Phaser.TweenManager} tweens - Reference to the tween manager. + */ this.tweens = null; /** - * @property {Phaser.World} world - Reference to the world. - */ + * @property {Phaser.World} world - Reference to the world. + */ this.world = null; /** - * @property {Phaser.Physics} physics - Reference to the physics manager. - */ + * @property {Phaser.Physics} physics - Reference to the physics manager. + */ this.physics = null; /** - * @property {Phaser.PluginManager} plugins - Reference to the plugin manager. - */ + * @property {Phaser.PluginManager} plugins - Reference to the plugin manager. + */ this.plugins = null; /** - * @property {Phaser.RandomDataGenerator} rnd - Instance of repeatable random data generator helper. - */ + * @property {Phaser.RandomDataGenerator} rnd - Instance of repeatable random data generator helper. + */ this.rnd = null; /** - * @property {Phaser.Device} device - Contains device information and capabilities. - */ + * @property {Phaser.Device} device - Contains device information and capabilities. + */ this.device = Phaser.Device; /** - * @property {Phaser.Camera} camera - A handy reference to world.camera. - */ + * @property {Phaser.Camera} camera - A handy reference to world.camera. + */ this.camera = null; /** - * @property {HTMLCanvasElement} canvas - A handy reference to renderer.view, the canvas that the game is being rendered in to. - */ + * @property {HTMLCanvasElement} canvas - A handy reference to renderer.view, the canvas that the game is being rendered in to. + */ this.canvas = null; /** - * @property {CanvasRenderingContext2D} context - A handy reference to renderer.context (only set for CANVAS games, not WebGL) - */ + * @property {CanvasRenderingContext2D} context - A handy reference to renderer.context (only set for CANVAS games, not WebGL) + */ this.context = null; /** - * @property {Phaser.Utils.Debug} debug - A set of useful debug utilities. - */ + * @property {Phaser.Utils.Debug} debug - A set of useful debug utilities. + */ this.debug = null; /** - * @property {Phaser.Particles} particles - The Particle Manager. - */ + * @property {Phaser.Particles} particles - The Particle Manager. + */ this.particles = null; /** - * @property {Phaser.Create} create - The Asset Generator. - */ + * @property {Phaser.Create} create - The Asset Generator. + */ this.create = null; /** - * If `false` Phaser will automatically render the display list every update. If `true` the render loop will be skipped. - * You can toggle this value at run-time to gain exact control over when Phaser renders. This can be useful in certain types of game or application. - * Please note that if you don't render the display list then none of the game object transforms will be updated, so use this value carefully. - * @property {boolean} lockRender - * @default - */ + * If `false` Phaser will automatically render the display list every update. If `true` the render loop will be skipped. + * You can toggle this value at run-time to gain exact control over when Phaser renders. This can be useful in certain types of game or application. + * Please note that if you don't render the display list then none of the game object transforms will be updated, so use this value carefully. + * @property {boolean} lockRender + * @default + */ this.lockRender = false; /** - * @property {boolean} pendingDestroy - Destroy the game at the next update. - * @default - */ + * @property {boolean} pendingDestroy - Destroy the game at the next update. + * @default + */ this.pendingDestroy = false; /** - * @property {boolean} stepping - Enable core loop stepping with Game.enableStep(). - * @default - * @readonly - */ + * @property {boolean} stepping - Enable core loop stepping with Game.enableStep(). + * @default + * @readonly + */ this.stepping = false; /** - * @property {boolean} pendingStep - An internal property used by enableStep, but also useful to query from your own game objects. - * @default - * @readonly - */ + * @property {boolean} pendingStep - An internal property used by enableStep, but also useful to query from your own game objects. + * @default + * @readonly + */ this.pendingStep = false; /** - * @property {number} stepCount - When stepping is enabled this contains the current step cycle. - * @default - * @readonly - */ + * @property {number} stepCount - When stepping is enabled this contains the current step cycle. + * @default + * @readonly + */ this.stepCount = 0; /** - * @property {Phaser.Signal} onPause - This event is fired when the game pauses. - */ + * @property {Phaser.Signal} onPause - This event is fired when the game pauses. + */ this.onPause = null; /** - * @property {Phaser.Signal} onResume - This event is fired when the game resumes from a paused state. - */ + * @property {Phaser.Signal} onResume - This event is fired when the game resumes from a paused state. + */ this.onResume = null; /** - * @property {Phaser.Signal} onBlur - This event is fired when the game no longer has focus (typically on page hide). - */ + * @property {Phaser.Signal} onBlur - This event is fired when the game no longer has focus (typically on page hide). + */ this.onBlur = null; /** - * @property {Phaser.Signal} onFocus - This event is fired when the game has focus (typically on page show). - */ + * @property {Phaser.Signal} onFocus - This event is fired when the game has focus (typically on page show). + */ this.onFocus = null; /** - * @property {boolean} _paused - Is game paused? - * @private - */ + * @property {boolean} _paused - Is game paused? + * @private + */ this._paused = false; /** - * @property {boolean} _codePaused - Was the game paused via code or a visibility change? - * @private - */ + * @property {boolean} _codePaused - Was the game paused via code or a visibility change? + * @private + */ this._codePaused = false; /** - * The ID of the current/last logic update applied this animation frame, starting from 0. - * The first update is `currentUpdateID === 0` and the last update is `currentUpdateID === updatesThisFrame.` - * @property {integer} currentUpdateID - * @protected - */ + * The ID of the current/last logic update applied this animation frame, starting from 0. + * The first update is `currentUpdateID === 0` and the last update is `currentUpdateID === updatesThisFrame.` + * @property {integer} currentUpdateID + * @protected + */ this.currentUpdateID = 0; /** - * Number of logic updates expected to occur this animation frame; will be 1 unless there are catch-ups required (and allowed). - * @property {integer} updatesThisFrame - * @protected - */ + * Number of logic updates expected to occur this animation frame; will be 1 unless there are catch-ups required (and allowed). + * @property {integer} updatesThisFrame + * @protected + */ this.updatesThisFrame = 1; /** - * Number of renders expected to occur this animation frame. May be 0 if {@link #dropFrames} is on or {@link #forceSingleRender} is off; otherwise it will be 1. - * @property {integer} rendersThisFrame - * @protected - */ + * Number of renders expected to occur this animation frame. May be 0 if {@link #dropFrames} is on or {@link #forceSingleRender} is off; otherwise it will be 1. + * @property {integer} rendersThisFrame + * @protected + */ this.rendersThisFrame = 1; /** - * @property {number} _deltaTime - Accumulate elapsed time until a logic update is due. - * @private - */ + * @property {number} _deltaTime - Accumulate elapsed time until a logic update is due. + * @private + */ this._deltaTime = 0; /** - * @property {number} _lastCount - Remember how many 'catch-up' iterations were used on the logicUpdate last frame. - * @private - */ + * @property {number} _lastCount - Remember how many 'catch-up' iterations were used on the logicUpdate last frame. + * @private + */ this._lastCount = 0; /** - * @property {number} _spiraling - If the 'catch-up' iterations are spiraling out of control, this counter is incremented. - * @private - */ + * @property {number} _spiraling - If the 'catch-up' iterations are spiraling out of control, this counter is incremented. + * @private + */ this._spiraling = 0; /** - * @property {boolean} _kickstart - Force a logic update + render by default (always set on Boot and State swap) - * @private - */ + * @property {boolean} _kickstart - Force a logic update + render by default (always set on Boot and State swap) + * @private + */ this._kickstart = true; /** - * If the game is struggling to maintain the desired FPS, this signal will be dispatched. - * The desired/chosen FPS should probably be closer to the {@link Phaser.Time#suggestedFps} value. - * @property {Phaser.Signal} fpsProblemNotifier - * @public - */ + * If the game is struggling to maintain the desired FPS, this signal will be dispatched. + * The desired/chosen FPS should probably be closer to the {@link Phaser.Time#suggestedFps} value. + * @property {Phaser.Signal} fpsProblemNotifier + * @public + */ this.fpsProblemNotifier = new Phaser.Signal(); /** - * @property {boolean} forceSingleUpdate - Should the game loop force a logic update, regardless of the delta timer? You can toggle it on the fly. - * @default - */ + * @property {boolean} forceSingleUpdate - Should the game loop force a logic update, regardless of the delta timer? You can toggle it on the fly. + * @default + */ this.forceSingleUpdate = true; /** - * @property {boolean} forceSingleRender - Should the game loop make one render per animation frame, even without a preceding logic update? (During spiraling conditions, {@link #dropFrames} is used instead.) - * @default - */ + * @property {boolean} forceSingleRender - Should the game loop make one render per animation frame, even without a preceding logic update? (During spiraling conditions, {@link #dropFrames} is used instead.) + * @default + */ this.forceSingleRender = true; /** - * @property {boolean} dropFrames - When {@link #forceSingleUpdate} is off, skip {@link #updateRender rendering} if logic updates are spiraling upwards. - * @default - */ + * @property {boolean} dropFrames - When {@link #forceSingleUpdate} is off, skip {@link #updateRender rendering} if logic updates are spiraling upwards. + * @default + */ this.dropFrames = false; /** - * @property {number} maxUpdates - When {@link #forceSingleUpdate} is off, the maximum number of logic updates to make per animation frame, if required to catch up. - * @default - */ + * @property {number} maxUpdates - When {@link #forceSingleUpdate} is off, the maximum number of logic updates to make per animation frame, if required to catch up. + * @default + */ this.maxUpdates = 3; /** - * @property {string} powerPreference - When the WebGL renderer is used, hint to the browser which GPU to use. - * @readonly - * @default - */ + * @property {string} powerPreference - When the WebGL renderer is used, hint to the browser which GPU to use. + * @readonly + * @default + */ this.powerPreference = 'default'; /** - * @property {number} _nextNotification - The soonest game.time.time value that the next fpsProblemNotifier can be dispatched. - * @private - */ + * @property {number} _nextNotification - The soonest game.time.time value that the next fpsProblemNotifier can be dispatched. + * @private + */ this._nextFpsNotification = 0; // Parse the configuration object (if any) @@ -538,68 +537,66 @@ Phaser.Game = function (width, height, renderer, parent, state, transparent, ant this.device.whenReady(this.boot, this); return this; - }; /** -* A configuration object for {@link Phaser.Game}. -* -* @typedef {object} GameConfig -* @property {boolean} [GameConfig.alignH=false] - Sets {@link Phaser.ScaleManager#pageAlignHorizontally}. -* @property {boolean} [GameConfig.alignV=false] - Sets {@link Phaser.ScaleManager#pageAlignVertically}. -* @property {boolean} [GameConfig.antialias=true] -* @property {number|string} [GameConfig.backgroundColor=0] - Sets {@link Phaser.Stage#backgroundColor}. -* @property {HTMLCanvasElement} [GameConfig.canvas] - An existing canvas to display the game in. -* @property {string} [GameConfig.canvasID] - `id` attribute value to assign to the game canvas. -* @property {string} [GameConfig.canvasStyle] - `style` attribute value to assign to the game canvas. -* @property {boolean} [GameConfig.clearBeforeRender=true] - Sets {@link Phaser.Game#clearBeforeRender}. -* @property {boolean} [GameConfig.crisp=false] - Sets the canvas's `image-rendering` property to `pixelated` or `crisp-edges`. See {@link Phaser.Canvas.setImageRenderingCrisp}. -* @property {boolean} [GameConfig.disableVisibilityChange=false] - Sets {@link Phaser.Stage#disableVisibilityChange} -* @property {boolean} [GameConfig.disableStart=false] - Prevents the game loop from starting, allowing you to call updates manually. Helpful for automated testing. -* @property {boolean} [GameConfig.enableDebug=true] - Enable {@link Phaser.Utils.Debug}. You can gain a little performance by disabling this in production. -* @property {boolean} [GameConfig.failIfMajorPerformanceCaveat] - Abort WebGL context creation if performance would be poor. You can use this with renderer AUTO. -* @property {boolean} [GameConfig.forceSetTimeout] - Use {@link https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout setTimeOut} for the game loop even if {@link https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame requestAnimationFrame} is available. -* @property {number} [GameConfig.fullScreenScaleMode] - The scaling method used by the ScaleManager when in fullscreen. -* @property {HTMLElement} [GameConfig.fullScreenTarget] - The DOM element on which the Fullscreen API enter request will be invoked. -* @property {number|string} [GameConfig.height=600] -* @property {boolean} [GameConfig.keyboard=true] - Starts the keyboard input handler. -* @property {number} [GameConfig.maxPointers=-1] - Sets {@link Phaser.Input#maxPointers}. -* @property {boolean} [GameConfig.mouse=true] - Starts the mouse input handler, if the mspointer and touch handlers were not started. -* @property {boolean} [GameConfig.mouseWheel=true] - Starts the {@link Phaser.MouseWheel mouse wheel} handler, if supported by the device. -* @property {boolean} [GameConfig.mspointer=true] - Starts the {@link Phaser.MSPointer Pointer Events} handler (mspointer), if supported by the device. -* @property {boolean} [GameConfig.multiTexture=false] - Enable support for multiple bound Textures in WebGL. Same as `{renderer: Phaser.WEBGL_MULTI}`. -* @property {string|HTMLElement} [GameConfig.parent=''] - The DOM element into which this games canvas will be injected. -* @property {object} [GameConfig.physicsConfig] -* @property {boolean} [GameConfig.pointerLock=true] - Starts the {@link Phaser.PointerLock Pointer Lock} handler, if supported by the device. -* @property {string} [GameConfig.powerPreference='default'] - Sets the WebGL renderer's powerPreference when the WebGL renderer is used. -* @property {boolean} [GameConfig.preserveDrawingBuffer=false] - Whether or not the contents of the stencil buffer is retained after rendering. -* @property {number} [GameConfig.renderer=Phaser.AUTO] -* @property {number} [GameConfig.resolution=1] - The resolution of your game, as a ratio of canvas pixels to game pixels. -* @property {boolean} [GameConfig.roundPixels=false] - Round pixel coordinates for rendering (rather than interpolating). Handy for crisp pixel art and speed on legacy devices. -* @property {number} [GameConfig.scaleH=1] - Horizontal scaling factor for USER_SCALE scale mode. -* @property {number} [GameConfig.scaleMode] - The scaling method used by the ScaleManager when not in fullscreen. -* @property {number} [GameConfig.scaleV=1] - Vertical scaling factor for USER_SCALE scale mode. -* @property {number} [GameConfig.seed] - Seed for {@link Phaser.RandomDataGenerator}. -* @property {object} [GameConfig.state] -* @property {boolean} [GameConfig.touch=true] - Starts the {@link Phaser.Touch touch} handler, if supported by the device and the Pointer Events handler (mspointer) was not started. -* @property {boolean|string} [GameConfig.transparent=false] - Sets {@link Phaser.Game#transparent}. `'notMultiplied'` disables the WebGL context attribute `premultipliedAlpha`. -* @property {number} [GameConfig.trimH=0] - Horizontal trim for USER_SCALE scale mode. -* @property {number} [GameConfig.trimV=0] - Vertical trim for USER_SCALE scale mode. -* @property {number|string} [GameConfig.width=800] -*/ + * A configuration object for {@link Phaser.Game}. + * + * @typedef {object} GameConfig + * @property {boolean} [GameConfig.alignH=false] - Sets {@link Phaser.ScaleManager#pageAlignHorizontally}. + * @property {boolean} [GameConfig.alignV=false] - Sets {@link Phaser.ScaleManager#pageAlignVertically}. + * @property {boolean} [GameConfig.antialias=true] + * @property {number|string} [GameConfig.backgroundColor=0] - Sets {@link Phaser.Stage#backgroundColor}. + * @property {HTMLCanvasElement} [GameConfig.canvas] - An existing canvas to display the game in. + * @property {string} [GameConfig.canvasID] - `id` attribute value to assign to the game canvas. + * @property {string} [GameConfig.canvasStyle] - `style` attribute value to assign to the game canvas. + * @property {boolean} [GameConfig.clearBeforeRender=true] - Sets {@link Phaser.Game#clearBeforeRender}. + * @property {boolean} [GameConfig.crisp=false] - Sets the canvas's `image-rendering` property to `pixelated` or `crisp-edges`. See {@link Phaser.Canvas.setImageRenderingCrisp}. + * @property {boolean} [GameConfig.disableVisibilityChange=false] - Sets {@link Phaser.Stage#disableVisibilityChange} + * @property {boolean} [GameConfig.disableStart=false] - Prevents the game loop from starting, allowing you to call updates manually. Helpful for automated testing. + * @property {boolean} [GameConfig.enableDebug=true] - Enable {@link Phaser.Utils.Debug}. You can gain a little performance by disabling this in production. + * @property {boolean} [GameConfig.failIfMajorPerformanceCaveat] - Abort WebGL context creation if performance would be poor. You can use this with renderer AUTO. + * @property {boolean} [GameConfig.forceSetTimeout] - Use {@link https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout setTimeOut} for the game loop even if {@link https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame requestAnimationFrame} is available. + * @property {number} [GameConfig.fullScreenScaleMode] - The scaling method used by the ScaleManager when in fullscreen. + * @property {HTMLElement} [GameConfig.fullScreenTarget] - The DOM element on which the Fullscreen API enter request will be invoked. + * @property {number|string} [GameConfig.height=600] + * @property {boolean} [GameConfig.keyboard=true] - Starts the keyboard input handler. + * @property {number} [GameConfig.maxPointers=-1] - Sets {@link Phaser.Input#maxPointers}. + * @property {boolean} [GameConfig.mouse=true] - Starts the mouse input handler, if the mspointer and touch handlers were not started. + * @property {boolean} [GameConfig.mouseWheel=true] - Starts the {@link Phaser.MouseWheel mouse wheel} handler, if supported by the device. + * @property {boolean} [GameConfig.mspointer=true] - Starts the {@link Phaser.MSPointer Pointer Events} handler (mspointer), if supported by the device. + * @property {boolean} [GameConfig.multiTexture=false] - Enable support for multiple bound Textures in WebGL. Same as `{renderer: Phaser.WEBGL_MULTI}`. + * @property {string|HTMLElement} [GameConfig.parent=''] - The DOM element into which this games canvas will be injected. + * @property {object} [GameConfig.physicsConfig] + * @property {boolean} [GameConfig.pointerLock=true] - Starts the {@link Phaser.PointerLock Pointer Lock} handler, if supported by the device. + * @property {string} [GameConfig.powerPreference='default'] - Sets the WebGL renderer's powerPreference when the WebGL renderer is used. + * @property {boolean} [GameConfig.preserveDrawingBuffer=false] - Whether or not the contents of the stencil buffer is retained after rendering. + * @property {number} [GameConfig.renderer=Phaser.AUTO] + * @property {number} [GameConfig.resolution=1] - The resolution of your game, as a ratio of canvas pixels to game pixels. + * @property {boolean} [GameConfig.roundPixels=false] - Round pixel coordinates for rendering (rather than interpolating). Handy for crisp pixel art and speed on legacy devices. + * @property {number} [GameConfig.scaleH=1] - Horizontal scaling factor for USER_SCALE scale mode. + * @property {number} [GameConfig.scaleMode] - The scaling method used by the ScaleManager when not in fullscreen. + * @property {number} [GameConfig.scaleV=1] - Vertical scaling factor for USER_SCALE scale mode. + * @property {number} [GameConfig.seed] - Seed for {@link Phaser.RandomDataGenerator}. + * @property {object} [GameConfig.state] + * @property {boolean} [GameConfig.touch=true] - Starts the {@link Phaser.Touch touch} handler, if supported by the device and the Pointer Events handler (mspointer) was not started. + * @property {boolean|string} [GameConfig.transparent=false] - Sets {@link Phaser.Game#transparent}. `'notMultiplied'` disables the WebGL context attribute `premultipliedAlpha`. + * @property {number} [GameConfig.trimH=0] - Horizontal trim for USER_SCALE scale mode. + * @property {number} [GameConfig.trimV=0] - Vertical trim for USER_SCALE scale mode. + * @property {number|string} [GameConfig.width=800] + */ // Documentation stub for linking. Phaser.Game.prototype = { /** - * Parses a Game configuration object. - * - * @method Phaser.Game#parseConfig - * @protected - */ + * Parses a Game configuration object. + * + * @method Phaser.Game#parseConfig + * @protected + */ parseConfig: function (config) { - this.config = config; if (config.enableDebug === undefined) @@ -684,18 +681,16 @@ Phaser.Game.prototype = { } this.state = new Phaser.StateManager(this, state); - }, /** - * Initialize engine sub modules and start the game. - * - * @method Phaser.Game#boot - * @protected - */ + * Initialize engine sub modules and start the game. + * + * @method Phaser.Game#boot + * @protected + */ boot: function () { - if (this.isBooted) { return; @@ -785,18 +780,16 @@ Phaser.Game.prototype = { this.raf.start(); }, this); } - }, /** - * Displays a Phaser version debug header in the console. - * - * @method Phaser.Game#showDebugHeader - * @protected - */ + * Displays a Phaser version debug header in the console. + * + * @method Phaser.Game#showDebugHeader + * @protected + */ showDebugHeader: function () { - if (window.PhaserGlobal && window.PhaserGlobal.hideBanner) { return; @@ -853,18 +846,16 @@ Phaser.Game.prototype = { { console.log('Phaser v' + v + ' | Pixi.js | ' + r + ' | ' + a + ' | http://phaser.io'); } - }, /** - * Checks if the device is capable of using the requested renderer and sets it up or an alternative if not. - * - * @method Phaser.Game#setUpRenderer - * @protected - */ + * Checks if the device is capable of using the requested renderer and sets it up or an alternative if not. + * + * @method Phaser.Game#setUpRenderer + * @protected + */ setUpRenderer: function () { - if (!this.device.canvas) { // Nothing else to do @@ -950,52 +941,46 @@ Phaser.Game.prototype = { Phaser.Canvas.addToDOM(this.canvas, this.parent, false); Phaser.Canvas.setTouchAction(this.canvas); } - }, /** - * Handles WebGL context loss. - * - * @method Phaser.Game#contextLost - * @private - * @param {Event} event - The webglcontextlost event. - */ + * Handles WebGL context loss. + * + * @method Phaser.Game#contextLost + * @private + * @param {Event} event - The webglcontextlost event. + */ contextLost: function (event) { - event.preventDefault(); this.renderer.contextLost = true; - }, /** - * Handles WebGL context restoration. - * - * @method Phaser.Game#contextRestored - * @private - */ + * Handles WebGL context restoration. + * + * @method Phaser.Game#contextRestored + * @private + */ contextRestored: function () { - this.renderer.initContext(); this.cache.clearGLTextures(); this.renderer.contextLost = false; - }, /** - * The core game loop. - * - * @method Phaser.Game#update - * @protected - * @param {number} time - The current time as provided by RequestAnimationFrame. - */ + * The core game loop. + * + * @method Phaser.Game#update + * @protected + * @param {number} time - The current time as provided by RequestAnimationFrame. + */ update: function (time) { - if (this.pendingDestroy) { this.destroy(); @@ -1052,8 +1037,10 @@ Phaser.Game.prototype = { // accumulate time until the slowStep threshold is met or exceeded... up to a limit of `maxUpdates` (3) catch-up frames at slowStep intervals this._deltaTime += Math.max(Math.min(slowStep * this.maxUpdates, this.time.elapsed), 0); - // call the game update logic multiple times if necessary to "catch up" with dropped frames - // unless forceSingleUpdate is true + /* + * call the game update logic multiple times if necessary to "catch up" with dropped frames + * unless forceSingleUpdate is true + */ var count = 0; this.updatesThisFrame = Math.floor(this._deltaTime / slowStep); @@ -1115,19 +1102,17 @@ Phaser.Game.prototype = { // flush gl to prevent flickering on some android devices this.renderer.gl.flush(); } - }, /** - * Updates all logic subsystems in Phaser. Called automatically by Game.update. - * - * @method Phaser.Game#updateLogic - * @protected - * @param {number} timeStep - The current timeStep value as determined by Game.update. - */ + * Updates all logic subsystems in Phaser. Called automatically by Game.update. + * + * @method Phaser.Game#updateLogic + * @protected + * @param {number} timeStep - The current timeStep value as determined by Game.update. + */ updateLogic: function (timeStep) { - if (!this._paused && !this.pendingStep) { if (this.stepping) @@ -1167,27 +1152,25 @@ Phaser.Game.prototype = { } this.stage.updateTransform(); - }, /** - * Runs the Render cycle. - * It starts by calling State.preRender. In here you can do any last minute adjustments of display objects as required. - * It then calls the renderer, which renders the entire display list, starting from the Stage object and working down. - * It then calls plugin.render on any loaded plugins, in the order in which they were enabled. - * After this State.render is called. Any rendering that happens here will take place on-top of the display list. - * Finally plugin.postRender is called on any loaded plugins, in the order in which they were enabled. - * This method is called automatically by Game.update, you don't need to call it directly. - * Should you wish to have fine-grained control over when Phaser renders then use the `Game.lockRender` boolean. - * Phaser will only render when this boolean is `false`. - * - * @method Phaser.Game#updateRender - * @protected - * @param {number} elapsedTime - The time elapsed since the last update. - */ + * Runs the Render cycle. + * It starts by calling State.preRender. In here you can do any last minute adjustments of display objects as required. + * It then calls the renderer, which renders the entire display list, starting from the Stage object and working down. + * It then calls plugin.render on any loaded plugins, in the order in which they were enabled. + * After this State.render is called. Any rendering that happens here will take place on-top of the display list. + * Finally plugin.postRender is called on any loaded plugins, in the order in which they were enabled. + * This method is called automatically by Game.update, you don't need to call it directly. + * Should you wish to have fine-grained control over when Phaser renders then use the `Game.lockRender` boolean. + * Phaser will only render when this boolean is `false`. + * + * @method Phaser.Game#updateRender + * @protected + * @param {number} elapsedTime - The time elapsed since the last update. + */ updateRender: function (elapsedTime) { - if (this.lockRender || this.renderType === Phaser.HEADLESS) { return; @@ -1204,66 +1187,58 @@ Phaser.Game.prototype = { this.state.render(elapsedTime); this.plugins.postRender(elapsedTime); - }, /** - * Enable core game loop stepping. When enabled you must call game.step() directly (perhaps via a DOM button?) - * Calling step will advance the game loop by one frame. This is extremely useful for hard to track down errors! - * - * @method Phaser.Game#enableStep - */ + * Enable core game loop stepping. When enabled you must call game.step() directly (perhaps via a DOM button?) + * Calling step will advance the game loop by one frame. This is extremely useful for hard to track down errors! + * + * @method Phaser.Game#enableStep + */ enableStep: function () { - this.stepping = true; this.pendingStep = false; this.stepCount = 0; - }, /** - * Disables core game loop stepping. - * - * @method Phaser.Game#disableStep - */ + * Disables core game loop stepping. + * + * @method Phaser.Game#disableStep + */ disableStep: function () { - this.stepping = false; this.pendingStep = false; - }, /** - * When stepping is enabled you must call this function directly (perhaps via a DOM button?) to advance the game loop by one frame. - * This is extremely useful to hard to track down errors! Use the internal stepCount property to monitor progress. - * - * @method Phaser.Game#step - */ + * When stepping is enabled you must call this function directly (perhaps via a DOM button?) to advance the game loop by one frame. + * This is extremely useful to hard to track down errors! Use the internal stepCount property to monitor progress. + * + * @method Phaser.Game#step + */ step: function () { - this.pendingStep = false; this.stepCount++; - }, /** - * Nukes the entire game from orbit. - * - * Calls destroy on Game.state, Game.sound, Game.scale, Game.stage, Game.input, Game.physics and Game.plugins. - * - * Then sets all of those local handlers to null, destroys the renderer, removes the canvas from the DOM - * and resets the PIXI default renderer. - * - * To destroy the game during an update callback, set {@link #pendingDestroy} instead. - * - * @method Phaser.Game#destroy - */ + * Nukes the entire game from orbit. + * + * Calls destroy on Game.state, Game.sound, Game.scale, Game.stage, Game.input, Game.physics and Game.plugins. + * + * Then sets all of those local handlers to null, destroys the renderer, removes the canvas from the DOM + * and resets the PIXI default renderer. + * + * To destroy the game during an update callback, set {@link #pendingDestroy} instead. + * + * @method Phaser.Game#destroy + */ destroy: function () { - this.raf.stop(); this.debug.destroy(); @@ -1304,19 +1279,17 @@ Phaser.Game.prototype = { PIXI.defaultRenderer = null; Phaser.GAMES[this.id] = null; - }, /** - * Called by the Stage visibility handler. - * - * @method Phaser.Game#gamePaused - * @param {object} event - The DOM event that caused the game to pause, if any. - * @protected - */ + * Called by the Stage visibility handler. + * + * @method Phaser.Game#gamePaused + * @param {object} event - The DOM event that caused the game to pause, if any. + * @protected + */ gamePaused: function (event) { - // If the game is already paused it was done via game code, so don't re-pause it if (!this._paused) { @@ -1337,19 +1310,17 @@ Phaser.Game.prototype = { this.lockRender = true; } } - }, /** - * Called by the Stage visibility handler. - * - * @method Phaser.Game#gameResumed - * @param {object} event - The DOM event that caused the game to pause, if any. - * @protected - */ + * Called by the Stage visibility handler. + * + * @method Phaser.Game#gameResumed + * @param {object} event - The DOM event that caused the game to pause, if any. + * @protected + */ gameResumed: function (event) { - // Game is paused, but wasn't paused via code, so resume it if (this._paused && !this._codePaused) { @@ -1372,38 +1343,34 @@ Phaser.Game.prototype = { this.lockRender = false; } } - }, /** - * Called by the Stage visibility handler. - * - * @method Phaser.Game#focusLoss - * @param {object} event - The DOM event that caused the game to pause, if any. - * @protected - */ + * Called by the Stage visibility handler. + * + * @method Phaser.Game#focusLoss + * @param {object} event - The DOM event that caused the game to pause, if any. + * @protected + */ focusLoss: function (event) { - this.onBlur.dispatch(event); if (!this.stage.disableVisibilityChange) { this.gamePaused(event); } - }, /** - * Called by the Stage visibility handler. - * - * @method Phaser.Game#focusGain - * @param {object} event - The DOM event that caused the game to pause, if any. - * @protected - */ + * Called by the Stage visibility handler. + * + * @method Phaser.Game#focusGain + * @param {object} event - The DOM event that caused the game to pause, if any. + * @protected + */ focusGain: function (event) { - this.focusWindow(); this.onFocus.dispatch(event); @@ -1412,17 +1379,15 @@ Phaser.Game.prototype = { { this.gameResumed(event); } - }, /** - * Try to focus the browsing context, unless prohibited by PhaserGlobal.stopFocus. - * - * @private - */ + * Try to focus the browsing context, unless prohibited by PhaserGlobal.stopFocus. + * + * @private + */ focusWindow: function () { - if (window.focus) { if (!window.PhaserGlobal || (window.PhaserGlobal && !window.PhaserGlobal.stopFocus)) @@ -1430,7 +1395,6 @@ Phaser.Game.prototype = { window.focus(); } } - } }; @@ -1438,11 +1402,11 @@ Phaser.Game.prototype = { Phaser.Game.prototype.constructor = Phaser.Game; /** -* The paused state of the Game. A paused game doesn't update any of its subsystems. -* When a game is paused the onPause event is dispatched. When it is resumed the onResume event is dispatched. -* @name Phaser.Game#paused -* @property {boolean} paused - Gets and sets the paused state of the Game. -*/ + * The paused state of the Game. A paused game doesn't update any of its subsystems. + * When a game is paused the onPause event is dispatched. When it is resumed the onResume event is dispatched. + * @name Phaser.Game#paused + * @property {boolean} paused - Gets and sets the paused state of the Game. + */ Object.defineProperty(Phaser.Game.prototype, 'paused', { get: function () @@ -1452,7 +1416,6 @@ Object.defineProperty(Phaser.Game.prototype, 'paused', { set: function (value) { - if (value === true) { if (this._paused === false) @@ -1479,7 +1442,6 @@ Object.defineProperty(Phaser.Game.prototype, 'paused', { } this._codePaused = false; } - } }); @@ -1490,4 +1452,4 @@ Object.defineProperty(Phaser.Game.prototype, 'paused', { * * ヽ(〃^▽^〃)ノ * -*/ + */ diff --git a/src/core/Group.js b/src/core/Group.js index 347ccbfbd..ffe1b2342 100644 --- a/src/core/Group.js +++ b/src/core/Group.js @@ -1,41 +1,40 @@ /** -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ - -/** -* A Group is a container for {@link DisplayObject display objects} including {@link Phaser.Sprite Sprites} and {@link Phaser.Image Images}. -* -* Groups form the logical tree structure of the display/scene graph where local transformations are applied to children. -* For instance, all children are also moved/rotated/scaled when the group is moved/rotated/scaled. -* -* In addition, Groups provides support for fast pooling and object recycling. -* -* Groups are also display objects and can be nested as children within other Groups. -* -* @class Phaser.Group -* @extends PIXI.DisplayObjectContainer -* @param {Phaser.Game} game - A reference to the currently running game. -* @param {DisplayObject|null} [parent=(game world)] - The parent Group (or other {@link DisplayObject}) that this group will be added to. -* If undefined/unspecified the Group will be added to the {@link Phaser.Game#world Game World}; if null the Group will not be added to any parent. -* @param {string} [name='group'] - A name for this group. Not used internally but useful for debugging. -* @param {boolean} [addToStage=false] - If true this group will be added directly to the Game.Stage instead of Game.World. -* @param {boolean} [enableBody=false] - If true all Sprites created with {@link #create} or {@link #createMulitple} will have a physics body created on them. Change the body type with {@link #physicsBodyType}. -* @param {integer} [physicsBodyType=0] - The physics body type to use when physics bodies are automatically added. See {@link #physicsBodyType} for values. -*/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ + +/** + * A Group is a container for {@link DisplayObject display objects} including {@link Phaser.Sprite Sprites} and {@link Phaser.Image Images}. + * + * Groups form the logical tree structure of the display/scene graph where local transformations are applied to children. + * For instance, all children are also moved/rotated/scaled when the group is moved/rotated/scaled. + * + * In addition, Groups provides support for fast pooling and object recycling. + * + * Groups are also display objects and can be nested as children within other Groups. + * + * @class Phaser.Group + * @extends PIXI.DisplayObjectContainer + * @param {Phaser.Game} game - A reference to the currently running game. + * @param {DisplayObject|null} [parent=(game world)] - The parent Group (or other {@link DisplayObject}) that this group will be added to. + * If undefined/unspecified the Group will be added to the {@link Phaser.Game#world Game World}; if null the Group will not be added to any parent. + * @param {string} [name='group'] - A name for this group. Not used internally but useful for debugging. + * @param {boolean} [addToStage=false] - If true this group will be added directly to the Game.Stage instead of Game.World. + * @param {boolean} [enableBody=false] - If true all Sprites created with {@link #create} or {@link #createMulitple} will have a physics body created on them. Change the body type with {@link #physicsBodyType}. + * @param {integer} [physicsBodyType=0] - The physics body type to use when physics bodies are automatically added. See {@link #physicsBodyType} for values. + */ Phaser.Group = function (game, parent, name, addToStage, enableBody, physicsBodyType) { - if (addToStage === undefined) { addToStage = false; } if (enableBody === undefined) { enableBody = false; } if (physicsBodyType === undefined) { physicsBodyType = Phaser.Physics.ARCADE; } /** - * A reference to the currently running Game. - * @property {Phaser.Game} game - * @protected - */ + * A reference to the currently running Game. + * @property {Phaser.Game} game + * @protected + */ this.game = game; if (parent === undefined) @@ -44,17 +43,17 @@ Phaser.Group = function (game, parent, name, addToStage, enableBody, physicsBody } /** - * A name for this group. Not used internally but useful for debugging. - * @property {string} name - */ + * A name for this group. Not used internally but useful for debugging. + * @property {string} name + */ this.name = name || 'group'; /** - * The z-depth value of this object within its parent container/Group - the World is a Group as well. - * This value must be unique for each child in a Group. - * @property {integer} z - * @readOnly - */ + * The z-depth value of this object within its parent container/Group - the World is a Group as well. + * This value must be unique for each child in a Group. + * @property {integer} z + * @readOnly + */ this.z = 0; PIXI.DisplayObjectContainer.call(this); @@ -72,303 +71,301 @@ Phaser.Group = function (game, parent, name, addToStage, enableBody, physicsBody } /** - * Internal Phaser Type value. - * @property {integer} type - * @protected - */ + * Internal Phaser Type value. + * @property {integer} type + * @protected + */ this.type = Phaser.GROUP; /** - * @property {number} physicsType - The const physics body type of this object. - * @readonly - */ + * @property {number} physicsType - The const physics body type of this object. + * @readonly + */ this.physicsType = Phaser.GROUP; /** - * The alive property is useful for Groups that are children of other Groups and need to be included/excluded in checks like forEachAlive. - * @property {boolean} alive - * @default - */ + * The alive property is useful for Groups that are children of other Groups and need to be included/excluded in checks like forEachAlive. + * @property {boolean} alive + * @default + */ this.alive = true; /** - * If exists is false the group will be excluded from collision checks and filters such as {@link #forEachExists}. The group will not call `preUpdate` and `postUpdate` on its children and the children will not receive physics updates or camera/world boundary checks. The group will still be {@link #visible} and will still call `update` on its children (unless {@link #updateOnlyExistingChildren} is true). - * @property {boolean} exists - * @default - */ + * If exists is false the group will be excluded from collision checks and filters such as {@link #forEachExists}. The group will not call `preUpdate` and `postUpdate` on its children and the children will not receive physics updates or camera/world boundary checks. The group will still be {@link #visible} and will still call `update` on its children (unless {@link #updateOnlyExistingChildren} is true). + * @property {boolean} exists + * @default + */ this.exists = true; /** - * A group with `ignoreDestroy` set to `true` ignores all calls to its `destroy` method. - * @property {boolean} ignoreDestroy - * @default - */ + * A group with `ignoreDestroy` set to `true` ignores all calls to its `destroy` method. + * @property {boolean} ignoreDestroy + * @default + */ this.ignoreDestroy = false; /** - * A Group is that has `pendingDestroy` set to `true` is flagged to have its destroy method - * called on the next logic update. - * You can set it directly to flag the Group to be destroyed on its next update. - * - * This is extremely useful if you wish to destroy a Group from within one of its own callbacks - * or a callback of one of its children. - * - * @property {boolean} pendingDestroy - */ + * A Group is that has `pendingDestroy` set to `true` is flagged to have its destroy method + * called on the next logic update. + * You can set it directly to flag the Group to be destroyed on its next update. + * + * This is extremely useful if you wish to destroy a Group from within one of its own callbacks + * or a callback of one of its children. + * + * @property {boolean} pendingDestroy + */ this.pendingDestroy = false; /** - * The type of objects that will be created when using {@link #create} or {@link #createMultiple}. - * - * It should extend either Sprite or Image and accept the same constructor arguments: `(game, x, y, key, frame)`. - * - * @property {function} classType - * @default {@link Phaser.Sprite} - */ + * The type of objects that will be created when using {@link #create} or {@link #createMultiple}. + * + * It should extend either Sprite or Image and accept the same constructor arguments: `(game, x, y, key, frame)`. + * + * @property {function} classType + * @default {@link Phaser.Sprite} + */ this.classType = Phaser.Sprite; /** - * The current display object that the group cursor is pointing to, if any. (Can be set manually.) - * - * The cursor is a way to iterate through the children in a Group using {@link #next} and {@link #previous}. - * @property {?DisplayObject} cursor - */ + * The current display object that the group cursor is pointing to, if any. (Can be set manually.) + * + * The cursor is a way to iterate through the children in a Group using {@link #next} and {@link #previous}. + * @property {?DisplayObject} cursor + */ this.cursor = null; /** - * A Group with `inputEnableChildren` set to `true` will automatically call `inputEnabled = true` - * on any children _added_ to, or _created by_, this Group. - * - * If there are children already in the Group at the time you set this property, they are not changed. - * - * @property {boolean} inputEnableChildren - * @default - */ + * A Group with `inputEnableChildren` set to `true` will automatically call `inputEnabled = true` + * on any children _added_ to, or _created by_, this Group. + * + * If there are children already in the Group at the time you set this property, they are not changed. + * + * @property {boolean} inputEnableChildren + * @default + */ this.inputEnableChildren = false; /** - * Skip children with `exists = false` in {@link #update}. - * - * @property {boolean} updateOnlyExistingChildren - * @default - */ + * Skip children with `exists = false` in {@link #update}. + * + * @property {boolean} updateOnlyExistingChildren + * @default + */ this.updateOnlyExistingChildren = false; /** - * This Signal is dispatched whenever a child of this Group emits an onInputDown signal as a result - * of having been interacted with by a Pointer. You can bind functions to this Signal instead of to - * every child Sprite. - * - * This Signal is sent 2 arguments: A reference to the Sprite that triggered the signal, and - * a reference to the Pointer that caused it. - * - * @property {Phaser.Signal} onChildInputDown - */ + * This Signal is dispatched whenever a child of this Group emits an onInputDown signal as a result + * of having been interacted with by a Pointer. You can bind functions to this Signal instead of to + * every child Sprite. + * + * This Signal is sent 2 arguments: A reference to the Sprite that triggered the signal, and + * a reference to the Pointer that caused it. + * + * @property {Phaser.Signal} onChildInputDown + */ this.onChildInputDown = new Phaser.Signal(); /** - * This Signal is dispatched whenever a child of this Group emits an onInputUp signal as a result - * of having been interacted with by a Pointer. You can bind functions to this Signal instead of to - * every child Sprite. - * - * This Signal is sent 3 arguments: A reference to the Sprite that triggered the signal, - * a reference to the Pointer that caused it, and a boolean value `isOver` that tells you if the Pointer - * is still over the Sprite or not. - * - * @property {Phaser.Signal} onChildInputUp - */ + * This Signal is dispatched whenever a child of this Group emits an onInputUp signal as a result + * of having been interacted with by a Pointer. You can bind functions to this Signal instead of to + * every child Sprite. + * + * This Signal is sent 3 arguments: A reference to the Sprite that triggered the signal, + * a reference to the Pointer that caused it, and a boolean value `isOver` that tells you if the Pointer + * is still over the Sprite or not. + * + * @property {Phaser.Signal} onChildInputUp + */ this.onChildInputUp = new Phaser.Signal(); /** - * This Signal is dispatched whenever a child of this Group emits an onInputOver signal as a result - * of having been interacted with by a Pointer. You can bind functions to this Signal instead of to - * every child Sprite. - * - * This Signal is sent 2 arguments: A reference to the Sprite that triggered the signal, and - * a reference to the Pointer that caused it. - * - * @property {Phaser.Signal} onChildInputOver - */ + * This Signal is dispatched whenever a child of this Group emits an onInputOver signal as a result + * of having been interacted with by a Pointer. You can bind functions to this Signal instead of to + * every child Sprite. + * + * This Signal is sent 2 arguments: A reference to the Sprite that triggered the signal, and + * a reference to the Pointer that caused it. + * + * @property {Phaser.Signal} onChildInputOver + */ this.onChildInputOver = new Phaser.Signal(); /** - * This Signal is dispatched whenever a child of this Group emits an onInputOut signal as a result - * of having been interacted with by a Pointer. You can bind functions to this Signal instead of to - * every child Sprite. - * - * This Signal is sent 2 arguments: A reference to the Sprite that triggered the signal, and - * a reference to the Pointer that caused it. - * - * @property {Phaser.Signal} onChildInputOut - */ + * This Signal is dispatched whenever a child of this Group emits an onInputOut signal as a result + * of having been interacted with by a Pointer. You can bind functions to this Signal instead of to + * every child Sprite. + * + * This Signal is sent 2 arguments: A reference to the Sprite that triggered the signal, and + * a reference to the Pointer that caused it. + * + * @property {Phaser.Signal} onChildInputOut + */ this.onChildInputOut = new Phaser.Signal(); /** - * If true all Sprites created by, or added to this group, will have a physics body enabled on them. - * - * If there are children already in the Group at the time you set this property, they are not changed. - * - * The default body type is controlled with {@link #physicsBodyType}. - * @property {boolean} enableBody - */ + * If true all Sprites created by, or added to this group, will have a physics body enabled on them. + * + * If there are children already in the Group at the time you set this property, they are not changed. + * + * The default body type is controlled with {@link #physicsBodyType}. + * @property {boolean} enableBody + */ this.enableBody = enableBody; /** - * If true when a physics body is created (via {@link #enableBody}) it will create a physics debug object as well. - * - * This only works for P2 bodies. - * @property {boolean} enableBodyDebug - * @default - */ + * If true when a physics body is created (via {@link #enableBody}) it will create a physics debug object as well. + * + * This only works for P2 bodies. + * @property {boolean} enableBodyDebug + * @default + */ this.enableBodyDebug = false; /** - * If {@link #enableBody} is true this is the type of physics body that is created on new Sprites. - * - * The valid values are {@link Phaser.Physics.ARCADE}, {@link Phaser.Physics.P2JS}, {@link Phaser.Physics.NINJA}, etc. - * @property {integer} physicsBodyType - */ + * If {@link #enableBody} is true this is the type of physics body that is created on new Sprites. + * + * The valid values are {@link Phaser.Physics.ARCADE}, {@link Phaser.Physics.P2JS}, {@link Phaser.Physics.NINJA}, etc. + * @property {integer} physicsBodyType + */ this.physicsBodyType = physicsBodyType; /** - * If this Group contains Arcade Physics Sprites you can set a custom sort direction via this property. - * - * It should be set to one of the Phaser.Physics.Arcade sort direction constants: - * - * Phaser.Physics.Arcade.SORT_NONE - * Phaser.Physics.Arcade.LEFT_RIGHT - * Phaser.Physics.Arcade.RIGHT_LEFT - * Phaser.Physics.Arcade.TOP_BOTTOM - * Phaser.Physics.Arcade.BOTTOM_TOP - * - * If set to `null` the Group will use whatever Phaser.Physics.Arcade.sortDirection is set to. This is the default behavior. - * - * @property {integer} physicsSortDirection - * @default - */ + * If this Group contains Arcade Physics Sprites you can set a custom sort direction via this property. + * + * It should be set to one of the Phaser.Physics.Arcade sort direction constants: + * + * Phaser.Physics.Arcade.SORT_NONE + * Phaser.Physics.Arcade.LEFT_RIGHT + * Phaser.Physics.Arcade.RIGHT_LEFT + * Phaser.Physics.Arcade.TOP_BOTTOM + * Phaser.Physics.Arcade.BOTTOM_TOP + * + * If set to `null` the Group will use whatever Phaser.Physics.Arcade.sortDirection is set to. This is the default behavior. + * + * @property {integer} physicsSortDirection + * @default + */ this.physicsSortDirection = null; /** - * This signal is dispatched when the group is destroyed. - * @property {Phaser.Signal} onDestroy - */ + * This signal is dispatched when the group is destroyed. + * @property {Phaser.Signal} onDestroy + */ this.onDestroy = new Phaser.Signal(); /** - * @property {integer} cursorIndex - The current index of the Group cursor. Advance it with Group.next. - * @readOnly - */ + * @property {integer} cursorIndex - The current index of the Group cursor. Advance it with Group.next. + * @readOnly + */ this.cursorIndex = 0; /** - * A Group that is fixed to the camera uses its x/y coordinates as offsets from the top left of the camera. These are stored in Group.cameraOffset. - * - * Note that the cameraOffset values are in addition to any parent in the display list. - * So if this Group was in a Group that has x: 200, then this will be added to the cameraOffset.x - * - * @property {boolean} fixedToCamera - */ + * A Group that is fixed to the camera uses its x/y coordinates as offsets from the top left of the camera. These are stored in Group.cameraOffset. + * + * Note that the cameraOffset values are in addition to any parent in the display list. + * So if this Group was in a Group that has x: 200, then this will be added to the cameraOffset.x + * + * @property {boolean} fixedToCamera + */ this.fixedToCamera = false; /** - * If this object is {@link #fixedToCamera} then this stores the x/y position offset relative to the top-left of the camera view. - * If the parent of this Group is also `fixedToCamera` then the offset here is in addition to that and should typically be disabled. - * @property {Phaser.Point} cameraOffset - */ + * If this object is {@link #fixedToCamera} then this stores the x/y position offset relative to the top-left of the camera view. + * If the parent of this Group is also `fixedToCamera` then the offset here is in addition to that and should typically be disabled. + * @property {Phaser.Point} cameraOffset + */ this.cameraOffset = new Phaser.Point(); /** - * The hash array is an array belonging to this Group into which you can add any of its children via Group.addToHash and Group.removeFromHash. - * - * Only children of this Group can be added to and removed from the hash. - * - * This hash is used automatically by Phaser Arcade Physics in order to perform non z-index based destructive sorting. - * However if you don't use Arcade Physics, or this isn't a physics enabled Group, then you can use the hash to perform your own - * sorting and filtering of Group children without touching their z-index (and therefore display draw order) - * - * @property {array} hash - */ + * The hash array is an array belonging to this Group into which you can add any of its children via Group.addToHash and Group.removeFromHash. + * + * Only children of this Group can be added to and removed from the hash. + * + * This hash is used automatically by Phaser Arcade Physics in order to perform non z-index based destructive sorting. + * However if you don't use Arcade Physics, or this isn't a physics enabled Group, then you can use the hash to perform your own + * sorting and filtering of Group children without touching their z-index (and therefore display draw order) + * + * @property {array} hash + */ this.hash = []; /** - * The property on which children are sorted. - * @property {string} _sortProperty - * @private - */ + * The property on which children are sorted. + * @property {string} _sortProperty + * @private + */ this._sortProperty = 'z'; - }; Phaser.Group.prototype = Object.create(PIXI.DisplayObjectContainer.prototype); Phaser.Group.prototype.constructor = Phaser.Group; /** -* A returnType value, as specified in {@link #iterate} eg. -* @constant -* @type {integer} -*/ + * A returnType value, as specified in {@link #iterate} eg. + * @constant + * @type {integer} + */ Phaser.Group.RETURN_NONE = 0; /** -* A returnType value, as specified in {@link #iterate} eg. -* @constant -* @type {integer} -*/ + * A returnType value, as specified in {@link #iterate} eg. + * @constant + * @type {integer} + */ Phaser.Group.RETURN_TOTAL = 1; /** -* A returnType value, as specified in {@link #iterate} eg. -* @constant -* @type {integer} -*/ + * A returnType value, as specified in {@link #iterate} eg. + * @constant + * @type {integer} + */ Phaser.Group.RETURN_CHILD = 2; /** -* A returnType value, as specified in {@link #iterate} eg. -* @constant -* @type {integer} -*/ + * A returnType value, as specified in {@link #iterate} eg. + * @constant + * @type {integer} + */ Phaser.Group.RETURN_ALL = 3; /** -* A sort ordering value, as specified in {@link #sort} eg. -* @constant -* @type {integer} -*/ + * A sort ordering value, as specified in {@link #sort} eg. + * @constant + * @type {integer} + */ Phaser.Group.SORT_ASCENDING = -1; /** -* A sort ordering value, as specified in {@link #sort} eg. -* @constant -* @type {integer} -*/ + * A sort ordering value, as specified in {@link #sort} eg. + * @constant + * @type {integer} + */ Phaser.Group.SORT_DESCENDING = 1; /** -* Adds an existing object as the top child in this group. -* -* The child is automatically added to the top of the group, and is displayed above every previous child. -* -* Or if the _optional_ index is specified, the child is added at the location specified by the index value, -* this allows you to control child ordering. -* -* If the child was already in this Group, it is simply returned, and nothing else happens to it. -* -* If `Group.enableBody` is set, then a physics body will be created on the object, so long as one does not already exist. -* -* If `Group.inputEnableChildren` is set, then an Input Handler will be created on the object, so long as one does not already exist. -* -* Use {@link #create} to create and add a new child. -* -* @method Phaser.Group#add -* @param {DisplayObject} child - The display object to add as a child. -* @param {boolean} [silent=false] - If true the child will not dispatch the `onAddedToGroup` event. -* @param {integer} [index] - The index within the group to insert the child to. Where 0 is the bottom of the Group. -* @return {DisplayObject} The child that was added to the group. -*/ + * Adds an existing object as the top child in this group. + * + * The child is automatically added to the top of the group, and is displayed above every previous child. + * + * Or if the _optional_ index is specified, the child is added at the location specified by the index value, + * this allows you to control child ordering. + * + * If the child was already in this Group, it is simply returned, and nothing else happens to it. + * + * If `Group.enableBody` is set, then a physics body will be created on the object, so long as one does not already exist. + * + * If `Group.inputEnableChildren` is set, then an Input Handler will be created on the object, so long as one does not already exist. + * + * Use {@link #create} to create and add a new child. + * + * @method Phaser.Group#add + * @param {DisplayObject} child - The display object to add as a child. + * @param {boolean} [silent=false] - If true the child will not dispatch the `onAddedToGroup` event. + * @param {integer} [index] - The index within the group to insert the child to. Where 0 is the bottom of the Group. + * @return {DisplayObject} The child that was added to the group. + */ Phaser.Group.prototype.add = function (child, silent, index) { - if (silent === undefined) { silent = false; } if (child.parent === this) @@ -419,42 +416,38 @@ Phaser.Group.prototype.add = function (child, silent, index) } return child; - }; /** -* Adds an existing object to this group. -* -* The child is added to the group at the location specified by the index value, this allows you to control child ordering. -* -* If `Group.enableBody` is set, then a physics body will be created on the object, so long as one does not already exist. -* -* If `Group.inputEnableChildren` is set, then an Input Handler will be created on the object, so long as one does not already exist. -* -* @method Phaser.Group#addAt -* @param {DisplayObject} child - The display object to add as a child. -* @param {integer} [index=0] - The index within the group to insert the child to. -* @param {boolean} [silent=false] - If true the child will not dispatch the `onAddedToGroup` event. -* @return {DisplayObject} The child that was added to the group. -*/ + * Adds an existing object to this group. + * + * The child is added to the group at the location specified by the index value, this allows you to control child ordering. + * + * If `Group.enableBody` is set, then a physics body will be created on the object, so long as one does not already exist. + * + * If `Group.inputEnableChildren` is set, then an Input Handler will be created on the object, so long as one does not already exist. + * + * @method Phaser.Group#addAt + * @param {DisplayObject} child - The display object to add as a child. + * @param {integer} [index=0] - The index within the group to insert the child to. + * @param {boolean} [silent=false] - If true the child will not dispatch the `onAddedToGroup` event. + * @return {DisplayObject} The child that was added to the group. + */ Phaser.Group.prototype.addAt = function (child, index, silent) { - return this.add(child, silent, index); - }; /** -* Adds a child of this Group into the hash array. -* This call will return false if the child is not a child of this Group, or is already in the hash. -* -* @method Phaser.Group#addToHash -* @param {DisplayObject} child - The display object to add to this Groups hash. Must be a member of this Group already and not present in the hash. -* @return {boolean} True if the child was successfully added to the hash, otherwise false. -*/ + * Adds a child of this Group into the hash array. + * This call will return false if the child is not a child of this Group, or is already in the hash. + * + * @method Phaser.Group#addToHash + * @param {DisplayObject} child - The display object to add to this Groups hash. Must be a member of this Group already and not present in the hash. + * @return {boolean} True if the child was successfully added to the hash, otherwise false. + */ Phaser.Group.prototype.addToHash = function (child) { - if (child.parent === this) { var index = this.hash.indexOf(child); @@ -467,20 +460,18 @@ Phaser.Group.prototype.addToHash = function (child) } return false; - }; /** -* Removes a child of this Group from the hash array. -* This call will return false if the child is not in the hash. -* -* @method Phaser.Group#removeFromHash -* @param {DisplayObject} child - The display object to remove from this Groups hash. Must be a member of this Group and in the hash. -* @return {boolean} True if the child was successfully removed from the hash, otherwise false. -*/ + * Removes a child of this Group from the hash array. + * This call will return false if the child is not in the hash. + * + * @method Phaser.Group#removeFromHash + * @param {DisplayObject} child - The display object to remove from this Groups hash. Must be a member of this Group and in the hash. + * @return {boolean} True if the child was successfully removed from the hash, otherwise false. + */ Phaser.Group.prototype.removeFromHash = function (child) { - if (child) { var index = this.hash.indexOf(child); @@ -493,29 +484,27 @@ Phaser.Group.prototype.removeFromHash = function (child) } return false; - }; /** -* Adds an array of existing Display Objects to this Group. -* -* The Display Objects are automatically added to the top of this Group, and will render on-top of everything already in this Group. -* -* As well as an array you can also pass another Group as the first argument. In this case all of the children from that -* Group will be removed from it and added into this Group. -* -* If `Group.enableBody` is set, then a physics body will be created on the objects, so long as one does not already exist. -* -* If `Group.inputEnableChildren` is set, then an Input Handler will be created on the objects, so long as one does not already exist. -* -* @method Phaser.Group#addMultiple -* @param {DisplayObject[]|Phaser.Group} children - An array of display objects or a Phaser.Group. If a Group is given then *all* children will be moved from it. -* @param {boolean} [silent=false] - If true the children will not dispatch the `onAddedToGroup` event. -* @return {DisplayObject[]|Phaser.Group} The array of children or Group of children that were added to this Group. -*/ + * Adds an array of existing Display Objects to this Group. + * + * The Display Objects are automatically added to the top of this Group, and will render on-top of everything already in this Group. + * + * As well as an array you can also pass another Group as the first argument. In this case all of the children from that + * Group will be removed from it and added into this Group. + * + * If `Group.enableBody` is set, then a physics body will be created on the objects, so long as one does not already exist. + * + * If `Group.inputEnableChildren` is set, then an Input Handler will be created on the objects, so long as one does not already exist. + * + * @method Phaser.Group#addMultiple + * @param {DisplayObject[]|Phaser.Group} children - An array of display objects or a Phaser.Group. If a Group is given then *all* children will be moved from it. + * @param {boolean} [silent=false] - If true the children will not dispatch the `onAddedToGroup` event. + * @return {DisplayObject[]|Phaser.Group} The array of children or Group of children that were added to this Group. + */ Phaser.Group.prototype.addMultiple = function (children, silent) { - if (children instanceof Phaser.Group) { children.moveAll(this, silent); @@ -529,19 +518,17 @@ Phaser.Group.prototype.addMultiple = function (children, silent) } return children; - }; /** -* Returns the child found at the given index within this group. -* -* @method Phaser.Group#getAt -* @param {integer} index - The index to return the child from. -* @return {DisplayObject|integer} The child that was found at the given index, or -1 for an invalid index. -*/ + * Returns the child found at the given index within this group. + * + * @method Phaser.Group#getAt + * @param {integer} index - The index to return the child from. + * @return {DisplayObject|integer} The child that was found at the given index, or -1 for an invalid index. + */ Phaser.Group.prototype.getAt = function (index) { - if (index < 0 || index >= this.children.length) { return -1; @@ -550,35 +537,33 @@ Phaser.Group.prototype.getAt = function (index) { return this.getChildAt(index); } - }; /** -* Creates a new Phaser.Sprite object and adds it to the top of this group. -* -* Use {@link #classType} to change the type of object created. -* -* The child is automatically added to the top of the group, and is displayed above every previous child. -* -* Or if the _optional_ index is specified, the child is added at the location specified by the index value, -* this allows you to control child ordering. -* -* If `Group.enableBody` is set, then a physics body will be created on the object, so long as one does not already exist. -* -* If `Group.inputEnableChildren` is set, then an Input Handler will be created on the object, so long as one does not already exist. -* -* @method Phaser.Group#create -* @param {number} x - The x coordinate to display the newly created Sprite at. The value is in relation to the group.x point. -* @param {number} y - The y coordinate to display the newly created Sprite at. The value is in relation to the group.y point. -* @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|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 Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. -* @param {string|number} [frame] - If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. -* @param {boolean} [exists=true] - The default exists state of the Sprite. -* @param {integer} [index] - The index within the group to insert the child to. Where 0 is the bottom of the Group. -* @return {DisplayObject} The child that was created: will be a {@link Phaser.Sprite} unless {@link #classType} has been changed. -*/ + * Creates a new Phaser.Sprite object and adds it to the top of this group. + * + * Use {@link #classType} to change the type of object created. + * + * The child is automatically added to the top of the group, and is displayed above every previous child. + * + * Or if the _optional_ index is specified, the child is added at the location specified by the index value, + * this allows you to control child ordering. + * + * If `Group.enableBody` is set, then a physics body will be created on the object, so long as one does not already exist. + * + * If `Group.inputEnableChildren` is set, then an Input Handler will be created on the object, so long as one does not already exist. + * + * @method Phaser.Group#create + * @param {number} x - The x coordinate to display the newly created Sprite at. The value is in relation to the group.x point. + * @param {number} y - The y coordinate to display the newly created Sprite at. The value is in relation to the group.y point. + * @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|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 Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. + * @param {string|number} [frame] - If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. + * @param {boolean} [exists=true] - The default exists state of the Sprite. + * @param {integer} [index] - The index within the group to insert the child to. Where 0 is the bottom of the Group. + * @return {DisplayObject} The child that was created: will be a {@link Phaser.Sprite} unless {@link #classType} has been changed. + */ Phaser.Group.prototype.create = function (x, y, key, frame, exists, index) { - if (exists === undefined) { exists = true; } var child = new this.classType(this.game, x, y, key, frame); @@ -588,61 +573,59 @@ Phaser.Group.prototype.create = function (x, y, key, frame, exists, index) child.alive = exists; return this.add(child, false, index); - }; /** -* Creates multiple Phaser.Sprite objects and adds them to the top of this Group. -* -* This method is useful if you need to quickly generate a pool of sprites, such as bullets. -* -* Use {@link #classType} to change the type of object created. -* -* You can provide an array as the `key` and / or `frame` arguments. When you do this -* it will create `quantity` Sprites for every key (and frame) in the arrays. -* -* For example: -* -* `createMultiple(25, ['ball', 'carrot'])` -* -* In the above code there are 2 keys (ball and carrot) which means that 50 sprites will be -* created in total, 25 of each. You can also have the `frame` as an array: -* -* `createMultiple(5, 'bricks', [0, 1, 2, 3])` -* -* In the above there is one key (bricks), which is a sprite sheet. The frames array tells -* this method to use frames 0, 1, 2 and 3. So in total it will create 20 sprites, because -* the quantity was set to 5, so that is 5 brick sprites of frame 0, 5 brick sprites with -* frame 1, and so on. -* -* If you set both the key and frame arguments to be arrays then understand it will create -* a total quantity of sprites equal to the size of both arrays times each other. I.e.: -* -* `createMultiple(20, ['diamonds', 'balls'], [0, 1, 2])` -* -* The above will create 20 'diamonds' of frame 0, 20 with frame 1 and 20 with frame 2. -* It will then create 20 'balls' of frame 0, 20 with frame 1 and 20 with frame 2. -* In total it will have created 120 sprites. -* -* By default the Sprites will have their `exists` property set to `false`, and they will be -* positioned at 0x0, relative to the `Group.x / y` values. -* -* If `Group.enableBody` is set, then a physics body will be created on the objects, so long as one does not already exist. -* -* If `Group.inputEnableChildren` is set, then an Input Handler will be created on the objects, so long as one does not already exist. -* -* @method Phaser.Group#createMultiple -* @param {integer} quantity - The number of Sprites to create. -* @param {string|array} key - The Cache key of the image that the Sprites will use. Or an Array of keys. See the description for details on how the quantity applies when arrays are used. -* @param {integer|string|array} [frame=0] - If the Sprite image contains multiple frames you can specify which one to use here. Or an Array of frames. See the description for details on how the quantity applies when arrays are used. -* @param {boolean} [exists=false] - The default exists state of the Sprite. -* @param {function} [callback] - The function that will be called for each applicable child. It will be passed the new child and the loop index (0 through quantity - 1). -* @param {object} [callbackContext] - The context in which the function should be called (usually 'this'). The default context is the new child. -* @return {array} An array containing all of the Sprites that were created. -*/ + * Creates multiple Phaser.Sprite objects and adds them to the top of this Group. + * + * This method is useful if you need to quickly generate a pool of sprites, such as bullets. + * + * Use {@link #classType} to change the type of object created. + * + * You can provide an array as the `key` and / or `frame` arguments. When you do this + * it will create `quantity` Sprites for every key (and frame) in the arrays. + * + * For example: + * + * `createMultiple(25, ['ball', 'carrot'])` + * + * In the above code there are 2 keys (ball and carrot) which means that 50 sprites will be + * created in total, 25 of each. You can also have the `frame` as an array: + * + * `createMultiple(5, 'bricks', [0, 1, 2, 3])` + * + * In the above there is one key (bricks), which is a sprite sheet. The frames array tells + * this method to use frames 0, 1, 2 and 3. So in total it will create 20 sprites, because + * the quantity was set to 5, so that is 5 brick sprites of frame 0, 5 brick sprites with + * frame 1, and so on. + * + * If you set both the key and frame arguments to be arrays then understand it will create + * a total quantity of sprites equal to the size of both arrays times each other. I.e.: + * + * `createMultiple(20, ['diamonds', 'balls'], [0, 1, 2])` + * + * The above will create 20 'diamonds' of frame 0, 20 with frame 1 and 20 with frame 2. + * It will then create 20 'balls' of frame 0, 20 with frame 1 and 20 with frame 2. + * In total it will have created 120 sprites. + * + * By default the Sprites will have their `exists` property set to `false`, and they will be + * positioned at 0x0, relative to the `Group.x / y` values. + * + * If `Group.enableBody` is set, then a physics body will be created on the objects, so long as one does not already exist. + * + * If `Group.inputEnableChildren` is set, then an Input Handler will be created on the objects, so long as one does not already exist. + * + * @method Phaser.Group#createMultiple + * @param {integer} quantity - The number of Sprites to create. + * @param {string|array} key - The Cache key of the image that the Sprites will use. Or an Array of keys. See the description for details on how the quantity applies when arrays are used. + * @param {integer|string|array} [frame=0] - If the Sprite image contains multiple frames you can specify which one to use here. Or an Array of frames. See the description for details on how the quantity applies when arrays are used. + * @param {boolean} [exists=false] - The default exists state of the Sprite. + * @param {function} [callback] - The function that will be called for each applicable child. It will be passed the new child and the loop index (0 through quantity - 1). + * @param {object} [callbackContext] - The context in which the function should be called (usually 'this'). The default context is the new child. + * @return {array} An array containing all of the Sprites that were created. + */ Phaser.Group.prototype.createMultiple = function (quantity, key, frame, exists, callback, callbackContext) { - if (frame === undefined) { frame = 0; } if (exists === undefined) { exists = false; } @@ -661,10 +644,8 @@ Phaser.Group.prototype.createMultiple = function (quantity, key, frame, exists, key.forEach(function (singleKey) { - frame.forEach(function (singleFrame) { - for (var i = 0; i < quantity; i++) { var child = _this.create(0, 0, singleKey, singleFrame, exists); @@ -673,90 +654,84 @@ Phaser.Group.prototype.createMultiple = function (quantity, key, frame, exists, children.push(child); } - }); - }); return children; - }; /** -* Internal method that re-applies all of the children's Z values. -* -* This must be called whenever children ordering is altered so that their `z` indices are correctly updated. -* -* @method Phaser.Group#updateZ -* @protected -*/ + * Internal method that re-applies all of the children's Z values. + * + * This must be called whenever children ordering is altered so that their `z` indices are correctly updated. + * + * @method Phaser.Group#updateZ + * @protected + */ Phaser.Group.prototype.updateZ = function () { - var i = this.children.length; while (i--) { this.children[i].z = i; } - }; /** -* This method iterates through all children in the Group (regardless if they are visible or exist) -* and then changes their position so they are arranged in a Grid formation. Children must have -* the `alignTo` method in order to be positioned by this call. All default Phaser Game Objects have -* this. -* -* The grid dimensions are determined by the first four arguments. The `width` and `height` arguments -* relate to the width and height of the grid respectively. -* -* For example if the Group had 100 children in it: -* -* `Group.align(10, 10, 32, 32)` -* -* This will align all of the children into a grid formation of 10x10, using 32 pixels per -* grid cell. If you want a wider grid, you could do: -* -* `Group.align(25, 4, 32, 32)` -* -* This will align the children into a grid of 25x4, again using 32 pixels per grid cell. -* -* You can choose to set _either_ the `width` or `height` value to -1. Doing so tells the method -* to keep on aligning children until there are no children left. For example if this Group had -* 48 children in it, the following: -* -* `Group.align(-1, 8, 32, 32)` -* -* ... will align the children so that there are 8 children vertically (the second argument), -* and each row will contain 6 sprites, except the last one, which will contain 5 (totaling 48) -* -* You can also do: -* -* `Group.align(10, -1, 32, 32)` -* -* In this case it will create a grid 10 wide, and as tall as it needs to be in order to fit -* all of the children in. -* -* The `position` property allows you to control where in each grid cell the child is positioned. -* This is a constant and can be one of `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`, -* `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, -* `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`. -* -* The final argument; `offset` lets you start the alignment from a specific child index. -* -* @method Phaser.Group#align -* @param {integer} width - The width of the grid in items (not pixels). Set to -1 for a dynamic width. If -1 then you must set an explicit height value. -* @param {integer} height - The height of the grid in items (not pixels). Set to -1 for a dynamic height. If -1 then you must set an explicit width value. -* @param {integer} cellWidth - The width of each grid cell, in pixels. -* @param {integer} cellHeight - The height of each grid cell, in pixels. -* @param {integer} [position] - The position constant. One of `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`. -* @param {integer} [offset=0] - Optional index to start the alignment from. Defaults to zero, the first child in the Group, but can be set to any valid child index value. -* @return {boolean} True if the Group children were aligned, otherwise false. -*/ + * This method iterates through all children in the Group (regardless if they are visible or exist) + * and then changes their position so they are arranged in a Grid formation. Children must have + * the `alignTo` method in order to be positioned by this call. All default Phaser Game Objects have + * this. + * + * The grid dimensions are determined by the first four arguments. The `width` and `height` arguments + * relate to the width and height of the grid respectively. + * + * For example if the Group had 100 children in it: + * + * `Group.align(10, 10, 32, 32)` + * + * This will align all of the children into a grid formation of 10x10, using 32 pixels per + * grid cell. If you want a wider grid, you could do: + * + * `Group.align(25, 4, 32, 32)` + * + * This will align the children into a grid of 25x4, again using 32 pixels per grid cell. + * + * You can choose to set _either_ the `width` or `height` value to -1. Doing so tells the method + * to keep on aligning children until there are no children left. For example if this Group had + * 48 children in it, the following: + * + * `Group.align(-1, 8, 32, 32)` + * + * ... will align the children so that there are 8 children vertically (the second argument), + * and each row will contain 6 sprites, except the last one, which will contain 5 (totaling 48) + * + * You can also do: + * + * `Group.align(10, -1, 32, 32)` + * + * In this case it will create a grid 10 wide, and as tall as it needs to be in order to fit + * all of the children in. + * + * The `position` property allows you to control where in each grid cell the child is positioned. + * This is a constant and can be one of `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`, + * `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, + * `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`. + * + * The final argument; `offset` lets you start the alignment from a specific child index. + * + * @method Phaser.Group#align + * @param {integer} width - The width of the grid in items (not pixels). Set to -1 for a dynamic width. If -1 then you must set an explicit height value. + * @param {integer} height - The height of the grid in items (not pixels). Set to -1 for a dynamic height. If -1 then you must set an explicit width value. + * @param {integer} cellWidth - The width of each grid cell, in pixels. + * @param {integer} cellHeight - The height of each grid cell, in pixels. + * @param {integer} [position] - The position constant. One of `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`. + * @param {integer} [offset=0] - Optional index to start the alignment from. Defaults to zero, the first child in the Group, but can be set to any valid child index value. + * @return {boolean} True if the Group children were aligned, otherwise false. + */ Phaser.Group.prototype.align = function (width, height, cellWidth, cellHeight, position, offset) { - if (position === undefined) { position = Phaser.TOP_LEFT; } if (offset === undefined) { offset = 0; } @@ -824,21 +799,19 @@ Phaser.Group.prototype.align = function (width, height, cellWidth, cellHeight, p } return true; - }; /** -* Sets the group cursor to the first child in the group. -* -* If the optional index parameter is given it sets the cursor to the object at that index instead. -* -* @method Phaser.Group#resetCursor -* @param {integer} [index=0] - Set the cursor to point to a specific index. -* @return {any} The child the cursor now points to. -*/ + * Sets the group cursor to the first child in the group. + * + * If the optional index parameter is given it sets the cursor to the object at that index instead. + * + * @method Phaser.Group#resetCursor + * @param {integer} [index=0] - Set the cursor to point to a specific index. + * @return {any} The child the cursor now points to. + */ Phaser.Group.prototype.resetCursor = function (index) { - if (index === undefined) { index = 0; } if (index > this.children.length - 1) @@ -852,20 +825,18 @@ Phaser.Group.prototype.resetCursor = function (index) this.cursor = this.children[this.cursorIndex]; return this.cursor; } - }; /** -* Advances the group cursor to the next (higher) object in the group. -* -* If the cursor is at the end of the group (top child) it is moved the start of the group (bottom child). -* -* @method Phaser.Group#next -* @return {any} The child the cursor now points to. -*/ + * Advances the group cursor to the next (higher) object in the group. + * + * If the cursor is at the end of the group (top child) it is moved the start of the group (bottom child). + * + * @method Phaser.Group#next + * @return {any} The child the cursor now points to. + */ Phaser.Group.prototype.next = function () { - if (this.cursor) { // Wrap the cursor? @@ -882,20 +853,18 @@ Phaser.Group.prototype.next = function () return this.cursor; } - }; /** -* Moves the group cursor to the previous (lower) child in the group. -* -* If the cursor is at the start of the group (bottom child) it is moved to the end (top child). -* -* @method Phaser.Group#previous -* @return {any} The child the cursor now points to. -*/ + * Moves the group cursor to the previous (lower) child in the group. + * + * If the cursor is at the start of the group (bottom child) it is moved to the end (top child). + * + * @method Phaser.Group#previous + * @return {any} The child the cursor now points to. + */ Phaser.Group.prototype.previous = function () { - if (this.cursor) { // Wrap the cursor? @@ -912,36 +881,32 @@ Phaser.Group.prototype.previous = function () return this.cursor; } - }; /** -* Swaps the position of two children in this group. -* -* Both children must be in this group, a child cannot be swapped with itself, and unparented children cannot be swapped. -* -* @method Phaser.Group#swap -* @param {any} child1 - The first child to swap. -* @param {any} child2 - The second child to swap. -*/ + * Swaps the position of two children in this group. + * + * Both children must be in this group, a child cannot be swapped with itself, and unparented children cannot be swapped. + * + * @method Phaser.Group#swap + * @param {any} child1 - The first child to swap. + * @param {any} child2 - The second child to swap. + */ Phaser.Group.prototype.swap = function (child1, child2) { - this.swapChildren(child1, child2); this.updateZ(); - }; /** -* Brings the given child to the top of this group so it renders above all other children. -* -* @method Phaser.Group#bringToTop -* @param {any} child - The child to bring to the top of this group. -* @return {any} The child that was moved. -*/ + * Brings the given child to the top of this group so it renders above all other children. + * + * @method Phaser.Group#bringToTop + * @param {any} child - The child to bring to the top of this group. + * @return {any} The child that was moved. + */ Phaser.Group.prototype.bringToTop = function (child) { - if (child.parent === this && this.getIndex(child) < this.children.length) { this.remove(child, false, true); @@ -949,25 +914,23 @@ Phaser.Group.prototype.bringToTop = function (child) } return child; - }; /** -* Alias for {@link Phaser.Group#bringToTop}. -* @private -*/ + * Alias for {@link Phaser.Group#bringToTop}. + * @private + */ Phaser.Group.prototype.bringChildToTop = Phaser.Group.prototype.bringToTop; /** -* Sends the given child to the bottom of this group so it renders below all other children. -* -* @method Phaser.Group#sendToBack -* @param {any} child - The child to send to the bottom of this group. -* @return {any} The child that was moved. -*/ + * Sends the given child to the bottom of this group so it renders below all other children. + * + * @method Phaser.Group#sendToBack + * @param {any} child - The child to send to the bottom of this group. + * @return {any} The child that was moved. + */ Phaser.Group.prototype.sendToBack = function (child) { - if (child.parent === this && this.getIndex(child) > 0) { this.remove(child, false, true); @@ -975,25 +938,23 @@ Phaser.Group.prototype.sendToBack = function (child) } return child; - }; /** -* Alias for {@link Phaser.Group#sendToBack}. -* @private -*/ + * Alias for {@link Phaser.Group#sendToBack}. + * @private + */ Phaser.Group.prototype.sendChildToBack = Phaser.Group.prototype.sendToBack; /** -* Moves the given child up one place in this group unless it's already at the top. -* -* @method Phaser.Group#moveUp -* @param {any} child - The child to move up in the group. -* @return {any} The child that was moved. -*/ + * Moves the given child up one place in this group unless it's already at the top. + * + * @method Phaser.Group#moveUp + * @param {any} child - The child to move up in the group. + * @return {any} The child that was moved. + */ Phaser.Group.prototype.moveUp = function (child) { - if (child.parent === this && this.getIndex(child) < this.children.length - 1) { var a = this.getIndex(child); @@ -1006,19 +967,17 @@ Phaser.Group.prototype.moveUp = function (child) } return child; - }; /** -* Moves the given child down one place in this group unless it's already at the bottom. -* -* @method Phaser.Group#moveDown -* @param {any} child - The child to move down in the group. -* @return {any} The child that was moved. -*/ + * Moves the given child down one place in this group unless it's already at the bottom. + * + * @method Phaser.Group#moveDown + * @param {any} child - The child to move down in the group. + * @return {any} The child that was moved. + */ Phaser.Group.prototype.moveDown = function (child) { - if (child.parent === this && this.getIndex(child) > 0) { var a = this.getIndex(child); @@ -1031,20 +990,18 @@ Phaser.Group.prototype.moveDown = function (child) } return child; - }; /** -* Positions the child found at the given index within this group to the given x and y coordinates. -* -* @method Phaser.Group#xy -* @param {integer} index - The index of the child in the group to set the position of. -* @param {number} x - The new x position of the child. -* @param {number} y - The new y position of the child. -*/ + * Positions the child found at the given index within this group to the given x and y coordinates. + * + * @method Phaser.Group#xy + * @param {integer} index - The index of the child in the group to set the position of. + * @param {number} x - The new x position of the child. + * @param {number} y - The new y position of the child. + */ Phaser.Group.prototype.xy = function (index, x, y) { - if (index < 0 || index > this.children.length) { return -1; @@ -1054,69 +1011,61 @@ Phaser.Group.prototype.xy = function (index, x, y) this.getChildAt(index).x = x; this.getChildAt(index).y = y; } - }; /** -* Reverses all children in this group. -* -* This operation applies only to immediate children and does not propagate to subgroups. -* -* @method Phaser.Group#reverse -*/ + * Reverses all children in this group. + * + * This operation applies only to immediate children and does not propagate to subgroups. + * + * @method Phaser.Group#reverse + */ Phaser.Group.prototype.reverse = function () { - this.children.reverse(); this.updateZ(); - }; /** -* Get the index position of the given child in this group, which should match the child's `z` property. -* -* @method Phaser.Group#getIndex -* @param {any} child - The child to get the index for. -* @return {integer} The index of the child or -1 if it's not a member of this group. -*/ + * Get the index position of the given child in this group, which should match the child's `z` property. + * + * @method Phaser.Group#getIndex + * @param {any} child - The child to get the index for. + * @return {integer} The index of the child or -1 if it's not a member of this group. + */ Phaser.Group.prototype.getIndex = function (child) { - return this.children.indexOf(child); - }; /** -* Searches the Group for the first instance of a child with the `name` -* property matching the given argument. Should more than one child have -* the same name only the first instance is returned. -* -* @method Phaser.Group#getByName -* @param {string} name - The name to search for. -* @return {any} The first child with a matching name, or null if none were found. -*/ + * Searches the Group for the first instance of a child with the `name` + * property matching the given argument. Should more than one child have + * the same name only the first instance is returned. + * + * @method Phaser.Group#getByName + * @param {string} name - The name to search for. + * @return {any} The first child with a matching name, or null if none were found. + */ Phaser.Group.prototype.getByName = function (name) { - return this.getFirst('name', name); - }; /** -* Replaces a child of this Group with the given newChild. The newChild cannot be a member of this Group. -* -* If `Group.enableBody` is set, then a physics body will be created on the object, so long as one does not already exist. -* -* If `Group.inputEnableChildren` is set, then an Input Handler will be created on the object, so long as one does not already exist. -* -* @method Phaser.Group#replace -* @param {any} oldChild - The child in this group that will be replaced. -* @param {any} newChild - The child to be inserted into this group. -* @return {any} Returns the oldChild that was replaced within this group. -*/ + * Replaces a child of this Group with the given newChild. The newChild cannot be a member of this Group. + * + * If `Group.enableBody` is set, then a physics body will be created on the object, so long as one does not already exist. + * + * If `Group.inputEnableChildren` is set, then an Input Handler will be created on the object, so long as one does not already exist. + * + * @method Phaser.Group#replace + * @param {any} oldChild - The child in this group that will be replaced. + * @param {any} newChild - The child to be inserted into this group. + * @return {any} Returns the oldChild that was replaced within this group. + */ Phaser.Group.prototype.replace = function (oldChild, newChild) { - var index = this.getIndex(oldChild); if (index !== -1) @@ -1139,22 +1088,20 @@ Phaser.Group.prototype.replace = function (oldChild, newChild) return oldChild; } - }; /** -* Checks if the child has the given property. -* -* Will scan up to 4 levels deep only. -* -* @method Phaser.Group#hasProperty -* @param {any} child - The child to check for the existence of the property on. -* @param {string[]} key - An array of strings that make up the property. -* @return {boolean} True if the child has the property, otherwise false. -*/ + * Checks if the child has the given property. + * + * Will scan up to 4 levels deep only. + * + * @method Phaser.Group#hasProperty + * @param {any} child - The child to check for the existence of the property on. + * @param {string[]} key - An array of strings that make up the property. + * @return {boolean} True if the child has the property, otherwise false. + */ Phaser.Group.prototype.hasProperty = function (child, key) { - var len = key.length; if (len === 1 && key[0] in child) @@ -1175,44 +1122,46 @@ Phaser.Group.prototype.hasProperty = function (child, key) } return false; - }; /** -* Sets a property to the given value on the child. The operation parameter controls how the value is set. -* -* The operations are: -* - 0: set the existing value to the given value; if force is `true` a new property will be created if needed -* - 1: will add the given value to the value already present. -* - 2: will subtract the given value from the value already present. -* - 3: will multiply the value already present by the given value. -* - 4: will divide the value already present by the given value. -* -* @method Phaser.Group#setProperty -* @param {any} child - The child to set the property value on. -* @param {array} key - An array of strings that make up the property that will be set. -* @param {any} value - The value that will be set. -* @param {integer} [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. -* @param {boolean} [force=false] - If `force` is true then the property will be set on the child regardless if it already exists or not. If false and the property doesn't exist, nothing will be set. -* @return {boolean} True if the property was set, false if not. -*/ + * Sets a property to the given value on the child. The operation parameter controls how the value is set. + * + * The operations are: + * - 0: set the existing value to the given value; if force is `true` a new property will be created if needed + * - 1: will add the given value to the value already present. + * - 2: will subtract the given value from the value already present. + * - 3: will multiply the value already present by the given value. + * - 4: will divide the value already present by the given value. + * + * @method Phaser.Group#setProperty + * @param {any} child - The child to set the property value on. + * @param {array} key - An array of strings that make up the property that will be set. + * @param {any} value - The value that will be set. + * @param {integer} [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. + * @param {boolean} [force=false] - If `force` is true then the property will be set on the child regardless if it already exists or not. If false and the property doesn't exist, nothing will be set. + * @return {boolean} True if the property was set, false if not. + */ Phaser.Group.prototype.setProperty = function (child, key, value, operation, force) { - if (force === undefined) { force = false; } operation = operation || 0; // As ugly as this approach looks, and although it's limited to a depth of only 4, it's much faster than a for loop or object iteration. - // 0 = Equals - // 1 = Add - // 2 = Subtract - // 3 = Multiply - // 4 = Divide - - // We can't force a property in and the child doesn't have it, so abort. - // Equally we can't add, subtract, multiply or divide a property value if it doesn't exist, so abort in those cases too. + /* + * 0 = Equals + * 1 = Add + * 2 = Subtract + * 3 = Multiply + * 4 = Divide + */ + + /* + * We can't force a property in and the child doesn't have it, so abort. + * Equally we can't add, subtract, multiply or divide a property value if it doesn't exist, so abort in those cases too. + */ if (!this.hasProperty(child, key) && (!force || operation > 0)) { return false; @@ -1254,22 +1203,20 @@ Phaser.Group.prototype.setProperty = function (child, key, value, operation, for } return true; - }; /** -* Checks a property for the given value on the child. -* -* @method Phaser.Group#checkProperty -* @param {any} child - The child to check the property value on. -* @param {string} key - The property, as a string, to be checked. For example: 'body.velocity.x' -* @param {any} value - The value that will be checked. -* @param {boolean} [force=false] - Also return false if the property is missing or undefined (regardless of the `value` argument). -* @return {boolean} True if `child` is a child of this Group and the property was equal to value, false if not. -*/ + * Checks a property for the given value on the child. + * + * @method Phaser.Group#checkProperty + * @param {any} child - The child to check the property value on. + * @param {string} key - The property, as a string, to be checked. For example: 'body.velocity.x' + * @param {any} value - The value that will be checked. + * @param {boolean} [force=false] - Also return false if the property is missing or undefined (regardless of the `value` argument). + * @return {boolean} True if `child` is a child of this Group and the property was equal to value, false if not. + */ Phaser.Group.prototype.checkProperty = function (child, key, value, force) { - if (force === undefined) { force = false; } if (this !== child.parent) @@ -1285,27 +1232,25 @@ Phaser.Group.prototype.checkProperty = function (child, key, value, force) } return true; - }; /** -* Quickly set a property on a single child of this group to a new value. -* -* The operation parameter controls how the new value is assigned to the property, from simple replacement to addition and multiplication. -* -* @method Phaser.Group#set -* @param {Phaser.Sprite} child - The child to set the property on. -* @param {string} key - The property, as a string, to be set. For example: 'body.velocity.x' -* @param {any} value - The value that will be set. -* @param {boolean} [checkAlive=false] - If set then the child will only be updated if alive=true. -* @param {boolean} [checkVisible=false] - If set then the child will only be updated if visible=true. -* @param {integer} [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. -* @param {boolean} [force=false] - If `force` is true then the property will be set on the child regardless if it already exists or not. If false and the property doesn't exist, nothing will be set. -* @return {boolean} True if the property was set, false if not. -*/ + * Quickly set a property on a single child of this group to a new value. + * + * The operation parameter controls how the new value is assigned to the property, from simple replacement to addition and multiplication. + * + * @method Phaser.Group#set + * @param {Phaser.Sprite} child - The child to set the property on. + * @param {string} key - The property, as a string, to be set. For example: 'body.velocity.x' + * @param {any} value - The value that will be set. + * @param {boolean} [checkAlive=false] - If set then the child will only be updated if alive=true. + * @param {boolean} [checkVisible=false] - If set then the child will only be updated if visible=true. + * @param {integer} [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. + * @param {boolean} [force=false] - If `force` is true then the property will be set on the child regardless if it already exists or not. If false and the property doesn't exist, nothing will be set. + * @return {boolean} True if the property was set, false if not. + */ Phaser.Group.prototype.set = function (child, key, value, checkAlive, checkVisible, operation, force) { - if (force === undefined) { force = false; } key = key.split('.'); @@ -1317,28 +1262,26 @@ Phaser.Group.prototype.set = function (child, key, value, checkAlive, checkVisib { return this.setProperty(child, key, value, operation, force); } - }; /** -* Quickly set the same property across all children of this group to a new value. -* -* This call doesn't descend down children, so if you have a Group inside of this group, the property will be set on the group but not its children. -* If you need that ability please see `Group.setAllChildren`. -* -* The operation parameter controls how the new value is assigned to the property, from simple replacement to addition and multiplication. -* -* @method Phaser.Group#setAll -* @param {string} key - The property, as a string, to be set. For example: 'body.velocity.x' -* @param {any} value - The value that will be set. -* @param {boolean} [checkAlive=false] - If set then only children with alive=true will be updated. This includes any Groups that are children. -* @param {boolean} [checkVisible=false] - If set then only children with visible=true will be updated. This includes any Groups that are children. -* @param {integer} [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. -* @param {boolean} [force=false] - If `force` is true then the property will be set on the child regardless if it already exists or not. If false and the property doesn't exist, nothing will be set. -*/ + * Quickly set the same property across all children of this group to a new value. + * + * This call doesn't descend down children, so if you have a Group inside of this group, the property will be set on the group but not its children. + * If you need that ability please see `Group.setAllChildren`. + * + * The operation parameter controls how the new value is assigned to the property, from simple replacement to addition and multiplication. + * + * @method Phaser.Group#setAll + * @param {string} key - The property, as a string, to be set. For example: 'body.velocity.x' + * @param {any} value - The value that will be set. + * @param {boolean} [checkAlive=false] - If set then only children with alive=true will be updated. This includes any Groups that are children. + * @param {boolean} [checkVisible=false] - If set then only children with visible=true will be updated. This includes any Groups that are children. + * @param {integer} [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. + * @param {boolean} [force=false] - If `force` is true then the property will be set on the child regardless if it already exists or not. If false and the property doesn't exist, nothing will be set. + */ Phaser.Group.prototype.setAll = function (key, value, checkAlive, checkVisible, operation, force) { - if (checkAlive === undefined) { checkAlive = false; } if (checkVisible === undefined) { checkVisible = false; } if (force === undefined) { force = false; } @@ -1357,28 +1300,26 @@ Phaser.Group.prototype.setAll = function (key, value, checkAlive, checkVisible, this.setProperty(child, key, value, operation, force); } } - }; /** -* Quickly set the same property across all children of this group, and any child Groups, to a new value. -* -* If this group contains other Groups then the same property is set across their children as well, iterating down until it reaches the bottom. -* Unlike with `setAll` the property is NOT set on child Groups itself. -* -* The operation parameter controls how the new value is assigned to the property, from simple replacement to addition and multiplication. -* -* @method Phaser.Group#setAllChildren -* @param {string} key - The property, as a string, to be set. For example: 'body.velocity.x' -* @param {any} value - The value that will be set. -* @param {boolean} [checkAlive=false] - If set then only children with alive=true will be updated. This includes any Groups that are children. -* @param {boolean} [checkVisible=false] - If set then only children with visible=true will be updated. This includes any Groups that are children. -* @param {integer} [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. -* @param {boolean} [force=false] - If `force` is true then the property will be set on the child regardless if it already exists or not. If false and the property doesn't exist, nothing will be set. -*/ + * Quickly set the same property across all children of this group, and any child Groups, to a new value. + * + * If this group contains other Groups then the same property is set across their children as well, iterating down until it reaches the bottom. + * Unlike with `setAll` the property is NOT set on child Groups itself. + * + * The operation parameter controls how the new value is assigned to the property, from simple replacement to addition and multiplication. + * + * @method Phaser.Group#setAllChildren + * @param {string} key - The property, as a string, to be set. For example: 'body.velocity.x' + * @param {any} value - The value that will be set. + * @param {boolean} [checkAlive=false] - If set then only children with alive=true will be updated. This includes any Groups that are children. + * @param {boolean} [checkVisible=false] - If set then only children with visible=true will be updated. This includes any Groups that are children. + * @param {integer} [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. + * @param {boolean} [force=false] - If `force` is true then the property will be set on the child regardless if it already exists or not. If false and the property doesn't exist, nothing will be set. + */ Phaser.Group.prototype.setAllChildren = function (key, value, checkAlive, checkVisible, operation, force) { - if (checkAlive === undefined) { checkAlive = false; } if (checkVisible === undefined) { checkVisible = false; } if (force === undefined) { force = false; } @@ -1403,25 +1344,23 @@ Phaser.Group.prototype.setAllChildren = function (key, value, checkAlive, checkV } } } - }; /** -* Test that the same property across all children of this group is equal to the given value. -* -* This call doesn't descend down children, so if you have a Group inside of this group, the property will be checked on the group but not its children. -* -* @method Phaser.Group#checkAll -* @param {string} key - The property, as a string, to be checked. For example: 'body.velocity.x' -* @param {any} value - The value that will be checked. -* @param {boolean} [checkAlive=false] - If set then only children with alive=true will be checked. This includes any Groups that are children. -* @param {boolean} [checkVisible=false] - If set then only children with visible=true will be checked. This includes any Groups that are children. -* @param {boolean} [force=false] - Also return false if the property is missing or undefined (regardless of the `value` argument). -* @return {boolean} - True if all eligible children have the given property value (but see `force`); otherwise false. -*/ + * Test that the same property across all children of this group is equal to the given value. + * + * This call doesn't descend down children, so if you have a Group inside of this group, the property will be checked on the group but not its children. + * + * @method Phaser.Group#checkAll + * @param {string} key - The property, as a string, to be checked. For example: 'body.velocity.x' + * @param {any} value - The value that will be checked. + * @param {boolean} [checkAlive=false] - If set then only children with alive=true will be checked. This includes any Groups that are children. + * @param {boolean} [checkVisible=false] - If set then only children with visible=true will be checked. This includes any Groups that are children. + * @param {boolean} [force=false] - Also return false if the property is missing or undefined (regardless of the `value` argument). + * @return {boolean} - True if all eligible children have the given property value (but see `force`); otherwise false. + */ Phaser.Group.prototype.checkAll = function (key, value, checkAlive, checkVisible, force) { - if (checkAlive === undefined) { checkAlive = false; } if (checkVisible === undefined) { checkVisible = false; } if (force === undefined) { force = false; } @@ -1440,24 +1379,22 @@ Phaser.Group.prototype.checkAll = function (key, value, checkAlive, checkVisible } return true; - }; /** -* Test that at least one child of this group has the given property value. -* -* This call doesn't descend down children, so if you have a Group inside of this group, the property will be checked on the group but not its children. -* -* @method Phaser.Group#checkAny -* @param {string} key - The property, as a string, to be checked. For example: 'body.velocity.x' -* @param {any} value - The value that will be checked. -* @param {boolean} [checkAlive=false] - If set then only children with alive=true will be checked. This includes any Groups that are children. -* @param {boolean} [checkVisible=false] - If set then only children with visible=true will be checked. This includes any Groups that are children. -* @return {boolean} - True if at least one eligible child has the given property value; otherwise false. -*/ + * Test that at least one child of this group has the given property value. + * + * This call doesn't descend down children, so if you have a Group inside of this group, the property will be checked on the group but not its children. + * + * @method Phaser.Group#checkAny + * @param {string} key - The property, as a string, to be checked. For example: 'body.velocity.x' + * @param {any} value - The value that will be checked. + * @param {boolean} [checkAlive=false] - If set then only children with alive=true will be checked. This includes any Groups that are children. + * @param {boolean} [checkVisible=false] - If set then only children with visible=true will be checked. This includes any Groups that are children. + * @return {boolean} - True if at least one eligible child has the given property value; otherwise false. + */ Phaser.Group.prototype.checkAny = function (key, value, checkAlive, checkVisible) { - if (checkAlive === undefined) { checkAlive = false; } if (checkVisible === undefined) { checkVisible = false; } @@ -1475,79 +1412,70 @@ Phaser.Group.prototype.checkAny = function (key, value, checkAlive, checkVisible } return false; - }; /** -* Adds the amount to the given property on all children in this group. -* -* `Group.addAll('x', 10)` will add 10 to the child.x value for each child. -* -* @method Phaser.Group#addAll -* @param {string} property - The property to increment, for example 'body.velocity.x' or 'angle'. -* @param {number} amount - The amount to increment the property by. If child.x = 10 then addAll('x', 40) would make child.x = 50. -* @param {boolean} [checkAlive] - If true the property will only be changed if the child is alive. -* @param {boolean} [checkVisible] - If true the property will only be changed if the child is visible. -*/ + * Adds the amount to the given property on all children in this group. + * + * `Group.addAll('x', 10)` will add 10 to the child.x value for each child. + * + * @method Phaser.Group#addAll + * @param {string} property - The property to increment, for example 'body.velocity.x' or 'angle'. + * @param {number} amount - The amount to increment the property by. If child.x = 10 then addAll('x', 40) would make child.x = 50. + * @param {boolean} [checkAlive] - If true the property will only be changed if the child is alive. + * @param {boolean} [checkVisible] - If true the property will only be changed if the child is visible. + */ Phaser.Group.prototype.addAll = function (property, amount, checkAlive, checkVisible) { - this.setAll(property, amount, checkAlive, checkVisible, 1); - }; /** -* Subtracts the amount from the given property on all children in this group. -* -* `Group.subAll('x', 10)` will minus 10 from the child.x value for each child. -* -* @method Phaser.Group#subAll -* @param {string} property - The property to decrement, for example 'body.velocity.x' or 'angle'. -* @param {number} amount - The amount to subtract from the property. If child.x = 50 then subAll('x', 40) would make child.x = 10. -* @param {boolean} checkAlive - If true the property will only be changed if the child is alive. -* @param {boolean} checkVisible - If true the property will only be changed if the child is visible. -*/ + * Subtracts the amount from the given property on all children in this group. + * + * `Group.subAll('x', 10)` will minus 10 from the child.x value for each child. + * + * @method Phaser.Group#subAll + * @param {string} property - The property to decrement, for example 'body.velocity.x' or 'angle'. + * @param {number} amount - The amount to subtract from the property. If child.x = 50 then subAll('x', 40) would make child.x = 10. + * @param {boolean} checkAlive - If true the property will only be changed if the child is alive. + * @param {boolean} checkVisible - If true the property will only be changed if the child is visible. + */ Phaser.Group.prototype.subAll = function (property, amount, checkAlive, checkVisible) { - this.setAll(property, amount, checkAlive, checkVisible, 2); - }; /** -* Multiplies the given property by the amount on all children in this group. -* -* `Group.multiplyAll('x', 2)` will x2 the child.x value for each child. -* -* @method Phaser.Group#multiplyAll -* @param {string} property - The property to multiply, for example 'body.velocity.x' or 'angle'. -* @param {number} amount - The amount to multiply the property by. If child.x = 10 then multiplyAll('x', 2) would make child.x = 20. -* @param {boolean} checkAlive - If true the property will only be changed if the child is alive. -* @param {boolean} checkVisible - If true the property will only be changed if the child is visible. -*/ + * Multiplies the given property by the amount on all children in this group. + * + * `Group.multiplyAll('x', 2)` will x2 the child.x value for each child. + * + * @method Phaser.Group#multiplyAll + * @param {string} property - The property to multiply, for example 'body.velocity.x' or 'angle'. + * @param {number} amount - The amount to multiply the property by. If child.x = 10 then multiplyAll('x', 2) would make child.x = 20. + * @param {boolean} checkAlive - If true the property will only be changed if the child is alive. + * @param {boolean} checkVisible - If true the property will only be changed if the child is visible. + */ Phaser.Group.prototype.multiplyAll = function (property, amount, checkAlive, checkVisible) { - this.setAll(property, amount, checkAlive, checkVisible, 3); - }; /** -* Divides the given property by the amount on all children in this group. -* -* `Group.divideAll('x', 2)` will half the child.x value for each child. -* -* @method Phaser.Group#divideAll -* @param {string} property - The property to divide, for example 'body.velocity.x' or 'angle'. -* @param {number} amount - The amount to divide the property by. If child.x = 100 then divideAll('x', 2) would make child.x = 50. -* @param {boolean} checkAlive - If true the property will only be changed if the child is alive. -* @param {boolean} checkVisible - If true the property will only be changed if the child is visible. -*/ + * Divides the given property by the amount on all children in this group. + * + * `Group.divideAll('x', 2)` will half the child.x value for each child. + * + * @method Phaser.Group#divideAll + * @param {string} property - The property to divide, for example 'body.velocity.x' or 'angle'. + * @param {number} amount - The amount to divide the property by. If child.x = 100 then divideAll('x', 2) would make child.x = 50. + * @param {boolean} checkAlive - If true the property will only be changed if the child is alive. + * @param {boolean} checkVisible - If true the property will only be changed if the child is visible. + */ Phaser.Group.prototype.divideAll = function (property, amount, checkAlive, checkVisible) { - this.setAll(property, amount, checkAlive, checkVisible, 4); - }; /** @@ -1557,11 +1485,9 @@ Phaser.Group.prototype.divideAll = function (property, amount, checkAlive, check */ Phaser.Group.prototype.kill = function () { - this.alive = false; this.exists = false; this.visible = false; - }; /** @@ -1571,9 +1497,7 @@ Phaser.Group.prototype.kill = function () */ Phaser.Group.prototype.killAll = function () { - this.callAllExists('kill', true); - }; /** @@ -1583,11 +1507,9 @@ Phaser.Group.prototype.killAll = function () */ Phaser.Group.prototype.revive = function () { - this.alive = true; this.exists = true; this.visible = true; - }; /** @@ -1597,41 +1519,36 @@ Phaser.Group.prototype.revive = function () */ Phaser.Group.prototype.reviveAll = function () { - this.callAllExists('revive', false); - }; /** -* Calls {@link #resetChild} on each child (or each existing child). -* -* @method Phaser.Group#resetAll -* @param {number} [x] - The x coordinate to reset each child to. The value is in relation to the group.x point. -* @param {number} [y] - The y coordinate to reset each child to. The value is in relation to the group.y point. -* @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - The image or texture used by the Sprite during rendering. -* @param {string|number} [frame] - The frame of a sprite sheet or texture atlas. -* @param {boolean} [checkExists=false] - Reset only existing children. -*/ + * Calls {@link #resetChild} on each child (or each existing child). + * + * @method Phaser.Group#resetAll + * @param {number} [x] - The x coordinate to reset each child to. The value is in relation to the group.x point. + * @param {number} [y] - The y coordinate to reset each child to. The value is in relation to the group.y point. + * @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - The image or texture used by the Sprite during rendering. + * @param {string|number} [frame] - The frame of a sprite sheet or texture atlas. + * @param {boolean} [checkExists=false] - Reset only existing children. + */ Phaser.Group.prototype.resetAll = function (x, y, key, frame, checkExists) { - this.forEach(this.resetChild, this, checkExists, x, y, key, frame); - }; /** -* Calls a function, specified by name, on all children in the group who exist (or do not exist). -* -* After the existsValue parameter you can add as many parameters as you like, which will all be passed to the child callback. -* -* @method Phaser.Group#callAllExists -* @param {string} callback - Name of the function on the children to call. -* @param {boolean} existsValue - Only children with exists=existsValue will be called. -* @param {...any} parameter - Additional parameters that will be passed to the callback. -*/ + * Calls a function, specified by name, on all children in the group who exist (or do not exist). + * + * After the existsValue parameter you can add as many parameters as you like, which will all be passed to the child callback. + * + * @method Phaser.Group#callAllExists + * @param {string} callback - Name of the function on the children to call. + * @param {boolean} existsValue - Only children with exists=existsValue will be called. + * @param {...any} parameter - Additional parameters that will be passed to the callback. + */ Phaser.Group.prototype.callAllExists = function (callback, existsValue) { - var args; if (arguments.length > 2) @@ -1653,21 +1570,19 @@ Phaser.Group.prototype.callAllExists = function (callback, existsValue) child[callback].apply(child, args); } } - }; /** -* Returns a reference to a function that exists on a child of the group based on the given callback array. -* -* @method Phaser.Group#callbackFromArray -* @param {object} child - The object to inspect. -* @param {array} callback - The array of function names. -* @param {integer} length - The size of the array (pre-calculated in callAll). -* @protected -*/ + * Returns a reference to a function that exists on a child of the group based on the given callback array. + * + * @method Phaser.Group#callbackFromArray + * @param {object} child - The object to inspect. + * @param {array} callback - The array of function names. + * @param {integer} length - The size of the array (pre-calculated in callAll). + * @protected + */ Phaser.Group.prototype.callbackFromArray = function (child, callback, length) { - // Kinda looks like a Christmas tree if (length === 1) @@ -1704,23 +1619,21 @@ Phaser.Group.prototype.callbackFromArray = function (child, callback, length) } return false; - }; /** -* Calls a function, specified by name, on all on children. -* -* The function is called for all children regardless if they are dead or alive (see callAllExists for different options). -* After the method parameter and context you can add as many extra parameters as you like, which will all be passed to the child. -* -* @method Phaser.Group#callAll -* @param {string} method - Name of the function on the child to call. Deep property lookup is supported. -* @param {string} [context=null] - A string containing the context under which the method will be executed. Set to null to default to the child. -* @param {...any} args - Additional parameters that will be passed to the method. -*/ + * Calls a function, specified by name, on all on children. + * + * The function is called for all children regardless if they are dead or alive (see callAllExists for different options). + * After the method parameter and context you can add as many extra parameters as you like, which will all be passed to the child. + * + * @method Phaser.Group#callAll + * @param {string} method - Name of the function on the child to call. Deep property lookup is supported. + * @param {string} [context=null] - A string containing the context under which the method will be executed. Set to null to default to the child. + * @param {...any} args - Additional parameters that will be passed to the method. + */ Phaser.Group.prototype.callAll = function (method, context) { - if (method === undefined) { return; @@ -1777,17 +1690,15 @@ Phaser.Group.prototype.callAll = function (method, context) callback.apply(child, args); } } - }; /** -* The core preUpdate - as called by World. -* @method Phaser.Group#preUpdate -* @protected -*/ + * The core preUpdate - as called by World. + * @method Phaser.Group#preUpdate + * @protected + */ Phaser.Group.prototype.preUpdate = function () { - if (this.pendingDestroy) { this.destroy(); @@ -1800,8 +1711,10 @@ Phaser.Group.prototype.preUpdate = function () return false; } - // This chunk is identical to Phaser.Component.Core.prototype.preUpdateChildren, which is not yet defined. - // This can't loop in reverse, we need the renderOrderID to be in sequence + /* + * This chunk is identical to Phaser.Component.Core.prototype.preUpdateChildren, which is not yet defined. + * This can't loop in reverse, we need the renderOrderID to be in sequence + */ var i = 0; while (i < this.children.length) @@ -1817,20 +1730,18 @@ Phaser.Group.prototype.preUpdate = function () } return true; - }; /** -* The core update - as called by World. -* -* Children with `exists = false` are updated unless {@link #updateOnlyExistingChildren} is true. -* -* @method Phaser.Group#update -* @protected -*/ + * The core update - as called by World. + * + * Children with `exists = false` are updated unless {@link #updateOnlyExistingChildren} is true. + * + * @method Phaser.Group#update + * @protected + */ Phaser.Group.prototype.update = function () { - // Goes in reverse, because it's highly likely the child will destroy itself in `update` var i = this.children.length; @@ -1847,17 +1758,15 @@ Phaser.Group.prototype.update = function () child.update(); } } - }; /** -* The core postUpdate - as called by World. -* @method Phaser.Group#postUpdate -* @protected -*/ + * The core postUpdate - as called by World. + * @method Phaser.Group#postUpdate + * @protected + */ Phaser.Group.prototype.postUpdate = function () { - // Fixed to Camera? if (this.fixedToCamera) { @@ -1869,29 +1778,27 @@ Phaser.Group.prototype.postUpdate = function () { this.children[i].postUpdate(); } - }; /** -* Find children matching a certain predicate. -* -* For example: -* -* var healthyList = Group.filter(function(child, index, children) { -* return child.health > 10 ? true : false; -* }, true); -* healthyList.callAll('attack'); -* -* Note: Currently this will skip any children which are Groups themselves. -* -* @method Phaser.Group#filter -* @param {function} predicate - The function that each child will be evaluated against. Each child of the group will be passed to it as its first parameter, the index as the second, and the entire child array as the third -* @param {boolean} [checkExists=false] - If true, only existing can be selected; otherwise all children can be selected and will be passed to the predicate. -* @return {Phaser.ArraySet} Returns an array list containing all the children that the predicate returned true for -*/ + * Find children matching a certain predicate. + * + * For example: + * + * var healthyList = Group.filter(function(child, index, children) { + * return child.health > 10 ? true : false; + * }, true); + * healthyList.callAll('attack'); + * + * Note: Currently this will skip any children which are Groups themselves. + * + * @method Phaser.Group#filter + * @param {function} predicate - The function that each child will be evaluated against. Each child of the group will be passed to it as its first parameter, the index as the second, and the entire child array as the third + * @param {boolean} [checkExists=false] - If true, only existing can be selected; otherwise all children can be selected and will be passed to the predicate. + * @return {Phaser.ArraySet} Returns an array list containing all the children that the predicate returned true for + */ Phaser.Group.prototype.filter = function (predicate, checkExists) { - var index = -1; var length = this.children.length; var results = []; @@ -1910,29 +1817,27 @@ Phaser.Group.prototype.filter = function (predicate, checkExists) } return new Phaser.ArraySet(results); - }; /** -* Call a function on each child in this group. -* -* Additional arguments for the callback can be specified after the `checkExists` parameter. For example, -* -* Group.forEach(awardBonusGold, this, true, 100, 500) -* -* would invoke `awardBonusGold` function with the parameters `(child, 100, 500)`. -* -* Note: This check will skip any children which are Groups themselves. -* -* @method Phaser.Group#forEach -* @param {function} callback - The function that will be called for each applicable child. The child will be passed as the first argument. -* @param {object} callbackContext - The context in which the function should be called (usually 'this'). -* @param {boolean} [checkExists=false] - If set only children matching for which `exists` is true will be passed to the callback, otherwise all children will be passed. -* @param {...any} [args=(none)] - Additional arguments to pass to the callback function, after the child item. -*/ + * Call a function on each child in this group. + * + * Additional arguments for the callback can be specified after the `checkExists` parameter. For example, + * + * Group.forEach(awardBonusGold, this, true, 100, 500) + * + * would invoke `awardBonusGold` function with the parameters `(child, 100, 500)`. + * + * Note: This check will skip any children which are Groups themselves. + * + * @method Phaser.Group#forEach + * @param {function} callback - The function that will be called for each applicable child. The child will be passed as the first argument. + * @param {object} callbackContext - The context in which the function should be called (usually 'this'). + * @param {boolean} [checkExists=false] - If set only children matching for which `exists` is true will be passed to the callback, otherwise all children will be passed. + * @param {...any} [args=(none)] - Additional arguments to pass to the callback function, after the child item. + */ Phaser.Group.prototype.forEach = function (callback, callbackContext, checkExists) { - if (checkExists === undefined) { checkExists = false; } if (arguments.length <= 3) @@ -1949,8 +1854,10 @@ Phaser.Group.prototype.forEach = function (callback, callbackContext, checkExist } else { - // Assigning to arguments properties causes Extreme Deoptimization in Chrome, FF, and IE. - // Using an array and pushing each element (not a slice!) is _significantly_ faster. + /* + * Assigning to arguments properties causes Extreme Deoptimization in Chrome, FF, and IE. + * Using an array and pushing each element (not a slice!) is _significantly_ faster. + */ var args = [ null ]; for (var i = 3; i < arguments.length; i++) @@ -1969,22 +1876,20 @@ Phaser.Group.prototype.forEach = function (callback, callbackContext, checkExist } } } - }; /** -* Call a function on each existing child in this group. -* -* See {@link Phaser.Group#forEach forEach} for details. -* -* @method Phaser.Group#forEachExists -* @param {function} callback - The function that will be called for each applicable child. The child will be passed as the first argument. -* @param {object} callbackContext - The context in which the function should be called (usually 'this'). -* @param {...any} [args=(none)] - Additional arguments to pass to the callback function, after the child item. -*/ + * Call a function on each existing child in this group. + * + * See {@link Phaser.Group#forEach forEach} for details. + * + * @method Phaser.Group#forEachExists + * @param {function} callback - The function that will be called for each applicable child. The child will be passed as the first argument. + * @param {object} callbackContext - The context in which the function should be called (usually 'this'). + * @param {...any} [args=(none)] - Additional arguments to pass to the callback function, after the child item. + */ Phaser.Group.prototype.forEachExists = function (callback, callbackContext) { - var args; if (arguments.length > 2) @@ -1998,22 +1903,20 @@ Phaser.Group.prototype.forEachExists = function (callback, callbackContext) } this.iterate('exists', true, Phaser.Group.RETURN_TOTAL, callback, callbackContext, args); - }; /** -* Call a function on each alive child in this group. -* -* See {@link Phaser.Group#forEach forEach} for details. -* -* @method Phaser.Group#forEachAlive -* @param {function} callback - The function that will be called for each applicable child. The child will be passed as the first argument. -* @param {object} callbackContext - The context in which the function should be called (usually 'this'). -* @param {...any} [args=(none)] - Additional arguments to pass to the callback function, after the child item. -*/ + * Call a function on each alive child in this group. + * + * See {@link Phaser.Group#forEach forEach} for details. + * + * @method Phaser.Group#forEachAlive + * @param {function} callback - The function that will be called for each applicable child. The child will be passed as the first argument. + * @param {object} callbackContext - The context in which the function should be called (usually 'this'). + * @param {...any} [args=(none)] - Additional arguments to pass to the callback function, after the child item. + */ Phaser.Group.prototype.forEachAlive = function (callback, callbackContext) { - var args; if (arguments.length > 2) @@ -2027,22 +1930,20 @@ Phaser.Group.prototype.forEachAlive = function (callback, callbackContext) } this.iterate('alive', true, Phaser.Group.RETURN_TOTAL, callback, callbackContext, args); - }; /** -* Call a function on each dead child in this group. -* -* See {@link Phaser.Group#forEach forEach} for details. -* -* @method Phaser.Group#forEachDead -* @param {function} callback - The function that will be called for each applicable child. The child will be passed as the first argument. -* @param {object} callbackContext - The context in which the function should be called (usually 'this'). -* @param {...any} [args=(none)] - Additional arguments to pass to the callback function, after the child item. -*/ + * Call a function on each dead child in this group. + * + * See {@link Phaser.Group#forEach forEach} for details. + * + * @method Phaser.Group#forEachDead + * @param {function} callback - The function that will be called for each applicable child. The child will be passed as the first argument. + * @param {object} callbackContext - The context in which the function should be called (usually 'this'). + * @param {...any} [args=(none)] - Additional arguments to pass to the callback function, after the child item. + */ Phaser.Group.prototype.forEachDead = function (callback, callbackContext) { - var args; if (arguments.length > 2) @@ -2056,26 +1957,24 @@ Phaser.Group.prototype.forEachDead = function (callback, callbackContext) } this.iterate('alive', false, Phaser.Group.RETURN_TOTAL, callback, callbackContext, args); - }; /** -* Sort the children in the group according to a particular key and ordering. -* -* Call this function to sort the group according to a particular key value and order. -* -* For example to depth sort Sprites for Zelda-style game you might call `group.sort('y', Phaser.Group.SORT_ASCENDING)` at the bottom of your `State.update()`. -* -* Internally this uses a standard JavaScript Array sort, so everything that applies there also applies here, including -* alphabetical sorting, mixing strings and numbers, and Unicode sorting. See MDN for more details. -* -* @method Phaser.Group#sort -* @param {string} [key='z'] - The name of the property to sort on. Defaults to the objects z-depth value. -* @param {integer} [order=Phaser.Group.SORT_ASCENDING] - Order ascending ({@link Phaser.Group.SORT_ASCENDING SORT_ASCENDING}) or descending ({@link Phaser.Group.SORT_DESCENDING SORT_DESCENDING}). -*/ + * Sort the children in the group according to a particular key and ordering. + * + * Call this function to sort the group according to a particular key value and order. + * + * For example to depth sort Sprites for Zelda-style game you might call `group.sort('y', Phaser.Group.SORT_ASCENDING)` at the bottom of your `State.update()`. + * + * Internally this uses a standard JavaScript Array sort, so everything that applies there also applies here, including + * alphabetical sorting, mixing strings and numbers, and Unicode sorting. See MDN for more details. + * + * @method Phaser.Group#sort + * @param {string} [key='z'] - The name of the property to sort on. Defaults to the objects z-depth value. + * @param {integer} [order=Phaser.Group.SORT_ASCENDING] - Order ascending ({@link Phaser.Group.SORT_ASCENDING SORT_ASCENDING}) or descending ({@link Phaser.Group.SORT_DESCENDING SORT_DESCENDING}). + */ Phaser.Group.prototype.sort = function (key, order) { - if (this.children.length < 2) { // Nothing to swap @@ -2097,22 +1996,20 @@ Phaser.Group.prototype.sort = function (key, order) } this.updateZ(); - }; /** -* Sort the children in the group according to custom sort function. -* -* The `sortHandler` is provided the two parameters: the two children involved in the comparison (a and b). -* It should return -1 if `a > b`, 1 if `a < b` or 0 if `a === b`. -* -* @method Phaser.Group#customSort -* @param {function} sortHandler - The custom sort function. -* @param {object} [context=undefined] - The context in which the sortHandler is called. -*/ + * Sort the children in the group according to custom sort function. + * + * The `sortHandler` is provided the two parameters: the two children involved in the comparison (a and b). + * It should return -1 if `a > b`, 1 if `a < b` or 0 if `a === b`. + * + * @method Phaser.Group#customSort + * @param {function} sortHandler - The custom sort function. + * @param {object} [context=undefined] - The context in which the sortHandler is called. + */ Phaser.Group.prototype.customSort = function (sortHandler, context) { - if (this.children.length < 2) { // Nothing to swap @@ -2122,20 +2019,18 @@ Phaser.Group.prototype.customSort = function (sortHandler, context) this.children.sort(sortHandler.bind(context)); this.updateZ(); - }; /** -* An internal helper function for the sort process. -* -* @method Phaser.Group#ascendingSortHandler -* @protected -* @param {object} a - The first object being sorted. -* @param {object} b - The second object being sorted. -*/ + * An internal helper function for the sort process. + * + * @method Phaser.Group#ascendingSortHandler + * @protected + * @param {object} a - The first object being sorted. + * @param {object} b - The second object being sorted. + */ Phaser.Group.prototype.ascendingSortHandler = function (a, b) { - if (a[this._sortProperty] < b[this._sortProperty]) { return -1; @@ -2153,20 +2048,18 @@ Phaser.Group.prototype.ascendingSortHandler = function (a, b) { return 1; } - }; /** -* An internal helper function for the sort process. -* -* @method Phaser.Group#descendingSortHandler -* @protected -* @param {object} a - The first object being sorted. -* @param {object} b - The second object being sorted. -*/ + * An internal helper function for the sort process. + * + * @method Phaser.Group#descendingSortHandler + * @protected + * @param {object} a - The first object being sorted. + * @param {object} b - The second object being sorted. + */ Phaser.Group.prototype.descendingSortHandler = function (a, b) { - if (a[this._sortProperty] < b[this._sortProperty]) { return 1; @@ -2179,40 +2072,38 @@ Phaser.Group.prototype.descendingSortHandler = function (a, b) { return 0; } - }; /** -* Iterates over the children of the group performing one of several actions for matched children. -* -* A child is considered a match when it has a property, named `key`, whose value is equal to `value` -* according to a strict equality comparison. -* -* The result depends on the `returnType`: -* -* - {@link Phaser.Group.RETURN_TOTAL RETURN_TOTAL}: -* The callback, if any, is applied to all matching children. The number of matched children is returned. -* - {@link Phaser.Group.RETURN_NONE RETURN_NONE}: -* The callback, if any, is applied to all matching children. No value is returned. -* - {@link Phaser.Group.RETURN_CHILD RETURN_CHILD}: -* The callback, if any, is applied to the *first* matching child and the *first* matched child is returned. -* If there is no matching child then null is returned. -* -* If `args` is specified it must be an array. The matched child will be assigned to the first -* element and the entire array will be applied to the callback function. -* -* @method Phaser.Group#iterate -* @param {string} key - The child property to check, i.e. 'exists', 'alive', 'health' -* @param {any} value - A child matches if `child[key] === value` is true. -* @param {integer} returnType - How to iterate the children and what to return. -* @param {function} [callback=null] - Optional function that will be called on each matching child. The matched child is supplied as the first argument. -* @param {object} [callbackContext] - The context in which the function should be called (usually 'this'). -* @param {any[]} [args=(none)] - The arguments supplied to to the callback; the first array index (argument) will be replaced with the matched child. -* @return {any} Returns either an integer (for RETURN_TOTAL), the first matched child (for RETURN_CHILD), or null. -*/ + * Iterates over the children of the group performing one of several actions for matched children. + * + * A child is considered a match when it has a property, named `key`, whose value is equal to `value` + * according to a strict equality comparison. + * + * The result depends on the `returnType`: + * + * - {@link Phaser.Group.RETURN_TOTAL RETURN_TOTAL}: + * The callback, if any, is applied to all matching children. The number of matched children is returned. + * - {@link Phaser.Group.RETURN_NONE RETURN_NONE}: + * The callback, if any, is applied to all matching children. No value is returned. + * - {@link Phaser.Group.RETURN_CHILD RETURN_CHILD}: + * The callback, if any, is applied to the *first* matching child and the *first* matched child is returned. + * If there is no matching child then null is returned. + * + * If `args` is specified it must be an array. The matched child will be assigned to the first + * element and the entire array will be applied to the callback function. + * + * @method Phaser.Group#iterate + * @param {string} key - The child property to check, i.e. 'exists', 'alive', 'health' + * @param {any} value - A child matches if `child[key] === value` is true. + * @param {integer} returnType - How to iterate the children and what to return. + * @param {function} [callback=null] - Optional function that will be called on each matching child. The matched child is supplied as the first argument. + * @param {object} [callbackContext] - The context in which the function should be called (usually 'this'). + * @param {any[]} [args=(none)] - The arguments supplied to to the callback; the first array index (argument) will be replaced with the matched child. + * @return {any} Returns either an integer (for RETURN_TOTAL), the first matched child (for RETURN_CHILD), or null. + */ Phaser.Group.prototype.iterate = function (key, value, returnType, callback, callbackContext, args) { - if (this.children.length === 0) { if (returnType === Phaser.Group.RETURN_TOTAL) @@ -2275,46 +2166,42 @@ Phaser.Group.prototype.iterate = function (key, value, returnType, callback, cal // RETURN_CHILD or RETURN_NONE return null; } - }; /** -* Get the first display object with the given property name and value. -* -* @method Phaser.Group#getFirst -* @param {string} key - The child property to check. -* @param {string} value - A child matches if `child[key] === value` is true. -* @return {DisplayObject} The first child matching the query, or `null` if none were found. -*/ + * Get the first display object with the given property name and value. + * + * @method Phaser.Group#getFirst + * @param {string} key - The child property to check. + * @param {string} value - A child matches if `child[key] === value` is true. + * @return {DisplayObject} The first child matching the query, or `null` if none were found. + */ Phaser.Group.prototype.getFirst = function (key, value) { - return this.iterate(key, value, Phaser.Group.RETURN_CHILD); - }; /** -* Get the first display object that exists, or doesn't exist. -* -* You can use the optional argument `createIfNull` to create a new Game Object if none matching your exists argument were found in this Group. -* -* It works by calling `Group.create` passing it the parameters given to this method, and returning the new child. -* -* If a child *was* found , `createIfNull` is `false` and you provided the additional arguments then the child -* will be reset and/or have a new texture loaded on it. This is handled by `Group.resetChild`. -* -* @method Phaser.Group#getFirstExists -* @param {boolean} [exists=true] - If true, find the first existing child; otherwise find the first non-existing child. -* @param {boolean} [createIfNull=false] - If `true` and no alive children are found a new one is created. -* @param {number} [x] - The x coordinate to reset the child to. The value is in relation to the group.x point. -* @param {number} [y] - The y coordinate to reset the child to. The value is in relation to the group.y point. -* @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|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 Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. -* @param {string|number} [frame] - If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. -* @return {DisplayObject} The first child, or `null` if none found and `createIfNull` was false. -*/ + * Get the first display object that exists, or doesn't exist. + * + * You can use the optional argument `createIfNull` to create a new Game Object if none matching your exists argument were found in this Group. + * + * It works by calling `Group.create` passing it the parameters given to this method, and returning the new child. + * + * If a child *was* found , `createIfNull` is `false` and you provided the additional arguments then the child + * will be reset and/or have a new texture loaded on it. This is handled by `Group.resetChild`. + * + * @method Phaser.Group#getFirstExists + * @param {boolean} [exists=true] - If true, find the first existing child; otherwise find the first non-existing child. + * @param {boolean} [createIfNull=false] - If `true` and no alive children are found a new one is created. + * @param {number} [x] - The x coordinate to reset the child to. The value is in relation to the group.x point. + * @param {number} [y] - The y coordinate to reset the child to. The value is in relation to the group.y point. + * @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|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 Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. + * @param {string|number} [frame] - If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. + * @return {DisplayObject} The first child, or `null` if none found and `createIfNull` was false. + */ Phaser.Group.prototype.getFirstExists = function (exists, createIfNull, x, y, key, frame) { - if (createIfNull === undefined) { createIfNull = false; } if (typeof exists !== 'boolean') @@ -2325,89 +2212,83 @@ Phaser.Group.prototype.getFirstExists = function (exists, createIfNull, x, y, ke var child = this.getFirst('exists', exists); return (child === null && createIfNull) ? this.create(x, y, key, frame) : this.resetChild(child, x, y, key, frame); - }; /** -* Get the first child that is alive (`child.alive === true`). -* -* This is handy for choosing a squad leader, etc. -* -* You can use the optional argument `createIfNull` to create a new Game Object if no alive ones were found in this Group. -* -* It works by calling `Group.create` passing it the parameters given to this method, and returning the new child. -* -* If a child *was* found , `createIfNull` is `false` and you provided the additional arguments then the child -* will be reset and/or have a new texture loaded on it. This is handled by `Group.resetChild`. -* -* @method Phaser.Group#getFirstAlive -* @param {boolean} [createIfNull=false] - If `true` and no alive children are found a new one is created. -* @param {number} [x] - The x coordinate to reset the child to. The value is in relation to the group.x point. -* @param {number} [y] - The y coordinate to reset the child to. The value is in relation to the group.y point. -* @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|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 Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. -* @param {string|number} [frame] - If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. -* @return {DisplayObject} The alive dead child, or `null` if none found and `createIfNull` was false. -*/ + * Get the first child that is alive (`child.alive === true`). + * + * This is handy for choosing a squad leader, etc. + * + * You can use the optional argument `createIfNull` to create a new Game Object if no alive ones were found in this Group. + * + * It works by calling `Group.create` passing it the parameters given to this method, and returning the new child. + * + * If a child *was* found , `createIfNull` is `false` and you provided the additional arguments then the child + * will be reset and/or have a new texture loaded on it. This is handled by `Group.resetChild`. + * + * @method Phaser.Group#getFirstAlive + * @param {boolean} [createIfNull=false] - If `true` and no alive children are found a new one is created. + * @param {number} [x] - The x coordinate to reset the child to. The value is in relation to the group.x point. + * @param {number} [y] - The y coordinate to reset the child to. The value is in relation to the group.y point. + * @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|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 Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. + * @param {string|number} [frame] - If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. + * @return {DisplayObject} The alive dead child, or `null` if none found and `createIfNull` was false. + */ Phaser.Group.prototype.getFirstAlive = function (createIfNull, x, y, key, frame) { - if (createIfNull === undefined) { createIfNull = false; } var child = this.getFirst('alive', true); return (child === null && createIfNull) ? this.create(x, y, key, frame) : this.resetChild(child, x, y, key, frame); - }; /** -* Get the first child that is dead (`child.alive === false`). -* -* This is handy for checking if everything has been wiped out and adding to the pool as needed. -* -* You can use the optional argument `createIfNull` to create a new Game Object if no dead ones were found in this Group. -* -* It works by calling `Group.create` passing it the parameters given to this method, and returning the new child. -* -* If a child *was* found , `createIfNull` is `false` and you provided the additional arguments then the child -* will be reset and/or have a new texture loaded on it. This is handled by `Group.resetChild`. -* -* @method Phaser.Group#getFirstDead -* @param {boolean} [createIfNull=false] - If `true` and no dead children are found a new one is created. -* @param {number} [x] - The x coordinate to reset the child to. The value is in relation to the group.x point. -* @param {number} [y] - The y coordinate to reset the child to. The value is in relation to the group.y point. -* @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|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 Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. -* @param {string|number} [frame] - If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. -* @return {DisplayObject} The first dead child, or `null` if none found and `createIfNull` was false. -*/ + * Get the first child that is dead (`child.alive === false`). + * + * This is handy for checking if everything has been wiped out and adding to the pool as needed. + * + * You can use the optional argument `createIfNull` to create a new Game Object if no dead ones were found in this Group. + * + * It works by calling `Group.create` passing it the parameters given to this method, and returning the new child. + * + * If a child *was* found , `createIfNull` is `false` and you provided the additional arguments then the child + * will be reset and/or have a new texture loaded on it. This is handled by `Group.resetChild`. + * + * @method Phaser.Group#getFirstDead + * @param {boolean} [createIfNull=false] - If `true` and no dead children are found a new one is created. + * @param {number} [x] - The x coordinate to reset the child to. The value is in relation to the group.x point. + * @param {number} [y] - The y coordinate to reset the child to. The value is in relation to the group.y point. + * @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|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 Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. + * @param {string|number} [frame] - If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. + * @return {DisplayObject} The first dead child, or `null` if none found and `createIfNull` was false. + */ Phaser.Group.prototype.getFirstDead = function (createIfNull, x, y, key, frame) { - if (createIfNull === undefined) { createIfNull = false; } var child = this.getFirst('alive', false); return (child === null && createIfNull) ? this.create(x, y, key, frame) : this.resetChild(child, x, y, key, frame); - }; /** -* Takes a child and if the `x` and `y` arguments are given it calls `child.reset(x, y)` on it. -* -* If the `key` and optionally the `frame` arguments are given, it calls `child.loadTexture(key, frame)` on it. -* -* The two operations are separate. For example if you just wish to load a new texture then pass `null` as the x and y values. -* -* @method Phaser.Group#resetChild -* @param {DisplayObject} child - The child to reset and/or load the texture on. -* @param {number} [x] - The x coordinate to reset the child to. The value is in relation to the group.x point. -* @param {number} [y] - The y coordinate to reset the child to. The value is in relation to the group.y point. -* @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|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 Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. -* @param {string|number} [frame] - If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. -* @return {DisplayObject} The child that was reset: usually a {@link Phaser.Sprite}. -*/ + * Takes a child and if the `x` and `y` arguments are given it calls `child.reset(x, y)` on it. + * + * If the `key` and optionally the `frame` arguments are given, it calls `child.loadTexture(key, frame)` on it. + * + * The two operations are separate. For example if you just wish to load a new texture then pass `null` as the x and y values. + * + * @method Phaser.Group#resetChild + * @param {DisplayObject} child - The child to reset and/or load the texture on. + * @param {number} [x] - The x coordinate to reset the child to. The value is in relation to the group.x point. + * @param {number} [y] - The y coordinate to reset the child to. The value is in relation to the group.y point. + * @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|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 Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. + * @param {string|number} [frame] - If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. + * @return {DisplayObject} The child that was reset: usually a {@link Phaser.Sprite}. + */ Phaser.Group.prototype.resetChild = function (child, x, y, key, frame) { - if (child === null) { return null; @@ -2427,66 +2308,60 @@ Phaser.Group.prototype.resetChild = function (child, x, y, key, frame) } return child; - }; /** -* Return the child at the top of this group. -* -* The top child is the child displayed (rendered) above every other child. -* -* @method Phaser.Group#getTop -* @return {any} The child at the top of the Group. -*/ + * Return the child at the top of this group. + * + * The top child is the child displayed (rendered) above every other child. + * + * @method Phaser.Group#getTop + * @return {any} The child at the top of the Group. + */ Phaser.Group.prototype.getTop = function () { - if (this.children.length > 0) { return this.children[this.children.length - 1]; } - }; /** -* Returns the child at the bottom of this group. -* -* The bottom child the child being displayed (rendered) below every other child. -* -* @method Phaser.Group#getBottom -* @return {any} The child at the bottom of the Group. -*/ + * Returns the child at the bottom of this group. + * + * The bottom child the child being displayed (rendered) below every other child. + * + * @method Phaser.Group#getBottom + * @return {any} The child at the bottom of the Group. + */ Phaser.Group.prototype.getBottom = function () { - if (this.children.length > 0) { return this.children[0]; } - }; /** -* Get the closest child to given Object, with optional callback to filter children. -* -* This can be a Sprite, Group, Image or any object with public x and y properties. -* -* 'close' is determined by the distance from the objects `x` and `y` properties compared to the childs `x` and `y` properties. -* -* You can use the optional `callback` argument to apply your own filter to the distance checks. -* If the child is closer then the previous child, it will be sent to `callback` as the first argument, -* with the distance as the second. The callback should return `true` if it passes your -* filtering criteria, otherwise it should return `false`. -* -* @method Phaser.Group#getClosestTo -* @param {any} object - The object used to determine the distance. This can be a Sprite, Group, Image or any object with public x and y properties. -* @param {function} [callback] - The function that each child will be evaluated against. Each child of the group will be passed to it as its first parameter, with the distance as the second. It should return `true` if the child passes the matching criteria. -* @param {object} [callbackContext] - The context in which the function should be called (usually 'this'). -* @return {any} The child closest to given object, or `null` if no child was found. -*/ + * Get the closest child to given Object, with optional callback to filter children. + * + * This can be a Sprite, Group, Image or any object with public x and y properties. + * + * 'close' is determined by the distance from the objects `x` and `y` properties compared to the childs `x` and `y` properties. + * + * You can use the optional `callback` argument to apply your own filter to the distance checks. + * If the child is closer then the previous child, it will be sent to `callback` as the first argument, + * with the distance as the second. The callback should return `true` if it passes your + * filtering criteria, otherwise it should return `false`. + * + * @method Phaser.Group#getClosestTo + * @param {any} object - The object used to determine the distance. This can be a Sprite, Group, Image or any object with public x and y properties. + * @param {function} [callback] - The function that each child will be evaluated against. Each child of the group will be passed to it as its first parameter, with the distance as the second. It should return `true` if the child passes the matching criteria. + * @param {object} [callbackContext] - The context in which the function should be called (usually 'this'). + * @return {any} The child closest to given object, or `null` if no child was found. + */ Phaser.Group.prototype.getClosestTo = function (object, callback, callbackContext) { - var distance = Number.MAX_VALUE; var tempDistance = 0; var result = null; @@ -2508,30 +2383,28 @@ Phaser.Group.prototype.getClosestTo = function (object, callback, callbackContex } return result; - }; /** -* Get the child furthest away from the given Object, with optional callback to filter children. -* -* This can be a Sprite, Group, Image or any object with public x and y properties. -* -* 'furthest away' is determined by the distance from the objects `x` and `y` properties compared to the childs `x` and `y` properties. -* -* You can use the optional `callback` argument to apply your own filter to the distance checks. -* If the child is closer then the previous child, it will be sent to `callback` as the first argument, -* with the distance as the second. The callback should return `true` if it passes your -* filtering criteria, otherwise it should return `false`. -* -* @method Phaser.Group#getFurthestFrom -* @param {any} object - The object used to determine the distance. This can be a Sprite, Group, Image or any object with public x and y properties. -* @param {function} [callback] - The function that each child will be evaluated against. Each child of the group will be passed to it as its first parameter, with the distance as the second. It should return `true` if the child passes the matching criteria. -* @param {object} [callbackContext] - The context in which the function should be called (usually 'this'). -* @return {any} The child furthest from the given object, or `null` if no child was found. -*/ + * Get the child furthest away from the given Object, with optional callback to filter children. + * + * This can be a Sprite, Group, Image or any object with public x and y properties. + * + * 'furthest away' is determined by the distance from the objects `x` and `y` properties compared to the childs `x` and `y` properties. + * + * You can use the optional `callback` argument to apply your own filter to the distance checks. + * If the child is closer then the previous child, it will be sent to `callback` as the first argument, + * with the distance as the second. The callback should return `true` if it passes your + * filtering criteria, otherwise it should return `false`. + * + * @method Phaser.Group#getFurthestFrom + * @param {any} object - The object used to determine the distance. This can be a Sprite, Group, Image or any object with public x and y properties. + * @param {function} [callback] - The function that each child will be evaluated against. Each child of the group will be passed to it as its first parameter, with the distance as the second. It should return `true` if the child passes the matching criteria. + * @param {object} [callbackContext] - The context in which the function should be called (usually 'this'). + * @return {any} The child furthest from the given object, or `null` if no child was found. + */ Phaser.Group.prototype.getFurthestFrom = function (object, callback, callbackContext) { - var distance = 0; var tempDistance = 0; var result = null; @@ -2553,61 +2426,53 @@ Phaser.Group.prototype.getFurthestFrom = function (object, callback, callbackCon } return result; - }; /** -* Get the number of children with the given property name and value. -* -* @method Phaser.Group#count -* @param {string} key - The child property to check. -* @param {string} value - A child matches if `child[key] === value` is true. -* @return {integer} The number of children matching the query. -*/ + * Get the number of children with the given property name and value. + * + * @method Phaser.Group#count + * @param {string} key - The child property to check. + * @param {string} value - A child matches if `child[key] === value` is true. + * @return {integer} The number of children matching the query. + */ Phaser.Group.prototype.count = function (key, value) { - return this.iterate(key, value, Phaser.Group.RETURN_TOTAL); - }; /** -* Get the number of living children in this group. -* -* @method Phaser.Group#countLiving -* @return {integer} The number of children flagged as alive. -*/ + * Get the number of living children in this group. + * + * @method Phaser.Group#countLiving + * @return {integer} The number of children flagged as alive. + */ Phaser.Group.prototype.countLiving = function () { - return this.count('alive', true); - }; /** -* Get the number of dead children in this group. -* -* @method Phaser.Group#countDead -* @return {integer} The number of children flagged as dead. -*/ + * Get the number of dead children in this group. + * + * @method Phaser.Group#countDead + * @return {integer} The number of children flagged as dead. + */ Phaser.Group.prototype.countDead = function () { - return this.count('alive', false); - }; /** -* Returns a random child from the group. -* -* @method Phaser.Group#getRandom -* @param {integer} [startIndex=0] - Offset from the front of the group (lowest child). -* @param {integer} [length=(to top)] - Restriction on the number of values you want to randomly select from. -* @return {any} A random child of this Group. -*/ + * Returns a random child from the group. + * + * @method Phaser.Group#getRandom + * @param {integer} [startIndex=0] - Offset from the front of the group (lowest child). + * @param {integer} [length=(to top)] - Restriction on the number of values you want to randomly select from. + * @return {any} A random child of this Group. + */ Phaser.Group.prototype.getRandom = function (startIndex, length) { - if (startIndex === undefined) { startIndex = 0; } if (length === undefined) { length = this.children.length; } @@ -2617,51 +2482,47 @@ Phaser.Group.prototype.getRandom = function (startIndex, length) } return Phaser.ArrayUtils.getRandomItem(this.children, startIndex, length); - }; /** -* Returns a random child from the Group that has `exists` set to `true`. -* -* Optionally you can specify a start and end index. For example if this Group had 100 children, -* and you set `startIndex` to 0 and `endIndex` to 50, it would return a random child from only -* the first 50 children in the Group. -* -* @method Phaser.Group#getRandomExists -* @param {integer} [startIndex=0] - The first child index to start the search from. -* @param {integer} [endIndex] - The last child index to search up to. -* @return {any} A random child of this Group that exists. -*/ + * Returns a random child from the Group that has `exists` set to `true`. + * + * Optionally you can specify a start and end index. For example if this Group had 100 children, + * and you set `startIndex` to 0 and `endIndex` to 50, it would return a random child from only + * the first 50 children in the Group. + * + * @method Phaser.Group#getRandomExists + * @param {integer} [startIndex=0] - The first child index to start the search from. + * @param {integer} [endIndex] - The last child index to search up to. + * @return {any} A random child of this Group that exists. + */ Phaser.Group.prototype.getRandomExists = function (startIndex, endIndex) { - var list = this.getAll('exists', true, startIndex, endIndex); return this.game.rnd.pick(list); - }; /** -* Returns all children in this Group. -* -* You can optionally specify a matching criteria using the `property` and `value` arguments. -* -* For example: `getAll('exists', true)` would return only children that have an `exists` property equal to `true`. -* -* Optionally you can specify a start and end index. For example if this Group had 100 children, -* and you set `startIndex` to 0 and `endIndex` to 50, it would return the first 50 children in the Group. -* If `property` and `value` are also specified, only children within the given index range are searched. -* -* @method Phaser.Group#getAll -* @param {string} [property] - An optional property to test against the value argument. -* @param {any} [value] - If property is set then Child.property must strictly equal this value to be included in the results. -* @param {integer} [startIndex=0] - The first child index to start the search from. -* @param {integer} [endIndex] - The last child index to search up until. -* @return {array} - An array containing all, some, or none of the Children of this Group. -*/ + * Returns all children in this Group. + * + * You can optionally specify a matching criteria using the `property` and `value` arguments. + * + * For example: `getAll('exists', true)` would return only children that have an `exists` property equal to `true`. + * + * Optionally you can specify a start and end index. For example if this Group had 100 children, + * and you set `startIndex` to 0 and `endIndex` to 50, it would return the first 50 children in the Group. + * If `property` and `value` are also specified, only children within the given index range are searched. + * + * @method Phaser.Group#getAll + * @param {string} [property] - An optional property to test against the value argument. + * @param {any} [value] - If property is set then Child.property must strictly equal this value to be included in the results. + * @param {integer} [startIndex=0] - The first child index to start the search from. + * @param {integer} [endIndex] - The last child index to search up until. + * @return {array} - An array containing all, some, or none of the Children of this Group. + */ Phaser.Group.prototype.getAll = function (property, value, startIndex, endIndex) { - if (startIndex === undefined) { startIndex = 0; } if (endIndex === undefined) { endIndex = this.children.length; } @@ -2685,25 +2546,23 @@ Phaser.Group.prototype.getAll = function (property, value, startIndex, endIndex) } return output; - }; /** -* Removes the given child from this group. -* -* This will dispatch an `onRemovedFromGroup` event from the child (if it has one), and optionally destroy the child. -* -* If the group cursor was referring to the removed child it is updated to refer to the next child. -* -* @method Phaser.Group#remove -* @param {any} child - The child to remove. -* @param {boolean} [destroy=false] - If true `destroy` will be invoked on the removed child. -* @param {boolean} [silent=false] - If true the the child will not dispatch the `onRemovedFromGroup` event. -* @return {boolean} true if the child was removed from this group, otherwise false. -*/ + * Removes the given child from this group. + * + * This will dispatch an `onRemovedFromGroup` event from the child (if it has one), and optionally destroy the child. + * + * If the group cursor was referring to the removed child it is updated to refer to the next child. + * + * @method Phaser.Group#remove + * @param {any} child - The child to remove. + * @param {boolean} [destroy=false] - If true `destroy` will be invoked on the removed child. + * @param {boolean} [silent=false] - If true the the child will not dispatch the `onRemovedFromGroup` event. + * @return {boolean} true if the child was removed from this group, otherwise false. + */ Phaser.Group.prototype.remove = function (child, destroy, silent) { - if (destroy === undefined) { destroy = false; } if (silent === undefined) { silent = false; } @@ -2734,20 +2593,18 @@ Phaser.Group.prototype.remove = function (child, destroy, silent) } return true; - }; /** -* Moves all children from this Group to the Group given. -* -* @method Phaser.Group#moveAll -* @param {Phaser.Group} group - The new Group to which the children will be moved to. -* @param {boolean} [silent=false] - If true the children will not dispatch the `onAddedToGroup` event for the new Group. -* @return {Phaser.Group} The Group to which all the children were moved. -*/ + * Moves all children from this Group to the Group given. + * + * @method Phaser.Group#moveAll + * @param {Phaser.Group} group - The new Group to which the children will be moved to. + * @param {boolean} [silent=false] - If true the children will not dispatch the `onAddedToGroup` event for the new Group. + * @return {Phaser.Group} The Group to which all the children were moved. + */ Phaser.Group.prototype.moveAll = function (group, silent) { - if (silent === undefined) { silent = false; } if (this.children.length > 0 && group instanceof Phaser.Group) @@ -2764,25 +2621,23 @@ Phaser.Group.prototype.moveAll = function (group, silent) } return group; - }; /** -* Removes all children from this Group, but does not remove the group from its parent. -* -* The children can be optionally destroyed as they are removed. -* -* You can also optionally also destroy the BaseTexture the Child is using. Be careful if you've -* more than one Game Object sharing the same BaseTexture. -* -* @method Phaser.Group#removeAll -* @param {boolean} [destroy=false] - If true `destroy` will be invoked on each removed child. -* @param {boolean} [silent=false] - If true the children will not dispatch their `onRemovedFromGroup` events. -* @param {boolean} [destroyTexture=false] - If true, and if the `destroy` argument is also true, the BaseTexture belonging to the Child is also destroyed. Note that if another Game Object is sharing the same BaseTexture it will invalidate it. -*/ + * Removes all children from this Group, but does not remove the group from its parent. + * + * The children can be optionally destroyed as they are removed. + * + * You can also optionally also destroy the BaseTexture the Child is using. Be careful if you've + * more than one Game Object sharing the same BaseTexture. + * + * @method Phaser.Group#removeAll + * @param {boolean} [destroy=false] - If true `destroy` will be invoked on each removed child. + * @param {boolean} [silent=false] - If true the children will not dispatch their `onRemovedFromGroup` events. + * @param {boolean} [destroyTexture=false] - If true, and if the `destroy` argument is also true, the BaseTexture belonging to the Child is also destroyed. Note that if another Game Object is sharing the same BaseTexture it will invalidate it. + */ Phaser.Group.prototype.removeAll = function (destroy, silent, destroyTexture) { - if (destroy === undefined) { destroy = false; } if (silent === undefined) { silent = false; } if (destroyTexture === undefined) { destroyTexture = false; } @@ -2813,21 +2668,19 @@ Phaser.Group.prototype.removeAll = function (destroy, silent, destroyTexture) this.hash = []; this.cursor = null; - }; /** -* Removes all children from this group whose index falls beteen the given startIndex and endIndex values. -* -* @method Phaser.Group#removeBetween -* @param {integer} startIndex - The index to start removing children from. -* @param {integer} [endIndex] - The index to stop removing children at. Must be higher than startIndex. If undefined this method will remove all children between startIndex and the end of the group. -* @param {boolean} [destroy=false] - If true `destroy` will be invoked on each removed child. -* @param {boolean} [silent=false] - If true the children will not dispatch their `onRemovedFromGroup` events. -*/ + * Removes all children from this group whose index falls beteen the given startIndex and endIndex values. + * + * @method Phaser.Group#removeBetween + * @param {integer} startIndex - The index to start removing children from. + * @param {integer} [endIndex] - The index to stop removing children at. Must be higher than startIndex. If undefined this method will remove all children between startIndex and the end of the group. + * @param {boolean} [destroy=false] - If true `destroy` will be invoked on each removed child. + * @param {boolean} [silent=false] - If true the children will not dispatch their `onRemovedFromGroup` events. + */ Phaser.Group.prototype.removeBetween = function (startIndex, endIndex, destroy, silent) { - if (endIndex === undefined) { endIndex = this.children.length - 1; } if (destroy === undefined) { destroy = false; } if (silent === undefined) { silent = false; } @@ -2869,7 +2722,6 @@ Phaser.Group.prototype.removeBetween = function (startIndex, endIndex, destroy, } this.updateZ(); - }; /** @@ -2881,16 +2733,12 @@ Phaser.Group.prototype.removeBetween = function (startIndex, endIndex, destroy, */ Phaser.Group.prototype.scatter = function (rect, checkExists) { - if (rect == null) { rect = this.game.world.bounds; } this.forEach(function (child) { - child.position.set(rect.randomX, rect.randomY); - }, null, checkExists); - }; /** @@ -2902,24 +2750,21 @@ Phaser.Group.prototype.scatter = function (rect, checkExists) */ Phaser.Group.prototype.shuffle = function () { - Phaser.ArrayUtils.shuffle(this.children); this.updateZ(); - }; /** -* Destroys this group. -* -* Removes all children, then removes this group from its parent and nulls references. -* -* @method Phaser.Group#destroy -* @param {boolean} [destroyChildren=true] - If true `destroy` will be invoked on each removed child. -* @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. -*/ + * Destroys this group. + * + * Removes all children, then removes this group from its parent and nulls references. + * + * @method Phaser.Group#destroy + * @param {boolean} [destroyChildren=true] - If true `destroy` will be invoked on each removed child. + * @param {boolean} [soft=false] - A 'soft destroy' (set to true) doesn't remove this group from its parent or null the game reference. Set to false and it does. + */ Phaser.Group.prototype.destroy = function (destroyChildren, soft) { - if (this.game === null || this.ignoreDestroy) { return; } if (destroyChildren === undefined) { destroyChildren = true; } @@ -2943,56 +2788,51 @@ Phaser.Group.prototype.destroy = function (destroyChildren, soft) this.game = null; this.exists = false; } - }; /** -* Total number of existing children in the group. -* -* @name Phaser.Group#total -* @property {integer} total -* @readonly -*/ + * Total number of existing children in the group. + * + * @name Phaser.Group#total + * @property {integer} total + * @readonly + */ Object.defineProperty(Phaser.Group.prototype, 'total', { get: function () { - return this.iterate('exists', true, Phaser.Group.RETURN_TOTAL); - } }); /** -* Total number of children in this group, regardless of exists/alive status. -* -* @name Phaser.Group#length -* @property {integer} length -* @readonly -*/ + * Total number of children in this group, regardless of exists/alive status. + * + * @name Phaser.Group#length + * @property {integer} length + * @readonly + */ Object.defineProperty(Phaser.Group.prototype, 'length', { get: function () { - return this.children.length; - } }); /** -* The angle of rotation of the group container, in degrees. -* -* This adjusts the group itself by modifying its local rotation transform. -* -* This has no impact on the rotation/angle properties of the children, but it will update their worldTransform -* and on-screen orientation and position. -* -* @name Phaser.Group#angle -* @property {number} angle -*/ + * The angle of rotation of the group container, in degrees. + * + * This adjusts the group itself by modifying its local rotation transform. + * + * This has no impact on the rotation/angle properties of the children, but it will update their worldTransform + * and on-screen orientation and position. + * + * @name Phaser.Group#angle + * @property {number} angle + */ Object.defineProperty(Phaser.Group.prototype, 'angle', { get: function () @@ -3008,337 +2848,313 @@ Object.defineProperty(Phaser.Group.prototype, 'angle', { }); /** -* The center x coordinate of this Group. -* -* It is derived by calling `getBounds`, calculating the Groups dimensions based on its -* visible children. -* -* @name Phaser.Group#centerX -* @property {number} centerX -*/ + * The center x coordinate of this Group. + * + * It is derived by calling `getBounds`, calculating the Groups dimensions based on its + * visible children. + * + * @name Phaser.Group#centerX + * @property {number} centerX + */ Object.defineProperty(Phaser.Group.prototype, 'centerX', { get: function () { - return this.getBounds(this.parent).centerX; - }, set: function (value) { - var r = this.getBounds(this.parent); var offset = this.x - r.x; this.x = (value + offset) - r.halfWidth; - } }); /** -* The center y coordinate of this Group. -* -* It is derived by calling `getBounds`, calculating the Groups dimensions based on its -* visible children. -* -* @name Phaser.Group#centerY -* @property {number} centerY -*/ + * The center y coordinate of this Group. + * + * It is derived by calling `getBounds`, calculating the Groups dimensions based on its + * visible children. + * + * @name Phaser.Group#centerY + * @property {number} centerY + */ Object.defineProperty(Phaser.Group.prototype, 'centerY', { get: function () { - return this.getBounds(this.parent).centerY; - }, set: function (value) { - var r = this.getBounds(this.parent); var offset = this.y - r.y; this.y = (value + offset) - r.halfHeight; - } }); /** -* The left coordinate of this Group. -* -* It is derived by calling `getBounds`, calculating the Groups dimensions based on its -* visible children. -* -* @name Phaser.Group#left -* @property {number} left -*/ + * The left coordinate of this Group. + * + * It is derived by calling `getBounds`, calculating the Groups dimensions based on its + * visible children. + * + * @name Phaser.Group#left + * @property {number} left + */ Object.defineProperty(Phaser.Group.prototype, 'left', { get: function () { - return this.getBounds(this.parent).left; - }, set: function (value) { - var r = this.getBounds(this.parent); var offset = this.x - r.x; this.x = value + offset; - } }); /** -* The right coordinate of this Group. -* -* It is derived by calling `getBounds`, calculating the Groups dimensions based on its -* visible children. -* -* @name Phaser.Group#right -* @property {number} right -*/ + * The right coordinate of this Group. + * + * It is derived by calling `getBounds`, calculating the Groups dimensions based on its + * visible children. + * + * @name Phaser.Group#right + * @property {number} right + */ Object.defineProperty(Phaser.Group.prototype, 'right', { get: function () { - return this.getBounds(this.parent).right; - }, set: function (value) { - var r = this.getBounds(this.parent); var offset = this.x - r.x; this.x = (value + offset) - r.width; - } }); /** -* The top coordinate of this Group. -* -* It is derived by calling `getBounds`, calculating the Groups dimensions based on its -* visible children. -* -* @name Phaser.Group#top -* @property {number} top -*/ + * The top coordinate of this Group. + * + * It is derived by calling `getBounds`, calculating the Groups dimensions based on its + * visible children. + * + * @name Phaser.Group#top + * @property {number} top + */ Object.defineProperty(Phaser.Group.prototype, 'top', { get: function () { - return this.getBounds(this.parent).top; - }, set: function (value) { - var r = this.getBounds(this.parent); var offset = this.y - r.y; this.y = (value + offset); - } }); /** -* The bottom coordinate of this Group. -* -* It is derived by calling `getBounds`, calculating the Groups dimensions based on its -* visible children. -* -* @name Phaser.Group#bottom -* @property {number} bottom -*/ + * The bottom coordinate of this Group. + * + * It is derived by calling `getBounds`, calculating the Groups dimensions based on its + * visible children. + * + * @name Phaser.Group#bottom + * @property {number} bottom + */ Object.defineProperty(Phaser.Group.prototype, 'bottom', { get: function () { - return this.getBounds(this.parent).bottom; - }, set: function (value) { - var r = this.getBounds(this.parent); var offset = this.y - r.y; this.y = (value + offset) - r.height; - } }); /** -* Aligns this Group within another Game Object, or Rectangle, known as the -* 'container', to one of 9 possible positions. -* -* The container must be a Game Object, or Phaser.Rectangle object. This can include properties -* such as `World.bounds` or `Camera.view`, for aligning Groups within the world -* and camera bounds. Or it can include other Sprites, Images, Text objects, BitmapText, -* TileSprites or Buttons. -* -* Please note that aligning a Group to another Game Object does **not** make it a child of -* the container. It simply modifies its position coordinates so it aligns with it. -* -* The position constants you can use are: -* -* `Phaser.TOP_LEFT`, `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, -* `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`, -* `Phaser.BOTTOM_CENTER` and `Phaser.BOTTOM_RIGHT`. -* -* Groups are placed in such a way that their _bounds_ align with the -* container, taking into consideration rotation and scale of its children. -* This allows you to neatly align Groups, irrespective of their position value. -* -* The optional `offsetX` and `offsetY` arguments allow you to apply extra spacing to the final -* aligned position of the Group. For example: -* -* `group.alignIn(background, Phaser.BOTTOM_RIGHT, -20, -20)` -* -* Would align the `group` to the bottom-right, but moved 20 pixels in from the corner. -* Think of the offsets as applying an adjustment to the containers bounds before the alignment takes place. -* So providing a negative offset will 'shrink' the container bounds by that amount, and providing a positive -* one expands it. -* -* @method Phaser.Group#alignIn -* @param {Phaser.Rectangle|Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapText|Phaser.Button|Phaser.Graphics|Phaser.TileSprite} container - The Game Object or Rectangle with which to align this Group to. Can also include properties such as `World.bounds` or `Camera.view`. -* @param {integer} [position] - The position constant. One of `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`. -* @param {integer} [offsetX=0] - A horizontal adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. -* @param {integer} [offsetY=0] - A vertical adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. -* @return {Phaser.Group} This Group. -*/ + * Aligns this Group within another Game Object, or Rectangle, known as the + * 'container', to one of 9 possible positions. + * + * The container must be a Game Object, or Phaser.Rectangle object. This can include properties + * such as `World.bounds` or `Camera.view`, for aligning Groups within the world + * and camera bounds. Or it can include other Sprites, Images, Text objects, BitmapText, + * TileSprites or Buttons. + * + * Please note that aligning a Group to another Game Object does **not** make it a child of + * the container. It simply modifies its position coordinates so it aligns with it. + * + * The position constants you can use are: + * + * `Phaser.TOP_LEFT`, `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, + * `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`, + * `Phaser.BOTTOM_CENTER` and `Phaser.BOTTOM_RIGHT`. + * + * Groups are placed in such a way that their _bounds_ align with the + * container, taking into consideration rotation and scale of its children. + * This allows you to neatly align Groups, irrespective of their position value. + * + * The optional `offsetX` and `offsetY` arguments allow you to apply extra spacing to the final + * aligned position of the Group. For example: + * + * `group.alignIn(background, Phaser.BOTTOM_RIGHT, -20, -20)` + * + * Would align the `group` to the bottom-right, but moved 20 pixels in from the corner. + * Think of the offsets as applying an adjustment to the containers bounds before the alignment takes place. + * So providing a negative offset will 'shrink' the container bounds by that amount, and providing a positive + * one expands it. + * + * @method Phaser.Group#alignIn + * @param {Phaser.Rectangle|Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapText|Phaser.Button|Phaser.Graphics|Phaser.TileSprite} container - The Game Object or Rectangle with which to align this Group to. Can also include properties such as `World.bounds` or `Camera.view`. + * @param {integer} [position] - The position constant. One of `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`. + * @param {integer} [offsetX=0] - A horizontal adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. + * @param {integer} [offsetY=0] - A vertical adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. + * @return {Phaser.Group} This Group. + */ // This function is set at the bottom of src/gameobjects/components/Bounds.js /** -* Aligns this Group to the side of another Game Object, or Rectangle, known as the -* 'parent', in one of 11 possible positions. -* -* The parent must be a Game Object, or Phaser.Rectangle object. This can include properties -* such as `World.bounds` or `Camera.view`, for aligning Groups within the world -* and camera bounds. Or it can include other Sprites, Images, Text objects, BitmapText, -* TileSprites or Buttons. -* -* Please note that aligning a Group to another Game Object does **not** make it a child of -* the parent. It simply modifies its position coordinates so it aligns with it. -* -* The position constants you can use are: -* -* `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_TOP`, -* `Phaser.LEFT_CENTER`, `Phaser.LEFT_BOTTOM`, `Phaser.RIGHT_TOP`, `Phaser.RIGHT_CENTER`, -* `Phaser.RIGHT_BOTTOM`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` -* and `Phaser.BOTTOM_RIGHT`. -* -* Groups are placed in such a way that their _bounds_ align with the -* parent, taking into consideration rotation and scale of the children. -* This allows you to neatly align Groups, irrespective of their position value. -* -* The optional `offsetX` and `offsetY` arguments allow you to apply extra spacing to the final -* aligned position of the Group. For example: -* -* `group.alignTo(background, Phaser.BOTTOM_RIGHT, -20, -20)` -* -* Would align the `group` to the bottom-right, but moved 20 pixels in from the corner. -* Think of the offsets as applying an adjustment to the parents bounds before the alignment takes place. -* So providing a negative offset will 'shrink' the parent bounds by that amount, and providing a positive -* one expands it. -* -* @method Phaser.Group#alignTo -* @param {Phaser.Rectangle|Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapText|Phaser.Button|Phaser.Graphics|Phaser.TileSprite} parent - The Game Object or Rectangle with which to align this Group to. Can also include properties such as `World.bounds` or `Camera.view`. -* @param {integer} [position] - The position constant. One of `Phaser.TOP_LEFT`, `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_TOP`, `Phaser.LEFT_CENTER`, `Phaser.LEFT_BOTTOM`, `Phaser.RIGHT_TOP`, `Phaser.RIGHT_CENTER`, `Phaser.RIGHT_BOTTOM`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`. -* @param {integer} [offsetX=0] - A horizontal adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. -* @param {integer} [offsetY=0] - A vertical adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. -* @return {Phaser.Group} This Group. -*/ + * Aligns this Group to the side of another Game Object, or Rectangle, known as the + * 'parent', in one of 11 possible positions. + * + * The parent must be a Game Object, or Phaser.Rectangle object. This can include properties + * such as `World.bounds` or `Camera.view`, for aligning Groups within the world + * and camera bounds. Or it can include other Sprites, Images, Text objects, BitmapText, + * TileSprites or Buttons. + * + * Please note that aligning a Group to another Game Object does **not** make it a child of + * the parent. It simply modifies its position coordinates so it aligns with it. + * + * The position constants you can use are: + * + * `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_TOP`, + * `Phaser.LEFT_CENTER`, `Phaser.LEFT_BOTTOM`, `Phaser.RIGHT_TOP`, `Phaser.RIGHT_CENTER`, + * `Phaser.RIGHT_BOTTOM`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` + * and `Phaser.BOTTOM_RIGHT`. + * + * Groups are placed in such a way that their _bounds_ align with the + * parent, taking into consideration rotation and scale of the children. + * This allows you to neatly align Groups, irrespective of their position value. + * + * The optional `offsetX` and `offsetY` arguments allow you to apply extra spacing to the final + * aligned position of the Group. For example: + * + * `group.alignTo(background, Phaser.BOTTOM_RIGHT, -20, -20)` + * + * Would align the `group` to the bottom-right, but moved 20 pixels in from the corner. + * Think of the offsets as applying an adjustment to the parents bounds before the alignment takes place. + * So providing a negative offset will 'shrink' the parent bounds by that amount, and providing a positive + * one expands it. + * + * @method Phaser.Group#alignTo + * @param {Phaser.Rectangle|Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapText|Phaser.Button|Phaser.Graphics|Phaser.TileSprite} parent - The Game Object or Rectangle with which to align this Group to. Can also include properties such as `World.bounds` or `Camera.view`. + * @param {integer} [position] - The position constant. One of `Phaser.TOP_LEFT`, `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_TOP`, `Phaser.LEFT_CENTER`, `Phaser.LEFT_BOTTOM`, `Phaser.RIGHT_TOP`, `Phaser.RIGHT_CENTER`, `Phaser.RIGHT_BOTTOM`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`. + * @param {integer} [offsetX=0] - A horizontal adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. + * @param {integer} [offsetY=0] - A vertical adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. + * @return {Phaser.Group} This Group. + */ // This function is set at the bottom of src/gameobjects/components/Bounds.js /** -* A display object is any object that can be rendered in the Phaser/pixi.js scene graph: -* -* - {@link PIXI.DisplayObject} -* - {@link PIXI.DisplayObjectContainer} -* - {@link Phaser.BitmapText} -* - {@link Phaser.Creature} -* - {@link Phaser.Graphics} -* - {@link Phaser.Group} -* - {@link Phaser.FlexLayer} -* - {@link Phaser.Particles.Arcade.Emitter} -* - {@link Phaser.Physics.P2.BodyDebug} -* - {@link Phaser.SpriteBatch} -* - {@link Phaser.World} -* - {@link Phaser.Rope} -* - {@link Phaser.Stage} -* - {@link PIXI.Sprite} -* - {@link Phaser.Image} -* - {@link Phaser.Button} -* - {@link Phaser.Sprite} -* - {@link Phaser.Bullet} -* - {@link Phaser.Particle} -* - {@link Phaser.Text} -* - {@link Phaser.TilemapLayer} -* - {@link Phaser.TileSprite} -* -* @typedef {object} DisplayObject -*/ + * A display object is any object that can be rendered in the Phaser/pixi.js scene graph: + * + * - {@link PIXI.DisplayObject} + * - {@link PIXI.DisplayObjectContainer} + * - {@link Phaser.BitmapText} + * - {@link Phaser.Creature} + * - {@link Phaser.Graphics} + * - {@link Phaser.Group} + * - {@link Phaser.FlexLayer} + * - {@link Phaser.Particles.Arcade.Emitter} + * - {@link Phaser.Physics.P2.BodyDebug} + * - {@link Phaser.SpriteBatch} + * - {@link Phaser.World} + * - {@link Phaser.Rope} + * - {@link Phaser.Stage} + * - {@link PIXI.Sprite} + * - {@link Phaser.Image} + * - {@link Phaser.Button} + * - {@link Phaser.Sprite} + * - {@link Phaser.Bullet} + * - {@link Phaser.Particle} + * - {@link Phaser.Text} + * - {@link Phaser.TilemapLayer} + * - {@link Phaser.TileSprite} + * + * @typedef {object} DisplayObject + */ // Documentation stub for linking. /** -* The x coordinate of the group container. -* -* You can adjust the group container itself by modifying its coordinates. -* This will have no impact on the x/y coordinates of its children, but it will update their worldTransform and on-screen position. -* @name Phaser.Group#x -* @property {number} x -*/ + * The x coordinate of the group container. + * + * You can adjust the group container itself by modifying its coordinates. + * This will have no impact on the x/y coordinates of its children, but it will update their worldTransform and on-screen position. + * @name Phaser.Group#x + * @property {number} x + */ /** -* The y coordinate of the group container. -* -* You can adjust the group container itself by modifying its coordinates. -* This will have no impact on the x/y coordinates of its children, but it will update their worldTransform and on-screen position. -* @name Phaser.Group#y -* @property {number} y -*/ + * The y coordinate of the group container. + * + * You can adjust the group container itself by modifying its coordinates. + * This will have no impact on the x/y coordinates of its children, but it will update their worldTransform and on-screen position. + * @name Phaser.Group#y + * @property {number} y + */ /** -* The angle of rotation of the group container, in radians. -* -* This will adjust the group container itself by modifying its rotation. -* This will have no impact on the rotation value of its children, but it will update their worldTransform and on-screen position. -* @name Phaser.Group#rotation -* @property {number} rotation -*/ + * The angle of rotation of the group container, in radians. + * + * This will adjust the group container itself by modifying its rotation. + * This will have no impact on the rotation value of its children, but it will update their worldTransform and on-screen position. + * @name Phaser.Group#rotation + * @property {number} rotation + */ /** -* The visible state of the group. Non-visible Groups and all of their children are not rendered. -* -* @name Phaser.Group#visible -* @property {boolean} visible -*/ + * The visible state of the group. Non-visible Groups and all of their children are not rendered. + * + * @name Phaser.Group#visible + * @property {boolean} visible + */ /** -* The alpha value of the group container. -* -* @name Phaser.Group#alpha -* @property {number} alpha -*/ + * The alpha value of the group container. + * + * @name Phaser.Group#alpha + * @property {number} alpha + */ diff --git a/src/core/Plugin.js b/src/core/Plugin.js index 21fec4870..2e83c03b6 100644 --- a/src/core/Plugin.js +++ b/src/core/Plugin.js @@ -1,138 +1,134 @@ /** -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* This is a base Plugin template to use for any Phaser plugin development. -* -* ##### Callbacks -* -* add | active | visible | remove -* -----|-------------|-------------|-------- -* init | | | -* | preUpdate* | | -* | update* | render* | -* | postUpdate* | postRender* | -* | | | destroy -* -* Update and render calls are repeated (*). -* -* @class Phaser.Plugin -* @constructor -* @param {Phaser.Game} game - A reference to the currently running game. -* @param {any} parent - The object that owns this plugin, usually Phaser.PluginManager. -*/ + * This is a base Plugin template to use for any Phaser plugin development. + * + * ##### Callbacks + * + * add | active | visible | remove + * -----|-------------|-------------|-------- + * init | | | + * | preUpdate* | | + * | update* | render* | + * | postUpdate* | postRender* | + * | | | destroy + * + * Update and render calls are repeated (*). + * + * @class Phaser.Plugin + * @constructor + * @param {Phaser.Game} game - A reference to the currently running game. + * @param {any} parent - The object that owns this plugin, usually Phaser.PluginManager. + */ Phaser.Plugin = function (game, parent) { - if (parent === undefined) { parent = null; } /** - * @property {Phaser.Game} game - A reference to the currently running game. - */ + * @property {Phaser.Game} game - A reference to the currently running game. + */ this.game = game; /** - * @property {any} parent - The parent of this plugin. If added to the PluginManager the parent will be set to that, otherwise it will be null. - */ + * @property {any} parent - The parent of this plugin. If added to the PluginManager the parent will be set to that, otherwise it will be null. + */ this.parent = parent; /** - * @property {boolean} active - A Plugin with active=true has its preUpdate and update methods called by the parent, otherwise they are skipped. - * @default - */ + * @property {boolean} active - A Plugin with active=true has its preUpdate and update methods called by the parent, otherwise they are skipped. + * @default + */ this.active = false; /** - * @property {boolean} visible - A Plugin with visible=true has its render and postRender methods called by the parent, otherwise they are skipped. - * @default - */ + * @property {boolean} visible - A Plugin with visible=true has its render and postRender methods called by the parent, otherwise they are skipped. + * @default + */ this.visible = false; /** - * @property {boolean} hasPreUpdate - A flag to indicate if this plugin has a preUpdate method. - * @default - */ + * @property {boolean} hasPreUpdate - A flag to indicate if this plugin has a preUpdate method. + * @default + */ this.hasPreUpdate = false; /** - * @property {boolean} hasUpdate - A flag to indicate if this plugin has an update method. - * @default - */ + * @property {boolean} hasUpdate - A flag to indicate if this plugin has an update method. + * @default + */ this.hasUpdate = false; /** - * @property {boolean} hasPostUpdate - A flag to indicate if this plugin has a postUpdate method. - * @default - */ + * @property {boolean} hasPostUpdate - A flag to indicate if this plugin has a postUpdate method. + * @default + */ this.hasPostUpdate = false; /** - * @property {boolean} hasRender - A flag to indicate if this plugin has a render method. - * @default - */ + * @property {boolean} hasRender - A flag to indicate if this plugin has a render method. + * @default + */ this.hasRender = false; /** - * @property {boolean} hasPostRender - A flag to indicate if this plugin has a postRender method. - * @default - */ + * @property {boolean} hasPostRender - A flag to indicate if this plugin has a postRender method. + * @default + */ this.hasPostRender = false; - }; Phaser.Plugin.prototype = { /** - * Pre-update is called at the very start of the update cycle, before any other subsystems have been updated (including Physics). - * It is only called if active is set to true. - * @method Phaser.Plugin#preUpdate - */ + * Pre-update is called at the very start of the update cycle, before any other subsystems have been updated (including Physics). + * It is only called if active is set to true. + * @method Phaser.Plugin#preUpdate + */ preUpdate: function () { }, /** - * Update is called after all the core subsystems (Input, Tweens, Sound, etc) and the State have updated, but before the render. - * It is only called if active is set to true. - * @method Phaser.Plugin#update - */ + * Update is called after all the core subsystems (Input, Tweens, Sound, etc) and the State have updated, but before the render. + * It is only called if active is set to true. + * @method Phaser.Plugin#update + */ update: function () { }, /** - * Render is called right after the Game Renderer completes, but before the State.render. - * It is only called if visible is set to true. - * @method Phaser.Plugin#render - */ + * Render is called right after the Game Renderer completes, but before the State.render. + * It is only called if visible is set to true. + * @method Phaser.Plugin#render + */ render: function () { }, /** - * Post-render is called after the Game Renderer and State.render have run. - * It is only called if visible is set to true. - * @method Phaser.Plugin#postRender - */ + * Post-render is called after the Game Renderer and State.render have run. + * It is only called if visible is set to true. + * @method Phaser.Plugin#postRender + */ postRender: function () { }, /** - * Clear down this Plugin and null out references - * @method Phaser.Plugin#destroy - */ + * Clear down this Plugin and null out references + * @method Phaser.Plugin#destroy + */ destroy: function () { - this.game = null; this.parent = null; this.active = false; this.visible = false; - } }; diff --git a/src/core/PluginManager.js b/src/core/PluginManager.js index edcf8149d..c680c3239 100644 --- a/src/core/PluginManager.js +++ b/src/core/PluginManager.js @@ -1,59 +1,56 @@ /* jshint newcap: false */ /** -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* The Plugin Manager is responsible for the loading, running and unloading of Phaser Plugins. -* -* @class Phaser.PluginManager -* @constructor -* @param {Phaser.Game} game - A reference to the currently running game. -*/ + * The Plugin Manager is responsible for the loading, running and unloading of Phaser Plugins. + * + * @class Phaser.PluginManager + * @constructor + * @param {Phaser.Game} game - A reference to the currently running game. + */ Phaser.PluginManager = function (game) { - /** - * @property {Phaser.Game} game - A reference to the currently running game. - */ + * @property {Phaser.Game} game - A reference to the currently running game. + */ this.game = game; /** - * @property {Phaser.Plugin[]} plugins - An array of all the plugins being managed by this PluginManager. - */ + * @property {Phaser.Plugin[]} plugins - An array of all the plugins being managed by this PluginManager. + */ this.plugins = []; /** - * @property {number} _len - Internal cache var. - * @private - */ + * @property {number} _len - Internal cache var. + * @private + */ this._len = 0; /** - * @property {number} _i - Internal cache var. - * @private - */ + * @property {number} _i - Internal cache var. + * @private + */ this._i = 0; - }; Phaser.PluginManager.prototype = { /** - * Add a new Plugin into the PluginManager. - * The Plugin must have 2 properties: game and parent. Plugin.game is set to the game reference the PluginManager uses, and parent is set to the PluginManager. - * - * @method Phaser.PluginManager#add - * @param {object|Phaser.Plugin} plugin - The Plugin to add into the PluginManager. This can be a function or an existing object. - * @param {...*} parameter - Additional arguments that will be passed to the Plugin.init method. - * @return {Phaser.Plugin} The Plugin that was added to the manager. - */ + * Add a new Plugin into the PluginManager. + * The Plugin must have 2 properties: game and parent. Plugin.game is set to the game reference the PluginManager uses, and parent is set to the PluginManager. + * + * @method Phaser.PluginManager#add + * @param {object|Phaser.Plugin} plugin - The Plugin to add into the PluginManager. This can be a function or an existing object. + * @param {...*} parameter - Additional arguments that will be passed to the Plugin.init method. + * @return {Phaser.Plugin} The Plugin that was added to the manager. + */ add: function (plugin) { - var args = Array.prototype.slice.call(arguments, 1); var result = false; @@ -129,15 +126,14 @@ Phaser.PluginManager.prototype = { }, /** - * Remove a Plugin from the PluginManager. It calls Plugin.destroy on the plugin before removing it from the manager. - * - * @method Phaser.PluginManager#remove - * @param {Phaser.Plugin} plugin - The plugin to be removed. - * @param {boolean} [destroy=true] - Call destroy on the plugin that is removed? - */ + * Remove a Plugin from the PluginManager. It calls Plugin.destroy on the plugin before removing it from the manager. + * + * @method Phaser.PluginManager#remove + * @param {Phaser.Plugin} plugin - The plugin to be removed. + * @param {boolean} [destroy=true] - Call destroy on the plugin that is removed? + */ remove: function (plugin, destroy) { - if (destroy === undefined) { destroy = true; } this._i = this._len; @@ -156,17 +152,15 @@ Phaser.PluginManager.prototype = { return; } } - }, /** - * Remove all Plugins from the PluginManager. It calls Plugin.destroy on every plugin before removing it from the manager. - * - * @method Phaser.PluginManager#removeAll - */ + * Remove all Plugins from the PluginManager. It calls Plugin.destroy on every plugin before removing it from the manager. + * + * @method Phaser.PluginManager#removeAll + */ removeAll: function () { - this._i = this._len; while (this._i--) @@ -176,18 +170,16 @@ Phaser.PluginManager.prototype = { this.plugins.length = 0; this._len = 0; - }, /** - * Pre-update is called at the very start of the update cycle, before any other subsystems have been updated (including Physics). - * It only calls plugins who have active=true. - * - * @method Phaser.PluginManager#preUpdate - */ + * Pre-update is called at the very start of the update cycle, before any other subsystems have been updated (including Physics). + * It only calls plugins who have active=true. + * + * @method Phaser.PluginManager#preUpdate + */ preUpdate: function () { - this._i = this._len; while (this._i--) @@ -197,18 +189,16 @@ Phaser.PluginManager.prototype = { this.plugins[this._i].preUpdate(); } } - }, /** - * Update is called after all the core subsystems (Input, Tweens, Sound, etc) and the State have updated, but before the render. - * It only calls plugins who have active=true. - * - * @method Phaser.PluginManager#update - */ + * Update is called after all the core subsystems (Input, Tweens, Sound, etc) and the State have updated, but before the render. + * It only calls plugins who have active=true. + * + * @method Phaser.PluginManager#update + */ update: function () { - this._i = this._len; while (this._i--) @@ -218,19 +208,17 @@ Phaser.PluginManager.prototype = { this.plugins[this._i].update(); } } - }, /** - * PostUpdate is the last thing to be called before the world render. - * In particular, it is called after the world postUpdate, which means the camera has been adjusted. - * It only calls plugins who have active=true. - * - * @method Phaser.PluginManager#postUpdate - */ + * PostUpdate is the last thing to be called before the world render. + * In particular, it is called after the world postUpdate, which means the camera has been adjusted. + * It only calls plugins who have active=true. + * + * @method Phaser.PluginManager#postUpdate + */ postUpdate: function () { - this._i = this._len; while (this._i--) @@ -240,18 +228,16 @@ Phaser.PluginManager.prototype = { this.plugins[this._i].postUpdate(); } } - }, /** - * Render is called right after the Game Renderer completes, but before the State.render. - * It only calls plugins who have visible=true. - * - * @method Phaser.PluginManager#render - */ + * Render is called right after the Game Renderer completes, but before the State.render. + * It only calls plugins who have visible=true. + * + * @method Phaser.PluginManager#render + */ render: function () { - this._i = this._len; while (this._i--) @@ -261,18 +247,16 @@ Phaser.PluginManager.prototype = { this.plugins[this._i].render(); } } - }, /** - * Post-render is called after the Game Renderer and State.render have run. - * It only calls plugins who have visible=true. - * - * @method Phaser.PluginManager#postRender - */ + * Post-render is called after the Game Renderer and State.render have run. + * It only calls plugins who have visible=true. + * + * @method Phaser.PluginManager#postRender + */ postRender: function () { - this._i = this._len; while (this._i--) @@ -282,21 +266,18 @@ Phaser.PluginManager.prototype = { this.plugins[this._i].postRender(); } } - }, /** - * Clear down this PluginManager, calls destroy on every plugin and nulls out references. - * - * @method Phaser.PluginManager#destroy - */ + * Clear down this PluginManager, calls destroy on every plugin and nulls out references. + * + * @method Phaser.PluginManager#destroy + */ destroy: function () { - this.removeAll(); this.game = null; - } }; diff --git a/src/core/ScaleManager.js b/src/core/ScaleManager.js index 668518a00..a3f8e1222 100644 --- a/src/core/ScaleManager.js +++ b/src/core/ScaleManager.js @@ -1,435 +1,434 @@ /** -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* @classdesc -* The ScaleManager object handles the the scaling, resizing, and alignment of the -* Game size and the game Display canvas. -* -* The Game size is the logical size of the game; the Display canvas has size as an HTML element. -* -* The calculations of these are heavily influenced by the bounding Parent size which is the computed -* dimensions of the Display canvas's Parent container/element - the _effective CSS rules of the -* canvas's Parent element play an important role_ in the operation of the ScaleManager. -* -* The Display canvas - or Game size, depending {@link #scaleMode} - is updated to best utilize the Parent size. -* When in Fullscreen mode or with {@link #parentIsWindow} the Parent size is that of the visual viewport (see {@link Phaser.ScaleManager#getParentBounds getParentBounds}). -* -* #### Parent and Display canvas containment guidelines: -* -* - Style the Parent element (of the game canvas) to control the Parent size and -* thus the Display canvas's size and layout. -* -* - The Parent element's CSS styles should _effectively_ apply maximum (and minimum) bounding behavior. -* -* - The Parent element should _not_ apply a padding as this is not accounted for. -* If a padding is required apply it to the Parent's parent or apply a margin to the Parent. -* If you need to add a border, margin or any other CSS around your game container, then use a parent element and -* apply the CSS to this instead, otherwise you'll be constantly resizing the shape of the game container. -* -* - The Display canvas layout CSS styles (i.e. margins, size) should not be altered/specified as -* they may be updated by the ScaleManager. -* -* #### Example Uses -* -* - ##### Fixed game size; scale canvas proportionally to fill its container -* -* Use `scaleMode` SHOW_ALL. -* -* - ##### Fixed game size; stretch canvas to fill its container (uncommon) -* -* Use `scaleMode` EXACT_FIT. -* -* - ##### Fixed game size; scale canvas proportionally by some other criteria -* -* Use `scaleMode` USER_SCALE. Examine `parentBounds` in the {@link #setResizeCallback resize callback} and call {@link #setUserScale} if necessary. -* -* - ##### Fluid game/canvas size -* -* Use `scaleMode` RESIZE. Examine the game or canvas size from the {@link #onSizeChange} signal **or** the {@link Phaser.State#resize} callback and reposition game objects if necessary. -* -* - ##### Preferred orientation -* -* Call {@link #forceOrientation} with the preferred orientation and use any of the {@link #onOrientationChange}, {@link #enterIncorrectOrientation}, or {@link #leaveIncorrectOrientation} signals. -* -* @description -* Create a new ScaleManager object - this is done automatically by {@link Phaser.Game} -* -* The `width` and `height` constructor parameters can either be a number which represents pixels or a string that represents a percentage: e.g. `800` (for 800 pixels) or `"80%"` for 80%. -* -* @class -* @param {Phaser.Game} game - A reference to the currently running game. -* @param {number|string} width - The width of the game. See above. -* @param {number|string} height - The height of the game. See above. -*/ + * @classdesc + * The ScaleManager object handles the the scaling, resizing, and alignment of the + * Game size and the game Display canvas. + * + * The Game size is the logical size of the game; the Display canvas has size as an HTML element. + * + * The calculations of these are heavily influenced by the bounding Parent size which is the computed + * dimensions of the Display canvas's Parent container/element - the _effective CSS rules of the + * canvas's Parent element play an important role_ in the operation of the ScaleManager. + * + * The Display canvas - or Game size, depending {@link #scaleMode} - is updated to best utilize the Parent size. + * When in Fullscreen mode or with {@link #parentIsWindow} the Parent size is that of the visual viewport (see {@link Phaser.ScaleManager#getParentBounds getParentBounds}). + * + * #### Parent and Display canvas containment guidelines: + * + * - Style the Parent element (of the game canvas) to control the Parent size and + * thus the Display canvas's size and layout. + * + * - The Parent element's CSS styles should _effectively_ apply maximum (and minimum) bounding behavior. + * + * - The Parent element should _not_ apply a padding as this is not accounted for. + * If a padding is required apply it to the Parent's parent or apply a margin to the Parent. + * If you need to add a border, margin or any other CSS around your game container, then use a parent element and + * apply the CSS to this instead, otherwise you'll be constantly resizing the shape of the game container. + * + * - The Display canvas layout CSS styles (i.e. margins, size) should not be altered/specified as + * they may be updated by the ScaleManager. + * + * #### Example Uses + * + * - ##### Fixed game size; scale canvas proportionally to fill its container + * + * Use `scaleMode` SHOW_ALL. + * + * - ##### Fixed game size; stretch canvas to fill its container (uncommon) + * + * Use `scaleMode` EXACT_FIT. + * + * - ##### Fixed game size; scale canvas proportionally by some other criteria + * + * Use `scaleMode` USER_SCALE. Examine `parentBounds` in the {@link #setResizeCallback resize callback} and call {@link #setUserScale} if necessary. + * + * - ##### Fluid game/canvas size + * + * Use `scaleMode` RESIZE. Examine the game or canvas size from the {@link #onSizeChange} signal **or** the {@link Phaser.State#resize} callback and reposition game objects if necessary. + * + * - ##### Preferred orientation + * + * Call {@link #forceOrientation} with the preferred orientation and use any of the {@link #onOrientationChange}, {@link #enterIncorrectOrientation}, or {@link #leaveIncorrectOrientation} signals. + * + * @description + * Create a new ScaleManager object - this is done automatically by {@link Phaser.Game} + * + * The `width` and `height` constructor parameters can either be a number which represents pixels or a string that represents a percentage: e.g. `800` (for 800 pixels) or `"80%"` for 80%. + * + * @class + * @param {Phaser.Game} game - A reference to the currently running game. + * @param {number|string} width - The width of the game. See above. + * @param {number|string} height - The height of the game. See above. + */ Phaser.ScaleManager = function (game, width, height) { - /** - * A reference to the currently running game. - * @property {Phaser.Game} game - * @protected - * @readonly - */ + * A reference to the currently running game. + * @property {Phaser.Game} game + * @protected + * @readonly + */ this.game = game; /** - * Provides access to some cross-device DOM functions. - * @property {Phaser.DOM} dom - * @protected - * @readonly - */ + * Provides access to some cross-device DOM functions. + * @property {Phaser.DOM} dom + * @protected + * @readonly + */ this.dom = Phaser.DOM; /** - * _EXPERIMENTAL:_ A responsive grid on which you can align game objects. - * @property {Phaser.FlexGrid} grid - * @public - */ + * _EXPERIMENTAL:_ A responsive grid on which you can align game objects. + * @property {Phaser.FlexGrid} grid + * @public + */ this.grid = null; /** - * Target width (in pixels) of the Display canvas. - * @property {number} width - * @readonly - */ + * Target width (in pixels) of the Display canvas. + * @property {number} width + * @readonly + */ this.width = 0; /** - * Target height (in pixels) of the Display canvas. - * @property {number} height - * @readonly - */ + * Target height (in pixels) of the Display canvas. + * @property {number} height + * @readonly + */ this.height = 0; /** - * Minimum width the canvas should be scaled to (in pixels). - * Change with {@link #setMinMax}. - * @property {?number} minWidth - * @readonly - * @protected - */ + * Minimum width the canvas should be scaled to (in pixels). + * Change with {@link #setMinMax}. + * @property {?number} minWidth + * @readonly + * @protected + */ this.minWidth = null; /** - * Maximum width the canvas should be scaled to (in pixels). - * If null it will scale to whatever width the browser can handle. - * Change with {@link #setMinMax}. - * @property {?number} maxWidth - * @readonly - * @protected - */ + * Maximum width the canvas should be scaled to (in pixels). + * If null it will scale to whatever width the browser can handle. + * Change with {@link #setMinMax}. + * @property {?number} maxWidth + * @readonly + * @protected + */ this.maxWidth = null; /** - * Minimum height the canvas should be scaled to (in pixels). - * Change with {@link #setMinMax}. - * @property {?number} minHeight - * @readonly - * @protected - */ + * Minimum height the canvas should be scaled to (in pixels). + * Change with {@link #setMinMax}. + * @property {?number} minHeight + * @readonly + * @protected + */ this.minHeight = null; /** - * Maximum height the canvas should be scaled to (in pixels). - * If null it will scale to whatever height the browser can handle. - * Change with {@link #setMinMax}. - * @property {?number} maxHeight - * @readonly - * @protected - */ + * Maximum height the canvas should be scaled to (in pixels). + * If null it will scale to whatever height the browser can handle. + * Change with {@link #setMinMax}. + * @property {?number} maxHeight + * @readonly + * @protected + */ this.maxHeight = null; /** - * The offset coordinates of the Display canvas from the top-left of the browser window. - * The is used internally by Phaser.Pointer (for Input) and possibly other types. - * @property {Phaser.Point} offset - * @readonly - * @protected - */ + * The offset coordinates of the Display canvas from the top-left of the browser window. + * The is used internally by Phaser.Pointer (for Input) and possibly other types. + * @property {Phaser.Point} offset + * @readonly + * @protected + */ this.offset = new Phaser.Point(); /** - * If true, the game should only run in a landscape orientation. - * Change with {@link #forceOrientation}. - * @property {boolean} forceLandscape - * @readonly - * @default - * @protected - */ + * If true, the game should only run in a landscape orientation. + * Change with {@link #forceOrientation}. + * @property {boolean} forceLandscape + * @readonly + * @default + * @protected + */ this.forceLandscape = false; /** - * If true, the game should only run in a portrait - * Change with {@link #forceOrientation}. - * @property {boolean} forcePortrait - * @readonly - * @default - * @protected - */ + * If true, the game should only run in a portrait + * Change with {@link #forceOrientation}. + * @property {boolean} forcePortrait + * @readonly + * @default + * @protected + */ this.forcePortrait = false; /** - * True if {@link #forceLandscape} or {@link #forcePortrait} are set and do not agree with the browser orientation. - * - * This value is not updated immediately. - * - * @property {boolean} incorrectOrientation - * @readonly - * @protected - */ + * True if {@link #forceLandscape} or {@link #forcePortrait} are set and do not agree with the browser orientation. + * + * This value is not updated immediately. + * + * @property {boolean} incorrectOrientation + * @readonly + * @protected + */ this.incorrectOrientation = false; /** - * See {@link #pageAlignHorizontally}. - * @property {boolean} _pageAlignHorizontally - * @private - */ + * See {@link #pageAlignHorizontally}. + * @property {boolean} _pageAlignHorizontally + * @private + */ this._pageAlignHorizontally = false; /** - * See {@link #pageAlignVertically}. - * @property {boolean} _pageAlignVertically - * @private - */ + * See {@link #pageAlignVertically}. + * @property {boolean} _pageAlignVertically + * @private + */ this._pageAlignVertically = false; /** - * This signal is dispatched when the orientation changes _or_ the validity of the current orientation changes. - * - * The signal is supplied with the following arguments: - * - `scale` - the ScaleManager object - * - `prevOrientation`, a string - The previous orientation as per {@link Phaser.ScaleManager#screenOrientation screenOrientation}. - * - `wasIncorrect`, a boolean - True if the previous orientation was last determined to be incorrect. - * - * Access the current orientation and validity with `scale.screenOrientation` and `scale.incorrectOrientation`. - * Thus the following tests can be done: - * - * // The orientation itself changed: - * scale.screenOrientation !== prevOrientation - * // The orientation just became incorrect: - * scale.incorrectOrientation && !wasIncorrect - * - * It is possible that this signal is triggered after {@link #forceOrientation} so the orientation - * correctness changes even if the orientation itself does not change. - * - * This is signaled from `preUpdate` (or `pauseUpdate`) _even when_ the game is paused. - * - * @property {Phaser.Signal} onOrientationChange - * @public - */ + * This signal is dispatched when the orientation changes _or_ the validity of the current orientation changes. + * + * The signal is supplied with the following arguments: + * - `scale` - the ScaleManager object + * - `prevOrientation`, a string - The previous orientation as per {@link Phaser.ScaleManager#screenOrientation screenOrientation}. + * - `wasIncorrect`, a boolean - True if the previous orientation was last determined to be incorrect. + * + * Access the current orientation and validity with `scale.screenOrientation` and `scale.incorrectOrientation`. + * Thus the following tests can be done: + * + * // The orientation itself changed: + * scale.screenOrientation !== prevOrientation + * // The orientation just became incorrect: + * scale.incorrectOrientation && !wasIncorrect + * + * It is possible that this signal is triggered after {@link #forceOrientation} so the orientation + * correctness changes even if the orientation itself does not change. + * + * This is signaled from `preUpdate` (or `pauseUpdate`) _even when_ the game is paused. + * + * @property {Phaser.Signal} onOrientationChange + * @public + */ this.onOrientationChange = new Phaser.Signal(); /** - * This signal is dispatched when the browser enters an incorrect orientation, as defined by {@link #forceOrientation}. - * - * This is signaled from `preUpdate` (or `pauseUpdate`) _even when_ the game is paused. - * - * @property {Phaser.Signal} enterIncorrectOrientation - * @public - */ + * This signal is dispatched when the browser enters an incorrect orientation, as defined by {@link #forceOrientation}. + * + * This is signaled from `preUpdate` (or `pauseUpdate`) _even when_ the game is paused. + * + * @property {Phaser.Signal} enterIncorrectOrientation + * @public + */ this.enterIncorrectOrientation = new Phaser.Signal(); /** - * This signal is dispatched when the browser leaves an incorrect orientation, as defined by {@link #forceOrientation}. - * - * This is signaled from `preUpdate` (or `pauseUpdate`) _even when_ the game is paused. - * - * @property {Phaser.Signal} leaveIncorrectOrientation - * @public - */ + * This signal is dispatched when the browser leaves an incorrect orientation, as defined by {@link #forceOrientation}. + * + * This is signaled from `preUpdate` (or `pauseUpdate`) _even when_ the game is paused. + * + * @property {Phaser.Signal} leaveIncorrectOrientation + * @public + */ this.leaveIncorrectOrientation = new Phaser.Signal(); /** - * This boolean provides you with a way to determine if the browser is in Full Screen - * mode (via the Full Screen API), and Phaser was the one responsible for activating it. - * - * It's possible that ScaleManager.isFullScreen returns `true` even if Phaser wasn't the - * one that made the browser go full-screen, so this flag lets you determine that. - * - * @property {boolean} hasPhaserSetFullScreen - * @default - */ + * This boolean provides you with a way to determine if the browser is in Full Screen + * mode (via the Full Screen API), and Phaser was the one responsible for activating it. + * + * It's possible that ScaleManager.isFullScreen returns `true` even if Phaser wasn't the + * one that made the browser go full-screen, so this flag lets you determine that. + * + * @property {boolean} hasPhaserSetFullScreen + * @default + */ this.hasPhaserSetFullScreen = false; /** - * If specified, this is the DOM element on which the Fullscreen API enter request will be invoked. - * The target element must have the correct CSS styling and contain the Display canvas. - * - * The elements style will be modified (ie. the width and height might be set to 100%) - * but it will not be added to, removed from, or repositioned within the DOM. - * An attempt is made to restore relevant style changes when fullscreen mode is left. - * - * For pre-2.2.0 behavior set `game.scale.fullScreenTarget = game.canvas`. - * - * @property {?DOMElement} fullScreenTarget - * @default - */ + * If specified, this is the DOM element on which the Fullscreen API enter request will be invoked. + * The target element must have the correct CSS styling and contain the Display canvas. + * + * The elements style will be modified (ie. the width and height might be set to 100%) + * but it will not be added to, removed from, or repositioned within the DOM. + * An attempt is made to restore relevant style changes when fullscreen mode is left. + * + * For pre-2.2.0 behavior set `game.scale.fullScreenTarget = game.canvas`. + * + * @property {?DOMElement} fullScreenTarget + * @default + */ this.fullScreenTarget = null; /** - * The fullscreen target, as created by {@link #createFullScreenTarget}. - * This is not set if {@link #fullScreenTarget} is used and is cleared when fullscreen mode ends. - * @property {?DOMElement} _createdFullScreenTarget - * @private - */ + * The fullscreen target, as created by {@link #createFullScreenTarget}. + * This is not set if {@link #fullScreenTarget} is used and is cleared when fullscreen mode ends. + * @property {?DOMElement} _createdFullScreenTarget + * @private + */ this._createdFullScreenTarget = null; /** - * This signal is dispatched when fullscreen mode is ready to be initialized but - * before the fullscreen request. - * - * The signal is passed two arguments: `scale` (the ScaleManager), and an object in the form `{targetElement: DOMElement}`. - * - * The `targetElement` is the {@link #fullScreenTarget} element, - * if such is assigned, or a new element created by {@link #createFullScreenTarget}. - * - * Custom CSS styling or resets can be applied to `targetElement` as required. - * - * If `targetElement` is _not_ the same element as {@link #fullScreenTarget}: - * - After initialization the Display canvas is moved onto the `targetElement` for - * the duration of the fullscreen mode, and restored to it's original DOM location when fullscreen is exited. - * - The `targetElement` is moved/re-parented within the DOM and may have its CSS styles updated. - * - * The behavior of a pre-assigned target element is covered in {@link Phaser.ScaleManager#fullScreenTarget fullScreenTarget}. - * - * @property {Phaser.Signal} onFullScreenInit - * @public - */ + * This signal is dispatched when fullscreen mode is ready to be initialized but + * before the fullscreen request. + * + * The signal is passed two arguments: `scale` (the ScaleManager), and an object in the form `{targetElement: DOMElement}`. + * + * The `targetElement` is the {@link #fullScreenTarget} element, + * if such is assigned, or a new element created by {@link #createFullScreenTarget}. + * + * Custom CSS styling or resets can be applied to `targetElement` as required. + * + * If `targetElement` is _not_ the same element as {@link #fullScreenTarget}: + * - After initialization the Display canvas is moved onto the `targetElement` for + * the duration of the fullscreen mode, and restored to it's original DOM location when fullscreen is exited. + * - The `targetElement` is moved/re-parented within the DOM and may have its CSS styles updated. + * + * The behavior of a pre-assigned target element is covered in {@link Phaser.ScaleManager#fullScreenTarget fullScreenTarget}. + * + * @property {Phaser.Signal} onFullScreenInit + * @public + */ this.onFullScreenInit = new Phaser.Signal(); /** - * This signal is dispatched when the browser enters or leaves fullscreen mode, if supported. - * - * The signal is supplied with a single argument: `scale` (the ScaleManager). Use `scale.isFullScreen` to determine - * if currently running in Fullscreen mode. - * - * @property {Phaser.Signal} onFullScreenChange - * @public - */ + * This signal is dispatched when the browser enters or leaves fullscreen mode, if supported. + * + * The signal is supplied with a single argument: `scale` (the ScaleManager). Use `scale.isFullScreen` to determine + * if currently running in Fullscreen mode. + * + * @property {Phaser.Signal} onFullScreenChange + * @public + */ this.onFullScreenChange = new Phaser.Signal(); /** - * This signal is dispatched when the browser fails to enter fullscreen mode; - * or if the device does not support fullscreen mode and `startFullScreen` is invoked. - * - * The signal is supplied with a single argument: `scale` (the ScaleManager). - * - * @property {Phaser.Signal} onFullScreenError - * @public - */ + * This signal is dispatched when the browser fails to enter fullscreen mode; + * or if the device does not support fullscreen mode and `startFullScreen` is invoked. + * + * The signal is supplied with a single argument: `scale` (the ScaleManager). + * + * @property {Phaser.Signal} onFullScreenError + * @public + */ this.onFullScreenError = new Phaser.Signal(); /** - * The _last known_ orientation of the screen, as defined in the Window Screen Web API. - * See {@link Phaser.DOM.getScreenOrientation} for possible values. - * - * @property {string} screenOrientation - * @readonly - * @public - */ + * The _last known_ orientation of the screen, as defined in the Window Screen Web API. + * See {@link Phaser.DOM.getScreenOrientation} for possible values. + * + * @property {string} screenOrientation + * @readonly + * @public + */ this.screenOrientation = this.dom.getScreenOrientation(); /** - * The _current_ scale factor based on the game dimensions vs. the scaled dimensions. - * @property {Phaser.Point} scaleFactor - * @readonly - */ + * The _current_ scale factor based on the game dimensions vs. the scaled dimensions. + * @property {Phaser.Point} scaleFactor + * @readonly + */ this.scaleFactor = new Phaser.Point(1, 1); /** - * The _current_ inversed scale factor. The displayed dimensions divided by the game dimensions. - * @property {Phaser.Point} scaleFactorInversed - * @readonly - * @protected - */ + * The _current_ inversed scale factor. The displayed dimensions divided by the game dimensions. + * @property {Phaser.Point} scaleFactorInversed + * @readonly + * @protected + */ this.scaleFactorInversed = new Phaser.Point(1, 1); /** - * The Display canvas is aligned by adjusting the margins; the last margins are stored here. - * - * @property {Bounds-like} margin - * @readonly - * @protected - */ + * The Display canvas is aligned by adjusting the margins; the last margins are stored here. + * + * @property {Bounds-like} margin + * @readonly + * @protected + */ this.margin = {left: 0, top: 0, right: 0, bottom: 0, x: 0, y: 0}; /** - * The bounds of the scaled game. The x/y will match the offset of the canvas element and the width/height the scaled width and height. - * @property {Phaser.Rectangle} bounds - * @readonly - */ + * The bounds of the scaled game. The x/y will match the offset of the canvas element and the width/height the scaled width and height. + * @property {Phaser.Rectangle} bounds + * @readonly + */ this.bounds = new Phaser.Rectangle(); /** - * The aspect ratio of the scaled Display canvas. - * @property {number} aspectRatio - * @readonly - */ + * The aspect ratio of the scaled Display canvas. + * @property {number} aspectRatio + * @readonly + */ this.aspectRatio = 0; /** - * The aspect ratio of the original game dimensions. - * @property {number} sourceAspectRatio - * @readonly - */ + * The aspect ratio of the original game dimensions. + * @property {number} sourceAspectRatio + * @readonly + */ this.sourceAspectRatio = 0; /** - * The native browser events from Fullscreen API changes. - * @property {any} event - * @readonly - * @private - */ + * The native browser events from Fullscreen API changes. + * @property {any} event + * @readonly + * @private + */ this.event = null; /** - * The edges on which to constrain the game Display/canvas in _addition_ to the restrictions of the parent container. - * - * The properties are strings and can be '', 'visual', 'layout', or 'layout-soft'. - * - If 'visual', the edge will be constrained to the Window / displayed screen area - * - If 'layout', the edge will be constrained to the CSS Layout bounds - * - An invalid value is treated as 'visual' - * - * @member - * @property {string} bottom - * @property {string} right - * @default - */ + * The edges on which to constrain the game Display/canvas in _addition_ to the restrictions of the parent container. + * + * The properties are strings and can be '', 'visual', 'layout', or 'layout-soft'. + * - If 'visual', the edge will be constrained to the Window / displayed screen area + * - If 'layout', the edge will be constrained to the CSS Layout bounds + * - An invalid value is treated as 'visual' + * + * @member + * @property {string} bottom + * @property {string} right + * @default + */ this.windowConstraints = { right: 'layout', bottom: '' }; /** - * Various compatibility settings. - * A value of "(auto)" indicates the setting is configured based on device and runtime information. - * - * A {@link #refresh} may need to be performed after making changes. - * - * @protected - * - * @property {boolean} [supportsFullScreen=(auto)] - True only if fullscreen support will be used. (Changing to fullscreen still might not work.) - * - * @property {boolean} [orientationFallback=(auto)] - See {@link Phaser.DOM.getScreenOrientation}. - * - * @property {boolean} [noMargins=false] - If true then the Display canvas's margins will not be updated anymore: existing margins must be manually cleared. Disabling margins prevents automatic canvas alignment/centering, possibly in fullscreen. - * - * @property {?Phaser.Point} [scrollTo=(auto)] - If specified the window will be scrolled to this position on every refresh. - * - * @property {boolean} [forceMinimumDocumentHeight=false] - If enabled the document elements minimum height is explicitly set on updates. - * The height set varies by device and may either be the height of the window or the viewport. - * - * @property {boolean} [canExpandParent=true] - If enabled then SHOW_ALL and USER_SCALE modes can try and expand the parent element. It may be necessary for the parent element to impose CSS width/height restrictions. - * - * @property {string} [clickTrampoline=(auto)] - On certain browsers (eg. IE) FullScreen events need to be triggered via 'click' events. - * A value of 'when-not-mouse' uses a click trampoline when a pointer that is not the primary mouse is used. - * Any other string value (including the empty string) prevents using click trampolines. - * For more details on click trampolines see {@link Phaser.Pointer#addClickTrampoline}. - */ + * Various compatibility settings. + * A value of "(auto)" indicates the setting is configured based on device and runtime information. + * + * A {@link #refresh} may need to be performed after making changes. + * + * @protected + * + * @property {boolean} [supportsFullScreen=(auto)] - True only if fullscreen support will be used. (Changing to fullscreen still might not work.) + * + * @property {boolean} [orientationFallback=(auto)] - See {@link Phaser.DOM.getScreenOrientation}. + * + * @property {boolean} [noMargins=false] - If true then the Display canvas's margins will not be updated anymore: existing margins must be manually cleared. Disabling margins prevents automatic canvas alignment/centering, possibly in fullscreen. + * + * @property {?Phaser.Point} [scrollTo=(auto)] - If specified the window will be scrolled to this position on every refresh. + * + * @property {boolean} [forceMinimumDocumentHeight=false] - If enabled the document elements minimum height is explicitly set on updates. + * The height set varies by device and may either be the height of the window or the viewport. + * + * @property {boolean} [canExpandParent=true] - If enabled then SHOW_ALL and USER_SCALE modes can try and expand the parent element. It may be necessary for the parent element to impose CSS width/height restrictions. + * + * @property {string} [clickTrampoline=(auto)] - On certain browsers (eg. IE) FullScreen events need to be triggered via 'click' events. + * A value of 'when-not-mouse' uses a click trampoline when a pointer that is not the primary mouse is used. + * Any other string value (including the empty string) prevents using click trampolines. + * For more details on click trampolines see {@link Phaser.Pointer#addClickTrampoline}. + */ this.compatibility = { supportsFullScreen: false, orientationFallback: null, @@ -441,181 +440,181 @@ Phaser.ScaleManager = function (game, width, height) }; /** - * Scale mode to be used when not in fullscreen. - * @property {number} _scaleMode - * @private - */ + * Scale mode to be used when not in fullscreen. + * @property {number} _scaleMode + * @private + */ this._scaleMode = Phaser.ScaleManager.NO_SCALE; /* - * Scale mode to be used in fullscreen. - * @property {number} _fullScreenScaleMode - * @private - */ + * Scale mode to be used in fullscreen. + * @property {number} _fullScreenScaleMode + * @private + */ this._fullScreenScaleMode = Phaser.ScaleManager.NO_SCALE; /** - * True if the the browser window (instead of the display canvas's DOM parent) should be used as the bounding parent. - * - * This is set automatically based on the `parent` argument passed to {@link Phaser.Game}. - * - * The {@link #parentNode} property is generally ignored while this is in effect. - * - * @property {boolean} parentIsWindow - */ + * True if the the browser window (instead of the display canvas's DOM parent) should be used as the bounding parent. + * + * This is set automatically based on the `parent` argument passed to {@link Phaser.Game}. + * + * The {@link #parentNode} property is generally ignored while this is in effect. + * + * @property {boolean} parentIsWindow + */ this.parentIsWindow = false; /** - * The _original_ DOM element for the parent of the Display canvas. - * This may be different in fullscreen - see {@link #createFullScreenTarget}. - * - * This is set automatically based on the `parent` argument passed to {@link Phaser.Game}. - * - * This should only be changed after moving the Game canvas to a different DOM parent. - * - * @property {?DOMElement} parentNode - */ + * The _original_ DOM element for the parent of the Display canvas. + * This may be different in fullscreen - see {@link #createFullScreenTarget}. + * + * This is set automatically based on the `parent` argument passed to {@link Phaser.Game}. + * + * This should only be changed after moving the Game canvas to a different DOM parent. + * + * @property {?DOMElement} parentNode + */ this.parentNode = null; /** - * The scale of the game in relation to its parent container. - * @property {Phaser.Point} parentScaleFactor - * @readonly - */ + * The scale of the game in relation to its parent container. + * @property {Phaser.Point} parentScaleFactor + * @readonly + */ this.parentScaleFactor = new Phaser.Point(1, 1); /** - * The maximum time (in ms) between dimension update checks for the Canvas's parent element (or window). - * Update checks normally happen quicker in response to other events. - * - * @property {integer} trackParentInterval - * @default - * @protected - * @see {@link Phaser.ScaleManager#refresh refresh} - */ + * The maximum time (in ms) between dimension update checks for the Canvas's parent element (or window). + * Update checks normally happen quicker in response to other events. + * + * @property {integer} trackParentInterval + * @default + * @protected + * @see {@link Phaser.ScaleManager#refresh refresh} + */ this.trackParentInterval = 2000; /** - * This signal is dispatched when the size of the Display canvas changes _or_ the size of the Game changes. - * When invoked this is done _after_ the Canvas size/position have been updated. - * - * The callback is supplied with three arguments: the Scale Manager, canvas {@link #width}, and canvas {@link #height}. (Game dimensions can be found in `scale.game.width` and `scale.game.height`.) - * - * This signal is _only_ called when a change occurs and a reflow may be required. - * For example, if the canvas does not change sizes because of CSS settings (such as min-width) - * then this signal will _not_ be triggered. - * - * Use this to handle responsive game layout options. - * - * This is signaled from `preUpdate` (or `pauseUpdate`) _even when_ the game is paused. - * - * @property {Phaser.Signal} onSizeChange - */ + * This signal is dispatched when the size of the Display canvas changes _or_ the size of the Game changes. + * When invoked this is done _after_ the Canvas size/position have been updated. + * + * The callback is supplied with three arguments: the Scale Manager, canvas {@link #width}, and canvas {@link #height}. (Game dimensions can be found in `scale.game.width` and `scale.game.height`.) + * + * This signal is _only_ called when a change occurs and a reflow may be required. + * For example, if the canvas does not change sizes because of CSS settings (such as min-width) + * then this signal will _not_ be triggered. + * + * Use this to handle responsive game layout options. + * + * This is signaled from `preUpdate` (or `pauseUpdate`) _even when_ the game is paused. + * + * @property {Phaser.Signal} onSizeChange + */ this.onSizeChange = new Phaser.Signal(); /** - * The callback that will be called each the parent container resizes. - * @property {function} onResize - * @private - */ + * The callback that will be called each the parent container resizes. + * @property {function} onResize + * @private + */ this.onResize = null; /** - * The context in which the {@link #onResize} callback will be called. - * @property {object} onResizeContext - * @private - */ + * The context in which the {@link #onResize} callback will be called. + * @property {object} onResizeContext + * @private + */ this.onResizeContext = null; /** - * @property {integer} _pendingScaleMode - Used to retain the scale mode if set from config before Boot. - * @private - */ + * @property {integer} _pendingScaleMode - Used to retain the scale mode if set from config before Boot. + * @private + */ this._pendingScaleMode = null; /** - * Information saved when fullscreen mode is started. - * @property {?object} _fullScreenRestore - * @private - */ + * Information saved when fullscreen mode is started. + * @property {?object} _fullScreenRestore + * @private + */ this._fullScreenRestore = null; /** - * The _actual_ game dimensions, as initially set or set by {@link #setGameSize}. - * @property {Phaser.Rectangle} _gameSize - * @private - */ + * The _actual_ game dimensions, as initially set or set by {@link #setGameSize}. + * @property {Phaser.Rectangle} _gameSize + * @private + */ this._gameSize = new Phaser.Rectangle(); /** - * The user-supplied scale factor, used with the USER_SCALE scaling mode. - * @property {Phaser.Point} _userScaleFactor - * @private - */ + * The user-supplied scale factor, used with the USER_SCALE scaling mode. + * @property {Phaser.Point} _userScaleFactor + * @private + */ this._userScaleFactor = new Phaser.Point(1, 1); /** - * The user-supplied scale trim, used with the USER_SCALE scaling mode. - * @property {Phaser.Point} _userScaleTrim - * @private - */ + * The user-supplied scale trim, used with the USER_SCALE scaling mode. + * @property {Phaser.Point} _userScaleTrim + * @private + */ this._userScaleTrim = new Phaser.Point(0, 0); /** - * The last time the bounds were checked in `preUpdate`. - * @property {number} _lastUpdate - * @private - */ + * The last time the bounds were checked in `preUpdate`. + * @property {number} _lastUpdate + * @private + */ this._lastUpdate = 0; /** - * Size checks updates are delayed according to the throttle. - * The throttle increases to `trackParentInterval` over time and is used to more - * rapidly detect changes in certain browsers (eg. IE) while providing back-off safety. - * @property {integer} _updateThrottle - * @private - */ + * Size checks updates are delayed according to the throttle. + * The throttle increases to `trackParentInterval` over time and is used to more + * rapidly detect changes in certain browsers (eg. IE) while providing back-off safety. + * @property {integer} _updateThrottle + * @private + */ this._updateThrottle = 0; /** - * The minimum throttle allowed until it has slowed down sufficiently. - * @property {integer} _updateThrottleReset - * @private - */ + * The minimum throttle allowed until it has slowed down sufficiently. + * @property {integer} _updateThrottleReset + * @private + */ this._updateThrottleReset = 100; /** - * The cached result of the parent (possibly window) bounds; used to invalidate sizing. - * @property {Phaser.Rectangle} _parentBounds - * @private - */ + * The cached result of the parent (possibly window) bounds; used to invalidate sizing. + * @property {Phaser.Rectangle} _parentBounds + * @private + */ this._parentBounds = new Phaser.Rectangle(); /** - * Temporary bounds used for internal work to cut down on new objects created. - * @property {Phaser.Rectangle} _parentBounds - * @private - */ + * Temporary bounds used for internal work to cut down on new objects created. + * @property {Phaser.Rectangle} _parentBounds + * @private + */ this._tempBounds = new Phaser.Rectangle(); /** - * The Canvas size at which the last onSizeChange signal was triggered. - * @property {Phaser.Rectangle} _lastReportedCanvasSize - * @private - */ + * The Canvas size at which the last onSizeChange signal was triggered. + * @property {Phaser.Rectangle} _lastReportedCanvasSize + * @private + */ this._lastReportedCanvasSize = new Phaser.Rectangle(); /** - * The Game size at which the last onSizeChange signal was triggered. - * @property {Phaser.Rectangle} _lastReportedGameSize - * @private - */ + * The Game size at which the last onSizeChange signal was triggered. + * @property {Phaser.Rectangle} _lastReportedGameSize + * @private + */ this._lastReportedGameSize = new Phaser.Rectangle(); /** - * @property {boolean} _booted - ScaleManager booted state. - * @private - */ + * @property {boolean} _booted - ScaleManager booted state. + * @private + */ this._booted = false; if (game.config) @@ -624,55 +623,54 @@ Phaser.ScaleManager = function (game, width, height) } this.setupScale(width, height); - }; /** -* A scale mode that stretches content to fill all available space - see {@link Phaser.ScaleManager#scaleMode scaleMode}. -* -* @constant -* @type {integer} -*/ + * A scale mode that stretches content to fill all available space - see {@link Phaser.ScaleManager#scaleMode scaleMode}. + * + * @constant + * @type {integer} + */ Phaser.ScaleManager.EXACT_FIT = 0; /** -* A scale mode that prevents any scaling - see {@link Phaser.ScaleManager#scaleMode scaleMode}. -* -* @constant -* @type {integer} -*/ + * A scale mode that prevents any scaling - see {@link Phaser.ScaleManager#scaleMode scaleMode}. + * + * @constant + * @type {integer} + */ Phaser.ScaleManager.NO_SCALE = 1; /** -* A scale mode that shows the entire game while maintaining proportions - see {@link Phaser.ScaleManager#scaleMode scaleMode}. -* -* @constant -* @type {integer} -*/ + * A scale mode that shows the entire game while maintaining proportions - see {@link Phaser.ScaleManager#scaleMode scaleMode}. + * + * @constant + * @type {integer} + */ Phaser.ScaleManager.SHOW_ALL = 2; /** -* A scale mode that causes the Game size to change - see {@link Phaser.ScaleManager#scaleMode scaleMode}. -* -* @constant -* @type {integer} -*/ + * A scale mode that causes the Game size to change - see {@link Phaser.ScaleManager#scaleMode scaleMode}. + * + * @constant + * @type {integer} + */ Phaser.ScaleManager.RESIZE = 3; /** -* A scale mode that allows a custom scale factor - see {@link Phaser.ScaleManager#scaleMode scaleMode}. -* -* @constant -* @type {integer} -*/ + * A scale mode that allows a custom scale factor - see {@link Phaser.ScaleManager#scaleMode scaleMode}. + * + * @constant + * @type {integer} + */ Phaser.ScaleManager.USER_SCALE = 4; /** -* Names of the scale modes, indexed by value. -* -* @constant -* @type {string[]} -*/ + * Names of the scale modes, indexed by value. + * + * @constant + * @type {string[]} + */ Phaser.ScaleManager.MODES = [ 'EXACT_FIT', 'NO_SCALE', @@ -684,14 +682,13 @@ Phaser.ScaleManager.MODES = [ Phaser.ScaleManager.prototype = { /** - * Start the ScaleManager. - * - * @method Phaser.ScaleManager#boot - * @protected - */ + * Start the ScaleManager. + * + * @method Phaser.ScaleManager#boot + * @protected + */ boot: function () { - // Configure device-dependent compatibility var compat = this.compatibility; @@ -788,19 +785,17 @@ Phaser.ScaleManager.prototype = { this.scaleMode = this._pendingScaleMode; this._pendingScaleMode = null; } - }, /** - * Load configuration settings. - * - * @method Phaser.ScaleManager#parseConfig - * @protected - * @param {object} config - The game configuration object. - */ + * Load configuration settings. + * + * @method Phaser.ScaleManager#parseConfig + * @protected + * @param {object} config - The game configuration object. + */ parseConfig: function (config) { - if (config.scaleMode !== undefined) { if (this._booted) @@ -830,22 +825,20 @@ Phaser.ScaleManager.prototype = { { this.setUserScale(config.scaleH, config.scaleV, config.trimH, config.trimV); } - }, /** - * Calculates and sets the game dimensions based on the given width and height. - * - * This should _not_ be called when in fullscreen mode. - * - * @method Phaser.ScaleManager#setupScale - * @protected - * @param {number|string} width - The width of the game. - * @param {number|string} height - The height of the game. - */ + * Calculates and sets the game dimensions based on the given width and height. + * + * This should _not_ be called when in fullscreen mode. + * + * @method Phaser.ScaleManager#setupScale + * @protected + * @param {number|string} width - The width of the game. + * @param {number|string} height - The height of the game. + */ setupScale: function (width, height) { - var target; var rect = new Phaser.Rectangle(); @@ -919,40 +912,36 @@ Phaser.ScaleManager.prototype = { this._gameSize.setTo(0, 0, newWidth, newHeight); this.updateDimensions(newWidth, newHeight, false); - }, /** - * Invoked when the game is resumed. - * - * @method Phaser.ScaleManager#_gameResumed - * @private - */ + * Invoked when the game is resumed. + * + * @method Phaser.ScaleManager#_gameResumed + * @private + */ _gameResumed: function () { - this.queueUpdate(true); - }, /** - * Set the actual Game size. - * Use this instead of directly changing `game.width` or `game.height`. - * - * The actual physical display (Canvas element size) depends on various settings including - * - Scale mode - * - Scaling factor - * - Size of Canvas's parent element or CSS rules such as min-height/max-height; - * - The size of the Window - * - * @method Phaser.ScaleManager#setGameSize - * @public - * @param {integer} width - _Game width_, in pixels. - * @param {integer} height - _Game height_, in pixels. - */ + * Set the actual Game size. + * Use this instead of directly changing `game.width` or `game.height`. + * + * The actual physical display (Canvas element size) depends on various settings including + * - Scale mode + * - Scaling factor + * - Size of Canvas's parent element or CSS rules such as min-height/max-height; + * - The size of the Window + * + * @method Phaser.ScaleManager#setGameSize + * @public + * @param {integer} width - _Game width_, in pixels. + * @param {integer} height - _Game height_, in pixels. + */ setGameSize: function (width, height) { - this._gameSize.setTo(0, 0, width, height); if (this.currentScaleMode !== Phaser.ScaleManager.RESIZE) @@ -961,30 +950,28 @@ Phaser.ScaleManager.prototype = { } this.queueUpdate(true); - }, /** - * Set a User scaling factor used in the USER_SCALE scaling mode. - * - * The target canvas size is computed by: - * - * canvas.width = (game.width * hScale) - hTrim - * canvas.height = (game.height * vScale) - vTrim - * - * This method can be used in the {@link Phaser.ScaleManager#setResizeCallback resize callback}. Set `queueUpdate` and `force` to false if the resize callback is being called repeatedly. - * - * @method Phaser.ScaleManager#setUserScale - * @param {number} hScale - Horizontal scaling factor. - * @param {numer} vScale - Vertical scaling factor. - * @param {integer} [hTrim=0] - Horizontal trim, applied after scaling. - * @param {integer} [vTrim=0] - Vertical trim, applied after scaling. - * @param {boolean} [queueUpdate=true] - Queue a size/bounds check at next preUpdate - * @param {boolean} [force=true] - Force a resize during the next preUpdate - */ + * Set a User scaling factor used in the USER_SCALE scaling mode. + * + * The target canvas size is computed by: + * + * canvas.width = (game.width * hScale) - hTrim + * canvas.height = (game.height * vScale) - vTrim + * + * This method can be used in the {@link Phaser.ScaleManager#setResizeCallback resize callback}. Set `queueUpdate` and `force` to false if the resize callback is being called repeatedly. + * + * @method Phaser.ScaleManager#setUserScale + * @param {number} hScale - Horizontal scaling factor. + * @param {numer} vScale - Vertical scaling factor. + * @param {integer} [hTrim=0] - Horizontal trim, applied after scaling. + * @param {integer} [vTrim=0] - Vertical trim, applied after scaling. + * @param {boolean} [queueUpdate=true] - Queue a size/bounds check at next preUpdate + * @param {boolean} [force=true] - Force a resize during the next preUpdate + */ setUserScale: function (hScale, vScale, hTrim, vTrim, queueUpdate, force) { - this._userScaleFactor.setTo(hScale, vScale); this._userScaleTrim.setTo(hTrim | 0, vTrim | 0); @@ -995,56 +982,52 @@ Phaser.ScaleManager.prototype = { { this.queueUpdate(force); } - }, /** - * Sets the callback that will be invoked before sizing calculations. - * - * Typically this is triggered when the Scale Manager has detected a change to the canvas's boundaries: - * the browser window has been resized, the device has been rotated, or the parent container's size has changed. - * At this point the Scale Manager has not resized the game or canvas yet (and may not resize them at all - * after it makes its sizing calculations). You can read the size of the parent container from the - * `parentBounds` argument to the callback. - * - * This is the appropriate place to call {@link #setUserScale} if needing custom dynamic scaling. - * - * The callback is supplied with two arguments `scale` and `parentBounds` where `scale` is the ScaleManager - * and `parentBounds`, a Phaser.Rectangle, is the size of the Parent element. - * - * This callback - * - May be invoked even though the parent container or canvas sizes have not changed - * - Unlike {@link #onSizeChange}, it runs _before_ the canvas is guaranteed to be updated - * - Will be invoked from `preUpdate`, _even when_ the game is paused - * - * See {@link #onSizeChange} for a better way of reacting to layout updates. - * - * @method Phaser.ScaleManager#setResizeCallback - * @public - * @param {function} callback - The callback that will be called each time a window.resize event happens or if set, the parent container resizes. - * @param {object} context - The context in which the callback will be called. - */ + * Sets the callback that will be invoked before sizing calculations. + * + * Typically this is triggered when the Scale Manager has detected a change to the canvas's boundaries: + * the browser window has been resized, the device has been rotated, or the parent container's size has changed. + * At this point the Scale Manager has not resized the game or canvas yet (and may not resize them at all + * after it makes its sizing calculations). You can read the size of the parent container from the + * `parentBounds` argument to the callback. + * + * This is the appropriate place to call {@link #setUserScale} if needing custom dynamic scaling. + * + * The callback is supplied with two arguments `scale` and `parentBounds` where `scale` is the ScaleManager + * and `parentBounds`, a Phaser.Rectangle, is the size of the Parent element. + * + * This callback + * - May be invoked even though the parent container or canvas sizes have not changed + * - Unlike {@link #onSizeChange}, it runs _before_ the canvas is guaranteed to be updated + * - Will be invoked from `preUpdate`, _even when_ the game is paused + * + * See {@link #onSizeChange} for a better way of reacting to layout updates. + * + * @method Phaser.ScaleManager#setResizeCallback + * @public + * @param {function} callback - The callback that will be called each time a window.resize event happens or if set, the parent container resizes. + * @param {object} context - The context in which the callback will be called. + */ setResizeCallback: function (callback, context) { - this.onResize = callback; this.onResizeContext = context; - }, /** - * Signals a resize - IF the canvas or Game size differs from the last signal. - * - * This also triggers updates on {@link #grid} (FlexGrid) and, if in a RESIZE mode, `game.state` (StateManager). - * - * It dispatches the {@link #onSizeChange} signal. - * - * @method Phaser.ScaleManager#signalSizeChange - * @private - */ + * Signals a resize - IF the canvas or Game size differs from the last signal. + * + * This also triggers updates on {@link #grid} (FlexGrid) and, if in a RESIZE mode, `game.state` (StateManager). + * + * It dispatches the {@link #onSizeChange} signal. + * + * @method Phaser.ScaleManager#signalSizeChange + * @private + */ signalSizeChange: function () { - if (!Phaser.Rectangle.sameDimensions(this, this._lastReportedCanvasSize) || !Phaser.Rectangle.sameDimensions(this.game, this._lastReportedGameSize)) { @@ -1068,27 +1051,25 @@ Phaser.ScaleManager.prototype = { this.game.load.resize(width, height); } } - }, /** - * Set the min and max dimensions for the Display canvas. - * - * _Note:_ The min/max dimensions are only applied in some cases - * - When the device is not in an incorrect orientation; or - * - The scale mode is EXACT_FIT when not in fullscreen - * - * @method Phaser.ScaleManager#setMinMax - * @public - * @param {number} minWidth - The minimum width the game is allowed to scale down to. - * @param {number} minHeight - The minimum height the game is allowed to scale down to. - * @param {number} [maxWidth] - The maximum width the game is allowed to scale up to; only changed if specified. - * @param {number} [maxHeight] - The maximum height the game is allowed to scale up to; only changed if specified. - * @todo These values are only sometimes honored. - */ + * Set the min and max dimensions for the Display canvas. + * + * _Note:_ The min/max dimensions are only applied in some cases + * - When the device is not in an incorrect orientation; or + * - The scale mode is EXACT_FIT when not in fullscreen + * + * @method Phaser.ScaleManager#setMinMax + * @public + * @param {number} minWidth - The minimum width the game is allowed to scale down to. + * @param {number} minHeight - The minimum height the game is allowed to scale down to. + * @param {number} [maxWidth] - The maximum width the game is allowed to scale up to; only changed if specified. + * @param {number} [maxHeight] - The maximum height the game is allowed to scale up to; only changed if specified. + * @todo These values are only sometimes honored. + */ setMinMax: function (minWidth, minHeight, maxWidth, maxHeight) { - this.minWidth = minWidth; this.minHeight = minHeight; @@ -1101,18 +1082,16 @@ Phaser.ScaleManager.prototype = { { this.maxHeight = maxHeight; } - }, /** - * The ScaleManager.preUpdate is called automatically by the core Game loop. - * - * @method Phaser.ScaleManager#preUpdate - * @protected - */ + * The ScaleManager.preUpdate is called automatically by the core Game loop. + * + * @method Phaser.ScaleManager#preUpdate + * @protected + */ preUpdate: function () { - if (this.game.time.time < (this._lastUpdate + this._updateThrottle)) { return; @@ -1155,37 +1134,33 @@ Phaser.ScaleManager.prototype = { this._updateThrottle = Phaser.Math.clamp(throttle, 25, this.trackParentInterval); this._lastUpdate = this.game.time.time; - }, /** - * Update method while paused. - * - * @method Phaser.ScaleManager#pauseUpdate - * @private - */ + * Update method while paused. + * + * @method Phaser.ScaleManager#pauseUpdate + * @private + */ pauseUpdate: function () { - this.preUpdate(); // Updates at slowest. this._updateThrottle = this.trackParentInterval; - }, /** - * Update the dimensions taking the parent scaling factor into account. - * - * @method Phaser.ScaleManager#updateDimensions - * @private - * @param {number} width - The new width of the parent container. - * @param {number} height - The new height of the parent container. - * @param {boolean} resize - True if the renderer should be resized, otherwise false to just update the internal vars. - */ + * Update the dimensions taking the parent scaling factor into account. + * + * @method Phaser.ScaleManager#updateDimensions + * @private + * @param {number} width - The new width of the parent container. + * @param {number} height - The new height of the parent container. + * @param {boolean} resize - True if the renderer should be resized, otherwise false to just update the internal vars. + */ updateDimensions: function (width, height, resize) { - this.width = width * this.parentScaleFactor.x; this.height = height * this.parentScaleFactor.y; @@ -1206,19 +1181,17 @@ Phaser.ScaleManager.prototype = { // This should only happen if the world is smaller than the new canvas size this.game.world.resize(this.width, this.height); } - }, /** - * Update relevant scaling values based on the ScaleManager dimension and game dimensions, - * which should already be set. This does not change {@link #sourceAspectRatio}. - * - * @method Phaser.ScaleManager#updateScalingAndBounds - * @private - */ + * Update relevant scaling values based on the ScaleManager dimension and game dimensions, + * which should already be set. This does not change {@link #sourceAspectRatio}. + * + * @method Phaser.ScaleManager#updateScalingAndBounds + * @private + */ updateScalingAndBounds: function () { - this.scaleFactor.x = this.game.width / this.width; this.scaleFactor.y = this.game.height / this.height; @@ -1240,26 +1213,24 @@ Phaser.ScaleManager.prototype = { { this.game.input.scale.setTo(this.scaleFactor.x, this.scaleFactor.y); } - }, /** - * Force the game to run in only one orientation. - * - * This enables generation of incorrect orientation signals and affects resizing but does not otherwise rotate or lock the orientation. - * - * Orientation checks are performed via the Screen Orientation API, if available in browser. This means it will check your monitor - * orientation on desktop, or your device orientation on mobile, rather than comparing actual game dimensions. If you need to check the - * viewport dimensions instead and bypass the Screen Orientation API then set: `ScaleManager.compatibility.orientationFallback = 'viewport'` - * - * @method Phaser.ScaleManager#forceOrientation - * @public - * @param {boolean} forceLandscape - true if the game should run in landscape mode only. - * @param {boolean} [forcePortrait=false] - true if the game should run in portrait mode only. - */ + * Force the game to run in only one orientation. + * + * This enables generation of incorrect orientation signals and affects resizing but does not otherwise rotate or lock the orientation. + * + * Orientation checks are performed via the Screen Orientation API, if available in browser. This means it will check your monitor + * orientation on desktop, or your device orientation on mobile, rather than comparing actual game dimensions. If you need to check the + * viewport dimensions instead and bypass the Screen Orientation API then set: `ScaleManager.compatibility.orientationFallback = 'viewport'` + * + * @method Phaser.ScaleManager#forceOrientation + * @public + * @param {boolean} forceLandscape - true if the game should run in landscape mode only. + * @param {boolean} [forcePortrait=false] - true if the game should run in portrait mode only. + */ forceOrientation: function (forceLandscape, forcePortrait) { - if (forcePortrait === undefined) { forcePortrait = false; } if (forceLandscape === true && forcePortrait === true) @@ -1272,20 +1243,18 @@ Phaser.ScaleManager.prototype = { this.forcePortrait = forcePortrait; this.queueUpdate(true); - }, /** - * Classify the orientation, per `getScreenOrientation`. - * - * @method Phaser.ScaleManager#classifyOrientation - * @private - * @param {string} orientation - The orientation string, e.g. 'portrait-primary'. - * @return {?string} The classified orientation: 'portrait', 'landscape`, or null. - */ + * Classify the orientation, per `getScreenOrientation`. + * + * @method Phaser.ScaleManager#classifyOrientation + * @private + * @param {string} orientation - The orientation string, e.g. 'portrait-primary'. + * @return {?string} The classified orientation: 'portrait', 'landscape`, or null. + */ classifyOrientation: function (orientation) { - if (orientation === 'portrait-primary' || orientation === 'portrait-secondary') { return 'portrait'; @@ -1298,19 +1267,17 @@ Phaser.ScaleManager.prototype = { { return null; } - }, /** - * Updates the current orientation and dispatches orientation change events. - * - * @method Phaser.ScaleManager#updateOrientationState - * @private - * @return {boolean} True if the orientation state changed which means a forced update is likely required. - */ + * Updates the current orientation and dispatches orientation change events. + * + * @method Phaser.ScaleManager#updateOrientationState + * @private + * @return {boolean} True if the orientation state changed which means a forced update is likely required. + */ updateOrientationState: function () { - var previousOrientation = this.screenOrientation; var previouslyIncorrect = this.incorrectOrientation; @@ -1340,96 +1307,86 @@ Phaser.ScaleManager.prototype = { } return changed || correctnessChanged; - }, /** - * window.orientationchange event handler. - * - * @method Phaser.ScaleManager#orientationChange - * @private - * @param {Event} event - The orientationchange event data. - */ + * window.orientationchange event handler. + * + * @method Phaser.ScaleManager#orientationChange + * @private + * @param {Event} event - The orientationchange event data. + */ orientationChange: function (event) { - this.event = event; this.queueUpdate(true); - }, /** - * window.resize event handler. - * - * @method Phaser.ScaleManager#windowResize - * @private - * @param {Event} event - The resize event data. - */ + * window.resize event handler. + * + * @method Phaser.ScaleManager#windowResize + * @private + * @param {Event} event - The resize event data. + */ windowResize: function (event) { - this.event = event; this.queueUpdate(true); - }, /** - * Scroll to the top - in some environments. See `compatibility.scrollTo`. - * - * @method Phaser.ScaleManager#scrollTop - * @private - */ + * Scroll to the top - in some environments. See `compatibility.scrollTo`. + * + * @method Phaser.ScaleManager#scrollTop + * @private + */ scrollTop: function () { - var scrollTo = this.compatibility.scrollTo; if (scrollTo) { window.scrollTo(scrollTo.x, scrollTo.y); } - }, /** - * The "refresh" methods informs the ScaleManager that a layout refresh is required. - * - * The ScaleManager automatically queues a layout refresh (eg. updates the Game size or Display canvas layout) - * when the browser is resized, the orientation changes, or when there is a detected change - * of the Parent size. Refreshing is also done automatically when public properties, - * such as {@link #scaleMode}, are updated or state-changing methods are invoked. - * - * The "refresh" method _may_ need to be used in a few (rare) situtations when - * - * - a device change event is not correctly detected; or - * - the Parent size changes (and an immediate reflow is desired); or - * - the ScaleManager state is updated by non-standard means; or - * - certain {@link #compatibility} properties are manually changed. - * - * The queued layout refresh is not immediate but will run promptly in an upcoming `preRender`. - * - * @method Phaser.ScaleManager#refresh - * @public - */ + * The "refresh" methods informs the ScaleManager that a layout refresh is required. + * + * The ScaleManager automatically queues a layout refresh (eg. updates the Game size or Display canvas layout) + * when the browser is resized, the orientation changes, or when there is a detected change + * of the Parent size. Refreshing is also done automatically when public properties, + * such as {@link #scaleMode}, are updated or state-changing methods are invoked. + * + * The "refresh" method _may_ need to be used in a few (rare) situtations when + * + * - a device change event is not correctly detected; or + * - the Parent size changes (and an immediate reflow is desired); or + * - the ScaleManager state is updated by non-standard means; or + * - certain {@link #compatibility} properties are manually changed. + * + * The queued layout refresh is not immediate but will run promptly in an upcoming `preRender`. + * + * @method Phaser.ScaleManager#refresh + * @public + */ refresh: function () { - this.scrollTop(); this.queueUpdate(true); - }, /** - * Updates the game / canvas position and size. - * - * @method Phaser.ScaleManager#updateLayout - * @private - */ + * Updates the game / canvas position and size. + * + * @method Phaser.ScaleManager#updateLayout + * @private + */ updateLayout: function () { - var scaleMode = this.currentScaleMode; if (scaleMode === Phaser.ScaleManager.RESIZE) @@ -1442,8 +1399,10 @@ Phaser.ScaleManager.prototype = { if (this.compatibility.forceMinimumDocumentHeight) { - // (This came from older code, by why is it here?) - // Set minimum height of content to new window height + /* + * (This came from older code, by why is it here?) + * Set minimum height of content to new window height + */ document.documentElement.style.minHeight = window.innerHeight + 'px'; } @@ -1461,9 +1420,11 @@ Phaser.ScaleManager.prototype = { if (!this.isFullScreen && this.boundingParent && this.compatibility.canExpandParent) { - // Try to expand parent out, but choosing maximizing dimensions. - // Then select minimize dimensions which should then honor parent - // maximum bound applications. + /* + * Try to expand parent out, but choosing maximizing dimensions. + * Then select minimize dimensions which should then honor parent + * maximum bound applications. + */ this.setShowAll(true); this.resetCanvas(); this.setShowAll(); @@ -1497,29 +1458,27 @@ Phaser.ScaleManager.prototype = { this.height = this.height | 0; this.reflowCanvas(); - }, /** - * Returns the computed Parent size/bounds that the Display canvas is allowed/expected to fill. - * - * If in fullscreen mode or without parent (see {@link #parentIsWindow}), - * this will be the bounds of the visual viewport itself. - * - * This function takes the {@link #windowConstraints} into consideration - if the parent is partially outside - * the viewport then this function may return a smaller than expected size. - * - * Values are rounded to the nearest pixel. - * - * @method Phaser.ScaleManager#getParentBounds - * @protected - * @param {Phaser.Rectangle} [target=(new Rectangle)] - The rectangle to update; a new one is created as needed. - * @param {HTMLElement} [parent] - Ignore {@link #boundingParent} and use this node instead. - * @return {Phaser.Rectangle} The established parent bounds. - */ + * Returns the computed Parent size/bounds that the Display canvas is allowed/expected to fill. + * + * If in fullscreen mode or without parent (see {@link #parentIsWindow}), + * this will be the bounds of the visual viewport itself. + * + * This function takes the {@link #windowConstraints} into consideration - if the parent is partially outside + * the viewport then this function may return a smaller than expected size. + * + * Values are rounded to the nearest pixel. + * + * @method Phaser.ScaleManager#getParentBounds + * @protected + * @param {Phaser.Rectangle} [target=(new Rectangle)] - The rectangle to update; a new one is created as needed. + * @param {HTMLElement} [parent] - Ignore {@link #boundingParent} and use this node instead. + * @return {Phaser.Rectangle} The established parent bounds. + */ getParentBounds: function (target, parent) { - var bounds = target || new Phaser.Rectangle(); var parentNode = parent || this.boundingParent; var visualBounds = this.dom.visualBounds; @@ -1557,7 +1516,6 @@ Phaser.ScaleManager.prototype = { Math.round(bounds.width), Math.round(bounds.height)); return bounds; - }, @@ -1570,7 +1528,6 @@ Phaser.ScaleManager.prototype = { */ align: function (horizontal, vertical) { - if (horizontal != null) { this.pageAlignHorizontally = horizontal; @@ -1580,22 +1537,20 @@ Phaser.ScaleManager.prototype = { { this.pageAlignVertically = vertical; } - }, /** - * Update the canvas position/margins - for alignment within the parent container. - * - * The canvas margins _must_ be reset/cleared prior to invoking this. - * - * @method Phaser.ScaleManager#alignCanvas - * @private - * @param {boolean} horizontal - Align horizontally? - * @param {boolean} vertical - Align vertically? - */ + * Update the canvas position/margins - for alignment within the parent container. + * + * The canvas margins _must_ be reset/cleared prior to invoking this. + * + * @method Phaser.ScaleManager#alignCanvas + * @private + * @param {boolean} horizontal - Align horizontally? + * @param {boolean} vertical - Align vertically? + */ alignCanvas: function (horizontal, vertical) { - var parentBounds = this.getParentBounds(this._tempBounds); var canvas = this.game.canvas; var margin = this.margin; @@ -1656,38 +1611,34 @@ Phaser.ScaleManager.prototype = { // Silly backwards compatibility.. margin.x = margin.left; margin.y = margin.top; - }, /** - * Updates the Game state / size. - * - * The canvas margins may always be adjusted, even if alignment is not in effect. - * - * @method Phaser.ScaleManager#reflowGame - * @private - */ + * Updates the Game state / size. + * + * The canvas margins may always be adjusted, even if alignment is not in effect. + * + * @method Phaser.ScaleManager#reflowGame + * @private + */ reflowGame: function () { - this.resetCanvas('', ''); var bounds = this.getParentBounds(this._tempBounds); this.updateDimensions(bounds.width, bounds.height, true); - }, /** - * Updates the Display canvas size. - * - * The canvas margins may always be adjusted, even alignment is not in effect. - * - * @method Phaser.ScaleManager#reflowCanvas - * @private - */ + * Updates the Display canvas size. + * + * The canvas margins may always be adjusted, even alignment is not in effect. + * + * @method Phaser.ScaleManager#reflowCanvas + * @private + */ reflowCanvas: function () { - if (!this.incorrectOrientation) { this.width = Phaser.Math.clamp(this.width, this.minWidth || 0, this.maxWidth || this.width); @@ -1709,20 +1660,18 @@ Phaser.ScaleManager.prototype = { } this.updateScalingAndBounds(); - }, /** - * "Reset" the Display canvas and set the specified width/height. - * - * @method Phaser.ScaleManager#resetCanvas - * @private - * @param {string} [cssWidth=(current width)] - The css width to set. - * @param {string} [cssHeight=(current height)] - The css height to set. - */ + * "Reset" the Display canvas and set the specified width/height. + * + * @method Phaser.ScaleManager#resetCanvas + * @private + * @param {string} [cssWidth=(current width)] - The css width to set. + * @param {string} [cssHeight=(current height)] - The css height to set. + */ resetCanvas: function (cssWidth, cssHeight) { - if (cssWidth === undefined) { cssWidth = this.width + 'px'; } if (cssHeight === undefined) { cssHeight = this.height + 'px'; } @@ -1738,19 +1687,17 @@ Phaser.ScaleManager.prototype = { canvas.style.width = cssWidth; canvas.style.height = cssHeight; - }, /** - * Queues/marks a size/bounds check as needing to occur (from `preUpdate`). - * - * @method Phaser.ScaleManager#queueUpdate - * @private - * @param {boolean} force - If true resets the parent bounds to ensure the check is dirty. - */ + * Queues/marks a size/bounds check as needing to occur (from `preUpdate`). + * + * @method Phaser.ScaleManager#queueUpdate + * @private + * @param {boolean} force - If true resets the parent bounds to ensure the check is dirty. + */ queueUpdate: function (force) { - if (force) { this._parentBounds.width = 0; @@ -1758,49 +1705,43 @@ Phaser.ScaleManager.prototype = { } this._updateThrottle = this._updateThrottleReset; - }, /** - * Reset internal data/state. - * - * @method Phaser.ScaleManager#reset - * @private - */ + * Reset internal data/state. + * + * @method Phaser.ScaleManager#reset + * @private + */ reset: function (clearWorld) { - if (clearWorld && this.grid) { this.grid.reset(); } - }, /** - * Updates the width/height to that of the window. - * - * @method Phaser.ScaleManager#setMaximum - * @private - */ + * Updates the width/height to that of the window. + * + * @method Phaser.ScaleManager#setMaximum + * @private + */ setMaximum: function () { - this.width = this.dom.visualBounds.width; this.height = this.dom.visualBounds.height; - }, /** - * Updates the width/height such that the game is scaled proportionally. - * - * @method Phaser.ScaleManager#setShowAll - * @private - * @param {boolean} expanding - If true then the maximizing dimension is chosen. - */ + * Updates the width/height such that the game is scaled proportionally. + * + * @method Phaser.ScaleManager#setShowAll + * @private + * @param {boolean} expanding - If true then the maximizing dimension is chosen. + */ setShowAll: function (expanding) { - var bounds = this.getParentBounds(this._tempBounds); var width = bounds.width; var height = bounds.height; @@ -1818,19 +1759,17 @@ Phaser.ScaleManager.prototype = { this.width = Math.round(this.game.width * multiplier); this.height = Math.round(this.game.height * multiplier); - }, /** - * Updates the width/height such that the game is stretched to the available size. - * Honors {@link #maxWidth} and {@link #maxHeight} when _not_ in fullscreen. - * - * @method Phaser.ScaleManager#setExactFit - * @private - */ + * Updates the width/height such that the game is stretched to the available size. + * Honors {@link #maxWidth} and {@link #maxHeight} when _not_ in fullscreen. + * + * @method Phaser.ScaleManager#setExactFit + * @private + */ setExactFit: function () { - var bounds = this.getParentBounds(this._tempBounds); this.width = bounds.width; @@ -1851,21 +1790,19 @@ Phaser.ScaleManager.prototype = { { this.height = Math.min(this.height, this.maxHeight); } - }, /** - * Creates a fullscreen target. This is called automatically as as needed when entering - * fullscreen mode and the resulting element is supplied to {@link #onFullScreenInit}. - * - * Use {@link #onFullScreenInit} to customize the created object. - * - * @method Phaser.ScaleManager#createFullScreenTarget - * @protected - */ + * Creates a fullscreen target. This is called automatically as as needed when entering + * fullscreen mode and the resulting element is supplied to {@link #onFullScreenInit}. + * + * Use {@link #onFullScreenInit} to customize the created object. + * + * @method Phaser.ScaleManager#createFullScreenTarget + * @protected + */ createFullScreenTarget: function () { - var fsTarget = document.createElement('div'); fsTarget.style.margin = '0'; @@ -1873,40 +1810,38 @@ Phaser.ScaleManager.prototype = { fsTarget.style.background = '#000'; return fsTarget; - }, /** - * Display the game in the browser's fullscreen mode. - * - * This _must_ be called from a user-input Pointer or Mouse event (and possibly a {@link https://www.chromestatus.com/feature/6131337345892352 "user gesture"}), e.g., - * - * - {@link Phaser.Events#onInputUp} - * - {@link Phaser.Input#onUp} or {@link Phaser.Input#onTap} - * - `click`, `mousedown`, `mouseup`, `pointerup`, or `touchend` - * - * Games within an iframe will also be blocked from fullscreen unless the iframe has the `allowfullscreen` attribute. - * - * The {@link https://developer.mozilla.org/en-US/docs/Web/API/Fullscreen_API Fullscreen API} must be {@link http://caniuse.com/#search=fullscreen supported by the browser} for this to work - it is not the same as setting - * the game size to fill the browser window. See {@link Phaser.ScaleManager#compatibility compatibility.supportsFullScreen} to check if the current - * device is reported to support fullscreen mode. - * - * The {@link #fullScreenFailed} signal will be dispatched if the fullscreen change request failed or the game does not support the Fullscreen API. - * - * Safari blocks access to keyboard events in fullscreen mode (as a security measure). - * - * @method Phaser.ScaleManager#startFullScreen - * @public - * @param {boolean} [antialias] - Changes the anti-alias feature of the canvas before jumping in to fullscreen (false = retain pixel art, true = smooth art). If not specified then no change is made. Only works in CANVAS mode. - * @param {boolean} [allowTrampoline=undefined] - Internal argument. If `false` click trampolining is suppressed. - * @param {object} [options={navigationUI: 'hide'}] - Options passed to requestFullscreen(). - * @return {boolean} Returns true if the device supports fullscreen mode and fullscreen mode was attempted to be started. (It might not actually start, wait for the signals.) - * - * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/requestFullScreen - */ + * Display the game in the browser's fullscreen mode. + * + * This _must_ be called from a user-input Pointer or Mouse event (and possibly a {@link https://www.chromestatus.com/feature/6131337345892352 "user gesture"}), e.g., + * + * - {@link Phaser.Events#onInputUp} + * - {@link Phaser.Input#onUp} or {@link Phaser.Input#onTap} + * - `click`, `mousedown`, `mouseup`, `pointerup`, or `touchend` + * + * Games within an iframe will also be blocked from fullscreen unless the iframe has the `allowfullscreen` attribute. + * + * The {@link https://developer.mozilla.org/en-US/docs/Web/API/Fullscreen_API Fullscreen API} must be {@link http://caniuse.com/#search=fullscreen supported by the browser} for this to work - it is not the same as setting + * the game size to fill the browser window. See {@link Phaser.ScaleManager#compatibility compatibility.supportsFullScreen} to check if the current + * device is reported to support fullscreen mode. + * + * The {@link #fullScreenFailed} signal will be dispatched if the fullscreen change request failed or the game does not support the Fullscreen API. + * + * Safari blocks access to keyboard events in fullscreen mode (as a security measure). + * + * @method Phaser.ScaleManager#startFullScreen + * @public + * @param {boolean} [antialias] - Changes the anti-alias feature of the canvas before jumping in to fullscreen (false = retain pixel art, true = smooth art). If not specified then no change is made. Only works in CANVAS mode. + * @param {boolean} [allowTrampoline=undefined] - Internal argument. If `false` click trampolining is suppressed. + * @param {object} [options={navigationUI: 'hide'}] - Options passed to requestFullscreen(). + * @return {boolean} Returns true if the device supports fullscreen mode and fullscreen mode was attempted to be started. (It might not actually start, wait for the signals.) + * + * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/requestFullScreen + */ startFullScreen: function (antialias, allowTrampoline, options) { - if (this.isFullScreen) { return false; @@ -1961,8 +1896,10 @@ Phaser.ScaleManager.prototype = { if (this._createdFullScreenTarget) { - // Move the Display canvas inside of the target and add the target to the DOM - // (The target has to be added for the Fullscreen API to work.) + /* + * Move the Display canvas inside of the target and add the target to the DOM + * (The target has to be added for the Fullscreen API to work.) + */ var canvas = this.game.canvas; var parent = canvas.parentNode; parent.insertBefore(fsTarget, canvas); @@ -1984,19 +1921,17 @@ Phaser.ScaleManager.prototype = { } return true; - }, /** - * Stops / exits fullscreen mode, if active. - * - * @method Phaser.ScaleManager#stopFullScreen - * @public - * @return {boolean} Returns true if the browser supports fullscreen mode and fullscreen mode will be exited. - */ + * Stops / exits fullscreen mode, if active. + * + * @method Phaser.ScaleManager#stopFullScreen + * @public + * @return {boolean} Returns true if the browser supports fullscreen mode and fullscreen mode will be exited. + */ stopFullScreen: function () { - if (!this.isFullScreen || !this.compatibility.supportsFullScreen) { return false; @@ -2007,45 +1942,43 @@ Phaser.ScaleManager.prototype = { document[this.game.device.cancelFullscreen](); return true; - }, /** - * Cleans up the previous fullscreen target, if such was automatically created. - * This ensures the canvas is restored to its former parent, assuming the target didn't move. - * - * @method Phaser.ScaleManager#cleanupCreatedTarget - * @private - */ + * Cleans up the previous fullscreen target, if such was automatically created. + * This ensures the canvas is restored to its former parent, assuming the target didn't move. + * + * @method Phaser.ScaleManager#cleanupCreatedTarget + * @private + */ cleanupCreatedTarget: function () { - var fsTarget = this._createdFullScreenTarget; if (fsTarget && fsTarget.parentNode) { - // Make sure to cleanup synthetic target for sure; - // swap the canvas back to the parent. + /* + * Make sure to cleanup synthetic target for sure; + * swap the canvas back to the parent. + */ var parent = fsTarget.parentNode; parent.insertBefore(this.game.canvas, fsTarget); parent.removeChild(fsTarget); } this._createdFullScreenTarget = null; - }, /** - * Used to prepare/restore extra fullscreen mode settings. - * (This does move any elements within the DOM tree.) - * - * @method Phaser.ScaleManager#prepScreenMode - * @private - * @param {boolean} enteringFullscreen - True if _entering_ fullscreen, false if _leaving_. - */ + * Used to prepare/restore extra fullscreen mode settings. + * (This does move any elements within the DOM tree.) + * + * @method Phaser.ScaleManager#prepScreenMode + * @private + * @param {boolean} enteringFullscreen - True if _entering_ fullscreen, false if _leaving_. + */ prepScreenMode: function (enteringFullscreen) { - var createdTarget = !!this._createdFullScreenTarget; var fsTarget = this._createdFullScreenTarget || this.fullScreenTarget; @@ -2081,19 +2014,17 @@ Phaser.ScaleManager.prototype = { this.updateDimensions(this._gameSize.width, this._gameSize.height, true); this.resetCanvas(); } - }, /** - * Called automatically when the browser enters of leaves fullscreen mode. - * - * @method Phaser.ScaleManager#fullScreenChange - * @private - * @param {Event} [event=undefined] - The fullscreenchange event - */ + * Called automatically when the browser enters of leaves fullscreen mode. + * + * @method Phaser.ScaleManager#fullScreenChange + * @private + * @param {Event} [event=undefined] - The fullscreenchange event + */ fullScreenChange: function (event) { - this.event = event; if (this.isFullScreen) @@ -2114,20 +2045,18 @@ Phaser.ScaleManager.prototype = { } this.onFullScreenChange.dispatch(this, this.width, this.height); - }, /** - * Called automatically when the browser fullscreen request fails; - * or called when a fullscreen request is made on a device for which it is not supported. - * - * @method Phaser.ScaleManager#fullScreenError - * @private - * @param {Event} [event=undefined] - The fullscreenerror event; undefined if invoked on a device that does not support the Fullscreen API. - */ + * Called automatically when the browser fullscreen request fails; + * or called when a fullscreen request is made on a device for which it is not supported. + * + * @method Phaser.ScaleManager#fullScreenError + * @private + * @param {Event} [event=undefined] - The fullscreenerror event; undefined if invoked on a device that does not support the Fullscreen API. + */ fullScreenError: function (event) { - this.event = event; this.cleanupCreatedTarget(); @@ -2135,27 +2064,25 @@ Phaser.ScaleManager.prototype = { console.warn('Phaser.ScaleManager: requestFullscreen failed or device does not support the Fullscreen API'); this.onFullScreenError.dispatch(this); - }, /** - * Takes a Sprite or Image object and scales it to fit the given dimensions. - * Scaling happens proportionally without distortion to the sprites texture. - * The letterBox parameter controls if scaling will produce a letter-box effect or zoom the - * sprite until it fills the given values. Note that with letterBox set to false the scaled sprite may spill out over either - * the horizontal or vertical sides of the target dimensions. If you wish to stop this you can crop the Sprite. - * - * @method Phaser.ScaleManager#scaleSprite - * @protected - * @param {Phaser.Sprite|Phaser.Image} sprite - The sprite we want to scale. - * @param {integer} [width] - The target width that we want to fit the sprite in to. If not given it defaults to ScaleManager.width. - * @param {integer} [height] - The target height that we want to fit the sprite in to. If not given it defaults to ScaleManager.height. - * @param {boolean} [letterBox=false] - True if we want the `fitted` mode. Otherwise, the function uses the `zoom` mode. - * @return {Phaser.Sprite|Phaser.Image} The scaled sprite. - */ + * Takes a Sprite or Image object and scales it to fit the given dimensions. + * Scaling happens proportionally without distortion to the sprites texture. + * The letterBox parameter controls if scaling will produce a letter-box effect or zoom the + * sprite until it fills the given values. Note that with letterBox set to false the scaled sprite may spill out over either + * the horizontal or vertical sides of the target dimensions. If you wish to stop this you can crop the Sprite. + * + * @method Phaser.ScaleManager#scaleSprite + * @protected + * @param {Phaser.Sprite|Phaser.Image} sprite - The sprite we want to scale. + * @param {integer} [width] - The target width that we want to fit the sprite in to. If not given it defaults to ScaleManager.width. + * @param {integer} [height] - The target height that we want to fit the sprite in to. If not given it defaults to ScaleManager.height. + * @param {boolean} [letterBox=false] - True if we want the `fitted` mode. Otherwise, the function uses the `zoom` mode. + * @return {Phaser.Sprite|Phaser.Image} The scaled sprite. + */ scaleSprite: function (sprite, width, height, letterBox) { - if (width === undefined) { width = this.width; } if (height === undefined) { height = this.height; } if (letterBox === undefined) { letterBox = false; } @@ -2201,24 +2128,24 @@ Phaser.ScaleManager.prototype = { sprite.height = Math.floor(scaleY2); } - // Enable at some point? - // sprite.x = Math.floor((width - sprite.width) / 2); - // sprite.y = Math.floor((height - sprite.height) / 2); + /* + * Enable at some point? + * sprite.x = Math.floor((width - sprite.width) / 2); + * sprite.y = Math.floor((height - sprite.height) / 2); + */ return sprite; - }, /** - * Destroys the ScaleManager and removes any event listeners. - * This should probably only be called when the game is destroyed. - * - * @method Phaser.ScaleManager#destroy - * @protected - */ + * Destroys the ScaleManager and removes any event listeners. + * This should probably only be called when the game is destroyed. + * + * @method Phaser.ScaleManager#destroy + * @protected + */ destroy: function () { - this.game.onResume.remove(this._gameResumed, this); window.removeEventListener('orientationchange', this._orientationChange, false); @@ -2236,7 +2163,6 @@ Phaser.ScaleManager.prototype = { document.removeEventListener('MSFullscreenError', this._fullScreenError, false); document.removeEventListener('fullscreenerror', this._fullScreenError, false); } - } }; @@ -2244,20 +2170,19 @@ Phaser.ScaleManager.prototype = { Phaser.ScaleManager.prototype.constructor = Phaser.ScaleManager; /** -* The DOM element that is considered the Parent bounding element, if any. -* -* This `null` if {@link #parentIsWindow} is true or if fullscreen mode is entered and {@link #fullScreenTarget} is specified. -* It will also be null if there is no game canvas or if the game canvas has no parent. -* -* @name Phaser.ScaleManager#boundingParent -* @property {?DOMElement} boundingParent -* @readonly -*/ + * The DOM element that is considered the Parent bounding element, if any. + * + * This `null` if {@link #parentIsWindow} is true or if fullscreen mode is entered and {@link #fullScreenTarget} is specified. + * It will also be null if there is no game canvas or if the game canvas has no parent. + * + * @name Phaser.ScaleManager#boundingParent + * @property {?DOMElement} boundingParent + * @readonly + */ Object.defineProperty(Phaser.ScaleManager.prototype, 'boundingParent', { get: function () { - if (this.parentIsWindow || (this.isFullScreen && this.hasPhaserSetFullScreen && !this._createdFullScreenTarget)) { @@ -2267,60 +2192,56 @@ Object.defineProperty(Phaser.ScaleManager.prototype, 'boundingParent', { var parentNode = this.game.canvas && this.game.canvas.parentNode; return parentNode || null; - } }); /** -* The scaling method used by the ScaleManager when not in fullscreen. -* -*
-*
{@link Phaser.ScaleManager.NO_SCALE}
-*
-* The Game display area will not be scaled - even if it is too large for the canvas/screen. -* This mode _ignores_ any applied scaling factor and displays the canvas at the Game size. -*
-*
{@link Phaser.ScaleManager.EXACT_FIT}
-*
-* The Game display area will be _stretched_ to fill the entire size of the canvas's parent element and/or screen. -* Proportions are not maintained. -*
-*
{@link Phaser.ScaleManager.SHOW_ALL}
-*
-* Show the entire game display area while _maintaining_ the original aspect ratio. -*
-*
{@link Phaser.ScaleManager.RESIZE}
-*
-* The dimensions of the game display area are changed to match the size of the parent container. -* That is, this mode _changes the Game size_ to match the display size. -*

-* Any manually set Game size (see {@link #setGameSize}) is ignored while in effect. -*

-*
{@link Phaser.ScaleManager.USER_SCALE}
-*
-* The game Display is scaled according to the user-specified scale set by {@link Phaser.ScaleManager#setUserScale setUserScale}. -*

-* This scale can be adjusted in the {@link Phaser.ScaleManager#setResizeCallback resize callback} -* for flexible custom-sizing needs. -*

-*
-* -* @name Phaser.ScaleManager#scaleMode -* @property {integer} scaleMode -*/ + * The scaling method used by the ScaleManager when not in fullscreen. + * + *
+ *
{@link Phaser.ScaleManager.NO_SCALE}
+ *
+ * The Game display area will not be scaled - even if it is too large for the canvas/screen. + * This mode _ignores_ any applied scaling factor and displays the canvas at the Game size. + *
+ *
{@link Phaser.ScaleManager.EXACT_FIT}
+ *
+ * The Game display area will be _stretched_ to fill the entire size of the canvas's parent element and/or screen. + * Proportions are not maintained. + *
+ *
{@link Phaser.ScaleManager.SHOW_ALL}
+ *
+ * Show the entire game display area while _maintaining_ the original aspect ratio. + *
+ *
{@link Phaser.ScaleManager.RESIZE}
+ *
+ * The dimensions of the game display area are changed to match the size of the parent container. + * That is, this mode _changes the Game size_ to match the display size. + *

+ * Any manually set Game size (see {@link #setGameSize}) is ignored while in effect. + *

+ *
{@link Phaser.ScaleManager.USER_SCALE}
+ *
+ * The game Display is scaled according to the user-specified scale set by {@link Phaser.ScaleManager#setUserScale setUserScale}. + *

+ * This scale can be adjusted in the {@link Phaser.ScaleManager#setResizeCallback resize callback} + * for flexible custom-sizing needs. + *

+ *
+ * + * @name Phaser.ScaleManager#scaleMode + * @property {integer} scaleMode + */ Object.defineProperty(Phaser.ScaleManager.prototype, 'scaleMode', { get: function () { - return this._scaleMode; - }, set: function (value) { - if (value !== this._scaleMode) { if (!this.isFullScreen) @@ -2333,31 +2254,27 @@ Object.defineProperty(Phaser.ScaleManager.prototype, 'scaleMode', { } return this._scaleMode; - } }); /** -* The scaling method used by the ScaleManager when in fullscreen. -* -* See {@link Phaser.ScaleManager#scaleMode scaleMode} for the different modes allowed. -* -* @name Phaser.ScaleManager#fullScreenScaleMode -* @property {integer} fullScreenScaleMode -*/ + * The scaling method used by the ScaleManager when in fullscreen. + * + * See {@link Phaser.ScaleManager#scaleMode scaleMode} for the different modes allowed. + * + * @name Phaser.ScaleManager#fullScreenScaleMode + * @property {integer} fullScreenScaleMode + */ Object.defineProperty(Phaser.ScaleManager.prototype, 'fullScreenScaleMode', { get: function () { - return this._fullScreenScaleMode; - }, set: function (value) { - if (value !== this._fullScreenScaleMode) { // If in fullscreen then need a wee bit more work @@ -2376,113 +2293,102 @@ Object.defineProperty(Phaser.ScaleManager.prototype, 'fullScreenScaleMode', { } return this._fullScreenScaleMode; - } }); /** -* Returns the current scale mode - for normal or fullscreen operation. -* -* See {@link Phaser.ScaleManager#scaleMode scaleMode} for the different modes allowed. -* -* @name Phaser.ScaleManager#currentScaleMode -* @property {number} currentScaleMode -* @protected -* @readonly -*/ + * Returns the current scale mode - for normal or fullscreen operation. + * + * See {@link Phaser.ScaleManager#scaleMode scaleMode} for the different modes allowed. + * + * @name Phaser.ScaleManager#currentScaleMode + * @property {number} currentScaleMode + * @protected + * @readonly + */ Object.defineProperty(Phaser.ScaleManager.prototype, 'currentScaleMode', { get: function () { - return this.isFullScreen ? this._fullScreenScaleMode : this._scaleMode; - } }); /** -* When enabled the Display canvas will be horizontally-aligned _in the Parent container_ (or {@link Phaser.ScaleManager#parentIsWindow window}). -* -* To align horizontally across the page the Display canvas should be added directly to page; -* or the parent container should itself be horizontally aligned. -* -* Horizontal alignment is not applicable with the {@link .RESIZE} scaling mode. -* -* @name Phaser.ScaleManager#pageAlignHorizontally -* @property {boolean} pageAlignHorizontally -* @default false -*/ + * When enabled the Display canvas will be horizontally-aligned _in the Parent container_ (or {@link Phaser.ScaleManager#parentIsWindow window}). + * + * To align horizontally across the page the Display canvas should be added directly to page; + * or the parent container should itself be horizontally aligned. + * + * Horizontal alignment is not applicable with the {@link .RESIZE} scaling mode. + * + * @name Phaser.ScaleManager#pageAlignHorizontally + * @property {boolean} pageAlignHorizontally + * @default false + */ Object.defineProperty(Phaser.ScaleManager.prototype, 'pageAlignHorizontally', { get: function () { - return this._pageAlignHorizontally; - }, set: function (value) { - if (value !== this._pageAlignHorizontally) { this._pageAlignHorizontally = value; this.queueUpdate(true); } - } }); /** -* When enabled the Display canvas will be vertically-aligned _in the Parent container_ (or {@link Phaser.ScaleManager#parentIsWindow window}). -* -* To align vertically the Parent element should have a _non-collapsible_ height, such that it will maintain -* a height _larger_ than the height of the contained Game canvas - the game canvas will then be scaled vertically -* _within_ the remaining available height dictated by the Parent element. -* -* One way to prevent the parent from collapsing is to add an absolute "min-height" CSS property to the parent element. -* If specifying a relative "min-height/height" or adjusting margins, the Parent height must still be non-collapsible (see note). -* -* _Note_: In version 2.2 the minimum document height is _not_ automatically set to the viewport/window height. -* To automatically update the minimum document height set {@link Phaser.ScaleManager#compatibility compatibility.forceMinimumDocumentHeight} to true. -* -* Vertical alignment is not applicable with the {@link .RESIZE} scaling mode. -* -* @name Phaser.ScaleManager#pageAlignVertically -* @property {boolean} pageAlignVertically -* @default false -*/ + * When enabled the Display canvas will be vertically-aligned _in the Parent container_ (or {@link Phaser.ScaleManager#parentIsWindow window}). + * + * To align vertically the Parent element should have a _non-collapsible_ height, such that it will maintain + * a height _larger_ than the height of the contained Game canvas - the game canvas will then be scaled vertically + * _within_ the remaining available height dictated by the Parent element. + * + * One way to prevent the parent from collapsing is to add an absolute "min-height" CSS property to the parent element. + * If specifying a relative "min-height/height" or adjusting margins, the Parent height must still be non-collapsible (see note). + * + * _Note_: In version 2.2 the minimum document height is _not_ automatically set to the viewport/window height. + * To automatically update the minimum document height set {@link Phaser.ScaleManager#compatibility compatibility.forceMinimumDocumentHeight} to true. + * + * Vertical alignment is not applicable with the {@link .RESIZE} scaling mode. + * + * @name Phaser.ScaleManager#pageAlignVertically + * @property {boolean} pageAlignVertically + * @default false + */ Object.defineProperty(Phaser.ScaleManager.prototype, 'pageAlignVertically', { get: function () { - return this._pageAlignVertically; - }, set: function (value) { - if (value !== this._pageAlignVertically) { this._pageAlignVertically = value; this.queueUpdate(true); } - } }); /** -* Returns true if the browser is in fullscreen mode, otherwise false. -* @name Phaser.ScaleManager#isFullScreen -* @property {boolean} isFullScreen -* @readonly -*/ + * Returns true if the browser is in fullscreen mode, otherwise false. + * @name Phaser.ScaleManager#isFullScreen + * @property {boolean} isFullScreen + * @readonly + */ Object.defineProperty(Phaser.ScaleManager.prototype, 'isFullScreen', { get: function () @@ -2496,12 +2402,12 @@ Object.defineProperty(Phaser.ScaleManager.prototype, 'isFullScreen', { }); /** -* Returns true if the screen orientation is in portrait mode. -* -* @name Phaser.ScaleManager#isPortrait -* @property {boolean} isPortrait -* @readonly -*/ + * Returns true if the screen orientation is in portrait mode. + * + * @name Phaser.ScaleManager#isPortrait + * @property {boolean} isPortrait + * @readonly + */ Object.defineProperty(Phaser.ScaleManager.prototype, 'isPortrait', { get: function () @@ -2512,12 +2418,12 @@ Object.defineProperty(Phaser.ScaleManager.prototype, 'isPortrait', { }); /** -* Returns true if the screen orientation is in landscape mode. -* -* @name Phaser.ScaleManager#isLandscape -* @property {boolean} isLandscape -* @readonly -*/ + * Returns true if the screen orientation is in landscape mode. + * + * @name Phaser.ScaleManager#isLandscape + * @property {boolean} isLandscape + * @readonly + */ Object.defineProperty(Phaser.ScaleManager.prototype, 'isLandscape', { get: function () @@ -2528,15 +2434,15 @@ Object.defineProperty(Phaser.ScaleManager.prototype, 'isLandscape', { }); /** -* Returns true if the game dimensions are portrait (height > width). -* This is especially useful to check when using the RESIZE scale mode -* but wanting to maintain game orientation on desktop browsers, -* where typically the screen orientation will always be landscape regardless of the browser viewport. -* -* @name Phaser.ScaleManager#isGamePortrait -* @property {boolean} isGamePortrait -* @readonly -*/ + * Returns true if the game dimensions are portrait (height > width). + * This is especially useful to check when using the RESIZE scale mode + * but wanting to maintain game orientation on desktop browsers, + * where typically the screen orientation will always be landscape regardless of the browser viewport. + * + * @name Phaser.ScaleManager#isGamePortrait + * @property {boolean} isGamePortrait + * @readonly + */ Object.defineProperty(Phaser.ScaleManager.prototype, 'isGamePortrait', { get: function () @@ -2547,15 +2453,15 @@ Object.defineProperty(Phaser.ScaleManager.prototype, 'isGamePortrait', { }); /** -* Returns true if the game dimensions are landscape (width > height). -* This is especially useful to check when using the RESIZE scale mode -* but wanting to maintain game orientation on desktop browsers, -* where typically the screen orientation will always be landscape regardless of the browser viewport. -* -* @name Phaser.ScaleManager#isGameLandscape -* @property {boolean} isGameLandscape -* @readonly -*/ + * Returns true if the game dimensions are landscape (width > height). + * This is especially useful to check when using the RESIZE scale mode + * but wanting to maintain game orientation on desktop browsers, + * where typically the screen orientation will always be landscape regardless of the browser viewport. + * + * @name Phaser.ScaleManager#isGameLandscape + * @property {boolean} isGameLandscape + * @readonly + */ Object.defineProperty(Phaser.ScaleManager.prototype, 'isGameLandscape', { get: function () diff --git a/src/core/Signal.js b/src/core/Signal.js index cded0c81b..6db3e969d 100644 --- a/src/core/Signal.js +++ b/src/core/Signal.js @@ -1,142 +1,139 @@ /** -* @author Miller Medeiros http://millermedeiros.github.com/js-signals/ -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Miller Medeiros http://millermedeiros.github.com/js-signals/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* Signals are what Phaser uses to handle events and event dispatching. -* You can listen for a Signal by binding a callback / function to it. -* This is done by using either `Signal.add` or `Signal.addOnce`. -* -* For example you can listen for a touch or click event from the Input Manager -* by using its `onDown` Signal: -* -* `game.input.onDown.add(function() { ... });` -* -* Rather than inline your function, you can pass a reference: -* -* `game.input.onDown.add(clicked, this);` -* `function clicked () { ... }` -* -* In this case the second argument (`this`) is the context in which your function should be called. -* -* Now every time the InputManager dispatches the `onDown` signal (or event), your function -* will be called. -* -* Multiple callbacks can be bound to the same signal. -* They're ordered first by their `priority` arguments and then by the order in which they were added. -* If a callback calls {@link #halt} or returns `false`, any remaining callbacks are skipped. -* -* Very often a Signal will send arguments to your function. -* This is specific to the Signal itself. -* If you're unsure then check the documentation, or failing that simply do: -* -* `Signal.add(function() { console.log(arguments); })` -* -* and it will log all of the arguments your function received from the Signal. -* -* Sprites have lots of default signals you can listen to in their Events class, such as: -* -* `sprite.events.onKilled` -* -* Which is called automatically whenever the Sprite is killed. -* There are lots of other events, see the Events component for a list. -* -* As well as listening to pre-defined Signals you can also create your own: -* -* `var mySignal = new Phaser.Signal();` -* -* This creates a new Signal. You can bind a callback to it: -* -* `mySignal.add(myCallback, this);` -* -* and then finally when ready you can dispatch the Signal: -* -* `mySignal.dispatch(your arguments);` -* -* And your callback will be invoked. See the dispatch method for more details. -* -* @class Phaser.Signal -* @constructor -*/ + * Signals are what Phaser uses to handle events and event dispatching. + * You can listen for a Signal by binding a callback / function to it. + * This is done by using either `Signal.add` or `Signal.addOnce`. + * + * For example you can listen for a touch or click event from the Input Manager + * by using its `onDown` Signal: + * + * `game.input.onDown.add(function() { ... });` + * + * Rather than inline your function, you can pass a reference: + * + * `game.input.onDown.add(clicked, this);` + * `function clicked () { ... }` + * + * In this case the second argument (`this`) is the context in which your function should be called. + * + * Now every time the InputManager dispatches the `onDown` signal (or event), your function + * will be called. + * + * Multiple callbacks can be bound to the same signal. + * They're ordered first by their `priority` arguments and then by the order in which they were added. + * If a callback calls {@link #halt} or returns `false`, any remaining callbacks are skipped. + * + * Very often a Signal will send arguments to your function. + * This is specific to the Signal itself. + * If you're unsure then check the documentation, or failing that simply do: + * + * `Signal.add(function() { console.log(arguments); })` + * + * and it will log all of the arguments your function received from the Signal. + * + * Sprites have lots of default signals you can listen to in their Events class, such as: + * + * `sprite.events.onKilled` + * + * Which is called automatically whenever the Sprite is killed. + * There are lots of other events, see the Events component for a list. + * + * As well as listening to pre-defined Signals you can also create your own: + * + * `var mySignal = new Phaser.Signal();` + * + * This creates a new Signal. You can bind a callback to it: + * + * `mySignal.add(myCallback, this);` + * + * and then finally when ready you can dispatch the Signal: + * + * `mySignal.dispatch(your arguments);` + * + * And your callback will be invoked. See the dispatch method for more details. + * + * @class Phaser.Signal + * @constructor + */ Phaser.Signal = function () {}; Phaser.Signal.prototype = { /** - * @property {?Array.} _bindings - Internal variable. - * @private - */ + * @property {?Array.} _bindings - Internal variable. + * @private + */ _bindings: null, /** - * @property {any} _prevParams - Internal variable. - * @private - */ + * @property {any} _prevParams - Internal variable. + * @private + */ _prevParams: null, /** - * Memorize the previously dispatched event? - * - * If an event has been memorized it is automatically dispatched when a new listener is added with {@link #add} or {@link #addOnce}. - * Use {@link #forget} to clear any currently memorized event. - * - * @property {boolean} memorize - */ + * Memorize the previously dispatched event? + * + * If an event has been memorized it is automatically dispatched when a new listener is added with {@link #add} or {@link #addOnce}. + * Use {@link #forget} to clear any currently memorized event. + * + * @property {boolean} memorize + */ memorize: false, /** - * @property {boolean} _shouldPropagate - * @private - */ + * @property {boolean} _shouldPropagate + * @private + */ _shouldPropagate: true, /** - * Is the Signal active? Only active signals will broadcast dispatched events. - * - * Setting this property during a dispatch will only affect the next dispatch. To stop the propagation of a signal from a listener use {@link #halt}. - * - * @property {boolean} active - * @default - */ + * Is the Signal active? Only active signals will broadcast dispatched events. + * + * Setting this property during a dispatch will only affect the next dispatch. To stop the propagation of a signal from a listener use {@link #halt}. + * + * @property {boolean} active + * @default + */ active: true, /** - * @property {function} _boundDispatch - The bound dispatch function, if any. - * @private - */ + * @property {function} _boundDispatch - The bound dispatch function, if any. + * @private + */ _boundDispatch: false, /** - * @method Phaser.Signal#validateListener - * @param {function} listener - Signal handler function. - * @param {string} fnName - Function name. - * @private - */ + * @method Phaser.Signal#validateListener + * @param {function} listener - Signal handler function. + * @param {string} fnName - Function name. + * @private + */ validateListener: function (listener, fnName) { - if (typeof listener !== 'function') { throw new Error('Phaser.Signal: listener is a required param of {fn}() and should be a Function.'.replace('{fn}', fnName)); } - }, /** - * @method Phaser.Signal#_registerListener - * @private - * @param {function} listener - Signal handler function. - * @param {boolean} isOnce - Should the listener only be called once? - * @param {object} [listenerContext] - The context under which the listener is invoked. - * @param {number} [priority] - The priority level of the event listener. Listeners with higher priority will be executed before listeners with lower priority. Listeners with same priority level will be executed at the same order as they were added. (default = 0). - * @return {Phaser.SignalBinding} An Object representing the binding between the Signal and listener. - */ + * @method Phaser.Signal#_registerListener + * @private + * @param {function} listener - Signal handler function. + * @param {boolean} isOnce - Should the listener only be called once? + * @param {object} [listenerContext] - The context under which the listener is invoked. + * @param {number} [priority] - The priority level of the event listener. Listeners with higher priority will be executed before listeners with lower priority. Listeners with same priority level will be executed at the same order as they were added. (default = 0). + * @return {Phaser.SignalBinding} An Object representing the binding between the Signal and listener. + */ _registerListener: function (listener, isOnce, listenerContext, priority, args) { - var prevIndex = this._indexOfListener(listener, listenerContext); var binding; @@ -161,17 +158,15 @@ Phaser.Signal.prototype = { } return binding; - }, /** - * @method Phaser.Signal#_addBinding - * @private - * @param {Phaser.SignalBinding} binding - An Object representing the binding between the Signal and listener. - */ + * @method Phaser.Signal#_addBinding + * @private + * @param {Phaser.SignalBinding} binding - An Object representing the binding between the Signal and listener. + */ _addBinding: function (binding) { - if (!this._bindings) { this._bindings = []; @@ -187,19 +182,17 @@ Phaser.Signal.prototype = { while (this._bindings[n] && binding._priority <= this._bindings[n]._priority); this._bindings.splice(n + 1, 0, binding); - }, /** - * @method Phaser.Signal#_indexOfListener - * @private - * @param {function} listener - Signal handler function. - * @param {object} [context=null] - Signal handler function. - * @return {number} The index of the listener within the private bindings array. - */ + * @method Phaser.Signal#_indexOfListener + * @private + * @param {function} listener - Signal handler function. + * @param {object} [context=null] - Signal handler function. + * @return {number} The index of the listener within the private bindings array. + */ _indexOfListener: function (listener, context) { - if (!this._bindings) { return -1; @@ -221,53 +214,49 @@ Phaser.Signal.prototype = { } return -1; - }, /** - * Check if a specific listener is attached. - * - * @method Phaser.Signal#has - * @param {function} listener - Signal handler function. - * @param {object} [context] - Context on which listener will be executed (object that should represent the `this` variable inside listener function). - * @return {boolean} If Signal has the specified listener. - */ + * Check if a specific listener is attached. + * + * @method Phaser.Signal#has + * @param {function} listener - Signal handler function. + * @param {object} [context] - Context on which listener will be executed (object that should represent the `this` variable inside listener function). + * @return {boolean} If Signal has the specified listener. + */ has: function (listener, context) { - return this._indexOfListener(listener, context) !== -1; - }, /** - * Add an event listener for this signal. - * - * An event listener is a callback with a related context and priority. - * - * You can optionally provide extra arguments which will be passed to the callback after any internal parameters. - * - * For example: `Phaser.Key.onDown` when dispatched will send the Phaser.Key object that caused the signal as the first parameter. - * Any arguments you've specified after `priority` will be sent as well: - * - * `fireButton.onDown.add(shoot, this, 0, 'lazer', 100);` - * - * When onDown dispatches it will call the `shoot` callback passing it: `Phaser.Key, 'lazer', 100`. - * - * Where the first parameter is the one that Key.onDown dispatches internally and 'lazer', - * and the value 100 were the custom arguments given in the call to 'add'. - * - * If the callback calls {@link #halt} or returns `false`, any remaining callbacks bound to this Signal are skipped. - * - * @method Phaser.Signal#add - * @param {function} listener - The function to call when this Signal is dispatched. - * @param {object} [listenerContext] - The context under which the listener will be executed (i.e. the object that should represent the `this` variable). - * @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) - * @param {...any} [args=(none)] - Additional arguments to pass to the callback (listener) function. They will be appended after any arguments usually dispatched. - * @return {Phaser.SignalBinding} An Object representing the binding between the Signal and listener. - */ + * Add an event listener for this signal. + * + * An event listener is a callback with a related context and priority. + * + * You can optionally provide extra arguments which will be passed to the callback after any internal parameters. + * + * For example: `Phaser.Key.onDown` when dispatched will send the Phaser.Key object that caused the signal as the first parameter. + * Any arguments you've specified after `priority` will be sent as well: + * + * `fireButton.onDown.add(shoot, this, 0, 'lazer', 100);` + * + * When onDown dispatches it will call the `shoot` callback passing it: `Phaser.Key, 'lazer', 100`. + * + * Where the first parameter is the one that Key.onDown dispatches internally and 'lazer', + * and the value 100 were the custom arguments given in the call to 'add'. + * + * If the callback calls {@link #halt} or returns `false`, any remaining callbacks bound to this Signal are skipped. + * + * @method Phaser.Signal#add + * @param {function} listener - The function to call when this Signal is dispatched. + * @param {object} [listenerContext] - The context under which the listener will be executed (i.e. the object that should represent the `this` variable). + * @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) + * @param {...any} [args=(none)] - Additional arguments to pass to the callback (listener) function. They will be appended after any arguments usually dispatched. + * @return {Phaser.SignalBinding} An Object representing the binding between the Signal and listener. + */ add: function (listener, listenerContext, priority) { - this.validateListener(listener, 'add'); var args = []; @@ -281,25 +270,23 @@ Phaser.Signal.prototype = { } return this._registerListener(listener, false, listenerContext, priority, args); - }, /** - * Add a one-time listener - the listener is automatically removed after the first execution. - * - * If there is as {@link Phaser.Signal#memorize memorized} event then it will be dispatched and - * the listener will be removed immediately. - * - * @method Phaser.Signal#addOnce - * @param {function} listener - The function to call when this Signal is dispatched. - * @param {object} [listenerContext] - The context under which the listener will be executed (i.e. the object that should represent the `this` variable). - * @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) - * @param {...any} [args=(none)] - Additional arguments to pass to the callback (listener) function. They will be appended after any arguments usually dispatched. - * @return {Phaser.SignalBinding} An Object representing the binding between the Signal and listener. - */ + * Add a one-time listener - the listener is automatically removed after the first execution. + * + * If there is as {@link Phaser.Signal#memorize memorized} event then it will be dispatched and + * the listener will be removed immediately. + * + * @method Phaser.Signal#addOnce + * @param {function} listener - The function to call when this Signal is dispatched. + * @param {object} [listenerContext] - The context under which the listener will be executed (i.e. the object that should represent the `this` variable). + * @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) + * @param {...any} [args=(none)] - Additional arguments to pass to the callback (listener) function. They will be appended after any arguments usually dispatched. + * @return {Phaser.SignalBinding} An Object representing the binding between the Signal and listener. + */ addOnce: function (listener, listenerContext, priority) { - this.validateListener(listener, 'addOnce'); var args = []; @@ -313,20 +300,18 @@ Phaser.Signal.prototype = { } return this._registerListener(listener, true, listenerContext, priority, args); - }, /** - * Remove a single event listener. - * - * @method Phaser.Signal#remove - * @param {function} listener - Handler function that should be removed. - * @param {object} [context=null] - Execution context (since you can add the same handler multiple times if executing in a different context). - * @return {function} Listener handler function. - */ + * Remove a single event listener. + * + * @method Phaser.Signal#remove + * @param {function} listener - Handler function that should be removed. + * @param {object} [context=null] - Execution context (since you can add the same handler multiple times if executing in a different context). + * @return {function} Listener handler function. + */ remove: function (listener, context) { - this.validateListener(listener, 'remove'); var i = this._indexOfListener(listener, context); @@ -338,18 +323,16 @@ Phaser.Signal.prototype = { } return listener; - }, /** - * Remove all event listeners. - * - * @method Phaser.Signal#removeAll - * @param {object} [context=null] - If specified only listeners for the given context will be removed. - */ + * Remove all event listeners. + * + * @method Phaser.Signal#removeAll + * @param {object} [context=null] - If specified only listeners for the given context will be removed. + */ removeAll: function (context) { - if (context === undefined) { context = null; } if (!this._bindings) @@ -379,48 +362,42 @@ Phaser.Signal.prototype = { { this._bindings.length = 0; } - }, /** - * Gets the total number of listeners attached to this Signal. - * - * @method Phaser.Signal#getNumListeners - * @return {integer} Number of listeners attached to the Signal. - */ + * Gets the total number of listeners attached to this Signal. + * + * @method Phaser.Signal#getNumListeners + * @return {integer} Number of listeners attached to the Signal. + */ getNumListeners: function () { - return this._bindings ? this._bindings.length : 0; - }, /** - * Stop propagation of the event, blocking the dispatch to next listener on the queue. - * - * This should be called only during event dispatch as calling it before/after dispatch won't affect another broadcast. - * See {@link #active} to enable/disable the signal entirely. - * - * @method Phaser.Signal#halt - */ + * Stop propagation of the event, blocking the dispatch to next listener on the queue. + * + * This should be called only during event dispatch as calling it before/after dispatch won't affect another broadcast. + * See {@link #active} to enable/disable the signal entirely. + * + * @method Phaser.Signal#halt + */ halt: function () { - this._shouldPropagate = false; - }, /** - * Dispatch / broadcast the event to all listeners. - * - * To create an instance-bound dispatch for this Signal, use {@link #boundDispatch}. - * - * @method Phaser.Signal#dispatch - * @param {any} [params] - Parameters that should be passed to each handler. - */ + * Dispatch / broadcast the event to all listeners. + * + * To create an instance-bound dispatch for this Signal, use {@link #boundDispatch}. + * + * @method Phaser.Signal#dispatch + * @param {any} [params] - Parameters that should be passed to each handler. + */ dispatch: function () { - if (!this.active || (!this._bindings && !this.memorize)) { return; @@ -444,42 +421,40 @@ Phaser.Signal.prototype = { var bindings = this._bindings.slice(); // clone array in case add/remove items during dispatch this._shouldPropagate = true; // in case `halt` was called before dispatch or during the previous dispatch. - // execute all callbacks until end of the list or until a callback returns `false` or stops propagation - // reverse loop since listeners with higher priority will be added at the end of the list + /* + * execute all callbacks until end of the list or until a callback returns `false` or stops propagation + * reverse loop since listeners with higher priority will be added at the end of the list + */ do { n--; } while (bindings[n] && this._shouldPropagate && bindings[n].execute(paramsArr) !== false); - }, /** - * Forget the currently {@link Phaser.Signal#memorize memorized} event, if any. - * - * @method Phaser.Signal#forget - */ + * Forget the currently {@link Phaser.Signal#memorize memorized} event, if any. + * + * @method Phaser.Signal#forget + */ forget: function () { - if (this._prevParams) { this._prevParams = null; } - }, /** - * Dispose the signal - no more events can be dispatched. - * - * This removes all event listeners and clears references to external objects. - * Calling methods on a disposed objects results in undefined behavior. - * - * @method Phaser.Signal#dispose - */ + * Dispose the signal - no more events can be dispatched. + * + * This removes all event listeners and clears references to external objects. + * Calling methods on a disposed objects results in undefined behavior. + * + * @method Phaser.Signal#dispose + */ dispose: function () { - this.removeAll(); this._bindings = null; @@ -487,33 +462,30 @@ Phaser.Signal.prototype = { { this._prevParams = null; } - }, /** - * A string representation of the object. - * - * @method Phaser.Signal#toString - * @return {string} String representation of the object. - */ + * A string representation of the object. + * + * @method Phaser.Signal#toString + * @return {string} String representation of the object. + */ toString: function () { - return '[Phaser.Signal active:' + this.active + ' numListeners:' + this.getNumListeners() + ']'; - } }; /** -* Create a `dispatch` function that maintains a binding to the original Signal context. -* -* Use the resulting value if the dispatch function needs to be passed somewhere -* or called independently of the Signal object. -* -* @memberof Phaser.Signal -* @property {function} boundDispatch -*/ + * Create a `dispatch` function that maintains a binding to the original Signal context. + * + * Use the resulting value if the dispatch function needs to be passed somewhere + * or called independently of the Signal object. + * + * @memberof Phaser.Signal + * @property {function} boundDispatch + */ Object.defineProperty(Phaser.Signal.prototype, 'boundDispatch', { get: function () diff --git a/src/core/SignalBinding.js b/src/core/SignalBinding.js index 0063719cf..fb7c8a0d6 100644 --- a/src/core/SignalBinding.js +++ b/src/core/SignalBinding.js @@ -1,31 +1,30 @@ /** -* @author Miller Medeiros http://millermedeiros.github.com/js-signals/ -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Miller Medeiros http://millermedeiros.github.com/js-signals/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* Object that represents a binding between a Signal and a listener function. -* This is an internal constructor and shouldn't be created directly. -* Inspired by Joa Ebert AS3 SignalBinding and Robert Penner's Slot classes. -* -* @class Phaser.SignalBinding -* @constructor -* @param {Phaser.Signal} signal - Reference to Signal object that listener is currently bound to. -* @param {function} listener - Handler function bound to the signal. -* @param {boolean} isOnce - If binding should be executed just once. -* @param {object} [listenerContext=null] - Context on which listener will be executed (object that should represent the `this` variable inside listener function). -* @param {number} [priority] - The priority level of the event listener. (default = 0). -* @param {...any} [args=(none)] - Additional arguments to pass to the callback (listener) function. They will be appended after any arguments usually dispatched. -*/ + * Object that represents a binding between a Signal and a listener function. + * This is an internal constructor and shouldn't be created directly. + * Inspired by Joa Ebert AS3 SignalBinding and Robert Penner's Slot classes. + * + * @class Phaser.SignalBinding + * @constructor + * @param {Phaser.Signal} signal - Reference to Signal object that listener is currently bound to. + * @param {function} listener - Handler function bound to the signal. + * @param {boolean} isOnce - If binding should be executed just once. + * @param {object} [listenerContext=null] - Context on which listener will be executed (object that should represent the `this` variable inside listener function). + * @param {number} [priority] - The priority level of the event listener. (default = 0). + * @param {...any} [args=(none)] - Additional arguments to pass to the callback (listener) function. They will be appended after any arguments usually dispatched. + */ Phaser.SignalBinding = function (signal, listener, isOnce, listenerContext, priority, args) { - /** - * @property {Phaser.Game} _listener - Handler function bound to the signal. - * @private - */ + * @property {Phaser.Game} _listener - Handler function bound to the signal. + * @private + */ this._listener = listener; if (isOnce) @@ -39,9 +38,9 @@ Phaser.SignalBinding = function (signal, listener, isOnce, listenerContext, prio } /** - * @property {Phaser.Signal} _signal - Reference to Signal object that listener is currently bound to. - * @private - */ + * @property {Phaser.Signal} _signal - Reference to Signal object that listener is currently bound to. + * @private + */ this._signal = signal; if (priority) @@ -53,63 +52,61 @@ Phaser.SignalBinding = function (signal, listener, isOnce, listenerContext, prio { this._args = args; } - }; Phaser.SignalBinding.prototype = { /** - * @property {?object} context - Context on which listener will be executed (object that should represent the `this` variable inside listener function). - */ + * @property {?object} context - Context on which listener will be executed (object that should represent the `this` variable inside listener function). + */ context: null, /** - * @property {boolean} _isOnce - If binding should be executed just once. - * @private - */ + * @property {boolean} _isOnce - If binding should be executed just once. + * @private + */ _isOnce: false, /** - * @property {number} _priority - Listener priority. - * @private - */ + * @property {number} _priority - Listener priority. + * @private + */ _priority: 0, /** - * @property {array} _args - Listener arguments. - * @private - */ + * @property {array} _args - Listener arguments. + * @private + */ _args: null, /** - * @property {number} callCount - The number of times the handler function has been called. - */ + * @property {number} callCount - The number of times the handler function has been called. + */ callCount: 0, /** - * If binding is active and should be executed. - * @property {boolean} active - * @default - */ + * If binding is active and should be executed. + * @property {boolean} active + * @default + */ active: true, /** - * Default parameters passed to listener during `Signal.dispatch` and `SignalBinding.execute` (curried parameters). - * @property {array|null} params - * @default - */ + * Default parameters passed to listener during `Signal.dispatch` and `SignalBinding.execute` (curried parameters). + * @property {array|null} params + * @default + */ params: null, /** - * Call listener passing arbitrary parameters. - * If binding was added using `Signal.addOnce()` it will be automatically removed from signal dispatch queue, this method is used internally for the signal dispatch. - * @method Phaser.SignalBinding#execute - * @param {any[]} [paramsArr] - Array of parameters that should be passed to the listener. - * @return {any} Value returned by the listener. - */ + * Call listener passing arbitrary parameters. + * If binding was added using `Signal.addOnce()` it will be automatically removed from signal dispatch queue, this method is used internally for the signal dispatch. + * @method Phaser.SignalBinding#execute + * @param {any[]} [paramsArr] - Array of parameters that should be passed to the listener. + * @return {any} Value returned by the listener. + */ execute: function (paramsArr) { - var handlerReturn, params; if (this.active && !!this._listener) @@ -132,61 +129,60 @@ Phaser.SignalBinding.prototype = { } return handlerReturn; - }, /** - * Detach binding from signal. - * alias to: @see mySignal.remove(myBinding.getListener()); - * @method Phaser.SignalBinding#detach - * @return {function|null} Handler function bound to the signal or `null` if binding was previously detached. - */ + * Detach binding from signal. + * alias to: @see mySignal.remove(myBinding.getListener()); + * @method Phaser.SignalBinding#detach + * @return {function|null} Handler function bound to the signal or `null` if binding was previously detached. + */ detach: function () { return this.isBound() ? this._signal.remove(this._listener, this.context) : null; }, /** - * @method Phaser.SignalBinding#isBound - * @return {boolean} True if binding is still bound to the signal and has a listener. - */ + * @method Phaser.SignalBinding#isBound + * @return {boolean} True if binding is still bound to the signal and has a listener. + */ isBound: function () { return (!!this._signal && !!this._listener); }, /** - * @method Phaser.SignalBinding#isOnce - * @return {boolean} If SignalBinding will only be executed once. - */ + * @method Phaser.SignalBinding#isOnce + * @return {boolean} If SignalBinding will only be executed once. + */ isOnce: function () { return this._isOnce; }, /** - * @method Phaser.SignalBinding#getListener - * @return {function} Handler function bound to the signal. - */ + * @method Phaser.SignalBinding#getListener + * @return {function} Handler function bound to the signal. + */ getListener: function () { return this._listener; }, /** - * @method Phaser.SignalBinding#getSignal - * @return {Phaser.Signal} Signal that listener is currently bound to. - */ + * @method Phaser.SignalBinding#getSignal + * @return {Phaser.Signal} Signal that listener is currently bound to. + */ getSignal: function () { return this._signal; }, /** - * Delete instance properties - * @method Phaser.SignalBinding#_destroy - * @private - */ + * Delete instance properties + * @method Phaser.SignalBinding#_destroy + * @private + */ _destroy: function () { delete this._signal; @@ -195,9 +191,9 @@ Phaser.SignalBinding.prototype = { }, /** - * @method Phaser.SignalBinding#toString - * @return {string} String representation of the object. - */ + * @method Phaser.SignalBinding#toString + * @return {string} String representation of the object. + */ toString: function () { return '[Phaser.SignalBinding isOnce:' + this._isOnce + ', isBound:' + this.isBound() + ', active:' + this.active + ']'; diff --git a/src/core/Stage.js b/src/core/Stage.js index 16cc6ae81..b2ded53a3 100644 --- a/src/core/Stage.js +++ b/src/core/Stage.js @@ -1,86 +1,85 @@ /** -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* The Stage controls root level display objects upon which everything is displayed. -* It also handles browser visibility handling and the pausing due to loss of focus. -* -* @class Phaser.Stage -* @extends PIXI.DisplayObjectContainer -* @constructor -* @param {Phaser.Game} game - Game reference to the currently running game. + * The Stage controls root level display objects upon which everything is displayed. + * It also handles browser visibility handling and the pausing due to loss of focus. + * + * @class Phaser.Stage + * @extends PIXI.DisplayObjectContainer + * @constructor + * @param {Phaser.Game} game - Game reference to the currently running game. */ Phaser.Stage = function (game) { - /** - * @property {Phaser.Game} game - A reference to the currently running Game. - */ + * @property {Phaser.Game} game - A reference to the currently running Game. + */ this.game = game; PIXI.DisplayObjectContainer.call(this); /** - * @property {string} name - The name of this object. - * @default - */ + * @property {string} name - The name of this object. + * @default + */ this.name = '_stage_root'; /** - * By default if the browser tab loses focus the game will pause. - * You can stop that behavior by setting this property to true. - * Note that the browser can still elect to pause your game if it wishes to do so, - * for example swapping to another browser tab. This will cause the RAF callback to halt, - * effectively pausing your game, even though no in-game pause event is triggered if you enable this property. - * @property {boolean} disableVisibilityChange - * @default - */ + * By default if the browser tab loses focus the game will pause. + * You can stop that behavior by setting this property to true. + * Note that the browser can still elect to pause your game if it wishes to do so, + * for example swapping to another browser tab. This will cause the RAF callback to halt, + * effectively pausing your game, even though no in-game pause event is triggered if you enable this property. + * @property {boolean} disableVisibilityChange + * @default + */ this.disableVisibilityChange = false; /** - * @property {boolean} exists - If exists is true the Stage and all children are updated, otherwise it is skipped. - * @default - */ + * @property {boolean} exists - If exists is true the Stage and all children are updated, otherwise it is skipped. + * @default + */ this.exists = true; /** - * @property {Phaser.Matrix} worldTransform - Current transform of the object based on world (parent) factors - * @private - * @readOnly - */ + * @property {Phaser.Matrix} worldTransform - Current transform of the object based on world (parent) factors + * @private + * @readOnly + */ this.worldTransform = new Phaser.Matrix(); /** - * @property {Phaser.Stage} stage - The stage reference (the Stage is its own stage) - * @private - * @readOnly - */ + * @property {Phaser.Stage} stage - The stage reference (the Stage is its own stage) + * @private + * @readOnly + */ this.stage = this; /** - * @property {number} currentRenderOrderID - Reset each frame, keeps a count of the total number of objects updated. - */ + * @property {number} currentRenderOrderID - Reset each frame, keeps a count of the total number of objects updated. + */ this.currentRenderOrderID = 0; /** - * @property {string} hiddenVar - The page visibility API event name. - * @private - */ + * @property {string} hiddenVar - The page visibility API event name. + * @private + */ this._hiddenVar = 'hidden'; /** - * @property {function} _onChange - The blur/focus event handler. - * @private - */ + * @property {function} _onChange - The blur/focus event handler. + * @private + */ this._onChange = null; /** - * @property {number} _bgColor - Stage background color object. Populated by setBackgroundColor. - * @private - */ + * @property {number} _bgColor - Stage background color object. Populated by setBackgroundColor. + * @private + */ this._bgColor = { r: 0, g: 0, b: 0, a: 0, color: 0, rgba: '#000000' }; if (!this.game.transparent) @@ -93,22 +92,20 @@ Phaser.Stage = function (game) { this.parseConfig(game.config); } - }; Phaser.Stage.prototype = Object.create(PIXI.DisplayObjectContainer.prototype); Phaser.Stage.prototype.constructor = Phaser.Stage; /** -* Parses a Game configuration object. -* -* @method Phaser.Stage#parseConfig -* @protected -* @param {object} config -The configuration object to parse. -*/ + * Parses a Game configuration object. + * + * @method Phaser.Stage#parseConfig + * @protected + * @param {object} config -The configuration object to parse. + */ Phaser.Stage.prototype.parseConfig = function (config) { - if (config.disableVisibilityChange) { this.disableVisibilityChange = config.disableVisibilityChange; @@ -118,35 +115,31 @@ Phaser.Stage.prototype.parseConfig = function (config) { this.setBackgroundColor(config.backgroundColor); } - }; /** -* Initialises the stage and adds the event listeners. -* @method Phaser.Stage#boot -* @private -*/ + * Initialises the stage and adds the event listeners. + * @method Phaser.Stage#boot + * @private + */ Phaser.Stage.prototype.boot = function () { - Phaser.DOM.getOffset(this.game.canvas, this.offset); Phaser.Canvas.setUserSelect(this.game.canvas, 'none'); Phaser.Canvas.setTouchAction(this.game.canvas, 'none'); this.checkVisibility(); - }; /** -* This is called automatically after the plugins preUpdate and before the State.update. -* Most objects have preUpdate methods and it's where initial movement and positioning is done. -* -* @method Phaser.Stage#preUpdate -*/ + * This is called automatically after the plugins preUpdate and before the State.update. + * Most objects have preUpdate methods and it's where initial movement and positioning is done. + * + * @method Phaser.Stage#preUpdate + */ Phaser.Stage.prototype.preUpdate = function () { - this.currentRenderOrderID = 0; // This can't loop in reverse, we need the renderOrderID to be in sequence @@ -163,17 +156,15 @@ Phaser.Stage.prototype.preUpdate = function () i++; } } - }; /** -* This is called automatically after the State.update, but before particles or plugins update. -* -* @method Phaser.Stage#update -*/ + * This is called automatically after the State.update, but before particles or plugins update. + * + * @method Phaser.Stage#update + */ Phaser.Stage.prototype.update = function () { - // Goes in reverse, because it's highly likely the child will destroy itself in `update` var i = this.children.length; @@ -181,19 +172,17 @@ Phaser.Stage.prototype.update = function () { this.children[i].update(); } - }; /** -* This is called automatically before the renderer runs and after the plugins have updated. -* In postUpdate this is where all the final physics calculations and object positioning happens. -* The objects are processed in the order of the display list. -* -* @method Phaser.Stage#postUpdate -*/ + * This is called automatically before the renderer runs and after the plugins have updated. + * In postUpdate this is where all the final physics calculations and object positioning happens. + * The objects are processed in the order of the display list. + * + * @method Phaser.Stage#postUpdate + */ Phaser.Stage.prototype.postUpdate = function () { - // Apply the camera shake, fade, bounds, etc this.game.camera.update(); @@ -213,36 +202,32 @@ Phaser.Stage.prototype.postUpdate = function () } this.updateTransform(); - }; /** -* Updates the transforms for all objects on the display list. -* This overrides the Pixi default as we don't need the interactionManager, but do need the game property check. -* -* @method Phaser.Stage#updateTransform -*/ + * Updates the transforms for all objects on the display list. + * This overrides the Pixi default as we don't need the interactionManager, but do need the game property check. + * + * @method Phaser.Stage#updateTransform + */ Phaser.Stage.prototype.updateTransform = function () { - this.worldAlpha = 1; for (var i = 0; i < this.children.length; i++) { this.children[i].updateTransform(); } - }; /** -* Starts a page visibility event listener running, or window.onpagehide/onpageshow if not supported by the browser. -* Also listens for window.onblur and window.onfocus. -* -* @method Phaser.Stage#checkVisibility -*/ + * Starts a page visibility event listener running, or window.onpagehide/onpageshow if not supported by the browser. + * Also listens for window.onblur and window.onfocus. + * + * @method Phaser.Stage#checkVisibility + */ Phaser.Stage.prototype.checkVisibility = function () { - if (document.hidden !== undefined) { this._hiddenVar = 'visibilitychange'; @@ -321,23 +306,21 @@ Phaser.Stage.prototype.checkVisibility = function () CocoonJS.App.on('suspended', this._onChangePause); } } - }; /** -* This method is called when the document visibility is changed. -* -* - `blur` and `pagehide` events trigger {@link Phaser.Game#onBlur}. They {@link Phaser.Game#gamePaused pause the game} unless {@link #disableVisibilityChange} is on. -* - `click`, `focus`, and `pageshow` trigger {@link Phaser.Game#onFocus}. They {@link Phaser.Game#gameResumed resume the game} unless {@link #disableVisibilityChange} is on. -* - `visibilitychange` (hidden) and CocoonJS's `onSuspended` {@link Phaser.Game#gamePaused pause the game} unless {@link #disableVisibilityChange} is on. -* - `visibilitychange` (visible) and CocoonJS's `onActivated` {@link Phaser.Game#gameResumed resume the game} unless {@link #disableVisibilityChange} is on. -* -* @method Phaser.Stage#visibilityChange -* @param {Event} event - Its type will be used to decide whether the game should be paused or not. -*/ + * This method is called when the document visibility is changed. + * + * - `blur` and `pagehide` events trigger {@link Phaser.Game#onBlur}. They {@link Phaser.Game#gamePaused pause the game} unless {@link #disableVisibilityChange} is on. + * - `click`, `focus`, and `pageshow` trigger {@link Phaser.Game#onFocus}. They {@link Phaser.Game#gameResumed resume the game} unless {@link #disableVisibilityChange} is on. + * - `visibilitychange` (hidden) and CocoonJS's `onSuspended` {@link Phaser.Game#gamePaused pause the game} unless {@link #disableVisibilityChange} is on. + * - `visibilitychange` (visible) and CocoonJS's `onActivated` {@link Phaser.Game#gameResumed resume the game} unless {@link #disableVisibilityChange} is on. + * + * @method Phaser.Stage#visibilityChange + * @param {Event} event - Its type will be used to decide whether the game should be paused or not. + */ Phaser.Stage.prototype.visibilityChange = function (event) { - // These events always trigger the Game#onBlur or Game#onFocus signals. switch (event.type) @@ -366,26 +349,24 @@ Phaser.Stage.prototype.visibilityChange = function (event) { this.game.gameResumed(event); } - }; /** -* Sets the background color for the Stage. -* -* The color can be given as a hex string (`'#RRGGBB'`), a CSS color string (`'rgb(r,g,b)'`), or a numeric value (`0xRRGGBB`). -* -* An alpha channel is _not_ supported and will be ignored. -* -* If you've set your game to be {@link Phaser.Game#transparent transparent} then calls to setBackgroundColor are ignored. -* -* If {@link Phaser.Game#clearBeforeRender} is off then the background color won't appear. -* -* @method Phaser.Stage#setBackgroundColor -* @param {number|string} color - The color of the background. -*/ + * Sets the background color for the Stage. + * + * The color can be given as a hex string (`'#RRGGBB'`), a CSS color string (`'rgb(r,g,b)'`), or a numeric value (`0xRRGGBB`). + * + * An alpha channel is _not_ supported and will be ignored. + * + * If you've set your game to be {@link Phaser.Game#transparent transparent} then calls to setBackgroundColor are ignored. + * + * If {@link Phaser.Game#clearBeforeRender} is off then the background color won't appear. + * + * @method Phaser.Stage#setBackgroundColor + * @param {number|string} color - The color of the background. + */ Phaser.Stage.prototype.setBackgroundColor = function (color) { - if (this.game.transparent) { return; } Phaser.Color.valueToColor(color, this._bgColor); @@ -396,17 +377,15 @@ Phaser.Stage.prototype.setBackgroundColor = function (color) this._bgColor.g /= 255; this._bgColor.b /= 255; this._bgColor.a = 1; - }; /** -* Destroys the Stage and removes event listeners. -* -* @method Phaser.Stage#destroy -*/ + * Destroys the Stage and removes event listeners. + * + * @method Phaser.Stage#destroy + */ Phaser.Stage.prototype.destroy = function () { - if (this._hiddenVar) { document.removeEventListener(this._hiddenVar, this._onChange, false); @@ -419,27 +398,25 @@ Phaser.Stage.prototype.destroy = function () window.onfocus = null; window.removeEventListener('click', this._onClick); - }; /** -* Adds an existing object to the Stage. -* -* The child is automatically added to the front of the Stage, and is displayed above every previous child. -* Or if the _optional_ `index` is specified, the child is added at the location specified by the index value, -* this allows you to control child ordering. -* -* If the object was already on the Stage, it is simply returned, and nothing else happens to it. -* -* @method Phaser.Stage#add -* @param {DisplayObject} child - The display object to add as a child. -* @param {boolean} [silent] - Unused. Kept for compatibility with {@link Phaser.Group#add}. -* @param {integer} [index] - The index to insert the object to. -* @return {DisplayObject} The child that was added to the group. -*/ + * Adds an existing object to the Stage. + * + * The child is automatically added to the front of the Stage, and is displayed above every previous child. + * Or if the _optional_ `index` is specified, the child is added at the location specified by the index value, + * this allows you to control child ordering. + * + * If the object was already on the Stage, it is simply returned, and nothing else happens to it. + * + * @method Phaser.Stage#add + * @param {DisplayObject} child - The display object to add as a child. + * @param {boolean} [silent] - Unused. Kept for compatibility with {@link Phaser.Group#add}. + * @param {integer} [index] - The index to insert the object to. + * @return {DisplayObject} The child that was added to the group. + */ Phaser.Stage.prototype.add = function (child, silent, index) { - if (child.parent === this) { return child; @@ -460,50 +437,42 @@ Phaser.Stage.prototype.add = function (child, silent, index) } return child; - }; /** -* @name Phaser.Stage#backgroundColor -* @property {number|string} backgroundColor - Gets and sets the background color of the stage. The color can be given as a number: 0xff0000 or a hex string: '#ff0000' -* @see Phaser.Stage#setBackgroundColor -*/ + * @name Phaser.Stage#backgroundColor + * @property {number|string} backgroundColor - Gets and sets the background color of the stage. The color can be given as a number: 0xff0000 or a hex string: '#ff0000' + * @see Phaser.Stage#setBackgroundColor + */ Object.defineProperty(Phaser.Stage.prototype, 'backgroundColor', { get: function () { - return this._bgColor.color; - }, set: function (color) { - this.setBackgroundColor(color); - } }); /** -* Enable or disable texture smoothing for all objects on this Stage. Only works for bitmap/image textures. Smoothing is enabled by default. -* -* @name Phaser.Stage#smoothed -* @property {boolean} smoothed - Set to true to smooth all sprites rendered on this Stage, or false to disable smoothing (great for pixel art) -*/ + * Enable or disable texture smoothing for all objects on this Stage. Only works for bitmap/image textures. Smoothing is enabled by default. + * + * @name Phaser.Stage#smoothed + * @property {boolean} smoothed - Set to true to smooth all sprites rendered on this Stage, or false to disable smoothing (great for pixel art) + */ Object.defineProperty(Phaser.Stage.prototype, 'smoothed', { get: function () { - return PIXI.scaleModes.DEFAULT === PIXI.scaleModes.LINEAR; - }, set: function (value) { - if (value) { PIXI.scaleModes.DEFAULT = PIXI.scaleModes.LINEAR; diff --git a/src/core/State.js b/src/core/State.js index 581b532c8..d6a14e727 100644 --- a/src/core/State.js +++ b/src/core/State.js @@ -1,286 +1,284 @@ /** -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* This is a base State class which can be extended if you are creating your own game. -* It provides quick access to common functions such as the camera, cache, input, match, sound and more. -* -* #### Callbacks -* -* | start | preload | loaded | paused | stop | -* |-------|-------------|------------|--------------|----------| -* | init | | | | | -* | | preload | create | paused | | -* | | loadUpdate* | update* | pauseUpdate* | | -* | | | postUpdate*| | | -* | | | preRender* | | | -* | | loadRender* | render* | render* | | -* | | | | resumed | | -* | | | | | shutdown | -* -* Update and render calls (*) are repeated. -* -* If your State has a constructor, it will be invoked exactly once, during {@link {@link Phaser.StateManager#add}. -* -* @class Phaser.State -* @constructor -*/ + * This is a base State class which can be extended if you are creating your own game. + * It provides quick access to common functions such as the camera, cache, input, match, sound and more. + * + * #### Callbacks + * + * | start | preload | loaded | paused | stop | + * |-------|-------------|------------|--------------|----------| + * | init | | | | | + * | | preload | create | paused | | + * | | loadUpdate* | update* | pauseUpdate* | | + * | | | postUpdate*| | | + * | | | preRender* | | | + * | | loadRender* | render* | render* | | + * | | | | resumed | | + * | | | | | shutdown | + * + * Update and render calls (*) are repeated. + * + * If your State has a constructor, it will be invoked exactly once, during {@link {@link Phaser.StateManager#add}. + * + * @class Phaser.State + * @constructor + */ Phaser.State = function () { - /** - * @property {Phaser.Game} game - This is a reference to the currently running Game. - */ + * @property {Phaser.Game} game - This is a reference to the currently running Game. + */ this.game = null; /** - * @property {string} key - The string based identifier given to the State when added into the State Manager. - */ + * @property {string} key - The string based identifier given to the State when added into the State Manager. + */ this.key = ''; /** - * @property {Phaser.GameObjectFactory} add - A reference to the GameObjectFactory which can be used to add new objects to the World. - */ + * @property {Phaser.GameObjectFactory} add - A reference to the GameObjectFactory which can be used to add new objects to the World. + */ this.add = null; /** - * @property {Phaser.GameObjectCreator} make - A reference to the GameObjectCreator which can be used to make new objects. - */ + * @property {Phaser.GameObjectCreator} make - A reference to the GameObjectCreator which can be used to make new objects. + */ this.make = null; /** - * @property {Phaser.Camera} camera - A handy reference to World.camera. - */ + * @property {Phaser.Camera} camera - A handy reference to World.camera. + */ this.camera = null; /** - * @property {Phaser.Cache} cache - A reference to the game cache which contains any loaded or generated assets, such as images, sound and more. - */ + * @property {Phaser.Cache} cache - A reference to the game cache which contains any loaded or generated assets, such as images, sound and more. + */ this.cache = null; /** - * @property {Phaser.Input} input - A reference to the Input Manager. - */ + * @property {Phaser.Input} input - A reference to the Input Manager. + */ this.input = null; /** - * @property {Phaser.Loader} load - A reference to the Loader, which you mostly use in the preload method of your state to load external assets. - */ + * @property {Phaser.Loader} load - A reference to the Loader, which you mostly use in the preload method of your state to load external assets. + */ this.load = null; /** - * @property {Phaser.Math} math - A reference to Math class with lots of helpful functions. - */ + * @property {Phaser.Math} math - A reference to Math class with lots of helpful functions. + */ this.math = null; /** - * @property {Phaser.SoundManager} sound - A reference to the Sound Manager which can create, play and stop sounds, as well as adjust global volume. - */ + * @property {Phaser.SoundManager} sound - A reference to the Sound Manager which can create, play and stop sounds, as well as adjust global volume. + */ this.sound = null; /** - * @property {Phaser.ScaleManager} scale - A reference to the Scale Manager which controls the way the game scales on different displays. - */ + * @property {Phaser.ScaleManager} scale - A reference to the Scale Manager which controls the way the game scales on different displays. + */ this.scale = null; /** - * @property {Phaser.Stage} stage - A reference to the Stage. - */ + * @property {Phaser.Stage} stage - A reference to the Stage. + */ this.stage = null; /** - * @property {Phaser.StateManager} state - A reference to the State Manager, which controls state changes. - */ + * @property {Phaser.StateManager} state - A reference to the State Manager, which controls state changes. + */ this.state = null; /** - * @property {Phaser.Time} time - A reference to the game clock and timed events system. - */ + * @property {Phaser.Time} time - A reference to the game clock and timed events system. + */ this.time = null; /** - * @property {Phaser.TweenManager} tweens - A reference to the tween manager. - */ + * @property {Phaser.TweenManager} tweens - A reference to the tween manager. + */ this.tweens = null; /** - * @property {Phaser.World} world - A reference to the game world. All objects live in the Game World and its size is not bound by the display resolution. - */ + * @property {Phaser.World} world - A reference to the game world. All objects live in the Game World and its size is not bound by the display resolution. + */ this.world = null; /** - * @property {Phaser.Particles} particles - The Particle Manager. It is called during the core gameloop and updates any Particle Emitters it has created. - */ + * @property {Phaser.Particles} particles - The Particle Manager. It is called during the core gameloop and updates any Particle Emitters it has created. + */ this.particles = null; /** - * @property {Phaser.Physics} physics - A reference to the physics manager which looks after the different physics systems available within Phaser. - */ + * @property {Phaser.Physics} physics - A reference to the physics manager which looks after the different physics systems available within Phaser. + */ this.physics = null; /** - * @property {Phaser.RandomDataGenerator} rnd - A reference to the seeded and repeatable random data generator. - */ + * @property {Phaser.RandomDataGenerator} rnd - A reference to the seeded and repeatable random data generator. + */ this.rnd = null; - }; Phaser.State.prototype = { /** - * init is the very first function called when your State starts up. It's called before preload, create or anything else. - * If you need to route the game away to another State you could do so here, or if you need to prepare a set of variables - * or objects before the preloading starts. - * - * @method Phaser.State#init - * @param {...any} args - Any extra arguments passed to {@link Phaser.StateManager#start} or {@link Phaser.StateManager#restart}. - */ + * init is the very first function called when your State starts up. It's called before preload, create or anything else. + * If you need to route the game away to another State you could do so here, or if you need to prepare a set of variables + * or objects before the preloading starts. + * + * @method Phaser.State#init + * @param {...any} args - Any extra arguments passed to {@link Phaser.StateManager#start} or {@link Phaser.StateManager#restart}. + */ init: function () { }, /** - * preload is called first. Normally you'd use this to load your game assets (or those needed for the current State) - * You shouldn't create any objects in this method that require assets that you're also loading in this method, as - * they won't yet be available. - * - * @method Phaser.State#preload - * @param {Phaser.Game} game - */ + * preload is called first. Normally you'd use this to load your game assets (or those needed for the current State) + * You shouldn't create any objects in this method that require assets that you're also loading in this method, as + * they won't yet be available. + * + * @method Phaser.State#preload + * @param {Phaser.Game} game + */ preload: function () { }, /** - * loadUpdate is called during the Loader process. This only happens if you've set one or more assets to load in the preload method. - * - * @method Phaser.State#loadUpdate - * @param {Phaser.Game} game - */ + * loadUpdate is called during the Loader process. This only happens if you've set one or more assets to load in the preload method. + * + * @method Phaser.State#loadUpdate + * @param {Phaser.Game} game + */ loadUpdate: function () { }, /** - * loadRender is called during the Loader process. This only happens if you've set one or more assets to load in the preload method. - * The difference between loadRender and render is that any objects you render in this method you must be sure their assets exist. - * - * @method Phaser.State#loadRender - * @param {Phaser.Game} game - */ + * loadRender is called during the Loader process. This only happens if you've set one or more assets to load in the preload method. + * The difference between loadRender and render is that any objects you render in this method you must be sure their assets exist. + * + * @method Phaser.State#loadRender + * @param {Phaser.Game} game + */ loadRender: function () { }, /** - * create is called once preload has completed, this includes the loading of any assets from the Loader. - * If you don't have a preload method then create is the first method called in your State. - * - * @method Phaser.State#create - * @param {Phaser.Game} game - */ + * create is called once preload has completed, this includes the loading of any assets from the Loader. + * If you don't have a preload method then create is the first method called in your State. + * + * @method Phaser.State#create + * @param {Phaser.Game} game + */ create: function () { }, /** - * The update method is left empty for your own use. - * It is called during the core game loop AFTER debug, physics, plugins and the Stage have had their preUpdate methods called. - * It is called BEFORE Stage, Tweens, Sounds, Input, Physics, Particles and Plugins have had their postUpdate methods called. - * - * @method Phaser.State#update - * @param {Phaser.Game} game - */ + * The update method is left empty for your own use. + * It is called during the core game loop AFTER debug, physics, plugins and the Stage have had their preUpdate methods called. + * It is called BEFORE Stage, Tweens, Sounds, Input, Physics, Particles and Plugins have had their postUpdate methods called. + * + * @method Phaser.State#update + * @param {Phaser.Game} game + */ update: function () { }, /** - * The postUpdate method is left empty for your own use. - * It is called during the core game loop AFTER the Stage has had its postUpdate method called (including updateTransform). - * It is called BEFORE Plugins have had their postUpdate methods called. - * You don't need to call updateTransform yourself here unless Plugins need it. - * - * @method Phaser.State#postUpdate - * @param {Phaser.Game} game - */ + * The postUpdate method is left empty for your own use. + * It is called during the core game loop AFTER the Stage has had its postUpdate method called (including updateTransform). + * It is called BEFORE Plugins have had their postUpdate methods called. + * You don't need to call updateTransform yourself here unless Plugins need it. + * + * @method Phaser.State#postUpdate + * @param {Phaser.Game} game + */ postUpdate: function () { }, /** - * The preRender method is called after all Game Objects have been updated, but before any rendering takes place. - * - * @method Phaser.State#preRender - * @param {Phaser.Game} game - * @param {number} elapsedTime - */ + * The preRender method is called after all Game Objects have been updated, but before any rendering takes place. + * + * @method Phaser.State#preRender + * @param {Phaser.Game} game + * @param {number} elapsedTime + */ preRender: function () { }, /** - * Nearly all display objects in Phaser render automatically, you don't need to tell them to render. - * However the render method is called AFTER the game renderer and plugins have rendered, so you're able to do any - * final post-processing style effects here. Note that this happens before plugins postRender takes place. - * - * @method Phaser.State#render - * @param {Phaser.Game} game - */ + * Nearly all display objects in Phaser render automatically, you don't need to tell them to render. + * However the render method is called AFTER the game renderer and plugins have rendered, so you're able to do any + * final post-processing style effects here. Note that this happens before plugins postRender takes place. + * + * @method Phaser.State#render + * @param {Phaser.Game} game + */ render: function () { }, /** - * If your game is set to Scalemode RESIZE then each time the browser resizes it will call this function, passing in the new width and height. - * - * @method Phaser.State#resize - * @param {number} width - * @param {number} height - */ + * If your game is set to Scalemode RESIZE then each time the browser resizes it will call this function, passing in the new width and height. + * + * @method Phaser.State#resize + * @param {number} width + * @param {number} height + */ resize: function () { }, /** - * This method will be called if the core game loop is paused. - * - * @method Phaser.State#paused - * @param {Phaser.Game} game - */ + * This method will be called if the core game loop is paused. + * + * @method Phaser.State#paused + * @param {Phaser.Game} game + */ paused: function () { }, /** - * This method will be called when the core game loop resumes from a paused state. - * - * @method Phaser.State#resumed - * @param {Phaser.Game} game - */ + * This method will be called when the core game loop resumes from a paused state. + * + * @method Phaser.State#resumed + * @param {Phaser.Game} game + */ resumed: function () { }, /** - * pauseUpdate is called while the game is paused instead of preUpdate, update and postUpdate. - * - * @method Phaser.State#pauseUpdate - * @param {Phaser.Game} game - */ + * pauseUpdate is called while the game is paused instead of preUpdate, update and postUpdate. + * + * @method Phaser.State#pauseUpdate + * @param {Phaser.Game} game + */ pauseUpdate: function () { }, /** - * This method will be called when the State is shutdown (i.e. you switch to another state from this one). - * - * @method Phaser.State#shutdown - * @param {Phaser.Game} game - */ + * This method will be called when the State is shutdown (i.e. you switch to another state from this one). + * + * @method Phaser.State#shutdown + * @param {Phaser.Game} game + */ shutdown: function () { } diff --git a/src/core/StateManager.js b/src/core/StateManager.js index 93816a6c9..33c39ea4d 100644 --- a/src/core/StateManager.js +++ b/src/core/StateManager.js @@ -1,36 +1,35 @@ /* jshint newcap: false */ /** -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* The State Manager is responsible for loading, setting up and switching game states. -* -* @class Phaser.StateManager -* @constructor -* @param {Phaser.Game} game - A reference to the currently running game. -* @param {Phaser.State|Object} [pendingState=null] - A State object to seed the manager with. -*/ + * The State Manager is responsible for loading, setting up and switching game states. + * + * @class Phaser.StateManager + * @constructor + * @param {Phaser.Game} game - A reference to the currently running game. + * @param {Phaser.State|Object} [pendingState=null] - A State object to seed the manager with. + */ Phaser.StateManager = function (game, pendingState) { - /** - * @property {Phaser.Game} game - A reference to the currently running game. - */ + * @property {Phaser.Game} game - A reference to the currently running game. + */ this.game = game; /** - * @property {object} states - The object containing Phaser.States. - */ + * @property {object} states - The object containing Phaser.States. + */ this.states = {}; /** - * @property {Phaser.State} _pendingState - The state to be switched to in the next frame. - * @private - */ + * @property {Phaser.State} _pendingState - The state to be switched to in the next frame. + * @private + */ this._pendingState = null; if (typeof pendingState !== 'undefined' && pendingState !== null) @@ -39,139 +38,137 @@ Phaser.StateManager = function (game, pendingState) } /** - * @property {boolean} _clearWorld - Clear the world when we switch state? - * @private - */ + * @property {boolean} _clearWorld - Clear the world when we switch state? + * @private + */ this._clearWorld = false; /** - * @property {boolean} _clearCache - Clear the cache when we switch state? - * @private - */ + * @property {boolean} _clearCache - Clear the cache when we switch state? + * @private + */ this._clearCache = false; /** - * @property {boolean} _created - Flag that sets if the State has been created or not. - * @private - */ + * @property {boolean} _created - Flag that sets if the State has been created or not. + * @private + */ this._created = false; /** - * @property {any[]} _args - Temporary container when you pass vars from one State to another. - * @private - */ + * @property {any[]} _args - Temporary container when you pass vars from one State to another. + * @private + */ this._args = []; /** - * @property {string} current - The current active State object. - * @default - */ + * @property {string} current - The current active State object. + * @default + */ this.current = ''; /** - * onStateChange is a Phaser.Signal that is dispatched whenever the game changes state. - * - * It is dispatched only when the new state is started, which isn't usually at the same time as StateManager.start - * is called because state swapping is done in sync with the game loop. It is dispatched *before* any of the new states - * methods (such as preload and create) are called, and *after* the previous states shutdown method has been run. - * - * The callback you specify is sent two parameters: the string based key of the new state, - * and the second parameter is the string based key of the old / previous state. - * - * @property {Phaser.Signal} onStateChange - */ + * onStateChange is a Phaser.Signal that is dispatched whenever the game changes state. + * + * It is dispatched only when the new state is started, which isn't usually at the same time as StateManager.start + * is called because state swapping is done in sync with the game loop. It is dispatched *before* any of the new states + * methods (such as preload and create) are called, and *after* the previous states shutdown method has been run. + * + * The callback you specify is sent two parameters: the string based key of the new state, + * and the second parameter is the string based key of the old / previous state. + * + * @property {Phaser.Signal} onStateChange + */ this.onStateChange = new Phaser.Signal(); /** - * @property {function} onInitCallback - This is called when the state is set as the active state. - * @default - */ + * @property {function} onInitCallback - This is called when the state is set as the active state. + * @default + */ this.onInitCallback = null; /** - * @property {function} onPreloadCallback - This is called when the state starts to load assets. - * @default - */ + * @property {function} onPreloadCallback - This is called when the state starts to load assets. + * @default + */ this.onPreloadCallback = null; /** - * @property {function} onCreateCallback - This is called when the state preload has finished and creation begins. - * @default - */ + * @property {function} onCreateCallback - This is called when the state preload has finished and creation begins. + * @default + */ this.onCreateCallback = null; /** - * @property {function} onUpdateCallback - This is called when the state is updated, every game loop. It doesn't happen during preload (@see onLoadUpdateCallback). - * @default - */ + * @property {function} onUpdateCallback - This is called when the state is updated, every game loop. It doesn't happen during preload (@see onLoadUpdateCallback). + * @default + */ this.onUpdateCallback = null; /** - * @property {function} onRenderCallback - This is called post-render. It doesn't happen during preload (see onLoadRenderCallback). - * @default - */ + * @property {function} onRenderCallback - This is called post-render. It doesn't happen during preload (see onLoadRenderCallback). + * @default + */ this.onRenderCallback = null; /** - * @property {function} onResizeCallback - This is called if ScaleManager.scalemode is RESIZE and a resize event occurs. It's passed the new width and height. - * @default - */ + * @property {function} onResizeCallback - This is called if ScaleManager.scalemode is RESIZE and a resize event occurs. It's passed the new width and height. + * @default + */ this.onResizeCallback = null; /** - * @property {function} onPreRenderCallback - This is called before the state is rendered and before the stage is cleared but after all game objects have had their final properties adjusted. - * @default - */ + * @property {function} onPreRenderCallback - This is called before the state is rendered and before the stage is cleared but after all game objects have had their final properties adjusted. + * @default + */ this.onPreRenderCallback = null; /** - * @property {function} onLoadUpdateCallback - This is called when the State is updated during the preload phase. - * @default - */ + * @property {function} onLoadUpdateCallback - This is called when the State is updated during the preload phase. + * @default + */ this.onLoadUpdateCallback = null; /** - * @property {function} onLoadRenderCallback - This is called when the State is rendered during the preload phase. - * @default - */ + * @property {function} onLoadRenderCallback - This is called when the State is rendered during the preload phase. + * @default + */ this.onLoadRenderCallback = null; /** - * @property {function} onPausedCallback - This is called when the game is paused. - * @default - */ + * @property {function} onPausedCallback - This is called when the game is paused. + * @default + */ this.onPausedCallback = null; /** - * @property {function} onResumedCallback - This is called when the game is resumed from a paused state. - * @default - */ + * @property {function} onResumedCallback - This is called when the game is resumed from a paused state. + * @default + */ this.onResumedCallback = null; /** - * @property {function} onPauseUpdateCallback - This is called every frame while the game is paused. - * @default - */ + * @property {function} onPauseUpdateCallback - This is called every frame while the game is paused. + * @default + */ this.onPauseUpdateCallback = null; /** - * @property {function} onShutDownCallback - This is called when the state is shut down (i.e. swapped to another state). - * @default - */ + * @property {function} onShutDownCallback - This is called when the state is shut down (i.e. swapped to another state). + * @default + */ this.onShutDownCallback = null; - }; Phaser.StateManager.prototype = { /** - * The Boot handler is called by Phaser.Game when it first starts up. - * @method Phaser.StateManager#boot - * @private - */ + * The Boot handler is called by Phaser.Game when it first starts up. + * @method Phaser.StateManager#boot + * @private + */ boot: function () { - this.game.onPause.add(this.pause, this); this.game.onResume.add(this.resume, this); @@ -179,29 +176,27 @@ Phaser.StateManager.prototype = { { this.add('default', this._pendingState, true); } - }, /** - * Adds a new State into the StateManager. You must give each State a unique key by which you'll identify it. - * - * The State can be any of - * - * - a plain JavaScript object containing at least one required callback (see {@link #checkState}) - * - an instance of {@link Phaser.State} - * - an instance of a class extending Phaser.State - * - a constructor function (class) - * - * If a function is given a new state object will be created by calling it, passing the current {@link Phaser.Game game} as the first argument. - * - * @method Phaser.StateManager#add - * @param {string} key - A unique key you use to reference this state, i.e. "MainMenu", "Level1". - * @param {Phaser.State|object|function} state - The state you want to switch to. - * @param {boolean} [autoStart=false] - If true the State will be started immediately after adding it. - */ + * Adds a new State into the StateManager. You must give each State a unique key by which you'll identify it. + * + * The State can be any of + * + * - a plain JavaScript object containing at least one required callback (see {@link #checkState}) + * - an instance of {@link Phaser.State} + * - an instance of a class extending Phaser.State + * - a constructor function (class) + * + * If a function is given a new state object will be created by calling it, passing the current {@link Phaser.Game game} as the first argument. + * + * @method Phaser.StateManager#add + * @param {string} key - A unique key you use to reference this state, i.e. "MainMenu", "Level1". + * @param {Phaser.State|object|function} state - The state you want to switch to. + * @param {boolean} [autoStart=false] - If true the State will be started immediately after adding it. + */ add: function (key, state, autoStart) { - if (autoStart === undefined) { autoStart = false; } var newState; @@ -235,17 +230,15 @@ Phaser.StateManager.prototype = { } return newState; - }, /** - * Delete the given state. - * @method Phaser.StateManager#remove - * @param {string} key - A unique key you use to reference this state, i.e. "MainMenu", "Level1". - */ + * Delete the given state. + * @method Phaser.StateManager#remove + * @param {string} key - A unique key you use to reference this state, i.e. "MainMenu", "Level1". + */ remove: function (key) { - if (this.current === key) { this.callbackContext = null; @@ -267,21 +260,19 @@ Phaser.StateManager.prototype = { } delete this.states[key]; - }, /** - * Start the given State. If a State is already running then State.shutDown will be called (if it exists) before switching to the new State. - * - * @method Phaser.StateManager#start - * @param {string} key - The key of the state you want to start. - * @param {boolean} [clearWorld=true] - Clear everything in the world? This clears the World display list fully (but not the Stage, so if you've added your own objects to the Stage they will need managing directly) - * @param {boolean} [clearCache=false] - Clear the Game.Cache? This purges out all loaded assets. The default is false and you must have clearWorld=true if you want to clearCache as well. - * @param {...*} parameter - Additional parameters that will be passed to the State.init function (if it has one). - */ + * Start the given State. If a State is already running then State.shutDown will be called (if it exists) before switching to the new State. + * + * @method Phaser.StateManager#start + * @param {string} key - The key of the state you want to start. + * @param {boolean} [clearWorld=true] - Clear everything in the world? This clears the World display list fully (but not the Stage, so if you've added your own objects to the Stage they will need managing directly) + * @param {boolean} [clearCache=false] - Clear the Game.Cache? This purges out all loaded assets. The default is false and you must have clearWorld=true if you want to clearCache as well. + * @param {...*} parameter - Additional parameters that will be passed to the State.init function (if it has one). + */ start: function (key, clearWorld, clearCache) { - if (clearWorld === undefined) { clearWorld = true; } if (clearCache === undefined) { clearCache = false; } @@ -297,20 +288,18 @@ Phaser.StateManager.prototype = { this._args = Array.prototype.splice.call(arguments, 3); } } - }, /** - * Restarts the current State. State.shutDown will be called (if it exists) before the State is restarted. - * - * @method Phaser.StateManager#restart - * @param {boolean} [clearWorld=true] - Clear everything in the world? This clears the World display list fully (but not the Stage, so if you've added your own objects to the Stage they will need managing directly) - * @param {boolean} [clearCache=false] - Clear the Game.Cache? This purges out all loaded assets. The default is false and you must have clearWorld=true if you want to clearCache as well. - * @param {...*} parameter - Additional parameters that will be passed to the State.init function if it has one. - */ + * Restarts the current State. State.shutDown will be called (if it exists) before the State is restarted. + * + * @method Phaser.StateManager#restart + * @param {boolean} [clearWorld=true] - Clear everything in the world? This clears the World display list fully (but not the Stage, so if you've added your own objects to the Stage they will need managing directly) + * @param {boolean} [clearCache=false] - Clear the Game.Cache? This purges out all loaded assets. The default is false and you must have clearWorld=true if you want to clearCache as well. + * @param {...*} parameter - Additional parameters that will be passed to the State.init function if it has one. + */ restart: function (clearWorld, clearCache) { - if (clearWorld === undefined) { clearWorld = true; } if (clearCache === undefined) { clearCache = false; } @@ -323,26 +312,24 @@ Phaser.StateManager.prototype = { { this._args = Array.prototype.slice.call(arguments, 2); } - }, /** - * Used by onInit and onShutdown when those functions don't exist on the state - * @method Phaser.StateManager#dummy - * @private - */ + * Used by onInit and onShutdown when those functions don't exist on the state + * @method Phaser.StateManager#dummy + * @private + */ dummy: function () { }, /** - * preUpdate is called right at the start of the game loop. It is responsible for changing to a new state that was requested previously. - * - * @method Phaser.StateManager#preUpdate - */ + * preUpdate is called right at the start of the game loop. It is responsible for changing to a new state that was requested previously. + * + * @method Phaser.StateManager#preUpdate + */ preUpdate: function () { - if (this._pendingState && this.game.isBooted) { var previousStateKey = this.current; @@ -363,8 +350,10 @@ Phaser.StateManager.prototype = { this._pendingState = null; } - // If StateManager.start has been called from the init of a State that ALSO has a preload, then - // onPreloadCallback will be set, but must be ignored + /* + * If StateManager.start has been called from the init of a State that ALSO has a preload, then + * onPreloadCallback will be set, but must be ignored + */ if (this.onPreloadCallback) { this.game.load.reset(true); @@ -387,18 +376,16 @@ Phaser.StateManager.prototype = { this.loadComplete(); } } - }, /** - * This method clears the current State, calling its shutdown callback. The process also removes any active tweens, - * resets the camera, resets input, clears physics, removes timers and if set clears the world and cache too. - * - * @method Phaser.StateManager#clearCurrentState - */ + * This method clears the current State, calling its shutdown callback. The process also removes any active tweens, + * resets the camera, resets input, clears physics, removes timers and if set clears the world and cache too. + * + * @method Phaser.StateManager#clearCurrentState + */ clearCurrentState: function () { - if (this.current) { if (this.onShutDownCallback) @@ -433,19 +420,17 @@ Phaser.StateManager.prototype = { } } } - }, /** - * Checks if a given phaser state is valid. A State is considered valid if it has at least one of the core functions: preload, create, update or render. - * - * @method Phaser.StateManager#checkState - * @param {string} key - The key of the state you want to check. - * @return {boolean} true if the State has the required functions, otherwise false. - */ + * Checks if a given phaser state is valid. A State is considered valid if it has at least one of the core functions: preload, create, update or render. + * + * @method Phaser.StateManager#checkState + * @param {string} key - The key of the state you want to check. + * @return {boolean} true if the State has the required functions, otherwise false. + */ checkState: function (key) { - var state = this.states[key]; if (state) @@ -465,19 +450,17 @@ Phaser.StateManager.prototype = { console.warn('Phaser.StateManager - No state found with the key: ' + key); return false; } - }, /** - * Links game properties to the State given by the key. - * - * @method Phaser.StateManager#link - * @param {string} key - State key. - * @protected - */ + * Links game properties to the State given by the key. + * + * @method Phaser.StateManager#link + * @param {string} key - State key. + * @protected + */ link: function (key) { - var state = this.states[key]; state.game = this.game; @@ -499,19 +482,17 @@ Phaser.StateManager.prototype = { state.rnd = this.game.rnd; state.physics = this.game.physics; state.key = key; - }, /** - * Nulls all State level Phaser properties, including a reference to Game. - * - * @method Phaser.StateManager#unlink - * @param {string} key - State key. - * @protected - */ + * Nulls all State level Phaser properties, including a reference to Game. + * + * @method Phaser.StateManager#unlink + * @param {string} key - State key. + * @protected + */ unlink: function (key) { - var state = this.states[key]; if (state) @@ -535,19 +516,17 @@ Phaser.StateManager.prototype = { state.rnd = null; state.physics = null; } - }, /** - * Sets the current State. Should not be called directly (use StateManager.start) - * - * @method Phaser.StateManager#setCurrentState - * @param {string} key - State key. - * @private - */ + * Sets the current State. Should not be called directly (use StateManager.start) + * + * @method Phaser.StateManager#setCurrentState + * @param {string} key - State key. + * @private + */ setCurrentState: function (key) { - var state = this.states[key]; this.callbackContext = state; @@ -592,7 +571,6 @@ Phaser.StateManager.prototype = { } this.game._kickstart = true; - }, /** @@ -608,13 +586,12 @@ Phaser.StateManager.prototype = { }, /** - * @method Phaser.StateManager#loadComplete - * @protected - * @see Phaser.StateManager#preUpdate - */ + * @method Phaser.StateManager#loadComplete + * @protected + * @see Phaser.StateManager#preUpdate + */ loadComplete: function () { - if (this._created === false && this.onCreateCallback) { this._created = true; @@ -624,59 +601,51 @@ Phaser.StateManager.prototype = { { this._created = true; } - }, /** - * @method Phaser.StateManager#loadUpdate - * @protected - * @see Phaser.Loader#finishedLoading - */ + * @method Phaser.StateManager#loadUpdate + * @protected + * @see Phaser.Loader#finishedLoading + */ loadUpdate: function () { - if (this._created === false && this.onLoadUpdateCallback) { this.onLoadUpdateCallback.call(this.callbackContext, this.game); } - }, /** - * @method Phaser.StateManager#pause - * @protected - */ + * @method Phaser.StateManager#pause + * @protected + */ pause: function () { - if (this._created && this.onPausedCallback) { this.onPausedCallback.call(this.callbackContext, this.game); } - }, /** - * @method Phaser.StateManager#resume - * @protected - */ + * @method Phaser.StateManager#resume + * @protected + */ resume: function () { - if (this._created && this.onResumedCallback) { this.onResumedCallback.call(this.callbackContext, this.game); } - }, /** - * @method Phaser.StateManager#update - * @protected - */ + * @method Phaser.StateManager#update + * @protected + */ update: function () { - if (this._created) { if (this.onUpdateCallback) @@ -689,26 +658,22 @@ Phaser.StateManager.prototype = { { this.onLoadUpdateCallback.call(this.callbackContext, this.game); } - }, postUpdate: function () { - if (this._created && this.onPostUpdateCallback) { this.onPostUpdateCallback.call(this.callbackContext, this.game); } - }, /** - * @method Phaser.StateManager#pauseUpdate - * @protected - */ + * @method Phaser.StateManager#pauseUpdate + * @protected + */ pauseUpdate: function () { - if (this._created) { if (this.onPauseUpdateCallback) @@ -721,45 +686,39 @@ Phaser.StateManager.prototype = { { this.onLoadUpdateCallback.call(this.callbackContext, this.game); } - }, /** - * @method Phaser.StateManager#preRender - * @protected - * @param {number} elapsedTime - The time elapsed since the last update. - */ + * @method Phaser.StateManager#preRender + * @protected + * @param {number} elapsedTime - The time elapsed since the last update. + */ preRender: function (elapsedTime) { - if (this._created && this.onPreRenderCallback) { this.onPreRenderCallback.call(this.callbackContext, this.game, elapsedTime); } - }, /** - * @method Phaser.StateManager#resize - * @protected - */ + * @method Phaser.StateManager#resize + * @protected + */ resize: function (width, height) { - if (this.onResizeCallback) { this.onResizeCallback.call(this.callbackContext, width, height); } - }, /** - * @method Phaser.StateManager#render - * @protected - */ + * @method Phaser.StateManager#render + * @protected + */ render: function () { - if (this._created) { if (this.onRenderCallback) @@ -782,17 +741,15 @@ Phaser.StateManager.prototype = { { this.onLoadRenderCallback.call(this.callbackContext, this.game); } - }, /** - * Removes all StateManager callback references to the State object, nulls the game reference and clears the States object. - * You don't recover from this without rebuilding the Phaser instance again. - * @method Phaser.StateManager#destroy - */ + * Removes all StateManager callback references to the State object, nulls the game reference and clears the States object. + * You don't recover from this without rebuilding the Phaser instance again. + * @method Phaser.StateManager#destroy + */ destroy: function () { - this._clearWorld = true; this._clearCache = true; @@ -818,7 +775,6 @@ Phaser.StateManager.prototype = { this.states = {}; this._pendingState = null; this.current = ''; - } }; @@ -826,21 +782,19 @@ Phaser.StateManager.prototype = { Phaser.StateManager.prototype.constructor = Phaser.StateManager; /** -* @name Phaser.StateManager#created -* @property {boolean} created - True if the current state has had its `create` method run (if it has one, if not this is true by default). -* @readOnly -*/ + * @name Phaser.StateManager#created + * @property {boolean} created - True if the current state has had its `create` method run (if it has one, if not this is true by default). + * @readOnly + */ Object.defineProperty(Phaser.StateManager.prototype, 'created', { get: function () { - return this._created; - } }); /** -* "It's like nailing jelly to a kitten" - Gary Penn -*/ + * "It's like nailing jelly to a kitten" - Gary Penn + */ diff --git a/src/core/World.js b/src/core/World.js index e952b4e68..21682674b 100644 --- a/src/core/World.js +++ b/src/core/World.js @@ -1,112 +1,105 @@ /** -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* "This world is but a canvas to our imagination." - Henry David Thoreau -* -* A game has only one world. The world is an abstract place in which all game objects live. It is not bound -* by stage limits and can be any size. You look into the world via cameras. All game objects live within -* the world at world-based coordinates. By default a world is created the same size as your Stage. -* -* @class Phaser.World -* @extends Phaser.Group -* @constructor -* @param {Phaser.Game} game - Reference to the current game instance. -*/ + * "This world is but a canvas to our imagination." - Henry David Thoreau + * + * A game has only one world. The world is an abstract place in which all game objects live. It is not bound + * by stage limits and can be any size. You look into the world via cameras. All game objects live within + * the world at world-based coordinates. By default a world is created the same size as your Stage. + * + * @class Phaser.World + * @extends Phaser.Group + * @constructor + * @param {Phaser.Game} game - Reference to the current game instance. + */ Phaser.World = function (game) { - Phaser.Group.call(this, game, null, '__world', false); /** - * The World has no fixed size, but it does have a bounds outside of which objects are no longer considered as being "in world" and you should use this to clean-up the display list and purge dead objects. - * By default we set the Bounds to be from 0,0 to Game.width,Game.height. I.e. it will match the size given to the game constructor with 0,0 representing the top-left of the display. - * However 0,0 is actually the center of the world, and if you rotate or scale the world all of that will happen from 0,0. - * So if you want to make a game in which the world itself will rotate you should adjust the bounds so that 0,0 is the center point, i.e. set them to -1000,-1000,2000,2000 for a 2000x2000 sized world centered around 0,0. - * @property {Phaser.Rectangle} bounds - Bound of this world that objects can not escape from. - */ + * The World has no fixed size, but it does have a bounds outside of which objects are no longer considered as being "in world" and you should use this to clean-up the display list and purge dead objects. + * By default we set the Bounds to be from 0,0 to Game.width,Game.height. I.e. it will match the size given to the game constructor with 0,0 representing the top-left of the display. + * However 0,0 is actually the center of the world, and if you rotate or scale the world all of that will happen from 0,0. + * So if you want to make a game in which the world itself will rotate you should adjust the bounds so that 0,0 is the center point, i.e. set them to -1000,-1000,2000,2000 for a 2000x2000 sized world centered around 0,0. + * @property {Phaser.Rectangle} bounds - Bound of this world that objects can not escape from. + */ this.bounds = new Phaser.Rectangle(0, 0, game.width, game.height); /** - * @property {Phaser.Camera} camera - Camera instance. - */ + * @property {Phaser.Camera} camera - Camera instance. + */ this.camera = null; /** - * @property {boolean} _definedSize - True if the World has been given a specifically defined size (i.e. from a Tilemap or direct in code) or false if it's just matched to the Game dimensions. - * @readonly - */ + * @property {boolean} _definedSize - True if the World has been given a specifically defined size (i.e. from a Tilemap or direct in code) or false if it's just matched to the Game dimensions. + * @readonly + */ this._definedSize = false; /** - * @property {number} width - The defined width of the World. Sometimes the bounds needs to grow larger than this (if you resize the game) but this retains the original requested dimension. - */ + * @property {number} width - The defined width of the World. Sometimes the bounds needs to grow larger than this (if you resize the game) but this retains the original requested dimension. + */ this._width = game.width; /** - * @property {number} height - The defined height of the World. Sometimes the bounds needs to grow larger than this (if you resize the game) but this retains the original requested dimension. - */ + * @property {number} height - The defined height of the World. Sometimes the bounds needs to grow larger than this (if you resize the game) but this retains the original requested dimension. + */ this._height = game.height; this.game.state.onStateChange.add(this.stateChange, this); - }; Phaser.World.prototype = Object.create(Phaser.Group.prototype); Phaser.World.prototype.constructor = Phaser.World; /** -* Initialises the game world. -* -* @method Phaser.World#boot -* @protected -*/ + * Initialises the game world. + * + * @method Phaser.World#boot + * @protected + */ Phaser.World.prototype.boot = function () { - this.camera = new Phaser.Camera(this.game, 0, 0, 0, this.game.width, this.game.height); this.game.stage.addChild(this); this.camera.boot(); - }; /** -* Called whenever the State changes or resets. -* -* It resets the world.x and world.y coordinates back to zero, -* then resets the Camera. -* -* @method Phaser.World#stateChange -* @protected -*/ + * Called whenever the State changes or resets. + * + * It resets the world.x and world.y coordinates back to zero, + * then resets the Camera. + * + * @method Phaser.World#stateChange + * @protected + */ Phaser.World.prototype.stateChange = function () { - this.x = 0; this.y = 0; this.camera.reset(); - }; /** -* Updates the size of this world and sets World.x/y to the given values -* The Camera bounds and Physics bounds (if set) are also updated to match the new World bounds. -* -* @method Phaser.World#setBounds -* @param {number} x - Top left most corner of the world. -* @param {number} y - Top left most corner of the world. -* @param {number} width - New width of the game world in pixels. -* @param {number} height - New height of the game world in pixels. -*/ + * Updates the size of this world and sets World.x/y to the given values + * The Camera bounds and Physics bounds (if set) are also updated to match the new World bounds. + * + * @method Phaser.World#setBounds + * @param {number} x - Top left most corner of the world. + * @param {number} y - Top left most corner of the world. + * @param {number} width - New width of the game world in pixels. + * @param {number} height - New height of the game world in pixels. + */ Phaser.World.prototype.setBounds = function (x, y, width, height) { - this._definedSize = true; this._width = width; this._height = height; @@ -123,22 +116,20 @@ Phaser.World.prototype.setBounds = function (x, y, width, height) } this.game.physics.setBoundsToWorld(); - }; /** -* Updates this world's width and height (but not smaller than any previous {@link #setBounds defined size}). -* -* Phaser uses this to adapt to {@link Phaser.ScaleManager#updateDimensions layout changes}. -* You probably want to use {@link #setBounds} instead. -* -* @method Phaser.World#resize -* @param {number} width - New width of the game world in pixels. -* @param {number} height - New height of the game world in pixels. -*/ + * Updates this world's width and height (but not smaller than any previous {@link #setBounds defined size}). + * + * Phaser uses this to adapt to {@link Phaser.ScaleManager#updateDimensions layout changes}. + * You probably want to use {@link #setBounds} instead. + * + * @method Phaser.World#resize + * @param {number} width - New width of the game world in pixels. + * @param {number} height - New height of the game world in pixels. + */ Phaser.World.prototype.resize = function (width, height) { - // Don't ever scale the World bounds lower than the original requested dimensions if it's a defined world size if (this._definedSize) @@ -160,40 +151,36 @@ Phaser.World.prototype.resize = function (width, height) this.game.camera.setBoundsToWorld(); this.game.physics.setBoundsToWorld(); - }; /** -* Destroyer of worlds. -* -* @method Phaser.World#shutdown -*/ + * Destroyer of worlds. + * + * @method Phaser.World#shutdown + */ Phaser.World.prototype.shutdown = function () { - // World is a Group, so run a soft destruction on this and all children. this.destroy(true, true); - }; /** -* This will take the given game object and check if its x/y coordinates fall outside of the world bounds. -* If they do it will reposition the object to the opposite side of the world, creating a wrap-around effect. -* If sprite has a P2 body then the body (sprite.body) should be passed as first parameter to the function. -* -* Please understand there are limitations to this method. For example if you have scaled the World -* then objects won't always be re-positioned correctly, and you'll need to employ your own wrapping function. -* -* @method Phaser.World#wrap -* @param {Phaser.Sprite|Phaser.Image|Phaser.TileSprite|Phaser.Text} sprite - The object you wish to wrap around the world bounds. -* @param {number} [padding=0] - Extra padding added equally to the sprite.x and y coordinates before checking if within the world bounds. Ignored if useBounds is true. -* @param {boolean} [useBounds=false] - If useBounds is false wrap checks the object.x/y coordinates. If true it does a more accurate bounds check, which is more expensive. -* @param {boolean} [horizontal=true] - If horizontal is false, wrap will not wrap the object.x coordinates horizontally. -* @param {boolean} [vertical=true] - If vertical is false, wrap will not wrap the object.y coordinates vertically. -*/ + * This will take the given game object and check if its x/y coordinates fall outside of the world bounds. + * If they do it will reposition the object to the opposite side of the world, creating a wrap-around effect. + * If sprite has a P2 body then the body (sprite.body) should be passed as first parameter to the function. + * + * Please understand there are limitations to this method. For example if you have scaled the World + * then objects won't always be re-positioned correctly, and you'll need to employ your own wrapping function. + * + * @method Phaser.World#wrap + * @param {Phaser.Sprite|Phaser.Image|Phaser.TileSprite|Phaser.Text} sprite - The object you wish to wrap around the world bounds. + * @param {number} [padding=0] - Extra padding added equally to the sprite.x and y coordinates before checking if within the world bounds. Ignored if useBounds is true. + * @param {boolean} [useBounds=false] - If useBounds is false wrap checks the object.x/y coordinates. If true it does a more accurate bounds check, which is more expensive. + * @param {boolean} [horizontal=true] - If horizontal is false, wrap will not wrap the object.x coordinates horizontally. + * @param {boolean} [vertical=true] - If vertical is false, wrap will not wrap the object.y coordinates vertically. + */ Phaser.World.prototype.wrap = function (sprite, padding, useBounds, horizontal, vertical) { - if (padding === undefined) { padding = 0; } if (useBounds === undefined) { useBounds = false; } if (horizontal === undefined) { horizontal = true; } @@ -247,29 +234,26 @@ Phaser.World.prototype.wrap = function (sprite, padding, useBounds, horizontal, } } } - }; /** -* @method Phaser.World#wrapAll -* @param {Phaser.Group} group - A group of sprites. -* @param {boolean} [checkExists=false] - Wrap only sprites having `exists=true`. -* @param {number} [padding=0] - Extra padding added equally to the sprite.x and y coordinates before checking if within the world bounds. Ignored if useBounds is true. -* @param {boolean} [useBounds=false] - If useBounds is false wrap checks the object.x/y coordinates. If true it does a more accurate bounds check, which is more expensive. -* @param {boolean} [horizontal=true] - If horizontal is false, wrap will not wrap the object.x coordinates horizontally. -* @param {boolean} [vertical=true] - If vertical is false, wrap will not wrap the object.y coordinates vertically. -*/ + * @method Phaser.World#wrapAll + * @param {Phaser.Group} group - A group of sprites. + * @param {boolean} [checkExists=false] - Wrap only sprites having `exists=true`. + * @param {number} [padding=0] - Extra padding added equally to the sprite.x and y coordinates before checking if within the world bounds. Ignored if useBounds is true. + * @param {boolean} [useBounds=false] - If useBounds is false wrap checks the object.x/y coordinates. If true it does a more accurate bounds check, which is more expensive. + * @param {boolean} [horizontal=true] - If horizontal is false, wrap will not wrap the object.x coordinates horizontally. + * @param {boolean} [vertical=true] - If vertical is false, wrap will not wrap the object.y coordinates vertically. + */ Phaser.World.prototype.wrapAll = function (group, checkExists, padding, useBounds, horizontal, vertical) { - group.forEach(this.wrap, this, checkExists, padding, useBounds, horizontal, vertical); - }; /** -* @name Phaser.World#width -* @property {number} width - Gets or sets the current width of the game world. The world can never be smaller than the game (canvas) dimensions. -*/ + * @name Phaser.World#width + * @property {number} width - Gets or sets the current width of the game world. The world can never be smaller than the game (canvas) dimensions. + */ Object.defineProperty(Phaser.World.prototype, 'width', { get: function () @@ -279,7 +263,6 @@ Object.defineProperty(Phaser.World.prototype, 'width', { set: function (value) { - if (value < this.game.width) { value = this.game.width; @@ -288,15 +271,14 @@ Object.defineProperty(Phaser.World.prototype, 'width', { this.bounds.width = value; this._width = value; this._definedSize = true; - } }); /** -* @name Phaser.World#height -* @property {number} height - Gets or sets the current height of the game world. The world can never be smaller than the game (canvas) dimensions. -*/ + * @name Phaser.World#height + * @property {number} height - Gets or sets the current height of the game world. The world can never be smaller than the game (canvas) dimensions. + */ Object.defineProperty(Phaser.World.prototype, 'height', { get: function () @@ -306,7 +288,6 @@ Object.defineProperty(Phaser.World.prototype, 'height', { set: function (value) { - if (value < this.game.height) { value = this.game.height; @@ -315,16 +296,15 @@ Object.defineProperty(Phaser.World.prototype, 'height', { this.bounds.height = value; this._height = value; this._definedSize = true; - } }); /** -* @name Phaser.World#centerX -* @property {number} centerX - Gets the X position corresponding to the center point of the world. -* @readonly -*/ + * @name Phaser.World#centerX + * @property {number} centerX - Gets the X position corresponding to the center point of the world. + * @readonly + */ Object.defineProperty(Phaser.World.prototype, 'centerX', { get: function () @@ -335,10 +315,10 @@ Object.defineProperty(Phaser.World.prototype, 'centerX', { }); /** -* @name Phaser.World#centerY -* @property {number} centerY - Gets the Y position corresponding to the center point of the world. -* @readonly -*/ + * @name Phaser.World#centerY + * @property {number} centerY - Gets the Y position corresponding to the center point of the world. + * @readonly + */ Object.defineProperty(Phaser.World.prototype, 'centerY', { get: function () @@ -349,15 +329,14 @@ Object.defineProperty(Phaser.World.prototype, 'centerY', { }); /** -* @name Phaser.World#randomX -* @property {number} randomX - Gets a random integer which is lesser than or equal to the current width of the game world. -* @readonly -*/ + * @name Phaser.World#randomX + * @property {number} randomX - Gets a random integer which is lesser than or equal to the current width of the game world. + * @readonly + */ Object.defineProperty(Phaser.World.prototype, 'randomX', { get: function () { - if (this.bounds.x < 0) { return this.game.rnd.between(this.bounds.x, (this.bounds.width - Math.abs(this.bounds.x))); @@ -366,21 +345,19 @@ Object.defineProperty(Phaser.World.prototype, 'randomX', { { return this.game.rnd.between(this.bounds.x, this.bounds.width); } - } }); /** -* @name Phaser.World#randomY -* @property {number} randomY - Gets a random integer which is lesser than or equal to the current height of the game world. -* @readonly -*/ + * @name Phaser.World#randomY + * @property {number} randomY - Gets a random integer which is lesser than or equal to the current height of the game world. + * @readonly + */ Object.defineProperty(Phaser.World.prototype, 'randomY', { get: function () { - if (this.bounds.y < 0) { return this.game.rnd.between(this.bounds.y, (this.bounds.height - Math.abs(this.bounds.y))); @@ -389,7 +366,6 @@ Object.defineProperty(Phaser.World.prototype, 'randomY', { { return this.game.rnd.between(this.bounds.y, this.bounds.height); } - } }); diff --git a/src/gameobjects/BitmapData.js b/src/gameobjects/BitmapData.js index 8b7ccd10a..5880f417e 100644 --- a/src/gameobjects/BitmapData.js +++ b/src/gameobjects/BitmapData.js @@ -1,87 +1,86 @@ /** -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* A BitmapData object contains a Canvas element to which you can draw anything you like via normal Canvas context operations. -* A single BitmapData can be used as the texture for one or many Images / Sprites. -* So if you need to dynamically create a Sprite texture then they are a good choice. -* -* Important note: Every BitmapData creates its own Canvas element. Because BitmapData's are now Game Objects themselves, and don't -* live on the display list, they are NOT automatically cleared when you change State. Therefore you _must_ call BitmapData.destroy -* in your State's shutdown method if you wish to free-up the resources the BitmapData used, it will not happen for you. -* -* @class Phaser.BitmapData -* @constructor -* @param {Phaser.Game} game - A reference to the currently running game. -* @param {string} key - Internal Phaser reference key for the BitmapData. -* @param {number} [width=256] - The width of the BitmapData in pixels. If undefined or zero it's set to a default value. -* @param {number} [height=256] - The height of the BitmapData in pixels. If undefined or zero it's set to a default value. -* @param {boolean} [skipPool=false] - When this BitmapData generates its internal canvas to use for rendering, it will get the canvas from the CanvasPool if false, or create its own if true. -*/ + * A BitmapData object contains a Canvas element to which you can draw anything you like via normal Canvas context operations. + * A single BitmapData can be used as the texture for one or many Images / Sprites. + * So if you need to dynamically create a Sprite texture then they are a good choice. + * + * Important note: Every BitmapData creates its own Canvas element. Because BitmapData's are now Game Objects themselves, and don't + * live on the display list, they are NOT automatically cleared when you change State. Therefore you _must_ call BitmapData.destroy + * in your State's shutdown method if you wish to free-up the resources the BitmapData used, it will not happen for you. + * + * @class Phaser.BitmapData + * @constructor + * @param {Phaser.Game} game - A reference to the currently running game. + * @param {string} key - Internal Phaser reference key for the BitmapData. + * @param {number} [width=256] - The width of the BitmapData in pixels. If undefined or zero it's set to a default value. + * @param {number} [height=256] - The height of the BitmapData in pixels. If undefined or zero it's set to a default value. + * @param {boolean} [skipPool=false] - When this BitmapData generates its internal canvas to use for rendering, it will get the canvas from the CanvasPool if false, or create its own if true. + */ Phaser.BitmapData = function (game, key, width, height, skipPool) { - if (width === undefined || width === 0) { width = 256; } if (height === undefined || height === 0) { height = 256; } if (skipPool === undefined) { skipPool = false; } /** - * @property {Phaser.Game} game - A reference to the currently running game. - */ + * @property {Phaser.Game} game - A reference to the currently running game. + */ this.game = game; /** - * @property {string} key - The key of the BitmapData in the Cache, if stored there. - */ + * @property {string} key - The key of the BitmapData in the Cache, if stored there. + */ this.key = key; /** - * @property {number} width - The width of the BitmapData in pixels. - */ + * @property {number} width - The width of the BitmapData in pixels. + */ this.width = width; /** - * @property {number} height - The height of the BitmapData in pixels. - */ + * @property {number} height - The height of the BitmapData in pixels. + */ this.height = height; /** - * @property {HTMLCanvasElement} canvas - The canvas to which this BitmapData draws. - * @default - */ + * @property {HTMLCanvasElement} canvas - The canvas to which this BitmapData draws. + * @default + */ this.canvas = Phaser.Canvas.create(this, width, height, null, skipPool); /** - * @property {CanvasRenderingContext2D} context - The 2d context of the canvas. - * @default - */ + * @property {CanvasRenderingContext2D} context - The 2d context of the canvas. + * @default + */ this.context = this.canvas.getContext('2d', { alpha: true }); /** - * @property {CanvasRenderingContext2D} ctx - A reference to BitmapData.context. - */ + * @property {CanvasRenderingContext2D} ctx - A reference to BitmapData.context. + */ this.ctx = this.context; /** - * @property {string} smoothProperty - The context property needed for smoothing this Canvas. - */ + * @property {string} smoothProperty - The context property needed for smoothing this Canvas. + */ this.smoothProperty = (game.renderType === Phaser.CANVAS) ? game.renderer.renderSession.smoothProperty : Phaser.Canvas.getSmoothingPrefix(this.context); /** - * @property {ImageData} imageData - The context image data. - * Please note that a call to BitmapData.draw() or BitmapData.copy() does not update immediately this property for performance reason. Use BitmapData.update() to do so. - * This property is updated automatically after the first game loop, according to the dirty flag property. - */ + * @property {ImageData} imageData - The context image data. + * Please note that a call to BitmapData.draw() or BitmapData.copy() does not update immediately this property for performance reason. Use BitmapData.update() to do so. + * This property is updated automatically after the first game loop, according to the dirty flag property. + */ this.imageData = this.context.getImageData(0, 0, width, height); /** - * A Uint8ClampedArray view into BitmapData.buffer. - * Note that this is unavailable in some browsers (such as Epic Browser due to its security restrictions) - * @property {Uint8ClampedArray} data - */ + * A Uint8ClampedArray view into BitmapData.buffer. + * Note that this is unavailable in some browsers (such as Epic Browser due to its security restrictions) + * @property {Uint8ClampedArray} data + */ this.data = null; if (this.imageData) @@ -90,13 +89,13 @@ Phaser.BitmapData = function (game, key, width, height, skipPool) } /** - * @property {Uint32Array} pixels - An Uint32Array view into BitmapData.buffer. - */ + * @property {Uint32Array} pixels - An Uint32Array view into BitmapData.buffer. + */ this.pixels = null; /** - * @property {ArrayBuffer} buffer - An ArrayBuffer the same size as the context ImageData. - */ + * @property {ArrayBuffer} buffer - An ArrayBuffer the same size as the context ImageData. + */ if (this.data) { if (this.imageData.data.buffer) @@ -117,139 +116,137 @@ Phaser.BitmapData = function (game, key, width, height, skipPool) } /** - * @property {PIXI.BaseTexture} baseTexture - The PIXI.BaseTexture. - * @default - */ + * @property {PIXI.BaseTexture} baseTexture - The PIXI.BaseTexture. + * @default + */ this.baseTexture = new PIXI.BaseTexture(this.canvas, null, this.game.resolution); /** - * @property {PIXI.Texture} texture - The PIXI.Texture. - * @default - */ + * @property {PIXI.Texture} texture - The PIXI.Texture. + * @default + */ this.texture = new PIXI.Texture(this.baseTexture); /** - * @property {Phaser.FrameData} frameData - The FrameData container this BitmapData uses for rendering. - */ + * @property {Phaser.FrameData} frameData - The FrameData container this BitmapData uses for rendering. + */ this.frameData = new Phaser.FrameData(); /** - * @property {Phaser.Frame} textureFrame - The Frame this BitmapData uses for rendering. - * @default - */ + * @property {Phaser.Frame} textureFrame - The Frame this BitmapData uses for rendering. + * @default + */ this.textureFrame = this.frameData.addFrame(new Phaser.Frame(0, 0, 0, width, height, 'bitmapData')); this.texture.frame = this.textureFrame; /** - * @property {number} type - The const type of this object. - * @default - */ + * @property {number} type - The const type of this object. + * @default + */ this.type = Phaser.BITMAPDATA; /** - * @property {boolean} disableTextureUpload - If disableTextureUpload is true this BitmapData will never send its image data to the GPU when its dirty flag is true. - */ + * @property {boolean} disableTextureUpload - If disableTextureUpload is true this BitmapData will never send its image data to the GPU when its dirty flag is true. + */ this.disableTextureUpload = false; /** - * @property {boolean} dirty - If dirty this BitmapData will be re-rendered. - */ + * @property {boolean} dirty - If dirty this BitmapData will be re-rendered. + */ this.dirty = false; // Aliases this.cls = this.clear; /** - * @property {number} _image - Internal cache var. - * @private - */ + * @property {number} _image - Internal cache var. + * @private + */ this._image = null; /** - * @property {Phaser.Point} _pos - Internal cache var. - * @private - */ + * @property {Phaser.Point} _pos - Internal cache var. + * @private + */ this._pos = new Phaser.Point(); /** - * @property {Phaser.Point} _size - Internal cache var. - * @private - */ + * @property {Phaser.Point} _size - Internal cache var. + * @private + */ this._size = new Phaser.Point(); /** - * @property {Phaser.Point} _scale - Internal cache var. - * @private - */ + * @property {Phaser.Point} _scale - Internal cache var. + * @private + */ this._scale = new Phaser.Point(); /** - * @property {number} _rotate - Internal cache var. - * @private - */ + * @property {number} _rotate - Internal cache var. + * @private + */ this._rotate = 0; /** - * @property {object} _alpha - Internal cache var. - * @private - */ + * @property {object} _alpha - Internal cache var. + * @private + */ this._alpha = { prev: 1, current: 1 }; /** - * @property {Phaser.Point} _anchor - Internal cache var. - * @private - */ + * @property {Phaser.Point} _anchor - Internal cache var. + * @private + */ this._anchor = new Phaser.Point(); /** - * @property {number} _tempR - Internal cache var. - * @private - */ + * @property {number} _tempR - Internal cache var. + * @private + */ this._tempR = 0; /** - * @property {number} _tempG - Internal cache var. - * @private - */ + * @property {number} _tempG - Internal cache var. + * @private + */ this._tempG = 0; /** - * @property {number} _tempB - Internal cache var. - * @private - */ + * @property {number} _tempB - Internal cache var. + * @private + */ this._tempB = 0; /** - * @property {Phaser.Circle} _circle - Internal cache var. - * @private - */ + * @property {Phaser.Circle} _circle - Internal cache var. + * @private + */ this._circle = new Phaser.Circle(); /** - * @property {HTMLCanvasElement} _swapCanvas - A swap canvas. Used by moveH and moveV, created in those methods. - * @private - */ + * @property {HTMLCanvasElement} _swapCanvas - A swap canvas. Used by moveH and moveV, created in those methods. + * @private + */ this._swapCanvas = undefined; - }; Phaser.BitmapData.prototype = { /** - * Shifts the contents of this BitmapData by the distances given. - * - * The image will wrap-around the edges on all sides if the wrap argument is true (the default). - * - * @method Phaser.BitmapData#move - * @param {integer} x - The amount of pixels to horizontally shift the canvas by. Use a negative value to shift to the left, positive to the right. - * @param {integer} y - The amount of pixels to vertically shift the canvas by. Use a negative value to shift up, positive to shift down. - * @param {boolean} [wrap=true] - Wrap the content of the BitmapData. - * @return {Phaser.BitmapData} This BitmapData object for method chaining. - */ + * Shifts the contents of this BitmapData by the distances given. + * + * The image will wrap-around the edges on all sides if the wrap argument is true (the default). + * + * @method Phaser.BitmapData#move + * @param {integer} x - The amount of pixels to horizontally shift the canvas by. Use a negative value to shift to the left, positive to the right. + * @param {integer} y - The amount of pixels to vertically shift the canvas by. Use a negative value to shift up, positive to shift down. + * @param {boolean} [wrap=true] - Wrap the content of the BitmapData. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ move: function (x, y, wrap) { - if (x !== 0) { this.moveH(x, wrap); @@ -261,22 +258,20 @@ Phaser.BitmapData.prototype = { } return this; - }, /** - * Shifts the contents of this BitmapData horizontally. - * - * The image will wrap-around the sides if the wrap argument is true (the default). - * - * @method Phaser.BitmapData#moveH - * @param {integer} distance - The amount of pixels to horizontally shift the canvas by. Use a negative value to shift to the left, positive to the right. - * @param {boolean} [wrap=true] - Wrap the content of the BitmapData. - * @return {Phaser.BitmapData} This BitmapData object for method chaining. - */ + * Shifts the contents of this BitmapData horizontally. + * + * The image will wrap-around the sides if the wrap argument is true (the default). + * + * @method Phaser.BitmapData#moveH + * @param {integer} distance - The amount of pixels to horizontally shift the canvas by. Use a negative value to shift to the left, positive to the right. + * @param {boolean} [wrap=true] - Wrap the content of the BitmapData. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ moveH: function (distance, wrap) { - if (wrap === undefined) { wrap = true; } if (this._swapCanvas === undefined) @@ -325,22 +320,20 @@ Phaser.BitmapData.prototype = { this.clear(); return this.copy(this._swapCanvas); - }, /** - * Shifts the contents of this BitmapData vertically. - * - * The image will wrap-around the sides if the wrap argument is true (the default). - * - * @method Phaser.BitmapData#moveV - * @param {integer} distance - The amount of pixels to vertically shift the canvas by. Use a negative value to shift up, positive to shift down. - * @param {boolean} [wrap=true] - Wrap the content of the BitmapData. - * @return {Phaser.BitmapData} This BitmapData object for method chaining. - */ + * Shifts the contents of this BitmapData vertically. + * + * The image will wrap-around the sides if the wrap argument is true (the default). + * + * @method Phaser.BitmapData#moveV + * @param {integer} distance - The amount of pixels to vertically shift the canvas by. Use a negative value to shift up, positive to shift down. + * @param {boolean} [wrap=true] - Wrap the content of the BitmapData. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ moveV: function (distance, wrap) { - if (wrap === undefined) { wrap = true; } if (this._swapCanvas === undefined) @@ -389,20 +382,18 @@ Phaser.BitmapData.prototype = { this.clear(); return this.copy(this._swapCanvas); - }, /** - * Updates the given objects so that they use this BitmapData as their texture. - * This will replace any texture they will currently have set. - * - * @method Phaser.BitmapData#add - * @param {Phaser.Sprite|Phaser.Sprite[]|Phaser.Image|Phaser.Image[]} object - Either a single Sprite/Image or an Array of Sprites/Images. - * @return {Phaser.BitmapData} This BitmapData object for method chaining. - */ + * Updates the given objects so that they use this BitmapData as their texture. + * This will replace any texture they will currently have set. + * + * @method Phaser.BitmapData#add + * @param {Phaser.Sprite|Phaser.Sprite[]|Phaser.Image|Phaser.Image[]} object - Either a single Sprite/Image or an Array of Sprites/Images. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ add: function (object) { - if (Array.isArray(object)) { for (var i = 0; i < object.length; i++) @@ -419,22 +410,20 @@ Phaser.BitmapData.prototype = { } return this; - }, /** - * Takes the given Game Object, resizes this BitmapData to match it and then draws it into this BitmapDatas canvas, ready for further processing. - * The source game object is not modified by this operation. - * If the source object uses a texture as part of a Texture Atlas or Sprite Sheet, only the current frame will be used for sizing. - * If a string is given it will assume it's a cache key and look in Phaser.Cache for an image key matching the string. - * - * @method Phaser.BitmapData#load - * @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapData|Image|HTMLCanvasElement|string} source - The object that will be used to populate this BitmapData. If you give a string it will try and find the Image in the Game.Cache first. - * @return {Phaser.BitmapData} This BitmapData object for method chaining. - */ + * Takes the given Game Object, resizes this BitmapData to match it and then draws it into this BitmapDatas canvas, ready for further processing. + * The source game object is not modified by this operation. + * If the source object uses a texture as part of a Texture Atlas or Sprite Sheet, only the current frame will be used for sizing. + * If a string is given it will assume it's a cache key and look in Phaser.Cache for an image key matching the string. + * + * @method Phaser.BitmapData#load + * @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapData|Image|HTMLCanvasElement|string} source - The object that will be used to populate this BitmapData. If you give a string it will try and find the Image in the Game.Cache first. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ load: function (source) { - if (typeof source === 'string') { source = this.game.cache.getImage(source); @@ -455,34 +444,32 @@ Phaser.BitmapData.prototype = { this.update(); return this; - }, /** - * Clears the BitmapData context using a clearRect. - * - * @method Phaser.BitmapData#cls - */ + * Clears the BitmapData context using a clearRect. + * + * @method Phaser.BitmapData#cls + */ /** - * Clears the BitmapData context using a clearRect. - * - * You can optionally define the area to clear. - * If the arguments are left empty it will clear the entire canvas. - * - * You may need to call BitmapData.update after this in order to clear out the pixel data, - * but Phaser will not do this automatically for you. - * - * @method Phaser.BitmapData#clear - * @param {number} [x=0] - The x coordinate of the top-left of the area to clear. - * @param {number} [y=0] - The y coordinate of the top-left of the area to clear. - * @param {number} [width] - The width of the area to clear. If undefined it will use BitmapData.width. - * @param {number} [height] - The height of the area to clear. If undefined it will use BitmapData.height. - * @return {Phaser.BitmapData} This BitmapData object for method chaining. - */ + * Clears the BitmapData context using a clearRect. + * + * You can optionally define the area to clear. + * If the arguments are left empty it will clear the entire canvas. + * + * You may need to call BitmapData.update after this in order to clear out the pixel data, + * but Phaser will not do this automatically for you. + * + * @method Phaser.BitmapData#clear + * @param {number} [x=0] - The x coordinate of the top-left of the area to clear. + * @param {number} [y=0] - The y coordinate of the top-left of the area to clear. + * @param {number} [width] - The width of the area to clear. If undefined it will use BitmapData.width. + * @param {number} [height] - The height of the area to clear. If undefined it will use BitmapData.height. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ clear: function (x, y, width, height) { - if (x === undefined) { x = 0; } if (y === undefined) { y = 0; } if (width === undefined) { width = this.width; } @@ -493,22 +480,20 @@ Phaser.BitmapData.prototype = { this.dirty = true; return this; - }, /** - * Fills the BitmapData with the given color. - * - * @method Phaser.BitmapData#fill - * @param {number} r - The red color value, between 0 and 0xFF (255). - * @param {number} g - The green color value, between 0 and 0xFF (255). - * @param {number} b - The blue color value, between 0 and 0xFF (255). - * @param {number} [a=1] - The alpha color value, between 0 and 1. - * @return {Phaser.BitmapData} This BitmapData object for method chaining. - */ + * Fills the BitmapData with the given color. + * + * @method Phaser.BitmapData#fill + * @param {number} r - The red color value, between 0 and 0xFF (255). + * @param {number} g - The green color value, between 0 and 0xFF (255). + * @param {number} b - The blue color value, between 0 and 0xFF (255). + * @param {number} [a=1] - The alpha color value, between 0 and 1. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ fill: function (r, g, b, a) { - if (a === undefined) { a = 1; } this.context.fillStyle = 'rgba(' + r + ',' + g + ',' + b + ',' + a + ')'; @@ -516,7 +501,6 @@ Phaser.BitmapData.prototype = { this.dirty = true; return this; - }, /** @@ -531,9 +515,7 @@ Phaser.BitmapData.prototype = { */ getBase64: function (type, encoderOptions) { - return this.canvas.toDataURL(type, encoderOptions); - }, /** @@ -553,7 +535,6 @@ Phaser.BitmapData.prototype = { */ getImage: function (type, encoderOptions, onLoadCallback, onErrorCallback) { - var image = new Image(); if (onLoadCallback) { image.onload = onLoadCallback; } @@ -562,56 +543,54 @@ Phaser.BitmapData.prototype = { image.src = this.getBase64(type, encoderOptions); return image; - }, /** - * Creates a new {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/Image Image} element by converting this BitmapDatas canvas into a dataURL. - * - * The image is then stored in the {@link Phaser.Cache image Cache} using the key given. - * - * Finally a {@link PIXI.Texture} is created based on the image and returned. - * - * You can apply the texture to a sprite or any other supporting object by using either the - * key or the texture. First call `generateTexture`: - * - * ```javascript - * var texture = bitmapdata.generateTexture('ball'); - * ``` - * - * Then you can either apply the texture to a sprite: - * - * ```javascript - * game.add.sprite(0, 0, texture); - * ``` - * - * or by using the string based key: - * - * ```javascript - * game.add.sprite(0, 0, 'ball'); - * ``` - * - * Most browsers now load the image data asynchronously, so you should use a callback: - * - * ```javascript - * bitmapdata.generateTexture('ball', function (texture) { - * game.add.sprite(0, 0, texture); - * // or - * game.add.sprite(0, 0, 'ball'); - * }); - * ``` - * - * If this BitmapData is available during preload, you can use {@link Phaser.Loader#imageFromBitmapData} instead. - * - * @method Phaser.BitmapData#generateTexture - * @param {string} key - The key which will be used to store the image in the Cache. - * @param {function} [callback] - A function to execute once the texture is generated. It will be passed the newly generated texture. - * @param {any} [callbackContext] - The context in which to invoke the callback. - * @return {PIXI.Texture|null} The newly generated texture, or `null` if a callback was passed and the texture isn't available yet. - */ + * Creates a new {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/Image Image} element by converting this BitmapDatas canvas into a dataURL. + * + * The image is then stored in the {@link Phaser.Cache image Cache} using the key given. + * + * Finally a {@link PIXI.Texture} is created based on the image and returned. + * + * You can apply the texture to a sprite or any other supporting object by using either the + * key or the texture. First call `generateTexture`: + * + * ```javascript + * var texture = bitmapdata.generateTexture('ball'); + * ``` + * + * Then you can either apply the texture to a sprite: + * + * ```javascript + * game.add.sprite(0, 0, texture); + * ``` + * + * or by using the string based key: + * + * ```javascript + * game.add.sprite(0, 0, 'ball'); + * ``` + * + * Most browsers now load the image data asynchronously, so you should use a callback: + * + * ```javascript + * bitmapdata.generateTexture('ball', function (texture) { + * game.add.sprite(0, 0, texture); + * // or + * game.add.sprite(0, 0, 'ball'); + * }); + * ``` + * + * If this BitmapData is available during preload, you can use {@link Phaser.Loader#imageFromBitmapData} instead. + * + * @method Phaser.BitmapData#generateTexture + * @param {string} key - The key which will be used to store the image in the Cache. + * @param {function} [callback] - A function to execute once the texture is generated. It will be passed the newly generated texture. + * @param {any} [callbackContext] - The context in which to invoke the callback. + * @return {PIXI.Texture|null} The newly generated texture, or `null` if a callback was passed and the texture isn't available yet. + */ generateTexture: function (key, callback, callbackContext) { - var cache = this.game.cache; var image = new Image(); @@ -638,20 +617,18 @@ Phaser.BitmapData.prototype = { } return null; - }, /** - * Resizes the BitmapData. This changes the size of the underlying canvas and refreshes the buffer. - * - * @method Phaser.BitmapData#resize - * @param {integer} width - The new width of the BitmapData. - * @param {integer} height - The new height of the BitmapData. - * @return {Phaser.BitmapData} This BitmapData object for method chaining. - */ + * Resizes the BitmapData. This changes the size of the underlying canvas and refreshes the buffer. + * + * @method Phaser.BitmapData#resize + * @param {integer} width - The new width of the BitmapData. + * @param {integer} height - The new height of the BitmapData. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ resize: function (width, height) { - if (width !== this.width || height !== this.height) { this.width = width; @@ -683,26 +660,24 @@ Phaser.BitmapData.prototype = { } return this; - }, /** - * This re-creates the BitmapData.imageData from the current context. - * It then re-builds the ArrayBuffer, the data Uint8ClampedArray reference and the pixels Int32Array. - * If not given the dimensions defaults to the full size of the context. - * - * Warning: This is a very expensive operation, so use it sparingly. - * - * @method Phaser.BitmapData#update - * @param {number} [x=0] - The x coordinate of the top-left of the image data area to grab from. - * @param {number} [y=0] - The y coordinate of the top-left of the image data area to grab from. - * @param {number} [width=1] - The width of the image data area. - * @param {number} [height=1] - The height of the image data area. - * @return {Phaser.BitmapData} This BitmapData object for method chaining. - */ + * This re-creates the BitmapData.imageData from the current context. + * It then re-builds the ArrayBuffer, the data Uint8ClampedArray reference and the pixels Int32Array. + * If not given the dimensions defaults to the full size of the context. + * + * Warning: This is a very expensive operation, so use it sparingly. + * + * @method Phaser.BitmapData#update + * @param {number} [x=0] - The x coordinate of the top-left of the image data area to grab from. + * @param {number} [y=0] - The y coordinate of the top-left of the image data area to grab from. + * @param {number} [width=1] - The width of the image data area. + * @param {number} [height=1] - The height of the image data area. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ update: function (x, y, width, height) { - if (x === undefined) { x = 0; } if (y === undefined) { y = 0; } if (width === undefined) { width = Math.max(1, this.width); } @@ -728,31 +703,29 @@ Phaser.BitmapData.prototype = { } return this; - }, /** - * Scans through the area specified in this BitmapData and sends a color object for every pixel to the given callback. - * The callback will be sent a color object with 6 properties: `{ r: number, g: number, b: number, a: number, color: number, rgba: string }`. - * Where r, g, b and a are integers between 0 and 255 representing the color component values for red, green, blue and alpha. - * The `color` property is an Int32 of the full color. Note the endianess of this will change per system. - * The `rgba` property is a CSS style rgba() string which can be used with context.fillStyle calls, among others. - * The callback will also be sent the pixels x and y coordinates respectively. - * The callback must return either `false`, in which case no change will be made to the pixel, or a new color object. - * If a new color object is returned the pixel will be set to the r, g, b and a color values given within it. - * - * @method Phaser.BitmapData#processPixelRGB - * @param {function} callback - The callback that will be sent each pixel color object to be processed. - * @param {object} callbackContext - The context under which the callback will be called. - * @param {number} [x=0] - The x coordinate of the top-left of the region to process from. - * @param {number} [y=0] - The y coordinate of the top-left of the region to process from. - * @param {number} [width] - The width of the region to process. - * @param {number} [height] - The height of the region to process. - * @return {Phaser.BitmapData} This BitmapData object for method chaining. - */ + * Scans through the area specified in this BitmapData and sends a color object for every pixel to the given callback. + * The callback will be sent a color object with 6 properties: `{ r: number, g: number, b: number, a: number, color: number, rgba: string }`. + * Where r, g, b and a are integers between 0 and 255 representing the color component values for red, green, blue and alpha. + * The `color` property is an Int32 of the full color. Note the endianess of this will change per system. + * The `rgba` property is a CSS style rgba() string which can be used with context.fillStyle calls, among others. + * The callback will also be sent the pixels x and y coordinates respectively. + * The callback must return either `false`, in which case no change will be made to the pixel, or a new color object. + * If a new color object is returned the pixel will be set to the r, g, b and a color values given within it. + * + * @method Phaser.BitmapData#processPixelRGB + * @param {function} callback - The callback that will be sent each pixel color object to be processed. + * @param {object} callbackContext - The context under which the callback will be called. + * @param {number} [x=0] - The x coordinate of the top-left of the region to process from. + * @param {number} [y=0] - The y coordinate of the top-left of the region to process from. + * @param {number} [width] - The width of the region to process. + * @param {number} [height] - The height of the region to process. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ processPixelRGB: function (callback, callbackContext, x, y, width, height) { - if (x === undefined) { x = 0; } if (y === undefined) { y = 0; } if (width === undefined) { width = this.width; } @@ -787,28 +760,26 @@ Phaser.BitmapData.prototype = { } return this; - }, /** - * Scans through the area specified in this BitmapData and sends the color for every pixel to the given callback along with its x and y coordinates. - * Whatever value the callback returns is set as the new color for that pixel, unless it returns the same color, in which case it's skipped. - * Note that the format of the color received will be different depending on if the system is big or little endian. - * It is expected that your callback will deal with endianess. If you'd rather Phaser did it then use processPixelRGB instead. - * The callback will also be sent the pixels x and y coordinates respectively. - * - * @method Phaser.BitmapData#processPixel - * @param {function} callback - The callback that will be sent each pixel color to be processed. - * @param {object} callbackContext - The context under which the callback will be called. - * @param {number} [x=0] - The x coordinate of the top-left of the region to process from. - * @param {number} [y=0] - The y coordinate of the top-left of the region to process from. - * @param {number} [width] - The width of the region to process. - * @param {number} [height] - The height of the region to process. - * @return {Phaser.BitmapData} This BitmapData object for method chaining. - */ + * Scans through the area specified in this BitmapData and sends the color for every pixel to the given callback along with its x and y coordinates. + * Whatever value the callback returns is set as the new color for that pixel, unless it returns the same color, in which case it's skipped. + * Note that the format of the color received will be different depending on if the system is big or little endian. + * It is expected that your callback will deal with endianess. If you'd rather Phaser did it then use processPixelRGB instead. + * The callback will also be sent the pixels x and y coordinates respectively. + * + * @method Phaser.BitmapData#processPixel + * @param {function} callback - The callback that will be sent each pixel color to be processed. + * @param {object} callbackContext - The context under which the callback will be called. + * @param {number} [x=0] - The x coordinate of the top-left of the region to process from. + * @param {number} [y=0] - The y coordinate of the top-left of the region to process from. + * @param {number} [width] - The width of the region to process. + * @param {number} [height] - The height of the region to process. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ processPixel: function (callback, callbackContext, x, y, width, height) { - if (x === undefined) { x = 0; } if (y === undefined) { y = 0; } if (width === undefined) { width = this.width; } @@ -842,28 +813,26 @@ Phaser.BitmapData.prototype = { } return this; - }, /** - * Replaces all pixels matching one color with another. The color values are given as two sets of RGBA values. - * An optional region parameter controls if the replacement happens in just a specific area of the BitmapData or the entire thing. - * - * @method Phaser.BitmapData#replaceRGB - * @param {number} r1 - The red color value to be replaced. Between 0 and 255. - * @param {number} g1 - The green color value to be replaced. Between 0 and 255. - * @param {number} b1 - The blue color value to be replaced. Between 0 and 255. - * @param {number} a1 - The alpha color value to be replaced. Between 0 and 255. - * @param {number} r2 - The red color value that is the replacement color. Between 0 and 255. - * @param {number} g2 - The green color value that is the replacement color. Between 0 and 255. - * @param {number} b2 - The blue color value that is the replacement color. Between 0 and 255. - * @param {number} a2 - The alpha color value that is the replacement color. Between 0 and 255. - * @param {Phaser.Rectangle} [region] - The area to perform the search over. If not given it will replace over the whole BitmapData. - * @return {Phaser.BitmapData} This BitmapData object for method chaining. - */ + * Replaces all pixels matching one color with another. The color values are given as two sets of RGBA values. + * An optional region parameter controls if the replacement happens in just a specific area of the BitmapData or the entire thing. + * + * @method Phaser.BitmapData#replaceRGB + * @param {number} r1 - The red color value to be replaced. Between 0 and 255. + * @param {number} g1 - The green color value to be replaced. Between 0 and 255. + * @param {number} b1 - The blue color value to be replaced. Between 0 and 255. + * @param {number} a1 - The alpha color value to be replaced. Between 0 and 255. + * @param {number} r2 - The red color value that is the replacement color. Between 0 and 255. + * @param {number} g2 - The green color value that is the replacement color. Between 0 and 255. + * @param {number} b2 - The blue color value that is the replacement color. Between 0 and 255. + * @param {number} a2 - The alpha color value that is the replacement color. Between 0 and 255. + * @param {Phaser.Rectangle} [region] - The area to perform the search over. If not given it will replace over the whole BitmapData. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ replaceRGB: function (r1, g1, b1, a1, r2, g2, b2, a2, region) { - var sx = 0; var sy = 0; var w = this.width; @@ -893,22 +862,20 @@ Phaser.BitmapData.prototype = { this.dirty = true; return this; - }, /** - * Sets the hue, saturation and lightness values on every pixel in the given region, or the whole BitmapData if no region was specified. - * - * @method Phaser.BitmapData#setHSL - * @param {number} [h=null] - The hue, in the range 0 - 1. - * @param {number} [s=null] - The saturation, in the range 0 - 1. - * @param {number} [l=null] - The lightness, in the range 0 - 1. - * @param {Phaser.Rectangle} [region] - The area to perform the operation on. If not given it will run over the whole BitmapData. - * @return {Phaser.BitmapData} This BitmapData object for method chaining. - */ + * Sets the hue, saturation and lightness values on every pixel in the given region, or the whole BitmapData if no region was specified. + * + * @method Phaser.BitmapData#setHSL + * @param {number} [h=null] - The hue, in the range 0 - 1. + * @param {number} [s=null] - The saturation, in the range 0 - 1. + * @param {number} [l=null] - The lightness, in the range 0 - 1. + * @param {Phaser.Rectangle} [region] - The area to perform the operation on. If not given it will run over the whole BitmapData. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ setHSL: function (h, s, l, region) { - var bHaveH = h || h === 0; var bHaveS = s || s === 0; var bHaveL = l || l === 0; @@ -955,24 +922,22 @@ Phaser.BitmapData.prototype = { this.dirty = true; return this; - }, /** - * Shifts any or all of the hue, saturation and lightness values on every pixel in the given region, or the whole BitmapData if no region was specified. - * Shifting will add the given value onto the current h, s and l values, not replace them. - * The hue is wrapped to keep it within the range 0 to 1. Saturation and lightness are clamped to not exceed 1. - * - * @method Phaser.BitmapData#shiftHSL - * @param {number} [h=null] - The amount to shift the hue by. Within [-1, 1]. - * @param {number} [s=null] - The amount to shift the saturation by. Within [-1, 1]. - * @param {number} [l=null] - The amount to shift the lightness by. Within [-1, 1]. - * @param {Phaser.Rectangle} [region] - The area to perform the operation on. If not given it will run over the whole BitmapData. - * @return {Phaser.BitmapData} This BitmapData object for method chaining. - */ + * Shifts any or all of the hue, saturation and lightness values on every pixel in the given region, or the whole BitmapData if no region was specified. + * Shifting will add the given value onto the current h, s and l values, not replace them. + * The hue is wrapped to keep it within the range 0 to 1. Saturation and lightness are clamped to not exceed 1. + * + * @method Phaser.BitmapData#shiftHSL + * @param {number} [h=null] - The amount to shift the hue by. Within [-1, 1]. + * @param {number} [s=null] - The amount to shift the saturation by. Within [-1, 1]. + * @param {number} [l=null] - The amount to shift the lightness by. Within [-1, 1]. + * @param {Phaser.Rectangle} [region] - The area to perform the operation on. If not given it will run over the whole BitmapData. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ shiftHSL: function (h, s, l, region) { - if (h === undefined || h === null) { h = false; } if (s === undefined || s === null) { s = false; } if (l === undefined || l === null) { l = false; } @@ -1019,25 +984,23 @@ Phaser.BitmapData.prototype = { this.dirty = true; return this; - }, /** - * Sets the color of the given pixel to the specified red, green, blue and alpha values. - * - * @method Phaser.BitmapData#setPixel32 - * @param {integer} x - The x coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData and be an integer, not a float. - * @param {integer} y - The y coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData and be an integer, not a float. - * @param {number} red - The red color value, between 0 and 0xFF (255). - * @param {number} green - The green color value, between 0 and 0xFF (255). - * @param {number} blue - The blue color value, between 0 and 0xFF (255). - * @param {number} alpha - The alpha color value, between 0 and 0xFF (255). - * @param {boolean} [immediate=true] - If `true` the context.putImageData will be called and the dirty flag set. - * @return {Phaser.BitmapData} This BitmapData object for method chaining. - */ + * Sets the color of the given pixel to the specified red, green, blue and alpha values. + * + * @method Phaser.BitmapData#setPixel32 + * @param {integer} x - The x coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData and be an integer, not a float. + * @param {integer} y - The y coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData and be an integer, not a float. + * @param {number} red - The red color value, between 0 and 0xFF (255). + * @param {number} green - The green color value, between 0 and 0xFF (255). + * @param {number} blue - The blue color value, between 0 and 0xFF (255). + * @param {number} alpha - The alpha color value, between 0 and 0xFF (255). + * @param {boolean} [immediate=true] - If `true` the context.putImageData will be called and the dirty flag set. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ setPixel32: function (x, y, red, green, blue, alpha, immediate) { - if (immediate === undefined) { immediate = true; } if (x >= 0 && x <= this.width && y >= 0 && y <= this.height) @@ -1059,42 +1022,38 @@ Phaser.BitmapData.prototype = { } return this; - }, /** - * Sets the color of the given pixel to the specified red, green and blue values. - * - * @method Phaser.BitmapData#setPixel - * @param {integer} x - The x coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData and be an integer, not a float. - * @param {integer} y - The y coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData and be an integer, not a float. - * @param {number} red - The red color value, between 0 and 0xFF (255). - * @param {number} green - The green color value, between 0 and 0xFF (255). - * @param {number} blue - The blue color value, between 0 and 0xFF (255). - * @param {boolean} [immediate=true] - If `true` the context.putImageData will be called and the dirty flag set. - * @return {Phaser.BitmapData} This BitmapData object for method chaining. - */ + * Sets the color of the given pixel to the specified red, green and blue values. + * + * @method Phaser.BitmapData#setPixel + * @param {integer} x - The x coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData and be an integer, not a float. + * @param {integer} y - The y coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData and be an integer, not a float. + * @param {number} red - The red color value, between 0 and 0xFF (255). + * @param {number} green - The green color value, between 0 and 0xFF (255). + * @param {number} blue - The blue color value, between 0 and 0xFF (255). + * @param {boolean} [immediate=true] - If `true` the context.putImageData will be called and the dirty flag set. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ setPixel: function (x, y, red, green, blue, immediate) { - return this.setPixel32(x, y, red, green, blue, 255, immediate); - }, /** - * Get the color of a specific pixel in the context into a color object. - * If you have drawn anything to the BitmapData since it was created you must call BitmapData.update to refresh the array buffer, - * otherwise this may return out of date color values, or worse - throw a run-time error as it tries to access an array element that doesn't exist. - * - * @method Phaser.BitmapData#getPixel - * @param {integer} x - The x coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData and be an integer, not a float. - * @param {integer} y - The y coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData and be an integer, not a float. - * @param {object} [out] - An object into which 4 properties will be created: r, g, b and a. If not provided a new object will be created. - * @return {object} An object with the red, green, blue and alpha values set in the r, g, b and a properties. - */ + * Get the color of a specific pixel in the context into a color object. + * If you have drawn anything to the BitmapData since it was created you must call BitmapData.update to refresh the array buffer, + * otherwise this may return out of date color values, or worse - throw a run-time error as it tries to access an array element that doesn't exist. + * + * @method Phaser.BitmapData#getPixel + * @param {integer} x - The x coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData and be an integer, not a float. + * @param {integer} y - The y coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData and be an integer, not a float. + * @param {object} [out] - An object into which 4 properties will be created: r, g, b and a. If not provided a new object will be created. + * @return {object} An object with the red, green, blue and alpha values set in the r, g, b and a properties. + */ getPixel: function (x, y, out) { - if (!out) { out = Phaser.Color.createColor(); @@ -1110,82 +1069,74 @@ Phaser.BitmapData.prototype = { out.a = this.data[++index]; return out; - }, /** - * Get the color of a specific pixel including its alpha value. - * If you have drawn anything to the BitmapData since it was created you must call BitmapData.update to refresh the array buffer, - * otherwise this may return out of date color values, or worse - throw a run-time error as it tries to access an array element that doesn't exist. - * Note that on little-endian systems the format is 0xAABBGGRR and on big-endian the format is 0xRRGGBBAA. - * - * @method Phaser.BitmapData#getPixel32 - * @param {integer} x - The x coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData and be an integer, not a float. - * @param {integer} y - The y coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData and be an integer, not a float. - * @return {number} A native color value integer (format: 0xAARRGGBB) - */ + * Get the color of a specific pixel including its alpha value. + * If you have drawn anything to the BitmapData since it was created you must call BitmapData.update to refresh the array buffer, + * otherwise this may return out of date color values, or worse - throw a run-time error as it tries to access an array element that doesn't exist. + * Note that on little-endian systems the format is 0xAABBGGRR and on big-endian the format is 0xRRGGBBAA. + * + * @method Phaser.BitmapData#getPixel32 + * @param {integer} x - The x coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData and be an integer, not a float. + * @param {integer} y - The y coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData and be an integer, not a float. + * @return {number} A native color value integer (format: 0xAARRGGBB) + */ getPixel32: function (x, y) { - if (x >= 0 && x <= this.width && y >= 0 && y <= this.height) { return this.pixels[y * this.width + x]; } - }, /** - * Get the color of a specific pixel including its alpha value as a color object containing r,g,b,a and rgba properties. - * If you have drawn anything to the BitmapData since it was created you must call BitmapData.update to refresh the array buffer, - * otherwise this may return out of date color values, or worse - throw a run-time error as it tries to access an array element that doesn't exist. - * - * @method Phaser.BitmapData#getPixelRGB - * @param {integer} x - The x coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData and be an integer, not a float. - * @param {integer} y - The y coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData and be an integer, not a float. - * @param {object} [out] - An object into which 3 properties will be created: r, g and b. If not provided a new object will be created. - * @param {boolean} [hsl=false] - Also convert the rgb values into hsl? - * @param {boolean} [hsv=false] - Also convert the rgb values into hsv? - * @return {object} An object with the red, green and blue values set in the r, g and b properties. - */ + * Get the color of a specific pixel including its alpha value as a color object containing r,g,b,a and rgba properties. + * If you have drawn anything to the BitmapData since it was created you must call BitmapData.update to refresh the array buffer, + * otherwise this may return out of date color values, or worse - throw a run-time error as it tries to access an array element that doesn't exist. + * + * @method Phaser.BitmapData#getPixelRGB + * @param {integer} x - The x coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData and be an integer, not a float. + * @param {integer} y - The y coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData and be an integer, not a float. + * @param {object} [out] - An object into which 3 properties will be created: r, g and b. If not provided a new object will be created. + * @param {boolean} [hsl=false] - Also convert the rgb values into hsl? + * @param {boolean} [hsv=false] - Also convert the rgb values into hsv? + * @return {object} An object with the red, green and blue values set in the r, g and b properties. + */ getPixelRGB: function (x, y, out, hsl, hsv) { - return Phaser.Color.unpackPixel(this.getPixel32(x, y), out, hsl, hsv); - }, /** - * Gets all the pixels from the region specified by the given Rectangle object. - * - * @method Phaser.BitmapData#getPixels - * @param {Phaser.Rectangle} rect - The Rectangle region to get. - * @return {ImageData} Returns a ImageData object containing a Uint8ClampedArray data property. - */ + * Gets all the pixels from the region specified by the given Rectangle object. + * + * @method Phaser.BitmapData#getPixels + * @param {Phaser.Rectangle} rect - The Rectangle region to get. + * @return {ImageData} Returns a ImageData object containing a Uint8ClampedArray data property. + */ getPixels: function (rect) { - return this.context.getImageData(rect.x, rect.y, rect.width, rect.height); - }, /** - * Scans the BitmapData, pixel by pixel, until it encounters a pixel that isn't transparent (i.e. has an alpha value > 0). - * It then stops scanning and returns an object containing the color of the pixel in r, g and b properties and the location in the x and y properties. - * - * The direction parameter controls from which direction it should start the scan: - * - * 0 = top to bottom - * 1 = bottom to top - * 2 = left to right - * 3 = right to left - * - * @method Phaser.BitmapData#getFirstPixel - * @param {number} [direction=0] - The direction in which to scan for the first pixel. 0 = top to bottom, 1 = bottom to top, 2 = left to right and 3 = right to left. - * @return {object} Returns an object containing the color of the pixel in the `r`, `g` and `b` properties and the location in the `x` and `y` properties. - */ + * Scans the BitmapData, pixel by pixel, until it encounters a pixel that isn't transparent (i.e. has an alpha value > 0). + * It then stops scanning and returns an object containing the color of the pixel in r, g and b properties and the location in the x and y properties. + * + * The direction parameter controls from which direction it should start the scan: + * + * 0 = top to bottom + * 1 = bottom to top + * 2 = left to right + * 3 = right to left + * + * @method Phaser.BitmapData#getFirstPixel + * @param {number} [direction=0] - The direction in which to scan for the first pixel. 0 = top to bottom, 1 = bottom to top, 2 = left to right and 3 = right to left. + * @return {object} Returns an object containing the color of the pixel in the `r`, `g` and `b` properties and the location in the `x` and `y` properties. + */ getFirstPixel: function (direction) { - if (direction === undefined) { direction = 0; } var pixel = Phaser.Color.createColor(); @@ -1208,7 +1159,6 @@ Phaser.BitmapData.prototype = { do { - Phaser.Color.unpackPixel(this.getPixel32(x, y), pixel); if (direction === 0 || direction === 1) @@ -1250,20 +1200,18 @@ Phaser.BitmapData.prototype = { pixel.y = y; return pixel; - }, /** - * Scans the BitmapData and calculates the bounds. This is a rectangle that defines the extent of all non-transparent pixels. - * The rectangle returned will extend from the top-left of the image to the bottom-right, excluding transparent pixels. - * - * @method Phaser.BitmapData#getBounds - * @param {Phaser.Rectangle} [rect] - If provided this Rectangle object will be populated with the bounds, otherwise a new object will be created. - * @return {Phaser.Rectangle} A Rectangle whose dimensions encompass the full extent of non-transparent pixels in this BitmapData. - */ + * Scans the BitmapData and calculates the bounds. This is a rectangle that defines the extent of all non-transparent pixels. + * The rectangle returned will extend from the top-left of the image to the bottom-right, excluding transparent pixels. + * + * @method Phaser.BitmapData#getBounds + * @param {Phaser.Rectangle} [rect] - If provided this Rectangle object will be populated with the bounds, otherwise a new object will be created. + * @return {Phaser.Rectangle} A Rectangle whose dimensions encompass the full extent of non-transparent pixels in this BitmapData. + */ getBounds: function (rect) { - if (rect === undefined) { rect = new Phaser.Rectangle(); } rect.x = this.getFirstPixel(2).x; @@ -1279,24 +1227,22 @@ Phaser.BitmapData.prototype = { rect.height = (this.getFirstPixel(1).y - rect.y) + 1; return rect; - }, /** - * Creates a new Phaser.Image object, assigns this BitmapData to be its texture, adds it to the world then returns it. - * - * @method Phaser.BitmapData#addToWorld - * @param {number} [x=0] - The x coordinate to place the Image at. - * @param {number} [y=0] - The y coordinate to place the Image at. - * @param {number} [anchorX=0] - Set the x anchor point of the Image. A value between 0 and 1, where 0 is the top-left and 1 is bottom-right. - * @param {number} [anchorY=0] - Set the y anchor point of the Image. A value between 0 and 1, where 0 is the top-left and 1 is bottom-right. - * @param {number} [scaleX=1] - The horizontal scale factor of the Image. A value of 1 means no scaling. 2 would be twice the size, and so on. - * @param {number} [scaleY=1] - The vertical scale factor of the Image. A value of 1 means no scaling. 2 would be twice the size, and so on. - * @return {Phaser.Image} The newly added Image object. - */ + * Creates a new Phaser.Image object, assigns this BitmapData to be its texture, adds it to the world then returns it. + * + * @method Phaser.BitmapData#addToWorld + * @param {number} [x=0] - The x coordinate to place the Image at. + * @param {number} [y=0] - The y coordinate to place the Image at. + * @param {number} [anchorX=0] - Set the x anchor point of the Image. A value between 0 and 1, where 0 is the top-left and 1 is bottom-right. + * @param {number} [anchorY=0] - Set the y anchor point of the Image. A value between 0 and 1, where 0 is the top-left and 1 is bottom-right. + * @param {number} [scaleX=1] - The horizontal scale factor of the Image. A value of 1 means no scaling. 2 would be twice the size, and so on. + * @param {number} [scaleY=1] - The vertical scale factor of the Image. A value of 1 means no scaling. 2 would be twice the size, and so on. + * @return {Phaser.Image} The newly added Image object. + */ addToWorld: function (x, y, anchorX, anchorY, scaleX, scaleY) { - scaleX = scaleX || 1; scaleY = scaleY || 1; @@ -1306,7 +1252,6 @@ Phaser.BitmapData.prototype = { image.scale.set(scaleX, scaleY); return image; - }, /** @@ -1346,7 +1291,6 @@ Phaser.BitmapData.prototype = { */ copy: function (source, x, y, width, height, tx, ty, newWidth, newHeight, rotate, anchorX, anchorY, scaleX, scaleY, alpha, blendMode, roundPx) { - if (source === undefined || source === null) { source = this; } if (source instanceof Phaser.RenderTexture) @@ -1528,25 +1472,23 @@ Phaser.BitmapData.prototype = { this.dirty = true; return this; - }, /** - * Draws the given `source` Game Object to this BitmapData, using its `worldTransform` property to set the - * position, scale and rotation of where it is drawn. This function is used internally by `drawGroup`. - * It takes the objects tint and scale mode into consideration before drawing. - * - * You can optionally specify Blend Mode and Round Pixels arguments. - * - * @method Phaser.BitmapData#copyTransform - * @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapData|Phaser.BitmapText} [source] - The Game Object to draw. - * @param {string} [blendMode=null] - The composite blend mode that will be used when drawing. The default is no blend mode at all. This is a Canvas globalCompositeOperation value such as 'lighter' or 'xor'. - * @param {boolean} [roundPx=false] - Should the x and y values be rounded to integers before drawing? This prevents anti-aliasing in some instances. - * @return {Phaser.BitmapData} This BitmapData object for method chaining. - */ + * Draws the given `source` Game Object to this BitmapData, using its `worldTransform` property to set the + * position, scale and rotation of where it is drawn. This function is used internally by `drawGroup`. + * It takes the objects tint and scale mode into consideration before drawing. + * + * You can optionally specify Blend Mode and Round Pixels arguments. + * + * @method Phaser.BitmapData#copyTransform + * @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapData|Phaser.BitmapText} [source] - The Game Object to draw. + * @param {string} [blendMode=null] - The composite blend mode that will be used when drawing. The default is no blend mode at all. This is a Canvas globalCompositeOperation value such as 'lighter' or 'xor'. + * @param {boolean} [roundPx=false] - Should the x and y values be rounded to integers before drawing? This prevents anti-aliasing in some instances. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ copyTransform: function (source, blendMode, roundPx) { - if (blendMode === undefined) { blendMode = null; } if (roundPx === undefined) { roundPx = false; } @@ -1637,102 +1579,94 @@ Phaser.BitmapData.prototype = { this.dirty = true; return this; - }, /** - * Copies the area defined by the Rectangle parameter from the source image to this BitmapData at the given location. - * - * @method Phaser.BitmapData#copyRect - * @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapData|Phaser.RenderTexture|Image|string} source - The Image to copy from. If you give a string it will try and find the Image in the Game.Cache. - * @param {Phaser.Rectangle} area - The Rectangle region to copy from the source image. - * @param {number} x - The destination x coordinate to copy the image to. - * @param {number} y - The destination y coordinate to copy the image to. - * @param {number} [alpha=1] - The alpha that will be set on the context before drawing. A value between 0 (fully transparent) and 1, opaque. - * @param {string} [blendMode=null] - The composite blend mode that will be used when drawing. The default is no blend mode at all. This is a Canvas globalCompositeOperation value such as 'lighter' or 'xor'. - * @param {boolean} [roundPx=false] - Should the x and y values be rounded to integers before drawing? This prevents anti-aliasing in some instances. - * @return {Phaser.BitmapData} This BitmapData object for method chaining. - */ + * Copies the area defined by the Rectangle parameter from the source image to this BitmapData at the given location. + * + * @method Phaser.BitmapData#copyRect + * @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapData|Phaser.RenderTexture|Image|string} source - The Image to copy from. If you give a string it will try and find the Image in the Game.Cache. + * @param {Phaser.Rectangle} area - The Rectangle region to copy from the source image. + * @param {number} x - The destination x coordinate to copy the image to. + * @param {number} y - The destination y coordinate to copy the image to. + * @param {number} [alpha=1] - The alpha that will be set on the context before drawing. A value between 0 (fully transparent) and 1, opaque. + * @param {string} [blendMode=null] - The composite blend mode that will be used when drawing. The default is no blend mode at all. This is a Canvas globalCompositeOperation value such as 'lighter' or 'xor'. + * @param {boolean} [roundPx=false] - Should the x and y values be rounded to integers before drawing? This prevents anti-aliasing in some instances. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ copyRect: function (source, area, x, y, alpha, blendMode, roundPx) { - return this.copy(source, area.x, area.y, area.width, area.height, x, y, area.width, area.height, 0, 0, 0, 1, 1, alpha, blendMode, roundPx); - }, /** - * Draws the given Phaser.Sprite, Phaser.Image or Phaser.Text to this BitmapData at the coordinates specified. - * You can use the optional width and height values to 'stretch' the sprite as it is drawn. This uses drawImage stretching, not scaling. - * - * The children will be drawn at their `x` and `y` world space coordinates. If this is outside the bounds of the BitmapData they won't be visible. - * When drawing it will take into account the rotation, scale, scaleMode, alpha and tint values. - * - * Note: You should ensure that at least 1 full update has taken place before calling this, - * otherwise the objects are likely to render incorrectly, if at all. - * You can trigger an update yourself by calling `stage.updateTransform()` before calling `draw`. - * - * @method Phaser.BitmapData#draw - * @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.RenderTexture} source - The Sprite, Image or Text object to draw onto this BitmapData. - * @param {number} [x=0] - The x coordinate to translate to before drawing. If not specified it will default to `source.x`. - * @param {number} [y=0] - The y coordinate to translate to before drawing. If not specified it will default to `source.y`. - * @param {number} [width] - The new width of the Sprite being copied. If not specified it will default to `source.width`. - * @param {number} [height] - The new height of the Sprite being copied. If not specified it will default to `source.height`. - * @param {string} [blendMode=null] - The composite blend mode that will be used when drawing. The default is no blend mode at all. This is a Canvas globalCompositeOperation value such as 'lighter' or 'xor'. - * @param {boolean} [roundPx=false] - Should the x and y values be rounded to integers before drawing? This prevents anti-aliasing in some instances. - * @return {Phaser.BitmapData} This BitmapData object for method chaining. - */ + * Draws the given Phaser.Sprite, Phaser.Image or Phaser.Text to this BitmapData at the coordinates specified. + * You can use the optional width and height values to 'stretch' the sprite as it is drawn. This uses drawImage stretching, not scaling. + * + * The children will be drawn at their `x` and `y` world space coordinates. If this is outside the bounds of the BitmapData they won't be visible. + * When drawing it will take into account the rotation, scale, scaleMode, alpha and tint values. + * + * Note: You should ensure that at least 1 full update has taken place before calling this, + * otherwise the objects are likely to render incorrectly, if at all. + * You can trigger an update yourself by calling `stage.updateTransform()` before calling `draw`. + * + * @method Phaser.BitmapData#draw + * @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.RenderTexture} source - The Sprite, Image or Text object to draw onto this BitmapData. + * @param {number} [x=0] - The x coordinate to translate to before drawing. If not specified it will default to `source.x`. + * @param {number} [y=0] - The y coordinate to translate to before drawing. If not specified it will default to `source.y`. + * @param {number} [width] - The new width of the Sprite being copied. If not specified it will default to `source.width`. + * @param {number} [height] - The new height of the Sprite being copied. If not specified it will default to `source.height`. + * @param {string} [blendMode=null] - The composite blend mode that will be used when drawing. The default is no blend mode at all. This is a Canvas globalCompositeOperation value such as 'lighter' or 'xor'. + * @param {boolean} [roundPx=false] - Should the x and y values be rounded to integers before drawing? This prevents anti-aliasing in some instances. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ draw: function (source, x, y, width, height, blendMode, roundPx) { - // By specifying null for most parameters it will tell `copy` to use the Sprite values instead, which is what we want here return this.copy(source, null, null, null, null, x, y, width, height, null, null, null, null, null, null, blendMode, roundPx); - }, /** - * Draws the immediate children of a Phaser.Group to this BitmapData. - * - * It's perfectly valid to pass in `game.world` as the Group, and it will iterate through the entire display list. - * - * Children are drawn _only_ if they have their `exists` property set to `true`, and have image, or RenderTexture, based Textures. - * - * The children will be drawn at their `x` and `y` world space coordinates. If this is outside the bounds of the BitmapData they won't be visible. - * When drawing it will take into account the rotation, scale, scaleMode, alpha and tint values. - * - * Note: You should ensure that at least 1 full update has taken place before calling this, - * otherwise the objects are likely to render incorrectly, if at all. - * You can trigger an update yourself by calling `stage.updateTransform()` before calling `drawGroup`. - * - * @method Phaser.BitmapData#drawGroup - * @param {Phaser.Group} group - The Group to draw onto this BitmapData. Can also be Phaser.World. - * @param {string} [blendMode=null] - The composite blend mode that will be used when drawing. The default is no blend mode at all. This is a Canvas globalCompositeOperation value such as 'lighter' or 'xor'. - * @param {boolean} [roundPx=false] - Should the x and y values be rounded to integers before drawing? This prevents anti-aliasing in some instances. - * @return {Phaser.BitmapData} This BitmapData object for method chaining. - */ + * Draws the immediate children of a Phaser.Group to this BitmapData. + * + * It's perfectly valid to pass in `game.world` as the Group, and it will iterate through the entire display list. + * + * Children are drawn _only_ if they have their `exists` property set to `true`, and have image, or RenderTexture, based Textures. + * + * The children will be drawn at their `x` and `y` world space coordinates. If this is outside the bounds of the BitmapData they won't be visible. + * When drawing it will take into account the rotation, scale, scaleMode, alpha and tint values. + * + * Note: You should ensure that at least 1 full update has taken place before calling this, + * otherwise the objects are likely to render incorrectly, if at all. + * You can trigger an update yourself by calling `stage.updateTransform()` before calling `drawGroup`. + * + * @method Phaser.BitmapData#drawGroup + * @param {Phaser.Group} group - The Group to draw onto this BitmapData. Can also be Phaser.World. + * @param {string} [blendMode=null] - The composite blend mode that will be used when drawing. The default is no blend mode at all. This is a Canvas globalCompositeOperation value such as 'lighter' or 'xor'. + * @param {boolean} [roundPx=false] - Should the x and y values be rounded to integers before drawing? This prevents anti-aliasing in some instances. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ drawGroup: function (group, blendMode, roundPx) { - if (group.total > 0) { group.forEachExists(this.drawGroupProxy, this, blendMode, roundPx); } return this; - }, /** - * A proxy for drawGroup that handles child iteration for more complex Game Objects. - * - * @method Phaser.BitmapData#drawGroupProxy - * @private - * @param {Phaser.Sprite|Phaser.Image|Phaser.BitmapText} child - The child to draw. - * @param {string} [blendMode=null] - The composite blend mode that will be used when drawing. The default is no blend mode at all. This is a Canvas globalCompositeOperation value such as 'lighter' or 'xor'. - * @param {boolean} [roundPx=false] - Should the x and y values be rounded to integers before drawing? This prevents anti-aliasing in some instances. - */ + * A proxy for drawGroup that handles child iteration for more complex Game Objects. + * + * @method Phaser.BitmapData#drawGroupProxy + * @private + * @param {Phaser.Sprite|Phaser.Image|Phaser.BitmapText} child - The child to draw. + * @param {string} [blendMode=null] - The composite blend mode that will be used when drawing. The default is no blend mode at all. This is a Canvas globalCompositeOperation value such as 'lighter' or 'xor'. + * @param {boolean} [roundPx=false] - Should the x and y values be rounded to integers before drawing? This prevents anti-aliasing in some instances. + */ drawGroupProxy: function (child, blendMode, roundPx) { - if (child.hasOwnProperty('texture')) { this.copyTransform(child, blendMode, roundPx); @@ -1753,35 +1687,33 @@ Phaser.BitmapData.prototype = { } } } - }, /** - * Draws the Game Object or Group to this BitmapData and then recursively iterates through all of its children. - * - * If a child has an `exists` property then it (and its children) will be only be drawn if exists is `true`. - * - * The children will be drawn at their `x` and `y` world space coordinates. If this is outside the bounds of the BitmapData - * they won't be drawn. Depending on your requirements you may need to resize the BitmapData in advance to match the - * bounds of the top-level Game Object. - * - * When drawing it will take into account the child's world rotation, scale and alpha values. - * - * It's perfectly valid to pass in `game.world` as the parent object, and it will iterate through the entire display list. - * - * Note: If you are trying to grab your entire game at the start of a State then you should ensure that at least 1 full update - * has taken place before doing so, otherwise all of the objects will render with incorrect positions and scales. You can - * trigger an update yourself by calling `stage.updateTransform()` before calling `drawFull`. - * - * @method Phaser.BitmapData#drawFull - * @param {Phaser.World|Phaser.Group|Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapText} parent - The Game Object to draw onto this BitmapData and then recursively draw all of its children. - * @param {string} [blendMode=null] - The composite blend mode that will be used when drawing. The default is no blend mode at all. This is a Canvas globalCompositeOperation value such as 'lighter' or 'xor'. - * @param {boolean} [roundPx=false] - Should the x and y values be rounded to integers before drawing? This prevents anti-aliasing in some instances. - * @return {Phaser.BitmapData} This BitmapData object for method chaining. - */ + * Draws the Game Object or Group to this BitmapData and then recursively iterates through all of its children. + * + * If a child has an `exists` property then it (and its children) will be only be drawn if exists is `true`. + * + * The children will be drawn at their `x` and `y` world space coordinates. If this is outside the bounds of the BitmapData + * they won't be drawn. Depending on your requirements you may need to resize the BitmapData in advance to match the + * bounds of the top-level Game Object. + * + * When drawing it will take into account the child's world rotation, scale and alpha values. + * + * It's perfectly valid to pass in `game.world` as the parent object, and it will iterate through the entire display list. + * + * Note: If you are trying to grab your entire game at the start of a State then you should ensure that at least 1 full update + * has taken place before doing so, otherwise all of the objects will render with incorrect positions and scales. You can + * trigger an update yourself by calling `stage.updateTransform()` before calling `drawFull`. + * + * @method Phaser.BitmapData#drawFull + * @param {Phaser.World|Phaser.Group|Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapText} parent - The Game Object to draw onto this BitmapData and then recursively draw all of its children. + * @param {string} [blendMode=null] - The composite blend mode that will be used when drawing. The default is no blend mode at all. This is a Canvas globalCompositeOperation value such as 'lighter' or 'xor'. + * @param {boolean} [roundPx=false] - Should the x and y values be rounded to integers before drawing? This prevents anti-aliasing in some instances. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ drawFull: function (parent, blendMode, roundPx) { - if (parent.worldVisible === false || parent.worldAlpha === 0 || (parent.hasOwnProperty('exists') && parent.exists === false)) { return this; @@ -1812,24 +1744,22 @@ Phaser.BitmapData.prototype = { } return this; - }, /** - * Sets the shadow properties of this BitmapDatas context which will affect all draw operations made to it. - * You can cancel an existing shadow by calling this method and passing no parameters. - * Note: At the time of writing (October 2014) Chrome still doesn't support shadowBlur used with drawImage. - * - * @method Phaser.BitmapData#shadow - * @param {string} color - The color of the shadow, given in a CSS format, i.e. `#000000` or `rgba(0,0,0,1)`. If `null` or `undefined` the shadow will be reset. - * @param {number} [blur=5] - The amount the shadow will be blurred by. Low values = a crisp shadow, high values = a softer shadow. - * @param {number} [x=10] - The horizontal offset of the shadow in pixels. - * @param {number} [y=10] - The vertical offset of the shadow in pixels. - * @return {Phaser.BitmapData} This BitmapData object for method chaining. - */ + * Sets the shadow properties of this BitmapDatas context which will affect all draw operations made to it. + * You can cancel an existing shadow by calling this method and passing no parameters. + * Note: At the time of writing (October 2014) Chrome still doesn't support shadowBlur used with drawImage. + * + * @method Phaser.BitmapData#shadow + * @param {string} color - The color of the shadow, given in a CSS format, i.e. `#000000` or `rgba(0,0,0,1)`. If `null` or `undefined` the shadow will be reset. + * @param {number} [blur=5] - The amount the shadow will be blurred by. Low values = a crisp shadow, high values = a softer shadow. + * @param {number} [x=10] - The horizontal offset of the shadow in pixels. + * @param {number} [y=10] - The vertical offset of the shadow in pixels. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ shadow: function (color, blur, x, y) { - var ctx = this.context; if (color === undefined || color === null) @@ -1845,22 +1775,20 @@ Phaser.BitmapData.prototype = { } return this; - }, /** - * Draws the image onto this BitmapData using an image as an alpha mask. - * - * @method Phaser.BitmapData#alphaMask - * @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapData|Image|HTMLCanvasElement|string} source - The source to copy from. If you give a string it will try and find the Image in the Game.Cache first. This is quite expensive so try to provide the image itself. - * @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapData|Image|HTMLCanvasElement|string} [mask] - The object to be used as the mask. If you give a string it will try and find the Image in the Game.Cache first. This is quite expensive so try to provide the image itself. If you don't provide a mask it will use this BitmapData as the mask. - * @param {Phaser.Rectangle} [sourceRect] - A Rectangle where x/y define the coordinates to draw the Source image to and width/height define the size. - * @param {Phaser.Rectangle} [maskRect] - A Rectangle where x/y define the coordinates to draw the Mask image to and width/height define the size. - * @return {Phaser.BitmapData} This BitmapData object for method chaining. - */ + * Draws the image onto this BitmapData using an image as an alpha mask. + * + * @method Phaser.BitmapData#alphaMask + * @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapData|Image|HTMLCanvasElement|string} source - The source to copy from. If you give a string it will try and find the Image in the Game.Cache first. This is quite expensive so try to provide the image itself. + * @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapData|Image|HTMLCanvasElement|string} [mask] - The object to be used as the mask. If you give a string it will try and find the Image in the Game.Cache first. This is quite expensive so try to provide the image itself. If you don't provide a mask it will use this BitmapData as the mask. + * @param {Phaser.Rectangle} [sourceRect] - A Rectangle where x/y define the coordinates to draw the Source image to and width/height define the size. + * @param {Phaser.Rectangle} [maskRect] - A Rectangle where x/y define the coordinates to draw the Mask image to and width/height define the size. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ alphaMask: function (source, mask, sourceRect, maskRect) { - if (maskRect === undefined || maskRect === null) { this.draw(mask).blendSourceAtop(); @@ -1880,34 +1808,32 @@ Phaser.BitmapData.prototype = { } return this; - }, /** - * Scans this BitmapData for all pixels matching the given r,g,b values and then draws them into the given destination BitmapData. - * The original BitmapData remains unchanged. - * The destination BitmapData must be large enough to receive all of the pixels that are scanned unless the 'resize' parameter is true. - * Although the destination BitmapData is returned from this method, it's actually modified directly in place, meaning this call is perfectly valid: - * `picture.extract(mask, r, g, b)` - * You can specify optional r2, g2, b2 color values. If given the pixel written to the destination bitmap will be of the r2, g2, b2 color. - * If not given it will be written as the same color it was extracted. You can provide one or more alternative colors, allowing you to tint - * the color during extraction. - * - * @method Phaser.BitmapData#extract - * @param {Phaser.BitmapData} destination - The BitmapData that the extracted pixels will be drawn to. - * @param {number} r - The red color component, in the range 0 - 255. - * @param {number} g - The green color component, in the range 0 - 255. - * @param {number} b - The blue color component, in the range 0 - 255. - * @param {number} [a=255] - The alpha color component, in the range 0 - 255 that the new pixel will be drawn at. - * @param {boolean} [resize=false] - Should the destination BitmapData be resized to match this one before the pixels are copied? - * @param {number} [r2] - An alternative red color component to be written to the destination, in the range 0 - 255. - * @param {number} [g2] - An alternative green color component to be written to the destination, in the range 0 - 255. - * @param {number} [b2] - An alternative blue color component to be written to the destination, in the range 0 - 255. - * @returns {Phaser.BitmapData} The BitmapData that the extract pixels were drawn on. - */ + * Scans this BitmapData for all pixels matching the given r,g,b values and then draws them into the given destination BitmapData. + * The original BitmapData remains unchanged. + * The destination BitmapData must be large enough to receive all of the pixels that are scanned unless the 'resize' parameter is true. + * Although the destination BitmapData is returned from this method, it's actually modified directly in place, meaning this call is perfectly valid: + * `picture.extract(mask, r, g, b)` + * You can specify optional r2, g2, b2 color values. If given the pixel written to the destination bitmap will be of the r2, g2, b2 color. + * If not given it will be written as the same color it was extracted. You can provide one or more alternative colors, allowing you to tint + * the color during extraction. + * + * @method Phaser.BitmapData#extract + * @param {Phaser.BitmapData} destination - The BitmapData that the extracted pixels will be drawn to. + * @param {number} r - The red color component, in the range 0 - 255. + * @param {number} g - The green color component, in the range 0 - 255. + * @param {number} b - The blue color component, in the range 0 - 255. + * @param {number} [a=255] - The alpha color component, in the range 0 - 255 that the new pixel will be drawn at. + * @param {boolean} [resize=false] - Should the destination BitmapData be resized to match this one before the pixels are copied? + * @param {number} [r2] - An alternative red color component to be written to the destination, in the range 0 - 255. + * @param {number} [g2] - An alternative green color component to be written to the destination, in the range 0 - 255. + * @param {number} [b2] - An alternative blue color component to be written to the destination, in the range 0 - 255. + * @returns {Phaser.BitmapData} The BitmapData that the extract pixels were drawn on. + */ extract: function (destination, r, g, b, a, resize, r2, g2, b2) { - if (a === undefined) { a = 255; } if (resize === undefined) { resize = false; } if (r2 === undefined) { r2 = r; } @@ -1934,23 +1860,21 @@ Phaser.BitmapData.prototype = { destination.dirty = true; return destination; - }, /** - * Draws a filled Rectangle to the BitmapData at the given x, y coordinates and width / height in size. - * - * @method Phaser.BitmapData#rect - * @param {number} x - The x coordinate of the top-left of the Rectangle. - * @param {number} y - The y coordinate of the top-left of the Rectangle. - * @param {number} width - The width of the Rectangle. - * @param {number} height - The height of the Rectangle. - * @param {string} [fillStyle] - If set the context fillStyle will be set to this value before the rect is drawn. - * @return {Phaser.BitmapData} This BitmapData object for method chaining. - */ + * Draws a filled Rectangle to the BitmapData at the given x, y coordinates and width / height in size. + * + * @method Phaser.BitmapData#rect + * @param {number} x - The x coordinate of the top-left of the Rectangle. + * @param {number} y - The y coordinate of the top-left of the Rectangle. + * @param {number} width - The width of the Rectangle. + * @param {number} height - The height of the Rectangle. + * @param {string} [fillStyle] - If set the context fillStyle will be set to this value before the rect is drawn. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ rect: function (x, y, width, height, fillStyle) { - if (typeof fillStyle !== 'undefined') { this.context.fillStyle = fillStyle; @@ -1959,26 +1883,24 @@ Phaser.BitmapData.prototype = { this.context.fillRect(x, y, width, height); return this; - }, /** - * Draws text to the BitmapData in the given font and color. - * The default font is 14px Courier, so useful for quickly drawing debug text. - * If you need to do a lot of font work to this BitmapData we'd recommend implementing your own text draw method. - * - * @method Phaser.BitmapData#text - * @param {string} text - The text to write to the BitmapData. - * @param {number} x - The x coordinate of the top-left of the text string. - * @param {number} y - The y coordinate of the top-left of the text string. - * @param {string} [font='14px Courier'] - The font. This is passed directly to Context.font, so anything that can support, this can. - * @param {string} [color='rgb(255,255,255)'] - The color the text will be drawn in. - * @param {boolean} [shadow=true] - Draw a single pixel black shadow below the text (offset by text.x/y + 1) - * @return {Phaser.BitmapData} This BitmapData object for method chaining. - */ + * Draws text to the BitmapData in the given font and color. + * The default font is 14px Courier, so useful for quickly drawing debug text. + * If you need to do a lot of font work to this BitmapData we'd recommend implementing your own text draw method. + * + * @method Phaser.BitmapData#text + * @param {string} text - The text to write to the BitmapData. + * @param {number} x - The x coordinate of the top-left of the text string. + * @param {number} y - The y coordinate of the top-left of the text string. + * @param {string} [font='14px Courier'] - The font. This is passed directly to Context.font, so anything that can support, this can. + * @param {string} [color='rgb(255,255,255)'] - The color the text will be drawn in. + * @param {boolean} [shadow=true] - Draw a single pixel black shadow below the text (offset by text.x/y + 1) + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ text: function (text, x, y, font, color, shadow) { - if (x === undefined) { x = 0; } if (y === undefined) { y = 0; } if (font === undefined) { font = '14px Courier'; } @@ -2002,22 +1924,20 @@ Phaser.BitmapData.prototype = { ctx.font = prevFont; return this; - }, /** - * Draws a filled Circle to the BitmapData at the given x, y coordinates and radius in size. - * - * @method Phaser.BitmapData#circle - * @param {number} x - The x coordinate to draw the Circle at. This is the center of the circle. - * @param {number} y - The y coordinate to draw the Circle at. This is the center of the circle. - * @param {number} radius - The radius of the Circle in pixels. The radius is half the diameter. - * @param {string} [fillStyle] - If set the context fillStyle will be set to this value before the circle is drawn. - * @return {Phaser.BitmapData} This BitmapData object for method chaining. - */ + * Draws a filled Circle to the BitmapData at the given x, y coordinates and radius in size. + * + * @method Phaser.BitmapData#circle + * @param {number} x - The x coordinate to draw the Circle at. This is the center of the circle. + * @param {number} y - The y coordinate to draw the Circle at. This is the center of the circle. + * @param {number} radius - The radius of the Circle in pixels. The radius is half the diameter. + * @param {string} [fillStyle] - If set the context fillStyle will be set to this value before the circle is drawn. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ circle: function (x, y, radius, fillStyle) { - var ctx = this.context; if (fillStyle !== undefined) @@ -2032,24 +1952,22 @@ Phaser.BitmapData.prototype = { ctx.fill(); return this; - }, /** - * Draws a line between the coordinates given in the color and thickness specified. - * - * @method Phaser.BitmapData#line - * @param {number} x1 - The x coordinate to start the line from. - * @param {number} y1 - The y coordinate to start the line from. - * @param {number} x2 - The x coordinate to draw the line to. - * @param {number} y2 - The y coordinate to draw the line to. - * @param {string} [color='#fff'] - The stroke color that the line will be drawn in. - * @param {number} [width=1] - The line thickness. - * @return {Phaser.BitmapData} This BitmapData object for method chaining. - */ + * Draws a line between the coordinates given in the color and thickness specified. + * + * @method Phaser.BitmapData#line + * @param {number} x1 - The x coordinate to start the line from. + * @param {number} y1 - The y coordinate to start the line from. + * @param {number} x2 - The x coordinate to draw the line to. + * @param {number} y2 - The y coordinate to draw the line to. + * @param {string} [color='#fff'] - The stroke color that the line will be drawn in. + * @param {number} [width=1] - The line thickness. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ line: function (x1, y1, x2, y2, color, width) { - if (color === undefined) { color = '#fff'; } if (width === undefined) { width = 1; } @@ -2067,22 +1985,20 @@ Phaser.BitmapData.prototype = { ctx.closePath(); return this; - }, /** - * Draws a polygon. - * - * @method Phaser.BitmapData#polygon - * @param {object[]} points - An array of {@link Phaser.Point} or point-like objects. - * @param {CanvasGradient|CanvasPattern|string} [fillStyle] - A color, gradient, or pattern. - * @param {number} [lineWidth=0] - The line thickness. - * @param {CanvasGradient|CanvasPattern|string} [strokeStyle='#fff'] - The line color, gradient, or pattern (when `lineWidth` > 0). - * @return {Phaser.BitmapData} This BitmapData object for method chaining. - */ + * Draws a polygon. + * + * @method Phaser.BitmapData#polygon + * @param {object[]} points - An array of {@link Phaser.Point} or point-like objects. + * @param {CanvasGradient|CanvasPattern|string} [fillStyle] - A color, gradient, or pattern. + * @param {number} [lineWidth=0] - The line thickness. + * @param {CanvasGradient|CanvasPattern|string} [strokeStyle='#fff'] - The line color, gradient, or pattern (when `lineWidth` > 0). + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ polygon: function (points, fillStyle, lineWidth, strokeStyle) { - // Could reject points.length < 3 if (strokeStyle === undefined) { strokeStyle = '#fff'; } @@ -2117,21 +2033,19 @@ Phaser.BitmapData.prototype = { if (lineWidth) { ctx.stroke(); } return this; - }, /** - * Takes the given Line object and image and renders it to this BitmapData as a repeating texture line. - * - * @method Phaser.BitmapData#textureLine - * @param {Phaser.Line} line - A Phaser.Line object that will be used to plot the start and end of the line. - * @param {string|Image} image - The key of an image in the Phaser.Cache to use as the texture for this line, or an actual Image. - * @param {string} [repeat='repeat-x'] - The pattern repeat mode to use when drawing the line. Either `repeat`, `repeat-x` or `no-repeat`. - * @return {Phaser.BitmapData} This BitmapData object for method chaining. - */ + * Takes the given Line object and image and renders it to this BitmapData as a repeating texture line. + * + * @method Phaser.BitmapData#textureLine + * @param {Phaser.Line} line - A Phaser.Line object that will be used to plot the start and end of the line. + * @param {string|Image} image - The key of an image in the Phaser.Cache to use as the texture for this line, or an actual Image. + * @param {string} [repeat='repeat-x'] - The pattern repeat mode to use when drawing the line. Either `repeat`, `repeat-x` or `no-repeat`. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ textureLine: function (line, image, repeat) { - if (repeat === undefined) { repeat = 'repeat-x'; } if (typeof image === 'string') @@ -2168,20 +2082,18 @@ Phaser.BitmapData.prototype = { this.dirty = true; return this; - }, /** - * If the game is running in WebGL this will push the texture up to the GPU if it's dirty. - * This is called automatically if the BitmapData is being used by a Sprite, otherwise you need to remember to call it in your render function. - * If you wish to suppress this functionality set BitmapData.disableTextureUpload to `true`. - * - * @method Phaser.BitmapData#render - * @return {Phaser.BitmapData} This BitmapData object for method chaining. - */ + * If the game is running in WebGL this will push the texture up to the GPU if it's dirty. + * This is called automatically if the BitmapData is being used by a Sprite, otherwise you need to remember to call it in your render function. + * If you wish to suppress this functionality set BitmapData.disableTextureUpload to `true`. + * + * @method Phaser.BitmapData#render + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ render: function () { - if (!this.disableTextureUpload && this.dirty) { this.baseTexture.dirty(); @@ -2189,404 +2101,348 @@ Phaser.BitmapData.prototype = { } return this; - }, /** - * Destroys this BitmapData and puts the canvas it was using back into the canvas pool for re-use. - * - * @method Phaser.BitmapData#destroy - */ + * Destroys this BitmapData and puts the canvas it was using back into the canvas pool for re-use. + * + * @method Phaser.BitmapData#destroy + */ destroy: function () { - this.frameData.destroy(); this.texture.destroy(true); Phaser.CanvasPool.remove(this); - }, /** - * Resets the blend mode (effectively sets it to 'source-over') - * - * @method Phaser.BitmapData#blendReset - * @return {Phaser.BitmapData} This BitmapData object for method chaining. - */ + * Resets the blend mode (effectively sets it to 'source-over') + * + * @method Phaser.BitmapData#blendReset + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ blendReset: function () { - this.op = 'source-over'; return this; - }, /** - * Sets the blend mode to 'source-over' - * - * @method Phaser.BitmapData#blendSourceOver - * @return {Phaser.BitmapData} This BitmapData object for method chaining. - */ + * Sets the blend mode to 'source-over' + * + * @method Phaser.BitmapData#blendSourceOver + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ blendSourceOver: function () { - this.op = 'source-over'; return this; - }, /** - * Sets the blend mode to 'source-in' - * - * @method Phaser.BitmapData#blendSourceIn - * @return {Phaser.BitmapData} This BitmapData object for method chaining. - */ + * Sets the blend mode to 'source-in' + * + * @method Phaser.BitmapData#blendSourceIn + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ blendSourceIn: function () { - this.op = 'source-in'; return this; - }, /** - * Sets the blend mode to 'source-out' - * - * @method Phaser.BitmapData#blendSourceOut - * @return {Phaser.BitmapData} This BitmapData object for method chaining. - */ + * Sets the blend mode to 'source-out' + * + * @method Phaser.BitmapData#blendSourceOut + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ blendSourceOut: function () { - this.op = 'source-out'; return this; - }, /** - * Sets the blend mode to 'source-atop' - * - * @method Phaser.BitmapData#blendSourceAtop - * @return {Phaser.BitmapData} This BitmapData object for method chaining. - */ + * Sets the blend mode to 'source-atop' + * + * @method Phaser.BitmapData#blendSourceAtop + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ blendSourceAtop: function () { - this.op = 'source-atop'; return this; - }, /** - * Sets the blend mode to 'destination-over' - * - * @method Phaser.BitmapData#blendDestinationOver - * @return {Phaser.BitmapData} This BitmapData object for method chaining. - */ + * Sets the blend mode to 'destination-over' + * + * @method Phaser.BitmapData#blendDestinationOver + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ blendDestinationOver: function () { - this.op = 'destination-over'; return this; - }, /** - * Sets the blend mode to 'destination-in' - * - * @method Phaser.BitmapData#blendDestinationIn - * @return {Phaser.BitmapData} This BitmapData object for method chaining. - */ + * Sets the blend mode to 'destination-in' + * + * @method Phaser.BitmapData#blendDestinationIn + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ blendDestinationIn: function () { - this.op = 'destination-in'; return this; - }, /** - * Sets the blend mode to 'destination-out' - * - * @method Phaser.BitmapData#blendDestinationOut - * @return {Phaser.BitmapData} This BitmapData object for method chaining. - */ + * Sets the blend mode to 'destination-out' + * + * @method Phaser.BitmapData#blendDestinationOut + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ blendDestinationOut: function () { - this.op = 'destination-out'; return this; - }, /** - * Sets the blend mode to 'destination-atop' - * - * @method Phaser.BitmapData#blendDestinationAtop - * @return {Phaser.BitmapData} This BitmapData object for method chaining. - */ + * Sets the blend mode to 'destination-atop' + * + * @method Phaser.BitmapData#blendDestinationAtop + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ blendDestinationAtop: function () { - this.op = 'destination-atop'; return this; - }, /** - * Sets the blend mode to 'xor' - * - * @method Phaser.BitmapData#blendXor - * @return {Phaser.BitmapData} This BitmapData object for method chaining. - */ + * Sets the blend mode to 'xor' + * + * @method Phaser.BitmapData#blendXor + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ blendXor: function () { - this.op = 'xor'; return this; - }, /** - * Sets the blend mode to 'lighter' - * - * @method Phaser.BitmapData#blendAdd - * @return {Phaser.BitmapData} This BitmapData object for method chaining. - */ + * Sets the blend mode to 'lighter' + * + * @method Phaser.BitmapData#blendAdd + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ blendAdd: function () { - this.op = 'lighter'; return this; - }, /** - * Sets the blend mode to 'multiply' - * - * @method Phaser.BitmapData#blendMultiply - * @return {Phaser.BitmapData} This BitmapData object for method chaining. - */ + * Sets the blend mode to 'multiply' + * + * @method Phaser.BitmapData#blendMultiply + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ blendMultiply: function () { - this.op = 'multiply'; return this; - }, /** - * Sets the blend mode to 'screen' - * - * @method Phaser.BitmapData#blendScreen - * @return {Phaser.BitmapData} This BitmapData object for method chaining. - */ + * Sets the blend mode to 'screen' + * + * @method Phaser.BitmapData#blendScreen + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ blendScreen: function () { - this.op = 'screen'; return this; - }, /** - * Sets the blend mode to 'overlay' - * - * @method Phaser.BitmapData#blendOverlay - * @return {Phaser.BitmapData} This BitmapData object for method chaining. - */ + * Sets the blend mode to 'overlay' + * + * @method Phaser.BitmapData#blendOverlay + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ blendOverlay: function () { - this.op = 'overlay'; return this; - }, /** - * Sets the blend mode to 'darken' - * - * @method Phaser.BitmapData#blendDarken - * @return {Phaser.BitmapData} This BitmapData object for method chaining. - */ + * Sets the blend mode to 'darken' + * + * @method Phaser.BitmapData#blendDarken + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ blendDarken: function () { - this.op = 'darken'; return this; - }, /** - * Sets the blend mode to 'lighten' - * - * @method Phaser.BitmapData#blendLighten - * @return {Phaser.BitmapData} This BitmapData object for method chaining. - */ + * Sets the blend mode to 'lighten' + * + * @method Phaser.BitmapData#blendLighten + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ blendLighten: function () { - this.op = 'lighten'; return this; - }, /** - * Sets the blend mode to 'color-dodge' - * - * @method Phaser.BitmapData#blendColorDodge - * @return {Phaser.BitmapData} This BitmapData object for method chaining. - */ + * Sets the blend mode to 'color-dodge' + * + * @method Phaser.BitmapData#blendColorDodge + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ blendColorDodge: function () { - this.op = 'color-dodge'; return this; - }, /** - * Sets the blend mode to 'color-burn' - * - * @method Phaser.BitmapData#blendColorBurn - * @return {Phaser.BitmapData} This BitmapData object for method chaining. - */ + * Sets the blend mode to 'color-burn' + * + * @method Phaser.BitmapData#blendColorBurn + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ blendColorBurn: function () { - this.op = 'color-burn'; return this; - }, /** - * Sets the blend mode to 'hard-light' - * - * @method Phaser.BitmapData#blendHardLight - * @return {Phaser.BitmapData} This BitmapData object for method chaining. - */ + * Sets the blend mode to 'hard-light' + * + * @method Phaser.BitmapData#blendHardLight + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ blendHardLight: function () { - this.op = 'hard-light'; return this; - }, /** - * Sets the blend mode to 'soft-light' - * - * @method Phaser.BitmapData#blendSoftLight - * @return {Phaser.BitmapData} This BitmapData object for method chaining. - */ + * Sets the blend mode to 'soft-light' + * + * @method Phaser.BitmapData#blendSoftLight + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ blendSoftLight: function () { - this.op = 'soft-light'; return this; - }, /** - * Sets the blend mode to 'difference' - * - * @method Phaser.BitmapData#blendDifference - * @return {Phaser.BitmapData} This BitmapData object for method chaining. - */ + * Sets the blend mode to 'difference' + * + * @method Phaser.BitmapData#blendDifference + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ blendDifference: function () { - this.op = 'difference'; return this; - }, /** - * Sets the blend mode to 'exclusion' - * - * @method Phaser.BitmapData#blendExclusion - * @return {Phaser.BitmapData} This BitmapData object for method chaining. - */ + * Sets the blend mode to 'exclusion' + * + * @method Phaser.BitmapData#blendExclusion + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ blendExclusion: function () { - this.op = 'exclusion'; return this; - }, /** - * Sets the blend mode to 'hue' - * - * @method Phaser.BitmapData#blendHue - * @return {Phaser.BitmapData} This BitmapData object for method chaining. - */ + * Sets the blend mode to 'hue' + * + * @method Phaser.BitmapData#blendHue + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ blendHue: function () { - this.op = 'hue'; return this; - }, /** - * Sets the blend mode to 'saturation' - * - * @method Phaser.BitmapData#blendSaturation - * @return {Phaser.BitmapData} This BitmapData object for method chaining. - */ + * Sets the blend mode to 'saturation' + * + * @method Phaser.BitmapData#blendSaturation + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ blendSaturation: function () { - this.op = 'saturation'; return this; - }, /** - * Sets the blend mode to 'color' - * - * @method Phaser.BitmapData#blendColor - * @return {Phaser.BitmapData} This BitmapData object for method chaining. - */ + * Sets the blend mode to 'color' + * + * @method Phaser.BitmapData#blendColor + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ blendColor: function () { - this.op = 'color'; return this; - }, /** - * Sets the blend mode to 'luminosity' - * - * @method Phaser.BitmapData#blendLuminosity - * @return {Phaser.BitmapData} This BitmapData object for method chaining. - */ + * Sets the blend mode to 'luminosity' + * + * @method Phaser.BitmapData#blendLuminosity + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ blendLuminosity: function () { - this.op = 'luminosity'; return this; - }, /** - * Updates a portion of the BitmapData from a source Bitmap. - * This optimization is important if calling update() on a large Bitmap is causing performance issues. - * Make sure you use getPixel32() instead of getPixel(). - * This does not work with floating point numbers for x and y. - * - * @method Phaser.BitmapData#copyBitmapData - * @param {Phaser.BitmapData} [source] - The BitmapData you wish to copy. - * @param {number} [x] - The x coordinate of the top-left of the area to copy. - * @param {number} [y] - The y coordinate of the top-left of the area to copy. - * @return {Phaser.BitmapData} This BitmapData object for method chaining. - */ + * Updates a portion of the BitmapData from a source Bitmap. + * This optimization is important if calling update() on a large Bitmap is causing performance issues. + * Make sure you use getPixel32() instead of getPixel(). + * This does not work with floating point numbers for x and y. + * + * @method Phaser.BitmapData#copyBitmapData + * @param {Phaser.BitmapData} [source] - The BitmapData you wish to copy. + * @param {number} [x] - The x coordinate of the top-left of the area to copy. + * @param {number} [y] - The y coordinate of the top-left of the area to copy. + * @return {Phaser.BitmapData} This BitmapData object for method chaining. + */ copyBitmapData: function (source, x, y) { - source.update(); for (var i = 0, destRowStart; i < source.height; i++) { @@ -2597,51 +2453,42 @@ Phaser.BitmapData.prototype = { } } return this; - } }; /** -* @name Phaser.BitmapData#smoothed -* @property {boolean} smoothed - Gets or sets this BitmapData.contexts smoothing enabled value. -*/ + * @name Phaser.BitmapData#smoothed + * @property {boolean} smoothed - Gets or sets this BitmapData.contexts smoothing enabled value. + */ Object.defineProperty(Phaser.BitmapData.prototype, 'smoothed', { get: function () { - return Phaser.Canvas.getSmoothingEnabled(this.context); - }, set: function (value) { - Phaser.Canvas.setSmoothingEnabled(this.context, value); - } }); /** -* @name Phaser.BitmapData#op -* @property {string} op - A short-hand code to get or set the global composite operation of the BitmapDatas canvas. -*/ + * @name Phaser.BitmapData#op + * @property {string} op - A short-hand code to get or set the global composite operation of the BitmapDatas canvas. + */ Object.defineProperty(Phaser.BitmapData.prototype, 'op', { get: function () { - return this.context.globalCompositeOperation; - }, set: function (value) { - this.context.globalCompositeOperation = value; - } }); @@ -2660,7 +2507,6 @@ Object.defineProperty(Phaser.BitmapData.prototype, 'op', { */ Phaser.BitmapData.getTransform = function (translateX, translateY, scaleX, scaleY, skewX, skewY) { - if (typeof translateX !== 'number') { translateX = 0; } if (typeof translateY !== 'number') { translateY = 0; } if (typeof scaleX !== 'number') { scaleX = 1; } @@ -2669,7 +2515,6 @@ Phaser.BitmapData.getTransform = function (translateX, translateY, scaleX, scale if (typeof skewY !== 'number') { skewY = 0; } return { sx: scaleX, sy: scaleY, scaleX: scaleX, scaleY: scaleY, skewX: skewX, skewY: skewY, translateX: translateX, translateY: translateY, tx: translateX, ty: translateY }; - }; Phaser.BitmapData.prototype.constructor = Phaser.BitmapData; diff --git a/src/gameobjects/BitmapText.js b/src/gameobjects/BitmapText.js index badd54a5a..e242f557c 100644 --- a/src/gameobjects/BitmapText.js +++ b/src/gameobjects/BitmapText.js @@ -1,59 +1,58 @@ /** -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* BitmapText objects work by taking a texture file and an XML or JSON file that describes the font structure. -* It then generates a new Sprite object for each letter of the text, proportionally spaced out and aligned to -* match the font structure. -* -* BitmapText objects are less flexible than Text objects, in that they have less features such as shadows, fills and the ability -* to use Web Fonts, however you trade this flexibility for rendering speed. You can also create visually compelling BitmapTexts by -* processing the font texture in an image editor, applying fills and any other effects required. -* -* To create multi-line text insert \r, \n or \r\n escape codes into the text string. -* -* If you are having performance issues due to the volume of sprites being rendered, and do not require the text to be constantly -* updating, you can use BitmapText.generateTexture to create a static texture from this BitmapText. -* -* To create a BitmapText data files you can use: -* -* BMFont (Windows, free): http://www.angelcode.com/products/bmfont/ -* Glyph Designer (OS X, commercial): http://www.71squared.com/en/glyphdesigner -* Littera (Web-based, free): http://kvazars.com/littera/ -* -* For most use cases it is recommended to use XML. If you wish to use JSON, the formatting should be equal to the result of -* converting a valid XML file through the popular X2JS library. An online tool for conversion can be found here: http://codebeautify.org/xmltojson -* -* If you were using an older version of Phaser (< 2.4) and using the DOMish parser hack, please remove this. It isn't required any longer. -* -* @class Phaser.BitmapText -* @constructor -* @extends PIXI.DisplayObjectContainer -* @extends Phaser.Component.Core -* @extends Phaser.Component.Angle -* @extends Phaser.Component.AutoCull -* @extends Phaser.Component.Bounds -* @extends Phaser.Component.Destroy -* @extends Phaser.Component.FixedToCamera -* @extends Phaser.Component.InputEnabled -* @extends Phaser.Component.InWorld -* @extends Phaser.Component.LifeSpan -* @extends Phaser.Component.PhysicsBody -* @extends Phaser.Component.Reset -* @param {Phaser.Game} game - A reference to the currently running game. -* @param {number} x - X coordinate to display the BitmapText object at. -* @param {number} y - Y coordinate to display the BitmapText object at. -* @param {string} font - The key of the BitmapText as stored in Phaser.Cache. -* @param {string} [text=''] - The text that will be rendered. This can also be set later via BitmapText.text. -* @param {number} [size=32] - The size the font will be rendered at in pixels. -* @param {string} [align='left'] - The alignment of multi-line text. Has no effect if there is only one line of text. -*/ + * BitmapText objects work by taking a texture file and an XML or JSON file that describes the font structure. + * It then generates a new Sprite object for each letter of the text, proportionally spaced out and aligned to + * match the font structure. + * + * BitmapText objects are less flexible than Text objects, in that they have less features such as shadows, fills and the ability + * to use Web Fonts, however you trade this flexibility for rendering speed. You can also create visually compelling BitmapTexts by + * processing the font texture in an image editor, applying fills and any other effects required. + * + * To create multi-line text insert \r, \n or \r\n escape codes into the text string. + * + * If you are having performance issues due to the volume of sprites being rendered, and do not require the text to be constantly + * updating, you can use BitmapText.generateTexture to create a static texture from this BitmapText. + * + * To create a BitmapText data files you can use: + * + * BMFont (Windows, free): http://www.angelcode.com/products/bmfont/ + * Glyph Designer (OS X, commercial): http://www.71squared.com/en/glyphdesigner + * Littera (Web-based, free): http://kvazars.com/littera/ + * + * For most use cases it is recommended to use XML. If you wish to use JSON, the formatting should be equal to the result of + * converting a valid XML file through the popular X2JS library. An online tool for conversion can be found here: http://codebeautify.org/xmltojson + * + * If you were using an older version of Phaser (< 2.4) and using the DOMish parser hack, please remove this. It isn't required any longer. + * + * @class Phaser.BitmapText + * @constructor + * @extends PIXI.DisplayObjectContainer + * @extends Phaser.Component.Core + * @extends Phaser.Component.Angle + * @extends Phaser.Component.AutoCull + * @extends Phaser.Component.Bounds + * @extends Phaser.Component.Destroy + * @extends Phaser.Component.FixedToCamera + * @extends Phaser.Component.InputEnabled + * @extends Phaser.Component.InWorld + * @extends Phaser.Component.LifeSpan + * @extends Phaser.Component.PhysicsBody + * @extends Phaser.Component.Reset + * @param {Phaser.Game} game - A reference to the currently running game. + * @param {number} x - X coordinate to display the BitmapText object at. + * @param {number} y - Y coordinate to display the BitmapText object at. + * @param {string} font - The key of the BitmapText as stored in Phaser.Cache. + * @param {string} [text=''] - The text that will be rendered. This can also be set later via BitmapText.text. + * @param {number} [size=32] - The size the font will be rendered at in pixels. + * @param {string} [align='left'] - The alignment of multi-line text. Has no effect if there is only one line of text. + */ Phaser.BitmapText = function (game, x, y, font, text, size, align) { - x = x || 0; y = y || 0; font = font || ''; @@ -64,103 +63,102 @@ Phaser.BitmapText = function (game, x, y, font, text, size, align) PIXI.DisplayObjectContainer.call(this); /** - * @property {number} type - The const type of this object. - * @readonly - */ + * @property {number} type - The const type of this object. + * @readonly + */ this.type = Phaser.BITMAPTEXT; /** - * @property {number} physicsType - The const physics body type of this object. - * @readonly - */ + * @property {number} physicsType - The const physics body type of this object. + * @readonly + */ this.physicsType = Phaser.SPRITE; /** - * @property {number} textWidth - The width in pixels of the overall text area, taking into consideration multi-line text. - * @readOnly - */ + * @property {number} textWidth - The width in pixels of the overall text area, taking into consideration multi-line text. + * @readOnly + */ this.textWidth = 0; /** - * @property {number} textHeight - The height in pixels of the overall text area, taking into consideration multi-line text. - * @readOnly - */ + * @property {number} textHeight - The height in pixels of the overall text area, taking into consideration multi-line text. + * @readOnly + */ this.textHeight = 0; /** - * @property {Phaser.Point} anchor - The anchor value of this BitmapText. - */ + * @property {Phaser.Point} anchor - The anchor value of this BitmapText. + */ this.anchor = new Phaser.Point(); /** - * @property {Phaser.Point} _prevAnchor - The previous anchor value. - * @private - */ + * @property {Phaser.Point} _prevAnchor - The previous anchor value. + * @private + */ this._prevAnchor = new Phaser.Point(); /** - * @property {array} _glyphs - Private tracker for the letter sprite pool. - * @private - */ + * @property {array} _glyphs - Private tracker for the letter sprite pool. + * @private + */ this._glyphs = []; /** - * @property {number} _maxWidth - Internal cache var. - * @private - */ + * @property {number} _maxWidth - Internal cache var. + * @private + */ this._maxWidth = 0; /** - * @property {string} _text - Internal cache var. - * @private - */ + * @property {string} _text - Internal cache var. + * @private + */ this._text = text.toString() || ''; /** - * @property {string} _data - Internal cache var. - * @private - */ + * @property {string} _data - Internal cache var. + * @private + */ this._data = game.cache.getBitmapFont(font); /** - * @property {string} _font - Internal cache var. - * @private - */ + * @property {string} _font - Internal cache var. + * @private + */ this._font = font; /** - * @property {number} _fontSize - Internal cache var. - * @private - */ + * @property {number} _fontSize - Internal cache var. + * @private + */ this._fontSize = size; /** - * @property {string} _align - Internal cache var. - * @private - */ + * @property {string} _align - Internal cache var. + * @private + */ this._align = align; /** - * @property {number} _letterSpacing - Internal cache var. - * @private - */ + * @property {number} _letterSpacing - Internal cache var. + * @private + */ this._letterSpacing = 0; /** - * @property {number} _tint - Internal cache var. - * @private - */ + * @property {number} _tint - Internal cache var. + * @private + */ this._tint = 0xFFFFFF; this.updateText(); /** - * @property {boolean} dirty - The dirty state of this object. - */ + * @property {boolean} dirty - The dirty state of this object. + */ this.dirty = false; Phaser.Component.Core.init.call(this, game, x, y, '', null); - }; Phaser.BitmapText.prototype = Object.create(PIXI.DisplayObjectContainer.prototype); @@ -185,31 +183,28 @@ Phaser.BitmapText.prototype.preUpdateInWorld = Phaser.Component.InWorld.preUpdat Phaser.BitmapText.prototype.preUpdateCore = Phaser.Component.Core.preUpdate; /** -* Automatically called by World.preUpdate. -* -* @method -* @memberof Phaser.BitmapText -* @return {boolean} True if the BitmapText was rendered, otherwise false. -*/ + * Automatically called by World.preUpdate. + * + * @method + * @memberof Phaser.BitmapText + * @return {boolean} True if the BitmapText was rendered, otherwise false. + */ Phaser.BitmapText.prototype.preUpdate = function () { - if (!this.preUpdatePhysics() || !this.preUpdateLifeSpan() || !this.preUpdateInWorld()) { return false; } return this.preUpdateCore(); - }; /** -* Automatically called by World.preUpdate. -* @method Phaser.BitmapText.prototype.postUpdate -*/ + * Automatically called by World.preUpdate. + * @method Phaser.BitmapText.prototype.postUpdate + */ Phaser.BitmapText.prototype.postUpdate = function () { - Phaser.Component.PhysicsBody.postUpdate.call(this); Phaser.Component.FixedToCamera.postUpdate.call(this); @@ -220,38 +215,34 @@ Phaser.BitmapText.prototype.postUpdate = function () this.body.setSize(this.textWidth, this.textHeight); } } - }; /** -* The text to be displayed by this BitmapText object. -* -* It's faster to use `BitmapText.text = string`, but this is kept for backwards compatibility. -* -* @method Phaser.BitmapText.prototype.setText -* @param {string} text - The text to be displayed by this BitmapText object. -*/ + * The text to be displayed by this BitmapText object. + * + * It's faster to use `BitmapText.text = string`, but this is kept for backwards compatibility. + * + * @method Phaser.BitmapText.prototype.setText + * @param {string} text - The text to be displayed by this BitmapText object. + */ Phaser.BitmapText.prototype.setText = function (text) { - this.text = text; - }; /** -* Given the input text this will scan the characters until either a newline is encountered, -* or the line exceeds maxWidth, taking into account kerning, character widths and scaling. -* -* @method Phaser.BitmapText.prototype.scanLine -* @private -* @param {object} data - A reference to the font object in the Phaser.Cache. -* @param {float} scale - The scale of the font in relation to the texture. -* @param {string} text - The text to parse. -* @return {object} An object containing the parsed characters, total pixel width and x offsets. -*/ + * Given the input text this will scan the characters until either a newline is encountered, + * or the line exceeds maxWidth, taking into account kerning, character widths and scaling. + * + * @method Phaser.BitmapText.prototype.scanLine + * @private + * @param {object} data - A reference to the font object in the Phaser.Cache. + * @param {float} scale - The scale of the font in relation to the texture. + * @param {string} text - The text to parse. + * @return {object} An object containing the parsed characters, total pixel width and x offsets. + */ Phaser.BitmapText.prototype.scanLine = function (data, scale, text) { - var x = 0; var w = 0; var lastSpace = -1; @@ -276,8 +267,10 @@ Phaser.BitmapText.prototype.scanLine = function (data, scale, text) var c = 0; - // If the character data isn't found in the data array - // then we replace it with a blank space + /* + * If the character data isn't found in the data array + * then we replace it with a blank space + */ if (charData === undefined) { charCode = 32; @@ -317,23 +310,21 @@ Phaser.BitmapText.prototype.scanLine = function (data, scale, text) } return { width: w, text: text, end: end, chars: chars }; - }; /** -* Given a text string this will scan each character in the string to ensure it exists -* in the BitmapText font data. If it doesn't the character is removed, or replaced with the `replace` argument. -* -* If no font data has been loaded at all this returns an empty string, as nothing can be rendered. -* -* @method Phaser.BitmapText.prototype.cleanText -* @param {string} text - The text to parse. -* @param {string} [replace=''] - The replacement string for any missing characters. -* @return {string} The cleaned text string. -*/ + * Given a text string this will scan each character in the string to ensure it exists + * in the BitmapText font data. If it doesn't the character is removed, or replaced with the `replace` argument. + * + * If no font data has been loaded at all this returns an empty string, as nothing can be rendered. + * + * @method Phaser.BitmapText.prototype.cleanText + * @param {string} text - The text to parse. + * @param {string} [replace=''] - The replacement string for any missing characters. + * @return {string} The cleaned text string. + */ Phaser.BitmapText.prototype.cleanText = function (text, replace) { - if (replace === undefined) { replace = ''; @@ -370,18 +361,16 @@ Phaser.BitmapText.prototype.cleanText = function (text, replace) } return lines.join('\n'); - }; /** -* Renders text and updates it when needed. -* -* @method Phaser.BitmapText.prototype.updateText -* @private -*/ + * Renders text and updates it when needed. + * + * @method Phaser.BitmapText.prototype.updateText + * @private + */ Phaser.BitmapText.prototype.updateText = function () { - var data = this._data.font; if (!data) @@ -413,7 +402,6 @@ Phaser.BitmapText.prototype.updateText = function () y += (data.lineHeight * scale); text = text.substr(line.text.length + 1); - } while (line.end === false); this.textHeight = y; @@ -479,31 +467,31 @@ Phaser.BitmapText.prototype.updateText = function () } } - // Remove unnecessary children - // This moves them from the display list (children array) but retains them in the _glyphs pool + /* + * Remove unnecessary children + * This moves them from the display list (children array) but retains them in the _glyphs pool + */ for (i = t; i < this._glyphs.length; i++) { this.removeChild(this._glyphs[i]); } - }; /** -* If a BitmapText changes from having a large number of characters to having very few characters it will cause lots of -* Sprites to be retained in the BitmapText._glyphs array. Although they are not attached to the display list they -* still take up memory while sat in the glyphs pool waiting to be re-used in the future. -* -* If you know that the BitmapText will not grow any larger then you can purge out the excess glyphs from the pool -* by calling this method. -* -* Calling this doesn't prevent you from increasing the length of the text again in the future. -* -* @method Phaser.BitmapText.prototype.purgeGlyphs -* @return {integer} The amount of glyphs removed from the pool. -*/ + * If a BitmapText changes from having a large number of characters to having very few characters it will cause lots of + * Sprites to be retained in the BitmapText._glyphs array. Although they are not attached to the display list they + * still take up memory while sat in the glyphs pool waiting to be re-used in the future. + * + * If you know that the BitmapText will not grow any larger then you can purge out the excess glyphs from the pool + * by calling this method. + * + * Calling this doesn't prevent you from increasing the length of the text again in the future. + * + * @method Phaser.BitmapText.prototype.purgeGlyphs + * @return {integer} The amount of glyphs removed from the pool. + */ Phaser.BitmapText.prototype.purgeGlyphs = function () { - var len = this._glyphs.length; var kept = []; @@ -525,18 +513,16 @@ Phaser.BitmapText.prototype.purgeGlyphs = function () this.updateText(); return len - kept.length; - }; /** -* Updates the transform of this object. -* -* @method Phaser.BitmapText.prototype.updateTransform -* @private -*/ + * Updates the transform of this object. + * + * @method Phaser.BitmapText.prototype.updateTransform + * @private + */ Phaser.BitmapText.prototype.updateTransform = function () { - if (this.dirty || !this.anchor.equals(this._prevAnchor)) { this.updateText(); @@ -545,13 +531,12 @@ Phaser.BitmapText.prototype.updateTransform = function () } PIXI.DisplayObjectContainer.prototype.updateTransform.call(this); - }; /** -* @name Phaser.BitmapText#letterSpacing -* @property {string} letterSpacing - Sets the letter spacing between each character of this Bitmap Text. Can be a positive value to increase the space, or negative to reduce it. Spacing is applied after the kerning values have been set. -*/ + * @name Phaser.BitmapText#letterSpacing + * @property {string} letterSpacing - Sets the letter spacing between each character of this Bitmap Text. Can be a positive value to increase the space, or negative to reduce it. Spacing is applied after the kerning values have been set. + */ Object.defineProperty(Phaser.BitmapText.prototype, 'letterSpacing', { get: function () @@ -561,21 +546,19 @@ Object.defineProperty(Phaser.BitmapText.prototype, 'letterSpacing', { set: function (value) { - if (typeof(value) === 'number') { this._letterSpacing = value; this.updateText(); } - } }); /** -* @name Phaser.BitmapText#align -* @property {string} align - Alignment for multi-line text ('left', 'center' or 'right'), does not affect single lines of text. -*/ + * @name Phaser.BitmapText#align + * @property {string} align - Alignment for multi-line text ('left', 'center' or 'right'), does not affect single lines of text. + */ Object.defineProperty(Phaser.BitmapText.prototype, 'align', { get: function () @@ -585,21 +568,19 @@ Object.defineProperty(Phaser.BitmapText.prototype, 'align', { set: function (value) { - if (value !== this._align && (value === 'left' || value === 'center' || value === 'right')) { this._align = value; this.updateText(); } - } }); /** -* @name Phaser.BitmapText#tint -* @property {number} tint - The tint applied to the BitmapText. This is a hex value. Set to white to disable (0xFFFFFF) -*/ + * @name Phaser.BitmapText#tint + * @property {number} tint - The tint applied to the BitmapText. This is a hex value. Set to white to disable (0xFFFFFF) + */ Object.defineProperty(Phaser.BitmapText.prototype, 'tint', { get: function () @@ -609,21 +590,19 @@ Object.defineProperty(Phaser.BitmapText.prototype, 'tint', { set: function (value) { - if (value !== this._tint) { this._tint = value; this.updateText(); } - } }); /** -* @name Phaser.BitmapText#font -* @property {string} font - The font the text will be rendered in, i.e. 'Arial'. Must be loaded in the browser before use. -*/ + * @name Phaser.BitmapText#font + * @property {string} font - The font the text will be rendered in, i.e. 'Arial'. Must be loaded in the browser before use. + */ Object.defineProperty(Phaser.BitmapText.prototype, 'font', { get: function () @@ -633,22 +612,20 @@ Object.defineProperty(Phaser.BitmapText.prototype, 'font', { set: function (value) { - if (value !== this._font) { this._font = value.trim(); this._data = this.game.cache.getBitmapFont(this._font); this.updateText(); } - } }); /** -* @name Phaser.BitmapText#fontSize -* @property {number} fontSize - The size of the font in pixels. -*/ + * @name Phaser.BitmapText#fontSize + * @property {number} fontSize - The size of the font in pixels. + */ Object.defineProperty(Phaser.BitmapText.prototype, 'fontSize', { get: function () @@ -658,7 +635,6 @@ Object.defineProperty(Phaser.BitmapText.prototype, 'fontSize', { set: function (value) { - value = parseInt(value, 10); if (value !== this._fontSize && value > 0) @@ -666,15 +642,14 @@ Object.defineProperty(Phaser.BitmapText.prototype, 'fontSize', { this._fontSize = value; this.updateText(); } - } }); /** -* @name Phaser.BitmapText#text -* @property {string} text - The text to be displayed by this BitmapText object. -*/ + * @name Phaser.BitmapText#text + * @property {string} text - The text to be displayed by this BitmapText object. + */ Object.defineProperty(Phaser.BitmapText.prototype, 'text', { get: function () @@ -684,74 +659,65 @@ Object.defineProperty(Phaser.BitmapText.prototype, 'text', { set: function (value) { - if (value !== this._text) { this._text = value.toString() || ''; this.updateText(); } - } }); /** -* The maximum display width of this BitmapText in pixels. -* -* If BitmapText.text is longer than maxWidth then the lines will be automatically wrapped -* based on the last whitespace character found in the line. -* -* If no whitespace was found then no wrapping will take place and consequently the maxWidth value will not be honored. -* -* Disable maxWidth by setting the value to 0. -* -* @name Phaser.BitmapText#maxWidth -* @property {number} maxWidth - The maximum width of this BitmapText in pixels. -*/ + * The maximum display width of this BitmapText in pixels. + * + * If BitmapText.text is longer than maxWidth then the lines will be automatically wrapped + * based on the last whitespace character found in the line. + * + * If no whitespace was found then no wrapping will take place and consequently the maxWidth value will not be honored. + * + * Disable maxWidth by setting the value to 0. + * + * @name Phaser.BitmapText#maxWidth + * @property {number} maxWidth - The maximum width of this BitmapText in pixels. + */ Object.defineProperty(Phaser.BitmapText.prototype, 'maxWidth', { get: function () { - return this._maxWidth; - }, set: function (value) { - if (value !== this._maxWidth) { this._maxWidth = value; this.updateText(); } - } }); /** -* Enable or disable texture smoothing for this BitmapText. -* -* The smoothing is applied to the BaseTexture of this font, which all letters of the text reference. -* -* Smoothing is enabled by default. -* -* @name Phaser.BitmapText#smoothed -* @property {boolean} smoothed -*/ + * Enable or disable texture smoothing for this BitmapText. + * + * The smoothing is applied to the BaseTexture of this font, which all letters of the text reference. + * + * Smoothing is enabled by default. + * + * @name Phaser.BitmapText#smoothed + * @property {boolean} smoothed + */ Object.defineProperty(Phaser.BitmapText.prototype, 'smoothed', { get: function () { - return !this._data.base.scaleMode; - }, set: function (value) { - if (value) { this._data.base.scaleMode = 0; @@ -761,7 +727,6 @@ Object.defineProperty(Phaser.BitmapText.prototype, 'smoothed', { this._data.base.scaleMode = 1; } this._data.base.dirty(); - } }); diff --git a/src/gameobjects/Button.js b/src/gameobjects/Button.js index 9091df1b3..3703bd8b6 100644 --- a/src/gameobjects/Button.js +++ b/src/gameobjects/Button.js @@ -1,40 +1,39 @@ /** -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* Create a new `Button` object. A Button is a special type of Sprite that is set-up to handle Pointer events automatically. -* -* The four states a Button responds to are: -* -* * 'Over' - when the Pointer moves over the Button. This is also commonly known as 'hover'. -* * 'Out' - when the Pointer that was previously over the Button moves out of it. -* * 'Down' - when the Pointer is pressed down on the Button. I.e. touched on a touch enabled device or clicked with the mouse. -* * 'Up' - when the Pointer that was pressed down on the Button is released again. -* -* A different texture/frame and activation sound can be specified for any of the states. -* -* Frames can be specified as either an integer (the frame ID) or a string (the frame name); the same values that can be used with a Sprite constructor. -* -* @class Phaser.Button -* @constructor -* @extends Phaser.Image -* @param {Phaser.Game} game Current game instance. -* @param {number} [x=0] - X position of the Button. -* @param {number} [y=0] - Y position of the Button. -* @param {string} [key] - The image key (in the Game.Cache) to use as the texture for this Button. -* @param {function} [callback] - The function to call when this Button is pressed, receiving `this` (the Button), `pointer` (the Pointer causing the input), and `isOver` (whether the Pointer is still on the Button). See {@link Phaser.Events#onInputUp}. -* @param {object} [callbackContext] - The context in which the callback will be called (usually 'this'). -* @param {string|integer} [overFrame] - The frame / frameName when the button is in the Over state. -* @param {string|integer} [outFrame] - The frame / frameName when the button is in the Out state. -* @param {string|integer} [downFrame] - The frame / frameName when the button is in the Down state. -* @param {string|integer} [upFrame] - The frame / frameName when the button is in the Up state. -*/ + * Create a new `Button` object. A Button is a special type of Sprite that is set-up to handle Pointer events automatically. + * + * The four states a Button responds to are: + * + * * 'Over' - when the Pointer moves over the Button. This is also commonly known as 'hover'. + * * 'Out' - when the Pointer that was previously over the Button moves out of it. + * * 'Down' - when the Pointer is pressed down on the Button. I.e. touched on a touch enabled device or clicked with the mouse. + * * 'Up' - when the Pointer that was pressed down on the Button is released again. + * + * A different texture/frame and activation sound can be specified for any of the states. + * + * Frames can be specified as either an integer (the frame ID) or a string (the frame name); the same values that can be used with a Sprite constructor. + * + * @class Phaser.Button + * @constructor + * @extends Phaser.Image + * @param {Phaser.Game} game Current game instance. + * @param {number} [x=0] - X position of the Button. + * @param {number} [y=0] - Y position of the Button. + * @param {string} [key] - The image key (in the Game.Cache) to use as the texture for this Button. + * @param {function} [callback] - The function to call when this Button is pressed, receiving `this` (the Button), `pointer` (the Pointer causing the input), and `isOver` (whether the Pointer is still on the Button). See {@link Phaser.Events#onInputUp}. + * @param {object} [callbackContext] - The context in which the callback will be called (usually 'this'). + * @param {string|integer} [overFrame] - The frame / frameName when the button is in the Over state. + * @param {string|integer} [outFrame] - The frame / frameName when the button is in the Out state. + * @param {string|integer} [downFrame] - The frame / frameName when the button is in the Down state. + * @param {string|integer} [upFrame] - The frame / frameName when the button is in the Up state. + */ Phaser.Button = function (game, x, y, key, callback, callbackContext, overFrame, outFrame, downFrame, upFrame) { - x = x || 0; y = y || 0; key = key || null; @@ -44,163 +43,163 @@ Phaser.Button = function (game, x, y, key, callback, callbackContext, overFrame, Phaser.Image.call(this, game, x, y, key, outFrame); /** - * The Phaser Object Type. - * @property {number} type - * @readonly - */ + * The Phaser Object Type. + * @property {number} type + * @readonly + */ this.type = Phaser.BUTTON; /** - * @property {number} physicsType - The const physics body type of this object. - * @readonly - */ + * @property {number} physicsType - The const physics body type of this object. + * @readonly + */ this.physicsType = Phaser.SPRITE; /** - * The name or ID of the Over state frame. - * @property {string|integer} onOverFrame - * @private - */ + * The name or ID of the Over state frame. + * @property {string|integer} onOverFrame + * @private + */ this._onOverFrame = null; /** - * The name or ID of the Out state frame. - * @property {string|integer} onOutFrame - * @private - */ + * The name or ID of the Out state frame. + * @property {string|integer} onOutFrame + * @private + */ this._onOutFrame = null; /** - * The name or ID of the Down state frame. - * @property {string|integer} onDownFrame - * @private - */ + * The name or ID of the Down state frame. + * @property {string|integer} onDownFrame + * @private + */ this._onDownFrame = null; /** - * The name or ID of the Up state frame. - * @property {string|integer} onUpFrame - * @private - */ + * The name or ID of the Up state frame. + * @property {string|integer} onUpFrame + * @private + */ this._onUpFrame = null; /** - * The Sound to be played when this Buttons Over state is activated. - * @property {Phaser.Sound|Phaser.AudioSprite|null} onOverSound - * @readonly - */ + * The Sound to be played when this Buttons Over state is activated. + * @property {Phaser.Sound|Phaser.AudioSprite|null} onOverSound + * @readonly + */ this.onOverSound = null; /** - * The Sound to be played when this Buttons Out state is activated. - * @property {Phaser.Sound|Phaser.AudioSprite|null} onOutSound - * @readonly - */ + * The Sound to be played when this Buttons Out state is activated. + * @property {Phaser.Sound|Phaser.AudioSprite|null} onOutSound + * @readonly + */ this.onOutSound = null; /** - * The Sound to be played when this Buttons Down state is activated. - * @property {Phaser.Sound|Phaser.AudioSprite|null} onDownSound - * @readonly - */ + * The Sound to be played when this Buttons Down state is activated. + * @property {Phaser.Sound|Phaser.AudioSprite|null} onDownSound + * @readonly + */ this.onDownSound = null; /** - * The Sound to be played when this Buttons Up state is activated. - * @property {Phaser.Sound|Phaser.AudioSprite|null} onUpSound - * @readonly - */ + * The Sound to be played when this Buttons Up state is activated. + * @property {Phaser.Sound|Phaser.AudioSprite|null} onUpSound + * @readonly + */ this.onUpSound = null; /** - * The Sound Marker used in conjunction with the onOverSound. - * @property {string} onOverSoundMarker - * @readonly - */ + * The Sound Marker used in conjunction with the onOverSound. + * @property {string} onOverSoundMarker + * @readonly + */ this.onOverSoundMarker = ''; /** - * The Sound Marker used in conjunction with the onOutSound. - * @property {string} onOutSoundMarker - * @readonly - */ + * The Sound Marker used in conjunction with the onOutSound. + * @property {string} onOutSoundMarker + * @readonly + */ this.onOutSoundMarker = ''; /** - * The Sound Marker used in conjunction with the onDownSound. - * @property {string} onDownSoundMarker - * @readonly - */ + * The Sound Marker used in conjunction with the onDownSound. + * @property {string} onDownSoundMarker + * @readonly + */ this.onDownSoundMarker = ''; /** - * The Sound Marker used in conjunction with the onUpSound. - * @property {string} onUpSoundMarker - * @readonly - */ + * The Sound Marker used in conjunction with the onUpSound. + * @property {string} onUpSoundMarker + * @readonly + */ this.onUpSoundMarker = ''; /** - * The Signal (or event) dispatched when this Button is in an Over state. - * @property {Phaser.Signal} onInputOver - * @see Phaser.Events#onInputOver - */ + * The Signal (or event) dispatched when this Button is in an Over state. + * @property {Phaser.Signal} onInputOver + * @see Phaser.Events#onInputOver + */ this.onInputOver = new Phaser.Signal(); /** - * The Signal (or event) dispatched when this Button is in an Out state. - * @property {Phaser.Signal} onInputOut - * @see Phaser.Events#onInputOut - */ + * The Signal (or event) dispatched when this Button is in an Out state. + * @property {Phaser.Signal} onInputOut + * @see Phaser.Events#onInputOut + */ this.onInputOut = new Phaser.Signal(); /** - * The Signal (or event) dispatched when this Button is in an Down state. - * @property {Phaser.Signal} onInputDown - * @see Phaser.Events#onInputDown - */ + * The Signal (or event) dispatched when this Button is in an Down state. + * @property {Phaser.Signal} onInputDown + * @see Phaser.Events#onInputDown + */ this.onInputDown = new Phaser.Signal(); /** - * The Signal (or event) dispatched when this Button is in an Up state. - * @property {Phaser.Signal} onInputUp - * @see Phaser.Events#onInputUp - */ + * The Signal (or event) dispatched when this Button is in an Up state. + * @property {Phaser.Signal} onInputUp + * @see Phaser.Events#onInputUp + */ this.onInputUp = new Phaser.Signal(); /** - * If true then onOver events (such as onOverSound) will only be triggered if the Pointer object causing them was the Mouse Pointer. - * The frame will still be changed as applicable. - * - * @property {boolean} onOverMouseOnly - * @default - */ + * If true then onOver events (such as onOverSound) will only be triggered if the Pointer object causing them was the Mouse Pointer. + * The frame will still be changed as applicable. + * + * @property {boolean} onOverMouseOnly + * @default + */ this.onOverMouseOnly = true; /** - * Suppress the over event if a pointer was just released and it matches the given {@link Phaser.PointerModer pointer mode bitmask}. - * - * This behavior was introduced in Phaser 2.3.1; this property is a soft-revert of the change. - * - * @property {Phaser.PointerMode?} justReleasedPreventsOver=ACTIVE_CURSOR - */ + * Suppress the over event if a pointer was just released and it matches the given {@link Phaser.PointerModer pointer mode bitmask}. + * + * This behavior was introduced in Phaser 2.3.1; this property is a soft-revert of the change. + * + * @property {Phaser.PointerMode?} justReleasedPreventsOver=ACTIVE_CURSOR + */ this.justReleasedPreventsOver = Phaser.PointerMode.CONTACT; /** - * When true the the texture frame will not be automatically switched on up/down/over/out events. - * @property {boolean} freezeFrames - * @default - */ + * When true the the texture frame will not be automatically switched on up/down/over/out events. + * @property {boolean} freezeFrames + * @default + */ this.freezeFrames = false; /** - * When the Button is touched / clicked and then released you can force it to enter a state of "out" instead of "up". - * - * This can also accept a {@link Phaser.PointerModer pointer mode bitmask} for more refined control. - * - * @property {boolean|Phaser.PointerMode} forceOut=false - * @default - */ + * When the Button is touched / clicked and then released you can force it to enter a state of "out" instead of "up". + * + * This can also accept a {@link Phaser.PointerModer pointer mode bitmask} for more refined control. + * + * @property {boolean|Phaser.PointerMode} forceOut=false + * @default + */ this.forceOut = false; this.inputEnabled = true; @@ -221,7 +220,6 @@ Phaser.Button = function (game, x, y, key, callback, callbackContext, overFrame, this.events.onInputOut.add(this.onInputOutHandler, this); this.events.onInputDown.add(this.onInputDownHandler, this); this.events.onInputUp.add(this.onInputUpHandler, this); - }; Phaser.Button.prototype = Object.create(Phaser.Image.prototype); @@ -234,26 +232,24 @@ var STATE_DOWN = 'Down'; var STATE_UP = 'Up'; /** -* Clears all of the frames set on this Button. -* -* @method Phaser.Button#clearFrames -*/ + * Clears all of the frames set on this Button. + * + * @method Phaser.Button#clearFrames + */ Phaser.Button.prototype.clearFrames = function () { - this.setFrames(null, null, null, null); - }; /** -* Set the frame name/ID for the given state. -* -* @method Phaser.Button#setStateFrame -* @private -* @param {object} state - See `STATE_*` -* @param {number|string} frame - The number or string representing the frame. -* @param {boolean} switchImmediately - Immediately switch to the frame if it was set - and this is true. -*/ + * Set the frame name/ID for the given state. + * + * @method Phaser.Button#setStateFrame + * @private + * @param {object} state - See `STATE_*` + * @param {number|string} frame - The number or string representing the frame. + * @param {boolean} switchImmediately - Immediately switch to the frame if it was set - and this is true. + */ Phaser.Button.prototype.setStateFrame = function (state, frame, switchImmediately) { var frameKey = '_on' + state + 'Frame'; @@ -271,20 +267,18 @@ Phaser.Button.prototype.setStateFrame = function (state, frame, switchImmediatel { this[frameKey] = null; } - }; /** -* Change the frame to that of the given state, _if_ the state has a frame assigned _and_ if the frames are not currently "frozen". -* -* @method Phaser.Button#changeStateFrame -* @private -* @param {object} state - See `STATE_*` -* @return {boolean} True only if the frame was assigned a value, possibly the same one it already had. -*/ + * Change the frame to that of the given state, _if_ the state has a frame assigned _and_ if the frames are not currently "frozen". + * + * @method Phaser.Button#changeStateFrame + * @private + * @param {object} state - See `STATE_*` + * @return {boolean} True only if the frame was assigned a value, possibly the same one it already had. + */ Phaser.Button.prototype.changeStateFrame = function (state) { - if (this.freezeFrames) { return false; @@ -307,43 +301,39 @@ Phaser.Button.prototype.changeStateFrame = function (state) { return false; } - }; /** -* Used to manually set the frames that will be used for the different states of the Button. -* -* Frames can be specified as either an integer (the frame ID) or a string (the frame name); these are the same values that can be used with a Sprite constructor. -* -* @method Phaser.Button#setFrames -* @public -* @param {string|integer} [overFrame] - The frame / frameName when the button is in the Over state. -* @param {string|integer} [outFrame] - The frame / frameName when the button is in the Out state. -* @param {string|integer} [downFrame] - The frame / frameName when the button is in the Down state. -* @param {string|integer} [upFrame] - The frame / frameName when the button is in the Up state. -*/ + * Used to manually set the frames that will be used for the different states of the Button. + * + * Frames can be specified as either an integer (the frame ID) or a string (the frame name); these are the same values that can be used with a Sprite constructor. + * + * @method Phaser.Button#setFrames + * @public + * @param {string|integer} [overFrame] - The frame / frameName when the button is in the Over state. + * @param {string|integer} [outFrame] - The frame / frameName when the button is in the Out state. + * @param {string|integer} [downFrame] - The frame / frameName when the button is in the Down state. + * @param {string|integer} [upFrame] - The frame / frameName when the button is in the Up state. + */ Phaser.Button.prototype.setFrames = function (overFrame, outFrame, downFrame, upFrame) { - this.setStateFrame(STATE_OVER, overFrame, this.input.pointerOver()); this.setStateFrame(STATE_OUT, outFrame, !this.input.pointerOver()); this.setStateFrame(STATE_DOWN, downFrame, this.input.pointerDown()); this.setStateFrame(STATE_UP, upFrame, this.input.pointerUp()); - }; /** -* Set the sound/marker for the given state. -* -* @method Phaser.Button#setStateSound -* @private -* @param {object} state - See `STATE_*` -* @param {Phaser.Sound|Phaser.AudioSprite} [sound] - Sound. -* @param {string} [marker=''] - Sound marker. -*/ + * Set the sound/marker for the given state. + * + * @method Phaser.Button#setStateSound + * @private + * @param {object} state - See `STATE_*` + * @param {Phaser.Sound|Phaser.AudioSprite} [sound] - Sound. + * @param {string} [marker=''] - Sound marker. + */ Phaser.Button.prototype.setStateSound = function (state, sound, marker) { - var soundKey = 'on' + state + 'Sound'; var markerKey = 'on' + state + 'SoundMarker'; @@ -357,20 +347,18 @@ Phaser.Button.prototype.setStateSound = function (state, sound, marker) this[soundKey] = null; this[markerKey] = ''; } - }; /** -* Play the sound for the given state, _if_ the state has a sound assigned. -* -* @method Phaser.Button#playStateSound -* @private -* @param {object} state - See `STATE_*` -* @return {boolean} True only if a sound was played. -*/ + * Play the sound for the given state, _if_ the state has a sound assigned. + * + * @method Phaser.Button#playStateSound + * @private + * @param {object} state - See `STATE_*` + * @return {boolean} True only if a sound was played. + */ Phaser.Button.prototype.playStateSound = function (state) { - var soundKey = 'on' + state + 'Sound'; var sound = this[soundKey]; @@ -386,107 +374,95 @@ Phaser.Button.prototype.playStateSound = function (state) { return false; } - }; /** -* Sets the sounds to be played whenever this Button is interacted with. Sounds can be either full Sound objects, or markers pointing to a section of a Sound object. -* The most common forms of sounds are 'hover' effects and 'click' effects, which is why the order of the parameters is overSound then downSound. -* -* Call this function with no parameters to reset all sounds on this Button. -* -* @method Phaser.Button#setSounds -* @public -* @param {Phaser.Sound|Phaser.AudioSprite} [overSound] - Over Button Sound. -* @param {string} [overMarker] - Over Button Sound Marker. -* @param {Phaser.Sound|Phaser.AudioSprite} [downSound] - Down Button Sound. -* @param {string} [downMarker] - Down Button Sound Marker. -* @param {Phaser.Sound|Phaser.AudioSprite} [outSound] - Out Button Sound. -* @param {string} [outMarker] - Out Button Sound Marker. -* @param {Phaser.Sound|Phaser.AudioSprite} [upSound] - Up Button Sound. -* @param {string} [upMarker] - Up Button Sound Marker. -*/ + * Sets the sounds to be played whenever this Button is interacted with. Sounds can be either full Sound objects, or markers pointing to a section of a Sound object. + * The most common forms of sounds are 'hover' effects and 'click' effects, which is why the order of the parameters is overSound then downSound. + * + * Call this function with no parameters to reset all sounds on this Button. + * + * @method Phaser.Button#setSounds + * @public + * @param {Phaser.Sound|Phaser.AudioSprite} [overSound] - Over Button Sound. + * @param {string} [overMarker] - Over Button Sound Marker. + * @param {Phaser.Sound|Phaser.AudioSprite} [downSound] - Down Button Sound. + * @param {string} [downMarker] - Down Button Sound Marker. + * @param {Phaser.Sound|Phaser.AudioSprite} [outSound] - Out Button Sound. + * @param {string} [outMarker] - Out Button Sound Marker. + * @param {Phaser.Sound|Phaser.AudioSprite} [upSound] - Up Button Sound. + * @param {string} [upMarker] - Up Button Sound Marker. + */ Phaser.Button.prototype.setSounds = function (overSound, overMarker, downSound, downMarker, outSound, outMarker, upSound, upMarker) { - this.setStateSound(STATE_OVER, overSound, overMarker); this.setStateSound(STATE_OUT, outSound, outMarker); this.setStateSound(STATE_DOWN, downSound, downMarker); this.setStateSound(STATE_UP, upSound, upMarker); - }; /** -* The Sound to be played when a Pointer moves over this Button. -* -* @method Phaser.Button#setOverSound -* @public -* @param {Phaser.Sound|Phaser.AudioSprite} sound - The Sound that will be played. -* @param {string} [marker] - A Sound Marker that will be used in the playback. -*/ + * The Sound to be played when a Pointer moves over this Button. + * + * @method Phaser.Button#setOverSound + * @public + * @param {Phaser.Sound|Phaser.AudioSprite} sound - The Sound that will be played. + * @param {string} [marker] - A Sound Marker that will be used in the playback. + */ Phaser.Button.prototype.setOverSound = function (sound, marker) { - this.setStateSound(STATE_OVER, sound, marker); - }; /** -* The Sound to be played when a Pointer moves out of this Button. -* -* @method Phaser.Button#setOutSound -* @public -* @param {Phaser.Sound|Phaser.AudioSprite} sound - The Sound that will be played. -* @param {string} [marker] - A Sound Marker that will be used in the playback. -*/ + * The Sound to be played when a Pointer moves out of this Button. + * + * @method Phaser.Button#setOutSound + * @public + * @param {Phaser.Sound|Phaser.AudioSprite} sound - The Sound that will be played. + * @param {string} [marker] - A Sound Marker that will be used in the playback. + */ Phaser.Button.prototype.setOutSound = function (sound, marker) { - this.setStateSound(STATE_OUT, sound, marker); - }; /** -* The Sound to be played when a Pointer presses down on this Button. -* -* @method Phaser.Button#setDownSound -* @public -* @param {Phaser.Sound|Phaser.AudioSprite} sound - The Sound that will be played. -* @param {string} [marker] - A Sound Marker that will be used in the playback. -*/ + * The Sound to be played when a Pointer presses down on this Button. + * + * @method Phaser.Button#setDownSound + * @public + * @param {Phaser.Sound|Phaser.AudioSprite} sound - The Sound that will be played. + * @param {string} [marker] - A Sound Marker that will be used in the playback. + */ Phaser.Button.prototype.setDownSound = function (sound, marker) { - this.setStateSound(STATE_DOWN, sound, marker); - }; /** -* The Sound to be played when a Pointer has pressed down and is released from this Button. -* -* @method Phaser.Button#setUpSound -* @public -* @param {Phaser.Sound|Phaser.AudioSprite} sound - The Sound that will be played. -* @param {string} [marker] - A Sound Marker that will be used in the playback. -*/ + * The Sound to be played when a Pointer has pressed down and is released from this Button. + * + * @method Phaser.Button#setUpSound + * @public + * @param {Phaser.Sound|Phaser.AudioSprite} sound - The Sound that will be played. + * @param {string} [marker] - A Sound Marker that will be used in the playback. + */ Phaser.Button.prototype.setUpSound = function (sound, marker) { - this.setStateSound(STATE_UP, sound, marker); - }; /** -* Internal function that handles input events. -* -* @method Phaser.Button#onInputOverHandler -* @protected -* @param {Phaser.Button} sprite - The Button that the event occurred on. -* @param {Phaser.Pointer} pointer - The Pointer that activated the Button. -*/ + * Internal function that handles input events. + * + * @method Phaser.Button#onInputOverHandler + * @protected + * @param {Phaser.Button} sprite - The Button that the event occurred on. + * @param {Phaser.Pointer} pointer - The Pointer that activated the Button. + */ Phaser.Button.prototype.onInputOverHandler = function (sprite, pointer) { - if (pointer.justReleased() && (this.justReleasedPreventsOver & pointer.pointerMode) === pointer.pointerMode) { @@ -507,20 +483,18 @@ Phaser.Button.prototype.onInputOverHandler = function (sprite, pointer) { this.onInputOver.dispatch(this, pointer); } - }; /** -* Internal function that handles input events. -* -* @method Phaser.Button#onInputOutHandler -* @protected -* @param {Phaser.Button} sprite - The Button that the event occurred on. -* @param {Phaser.Pointer} pointer - The Pointer that activated the Button. -*/ + * Internal function that handles input events. + * + * @method Phaser.Button#onInputOutHandler + * @protected + * @param {Phaser.Button} sprite - The Button that the event occurred on. + * @param {Phaser.Pointer} pointer - The Pointer that activated the Button. + */ Phaser.Button.prototype.onInputOutHandler = function (sprite, pointer) { - this.changeStateFrame(STATE_OUT); this.playStateSound(STATE_OUT); @@ -532,16 +506,15 @@ Phaser.Button.prototype.onInputOutHandler = function (sprite, pointer) }; /** -* Internal function that handles input events. -* -* @method Phaser.Button#onInputDownHandler -* @protected -* @param {Phaser.Button} sprite - The Button that the event occurred on. -* @param {Phaser.Pointer} pointer - The Pointer that activated the Button. -*/ + * Internal function that handles input events. + * + * @method Phaser.Button#onInputDownHandler + * @protected + * @param {Phaser.Button} sprite - The Button that the event occurred on. + * @param {Phaser.Pointer} pointer - The Pointer that activated the Button. + */ Phaser.Button.prototype.onInputDownHandler = function (sprite, pointer) { - this.changeStateFrame(STATE_DOWN); this.playStateSound(STATE_DOWN); @@ -553,17 +526,16 @@ Phaser.Button.prototype.onInputDownHandler = function (sprite, pointer) }; /** -* Internal function that handles input events. -* -* @method Phaser.Button#onInputUpHandler -* @protected -* @param {Phaser.Button} sprite - The Button that the event occurred on. -* @param {Phaser.Pointer} pointer - The Pointer that activated the Button. -* @param {boolean} isOver - Is the Pointer still over the Game Object? -*/ + * Internal function that handles input events. + * + * @method Phaser.Button#onInputUpHandler + * @protected + * @param {Phaser.Button} sprite - The Button that the event occurred on. + * @param {Phaser.Pointer} pointer - The Pointer that activated the Button. + * @param {boolean} isOver - Is the Pointer still over the Game Object? + */ Phaser.Button.prototype.onInputUpHandler = function (sprite, pointer, isOver) { - this.playStateSound(STATE_UP); // Input dispatched early, before state change (but after sound) @@ -597,5 +569,4 @@ Phaser.Button.prototype.onInputUpHandler = function (sprite, pointer, isOver) } } } - }; diff --git a/src/gameobjects/Creature.js b/src/gameobjects/Creature.js index d8055f57d..77c0474f3 100644 --- a/src/gameobjects/Creature.js +++ b/src/gameobjects/Creature.js @@ -1,11 +1,11 @@ /* eslint-disable camelcase */ /* globals Creature,CreatureAnimation,CreatureManager,CreatureModuleUtils */ /** -* @author Richard Davey -* @author Kestrel Moon Studios -* @copyright 2016 Photon Storm Ltd and Kestrel Moon Studios -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @author Kestrel Moon Studios + * @copyright 2016 Photon Storm Ltd and Kestrel Moon Studios + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** @@ -16,30 +16,30 @@ PIXI.CreatureShader = function (gl) { /** - * @property _UID - * @type Number - * @private - */ + * @property _UID + * @type Number + * @private + */ this._UID = Phaser._UID++; /** - * @property gl - * @type WebGLContext - */ + * @property gl + * @type WebGLContext + */ this.gl = gl; /** - * The WebGL program. - * @property program - * @type Any - */ + * The WebGL program. + * @property program + * @type Any + */ this.program = null; /** - * The fragment shader. - * @property fragmentSrc - * @type Array - */ + * The fragment shader. + * @property fragmentSrc + * @type Array + */ this.fragmentSrc = [ '//CreatureShader Fragment Shader.', 'precision mediump float;', @@ -47,8 +47,10 @@ PIXI.CreatureShader = function (gl) 'varying float vTextureIndex;', 'varying vec4 vColor;', - // 'uniform float alpha;', - // 'uniform vec3 tint;', + /* + * 'uniform float alpha;', + * 'uniform vec3 tint;', + */ 'uniform sampler2D uSampler;', 'void main(void) {', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor;', @@ -56,10 +58,10 @@ PIXI.CreatureShader = function (gl) ]; /** - * The vertex shader. - * @property vertexSrc - * @type Array - */ + * The vertex shader. + * @property vertexSrc + * @type Array + */ this.vertexSrc = [ '//CreatureShader Vertex Shader.', 'attribute vec2 aVertexPosition;', @@ -143,44 +145,43 @@ PIXI.CreatureShader.prototype.destroy = function () /** -* Creature is a custom Game Object used in conjunction with the Creature Runtime libraries by Kestrel Moon Studios. -* -* It allows you to display animated Game Objects that were created with the [Creature Automated Animation Tool](http://www.kestrelmoon.com/creature/). -* -* Note 1: You can only use Phaser.Creature objects in WebGL enabled games. They do not work in Canvas mode games. -* -* Note 2: You must use a build of Phaser that includes the CreatureMeshBone.js runtime and gl-matrix.js, or have them -* loaded before your Phaser game boots. -* -* See the Phaser custom build process for more details. -* -* By default the Creature runtimes are NOT included in any pre-configured version of Phaser. -* -* So you'll need to do `grunt custom` to create a build that includes them. -* -* @class Phaser.Creature -* @extends PIXI.DisplayObjectContainer -* @extends Phaser.Component.Core -* @extends Phaser.Component.Angle -* @extends Phaser.Component.AutoCull -* @extends Phaser.Component.BringToTop -* @extends Phaser.Component.Destroy -* @extends Phaser.Component.FixedToCamera -* @extends Phaser.Component.LifeSpan -* @extends Phaser.Component.Reset -* @extends Phaser.Component.InputEnabled -* @constructor -* @param {Phaser.Game} game - A reference to the currently running game. -* @param {number} x - The x coordinate of the Game Object. The coordinate is relative to any parent container this Game Object may be in. -* @param {number} y - The y coordinate of the Game Object. The coordinate is relative to any parent container this Game Object may be in. -* @param {string|PIXI.Texture} key - The texture used by the Creature Object during rendering. It can be a string which is a reference to the Cache entry, or an instance of a PIXI.Texture. -* @param {string} mesh - The mesh data for the Creature Object. It should be a string which is a reference to the Cache JSON entry. -* @param {string} [animation='default'] - The animation within the mesh data to play. -* @param {string} [useFlatData=false] - Use flat data -*/ + * Creature is a custom Game Object used in conjunction with the Creature Runtime libraries by Kestrel Moon Studios. + * + * It allows you to display animated Game Objects that were created with the [Creature Automated Animation Tool](http://www.kestrelmoon.com/creature/). + * + * Note 1: You can only use Phaser.Creature objects in WebGL enabled games. They do not work in Canvas mode games. + * + * Note 2: You must use a build of Phaser that includes the CreatureMeshBone.js runtime and gl-matrix.js, or have them + * loaded before your Phaser game boots. + * + * See the Phaser custom build process for more details. + * + * By default the Creature runtimes are NOT included in any pre-configured version of Phaser. + * + * So you'll need to do `grunt custom` to create a build that includes them. + * + * @class Phaser.Creature + * @extends PIXI.DisplayObjectContainer + * @extends Phaser.Component.Core + * @extends Phaser.Component.Angle + * @extends Phaser.Component.AutoCull + * @extends Phaser.Component.BringToTop + * @extends Phaser.Component.Destroy + * @extends Phaser.Component.FixedToCamera + * @extends Phaser.Component.LifeSpan + * @extends Phaser.Component.Reset + * @extends Phaser.Component.InputEnabled + * @constructor + * @param {Phaser.Game} game - A reference to the currently running game. + * @param {number} x - The x coordinate of the Game Object. The coordinate is relative to any parent container this Game Object may be in. + * @param {number} y - The y coordinate of the Game Object. The coordinate is relative to any parent container this Game Object may be in. + * @param {string|PIXI.Texture} key - The texture used by the Creature Object during rendering. It can be a string which is a reference to the Cache entry, or an instance of a PIXI.Texture. + * @param {string} mesh - The mesh data for the Creature Object. It should be a string which is a reference to the Cache JSON entry. + * @param {string} [animation='default'] - The animation within the mesh data to play. + * @param {string} [useFlatData=false] - Use flat data + */ Phaser.Creature = function (game, x, y, key, mesh, animation, useFlatData) { - /** * @property {Phaser.Game} game - A reference to the currently running game. */ @@ -190,9 +191,9 @@ Phaser.Creature = function (game, x, y, key, mesh, animation, useFlatData) if (useFlatData === undefined) { useFlatData = false; } /** - * @property {number} type - The const type of this object. - * @readonly - */ + * @property {number} type - The const type of this object. + * @readonly + */ this.type = Phaser.CREATURE; if (!game.cache.checkJSONKey(mesh)) @@ -204,25 +205,25 @@ Phaser.Creature = function (game, x, y, key, mesh, animation, useFlatData) var meshData = game.cache.getJSON(mesh, true); /** - * @property {Creature} _creature - The Creature instance. - * @private - */ + * @property {Creature} _creature - The Creature instance. + * @private + */ this._creature = new Creature(meshData, useFlatData); /** - * @property {CreatureAnimation} animation - The CreatureAnimation instance. - */ + * @property {CreatureAnimation} animation - The CreatureAnimation instance. + */ this.animation = new CreatureAnimation(meshData, animation, useFlatData); /** - * @property {CreatureManager} manager - The CreatureManager instance for this object. - */ + * @property {CreatureManager} manager - The CreatureManager instance for this object. + */ this.manager = new CreatureManager(this._creature); /** - * @property {number} timeDelta - How quickly the animation advances. - * @default - */ + * @property {number} timeDelta - How quickly the animation advances. + * @default + */ this.timeDelta = 0.05; if (typeof key === 'string') @@ -235,8 +236,8 @@ Phaser.Creature = function (game, x, y, key, mesh, animation, useFlatData) } /** - * @property {PIXI.Texture} texture - The texture the animation is using. - */ + * @property {PIXI.Texture} texture - The texture the animation is using. + */ this.texture = texture; PIXI.DisplayObjectContainer.call(this); @@ -245,35 +246,35 @@ Phaser.Creature = function (game, x, y, key, mesh, animation, useFlatData) this.blendMode = PIXI.blendModes.NORMAL; /** - * @property {Phaser.Point} creatureBoundsMin - The minimum bounds point. - * @protected - */ + * @property {Phaser.Point} creatureBoundsMin - The minimum bounds point. + * @protected + */ this.creatureBoundsMin = new Phaser.Point(); /** - * @property {Phaser.Point} creatureBoundsMax - The maximum bounds point. - * @protected - */ + * @property {Phaser.Point} creatureBoundsMax - The maximum bounds point. + * @protected + */ this.creatureBoundsMax = new Phaser.Point(); var target = this.manager.target_creature; /** - * @property {Float32Array} vertices - The vertices data. - * @protected - */ + * @property {Float32Array} vertices - The vertices data. + * @protected + */ this.vertices = new Float32Array(target.total_num_pts * 2); /** - * @property {Float32Array} uvs - The UV data. - * @protected - */ + * @property {Float32Array} uvs - The UV data. + * @protected + */ this.uvs = new Float32Array(target.total_num_pts * 2); /** - * @property {Uint16Array} indices - * @protected - */ + * @property {Uint16Array} indices + * @protected + */ this.indices = new Uint16Array(target.global_indices.length); for (var i = 0; i < this.indices.length; i++) @@ -282,9 +283,9 @@ Phaser.Creature = function (game, x, y, key, mesh, animation, useFlatData) } /** - * @property {Uint16Array} colors - The vertices colors - * @protected - */ + * @property {Uint16Array} colors - The vertices colors + * @protected + */ this.colors = new Float32Array(target.total_num_pts * 4); for(var j = 0; j < this.colors.length; j++) { @@ -300,17 +301,16 @@ Phaser.Creature = function (game, x, y, key, mesh, animation, useFlatData) /** - * @property {number} tint - colour change - * @default - */ + * @property {number} tint - colour change + * @default + */ this.data.tint = 0xFFFFFF; /** - * @property {number} alpha - set the opacity - * @default - */ + * @property {number} alpha - set the opacity + * @default + */ this.data.alpha = 1.0; - }; Phaser.Creature.prototype = Object.create(PIXI.DisplayObjectContainer.prototype); @@ -331,14 +331,13 @@ Phaser.Creature.prototype.preUpdateInWorld = Phaser.Component.InWorld.preUpdate; Phaser.Creature.prototype.preUpdateCore = Phaser.Component.Core.preUpdate; /** -* Automatically called by World.preUpdate. -* -* @method Phaser.Creature#preUpdate -* @memberof Phaser.Creature -*/ + * Automatically called by World.preUpdate. + * + * @method Phaser.Creature#preUpdate + * @memberof Phaser.Creature + */ Phaser.Creature.prototype.preUpdate = function () { - if (!this.preUpdateInWorld()) { return false; @@ -349,19 +348,17 @@ Phaser.Creature.prototype.preUpdate = function () this.updateData(); return this.preUpdateCore(); - }; /** -* -* -* @method Phaser.Creature#_initWebGL -* @memberof Phaser.Creature -* @private -*/ + * + * + * @method Phaser.Creature#_initWebGL + * @memberof Phaser.Creature + * @private + */ Phaser.Creature.prototype._initWebGL = function (renderSession) { - // build the strip! var gl = renderSession.gl; @@ -381,17 +378,15 @@ Phaser.Creature.prototype._initWebGL = function (renderSession) gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._indexBuffer); gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.indices, gl.STATIC_DRAW); - }; /** -* @method Phaser.Creature#_renderWebGL -* @memberof Phaser.Creature -* @private -*/ + * @method Phaser.Creature#_renderWebGL + * @memberof Phaser.Creature + * @private + */ Phaser.Creature.prototype._renderWebGL = function (renderSession) { - // If the sprite is not visible or the alpha is 0 then no need to render this element if (!this.visible || this.alpha <= 0) { @@ -411,17 +406,15 @@ Phaser.Creature.prototype._renderWebGL = function (renderSession) this._renderCreature(renderSession); renderSession.spriteBatch.start(); - }; /** -* @method Phaser.Creature#_renderCreature -* @memberof Phaser.Creature -* @private -*/ + * @method Phaser.Creature#_renderCreature + * @memberof Phaser.Creature + * @private + */ Phaser.Creature.prototype._renderCreature = function (renderSession) { - var gl = renderSession.gl; var projection = renderSession.projection; @@ -504,17 +497,15 @@ Phaser.Creature.prototype._renderCreature = function (renderSession) } gl.drawElements(gl.TRIANGLES, this.indices.length, gl.UNSIGNED_SHORT, 0); - }; /** -* @method Phaser.Creature#updateCreatureBounds -* @memberof Phaser.Creature -* @private -*/ + * @method Phaser.Creature#updateCreatureBounds + * @memberof Phaser.Creature + * @private + */ Phaser.Creature.prototype.updateCreatureBounds = function () { - // Update bounds based off world transform matrix var target = this.manager.target_creature; @@ -525,17 +516,15 @@ Phaser.Creature.prototype.updateCreatureBounds = function () this.worldTransform.apply(this.creatureBoundsMin, this.creatureBoundsMin); this.worldTransform.apply(this.creatureBoundsMax, this.creatureBoundsMax); - }; /** -* @method Phaser.Creature#updateData -* @memberof Phaser.Creature -* @private -*/ + * @method Phaser.Creature#updateData + * @memberof Phaser.Creature + * @private + */ Phaser.Creature.prototype.updateData = function () { - var target = this.manager.target_creature; var read_pts = target.render_pts; @@ -545,17 +534,15 @@ Phaser.Creature.prototype.updateData = function () this.updateCreatureBounds(); this.dirty = true; - }; /** -* @method Phaser.Creature#updateRenderData -* @memberof Phaser.Creature -* @private -*/ + * @method Phaser.Creature#updateRenderData + * @memberof Phaser.Creature + * @private + */ Phaser.Creature.prototype.updateRenderData = function (verts, uvs) { - var target = this.manager.target_creature; var pt_index = 0; @@ -594,24 +581,21 @@ Phaser.Creature.prototype.updateRenderData = function (verts, uvs) this.colors[i] = cur_opacity; } } - }; /** -* Sets the Animation this Creature object will play, as defined in the mesh data. -* -* @method Phaser.Creature#setAnimation -* @memberof Phaser.Creature -* @param {string} key - The key of the animation to set, as defined in the mesh data. -*/ + * Sets the Animation this Creature object will play, as defined in the mesh data. + * + * @method Phaser.Creature#setAnimation + * @memberof Phaser.Creature + * @param {string} key - The key of the animation to set, as defined in the mesh data. + */ Phaser.Creature.prototype.setAnimation = function (key) { - this.data.anchorY = null; this.data.anchorX = null; this.data.animation = key; this.manager.SetActiveAnimationName(key, true); - }; /** @@ -623,86 +607,72 @@ Phaser.Creature.prototype.setAnimation = function (key) */ Phaser.Creature.prototype.setAnimationPlaySpeed = function (speed) { - if (speed) { this.timeDelta = speed; } - }; /** -* Plays the currently set animation. -* -* @method Phaser.Creature#play -* @memberof Phaser.Creature -* @param {boolean} [loop=false] - Should the animation loop? -*/ + * Plays the currently set animation. + * + * @method Phaser.Creature#play + * @memberof Phaser.Creature + * @param {boolean} [loop=false] - Should the animation loop? + */ Phaser.Creature.prototype.play = function (loop) { - if (loop === undefined) { loop = false; } this.loop = loop; this.manager.SetIsPlaying(true); this.manager.RunAtTime(0); - }; /** -* Stops the currently playing animation. -* -* @method Phaser.Creature#stop -* @memberof Phaser.Creature -*/ + * Stops the currently playing animation. + * + * @method Phaser.Creature#stop + * @memberof Phaser.Creature + */ Phaser.Creature.prototype.stop = function () { - this.manager.SetIsPlaying(false); - }; /** -* @name Phaser.Creature#isPlaying -* @property {boolean} isPlaying - Is the _current_ animation playing? -*/ + * @name Phaser.Creature#isPlaying + * @property {boolean} isPlaying - Is the _current_ animation playing? + */ Object.defineProperty(Phaser.Creature.prototype, 'isPlaying', { get: function () { - return this.manager.GetIsPlaying(); - }, set: function (value) { - this.manager.SetIsPlaying(value); - } }); /** -* @name Phaser.Creature#loop -* @property {boolean} loop - Should the _current_ animation loop or not? -*/ + * @name Phaser.Creature#loop + * @property {boolean} loop - Should the _current_ animation loop or not? + */ Object.defineProperty(Phaser.Creature.prototype, 'loop', { get: function () { - return this.manager.should_loop; - }, set: function (value) { - this.manager.SetShouldLoop(value); - } }); @@ -715,14 +685,11 @@ Object.defineProperty(Phaser.Creature.prototype, 'height', { get: function () { - return this.data.height; - }, set: function (value) { - var target = this.manager.target_creature; var width = this.data.width ? this.data.width : 0; @@ -730,7 +697,6 @@ Object.defineProperty(Phaser.Creature.prototype, 'height', { var values = target.GetPixelScaling(width, value); this.scale.set(values[0], values[1]); this.data.height = value; - } }); @@ -743,14 +709,11 @@ Object.defineProperty(Phaser.Creature.prototype, 'width', { get: function () { - return this.data.width; - }, set: function (value) { - var target = this.manager.target_creature; var height = this.data.height ? this.data.height : 0; @@ -758,7 +721,6 @@ Object.defineProperty(Phaser.Creature.prototype, 'width', { var values = target.GetPixelScaling(value, height); this.scale.set(values[0], values[1]); this.data.width = value; - } }); @@ -772,14 +734,11 @@ Object.defineProperty(Phaser.Creature.prototype, 'anchorX', { get: function () { - return this.data.anchorX; - }, set: function (value) { - if (value === 0) { value = 0.01; @@ -825,14 +784,11 @@ Object.defineProperty(Phaser.Creature.prototype, 'anchorY', { get: function () { - return this.data.anchorY; - }, set: function (value) { - if (value === 0) { value = 0.01; @@ -878,14 +834,11 @@ Object.defineProperty(Phaser.Creature.prototype, 'tint', { get: function () { - return this.data.tint; - }, set: function (value) { - this.data.tint = value; } @@ -899,25 +852,22 @@ Object.defineProperty(Phaser.Creature.prototype, 'alpha', { get: function () { - return this.data.alpha; - }, set: function (value) { - this.data.alpha = value; } }); /** -* Sets whether anchor point transformations are active. -* -* @method Phaser.Creature#setAnchorPointEnabled -* @memberof Phaser.Creature -*/ + * Sets whether anchor point transformations are active. + * + * @method Phaser.Creature#setAnchorPointEnabled + * @memberof Phaser.Creature + */ Phaser.Creature.prototype.setAnchorPointEnabled = function (value) { var target = this.manager.target_creature; @@ -925,12 +875,11 @@ Phaser.Creature.prototype.setAnchorPointEnabled = function (value) }; /** -* @method Phaser.Creature#createAllAnimations -* @memberof Phaser.Creature -*/ + * @method Phaser.Creature#createAllAnimations + * @memberof Phaser.Creature + */ Phaser.Creature.prototype.createAllAnimations = function (mesh) { - if (!this.game.cache.checkJSONKey(mesh)) { console.warn('Phaser.Creature: Invalid mesh key given. Not found in Phaser.Cache'); @@ -943,41 +892,35 @@ Phaser.Creature.prototype.createAllAnimations = function (mesh) }; /** -* @method Phaser.Creature#setMetaData -* @memberof Phaser.Creature -*/ + * @method Phaser.Creature#setMetaData + * @memberof Phaser.Creature + */ Phaser.Creature.prototype.setMetaData = function (meta) { if (!this.game.cache.checkJSONKey(meta)) { - console.warn('Phaser.Creature: Invalid meta key given. Not found in Phaser.Cache'); return; - } var metaJson = this.game.cache.getJSON(meta, true); var metaData = CreatureModuleUtils.BuildCreatureMetaData(metaJson); this._creature.SetMetaData(metaData); - }; /** -* @method Phaser.Creature#enableSkinSwap -* @memberof Phaser.Creature -*/ + * @method Phaser.Creature#enableSkinSwap + * @memberof Phaser.Creature + */ Phaser.Creature.prototype.enableSkinSwap = function (swapNameIn, active) { - var target = this.manager.target_creature; if (target.creature_meta_data === null) { - console.warn('Phaser.Creature: Attempting to use skin swapping before setting the meta data. You must use {@link #setMetaData} before using skin swapping functionality.'); return; - } target.EnableSkinSwap(swapNameIn, active); @@ -985,28 +928,22 @@ Phaser.Creature.prototype.enableSkinSwap = function (swapNameIn, active) this.indices = new Uint16Array(target.final_skin_swap_indices.length); for(var i = 0; i < this.indices.length; i++) { - this.indices[i] = target.final_skin_swap_indices[i]; - } - }; /** -* @method Phaser.Creature#disableSkinSwap -* @memberof Phaser.Creature -*/ + * @method Phaser.Creature#disableSkinSwap + * @memberof Phaser.Creature + */ Phaser.Creature.prototype.disableSkinSwap = function () { - var target = this.manager.target_creature; if (target.creature_meta_data === null) { - console.warn('Phaser.Creature: Attempting to use skin swapping before setting the meta data. You must use {@link #setMetaData} before using skin swapping functionality.'); return; - } target.DisableSkinSwap(); @@ -1014,35 +951,28 @@ Phaser.Creature.prototype.disableSkinSwap = function () this.indices = new Uint16Array(target.global_indices.length); for(var i = 0; i < this.indices.length; i++) { - this.indices[i] = target.global_indices[i]; - } - }; /** -* @method Phaser.Creature#setActiveItemSwap -* @memberof Phaser.Creature -*/ + * @method Phaser.Creature#setActiveItemSwap + * @memberof Phaser.Creature + */ Phaser.Creature.prototype.setActiveItemSwap = function (regionName, swapIdx) { - var target = this.manager.target_creature; target.active_uv_swap_actions[regionName] = swapIdx; - }; /** -* @method Phaser.Creature#removeActiveItemSwap -* @memberof Phaser.Creature -*/ + * @method Phaser.Creature#removeActiveItemSwap + * @memberof Phaser.Creature + */ Phaser.Creature.prototype.removeActiveItemSwap = function (regionName) { - var target = this.manager.target_creature; delete target.active_uv_swap_actions[regionName]; - }; diff --git a/src/gameobjects/GameObjectCreator.js b/src/gameobjects/GameObjectCreator.js index 098e91a13..e38c5f51f 100644 --- a/src/gameobjects/GameObjectCreator.js +++ b/src/gameobjects/GameObjectCreator.js @@ -1,141 +1,127 @@ /** -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* The GameObjectCreator is a quick way to create common game objects _without_ adding them to the game world. -* The object creator can be accessed with {@linkcode Phaser.Game#make `game.make`}. -* -* @class Phaser.GameObjectCreator -* @constructor -* @param {Phaser.Game} game - A reference to the currently running game. -*/ + * The GameObjectCreator is a quick way to create common game objects _without_ adding them to the game world. + * The object creator can be accessed with {@linkcode Phaser.Game#make `game.make`}. + * + * @class Phaser.GameObjectCreator + * @constructor + * @param {Phaser.Game} game - A reference to the currently running game. + */ Phaser.GameObjectCreator = function (game) { - /** - * @property {Phaser.Game} game - A reference to the currently running Game. - * @protected - */ + * @property {Phaser.Game} game - A reference to the currently running Game. + * @protected + */ this.game = game; /** - * @property {Phaser.World} world - A reference to the game world. - * @protected - */ + * @property {Phaser.World} world - A reference to the game world. + * @protected + */ this.world = this.game.world; - }; Phaser.GameObjectCreator.prototype = { /** - * Create a new Image object. - * - * An Image is a light-weight object you can use to display anything that doesn't need physics or animation. - * It can still rotate, scale, crop and receive input events. This makes it perfect for logos, backgrounds, simple buttons and other non-Sprite graphics. - * - * @method Phaser.GameObjectCreator#image - * @param {number} x - X position of the image. - * @param {number} y - Y position of the image. - * @param {string|Phaser.RenderTexture|PIXI.Texture} key - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture. - * @param {string|number} [frame] - If the sprite uses an image from a texture atlas or sprite sheet you can pass the frame here. Either a number for a frame ID or a string for a frame name. - * @returns {Phaser.Image} the newly created sprite object. - */ + * Create a new Image object. + * + * An Image is a light-weight object you can use to display anything that doesn't need physics or animation. + * It can still rotate, scale, crop and receive input events. This makes it perfect for logos, backgrounds, simple buttons and other non-Sprite graphics. + * + * @method Phaser.GameObjectCreator#image + * @param {number} x - X position of the image. + * @param {number} y - Y position of the image. + * @param {string|Phaser.RenderTexture|PIXI.Texture} key - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture. + * @param {string|number} [frame] - If the sprite uses an image from a texture atlas or sprite sheet you can pass the frame here. Either a number for a frame ID or a string for a frame name. + * @returns {Phaser.Image} the newly created sprite object. + */ image: function (x, y, key, frame) { - return new Phaser.Image(this.game, x, y, key, frame); - }, /** - * Create a new Sprite with specific position and sprite sheet key. - * - * @method Phaser.GameObjectCreator#sprite - * @param {number} x - X position of the new sprite. - * @param {number} y - Y position of the new sprite. - * @param {string|Phaser.RenderTexture|PIXI.Texture} key - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture. - * @param {string|number} [frame] - If the sprite uses an image from a texture atlas or sprite sheet you can pass the frame here. Either a number for a frame ID or a string for a frame name. - * @returns {Phaser.Sprite} the newly created sprite object. - */ + * Create a new Sprite with specific position and sprite sheet key. + * + * @method Phaser.GameObjectCreator#sprite + * @param {number} x - X position of the new sprite. + * @param {number} y - Y position of the new sprite. + * @param {string|Phaser.RenderTexture|PIXI.Texture} key - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture. + * @param {string|number} [frame] - If the sprite uses an image from a texture atlas or sprite sheet you can pass the frame here. Either a number for a frame ID or a string for a frame name. + * @returns {Phaser.Sprite} the newly created sprite object. + */ sprite: function (x, y, key, frame) { - return new Phaser.Sprite(this.game, x, y, key, frame); - }, /** - * Create a tween object for a specific object. - * - * The object can be any JavaScript object or Phaser object such as Sprite. - * - * @method Phaser.GameObjectCreator#tween - * @param {object} obj - Object the tween will be run on. - * @return {Phaser.Tween} The Tween object. - */ + * Create a tween object for a specific object. + * + * The object can be any JavaScript object or Phaser object such as Sprite. + * + * @method Phaser.GameObjectCreator#tween + * @param {object} obj - Object the tween will be run on. + * @return {Phaser.Tween} The Tween object. + */ tween: function (obj) { - return new Phaser.Tween(obj, this.game, this.game.tweens); - }, /** - * A Group is a container for display objects that allows for fast pooling, recycling and collision checks. - * - * @method Phaser.GameObjectCreator#group - * @param {any} [parent] - The parent Group or DisplayObjectContainer that will hold this group, if any. `undefined`, `null`, or `false` will assign no parent. - * @param {string} [name='group'] - A name for this Group. Not used internally but useful for your debugging. - * @param {boolean} [addToStage=false] - If set to true this Group will be added directly to `game.stage`. - * @param {boolean} [enableBody=false] - If true all Sprites created with `Group.create` or `Group.createMulitple` will have a physics body created on them. Change the body type with physicsBodyType. - * @param {number} [physicsBodyType=0] - If enableBody is true this is the type of physics body that is created on new Sprites. Phaser.Physics.ARCADE, Phaser.Physics.P2, Phaser.Physics.NINJA, etc. - * @return {Phaser.Group} The newly created Group. - */ + * A Group is a container for display objects that allows for fast pooling, recycling and collision checks. + * + * @method Phaser.GameObjectCreator#group + * @param {any} [parent] - The parent Group or DisplayObjectContainer that will hold this group, if any. `undefined`, `null`, or `false` will assign no parent. + * @param {string} [name='group'] - A name for this Group. Not used internally but useful for your debugging. + * @param {boolean} [addToStage=false] - If set to true this Group will be added directly to `game.stage`. + * @param {boolean} [enableBody=false] - If true all Sprites created with `Group.create` or `Group.createMulitple` will have a physics body created on them. Change the body type with physicsBodyType. + * @param {number} [physicsBodyType=0] - If enableBody is true this is the type of physics body that is created on new Sprites. Phaser.Physics.ARCADE, Phaser.Physics.P2, Phaser.Physics.NINJA, etc. + * @return {Phaser.Group} The newly created Group. + */ group: function (parent, name, addToStage, enableBody, physicsBodyType) { - return new Phaser.Group(this.game, parent || null, name, addToStage, enableBody, physicsBodyType); - }, /** - * Create a new SpriteBatch. - * - * @method Phaser.GameObjectCreator#spriteBatch - * @param {any} parent - The parent Group or DisplayObjectContainer that will hold this group, if any. - * @param {string} [name='group'] - A name for this Group. Not used internally but useful for debugging. - * @param {boolean} [addToStage=false] - If set to true this Group will be added directly to the Game.Stage instead of Game.World. - * @return {Phaser.SpriteBatch} The newly created group. - */ + * Create a new SpriteBatch. + * + * @method Phaser.GameObjectCreator#spriteBatch + * @param {any} parent - The parent Group or DisplayObjectContainer that will hold this group, if any. + * @param {string} [name='group'] - A name for this Group. Not used internally but useful for debugging. + * @param {boolean} [addToStage=false] - If set to true this Group will be added directly to the Game.Stage instead of Game.World. + * @return {Phaser.SpriteBatch} The newly created group. + */ spriteBatch: function (parent, name, addToStage) { - if (name === undefined) { name = 'group'; } if (addToStage === undefined) { addToStage = false; } return new Phaser.SpriteBatch(this.game, parent, name, addToStage); - }, /** - * Creates a new Sound object. - * - * @method Phaser.GameObjectCreator#audio - * @param {string} key - The Game.cache key of the sound that this object will use. - * @param {number} [volume=1] - The volume at which the sound will be played. - * @param {boolean} [loop=false] - Whether or not the sound will loop. - * @param {boolean} [connect=true] - Controls if the created Sound object will connect to the master gainNode of the SoundManager when running under WebAudio. - * @return {Phaser.Sound} The newly created text object. - */ + * Creates a new Sound object. + * + * @method Phaser.GameObjectCreator#audio + * @param {string} key - The Game.cache key of the sound that this object will use. + * @param {number} [volume=1] - The volume at which the sound will be played. + * @param {boolean} [loop=false] - Whether or not the sound will loop. + * @param {boolean} [connect=true] - Controls if the created Sound object will connect to the master gainNode of the SoundManager when running under WebAudio. + * @return {Phaser.Sound} The newly created text object. + */ audio: function (key, volume, loop, connect) { - return this.game.sound.add(key, volume, loop, connect); - }, /** @@ -147,240 +133,217 @@ Phaser.GameObjectCreator.prototype = { */ audioSprite: function (key) { - return this.game.sound.addSprite(key); - }, /** - * Creates a new Sound object. - * - * @method Phaser.GameObjectCreator#sound - * @param {string} key - The Game.cache key of the sound that this object will use. - * @param {number} [volume=1] - The volume at which the sound will be played. - * @param {boolean} [loop=false] - Whether or not the sound will loop. - * @param {boolean} [connect=true] - Controls if the created Sound object will connect to the master gainNode of the SoundManager when running under WebAudio. - * @return {Phaser.Sound} The newly created text object. - */ + * Creates a new Sound object. + * + * @method Phaser.GameObjectCreator#sound + * @param {string} key - The Game.cache key of the sound that this object will use. + * @param {number} [volume=1] - The volume at which the sound will be played. + * @param {boolean} [loop=false] - Whether or not the sound will loop. + * @param {boolean} [connect=true] - Controls if the created Sound object will connect to the master gainNode of the SoundManager when running under WebAudio. + * @return {Phaser.Sound} The newly created text object. + */ sound: function (key, volume, loop, connect) { - return this.game.sound.add(key, volume, loop, connect); - }, /** - * Creates a new TileSprite object. - * - * @method Phaser.GameObjectCreator#tileSprite - * @param {number} x - The x coordinate (in world space) to position the TileSprite at. - * @param {number} y - The y coordinate (in world space) to position the TileSprite at. - * @param {number} width - The width of the TileSprite. - * @param {number} height - The height of the TileSprite. - * @param {string|Phaser.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 Phaser Image Cache entry, or an instance of a PIXI.Texture or BitmapData. - * @param {string|number} frame - If this TileSprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. - * @return {Phaser.TileSprite} The newly created tileSprite object. - */ + * Creates a new TileSprite object. + * + * @method Phaser.GameObjectCreator#tileSprite + * @param {number} x - The x coordinate (in world space) to position the TileSprite at. + * @param {number} y - The y coordinate (in world space) to position the TileSprite at. + * @param {number} width - The width of the TileSprite. + * @param {number} height - The height of the TileSprite. + * @param {string|Phaser.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 Phaser Image Cache entry, or an instance of a PIXI.Texture or BitmapData. + * @param {string|number} frame - If this TileSprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. + * @return {Phaser.TileSprite} The newly created tileSprite object. + */ tileSprite: function (x, y, width, height, key, frame) { - return new Phaser.TileSprite(this.game, x, y, width, height, key, frame); - }, /** - * Creates a new Rope object. - * - * @method Phaser.GameObjectCreator#rope - * @param {number} x - The x coordinate (in world space) to position the Rope at. - * @param {number} y - The y coordinate (in world space) to position the Rope at. - * @param {number} width - The width of the Rope. - * @param {number} height - The height of the Rope. - * @param {string|Phaser.RenderTexture|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the TileSprite during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture. - * @param {string|number} frame - If this Rope is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. - * @return {Phaser.Rope} The newly created rope object. - */ + * Creates a new Rope object. + * + * @method Phaser.GameObjectCreator#rope + * @param {number} x - The x coordinate (in world space) to position the Rope at. + * @param {number} y - The y coordinate (in world space) to position the Rope at. + * @param {number} width - The width of the Rope. + * @param {number} height - The height of the Rope. + * @param {string|Phaser.RenderTexture|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the TileSprite during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture. + * @param {string|number} frame - If this Rope is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. + * @return {Phaser.Rope} The newly created rope object. + */ rope: function (x, y, key, frame, points) { - return new Phaser.Rope(this.game, x, y, key, frame, points); - }, /** - * Creates a new Text object. - * - * @method Phaser.GameObjectCreator#text - * @param {number} x - X position of the new text object. - * @param {number} y - Y position of the new text object. - * @param {string} text - The actual text that will be written. - * @param {object} style - The style object containing style attributes like font, font size , etc. - * @return {Phaser.Text} The newly created text object. - */ + * Creates a new Text object. + * + * @method Phaser.GameObjectCreator#text + * @param {number} x - X position of the new text object. + * @param {number} y - Y position of the new text object. + * @param {string} text - The actual text that will be written. + * @param {object} style - The style object containing style attributes like font, font size , etc. + * @return {Phaser.Text} The newly created text object. + */ text: function (x, y, text, style) { - return new Phaser.Text(this.game, x, y, text, style); - }, /** - * Creates a new Button object. - * - * @method Phaser.GameObjectCreator#button - * @param {number} [x] X position of the new button object. - * @param {number} [y] Y position of the new button object. - * @param {string} [key] The image key as defined in the Game.Cache to use as the texture for this button. - * @param {function} [callback] The function to call when this button is pressed - * @param {object} [callbackContext] The context in which the callback will be called (usually 'this') - * @param {string|number} [overFrame] This is the frame or frameName that will be set when this button is in an over state. Give either a number to use a frame ID or a string for a frame name. - * @param {string|number} [outFrame] This is the frame or frameName that will be set when this button is in an out state. Give either a number to use a frame ID or a string for a frame name. - * @param {string|number} [downFrame] This is the frame or frameName that will be set when this button is in a down state. Give either a number to use a frame ID or a string for a frame name. - * @param {string|number} [upFrame] This is the frame or frameName that will be set when this button is in an up state. Give either a number to use a frame ID or a string for a frame name. - * @return {Phaser.Button} The newly created button object. - */ + * Creates a new Button object. + * + * @method Phaser.GameObjectCreator#button + * @param {number} [x] X position of the new button object. + * @param {number} [y] Y position of the new button object. + * @param {string} [key] The image key as defined in the Game.Cache to use as the texture for this button. + * @param {function} [callback] The function to call when this button is pressed + * @param {object} [callbackContext] The context in which the callback will be called (usually 'this') + * @param {string|number} [overFrame] This is the frame or frameName that will be set when this button is in an over state. Give either a number to use a frame ID or a string for a frame name. + * @param {string|number} [outFrame] This is the frame or frameName that will be set when this button is in an out state. Give either a number to use a frame ID or a string for a frame name. + * @param {string|number} [downFrame] This is the frame or frameName that will be set when this button is in a down state. Give either a number to use a frame ID or a string for a frame name. + * @param {string|number} [upFrame] This is the frame or frameName that will be set when this button is in an up state. Give either a number to use a frame ID or a string for a frame name. + * @return {Phaser.Button} The newly created button object. + */ button: function (x, y, key, callback, callbackContext, overFrame, outFrame, downFrame, upFrame) { - return new Phaser.Button(this.game, x, y, key, callback, callbackContext, overFrame, outFrame, downFrame, upFrame); - }, /** - * Creates a new Graphics object. - * - * @method Phaser.GameObjectCreator#graphics - * @param {number} [x=0] - X position of the new graphics object. - * @param {number} [y=0] - Y position of the new graphics object. - * @return {Phaser.Graphics} The newly created graphics object. - */ + * Creates a new Graphics object. + * + * @method Phaser.GameObjectCreator#graphics + * @param {number} [x=0] - X position of the new graphics object. + * @param {number} [y=0] - Y position of the new graphics object. + * @return {Phaser.Graphics} The newly created graphics object. + */ graphics: function (x, y) { - return new Phaser.Graphics(this.game, x, y); - }, /** - * Creat a new Emitter. - * - * An Emitter is a lightweight particle emitter. It can be used for one-time explosions or for - * continuous effects like rain and fire. All it really does is launch Particle objects out - * at set intervals, and fixes their positions and velocities accorindgly. - * - * @method Phaser.GameObjectCreator#emitter - * @param {number} [x=0] - The x coordinate within the Emitter that the particles are emitted from. - * @param {number} [y=0] - The y coordinate within the Emitter that the particles are emitted from. - * @param {number} [maxParticles=50] - The total number of particles in this emitter. - * @return {Phaser.Emitter} The newly created emitter object. - */ + * Creat a new Emitter. + * + * An Emitter is a lightweight particle emitter. It can be used for one-time explosions or for + * continuous effects like rain and fire. All it really does is launch Particle objects out + * at set intervals, and fixes their positions and velocities accorindgly. + * + * @method Phaser.GameObjectCreator#emitter + * @param {number} [x=0] - The x coordinate within the Emitter that the particles are emitted from. + * @param {number} [y=0] - The y coordinate within the Emitter that the particles are emitted from. + * @param {number} [maxParticles=50] - The total number of particles in this emitter. + * @return {Phaser.Emitter} The newly created emitter object. + */ emitter: function (x, y, maxParticles) { - return new Phaser.Particles.Arcade.Emitter(this.game, x, y, maxParticles); - }, /** - * Create a new RetroFont object. - * - * A RetroFont can be used as a texture for an Image or Sprite and optionally add it to the Cache. - * A RetroFont uses a bitmap which contains fixed with characters for the font set. You use character spacing to define the set. - * If you need variable width character support then use a BitmapText object instead. The main difference between a RetroFont and a BitmapText - * is that a RetroFont creates a single texture that you can apply to a game object, where-as a BitmapText creates one Sprite object per letter of text. - * The texture can be asssigned or one or multiple images/sprites, but note that the text the RetroFont uses will be shared across them all, - * i.e. if you need each Image to have different text in it, then you need to create multiple RetroFont objects. - * - * @method Phaser.GameObjectCreator#retroFont - * @param {string} font - The key of the image in the Game.Cache that the RetroFont will use. - * @param {number} characterWidth - The width of each character in the font set. - * @param {number} characterHeight - The height of each character in the font set. - * @param {string} chars - The characters used in the font set, in display order. You can use the TEXT_SET consts for common font set arrangements. - * @param {number} charsPerRow - The number of characters per row in the font set. - * @param {number} [xSpacing=0] - If the characters in the font set have horizontal spacing between them set the required amount here. - * @param {number} [ySpacing=0] - If the characters in the font set have vertical spacing between them set the required amount here. - * @param {number} [xOffset=0] - If the font set doesn't start at the top left of the given image, specify the X coordinate offset here. - * @param {number} [yOffset=0] - If the font set doesn't start at the top left of the given image, specify the Y coordinate offset here. - * @return {Phaser.RetroFont} The newly created RetroFont texture which can be applied to an Image or Sprite. - */ + * Create a new RetroFont object. + * + * A RetroFont can be used as a texture for an Image or Sprite and optionally add it to the Cache. + * A RetroFont uses a bitmap which contains fixed with characters for the font set. You use character spacing to define the set. + * If you need variable width character support then use a BitmapText object instead. The main difference between a RetroFont and a BitmapText + * is that a RetroFont creates a single texture that you can apply to a game object, where-as a BitmapText creates one Sprite object per letter of text. + * The texture can be asssigned or one or multiple images/sprites, but note that the text the RetroFont uses will be shared across them all, + * i.e. if you need each Image to have different text in it, then you need to create multiple RetroFont objects. + * + * @method Phaser.GameObjectCreator#retroFont + * @param {string} font - The key of the image in the Game.Cache that the RetroFont will use. + * @param {number} characterWidth - The width of each character in the font set. + * @param {number} characterHeight - The height of each character in the font set. + * @param {string} chars - The characters used in the font set, in display order. You can use the TEXT_SET consts for common font set arrangements. + * @param {number} charsPerRow - The number of characters per row in the font set. + * @param {number} [xSpacing=0] - If the characters in the font set have horizontal spacing between them set the required amount here. + * @param {number} [ySpacing=0] - If the characters in the font set have vertical spacing between them set the required amount here. + * @param {number} [xOffset=0] - If the font set doesn't start at the top left of the given image, specify the X coordinate offset here. + * @param {number} [yOffset=0] - If the font set doesn't start at the top left of the given image, specify the Y coordinate offset here. + * @return {Phaser.RetroFont} The newly created RetroFont texture which can be applied to an Image or Sprite. + */ retroFont: function (font, characterWidth, characterHeight, chars, charsPerRow, xSpacing, ySpacing, xOffset, yOffset) { - return new Phaser.RetroFont(this.game, font, characterWidth, characterHeight, chars, charsPerRow, xSpacing, ySpacing, xOffset, yOffset); - }, /** - * Create a new BitmapText object. - * - * BitmapText objects work by taking a texture file and an XML file that describes the font structure. - * It then generates a new Sprite object for each letter of the text, proportionally spaced out and aligned to - * match the font structure. - * - * BitmapText objects are less flexible than Text objects, in that they have less features such as shadows, fills and the ability - * to use Web Fonts. However you trade this flexibility for pure rendering speed. You can also create visually compelling BitmapTexts by - * processing the font texture in an image editor first, applying fills and any other effects required. - * - * To create multi-line text insert \r, \n or \r\n escape codes into the text string. - * - * To create a BitmapText data files you can use: - * - * BMFont (Windows, free): http://www.angelcode.com/products/bmfont/ - * Glyph Designer (OS X, commercial): http://www.71squared.com/en/glyphdesigner - * Littera (Web-based, free): http://kvazars.com/littera/ - * - * @method Phaser.GameObjectCreator#bitmapText - * @param {number} x - X coordinate to display the BitmapText object at. - * @param {number} y - Y coordinate to display the BitmapText object at. - * @param {string} font - The key of the BitmapText as stored in Phaser.Cache. - * @param {string} [text=''] - The text that will be rendered. This can also be set later via BitmapText.text. - * @param {number} [size=32] - The size the font will be rendered at in pixels. - * @param {string} [align='left'] - The alignment of multi-line text. Has no effect if there is only one line of text. - * @return {Phaser.BitmapText} The newly created bitmapText object. - */ + * Create a new BitmapText object. + * + * BitmapText objects work by taking a texture file and an XML file that describes the font structure. + * It then generates a new Sprite object for each letter of the text, proportionally spaced out and aligned to + * match the font structure. + * + * BitmapText objects are less flexible than Text objects, in that they have less features such as shadows, fills and the ability + * to use Web Fonts. However you trade this flexibility for pure rendering speed. You can also create visually compelling BitmapTexts by + * processing the font texture in an image editor first, applying fills and any other effects required. + * + * To create multi-line text insert \r, \n or \r\n escape codes into the text string. + * + * To create a BitmapText data files you can use: + * + * BMFont (Windows, free): http://www.angelcode.com/products/bmfont/ + * Glyph Designer (OS X, commercial): http://www.71squared.com/en/glyphdesigner + * Littera (Web-based, free): http://kvazars.com/littera/ + * + * @method Phaser.GameObjectCreator#bitmapText + * @param {number} x - X coordinate to display the BitmapText object at. + * @param {number} y - Y coordinate to display the BitmapText object at. + * @param {string} font - The key of the BitmapText as stored in Phaser.Cache. + * @param {string} [text=''] - The text that will be rendered. This can also be set later via BitmapText.text. + * @param {number} [size=32] - The size the font will be rendered at in pixels. + * @param {string} [align='left'] - The alignment of multi-line text. Has no effect if there is only one line of text. + * @return {Phaser.BitmapText} The newly created bitmapText object. + */ bitmapText: function (x, y, font, text, size, align) { - return new Phaser.BitmapText(this.game, x, y, font, text, size, align); - }, /** - * Creates a new Phaser.Tilemap object. - * - * The map can either be populated with data from a Tiled JSON file or from a CSV file. - * To do this pass the Cache key as the first parameter. When using Tiled data you need only provide the key. - * When using CSV data you must provide the key and the tileWidth and tileHeight parameters. - * If creating a blank tilemap to be populated later, you can either specify no parameters at all and then use `Tilemap.create` or pass the map and tile dimensions here. - * Note that all Tilemaps use a base tile size to calculate dimensions from, but that a TilemapLayer may have its own unique tile size that overrides it. - * - * @method Phaser.GameObjectCreator#tilemap - * @param {string} [key] - The key of the tilemap data as stored in the Cache. If you're creating a blank map either leave this parameter out or pass `null`. - * @param {number} [tileWidth=32] - The pixel width of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data. - * @param {number} [tileHeight=32] - The pixel height of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data. - * @param {number} [width=10] - The width of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this. - * @param {number} [height=10] - The height of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this. - */ + * Creates a new Phaser.Tilemap object. + * + * The map can either be populated with data from a Tiled JSON file or from a CSV file. + * To do this pass the Cache key as the first parameter. When using Tiled data you need only provide the key. + * When using CSV data you must provide the key and the tileWidth and tileHeight parameters. + * If creating a blank tilemap to be populated later, you can either specify no parameters at all and then use `Tilemap.create` or pass the map and tile dimensions here. + * Note that all Tilemaps use a base tile size to calculate dimensions from, but that a TilemapLayer may have its own unique tile size that overrides it. + * + * @method Phaser.GameObjectCreator#tilemap + * @param {string} [key] - The key of the tilemap data as stored in the Cache. If you're creating a blank map either leave this parameter out or pass `null`. + * @param {number} [tileWidth=32] - The pixel width of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data. + * @param {number} [tileHeight=32] - The pixel height of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data. + * @param {number} [width=10] - The width of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this. + * @param {number} [height=10] - The height of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this. + */ tilemap: function (key, tileWidth, tileHeight, width, height) { - return new Phaser.Tilemap(this.game, key, tileWidth, tileHeight, width, height); - }, /** - * A dynamic initially blank canvas to which images can be drawn. - * - * @method Phaser.GameObjectCreator#renderTexture - * @param {number} [width=100] - the width of the RenderTexture. - * @param {number} [height=100] - the height of the RenderTexture. - * @param {string} [key=''] - Asset key for the RenderTexture when stored in the Cache (see addToCache parameter). - * @param {boolean} [addToCache=false] - Should this RenderTexture be added to the Game.Cache? If so you can retrieve it with Cache.getTexture(key) - * @return {Phaser.RenderTexture} The newly created RenderTexture object. - */ + * A dynamic initially blank canvas to which images can be drawn. + * + * @method Phaser.GameObjectCreator#renderTexture + * @param {number} [width=100] - the width of the RenderTexture. + * @param {number} [height=100] - the height of the RenderTexture. + * @param {string} [key=''] - Asset key for the RenderTexture when stored in the Cache (see addToCache parameter). + * @param {boolean} [addToCache=false] - Should this RenderTexture be added to the Game.Cache? If so you can retrieve it with Cache.getTexture(key) + * @return {Phaser.RenderTexture} The newly created RenderTexture object. + */ renderTexture: function (width, height, key, addToCache) { - if (key === undefined || key === '') { key = this.game.rnd.uuid(); } if (addToCache === undefined) { addToCache = false; } @@ -392,24 +355,22 @@ Phaser.GameObjectCreator.prototype = { } return texture; - }, /** - * Create a BitmpaData object. - * - * A BitmapData object can be manipulated and drawn to like a traditional Canvas object and used to texture Sprites. - * - * @method Phaser.GameObjectCreator#bitmapData - * @param {number} [width=256] - The width of the BitmapData in pixels. - * @param {number} [height=256] - The height of the BitmapData in pixels. - * @param {string} [key=''] - Asset key for the BitmapData when stored in the Cache (see addToCache parameter). - * @param {boolean} [addToCache=false] - Should this BitmapData be added to the Game.Cache? If so you can retrieve it with Cache.getBitmapData(key) - * @return {Phaser.BitmapData} The newly created BitmapData object. - */ + * Create a BitmpaData object. + * + * A BitmapData object can be manipulated and drawn to like a traditional Canvas object and used to texture Sprites. + * + * @method Phaser.GameObjectCreator#bitmapData + * @param {number} [width=256] - The width of the BitmapData in pixels. + * @param {number} [height=256] - The height of the BitmapData in pixels. + * @param {string} [key=''] - Asset key for the BitmapData when stored in the Cache (see addToCache parameter). + * @param {boolean} [addToCache=false] - Should this BitmapData be added to the Game.Cache? If so you can retrieve it with Cache.getBitmapData(key) + * @return {Phaser.BitmapData} The newly created BitmapData object. + */ bitmapData: function (width, height, key, addToCache) { - if (addToCache === undefined) { addToCache = false; } if (key === undefined || key === '') { key = this.game.rnd.uuid(); } @@ -421,20 +382,18 @@ Phaser.GameObjectCreator.prototype = { } return texture; - }, /** - * A WebGL shader/filter that can be applied to Sprites. - * - * @method Phaser.GameObjectCreator#filter - * @param {string} filter - The name of the filter you wish to create, for example HueRotate or SineWave. - * @param {any} - Whatever parameters are needed to be passed to the filter init function. - * @return {Phaser.Filter} The newly created Phaser.Filter object. - */ + * A WebGL shader/filter that can be applied to Sprites. + * + * @method Phaser.GameObjectCreator#filter + * @param {string} filter - The name of the filter you wish to create, for example HueRotate or SineWave. + * @param {any} - Whatever parameters are needed to be passed to the filter init function. + * @return {Phaser.Filter} The newly created Phaser.Filter object. + */ filter: function (filter) { - var args = Array.prototype.slice.call(arguments, 1); var filter = new Phaser.Filter[filter](this.game); @@ -442,7 +401,6 @@ Phaser.GameObjectCreator.prototype = { filter.init.apply(filter, args); return filter; - } }; diff --git a/src/gameobjects/GameObjectFactory.js b/src/gameobjects/GameObjectFactory.js index 8acc2e54a..9dcadb4d9 100644 --- a/src/gameobjects/GameObjectFactory.js +++ b/src/gameobjects/GameObjectFactory.js @@ -1,76 +1,71 @@ /** -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* The GameObjectFactory is a quick way to create many common game objects -* using {@linkcode Phaser.Game#add `game.add`}. -* -* Created objects are _automatically added_ to the appropriate Manager, World, or manually specified parent Group. -* -* @class Phaser.GameObjectFactory -* @constructor -* @param {Phaser.Game} game - A reference to the currently running game. -*/ + * The GameObjectFactory is a quick way to create many common game objects + * using {@linkcode Phaser.Game#add `game.add`}. + * + * Created objects are _automatically added_ to the appropriate Manager, World, or manually specified parent Group. + * + * @class Phaser.GameObjectFactory + * @constructor + * @param {Phaser.Game} game - A reference to the currently running game. + */ Phaser.GameObjectFactory = function (game) { - /** - * @property {Phaser.Game} game - A reference to the currently running Game. - * @protected - */ + * @property {Phaser.Game} game - A reference to the currently running Game. + * @protected + */ this.game = game; /** - * @property {Phaser.World} world - A reference to the game world. - * @protected - */ + * @property {Phaser.World} world - A reference to the game world. + * @protected + */ this.world = this.game.world; - }; Phaser.GameObjectFactory.prototype = { /** - * Adds an existing display object to the game world. - * - * @method Phaser.GameObjectFactory#existing - * @param {any} object - An instance of Phaser.Sprite, Phaser.Button or any other display object. - * @return {any} The child that was added to the World. - */ + * Adds an existing display object to the game world. + * + * @method Phaser.GameObjectFactory#existing + * @param {any} object - An instance of Phaser.Sprite, Phaser.Button or any other display object. + * @return {any} The child that was added to the World. + */ existing: function (object) { - return this.world.add(object); - }, /** - * Weapons provide the ability to easily create a bullet pool and manager. - * - * Weapons fire Phaser.Bullet objects, which are essentially Sprites with a few extra properties. - * The Bullets are enabled for Arcade Physics. They do not currently work with P2 Physics. - * - * The Bullets are created inside of `Weapon.bullets`, which is a Phaser.Group instance. Anything you - * can usually do with a Group, such as move it around the display list, iterate it, etc can be done - * to the bullets Group too. - * - * Bullets can have textures and even animations. You can control the speed at which they are fired, - * the firing rate, the firing angle, and even set things like gravity for them. - * - * @method Phaser.GameObjectFactory#weapon - * @param {integer} [quantity=1] - The quantity of bullets to seed the Weapon with. If -1 it will set the pool to automatically expand. - * @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - The image used as a texture by the bullets during rendering. If a string Phaser will get for an entry in the Image Cache. Or it can be an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. - * @param {string|number} [frame] - If a Texture Atlas or Sprite Sheet is used this allows you to specify the frame to be used by the bullets. Use either an integer for a Frame ID or a string for a frame name. - * @param {Phaser.Group} [group] - Optional Group to add the Weapon to. If not specified it will be added to the World group. - * @param {function} [bulletClass] - The Class of the bullets that are launched by this Weapon. See {@link Phaser.Weapon#bulletClass} - * @returns {Phaser.Weapon} A Weapon instance. - */ + * Weapons provide the ability to easily create a bullet pool and manager. + * + * Weapons fire Phaser.Bullet objects, which are essentially Sprites with a few extra properties. + * The Bullets are enabled for Arcade Physics. They do not currently work with P2 Physics. + * + * The Bullets are created inside of `Weapon.bullets`, which is a Phaser.Group instance. Anything you + * can usually do with a Group, such as move it around the display list, iterate it, etc can be done + * to the bullets Group too. + * + * Bullets can have textures and even animations. You can control the speed at which they are fired, + * the firing rate, the firing angle, and even set things like gravity for them. + * + * @method Phaser.GameObjectFactory#weapon + * @param {integer} [quantity=1] - The quantity of bullets to seed the Weapon with. If -1 it will set the pool to automatically expand. + * @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - The image used as a texture by the bullets during rendering. If a string Phaser will get for an entry in the Image Cache. Or it can be an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. + * @param {string|number} [frame] - If a Texture Atlas or Sprite Sheet is used this allows you to specify the frame to be used by the bullets. Use either an integer for a Frame ID or a string for a frame name. + * @param {Phaser.Group} [group] - Optional Group to add the Weapon to. If not specified it will be added to the World group. + * @param {function} [bulletClass] - The Class of the bullets that are launched by this Weapon. See {@link Phaser.Weapon#bulletClass} + * @returns {Phaser.Weapon} A Weapon instance. + */ weapon: function (quantity, key, frame, group, bulletClass) { - var weapon = this.game.plugins.add(Phaser.Weapon); if (bulletClass) @@ -81,85 +76,79 @@ Phaser.GameObjectFactory.prototype = { weapon.createBullets(quantity, key, frame, group); return weapon; - }, /** - * Create a new `Image` object. - * - * An Image is a light-weight object you can use to display anything that doesn't need physics or animation. - * - * It can still rotate, scale, crop and receive input events. - * This makes it perfect for logos, backgrounds, simple buttons and other non-Sprite graphics. - * - * @method Phaser.GameObjectFactory#image - * @param {number} [x=0] - The x coordinate of the Image. The coordinate is relative to any parent container this Image may be in. - * @param {number} [y=0] - The y coordinate of the Image. The coordinate is relative to any parent container this Image may be in. - * @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - The image used as a texture by this display object during rendering. If a string Phaser will get for an entry in the Image Cache. Or it can be an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. - * @param {string|number} [frame] - If a Texture Atlas or Sprite Sheet is used this allows you to specify the frame to be used. Use either an integer for a Frame ID or a string for a frame name. - * @param {Phaser.Group|Phaser.Stage} [group] - Optional Group to add the object to. If not specified it will be added to the World group. - * @returns {Phaser.Image} The newly created Image object. - */ + * Create a new `Image` object. + * + * An Image is a light-weight object you can use to display anything that doesn't need physics or animation. + * + * It can still rotate, scale, crop and receive input events. + * This makes it perfect for logos, backgrounds, simple buttons and other non-Sprite graphics. + * + * @method Phaser.GameObjectFactory#image + * @param {number} [x=0] - The x coordinate of the Image. The coordinate is relative to any parent container this Image may be in. + * @param {number} [y=0] - The y coordinate of the Image. The coordinate is relative to any parent container this Image may be in. + * @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - The image used as a texture by this display object during rendering. If a string Phaser will get for an entry in the Image Cache. Or it can be an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. + * @param {string|number} [frame] - If a Texture Atlas or Sprite Sheet is used this allows you to specify the frame to be used. Use either an integer for a Frame ID or a string for a frame name. + * @param {Phaser.Group|Phaser.Stage} [group] - Optional Group to add the object to. If not specified it will be added to the World group. + * @returns {Phaser.Image} The newly created Image object. + */ image: function (x, y, key, frame, group) { - if (group === undefined) { group = this.world; } return group.add(new Phaser.Image(this.game, x, y, key, frame)); - }, /** - * Create a new Sprite with specific position and sprite sheet key. - * - * At its most basic a Sprite consists of a set of coordinates and a texture that is used when rendered. - * They also contain additional properties allowing for physics motion (via Sprite.body), input handling (via Sprite.input), - * events (via Sprite.events), animation (via Sprite.animations), camera culling and more. Please see the Examples for use cases. - * - * @method Phaser.GameObjectFactory#sprite - * @param {number} [x=0] - The x coordinate of the sprite. The coordinate is relative to any parent container this sprite may be in. - * @param {number} [y=0] - The y coordinate of the sprite. The coordinate is relative to any parent container this sprite may be in. - * @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - The image used as a texture by this display object during rendering. If a string Phaser will get for an entry in the Image Cache. Or it can be an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. - * @param {string|number} [frame] - If a Texture Atlas or Sprite Sheet is used this allows you to specify the frame to be used. Use either an integer for a Frame ID or a string for a frame name. - * @param {Phaser.Group|Phaser.Stage} [group] - Optional Group to add the object to. If not specified it will be added to the World group. - * @returns {Phaser.Sprite} The newly created Sprite object. - */ + * Create a new Sprite with specific position and sprite sheet key. + * + * At its most basic a Sprite consists of a set of coordinates and a texture that is used when rendered. + * They also contain additional properties allowing for physics motion (via Sprite.body), input handling (via Sprite.input), + * events (via Sprite.events), animation (via Sprite.animations), camera culling and more. Please see the Examples for use cases. + * + * @method Phaser.GameObjectFactory#sprite + * @param {number} [x=0] - The x coordinate of the sprite. The coordinate is relative to any parent container this sprite may be in. + * @param {number} [y=0] - The y coordinate of the sprite. The coordinate is relative to any parent container this sprite may be in. + * @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - The image used as a texture by this display object during rendering. If a string Phaser will get for an entry in the Image Cache. Or it can be an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. + * @param {string|number} [frame] - If a Texture Atlas or Sprite Sheet is used this allows you to specify the frame to be used. Use either an integer for a Frame ID or a string for a frame name. + * @param {Phaser.Group|Phaser.Stage} [group] - Optional Group to add the object to. If not specified it will be added to the World group. + * @returns {Phaser.Sprite} The newly created Sprite object. + */ sprite: function (x, y, key, frame, group) { - if (group === undefined) { group = this.world; } return group.add(new Phaser.Sprite(this.game, x, y, key, frame)); - }, /** - * Create a new Creature Animation object. - * - * Creature is a custom Game Object used in conjunction with the Creature Runtime libraries by Kestrel Moon Studios. - * - * It allows you to display animated Game Objects that were created with the [Creature Automated Animation Tool](http://www.kestrelmoon.com/creature/). - * - * Note 1: You can only use Phaser.Creature objects in WebGL enabled games. They do not work in Canvas mode games. - * - * Note 2: You must use a build of Phaser that includes the CreatureMeshBone.js runtime and gl-matrix.js, or have them - * loaded before your Phaser game boots. - * - * See the Phaser custom build process for more details. - * - * @method Phaser.GameObjectFactory#creature - * @param {number} x - The x coordinate of the creature. The coordinate is relative to any parent container this creature may be in. - * @param {number} y - The y coordinate of the creature. The coordinate is relative to any parent container this creature may be in. - * @param {string|PIXI.Texture} key - The creature's image texture. If a string Phaser will get for an entry in the Image Cache. Or it can be an instance of a PIXI.Texture. - * @param {string} mesh - The creature's mesh data. It should be a string which is a reference to the Cache JSON entry. - * @param {Phaser.Group|Phaser.Stage} [group=this.world] - Optional Group to add the creature to. If omitted (or `undefined`), the creature will be added to the World group. - * @param {string} [animation='default'] - The animation within the mesh data to play. - * @param {string} [useFlatData=false] - Use flat data. - * @returns {Phaser.Creature} The newly created Creature object. - */ + * Create a new Creature Animation object. + * + * Creature is a custom Game Object used in conjunction with the Creature Runtime libraries by Kestrel Moon Studios. + * + * It allows you to display animated Game Objects that were created with the [Creature Automated Animation Tool](http://www.kestrelmoon.com/creature/). + * + * Note 1: You can only use Phaser.Creature objects in WebGL enabled games. They do not work in Canvas mode games. + * + * Note 2: You must use a build of Phaser that includes the CreatureMeshBone.js runtime and gl-matrix.js, or have them + * loaded before your Phaser game boots. + * + * See the Phaser custom build process for more details. + * + * @method Phaser.GameObjectFactory#creature + * @param {number} x - The x coordinate of the creature. The coordinate is relative to any parent container this creature may be in. + * @param {number} y - The y coordinate of the creature. The coordinate is relative to any parent container this creature may be in. + * @param {string|PIXI.Texture} key - The creature's image texture. If a string Phaser will get for an entry in the Image Cache. Or it can be an instance of a PIXI.Texture. + * @param {string} mesh - The creature's mesh data. It should be a string which is a reference to the Cache JSON entry. + * @param {Phaser.Group|Phaser.Stage} [group=this.world] - Optional Group to add the creature to. If omitted (or `undefined`), the creature will be added to the World group. + * @param {string} [animation='default'] - The animation within the mesh data to play. + * @param {string} [useFlatData=false] - Use flat data. + * @returns {Phaser.Creature} The newly created Creature object. + */ creature: function (x, y, key, mesh, group, animation, useFlatData) { - if (group === undefined) { group = this.world; } var obj = new Phaser.Creature(this.game, x, y, key, mesh, animation, useFlatData); @@ -167,117 +156,104 @@ Phaser.GameObjectFactory.prototype = { group.add(obj); return obj; - }, /** - * Create a tween on a specific object. - * - * The object can be any JavaScript object or Phaser object such as Sprite. - * - * @method Phaser.GameObjectFactory#tween - * @param {object} object - Object the tween will be run on. - * @return {Phaser.Tween} The newly created Phaser.Tween object. - */ + * Create a tween on a specific object. + * + * The object can be any JavaScript object or Phaser object such as Sprite. + * + * @method Phaser.GameObjectFactory#tween + * @param {object} object - Object the tween will be run on. + * @return {Phaser.Tween} The newly created Phaser.Tween object. + */ tween: function (object) { - return this.game.tweens.create(object); - }, /** - * A Group is a container for display objects that allows for fast pooling, recycling and collision checks. - * - * @method Phaser.GameObjectFactory#group - * @param {any} [parent] - The parent Group or DisplayObjectContainer that will hold this group, if any. If set to null the Group won't be added to the display list. If undefined it will be added to World by default. - * @param {string} [name='group'] - A name for this Group. Not used internally but useful for debugging. - * @param {boolean} [addToStage=false] - If set to true this Group will be added directly to the Game.Stage instead of Game.World. - * @param {boolean} [enableBody=false] - If true all Sprites created with `Group.create` or `Group.createMulitple` will have a physics body created on them. Change the body type with physicsBodyType. - * @param {number} [physicsBodyType=0] - If enableBody is true this is the type of physics body that is created on new Sprites. Phaser.Physics.ARCADE, Phaser.Physics.P2, Phaser.Physics.NINJA, etc. - * @return {Phaser.Group} The newly created Group. - */ + * A Group is a container for display objects that allows for fast pooling, recycling and collision checks. + * + * @method Phaser.GameObjectFactory#group + * @param {any} [parent] - The parent Group or DisplayObjectContainer that will hold this group, if any. If set to null the Group won't be added to the display list. If undefined it will be added to World by default. + * @param {string} [name='group'] - A name for this Group. Not used internally but useful for debugging. + * @param {boolean} [addToStage=false] - If set to true this Group will be added directly to the Game.Stage instead of Game.World. + * @param {boolean} [enableBody=false] - If true all Sprites created with `Group.create` or `Group.createMulitple` will have a physics body created on them. Change the body type with physicsBodyType. + * @param {number} [physicsBodyType=0] - If enableBody is true this is the type of physics body that is created on new Sprites. Phaser.Physics.ARCADE, Phaser.Physics.P2, Phaser.Physics.NINJA, etc. + * @return {Phaser.Group} The newly created Group. + */ group: function (parent, name, addToStage, enableBody, physicsBodyType) { - return new Phaser.Group(this.game, parent, name, addToStage, enableBody, physicsBodyType); - }, /** - * A Group is a container for display objects that allows for fast pooling, recycling and collision checks. - * - * A Physics Group is the same as an ordinary Group except that is has enableBody turned on by default, so any Sprites it creates - * are automatically given a physics body. - * - * @method Phaser.GameObjectFactory#physicsGroup - * @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.P2JS, Phaser.Physics.NINJA, etc. - * @param {any} [parent] - The parent Group or DisplayObjectContainer that will hold this group, if any. If set to null the Group won't be added to the display list. If undefined it will be added to World by default. - * @param {string} [name='group'] - A name for this Group. Not used internally but useful for debugging. - * @param {boolean} [addToStage=false] - If set to true this Group will be added directly to the Game.Stage instead of Game.World. - * @return {Phaser.Group} The newly created Group. - */ + * A Group is a container for display objects that allows for fast pooling, recycling and collision checks. + * + * A Physics Group is the same as an ordinary Group except that is has enableBody turned on by default, so any Sprites it creates + * are automatically given a physics body. + * + * @method Phaser.GameObjectFactory#physicsGroup + * @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.P2JS, Phaser.Physics.NINJA, etc. + * @param {any} [parent] - The parent Group or DisplayObjectContainer that will hold this group, if any. If set to null the Group won't be added to the display list. If undefined it will be added to World by default. + * @param {string} [name='group'] - A name for this Group. Not used internally but useful for debugging. + * @param {boolean} [addToStage=false] - If set to true this Group will be added directly to the Game.Stage instead of Game.World. + * @return {Phaser.Group} The newly created Group. + */ physicsGroup: function (physicsBodyType, parent, name, addToStage) { - return new Phaser.Group(this.game, parent, name, addToStage, true, physicsBodyType); - }, /** - * A SpriteBatch is a really fast version of a Phaser Group built solely for speed. - * Use when you need a lot of sprites or particles all sharing the same texture. - * The speed gains are specifically for WebGL. In Canvas mode you won't see any real difference. - * - * @method Phaser.GameObjectFactory#spriteBatch - * @param {Phaser.Group|null} parent - The parent Group that will hold this Sprite Batch. Set to `undefined` or `null` to add directly to game.world. - * @param {string} [name='group'] - A name for this Sprite Batch. Not used internally but useful for debugging. - * @param {boolean} [addToStage=false] - If set to true this Sprite Batch will be added directly to the Game.Stage instead of the parent. - * @return {Phaser.SpriteBatch} The newly created Sprite Batch. - */ + * A SpriteBatch is a really fast version of a Phaser Group built solely for speed. + * Use when you need a lot of sprites or particles all sharing the same texture. + * The speed gains are specifically for WebGL. In Canvas mode you won't see any real difference. + * + * @method Phaser.GameObjectFactory#spriteBatch + * @param {Phaser.Group|null} parent - The parent Group that will hold this Sprite Batch. Set to `undefined` or `null` to add directly to game.world. + * @param {string} [name='group'] - A name for this Sprite Batch. Not used internally but useful for debugging. + * @param {boolean} [addToStage=false] - If set to true this Sprite Batch will be added directly to the Game.Stage instead of the parent. + * @return {Phaser.SpriteBatch} The newly created Sprite Batch. + */ spriteBatch: function (parent, name, addToStage) { - if (parent === undefined) { parent = null; } if (name === undefined) { name = 'group'; } if (addToStage === undefined) { addToStage = false; } return new Phaser.SpriteBatch(this.game, parent, name, addToStage); - }, /** - * Creates a new Sound object. - * - * @method Phaser.GameObjectFactory#audio - * @param {string} key - The Game.cache key of the sound that this object will use. - * @param {number} [volume=1] - The volume at which the sound will be played. - * @param {boolean} [loop=false] - Whether or not the sound will loop. - * @param {boolean} [connect=true] - Controls if the created Sound object will connect to the master gainNode of the SoundManager when running under WebAudio. - * @return {Phaser.Sound} The newly created sound object. - */ + * Creates a new Sound object. + * + * @method Phaser.GameObjectFactory#audio + * @param {string} key - The Game.cache key of the sound that this object will use. + * @param {number} [volume=1] - The volume at which the sound will be played. + * @param {boolean} [loop=false] - Whether or not the sound will loop. + * @param {boolean} [connect=true] - Controls if the created Sound object will connect to the master gainNode of the SoundManager when running under WebAudio. + * @return {Phaser.Sound} The newly created sound object. + */ audio: function (key, volume, loop, connect) { - return this.game.sound.add(key, volume, loop, connect); - }, /** - * Creates a new Sound object. - * - * @method Phaser.GameObjectFactory#sound - * @param {string} key - The Game.cache key of the sound that this object will use. - * @param {number} [volume=1] - The volume at which the sound will be played. - * @param {boolean} [loop=false] - Whether or not the sound will loop. - * @param {boolean} [connect=true] - Controls if the created Sound object will connect to the master gainNode of the SoundManager when running under WebAudio. - * @return {Phaser.Sound} The newly created sound object. - */ + * Creates a new Sound object. + * + * @method Phaser.GameObjectFactory#sound + * @param {string} key - The Game.cache key of the sound that this object will use. + * @param {number} [volume=1] - The volume at which the sound will be played. + * @param {boolean} [loop=false] - Whether or not the sound will loop. + * @param {boolean} [connect=true] - Controls if the created Sound object will connect to the master gainNode of the SoundManager when running under WebAudio. + * @return {Phaser.Sound} The newly created sound object. + */ sound: function (key, volume, loop, connect) { - return this.game.sound.add(key, volume, loop, connect); - }, /** @@ -289,242 +265,221 @@ Phaser.GameObjectFactory.prototype = { */ audioSprite: function (key) { - return this.game.sound.addSprite(key); - }, /** - * Creates a new TileSprite object. - * - * @method Phaser.GameObjectFactory#tileSprite - * @param {number} x - The x coordinate of the TileSprite. The coordinate is relative to any parent container this TileSprite may be in. - * @param {number} y - The y coordinate of the TileSprite. The coordinate is relative to any parent container this TileSprite may be in. - * @param {number} width - The width of the TileSprite. - * @param {number} height - The height of the TileSprite. - * @param {string|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 Phaser Image Cache entry, or an instance of a PIXI.Texture or BitmapData. - * @param {string|number} [frame] - If a Texture Atlas or Sprite Sheet is used this allows you to specify the frame to be used. Use either an integer for a Frame ID or a string for a frame name. - * @param {Phaser.Group|Phaser.Stage} [group] - Optional Group to add the object to. If not specified it will be added to the World group. - * @return {Phaser.TileSprite} The newly created TileSprite object. - */ + * Creates a new TileSprite object. + * + * @method Phaser.GameObjectFactory#tileSprite + * @param {number} x - The x coordinate of the TileSprite. The coordinate is relative to any parent container this TileSprite may be in. + * @param {number} y - The y coordinate of the TileSprite. The coordinate is relative to any parent container this TileSprite may be in. + * @param {number} width - The width of the TileSprite. + * @param {number} height - The height of the TileSprite. + * @param {string|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 Phaser Image Cache entry, or an instance of a PIXI.Texture or BitmapData. + * @param {string|number} [frame] - If a Texture Atlas or Sprite Sheet is used this allows you to specify the frame to be used. Use either an integer for a Frame ID or a string for a frame name. + * @param {Phaser.Group|Phaser.Stage} [group] - Optional Group to add the object to. If not specified it will be added to the World group. + * @return {Phaser.TileSprite} The newly created TileSprite object. + */ tileSprite: function (x, y, width, height, key, frame, group) { - if (group === undefined) { group = this.world; } return group.add(new Phaser.TileSprite(this.game, x, y, width, height, key, frame)); - }, /** - * Creates a new Rope object. - * - * Example usage: https://github.com/codevinsky/phaser-rope-demo/blob/master/dist/demo.js - * - * @method Phaser.GameObjectFactory#rope - * @param {number} [x=0] - The x coordinate of the Rope. The coordinate is relative to any parent container this rope may be in. - * @param {number} [y=0] - The y coordinate of the Rope. The coordinate is relative to any parent container this rope may be in. - * @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - The image used as a texture by this display object during rendering. If a string Phaser will get for an entry in the Image Cache. Or it can be an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. - * @param {string|number} [frame] - If a Texture Atlas or Sprite Sheet is used this allows you to specify the frame to be used. Use either an integer for a Frame ID or a string for a frame name. - * @param {Array} points - An array of {Phaser.Point}. - * @param {Phaser.Group|Phaser.Stage} [group] - Optional Group to add the object to. If not specified it will be added to the World group. - * @return {Phaser.Rope} The newly created Rope object. - */ + * Creates a new Rope object. + * + * Example usage: https://github.com/codevinsky/phaser-rope-demo/blob/master/dist/demo.js + * + * @method Phaser.GameObjectFactory#rope + * @param {number} [x=0] - The x coordinate of the Rope. The coordinate is relative to any parent container this rope may be in. + * @param {number} [y=0] - The y coordinate of the Rope. The coordinate is relative to any parent container this rope may be in. + * @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - The image used as a texture by this display object during rendering. If a string Phaser will get for an entry in the Image Cache. Or it can be an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. + * @param {string|number} [frame] - If a Texture Atlas or Sprite Sheet is used this allows you to specify the frame to be used. Use either an integer for a Frame ID or a string for a frame name. + * @param {Array} points - An array of {Phaser.Point}. + * @param {Phaser.Group|Phaser.Stage} [group] - Optional Group to add the object to. If not specified it will be added to the World group. + * @return {Phaser.Rope} The newly created Rope object. + */ rope: function (x, y, key, frame, points, group) { - if (group === undefined) { group = this.world; } return group.add(new Phaser.Rope(this.game, x, y, key, frame, points)); - }, /** - * Creates a new Text object. - * - * @method Phaser.GameObjectFactory#text - * @param {number} [x=0] - The x coordinate of the Text. The coordinate is relative to any parent container this text may be in. - * @param {number} [y=0] - The y coordinate of the Text. The coordinate is relative to any parent container this text may be in. - * @param {string} [text=''] - The text string that will be displayed. - * @param {object} [style] - The style object containing style attributes like font, font size , etc. - * @param {Phaser.Group|Phaser.Stage} [group] - Optional Group to add the object to. If not specified it will be added to the World group. - * @return {Phaser.Text} The newly created text object. - */ + * Creates a new Text object. + * + * @method Phaser.GameObjectFactory#text + * @param {number} [x=0] - The x coordinate of the Text. The coordinate is relative to any parent container this text may be in. + * @param {number} [y=0] - The y coordinate of the Text. The coordinate is relative to any parent container this text may be in. + * @param {string} [text=''] - The text string that will be displayed. + * @param {object} [style] - The style object containing style attributes like font, font size , etc. + * @param {Phaser.Group|Phaser.Stage} [group] - Optional Group to add the object to. If not specified it will be added to the World group. + * @return {Phaser.Text} The newly created text object. + */ text: function (x, y, text, style, group) { - if (group === undefined) { group = this.world; } return group.add(new Phaser.Text(this.game, x, y, text, style)); - }, /** - * Creates a new Button object. - * - * @method Phaser.GameObjectFactory#button - * @param {number} [x=0] - The x coordinate of the Button. The coordinate is relative to any parent container this button may be in. - * @param {number} [y=0] - The y coordinate of the Button. The coordinate is relative to any parent container this button may be in. - * @param {string} [key] - The image key as defined in the Game.Cache to use as the texture for this button. - * @param {function} [callback] - The function to call when this button is pressed - * @param {object} [callbackContext] - The context in which the callback will be called (usually 'this') - * @param {string|number} [overFrame] - This is the frame or frameName that will be set when this button is in an over state. Give either a number to use a frame ID or a string for a frame name. - * @param {string|number} [outFrame] - This is the frame or frameName that will be set when this button is in an out state. Give either a number to use a frame ID or a string for a frame name. - * @param {string|number} [downFrame] - This is the frame or frameName that will be set when this button is in a down state. Give either a number to use a frame ID or a string for a frame name. - * @param {string|number} [upFrame] - This is the frame or frameName that will be set when this button is in an up state. Give either a number to use a frame ID or a string for a frame name. - * @param {Phaser.Group|Phaser.Stage} [group] - Optional Group to add the object to. If not specified it will be added to the World group. - * @return {Phaser.Button} The newly created Button object. - */ + * Creates a new Button object. + * + * @method Phaser.GameObjectFactory#button + * @param {number} [x=0] - The x coordinate of the Button. The coordinate is relative to any parent container this button may be in. + * @param {number} [y=0] - The y coordinate of the Button. The coordinate is relative to any parent container this button may be in. + * @param {string} [key] - The image key as defined in the Game.Cache to use as the texture for this button. + * @param {function} [callback] - The function to call when this button is pressed + * @param {object} [callbackContext] - The context in which the callback will be called (usually 'this') + * @param {string|number} [overFrame] - This is the frame or frameName that will be set when this button is in an over state. Give either a number to use a frame ID or a string for a frame name. + * @param {string|number} [outFrame] - This is the frame or frameName that will be set when this button is in an out state. Give either a number to use a frame ID or a string for a frame name. + * @param {string|number} [downFrame] - This is the frame or frameName that will be set when this button is in a down state. Give either a number to use a frame ID or a string for a frame name. + * @param {string|number} [upFrame] - This is the frame or frameName that will be set when this button is in an up state. Give either a number to use a frame ID or a string for a frame name. + * @param {Phaser.Group|Phaser.Stage} [group] - Optional Group to add the object to. If not specified it will be added to the World group. + * @return {Phaser.Button} The newly created Button object. + */ button: function (x, y, key, callback, callbackContext, overFrame, outFrame, downFrame, upFrame, group) { - if (group === undefined) { group = this.world; } return group.add(new Phaser.Button(this.game, x, y, key, callback, callbackContext, overFrame, outFrame, downFrame, upFrame)); - }, /** - * Creates a new Graphics object. - * - * @method Phaser.GameObjectFactory#graphics - * @param {number} [x=0] - The x coordinate of the Graphic. The coordinate is relative to any parent container this object may be in. - * @param {number} [y=0] - The y coordinate of the Graphic. The coordinate is relative to any parent container this object may be in. - * @param {Phaser.Group|Phaser.Stage} [group] - Optional Group to add the object to. If not specified it will be added to the World group. - * @return {Phaser.Graphics} The newly created graphics object. - */ + * Creates a new Graphics object. + * + * @method Phaser.GameObjectFactory#graphics + * @param {number} [x=0] - The x coordinate of the Graphic. The coordinate is relative to any parent container this object may be in. + * @param {number} [y=0] - The y coordinate of the Graphic. The coordinate is relative to any parent container this object may be in. + * @param {Phaser.Group|Phaser.Stage} [group] - Optional Group to add the object to. If not specified it will be added to the World group. + * @return {Phaser.Graphics} The newly created graphics object. + */ graphics: function (x, y, group) { - if (group === undefined) { group = this.world; } return group.add(new Phaser.Graphics(this.game, x, y)); - }, /** - * Create a new Emitter. - * - * A particle emitter can be used for one-time explosions or for - * continuous effects like rain and fire. All it really does is launch Particle objects out - * at set intervals, and fixes their positions and velocities accordingly. - * - * @method Phaser.GameObjectFactory#emitter - * @param {number} [x=0] - The x coordinate within the Emitter that the particles are emitted from. - * @param {number} [y=0] - The y coordinate within the Emitter that the particles are emitted from. - * @param {number} [maxParticles=50] - The total number of particles in this emitter. - * @return {Phaser.Particles.Arcade.Emitter} The newly created emitter object. - */ + * Create a new Emitter. + * + * A particle emitter can be used for one-time explosions or for + * continuous effects like rain and fire. All it really does is launch Particle objects out + * at set intervals, and fixes their positions and velocities accordingly. + * + * @method Phaser.GameObjectFactory#emitter + * @param {number} [x=0] - The x coordinate within the Emitter that the particles are emitted from. + * @param {number} [y=0] - The y coordinate within the Emitter that the particles are emitted from. + * @param {number} [maxParticles=50] - The total number of particles in this emitter. + * @return {Phaser.Particles.Arcade.Emitter} The newly created emitter object. + */ emitter: function (x, y, maxParticles) { - return this.game.particles.add(new Phaser.Particles.Arcade.Emitter(this.game, x, y, maxParticles)); - }, /** - * Create a new RetroFont object. - * - * A RetroFont can be used as a texture for an Image or Sprite and optionally add it to the Cache. - * A RetroFont uses a bitmap which contains fixed with characters for the font set. You use character spacing to define the set. - * If you need variable width character support then use a BitmapText object instead. The main difference between a RetroFont and a BitmapText - * is that a RetroFont creates a single texture that you can apply to a game object, where-as a BitmapText creates one Sprite object per letter of text. - * The texture can be asssigned or one or multiple images/sprites, but note that the text the RetroFont uses will be shared across them all, - * i.e. if you need each Image to have different text in it, then you need to create multiple RetroFont objects. - * - * @method Phaser.GameObjectFactory#retroFont - * @param {string} font - The key of the image in the Game.Cache that the RetroFont will use. - * @param {number} characterWidth - The width of each character in the font set. - * @param {number} characterHeight - The height of each character in the font set. - * @param {string} chars - The characters used in the font set, in display order. You can use the TEXT_SET consts for common font set arrangements. - * @param {number} charsPerRow - The number of characters per row in the font set. - * @param {number} [xSpacing=0] - If the characters in the font set have horizontal spacing between them set the required amount here. - * @param {number} [ySpacing=0] - If the characters in the font set have vertical spacing between them set the required amount here. - * @param {number} [xOffset=0] - If the font set doesn't start at the top left of the given image, specify the X coordinate offset here. - * @param {number} [yOffset=0] - If the font set doesn't start at the top left of the given image, specify the Y coordinate offset here. - * @return {Phaser.RetroFont} The newly created RetroFont texture which can be applied to an Image or Sprite. - */ + * Create a new RetroFont object. + * + * A RetroFont can be used as a texture for an Image or Sprite and optionally add it to the Cache. + * A RetroFont uses a bitmap which contains fixed with characters for the font set. You use character spacing to define the set. + * If you need variable width character support then use a BitmapText object instead. The main difference between a RetroFont and a BitmapText + * is that a RetroFont creates a single texture that you can apply to a game object, where-as a BitmapText creates one Sprite object per letter of text. + * The texture can be asssigned or one or multiple images/sprites, but note that the text the RetroFont uses will be shared across them all, + * i.e. if you need each Image to have different text in it, then you need to create multiple RetroFont objects. + * + * @method Phaser.GameObjectFactory#retroFont + * @param {string} font - The key of the image in the Game.Cache that the RetroFont will use. + * @param {number} characterWidth - The width of each character in the font set. + * @param {number} characterHeight - The height of each character in the font set. + * @param {string} chars - The characters used in the font set, in display order. You can use the TEXT_SET consts for common font set arrangements. + * @param {number} charsPerRow - The number of characters per row in the font set. + * @param {number} [xSpacing=0] - If the characters in the font set have horizontal spacing between them set the required amount here. + * @param {number} [ySpacing=0] - If the characters in the font set have vertical spacing between them set the required amount here. + * @param {number} [xOffset=0] - If the font set doesn't start at the top left of the given image, specify the X coordinate offset here. + * @param {number} [yOffset=0] - If the font set doesn't start at the top left of the given image, specify the Y coordinate offset here. + * @return {Phaser.RetroFont} The newly created RetroFont texture which can be applied to an Image or Sprite. + */ retroFont: function (font, characterWidth, characterHeight, chars, charsPerRow, xSpacing, ySpacing, xOffset, yOffset) { - return new Phaser.RetroFont(this.game, font, characterWidth, characterHeight, chars, charsPerRow, xSpacing, ySpacing, xOffset, yOffset); - }, /** - * Create a new BitmapText object. - * - * BitmapText objects work by taking a texture file and an XML file that describes the font structure. - * It then generates a new Sprite object for each letter of the text, proportionally spaced out and aligned to - * match the font structure. - * - * BitmapText objects are less flexible than Text objects, in that they have less features such as shadows, fills and the ability - * to use Web Fonts. However you trade this flexibility for pure rendering speed. You can also create visually compelling BitmapTexts by - * processing the font texture in an image editor first, applying fills and any other effects required. - * - * To create multi-line text insert \r, \n or \r\n escape codes into the text string. - * - * To create a BitmapText data files you can use: - * - * BMFont (Windows, free): http://www.angelcode.com/products/bmfont/ - * Glyph Designer (OS X, commercial): http://www.71squared.com/en/glyphdesigner - * Littera (Web-based, free): http://kvazars.com/littera/ - * - * @method Phaser.GameObjectFactory#bitmapText - * @param {number} x - X coordinate to display the BitmapText object at. - * @param {number} y - Y coordinate to display the BitmapText object at. - * @param {string} font - The key of the BitmapText as stored in Phaser.Cache. - * @param {string} [text=''] - The text that will be rendered. This can also be set later via BitmapText.text. - * @param {number} [size=32] - The size the font will be rendered at in pixels. - * @param {Phaser.Group|Phaser.Stage} [group] - Optional Group to add the object to. If not specified it will be added to the World group. - * @return {Phaser.BitmapText} The newly created bitmapText object. - */ + * Create a new BitmapText object. + * + * BitmapText objects work by taking a texture file and an XML file that describes the font structure. + * It then generates a new Sprite object for each letter of the text, proportionally spaced out and aligned to + * match the font structure. + * + * BitmapText objects are less flexible than Text objects, in that they have less features such as shadows, fills and the ability + * to use Web Fonts. However you trade this flexibility for pure rendering speed. You can also create visually compelling BitmapTexts by + * processing the font texture in an image editor first, applying fills and any other effects required. + * + * To create multi-line text insert \r, \n or \r\n escape codes into the text string. + * + * To create a BitmapText data files you can use: + * + * BMFont (Windows, free): http://www.angelcode.com/products/bmfont/ + * Glyph Designer (OS X, commercial): http://www.71squared.com/en/glyphdesigner + * Littera (Web-based, free): http://kvazars.com/littera/ + * + * @method Phaser.GameObjectFactory#bitmapText + * @param {number} x - X coordinate to display the BitmapText object at. + * @param {number} y - Y coordinate to display the BitmapText object at. + * @param {string} font - The key of the BitmapText as stored in Phaser.Cache. + * @param {string} [text=''] - The text that will be rendered. This can also be set later via BitmapText.text. + * @param {number} [size=32] - The size the font will be rendered at in pixels. + * @param {Phaser.Group|Phaser.Stage} [group] - Optional Group to add the object to. If not specified it will be added to the World group. + * @return {Phaser.BitmapText} The newly created bitmapText object. + */ bitmapText: function (x, y, font, text, size, group) { - if (group === undefined) { group = this.world; } return group.add(new Phaser.BitmapText(this.game, x, y, font, text, size)); - }, /** - * Creates a new Phaser.Tilemap object. - * - * The map can either be populated with data from a Tiled JSON file or from a CSV file. - * To do this pass the Cache key as the first parameter. When using Tiled data you need only provide the key. - * When using CSV data you must provide the key and the tileWidth and tileHeight parameters. - * If creating a blank tilemap to be populated later, you can either specify no parameters at all and then use `Tilemap.create` or pass the map and tile dimensions here. - * Note that all Tilemaps use a base tile size to calculate dimensions from, but that a TilemapLayer may have its own unique tile size that overrides it. - * - * @method Phaser.GameObjectFactory#tilemap - * @param {string} [key] - The key of the tilemap data as stored in the Cache. If you're creating a blank map either leave this parameter out or pass `null`. - * @param {number} [tileWidth=32] - The pixel width of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data. - * @param {number} [tileHeight=32] - The pixel height of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data. - * @param {number} [width=10] - The width of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this. - * @param {number} [height=10] - The height of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this. - * @return {Phaser.Tilemap} The newly created tilemap object. - */ + * Creates a new Phaser.Tilemap object. + * + * The map can either be populated with data from a Tiled JSON file or from a CSV file. + * To do this pass the Cache key as the first parameter. When using Tiled data you need only provide the key. + * When using CSV data you must provide the key and the tileWidth and tileHeight parameters. + * If creating a blank tilemap to be populated later, you can either specify no parameters at all and then use `Tilemap.create` or pass the map and tile dimensions here. + * Note that all Tilemaps use a base tile size to calculate dimensions from, but that a TilemapLayer may have its own unique tile size that overrides it. + * + * @method Phaser.GameObjectFactory#tilemap + * @param {string} [key] - The key of the tilemap data as stored in the Cache. If you're creating a blank map either leave this parameter out or pass `null`. + * @param {number} [tileWidth=32] - The pixel width of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data. + * @param {number} [tileHeight=32] - The pixel height of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data. + * @param {number} [width=10] - The width of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this. + * @param {number} [height=10] - The height of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this. + * @return {Phaser.Tilemap} The newly created tilemap object. + */ tilemap: function (key, tileWidth, tileHeight, width, height) { - return new Phaser.Tilemap(this.game, key, tileWidth, tileHeight, width, height); - }, /** - * A dynamic initially blank canvas to which images can be drawn. - * - * @method Phaser.GameObjectFactory#renderTexture - * @param {number} [width=100] - the width of the RenderTexture. - * @param {number} [height=100] - the height of the RenderTexture. - * @param {string} [key=''] - Asset key for the RenderTexture when stored in the Cache (see addToCache parameter). - * @param {boolean} [addToCache=false] - Should this RenderTexture be added to the Game.Cache? If so you can retrieve it with Cache.getTexture(key) - * @return {Phaser.RenderTexture} The newly created RenderTexture object. - */ + * A dynamic initially blank canvas to which images can be drawn. + * + * @method Phaser.GameObjectFactory#renderTexture + * @param {number} [width=100] - the width of the RenderTexture. + * @param {number} [height=100] - the height of the RenderTexture. + * @param {string} [key=''] - Asset key for the RenderTexture when stored in the Cache (see addToCache parameter). + * @param {boolean} [addToCache=false] - Should this RenderTexture be added to the Game.Cache? If so you can retrieve it with Cache.getTexture(key) + * @return {Phaser.RenderTexture} The newly created RenderTexture object. + */ renderTexture: function (width, height, key, addToCache) { - if (key === undefined || key === '') { key = this.game.rnd.uuid(); } if (addToCache === undefined) { addToCache = false; } @@ -536,41 +491,37 @@ Phaser.GameObjectFactory.prototype = { } return texture; - }, /** - * Create a Video object. - * - * This will return a Phaser.Video object which you can pass to a Sprite to be used as a texture. - * - * @method Phaser.GameObjectFactory#video - * @param {string|null} [key=null] - The key of the video file in the Phaser.Cache that this Video object will play. Set to `null` or leave undefined if you wish to use a webcam as the source. See `startMediaStream` to start webcam capture. - * @param {string|null} [url=null] - If the video hasn't been loaded then you can provide a full URL to the file here (make sure to set key to null) - * @return {Phaser.Video} The newly created Video object. - */ + * Create a Video object. + * + * This will return a Phaser.Video object which you can pass to a Sprite to be used as a texture. + * + * @method Phaser.GameObjectFactory#video + * @param {string|null} [key=null] - The key of the video file in the Phaser.Cache that this Video object will play. Set to `null` or leave undefined if you wish to use a webcam as the source. See `startMediaStream` to start webcam capture. + * @param {string|null} [url=null] - If the video hasn't been loaded then you can provide a full URL to the file here (make sure to set key to null) + * @return {Phaser.Video} The newly created Video object. + */ video: function (key, url) { - return new Phaser.Video(this.game, key, url); - }, /** - * Create a BitmapData object. - * - * A BitmapData object can be manipulated and drawn to like a traditional Canvas object and used to texture Sprites. - * - * @method Phaser.GameObjectFactory#bitmapData - * @param {number} [width=256] - The width of the BitmapData in pixels. - * @param {number} [height=256] - The height of the BitmapData in pixels. - * @param {string} [key=''] - Asset key for the BitmapData when stored in the Cache (see addToCache parameter). - * @param {boolean} [addToCache=false] - Should this BitmapData be added to the Game.Cache? If so you can retrieve it with Cache.getBitmapData(key) - * @return {Phaser.BitmapData} The newly created BitmapData object. - */ + * Create a BitmapData object. + * + * A BitmapData object can be manipulated and drawn to like a traditional Canvas object and used to texture Sprites. + * + * @method Phaser.GameObjectFactory#bitmapData + * @param {number} [width=256] - The width of the BitmapData in pixels. + * @param {number} [height=256] - The height of the BitmapData in pixels. + * @param {string} [key=''] - Asset key for the BitmapData when stored in the Cache (see addToCache parameter). + * @param {boolean} [addToCache=false] - Should this BitmapData be added to the Game.Cache? If so you can retrieve it with Cache.getBitmapData(key) + * @return {Phaser.BitmapData} The newly created BitmapData object. + */ bitmapData: function (width, height, key, addToCache) { - if (addToCache === undefined) { addToCache = false; } if (key === undefined || key === '') { key = this.game.rnd.uuid(); } @@ -582,20 +533,18 @@ Phaser.GameObjectFactory.prototype = { } return texture; - }, /** - * A WebGL shader/filter that can be applied to Sprites. - * - * @method Phaser.GameObjectFactory#filter - * @param {string} filter - The name of the filter you wish to create, for example HueRotate or SineWave. - * @param {any} - Whatever parameters are needed to be passed to the filter init function. - * @return {Phaser.Filter} The newly created Phaser.Filter object. - */ + * A WebGL shader/filter that can be applied to Sprites. + * + * @method Phaser.GameObjectFactory#filter + * @param {string} filter - The name of the filter you wish to create, for example HueRotate or SineWave. + * @param {any} - Whatever parameters are needed to be passed to the filter init function. + * @return {Phaser.Filter} The newly created Phaser.Filter object. + */ filter: function (filter) { - var args = Array.prototype.slice.call(arguments, 1); var filter = new Phaser.Filter[filter](this.game); @@ -603,24 +552,21 @@ Phaser.GameObjectFactory.prototype = { filter.init.apply(filter, args); return filter; - }, /** - * Add a new Plugin into the PluginManager. - * - * The Plugin must have 2 properties: `game` and `parent`. Plugin.game is set to the game reference the PluginManager uses, and parent is set to the PluginManager. - * - * @method Phaser.GameObjectFactory#plugin - * @param {object|Phaser.Plugin} plugin - The Plugin to add into the PluginManager. This can be a function or an existing object. - * @param {...*} parameter - Additional parameters that will be passed to the Plugin.init method. - * @return {Phaser.Plugin} The Plugin that was added to the manager. - */ + * Add a new Plugin into the PluginManager. + * + * The Plugin must have 2 properties: `game` and `parent`. Plugin.game is set to the game reference the PluginManager uses, and parent is set to the PluginManager. + * + * @method Phaser.GameObjectFactory#plugin + * @param {object|Phaser.Plugin} plugin - The Plugin to add into the PluginManager. This can be a function or an existing object. + * @param {...*} parameter - Additional parameters that will be passed to the Plugin.init method. + * @return {Phaser.Plugin} The Plugin that was added to the manager. + */ plugin: function () { - return this.game.plugins.add.apply(this.game.plugins, arguments); - } }; diff --git a/src/gameobjects/Graphics.js b/src/gameobjects/Graphics.js index c798011f1..007532667 100644 --- a/src/gameobjects/Graphics.js +++ b/src/gameobjects/Graphics.js @@ -1,78 +1,77 @@ /** -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* A Graphics object is a way to draw primitives to your game. Primitives include forms of geometry, such as Rectangles, -* Circles and Polygons. They also include lines, arcs and curves. When you initially create a Graphics object it will -* be empty. To 'draw' to it you first specify a lineStyle or fillStyle (or both), and then draw a shape. For example: -* -* ```javascript -* graphics.beginFill(0xff0000); -* graphics.drawCircle(50, 50, 100); -* graphics.endFill(); -* ``` -* -* This will draw a circle shape to the Graphics object, with a diameter of 100, located at x: 50, y: 50. -* -* When a Graphics object is rendered it will render differently based on if the game is running under Canvas or -* WebGL. Under Canvas it will use the HTML Canvas context drawing operations to draw the path. Under WebGL the -* graphics data is decomposed into polygons. Both of these are expensive processes, especially with complex shapes. -* -* If your Graphics object doesn't change much (or at all) once you've drawn your shape to it, then you will help -* performance by calling `Graphics.generateTexture`. This will 'bake' the Graphics object into a Texture, and return it. -* You can then use this Texture for Sprites or other display objects. If your Graphics object updates frequently then -* you should avoid doing this, as it will constantly generate new textures, which will consume memory. -* -* As you can tell, Graphics objects are a bit of a trade-off. While they are extremely useful, you need to be careful -* in their complexity and quantity of them in your game. -* -* You may have to modify {@link Phaser.Graphics#scale} rather than {@link Phaser.Graphics#width} or -* {@link Phaser.Graphics#height} to avoid an unusual race condition -* ({@link #489 https://github.com/photonstorm/phaser-ce/issues/489}). -* -* @class Phaser.Graphics -* @constructor -* @extends PIXI.DisplayObjectContainer -* @extends Phaser.Component.Core -* @extends Phaser.Component.Angle -* @extends Phaser.Component.AutoCull -* @extends Phaser.Component.Bounds -* @extends Phaser.Component.Destroy -* @extends Phaser.Component.FixedToCamera -* @extends Phaser.Component.InputEnabled -* @extends Phaser.Component.InWorld -* @extends Phaser.Component.LifeSpan -* @extends Phaser.Component.PhysicsBody -* @extends Phaser.Component.Reset -* @param {Phaser.Game} game - Current game instance. -* @param {number} [x=0] - X position of the new graphics object. -* @param {number} [y=0] - Y position of the new graphics object. -*/ + * A Graphics object is a way to draw primitives to your game. Primitives include forms of geometry, such as Rectangles, + * Circles and Polygons. They also include lines, arcs and curves. When you initially create a Graphics object it will + * be empty. To 'draw' to it you first specify a lineStyle or fillStyle (or both), and then draw a shape. For example: + * + * ```javascript + * graphics.beginFill(0xff0000); + * graphics.drawCircle(50, 50, 100); + * graphics.endFill(); + * ``` + * + * This will draw a circle shape to the Graphics object, with a diameter of 100, located at x: 50, y: 50. + * + * When a Graphics object is rendered it will render differently based on if the game is running under Canvas or + * WebGL. Under Canvas it will use the HTML Canvas context drawing operations to draw the path. Under WebGL the + * graphics data is decomposed into polygons. Both of these are expensive processes, especially with complex shapes. + * + * If your Graphics object doesn't change much (or at all) once you've drawn your shape to it, then you will help + * performance by calling `Graphics.generateTexture`. This will 'bake' the Graphics object into a Texture, and return it. + * You can then use this Texture for Sprites or other display objects. If your Graphics object updates frequently then + * you should avoid doing this, as it will constantly generate new textures, which will consume memory. + * + * As you can tell, Graphics objects are a bit of a trade-off. While they are extremely useful, you need to be careful + * in their complexity and quantity of them in your game. + * + * You may have to modify {@link Phaser.Graphics#scale} rather than {@link Phaser.Graphics#width} or + * {@link Phaser.Graphics#height} to avoid an unusual race condition + * ({@link #489 https://github.com/photonstorm/phaser-ce/issues/489}). + * + * @class Phaser.Graphics + * @constructor + * @extends PIXI.DisplayObjectContainer + * @extends Phaser.Component.Core + * @extends Phaser.Component.Angle + * @extends Phaser.Component.AutoCull + * @extends Phaser.Component.Bounds + * @extends Phaser.Component.Destroy + * @extends Phaser.Component.FixedToCamera + * @extends Phaser.Component.InputEnabled + * @extends Phaser.Component.InWorld + * @extends Phaser.Component.LifeSpan + * @extends Phaser.Component.PhysicsBody + * @extends Phaser.Component.Reset + * @param {Phaser.Game} game - Current game instance. + * @param {number} [x=0] - X position of the new graphics object. + * @param {number} [y=0] - Y position of the new graphics object. + */ Phaser.Graphics = function (game, x, y) { - if (x === undefined) { x = 0; } if (y === undefined) { y = 0; } /** - * @property {number} type - The const type of this object. - * @default - */ + * @property {number} type - The const type of this object. + * @default + */ this.type = Phaser.GRAPHICS; /** - * @property {number} physicsType - The const physics body type of this object. - * @readonly - */ + * @property {number} physicsType - The const physics body type of this object. + * @readonly + */ this.physicsType = Phaser.SPRITE; /** - * @property {Phaser.Point} anchor - Required for a Graphics shape to work as a Physics body, do not modify this value. - * @private - */ + * @property {Phaser.Point} anchor - Required for a Graphics shape to work as a Physics body, do not modify this value. + * @private + */ this.anchor = new Phaser.Point(); PIXI.DisplayObjectContainer.call(this); @@ -213,7 +212,6 @@ Phaser.Graphics = function (game, x, y) this.cachedSpriteDirty = false; Phaser.Component.Core.init.call(this, game, x, y, '', null); - }; Phaser.Graphics.prototype = Object.create(PIXI.DisplayObjectContainer.prototype); @@ -238,30 +236,27 @@ Phaser.Graphics.prototype.preUpdateInWorld = Phaser.Component.InWorld.preUpdate; Phaser.Graphics.prototype.preUpdateCore = Phaser.Component.Core.preUpdate; /** -* Automatically called by World.preUpdate. -* -* @method Phaser.Graphics#preUpdate -*/ + * Automatically called by World.preUpdate. + * + * @method Phaser.Graphics#preUpdate + */ Phaser.Graphics.prototype.preUpdate = function () { - if (!this.preUpdatePhysics() || !this.preUpdateLifeSpan() || !this.preUpdateInWorld()) { return false; } return this.preUpdateCore(); - }; /** -* Automatically called by World -* -* @method Phaser.Graphics#postUpdate -*/ + * Automatically called by World + * + * @method Phaser.Graphics#postUpdate + */ Phaser.Graphics.prototype.postUpdate = function () { - Phaser.Component.PhysicsBody.postUpdate.call(this); Phaser.Component.FixedToCamera.postUpdate.call(this); @@ -275,34 +270,30 @@ Phaser.Graphics.prototype.postUpdate = function () { this.children[i].postUpdate(); } - }; /** -* Destroy this Graphics instance. -* -* @method Phaser.Graphics#destroy -* @param {boolean} [destroyChildren=true] - Should every child of this object have its destroy method called? -*/ + * Destroy this Graphics instance. + * + * @method Phaser.Graphics#destroy + * @param {boolean} [destroyChildren=true] - Should every child of this object have its destroy method called? + */ Phaser.Graphics.prototype.destroy = function (destroyChildren) { - this.clear(); Phaser.Component.Destroy.prototype.destroy.call(this, destroyChildren); - }; /** -* Draws a single {@link Phaser.Polygon} triangle from a {@link Phaser.Point} array -* -* @method Phaser.Graphics#drawTriangle -* @param {Array} points - An array of Phaser.Points that make up the three vertices of this triangle -* @param {boolean} [cull=false] - Should we check if the triangle is back-facing -*/ + * Draws a single {@link Phaser.Polygon} triangle from a {@link Phaser.Point} array + * + * @method Phaser.Graphics#drawTriangle + * @param {Array} points - An array of Phaser.Points that make up the three vertices of this triangle + * @param {boolean} [cull=false] - Should we check if the triangle is back-facing + */ Phaser.Graphics.prototype.drawTriangle = function (points, cull) { - if (cull === undefined) { cull = false; } var triangle = new Phaser.Polygon(points); @@ -323,20 +314,18 @@ Phaser.Graphics.prototype.drawTriangle = function (points, cull) { this.drawPolygon(triangle); } - }; /** -* Draws {@link Phaser.Polygon} triangles -* -* @method Phaser.Graphics#drawTriangles -* @param {Array|Array} vertices - An array of Phaser.Points or numbers that make up the vertices of the triangles -* @param {Array} [indices=null] - An array of numbers that describe what order to draw the vertices in -* @param {boolean} [cull=false] - Should we check if the triangle is back-facing -*/ + * Draws {@link Phaser.Polygon} triangles + * + * @method Phaser.Graphics#drawTriangles + * @param {Array|Array} vertices - An array of Phaser.Points or numbers that make up the vertices of the triangles + * @param {Array} [indices=null] - An array of numbers that describe what order to draw the vertices in + * @param {boolean} [cull=false] - Should we check if the triangle is back-facing + */ Phaser.Graphics.prototype.drawTriangles = function (vertices, indices, cull) { - if (cull === undefined) { cull = false; } var point1 = new Phaser.Point(); @@ -412,7 +401,6 @@ Phaser.Graphics.prototype.drawTriangles = function (vertices, indices, cull) */ Phaser.Graphics.prototype.lineStyle = function (lineWidth, color, alpha) { - this.lineWidth = lineWidth || 0; this.lineColor = color || 0; this.lineAlpha = (alpha === undefined) ? 1 : alpha; @@ -434,7 +422,6 @@ Phaser.Graphics.prototype.lineStyle = function (lineWidth, color, alpha) } return this; - }; /** @@ -444,14 +431,12 @@ Phaser.Graphics.prototype.lineStyle = function (lineWidth, color, alpha) * @param x {Number} the X coordinate to move to * @param y {Number} the Y coordinate to move to * @return {Graphics} - */ + */ Phaser.Graphics.prototype.moveTo = function (x, y) { - this.drawShape(new Phaser.Polygon([ x, y ])); return this; - }; /** @@ -465,7 +450,6 @@ Phaser.Graphics.prototype.moveTo = function (x, y) */ Phaser.Graphics.prototype.lineTo = function (x, y) { - if (!this.currentPath) { this.moveTo(0, 0); @@ -476,7 +460,6 @@ Phaser.Graphics.prototype.lineTo = function (x, y) this._boundsDirty = true; return this; - }; /** @@ -492,7 +475,6 @@ Phaser.Graphics.prototype.lineTo = function (x, y) */ Phaser.Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) { - if (this.currentPath) { if (this.currentPath.shape.points.length === 0) @@ -533,7 +515,6 @@ Phaser.Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) this._boundsDirty = true; return this; - }; /** @@ -550,7 +531,6 @@ Phaser.Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) */ Phaser.Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) { - if (this.currentPath) { if (this.currentPath.shape.points.length === 0) @@ -594,7 +574,6 @@ Phaser.Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, t this._boundsDirty = true; return this; - }; /** @@ -612,7 +591,6 @@ Phaser.Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, t */ Phaser.Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) { - if (this.currentPath) { if (this.currentPath.shape.points.length === 0) @@ -666,7 +644,6 @@ Phaser.Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) this._boundsDirty = true; return this; - }; /** @@ -684,7 +661,6 @@ Phaser.Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) */ Phaser.Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise, segments) { - // If we do this we can never draw a full circle if (startAngle === endAngle) { @@ -754,7 +730,6 @@ Phaser.Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, this._boundsDirty = true; return this; - }; /** @@ -768,7 +743,6 @@ Phaser.Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, */ Phaser.Graphics.prototype.beginFill = function (color, alpha) { - this.filling = true; this.fillColor = color || 0; this.fillAlpha = (alpha === undefined) ? 1 : alpha; @@ -784,7 +758,6 @@ Phaser.Graphics.prototype.beginFill = function (color, alpha) } return this; - }; /** @@ -795,13 +768,11 @@ Phaser.Graphics.prototype.beginFill = function (color, alpha) */ Phaser.Graphics.prototype.endFill = function () { - this.filling = false; this.fillColor = null; this.fillAlpha = 1; return this; - }; /** @@ -815,11 +786,9 @@ Phaser.Graphics.prototype.endFill = function () */ Phaser.Graphics.prototype.drawRect = function (x, y, width, height) { - this.drawShape(new Phaser.Rectangle(x, y, width, height)); return this; - }; /** @@ -832,11 +801,9 @@ Phaser.Graphics.prototype.drawRect = function (x, y, width, height) */ Phaser.Graphics.prototype.drawRoundedRect = function (x, y, width, height, radius) { - this.drawShape(new Phaser.RoundedRectangle(x, y, width, height, radius)); return this; - }; /** @@ -850,11 +817,9 @@ Phaser.Graphics.prototype.drawRoundedRect = function (x, y, width, height, radiu */ Phaser.Graphics.prototype.drawCircle = function (x, y, diameter) { - this.drawShape(new Phaser.Circle(x, y, diameter)); return this; - }; /** @@ -869,11 +834,9 @@ Phaser.Graphics.prototype.drawCircle = function (x, y, diameter) */ Phaser.Graphics.prototype.drawEllipse = function (centerX, centerY, halfWidth, halfHeight) { - this.drawShape({x: centerX, y: centerY, width: halfWidth, height: halfHeight, type: Phaser.ELLIPSE}); return this; - }; /** @@ -885,20 +848,23 @@ Phaser.Graphics.prototype.drawEllipse = function (centerX, centerY, halfWidth, h */ Phaser.Graphics.prototype.drawPolygon = function (path) { - if (path instanceof Phaser.Polygon) { path = path.points; } - // prevents an argument assignment deopt - // see section 3.1: https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#3-managing-arguments + /* + * prevents an argument assignment deopt + * see section 3.1: https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#3-managing-arguments + */ var points = path; if (!Array.isArray(points)) { - // prevents an argument leak deopt - // see section 3.2: https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#3-managing-arguments + /* + * prevents an argument leak deopt + * see section 3.2: https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#3-managing-arguments + */ points = new Array(arguments.length); for (var i = 0; i < points.length; ++i) @@ -910,7 +876,6 @@ Phaser.Graphics.prototype.drawPolygon = function (path) this.drawShape(new Phaser.Polygon(points)); return this; - }; /** @@ -921,7 +886,6 @@ Phaser.Graphics.prototype.drawPolygon = function (path) */ Phaser.Graphics.prototype.clear = function () { - this.lineWidth = 0; this.filling = false; @@ -933,7 +897,6 @@ Phaser.Graphics.prototype.clear = function () this.updateLocalBounds(); return this; - }; /** @@ -950,7 +913,6 @@ Phaser.Graphics.prototype.clear = function () */ Phaser.Graphics.prototype.generateTexture = function (resolution, scaleMode, padding) { - if (resolution === undefined) { resolution = 1; } if (scaleMode === undefined) { scaleMode = PIXI.scaleModes.DEFAULT; } if (padding === undefined) { padding = 0; } @@ -973,19 +935,17 @@ Phaser.Graphics.prototype.generateTexture = function (resolution, scaleMode, pad PIXI.CanvasGraphics.renderGraphics(this, canvasBuffer.context); return texture; - }; /** -* Renders the object using the WebGL renderer -* -* @method Phaser.Graphics#_renderWebGL -* @param renderSession {RenderSession} -* @private -*/ + * Renders the object using the WebGL renderer + * + * @method Phaser.Graphics#_renderWebGL + * @param renderSession {RenderSession} + * @private + */ Phaser.Graphics.prototype._renderWebGL = function (renderSession) { - // if the sprite is not visible or the alpha is 0 then no need to render this element if (this.visible === false || this.alpha === 0 || this.isMask === true) { @@ -1071,19 +1031,17 @@ Phaser.Graphics.prototype._renderWebGL = function (renderSession) renderSession.spriteBatch.start(); } - }; /** -* Renders the object using the Canvas renderer -* -* @method Phaser.Graphics#_renderCanvas -* @param renderSession {RenderSession} -* @private -*/ + * Renders the object using the Canvas renderer + * + * @method Phaser.Graphics#_renderCanvas + * @param renderSession {RenderSession} + * @private + */ Phaser.Graphics.prototype._renderCanvas = function (renderSession) { - // if the sprite is not visible or the alpha is 0 then no need to render this element if (this.visible === false || this.alpha === 0 || this.isMask === true) { @@ -1156,7 +1114,6 @@ Phaser.Graphics.prototype._renderCanvas = function (renderSession) renderSession.maskManager.popMask(renderSession); } } - }; /** @@ -1172,7 +1129,6 @@ Phaser.Graphics.prototype._renderCanvas = function (renderSession) */ Phaser.Graphics.prototype.getBounds = function (matrix) { - if (this._currentBounds) { return this._currentBounds; @@ -1252,7 +1208,6 @@ Phaser.Graphics.prototype.getBounds = function (matrix) this._currentBounds = this._bounds; return this._currentBounds; - }; /** @@ -1263,7 +1218,6 @@ Phaser.Graphics.prototype.getBounds = function (matrix) */ Phaser.Graphics.prototype.getLocalBounds = function () { - var matrixCache = this.worldTransform; this.worldTransform = Phaser.identityMatrix; @@ -1283,18 +1237,16 @@ Phaser.Graphics.prototype.getLocalBounds = function () } return bounds; - }; /** -* Tests if a point is inside this graphics object -* -* @param point {Point} the point to test -* @return {boolean} the result of the test -*/ + * Tests if a point is inside this graphics object + * + * @param point {Point} the point to test + * @return {boolean} the result of the test + */ Phaser.Graphics.prototype.containsPoint = function (point, tempPoint) { - if (tempPoint === undefined) { tempPoint = new Phaser.Point(); } this.worldTransform.applyInverse(point, tempPoint); @@ -1321,7 +1273,6 @@ Phaser.Graphics.prototype.containsPoint = function (point, tempPoint) } return false; - }; @@ -1336,7 +1287,6 @@ Phaser.Graphics.prototype.containsPoint = function (point, tempPoint) */ Phaser.Graphics.prototype.getVisualBounds = function (output) { - if (this._boundsDirty) { this.updateLocalBounds(); @@ -1344,7 +1294,6 @@ Phaser.Graphics.prototype.getVisualBounds = function (output) } return this._localBounds.clone(output); - }; /** @@ -1354,7 +1303,6 @@ Phaser.Graphics.prototype.getVisualBounds = function (output) */ Phaser.Graphics.prototype.updateLocalBounds = function () { - var minX = Infinity; var maxX = -Infinity; @@ -1458,7 +1406,6 @@ Phaser.Graphics.prototype.updateLocalBounds = function () this._localBounds.y = minY - padding; this._localBounds.height = (maxY - minY) + padding * 2; - }; /** @@ -1469,7 +1416,6 @@ Phaser.Graphics.prototype.updateLocalBounds = function () */ Phaser.Graphics.prototype._generateCachedSprite = function () { - var bounds = this.getLocalBounds(); if (!this._cachedSprite) @@ -1500,7 +1446,6 @@ Phaser.Graphics.prototype._generateCachedSprite = function () // now render the graphic.. PIXI.CanvasGraphics.renderGraphics(this, this._cachedSprite.buffer.context); this._cachedSprite.alpha = this.alpha; - }; /** @@ -1511,7 +1456,6 @@ Phaser.Graphics.prototype._generateCachedSprite = function () */ Phaser.Graphics.prototype.updateCachedSpriteTexture = function () { - var cachedSprite = this._cachedSprite; var texture = cachedSprite.texture; var canvas = cachedSprite.buffer.canvas; @@ -1526,7 +1470,6 @@ Phaser.Graphics.prototype.updateCachedSpriteTexture = function () // update the dirty base textures texture.baseTexture.dirty(); - }; /** @@ -1536,10 +1479,8 @@ Phaser.Graphics.prototype.updateCachedSpriteTexture = function () */ Phaser.Graphics.prototype.destroyCachedSprite = function () { - this._cachedSprite.texture.destroy(true); this._cachedSprite = null; - }; /** @@ -1551,7 +1492,6 @@ Phaser.Graphics.prototype.destroyCachedSprite = function () */ Phaser.Graphics.prototype.drawShape = function (shape) { - if (this.currentPath) { // check current path! @@ -1584,7 +1524,6 @@ Phaser.Graphics.prototype.drawShape = function (shape) this._boundsDirty = true; return data; - }; /** @@ -1602,14 +1541,11 @@ Object.defineProperty(Phaser.Graphics.prototype, 'cacheAsBitmap', { get: function () { - return this._cacheAsBitmap; - }, set: function (value) { - this._cacheAsBitmap = value; if (this._cacheAsBitmap) @@ -1623,6 +1559,5 @@ Object.defineProperty(Phaser.Graphics.prototype, 'cacheAsBitmap', { this.dirty = true; this.webGLDirty = true; - } }); diff --git a/src/gameobjects/GraphicsData.js b/src/gameobjects/GraphicsData.js index cf9a75e8d..b1c20942d 100644 --- a/src/gameobjects/GraphicsData.js +++ b/src/gameobjects/GraphicsData.js @@ -14,7 +14,6 @@ Phaser.GraphicsData = function (lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) { - /* * @member {number} the width of the line to draw */ @@ -64,7 +63,6 @@ Phaser.GraphicsData = function (lineWidth, lineColor, lineAlpha, fillColor, fill * @member {number} The type of the shape, see the Const.Shapes file for all the existing types, */ this.type = shape.type; - }; Phaser.GraphicsData.prototype.constructor = Phaser.GraphicsData; @@ -76,7 +74,6 @@ Phaser.GraphicsData.prototype.constructor = Phaser.GraphicsData; */ Phaser.GraphicsData.prototype.clone = function () { - return new Phaser.GraphicsData( this.lineWidth, this.lineColor, @@ -86,5 +83,4 @@ Phaser.GraphicsData.prototype.clone = function () this.fill, this.shape ); - }; diff --git a/src/gameobjects/Image.js b/src/gameobjects/Image.js index 34847cc9c..99d055fc3 100644 --- a/src/gameobjects/Image.js +++ b/src/gameobjects/Image.js @@ -1,57 +1,55 @@ /** -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* An Image is a light-weight object you can use to display anything that doesn't need health, physics, or complex position monitoring. -* -* It can still rotate, scale, crop and receive input events. This makes it perfect for logos, backgrounds, simple buttons and other non-Sprite graphics. -* -* @class Phaser.Image -* @extends PIXI.Sprite -* @extends Phaser.Component.Core -* @extends Phaser.Component.Angle -* @extends Phaser.Component.Animation -* @extends Phaser.Component.AutoCull -* @extends Phaser.Component.Bounds -* @extends Phaser.Component.BringToTop -* @extends Phaser.Component.Crop -* @extends Phaser.Component.Destroy -* @extends Phaser.Component.FixedToCamera -* @extends Phaser.Component.InputEnabled -* @extends Phaser.Component.LifeSpan -* @extends Phaser.Component.LoadTexture -* @extends Phaser.Component.Overlap -* @extends Phaser.Component.Reset -* @extends Phaser.Component.ScaleMinMax -* @extends Phaser.Component.Smoothed -* @constructor -* @param {Phaser.Game} game - A reference to the currently running game. -* @param {number} [x=0] - The x coordinate of the Image. The coordinate is relative to any parent container this Image may be in. -* @param {number} [y=0] - The y coordinate of the Image. The coordinate is relative to any parent container this Image may be in. -* @param {string|Phaser.RenderTexture|Phaser.BitmapData|PIXI.Texture} [key] - The texture used by the Image during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture, BitmapData or PIXI.Texture. If this argument is omitted, the image will receive {@link Phaser.Cache.DEFAULT the default texture} (as if you had passed '__default'), but its `key` will remain empty. -* @param {string|number} [frame] - If this Image is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. -*/ + * An Image is a light-weight object you can use to display anything that doesn't need health, physics, or complex position monitoring. + * + * It can still rotate, scale, crop and receive input events. This makes it perfect for logos, backgrounds, simple buttons and other non-Sprite graphics. + * + * @class Phaser.Image + * @extends PIXI.Sprite + * @extends Phaser.Component.Core + * @extends Phaser.Component.Angle + * @extends Phaser.Component.Animation + * @extends Phaser.Component.AutoCull + * @extends Phaser.Component.Bounds + * @extends Phaser.Component.BringToTop + * @extends Phaser.Component.Crop + * @extends Phaser.Component.Destroy + * @extends Phaser.Component.FixedToCamera + * @extends Phaser.Component.InputEnabled + * @extends Phaser.Component.LifeSpan + * @extends Phaser.Component.LoadTexture + * @extends Phaser.Component.Overlap + * @extends Phaser.Component.Reset + * @extends Phaser.Component.ScaleMinMax + * @extends Phaser.Component.Smoothed + * @constructor + * @param {Phaser.Game} game - A reference to the currently running game. + * @param {number} [x=0] - The x coordinate of the Image. The coordinate is relative to any parent container this Image may be in. + * @param {number} [y=0] - The y coordinate of the Image. The coordinate is relative to any parent container this Image may be in. + * @param {string|Phaser.RenderTexture|Phaser.BitmapData|PIXI.Texture} [key] - The texture used by the Image during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture, BitmapData or PIXI.Texture. If this argument is omitted, the image will receive {@link Phaser.Cache.DEFAULT the default texture} (as if you had passed '__default'), but its `key` will remain empty. + * @param {string|number} [frame] - If this Image is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. + */ Phaser.Image = function (game, x, y, key, frame) { - x = x || 0; y = y || 0; key = key || null; frame = frame || null; /** - * @property {number} type - The const type of this object. - * @readonly - */ + * @property {number} type - The const type of this object. + * @readonly + */ this.type = Phaser.IMAGE; PIXI.Sprite.call(this, Phaser.Cache.DEFAULT); Phaser.Component.Core.init.call(this, game, x, y, key, frame); - }; Phaser.Image.prototype = Object.create(PIXI.Sprite.prototype); @@ -80,19 +78,17 @@ Phaser.Image.prototype.preUpdateInWorld = Phaser.Component.InWorld.preUpdate; Phaser.Image.prototype.preUpdateCore = Phaser.Component.Core.preUpdate; /** -* Automatically called by World.preUpdate. -* -* @method Phaser.Image#preUpdate -* @memberof Phaser.Image -*/ + * Automatically called by World.preUpdate. + * + * @method Phaser.Image#preUpdate + * @memberof Phaser.Image + */ Phaser.Image.prototype.preUpdate = function () { - if (!this.preUpdateInWorld() || !this.preUpdateLifeSpan()) { return false; } return this.preUpdateCore(); - }; diff --git a/src/gameobjects/Particle.js b/src/gameobjects/Particle.js index 3ac766713..4152bf4e1 100644 --- a/src/gameobjects/Particle.js +++ b/src/gameobjects/Particle.js @@ -1,76 +1,73 @@ /** -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* Create a new `Particle` object. Particles are extended Sprites that are emitted by a particle emitter such as Phaser.Particles.Arcade.Emitter. -* -* @class Phaser.Particle -* @constructor -* @extends Phaser.Sprite -* @param {Phaser.Game} game - A reference to the currently running game. -* @param {number} x - The x coordinate (in world space) to position the Particle at. -* @param {number} y - The y coordinate (in world space) to position the Particle at. -* @param {string|Phaser.RenderTexture|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the Particle during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture. -* @param {string|number} frame - If this Particle 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. -*/ + * Create a new `Particle` object. Particles are extended Sprites that are emitted by a particle emitter such as Phaser.Particles.Arcade.Emitter. + * + * @class Phaser.Particle + * @constructor + * @extends Phaser.Sprite + * @param {Phaser.Game} game - A reference to the currently running game. + * @param {number} x - The x coordinate (in world space) to position the Particle at. + * @param {number} y - The y coordinate (in world space) to position the Particle at. + * @param {string|Phaser.RenderTexture|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the Particle during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture. + * @param {string|number} frame - If this Particle is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. + */ Phaser.Particle = function (game, x, y, key, frame) { - Phaser.Sprite.call(this, game, x, y, key, frame); /** - * @property {boolean} autoScale - If this Particle automatically scales this is set to true by Particle.setScaleData. - * @protected - */ + * @property {boolean} autoScale - If this Particle automatically scales this is set to true by Particle.setScaleData. + * @protected + */ this.autoScale = false; /** - * @property {array} scaleData - A reference to the scaleData array owned by the Emitter that emitted this Particle. - * @protected - */ + * @property {array} scaleData - A reference to the scaleData array owned by the Emitter that emitted this Particle. + * @protected + */ this.scaleData = null; /** - * @property {number} _s - Internal cache var for tracking auto scale. - * @private - */ + * @property {number} _s - Internal cache var for tracking auto scale. + * @private + */ this._s = 0; /** - * @property {boolean} autoAlpha - If this Particle automatically changes alpha this is set to true by Particle.setAlphaData. - * @protected - */ + * @property {boolean} autoAlpha - If this Particle automatically changes alpha this is set to true by Particle.setAlphaData. + * @protected + */ this.autoAlpha = false; /** - * @property {array} alphaData - A reference to the alphaData array owned by the Emitter that emitted this Particle. - * @protected - */ + * @property {array} alphaData - A reference to the alphaData array owned by the Emitter that emitted this Particle. + * @protected + */ this.alphaData = null; /** - * @property {number} _a - Internal cache var for tracking auto alpha. - * @private - */ + * @property {number} _a - Internal cache var for tracking auto alpha. + * @private + */ this._a = 0; - }; Phaser.Particle.prototype = Object.create(Phaser.Sprite.prototype); Phaser.Particle.prototype.constructor = Phaser.Particle; /** -* Updates the Particle scale or alpha if autoScale and autoAlpha are set. -* -* @method Phaser.Particle#update -* @memberof Phaser.Particle -*/ + * Updates the Particle scale or alpha if autoScale and autoAlpha are set. + * + * @method Phaser.Particle#update + * @memberof Phaser.Particle + */ Phaser.Particle.prototype.update = function () { - if (this.autoScale) { this._s--; @@ -98,66 +95,60 @@ Phaser.Particle.prototype.update = function () this.autoAlpha = false; } } - }; /** -* Called by the Emitter when this particle is emitted. Left empty for you to over-ride as required. -* -* @method Phaser.Particle#onEmit -* @memberof Phaser.Particle -*/ + * Called by the Emitter when this particle is emitted. Left empty for you to over-ride as required. + * + * @method Phaser.Particle#onEmit + * @memberof Phaser.Particle + */ Phaser.Particle.prototype.onEmit = function () { }; /** -* Called by the Emitter if autoAlpha has been enabled. Passes over the alpha ease data and resets the alpha counter. -* -* @method Phaser.Particle#setAlphaData -* @memberof Phaser.Particle -*/ + * Called by the Emitter if autoAlpha has been enabled. Passes over the alpha ease data and resets the alpha counter. + * + * @method Phaser.Particle#setAlphaData + * @memberof Phaser.Particle + */ Phaser.Particle.prototype.setAlphaData = function (data) { - this.alphaData = data; this._a = data.length - 1; this.alpha = this.alphaData[this._a].v; this.autoAlpha = true; - }; /** -* Called by the Emitter if autoScale has been enabled. Passes over the scale ease data and resets the scale counter. -* -* @method Phaser.Particle#setScaleData -* @memberof Phaser.Particle -*/ + * Called by the Emitter if autoScale has been enabled. Passes over the scale ease data and resets the scale counter. + * + * @method Phaser.Particle#setScaleData + * @memberof Phaser.Particle + */ Phaser.Particle.prototype.setScaleData = function (data) { - this.scaleData = data; this._s = data.length - 1; this.scale.set(this.scaleData[this._s].x, this.scaleData[this._s].y); this.autoScale = true; - }; /** -* Resets the Particle. This places the Particle at the given x/y world coordinates and then -* sets alive, exists, visible and renderable all to true. Also resets the outOfBounds state and health values. -* If the Particle has a physics body that too is reset. -* -* @method Phaser.Particle#reset -* @memberof Phaser.Particle -* @param {number} x - The x coordinate (in world space) to position the Particle at. -* @param {number} y - The y coordinate (in world space) to position the Particle at. -* @param {number} [health=1] - The health to give the Particle. -* @return {Phaser.Particle} This instance. -*/ + * Resets the Particle. This places the Particle at the given x/y world coordinates and then + * sets alive, exists, visible and renderable all to true. Also resets the outOfBounds state and health values. + * If the Particle has a physics body that too is reset. + * + * @method Phaser.Particle#reset + * @memberof Phaser.Particle + * @param {number} x - The x coordinate (in world space) to position the Particle at. + * @param {number} y - The y coordinate (in world space) to position the Particle at. + * @param {number} [health=1] - The health to give the Particle. + * @return {Phaser.Particle} This instance. + */ Phaser.Particle.prototype.reset = function (x, y, health) { - Phaser.Component.Reset.prototype.reset.call(this, x, y, health); this.alpha = 1; @@ -167,5 +158,4 @@ Phaser.Particle.prototype.reset = function (x, y, health) this.autoAlpha = false; return this; - }; diff --git a/src/gameobjects/RenderTexture.js b/src/gameobjects/RenderTexture.js index 0b4dd44c1..666250c80 100644 --- a/src/gameobjects/RenderTexture.js +++ b/src/gameobjects/RenderTexture.js @@ -1,26 +1,25 @@ /** -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* A RenderTexture is a special texture that allows any displayObject to be rendered to it. It allows you to take many complex objects and -* render them down into a single quad (on WebGL) which can then be used to texture other display objects with. A way of generating textures at run-time. -* -* @class Phaser.RenderTexture -* @constructor -* @extends PIXI.Texture -* @param {Phaser.Game} game - Current game instance. -* @param {number} [width=100] - The width of the render texture. -* @param {number} [height=100] - The height of the render texture. -* @param {string} [key=''] - The key of the RenderTexture in the Cache, if stored there. -* @param {number} [scaleMode=Phaser.scaleModes.DEFAULT] - One of the Phaser.scaleModes consts. -* @param {number} [resolution=1] - The resolution of the texture being generated. -*/ + * A RenderTexture is a special texture that allows any displayObject to be rendered to it. It allows you to take many complex objects and + * render them down into a single quad (on WebGL) which can then be used to texture other display objects with. A way of generating textures at run-time. + * + * @class Phaser.RenderTexture + * @constructor + * @extends PIXI.Texture + * @param {Phaser.Game} game - Current game instance. + * @param {number} [width=100] - The width of the render texture. + * @param {number} [height=100] - The height of the render texture. + * @param {string} [key=''] - The key of the RenderTexture in the Cache, if stored there. + * @param {number} [scaleMode=Phaser.scaleModes.DEFAULT] - One of the Phaser.scaleModes consts. + * @param {number} [resolution=1] - The resolution of the texture being generated. + */ Phaser.RenderTexture = function (game, width, height, key, scaleMode, resolution, renderer, textureUnit) { - if (width === undefined) { width = 100; } if (height === undefined) { height = 100; } if (key === undefined) { key = ''; } @@ -30,24 +29,24 @@ Phaser.RenderTexture = function (game, width, height, key, scaleMode, resolution if (textureUnit === undefined) { textureUnit = 0; } /** - * @property {Phaser.Game} game - A reference to the currently running game. - */ + * @property {Phaser.Game} game - A reference to the currently running game. + */ this.game = game; /** - * @property {string} key - The key of the RenderTexture in the Cache, if stored there. - */ + * @property {string} key - The key of the RenderTexture in the Cache, if stored there. + */ this.key = key; /** - * @property {number} type - Base Phaser object type. - */ + * @property {number} type - Base Phaser object type. + */ this.type = Phaser.RENDERTEXTURE; /** - * @property {Phaser.Matrix} _tempMatrix - The matrix that is applied when display objects are rendered to this RenderTexture. - * @private - */ + * @property {Phaser.Matrix} _tempMatrix - The matrix that is applied when display objects are rendered to this RenderTexture. + * @private + */ this._tempMatrix = new Phaser.Matrix(); this.width = width; @@ -110,28 +109,26 @@ Phaser.RenderTexture = function (game, width, height, key, scaleMode, resolution this.tempMatrix = new Phaser.Matrix(); this._updateUvs(); - }; Phaser.RenderTexture.prototype = Object.create(PIXI.Texture.prototype); Phaser.RenderTexture.prototype.constructor = Phaser.RenderTexture; /** -* This function will draw the display object to the RenderTexture at the given coordinates. -* -* When the display object is drawn it takes into account scale and rotation. -* -* If you don't want those then use RenderTexture.renderRawXY instead. -* -* @method Phaser.RenderTexture.prototype.renderXY -* @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapText|Phaser.Group} displayObject - The display object to render to this texture. -* @param {number} x - The x position to render the object at. -* @param {number} y - The y position to render the object at. -* @param {boolean} [clear=false] - If true the texture will be cleared before the display object is drawn. -*/ + * This function will draw the display object to the RenderTexture at the given coordinates. + * + * When the display object is drawn it takes into account scale and rotation. + * + * If you don't want those then use RenderTexture.renderRawXY instead. + * + * @method Phaser.RenderTexture.prototype.renderXY + * @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapText|Phaser.Group} displayObject - The display object to render to this texture. + * @param {number} x - The x position to render the object at. + * @param {number} y - The y position to render the object at. + * @param {boolean} [clear=false] - If true the texture will be cleared before the display object is drawn. + */ Phaser.RenderTexture.prototype.renderXY = function (displayObject, x, y, clear) { - displayObject.updateTransform(); this._tempMatrix.copyFrom(displayObject.worldTransform); @@ -146,25 +143,23 @@ Phaser.RenderTexture.prototype.renderXY = function (displayObject, x, y, clear) { this._renderCanvas(displayObject, this._tempMatrix, clear); } - }; /** -* This function will draw the display object to the RenderTexture at the given coordinates. -* -* When the display object is drawn it doesn't take into account scale, rotation or translation. -* -* If you need those then use RenderTexture.renderXY instead. -* -* @method Phaser.RenderTexture.prototype.renderRawXY -* @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapText|Phaser.Group} displayObject - The display object to render to this texture. -* @param {number} x - The x position to render the object at. -* @param {number} y - The y position to render the object at. -* @param {boolean} [clear=false] - If true the texture will be cleared before the display object is drawn. -*/ + * This function will draw the display object to the RenderTexture at the given coordinates. + * + * When the display object is drawn it doesn't take into account scale, rotation or translation. + * + * If you need those then use RenderTexture.renderXY instead. + * + * @method Phaser.RenderTexture.prototype.renderRawXY + * @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapText|Phaser.Group} displayObject - The display object to render to this texture. + * @param {number} x - The x position to render the object at. + * @param {number} y - The y position to render the object at. + * @param {boolean} [clear=false] - If true the texture will be cleared before the display object is drawn. + */ Phaser.RenderTexture.prototype.renderRawXY = function (displayObject, x, y, clear) { - this._tempMatrix.identity().translate(x, y); if (this.renderer.type === Phaser.WEBGL) @@ -175,27 +170,25 @@ Phaser.RenderTexture.prototype.renderRawXY = function (displayObject, x, y, clea { this._renderCanvas(displayObject, this._tempMatrix, clear); } - }; /** -* This function will draw the display object to the RenderTexture. -* -* In versions of Phaser prior to 2.4.0 the second parameter was a Phaser.Point object. -* This is now a Matrix allowing you much more control over how the Display Object is rendered. -* If you need to replicate the earlier behavior please use Phaser.RenderTexture.renderXY instead. -* -* If you wish for the displayObject to be rendered taking its current scale, rotation and translation into account then either -* pass `null`, leave it undefined or pass `displayObject.worldTransform` as the matrix value. -* -* @method Phaser.RenderTexture.prototype.render -* @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapText|Phaser.Group} displayObject - The display object to render to this texture. -* @param {Phaser.Matrix} [matrix] - Optional matrix to apply to the display object before rendering. If null or undefined it will use the worldTransform matrix of the given display object. -* @param {boolean} [clear=false] - If true the texture will be cleared before the display object is drawn. -*/ + * This function will draw the display object to the RenderTexture. + * + * In versions of Phaser prior to 2.4.0 the second parameter was a Phaser.Point object. + * This is now a Matrix allowing you much more control over how the Display Object is rendered. + * If you need to replicate the earlier behavior please use Phaser.RenderTexture.renderXY instead. + * + * If you wish for the displayObject to be rendered taking its current scale, rotation and translation into account then either + * pass `null`, leave it undefined or pass `displayObject.worldTransform` as the matrix value. + * + * @method Phaser.RenderTexture.prototype.render + * @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapText|Phaser.Group} displayObject - The display object to render to this texture. + * @param {Phaser.Matrix} [matrix] - Optional matrix to apply to the display object before rendering. If null or undefined it will use the worldTransform matrix of the given display object. + * @param {boolean} [clear=false] - If true the texture will be cleared before the display object is drawn. + */ Phaser.RenderTexture.prototype.render = function (displayObject, matrix, clear) { - if (matrix === undefined || matrix === null) { this._tempMatrix.copyFrom(displayObject.worldTransform); @@ -213,20 +206,18 @@ Phaser.RenderTexture.prototype.render = function (displayObject, matrix, clear) { this._renderCanvas(displayObject, this._tempMatrix, clear); } - }; /** -* Resizes the RenderTexture. -* -* @method Phaser.RenderTexture.prototype.resize -* @param {number} width - The width to resize to. -* @param {number} height - The height to resize to. -* @param {boolean} updateBase - Should the baseTexture.width and height values be resized as well? -*/ + * Resizes the RenderTexture. + * + * @method Phaser.RenderTexture.prototype.resize + * @param {number} width - The width to resize to. + * @param {number} height - The height to resize to. + * @param {boolean} updateBase - Should the baseTexture.width and height values be resized as well? + */ Phaser.RenderTexture.prototype.resize = function (width, height, updateBase) { - if (width === this.width && height === this.height) { return; @@ -257,17 +248,15 @@ Phaser.RenderTexture.prototype.resize = function (width, height, updateBase) } this.textureBuffer.resize(this.width, this.height); - }; /** -* Clears the RenderTexture. -* -* @method Phaser.RenderTexture.prototype.clear -*/ + * Clears the RenderTexture. + * + * @method Phaser.RenderTexture.prototype.clear + */ Phaser.RenderTexture.prototype.clear = function () { - if (!this.valid) { return; @@ -279,29 +268,29 @@ Phaser.RenderTexture.prototype.clear = function () } this.textureBuffer.clear(); - }; /** -* This function will draw the display object to the texture. -* -* @private -* @method Phaser.RenderTexture.prototype._renderWebGL -* @param displayObject {DisplayObject} The display object to render this texture on -* @param [matrix] {Matrix} Optional matrix to apply to the display object before rendering. -* @param [clear] {Boolean} If true the texture will be cleared before the displayObject is drawn -* @private -*/ + * This function will draw the display object to the texture. + * + * @private + * @method Phaser.RenderTexture.prototype._renderWebGL + * @param displayObject {DisplayObject} The display object to render this texture on + * @param [matrix] {Matrix} Optional matrix to apply to the display object before rendering. + * @param [clear] {Boolean} If true the texture will be cleared before the displayObject is drawn + * @private + */ Phaser.RenderTexture.prototype._renderWebGL = function (displayObject, matrix, clear) { - if (!this.valid || displayObject.alpha === 0) { return; } - // Let's create a nice matrix to apply to our display object. - // Frame buffers come in upside down so we need to flip the matrix. + /* + * Let's create a nice matrix to apply to our display object. + * Frame buffers come in upside down so we need to flip the matrix. + */ var wt = displayObject.worldTransform; wt.identity(); wt.translate(0, this.projection.y * 2); @@ -338,28 +327,28 @@ Phaser.RenderTexture.prototype._renderWebGL = function (displayObject, matrix, c this.renderer.spriteBatch.dirty = true; gl.bindFramebuffer(gl.FRAMEBUFFER, null); - }; /** -* This function will draw the display object to the texture. -* -* @private -* @method Phaser.RenderTexture.prototype._renderCanvas -* @param displayObject {DisplayObject} The display object to render this texture on -* @param [matrix] {Matrix} Optional matrix to apply to the display object before rendering. -* @param [clear] {Boolean} If true the texture will be cleared before the displayObject is drawn -*/ + * This function will draw the display object to the texture. + * + * @private + * @method Phaser.RenderTexture.prototype._renderCanvas + * @param displayObject {DisplayObject} The display object to render this texture on + * @param [matrix] {Matrix} Optional matrix to apply to the display object before rendering. + * @param [clear] {Boolean} If true the texture will be cleared before the displayObject is drawn + */ Phaser.RenderTexture.prototype._renderCanvas = function (displayObject, matrix, clear) { - if (!this.valid || displayObject.alpha === 0) { return; } - // Let's create a nice matrix to apply to our display object. - // Frame buffers come in upside down so we need to flip the matrix. + /* + * Let's create a nice matrix to apply to our display object. + * Frame buffers come in upside down so we need to flip the matrix. + */ var wt = displayObject.worldTransform; wt.identity(); @@ -386,28 +375,26 @@ Phaser.RenderTexture.prototype._renderCanvas = function (displayObject, matrix, this.renderer.renderDisplayObject(displayObject, this.textureBuffer.context, matrix); this.renderer.resolution = realResolution; - }; /** -* Returns an HTML Image of the texture -* -* The image is loaded asynchronously, not right away. -* Use the callbacks if you need to wait for the loaded image. -* -* @method Phaser.RenderTexture.prototype.getImage -* @param {string} [type] - Image format. -* @param {number} [encoderOptions] - Image quality, for lossy formats. -* @param {function} [onLoadCallback] - A function to call when the image loads. -* @param {function} [onErrorCallback] - A function to call when the image fails to load. -* @return {Image} -* -* @see https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toDataURL -*/ + * Returns an HTML Image of the texture + * + * The image is loaded asynchronously, not right away. + * Use the callbacks if you need to wait for the loaded image. + * + * @method Phaser.RenderTexture.prototype.getImage + * @param {string} [type] - Image format. + * @param {number} [encoderOptions] - Image quality, for lossy formats. + * @param {function} [onLoadCallback] - A function to call when the image loads. + * @param {function} [onErrorCallback] - A function to call when the image fails to load. + * @return {Image} + * + * @see https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toDataURL + */ Phaser.RenderTexture.prototype.getImage = function (type, encoderOptions, onLoadCallback, onErrorCallback) { - var image = new Image(); image.src = this.getBase64(type, encoderOptions); @@ -415,35 +402,31 @@ Phaser.RenderTexture.prototype.getImage = function (type, encoderOptions, onLoad if (onErrorCallback) { image.onerror = onErrorCallback; } return image; - }; /** -* Returns a base64 encoded string of this texture. It works by calling RenderTexture.getCanvas and then running toDataURL on that. -* -* @method Phaser.RenderTexture.prototype.getBase64 -* @param {string} [type] - Image format. -* @param {number} [encoderOptions] - Image quality, for lossy formats. -* @return {String} A base64 encoded string of the texture. -* -* @see https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toDataURL -*/ + * Returns a base64 encoded string of this texture. It works by calling RenderTexture.getCanvas and then running toDataURL on that. + * + * @method Phaser.RenderTexture.prototype.getBase64 + * @param {string} [type] - Image format. + * @param {number} [encoderOptions] - Image quality, for lossy formats. + * @return {String} A base64 encoded string of the texture. + * + * @see https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toDataURL + */ Phaser.RenderTexture.prototype.getBase64 = function (type, encoderOptions) { - return this.getCanvas().toDataURL(type, encoderOptions); - }; /** -* Creates a Canvas element, renders this RenderTexture to it and then returns it. -* -* @method Phaser.RenderTexture.prototype.getCanvas -* @return {HTMLCanvasElement} A Canvas element with the texture rendered on. -*/ + * Creates a Canvas element, renders this RenderTexture to it and then returns it. + * + * @method Phaser.RenderTexture.prototype.getCanvas + * @return {HTMLCanvasElement} A Canvas element with the texture rendered on. + */ Phaser.RenderTexture.prototype.getCanvas = function () { - if (this.renderer.type === Phaser.WEBGL) { var gl = this.renderer.gl; @@ -468,5 +451,4 @@ Phaser.RenderTexture.prototype.getCanvas = function () { return this.textureBuffer.canvas; } - }; diff --git a/src/gameobjects/RetroFont.js b/src/gameobjects/RetroFont.js index f93bd3d58..711407c13 100644 --- a/src/gameobjects/RetroFont.js +++ b/src/gameobjects/RetroFont.js @@ -1,30 +1,29 @@ /** -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* A Retro Font is similar to a BitmapFont, in that it uses a texture to render the text. However unlike a BitmapFont every character in a RetroFont -* is the same size. This makes it similar to a sprite sheet. You typically find font sheets like this from old 8/16-bit games and demos. -* -* @class Phaser.RetroFont -* @extends Phaser.RenderTexture -* @constructor -* @param {Phaser.Game} game - Current game instance. -* @param {string} key - The font set graphic set as stored in the Game.Cache. -* @param {number} characterWidth - The width of each character in the font set. -* @param {number} characterHeight - The height of each character in the font set. -* @param {string} chars - The characters used in the font set, in display order. You can use the TEXT_SET consts for common font set arrangements. -* @param {number} [charsPerRow] - The number of characters per row in the font set. If not given charsPerRow will be the image width / characterWidth. -* @param {number} [xSpacing=0] - If the characters in the font set have horizontal spacing between them set the required amount here. -* @param {number} [ySpacing=0] - If the characters in the font set have vertical spacing between them set the required amount here. -* @param {number} [xOffset=0] - If the font set doesn't start at the top left of the given image, specify the X coordinate offset here. -* @param {number} [yOffset=0] - If the font set doesn't start at the top left of the given image, specify the Y coordinate offset here. -*/ + * A Retro Font is similar to a BitmapFont, in that it uses a texture to render the text. However unlike a BitmapFont every character in a RetroFont + * is the same size. This makes it similar to a sprite sheet. You typically find font sheets like this from old 8/16-bit games and demos. + * + * @class Phaser.RetroFont + * @extends Phaser.RenderTexture + * @constructor + * @param {Phaser.Game} game - Current game instance. + * @param {string} key - The font set graphic set as stored in the Game.Cache. + * @param {number} characterWidth - The width of each character in the font set. + * @param {number} characterHeight - The height of each character in the font set. + * @param {string} chars - The characters used in the font set, in display order. You can use the TEXT_SET consts for common font set arrangements. + * @param {number} [charsPerRow] - The number of characters per row in the font set. If not given charsPerRow will be the image width / characterWidth. + * @param {number} [xSpacing=0] - If the characters in the font set have horizontal spacing between them set the required amount here. + * @param {number} [ySpacing=0] - If the characters in the font set have vertical spacing between them set the required amount here. + * @param {number} [xOffset=0] - If the font set doesn't start at the top left of the given image, specify the X coordinate offset here. + * @param {number} [yOffset=0] - If the font set doesn't start at the top left of the given image, specify the Y coordinate offset here. + */ Phaser.RetroFont = function (game, key, characterWidth, characterHeight, chars, charsPerRow, xSpacing, ySpacing, xOffset, yOffset) { - if (!game.cache.checkImageKey(key)) { return false; @@ -36,98 +35,98 @@ Phaser.RetroFont = function (game, key, characterWidth, characterHeight, chars, } /** - * @property {number} characterWidth - The width of each character in the font set. - */ + * @property {number} characterWidth - The width of each character in the font set. + */ this.characterWidth = characterWidth; /** - * @property {number} characterHeight - The height of each character in the font set. - */ + * @property {number} characterHeight - The height of each character in the font set. + */ this.characterHeight = characterHeight; /** - * @property {number} characterSpacingX - If the characters in the font set have horizontal spacing between them set the required amount here. - */ + * @property {number} characterSpacingX - If the characters in the font set have horizontal spacing between them set the required amount here. + */ this.characterSpacingX = xSpacing || 0; /** - * @property {number} characterSpacingY - If the characters in the font set have vertical spacing between them set the required amount here. - */ + * @property {number} characterSpacingY - If the characters in the font set have vertical spacing between them set the required amount here. + */ this.characterSpacingY = ySpacing || 0; /** - * @property {number} characterPerRow - The number of characters per row in the font set. - */ + * @property {number} characterPerRow - The number of characters per row in the font set. + */ this.characterPerRow = charsPerRow; /** - * @property {number} offsetX - If the font set doesn't start at the top left of the given image, specify the X coordinate offset here. - * @readonly - */ + * @property {number} offsetX - If the font set doesn't start at the top left of the given image, specify the X coordinate offset here. + * @readonly + */ this.offsetX = xOffset || 0; /** - * @property {number} offsetY - If the font set doesn't start at the top left of the given image, specify the Y coordinate offset here. - * @readonly - */ + * @property {number} offsetY - If the font set doesn't start at the top left of the given image, specify the Y coordinate offset here. + * @readonly + */ this.offsetY = yOffset || 0; /** - * @property {string} align - Alignment of the text when multiLine = true or a fixedWidth is set. Set to RetroFont.ALIGN_LEFT (default), RetroFont.ALIGN_RIGHT or RetroFont.ALIGN_CENTER. - */ + * @property {string} align - Alignment of the text when multiLine = true or a fixedWidth is set. Set to RetroFont.ALIGN_LEFT (default), RetroFont.ALIGN_RIGHT or RetroFont.ALIGN_CENTER. + */ this.align = 'left'; /** - * @property {boolean} multiLine - If set to true all carriage-returns in text will form new lines (see align). If false the font will only contain one single line of text (the default) - * @default - */ + * @property {boolean} multiLine - If set to true all carriage-returns in text will form new lines (see align). If false the font will only contain one single line of text (the default) + * @default + */ this.multiLine = false; /** - * @property {boolean} autoUpperCase - Automatically convert any text to upper case. Lots of old bitmap fonts only contain upper-case characters, so the default is true. - * @default - */ + * @property {boolean} autoUpperCase - Automatically convert any text to upper case. Lots of old bitmap fonts only contain upper-case characters, so the default is true. + * @default + */ this.autoUpperCase = true; /** - * @property {number} customSpacingX - Adds horizontal spacing between each character of the font, in pixels. - * @default - */ + * @property {number} customSpacingX - Adds horizontal spacing between each character of the font, in pixels. + * @default + */ this.customSpacingX = 0; /** - * @property {number} customSpacingY - Adds vertical spacing between each line of multi-line text, set in pixels. - * @default - */ + * @property {number} customSpacingY - Adds vertical spacing between each line of multi-line text, set in pixels. + * @default + */ this.customSpacingY = 0; /** - * If you need this RetroFont image to have a fixed width you can set the width in this value. - * If text is wider than the width specified it will be cropped off. - * @property {number} fixedWidth - */ + * If you need this RetroFont image to have a fixed width you can set the width in this value. + * If text is wider than the width specified it will be cropped off. + * @property {number} fixedWidth + */ this.fixedWidth = 0; /** - * @property {Image} fontSet - A reference to the image stored in the Game.Cache that contains the font. - */ + * @property {Image} fontSet - A reference to the image stored in the Game.Cache that contains the font. + */ this.fontSet = game.cache.getImage(key); /** - * @property {string} _text - The text of the font image. - * @private - */ + * @property {string} _text - The text of the font image. + * @private + */ this._text = ''; /** - * @property {array} grabData - An array of rects for faster character pasting. - * @private - */ + * @property {array} grabData - An array of rects for faster character pasting. + * @private + */ this.grabData = []; /** - * @property {Phaser.FrameData} frameData - The FrameData representing this Retro Font. - */ + * @property {Phaser.FrameData} frameData - The FrameData representing this Retro Font. + */ this.frameData = new Phaser.FrameData(); // Now generate our rects for faster copying later on @@ -158,155 +157,151 @@ Phaser.RetroFont = function (game, key, characterWidth, characterHeight, chars, game.cache.updateFrameData(key, this.frameData); /** - * @property {Phaser.Image} stamp - The image that is stamped to the RenderTexture for each character in the font. - * @readonly - */ + * @property {Phaser.Image} stamp - The image that is stamped to the RenderTexture for each character in the font. + * @readonly + */ this.stamp = new Phaser.Image(game, 0, 0, key, 0); Phaser.RenderTexture.call(this, game, 100, 100, '', Phaser.scaleModes.NEAREST); /** - * @property {number} type - Base Phaser object type. - */ + * @property {number} type - Base Phaser object type. + */ this.type = Phaser.RETROFONT; - }; Phaser.RetroFont.prototype = Object.create(Phaser.RenderTexture.prototype); Phaser.RetroFont.prototype.constructor = Phaser.RetroFont; /** -* Align each line of multi-line text to the left. -* @constant -* @type {string} -*/ + * Align each line of multi-line text to the left. + * @constant + * @type {string} + */ Phaser.RetroFont.ALIGN_LEFT = 'left'; /** -* Align each line of multi-line text to the right. -* @constant -* @type {string} -*/ + * Align each line of multi-line text to the right. + * @constant + * @type {string} + */ Phaser.RetroFont.ALIGN_RIGHT = 'right'; /** -* Align each line of multi-line text in the center. -* @constant -* @type {string} -*/ + * Align each line of multi-line text in the center. + * @constant + * @type {string} + */ Phaser.RetroFont.ALIGN_CENTER = 'center'; /** -* Text Set 1 = !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~ -* @constant -* @type {string} -*/ + * Text Set 1 = !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~ + * @constant + * @type {string} + */ Phaser.RetroFont.TEXT_SET1 = ' !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~'; /** -* Text Set 2 = !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ -* @constant -* @type {string} -*/ + * Text Set 2 = !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ + * @constant + * @type {string} + */ Phaser.RetroFont.TEXT_SET2 = ' !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ'; /** -* Text Set 3 = ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 -* @constant -* @type {string} -*/ + * Text Set 3 = ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 + * @constant + * @type {string} + */ Phaser.RetroFont.TEXT_SET3 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 '; /** -* Text Set 4 = ABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789 -* @constant -* @type {string} -*/ + * Text Set 4 = ABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789 + * @constant + * @type {string} + */ Phaser.RetroFont.TEXT_SET4 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789'; /** -* Text Set 5 = ABCDEFGHIJKLMNOPQRSTUVWXYZ.,/() '!?-*:0123456789 -* @constant -* @type {string} -*/ + * Text Set 5 = ABCDEFGHIJKLMNOPQRSTUVWXYZ.,/() '!?-*:0123456789 + * @constant + * @type {string} + */ Phaser.RetroFont.TEXT_SET5 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ.,/() \'!?-*:0123456789'; /** -* Text Set 6 = ABCDEFGHIJKLMNOPQRSTUVWXYZ!?:;0123456789"(),-.' -* @constant -* @type {string} -*/ + * Text Set 6 = ABCDEFGHIJKLMNOPQRSTUVWXYZ!?:;0123456789"(),-.' + * @constant + * @type {string} + */ Phaser.RetroFont.TEXT_SET6 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ!?:;0123456789"(),-.\' '; /** -* Text Set 7 = AGMSY+:4BHNTZ!;5CIOU.?06DJPV,(17EKQW")28FLRX-'39 -* @constant -* @type {string} -*/ + * Text Set 7 = AGMSY+:4BHNTZ!;5CIOU.?06DJPV,(17EKQW")28FLRX-'39 + * @constant + * @type {string} + */ Phaser.RetroFont.TEXT_SET7 = 'AGMSY+:4BHNTZ!;5CIOU.?06DJPV,(17EKQW")28FLRX-\'39'; /** -* Text Set 8 = 0123456789 .ABCDEFGHIJKLMNOPQRSTUVWXYZ -* @constant -* @type {string} -*/ + * Text Set 8 = 0123456789 .ABCDEFGHIJKLMNOPQRSTUVWXYZ + * @constant + * @type {string} + */ Phaser.RetroFont.TEXT_SET8 = '0123456789 .ABCDEFGHIJKLMNOPQRSTUVWXYZ'; /** -* Text Set 9 = ABCDEFGHIJKLMNOPQRSTUVWXYZ()-0123456789.:,'"?! -* @constant -* @type {string} -*/ + * Text Set 9 = ABCDEFGHIJKLMNOPQRSTUVWXYZ()-0123456789.:,'"?! + * @constant + * @type {string} + */ Phaser.RetroFont.TEXT_SET9 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ()-0123456789.:,\'"?!'; /** -* Text Set 10 = ABCDEFGHIJKLMNOPQRSTUVWXYZ -* @constant -* @type {string} -*/ + * Text Set 10 = ABCDEFGHIJKLMNOPQRSTUVWXYZ + * @constant + * @type {string} + */ Phaser.RetroFont.TEXT_SET10 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; /** -* Text Set 11 = ABCDEFGHIJKLMNOPQRSTUVWXYZ.,"-+!?()':;0123456789 -* @constant -* @type {string} -*/ + * Text Set 11 = ABCDEFGHIJKLMNOPQRSTUVWXYZ.,"-+!?()':;0123456789 + * @constant + * @type {string} + */ Phaser.RetroFont.TEXT_SET11 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ.,"-+!?()\':;0123456789'; /** -* If you need this RetroFont to have a fixed width and custom alignment you can set the width here. -* If text is wider than the width specified it will be cropped off. -* -* @method Phaser.RetroFont#setFixedWidth -* @memberof Phaser.RetroFont -* @param {number} width - Width in pixels of this RetroFont. Set to zero to disable and re-enable automatic resizing. -* @param {string} [lineAlignment='left'] - Align the text within this width. Set to RetroFont.ALIGN_LEFT (default), RetroFont.ALIGN_RIGHT or RetroFont.ALIGN_CENTER. -*/ + * If you need this RetroFont to have a fixed width and custom alignment you can set the width here. + * If text is wider than the width specified it will be cropped off. + * + * @method Phaser.RetroFont#setFixedWidth + * @memberof Phaser.RetroFont + * @param {number} width - Width in pixels of this RetroFont. Set to zero to disable and re-enable automatic resizing. + * @param {string} [lineAlignment='left'] - Align the text within this width. Set to RetroFont.ALIGN_LEFT (default), RetroFont.ALIGN_RIGHT or RetroFont.ALIGN_CENTER. + */ Phaser.RetroFont.prototype.setFixedWidth = function (width, lineAlignment) { - if (lineAlignment === undefined) { lineAlignment = 'left'; } this.fixedWidth = width; this.align = lineAlignment; - }; /** -* A helper function that quickly sets lots of variables at once, and then updates the text. -* -* @method Phaser.RetroFont#setText -* @memberof Phaser.RetroFont -* @param {string} content - The text of this sprite. -* @param {boolean} [multiLine=false] - Set to true if you want to support carriage-returns in the text and create a multi-line sprite instead of a single line. -* @param {number} [characterSpacing=0] - To add horizontal spacing between each character specify the amount in pixels. -* @param {number} [lineSpacing=0] - To add vertical spacing between each line of text, set the amount in pixels. -* @param {string} [lineAlignment='left'] - Align each line of multi-line text. Set to RetroFont.ALIGN_LEFT, RetroFont.ALIGN_RIGHT or RetroFont.ALIGN_CENTER. -* @param {boolean} [allowLowerCase=false] - Lots of bitmap font sets only include upper-case characters, if yours needs to support lower case then set this to true. -*/ + * A helper function that quickly sets lots of variables at once, and then updates the text. + * + * @method Phaser.RetroFont#setText + * @memberof Phaser.RetroFont + * @param {string} content - The text of this sprite. + * @param {boolean} [multiLine=false] - Set to true if you want to support carriage-returns in the text and create a multi-line sprite instead of a single line. + * @param {number} [characterSpacing=0] - To add horizontal spacing between each character specify the amount in pixels. + * @param {number} [lineSpacing=0] - To add vertical spacing between each line of text, set the amount in pixels. + * @param {string} [lineAlignment='left'] - Align each line of multi-line text. Set to RetroFont.ALIGN_LEFT, RetroFont.ALIGN_RIGHT or RetroFont.ALIGN_CENTER. + * @param {boolean} [allowLowerCase=false] - Lots of bitmap font sets only include upper-case characters, if yours needs to support lower case then set this to true. + */ Phaser.RetroFont.prototype.setText = function (content, multiLine, characterSpacing, lineSpacing, lineAlignment, allowLowerCase) { - this.multiLine = multiLine || false; this.customSpacingX = characterSpacing || 0; this.customSpacingY = lineSpacing || 0; @@ -325,18 +320,16 @@ Phaser.RetroFont.prototype.setText = function (content, multiLine, characterSpac { this.text = content; } - }; /** -* Updates the texture with the new text. -* -* @method Phaser.RetroFont#buildRetroFontText -* @memberof Phaser.RetroFont -*/ + * Updates the texture with the new text. + * + * @method Phaser.RetroFont#buildRetroFontText + * @memberof Phaser.RetroFont + */ Phaser.RetroFont.prototype.buildRetroFontText = function () { - var cx = 0; var cy = 0; @@ -418,23 +411,21 @@ Phaser.RetroFont.prototype.buildRetroFontText = function () } this.requiresReTint = true; - }; /** -* Internal function that takes a single line of text (2nd parameter) and pastes it into the BitmapData at the given coordinates. -* Used by getLine and getMultiLine -* -* @method Phaser.RetroFont#pasteLine -* @memberof Phaser.RetroFont -* @param {string} line - The single line of text to paste. -* @param {number} x - The x coordinate. -* @param {number} y - The y coordinate. -* @param {number} customSpacingX - Custom X spacing. -*/ + * Internal function that takes a single line of text (2nd parameter) and pastes it into the BitmapData at the given coordinates. + * Used by getLine and getMultiLine + * + * @method Phaser.RetroFont#pasteLine + * @memberof Phaser.RetroFont + * @param {string} line - The single line of text to paste. + * @param {number} x - The x coordinate. + * @param {number} y - The y coordinate. + * @param {number} customSpacingX - Custom X spacing. + */ Phaser.RetroFont.prototype.pasteLine = function (line, x, y, customSpacingX) { - for (var c = 0; c < line.length; c++) { // If it's a space then there is no point copying, so leave a blank space @@ -462,15 +453,14 @@ Phaser.RetroFont.prototype.pasteLine = function (line, x, y, customSpacingX) }; /** -* Works out the longest line of text in _text and returns its length -* -* @method Phaser.RetroFont#getLongestLine -* @memberof Phaser.RetroFont -* @return {number} The length of the longest line of text. -*/ + * Works out the longest line of text in _text and returns its length + * + * @method Phaser.RetroFont#getLongestLine + * @memberof Phaser.RetroFont + * @return {number} The length of the longest line of text. + */ Phaser.RetroFont.prototype.getLongestLine = function () { - var longestLine = 0; if (this._text.length > 0) @@ -490,17 +480,16 @@ Phaser.RetroFont.prototype.getLongestLine = function () }; /** -* Internal helper function that removes all unsupported characters from the _text String, leaving only characters contained in the font set. -* -* @method Phaser.RetroFont#removeUnsupportedCharacters -* @memberof Phaser.RetroFont -* @protected -* @param {boolean} [stripCR=true] - Should it strip carriage returns as well? -* @return {string} A clean version of the string. -*/ + * Internal helper function that removes all unsupported characters from the _text String, leaving only characters contained in the font set. + * + * @method Phaser.RetroFont#removeUnsupportedCharacters + * @memberof Phaser.RetroFont + * @protected + * @param {boolean} [stripCR=true] - Should it strip carriage returns as well? + * @return {string} A clean version of the string. + */ Phaser.RetroFont.prototype.removeUnsupportedCharacters = function (stripCR) { - var newString = ''; for (var c = 0; c < this._text.length; c++) @@ -515,22 +504,20 @@ Phaser.RetroFont.prototype.removeUnsupportedCharacters = function (stripCR) } return newString; - }; /** -* Updates the x and/or y offset that the font is rendered from. This updates all of the texture frames, so be careful how often it is called. -* Note that the values given for the x and y properties are either ADDED to or SUBTRACTED from (if negative) the existing offsetX/Y values of the characters. -* So if the current offsetY is 8 and you want it to start rendering from y16 you would call updateOffset(0, 8) to add 8 to the current y offset. -* -* @method Phaser.RetroFont#updateOffset -* @memberof Phaser.RetroFont -* @param {number} [xOffset=0] - If the font set doesn't start at the top left of the given image, specify the X coordinate offset here. -* @param {number} [yOffset=0] - If the font set doesn't start at the top left of the given image, specify the Y coordinate offset here. -*/ + * Updates the x and/or y offset that the font is rendered from. This updates all of the texture frames, so be careful how often it is called. + * Note that the values given for the x and y properties are either ADDED to or SUBTRACTED from (if negative) the existing offsetX/Y values of the characters. + * So if the current offsetY is 8 and you want it to start rendering from y16 you would call updateOffset(0, 8) to add 8 to the current y offset. + * + * @method Phaser.RetroFont#updateOffset + * @memberof Phaser.RetroFont + * @param {number} [xOffset=0] - If the font set doesn't start at the top left of the given image, specify the X coordinate offset here. + * @param {number} [yOffset=0] - If the font set doesn't start at the top left of the given image, specify the Y coordinate offset here. + */ Phaser.RetroFont.prototype.updateOffset = function (x, y) { - if (this.offsetX === x && this.offsetY === y) { return; @@ -549,25 +536,21 @@ Phaser.RetroFont.prototype.updateOffset = function (x, y) } this.buildRetroFontText(); - }; /** -* @name Phaser.RetroFont#text -* @property {string} text - Set this value to update the text in this sprite. Carriage returns are automatically stripped out if multiLine is false. Text is converted to upper case if autoUpperCase is true. -*/ + * @name Phaser.RetroFont#text + * @property {string} text - Set this value to update the text in this sprite. Carriage returns are automatically stripped out if multiLine is false. Text is converted to upper case if autoUpperCase is true. + */ Object.defineProperty(Phaser.RetroFont.prototype, 'text', { get: function () { - return this._text; - }, set: function (value) { - var newText; if (this.autoUpperCase) @@ -587,30 +570,25 @@ Object.defineProperty(Phaser.RetroFont.prototype, 'text', { this.buildRetroFontText(); } - } }); /** -* @name Phaser.RetroFont#smoothed -* @property {boolean} smoothed - Sets if the stamp is smoothed or not. -*/ + * @name Phaser.RetroFont#smoothed + * @property {boolean} smoothed - Sets if the stamp is smoothed or not. + */ Object.defineProperty(Phaser.RetroFont.prototype, 'smoothed', { get: function () { - return this.stamp.smoothed; - }, set: function (value) { - this.stamp.smoothed = value; this.buildRetroFontText(); - } }); diff --git a/src/gameobjects/Rope.js b/src/gameobjects/Rope.js index 90cb3dbed..2482a1f97 100644 --- a/src/gameobjects/Rope.js +++ b/src/gameobjects/Rope.js @@ -1,49 +1,48 @@ /** -* @author Richard Davey -* @author Mat Groves (@Doormat23) -* @author Rovanion Luckey -* @copyright 2016 Photon Storm Ltd, Richard Davey -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @author Mat Groves (@Doormat23) + * @author Rovanion Luckey + * @copyright 2016 Photon Storm Ltd, Richard Davey + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* A Rope is a Sprite that has a repeating texture. -* -* The texture will automatically wrap on the edges as it moves. -* -* Please note that Ropes cannot have an input handler. -* -* @class Phaser.Rope -* @constructor -* @extends PIXI.DisplayObjectContainer -* @extends Phaser.Component.Core -* @extends Phaser.Component.Angle -* @extends Phaser.Component.Animation -* @extends Phaser.Component.AutoCull -* @extends Phaser.Component.Bounds -* @extends Phaser.Component.BringToTop -* @extends Phaser.Component.Crop -* @extends Phaser.Component.Delta -* @extends Phaser.Component.Destroy -* @extends Phaser.Component.FixedToCamera -* @extends Phaser.Component.InWorld -* @extends Phaser.Component.LifeSpan -* @extends Phaser.Component.LoadTexture -* @extends Phaser.Component.Overlap -* @extends Phaser.Component.PhysicsBody -* @extends Phaser.Component.Reset -* @extends Phaser.Component.ScaleMinMax -* @extends Phaser.Component.Smoothed -* @param {Phaser.Game} game - A reference to the currently running game. -* @param {number} x - The x coordinate (in world space) to position the Rope at. -* @param {number} y - The y coordinate (in world space) to position the Rope at. -* @param {string|Phaser.RenderTexture|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the Rope during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture. -* @param {string|number} frame - If this Rope is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. -* @param {Array} points - An array of {Phaser.Point}. -*/ + * A Rope is a Sprite that has a repeating texture. + * + * The texture will automatically wrap on the edges as it moves. + * + * Please note that Ropes cannot have an input handler. + * + * @class Phaser.Rope + * @constructor + * @extends PIXI.DisplayObjectContainer + * @extends Phaser.Component.Core + * @extends Phaser.Component.Angle + * @extends Phaser.Component.Animation + * @extends Phaser.Component.AutoCull + * @extends Phaser.Component.Bounds + * @extends Phaser.Component.BringToTop + * @extends Phaser.Component.Crop + * @extends Phaser.Component.Delta + * @extends Phaser.Component.Destroy + * @extends Phaser.Component.FixedToCamera + * @extends Phaser.Component.InWorld + * @extends Phaser.Component.LifeSpan + * @extends Phaser.Component.LoadTexture + * @extends Phaser.Component.Overlap + * @extends Phaser.Component.PhysicsBody + * @extends Phaser.Component.Reset + * @extends Phaser.Component.ScaleMinMax + * @extends Phaser.Component.Smoothed + * @param {Phaser.Game} game - A reference to the currently running game. + * @param {number} x - The x coordinate (in world space) to position the Rope at. + * @param {number} y - The y coordinate (in world space) to position the Rope at. + * @param {string|Phaser.RenderTexture|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the Rope during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture. + * @param {string|number} frame - If this Rope is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. + * @param {Array} points - An array of {Phaser.Point}. + */ Phaser.Rope = function (game, x, y, key, frame, points) { - this.points = points || []; this._hasUpdateAnimation = false; this._updateAnimationCallback = null; @@ -53,9 +52,9 @@ Phaser.Rope = function (game, x, y, key, frame, points) frame = frame || null; /** - * @property {number} type - The const type of this object. - * @readonly - */ + * @property {number} type - The const type of this object. + * @readonly + */ this.type = Phaser.ROPE; PIXI.DisplayObjectContainer.call(this); @@ -106,7 +105,6 @@ Phaser.Rope = function (game, x, y, key, frame, points) Phaser.Component.Core.init.call(this, game, x, y, key, frame); this.refresh(); - }; Phaser.Rope.prototype = Object.create(PIXI.DisplayObjectContainer.prototype); @@ -141,68 +139,61 @@ Phaser.Rope.TRIANGLE_STRIP = 0; Phaser.Rope.TRIANGLES = 1; /** -* Automatically called by World.preUpdate. -* -* @method Phaser.Rope#preUpdate -* @memberof Phaser.Rope -*/ + * Automatically called by World.preUpdate. + * + * @method Phaser.Rope#preUpdate + * @memberof Phaser.Rope + */ Phaser.Rope.prototype.preUpdate = function () { - if (!this.preUpdatePhysics() || !this.preUpdateLifeSpan() || !this.preUpdateInWorld()) { return false; } return this.preUpdateCore(); - }; /** -* Override and use this function in your own custom objects to handle any update requirements you may have. -* -* @method Phaser.Rope#update -* @memberof Phaser.Rope -*/ + * Override and use this function in your own custom objects to handle any update requirements you may have. + * + * @method Phaser.Rope#update + * @memberof Phaser.Rope + */ Phaser.Rope.prototype.update = function () { - if (this._hasUpdateAnimation) { this.updateAnimation.call(this); } - }; /** -* Resets the Rope. This places the Rope at the given x/y world coordinates and then -* sets alive, exists, visible and renderable all to true. Also resets the outOfBounds state. -* If the Rope has a physics body that too is reset. -* -* @method Phaser.Rope#reset -* @memberof Phaser.Rope -* @param {number} x - The x coordinate (in world space) to position the Sprite at. -* @param {number} y - The y coordinate (in world space) to position the Sprite at. -* @return {Phaser.Rope} This instance. -*/ + * Resets the Rope. This places the Rope at the given x/y world coordinates and then + * sets alive, exists, visible and renderable all to true. Also resets the outOfBounds state. + * If the Rope has a physics body that too is reset. + * + * @method Phaser.Rope#reset + * @memberof Phaser.Rope + * @param {number} x - The x coordinate (in world space) to position the Sprite at. + * @param {number} y - The y coordinate (in world space) to position the Sprite at. + * @return {Phaser.Rope} This instance. + */ Phaser.Rope.prototype.reset = function (x, y) { - Phaser.Component.Reset.prototype.reset.call(this, x, y); return this; - }; /** -* Refreshes the rope texture and UV coordinates. -* -* @method Phaser.Rope#refresh -* @memberof Phaser.Rope -*/ + * Refreshes the rope texture and UV coordinates. + * + * @method Phaser.Rope#refresh + * @memberof Phaser.Rope + */ Phaser.Rope.prototype.refresh = function () { - var points = this.points; if (points.length < 1) @@ -241,18 +232,16 @@ Phaser.Rope.prototype.refresh = function () indices[index] = index; indices[index + 1] = index + 1; } - }; /** -* Updates the Ropes transform ready for rendering. -* -* @method Phaser.Rope#updateTransform -* @memberof Phaser.Rope -*/ + * Updates the Ropes transform ready for rendering. + * + * @method Phaser.Rope#updateTransform + * @memberof Phaser.Rope + */ Phaser.Rope.prototype.updateTransform = function () { - var points = this.points; if (points.length < 1) @@ -308,33 +297,29 @@ Phaser.Rope.prototype.updateTransform = function () } PIXI.DisplayObjectContainer.prototype.updateTransform.call(this); - }; /** -* Sets the Texture this Rope uses for rendering. -* -* @method Phaser.Rope#setTexture -* @memberof Phaser.Rope -* @param {Texture} texture - The texture that will be used. -*/ + * Sets the Texture this Rope uses for rendering. + * + * @method Phaser.Rope#setTexture + * @memberof Phaser.Rope + * @param {Texture} texture - The texture that will be used. + */ Phaser.Rope.prototype.setTexture = function (texture) { - this.texture = texture; - }; /** -* Renders the Rope to WebGL. -* -* @private -* @method Phaser.Rope#_renderWebGL -* @memberof Phaser.Rope -*/ + * Renders the Rope to WebGL. + * + * @private + * @method Phaser.Rope#_renderWebGL + * @memberof Phaser.Rope + */ Phaser.Rope.prototype._renderWebGL = function (renderSession) { - if (!this.visible || this.alpha <= 0) { return; @@ -352,19 +337,17 @@ Phaser.Rope.prototype._renderWebGL = function (renderSession) this._renderStrip(renderSession); renderSession.spriteBatch.start(); - }; /** -* Builds the Strip. -* -* @private -* @method Phaser.Rope#_initWebGL -* @memberof Phaser.Rope -*/ + * Builds the Strip. + * + * @private + * @method Phaser.Rope#_initWebGL + * @memberof Phaser.Rope + */ Phaser.Rope.prototype._initWebGL = function (renderSession) { - // build the strip! var gl = renderSession.gl; @@ -384,19 +367,17 @@ Phaser.Rope.prototype._initWebGL = function (renderSession) gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._indexBuffer); gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.indices, gl.STATIC_DRAW); - }; /** -* Renders the Strip to WebGL. -* -* @private -* @method Phaser.Rope#_renderStrip -* @memberof Phaser.Rope -*/ + * Renders the Strip to WebGL. + * + * @private + * @method Phaser.Rope#_renderStrip + * @memberof Phaser.Rope + */ Phaser.Rope.prototype._renderStrip = function (renderSession) { - var gl = renderSession.gl; var projection = renderSession.projection; var offset = renderSession.offset; @@ -467,19 +448,17 @@ Phaser.Rope.prototype._renderStrip = function (renderSession) } gl.drawElements(drawMode, this.indices.length, gl.UNSIGNED_SHORT, 0); - }; /** -* Renders the Strip to Canvas. -* -* @private -* @method Phaser.Rope#_renderCanvas -* @memberof Phaser.Rope -*/ + * Renders the Strip to Canvas. + * + * @private + * @method Phaser.Rope#_renderCanvas + * @memberof Phaser.Rope + */ Phaser.Rope.prototype._renderCanvas = function (renderSession) { - var context = renderSession.context; var transform = this.worldTransform; @@ -504,19 +483,17 @@ Phaser.Rope.prototype._renderCanvas = function (renderSession) { this._renderCanvasTriangles(context); } - }; /** -* Renders a Triangle Strip to Canvas. -* -* @private -* @method Phaser.Rope#_renderCanvasTriangleStrip -* @memberof Phaser.Rope -*/ + * Renders a Triangle Strip to Canvas. + * + * @private + * @method Phaser.Rope#_renderCanvasTriangleStrip + * @memberof Phaser.Rope + */ Phaser.Rope.prototype._renderCanvasTriangleStrip = function (context) { - // draw triangles!! var vertices = this.vertices; var uvs = this.uvs; @@ -530,19 +507,17 @@ Phaser.Rope.prototype._renderCanvasTriangleStrip = function (context) var index = i * 2; this._renderCanvasDrawTriangle(context, vertices, uvs, index, (index + 2), (index + 4)); } - }; /** -* Renders a Triangle to Canvas. -* -* @private -* @method Phaser.Rope#_renderCanvasTriangles -* @memberof Phaser.Rope -*/ + * Renders a Triangle to Canvas. + * + * @private + * @method Phaser.Rope#_renderCanvasTriangles + * @memberof Phaser.Rope + */ Phaser.Rope.prototype._renderCanvasTriangles = function (context) { - var vertices = this.vertices; var uvs = this.uvs; var indices = this.indices; @@ -559,19 +534,17 @@ Phaser.Rope.prototype._renderCanvasTriangles = function (context) this._renderCanvasDrawTriangle(context, vertices, uvs, index0, index1, index2); } - }; /** -* Renders a Triangle to Canvas. -* -* @private -* @method Phaser.Rope#_renderCanvasDrawTriangle -* @memberof Phaser.Rope -*/ + * Renders a Triangle to Canvas. + * + * @private + * @method Phaser.Rope#_renderCanvasDrawTriangle + * @memberof Phaser.Rope + */ Phaser.Rope.prototype._renderCanvasDrawTriangle = function (context, vertices, uvs, index0, index1, index2) { - var textureSource = this.texture.baseTexture.source; var textureWidth = this.texture.width; var textureHeight = this.texture.height; @@ -649,18 +622,16 @@ Phaser.Rope.prototype._renderCanvasDrawTriangle = function (context, vertices, u context.drawImage(textureSource, 0, 0); context.restore(); - }; /** -* Renders a flat strip. -* -* @method Phaser.Rope#renderStripFlat -* @memberof Phaser.Rope -*/ + * Renders a flat strip. + * + * @method Phaser.Rope#renderStripFlat + * @memberof Phaser.Rope + */ Phaser.Rope.prototype.renderStripFlat = function (strip) { - var context = this.context; var vertices = strip.vertices; @@ -690,20 +661,18 @@ Phaser.Rope.prototype.renderStripFlat = function (strip) context.fillStyle = '#FF0000'; context.fill(); context.closePath(); - }; /** -* Returns the bounds of the mesh as a rectangle. The bounds calculation takes the worldTransform into account. -* -* @method Phaser.Rope#getBounds -* @memberof Phaser.Rope -* @param {Matrix} matrix - The transformation matrix of the Sprite. -* @return {Rectangle} The framing rectangle. -*/ + * Returns the bounds of the mesh as a rectangle. The bounds calculation takes the worldTransform into account. + * + * @method Phaser.Rope#getBounds + * @memberof Phaser.Rope + * @param {Matrix} matrix - The transformation matrix of the Sprite. + * @return {Rectangle} The framing rectangle. + */ Phaser.Rope.prototype.getBounds = function (matrix) { - var worldTransform = matrix || this.worldTransform; var a = worldTransform.a; @@ -752,27 +721,23 @@ Phaser.Rope.prototype.getBounds = function (matrix) this._currentBounds = bounds; return bounds; - }; /** -* A Rope will call its updateAnimation function on each update loop if it has one. -* -* @name Phaser.Rope#updateAnimation -* @property {function} updateAnimation - Set to a function if you'd like the rope to animate during the update phase. Set to false or null to remove it. -*/ + * A Rope will call its updateAnimation function on each update loop if it has one. + * + * @name Phaser.Rope#updateAnimation + * @property {function} updateAnimation - Set to a function if you'd like the rope to animate during the update phase. Set to false or null to remove it. + */ Object.defineProperty(Phaser.Rope.prototype, 'updateAnimation', { get: function () { - return this._updateAnimation; - }, set: function (value) { - if (value && typeof value === 'function') { this._hasUpdateAnimation = true; @@ -783,22 +748,20 @@ Object.defineProperty(Phaser.Rope.prototype, 'updateAnimation', { this._hasUpdateAnimation = false; this._updateAnimation = null; } - } }); /** -* The segments that make up the rope body as an array of Phaser.Rectangles -* -* @name Phaser.Rope#segments -* @property {Phaser.Rectangles[]} updateAnimation - Returns an array of Phaser.Rectangles that represent the segments of the given rope -*/ + * The segments that make up the rope body as an array of Phaser.Rectangles + * + * @name Phaser.Rope#segments + * @property {Phaser.Rectangles[]} updateAnimation - Returns an array of Phaser.Rectangles that represent the segments of the given rope + */ Object.defineProperty(Phaser.Rope.prototype, 'segments', { get: function () { - var segments = []; var index, x1, y1, x2, y2, width, height, rect; diff --git a/src/gameobjects/Sprite.js b/src/gameobjects/Sprite.js index f3e47daac..9d42ace14 100644 --- a/src/gameobjects/Sprite.js +++ b/src/gameobjects/Sprite.js @@ -1,70 +1,68 @@ /** -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* Sprites are the lifeblood of your game, used for nearly everything visual. -* -* At its most basic a Sprite consists of a set of coordinates and a texture that is rendered to the canvas. -* They also contain additional properties allowing for physics motion (via Sprite.body), input handling (via Sprite.input), -* events (via Sprite.events), animation (via Sprite.animations), camera culling and more. Please see the Examples for use cases. -* -* @class Phaser.Sprite -* @constructor -* @extends PIXI.Sprite -* @extends Phaser.Component.Core -* @extends Phaser.Component.Angle -* @extends Phaser.Component.Animation -* @extends Phaser.Component.AutoCull -* @extends Phaser.Component.Bounds -* @extends Phaser.Component.BringToTop -* @extends Phaser.Component.Crop -* @extends Phaser.Component.Delta -* @extends Phaser.Component.Destroy -* @extends Phaser.Component.FixedToCamera -* @extends Phaser.Component.Health -* @extends Phaser.Component.InCamera -* @extends Phaser.Component.InputEnabled -* @extends Phaser.Component.InWorld -* @extends Phaser.Component.LifeSpan -* @extends Phaser.Component.LoadTexture -* @extends Phaser.Component.Overlap -* @extends Phaser.Component.PhysicsBody -* @extends Phaser.Component.Reset -* @extends Phaser.Component.ScaleMinMax -* @extends Phaser.Component.Smoothed -* @param {Phaser.Game} game - A reference to the currently running game. -* @param {number} x - The x coordinate (in world space) to position the Sprite at. -* @param {number} y - The y coordinate (in world space) to position the Sprite at. -* @param {string|Phaser.RenderTexture|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture. If this argument is omitted, the sprite will receive {@link Phaser.Cache.DEFAULT the default texture} (as if you had passed '__default'), but its `key` will remain empty. -* @param {string|number} frame - If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. -*/ + * Sprites are the lifeblood of your game, used for nearly everything visual. + * + * At its most basic a Sprite consists of a set of coordinates and a texture that is rendered to the canvas. + * They also contain additional properties allowing for physics motion (via Sprite.body), input handling (via Sprite.input), + * events (via Sprite.events), animation (via Sprite.animations), camera culling and more. Please see the Examples for use cases. + * + * @class Phaser.Sprite + * @constructor + * @extends PIXI.Sprite + * @extends Phaser.Component.Core + * @extends Phaser.Component.Angle + * @extends Phaser.Component.Animation + * @extends Phaser.Component.AutoCull + * @extends Phaser.Component.Bounds + * @extends Phaser.Component.BringToTop + * @extends Phaser.Component.Crop + * @extends Phaser.Component.Delta + * @extends Phaser.Component.Destroy + * @extends Phaser.Component.FixedToCamera + * @extends Phaser.Component.Health + * @extends Phaser.Component.InCamera + * @extends Phaser.Component.InputEnabled + * @extends Phaser.Component.InWorld + * @extends Phaser.Component.LifeSpan + * @extends Phaser.Component.LoadTexture + * @extends Phaser.Component.Overlap + * @extends Phaser.Component.PhysicsBody + * @extends Phaser.Component.Reset + * @extends Phaser.Component.ScaleMinMax + * @extends Phaser.Component.Smoothed + * @param {Phaser.Game} game - A reference to the currently running game. + * @param {number} x - The x coordinate (in world space) to position the Sprite at. + * @param {number} y - The y coordinate (in world space) to position the Sprite at. + * @param {string|Phaser.RenderTexture|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture. If this argument is omitted, the sprite will receive {@link Phaser.Cache.DEFAULT the default texture} (as if you had passed '__default'), but its `key` will remain empty. + * @param {string|number} frame - If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. + */ Phaser.Sprite = function (game, x, y, key, frame) { - x = x || 0; y = y || 0; key = key || null; frame = frame || null; /** - * @property {number} type - The const type of this object. - * @readonly - */ + * @property {number} type - The const type of this object. + * @readonly + */ this.type = Phaser.SPRITE; /** - * @property {number} physicsType - The const physics body type of this object. - * @readonly - */ + * @property {number} physicsType - The const physics body type of this object. + * @readonly + */ this.physicsType = Phaser.SPRITE; PIXI.Sprite.call(this, Phaser.Cache.DEFAULT); Phaser.Component.Core.init.call(this, game, x, y, key, frame); - }; Phaser.Sprite.prototype = Object.create(PIXI.Sprite.prototype); @@ -99,20 +97,18 @@ Phaser.Sprite.prototype.preUpdateInWorld = Phaser.Component.InWorld.preUpdate; Phaser.Sprite.prototype.preUpdateCore = Phaser.Component.Core.preUpdate; /** -* Automatically called by World.preUpdate. -* -* @method -* @memberof Phaser.Sprite -* @return {boolean} True if the Sprite was rendered, otherwise false. -*/ + * Automatically called by World.preUpdate. + * + * @method + * @memberof Phaser.Sprite + * @return {boolean} True if the Sprite was rendered, otherwise false. + */ Phaser.Sprite.prototype.preUpdate = function () { - if (!this.preUpdatePhysics() || !this.preUpdateLifeSpan() || !this.preUpdateInWorld()) { return false; } return this.preUpdateCore(); - }; diff --git a/src/gameobjects/SpriteBatch.js b/src/gameobjects/SpriteBatch.js index 2854a8ced..67bf22ee0 100644 --- a/src/gameobjects/SpriteBatch.js +++ b/src/gameobjects/SpriteBatch.js @@ -1,50 +1,48 @@ /** -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* The SpriteBatch class is a really fast version of the DisplayObjectContainer built purely for speed, so use when you need a lot of sprites or particles. -* It's worth mentioning that by default sprite batches are used through-out the renderer, so you only really need to use a SpriteBatch if you have over -* 1000 sprites that all share the same texture (or texture atlas). It's also useful if running in Canvas mode and you have a lot of un-rotated or un-scaled -* Sprites as it skips all of the Canvas setTransform calls, which helps performance, especially on mobile devices. -* -* Please note that any Sprite that is part of a SpriteBatch will not have its bounds updated, so will fail checks such as outOfBounds. -* -* @class Phaser.SpriteBatch -* @extends Phaser.Group -* @constructor -* @param {Phaser.Game} game - A reference to the currently running game. -* @param {Phaser.Group|Phaser.Sprite|null} parent - The parent Group, DisplayObject or DisplayObjectContainer that this Group will be added to. If `undefined` or `null` it will use game.world. -* @param {string} [name=group] - A name for this Group. Not used internally but useful for debugging. -* @param {boolean} [addToStage=false] - If set to true this Group will be added directly to the Game.Stage instead of Game.World. -*/ + * The SpriteBatch class is a really fast version of the DisplayObjectContainer built purely for speed, so use when you need a lot of sprites or particles. + * It's worth mentioning that by default sprite batches are used through-out the renderer, so you only really need to use a SpriteBatch if you have over + * 1000 sprites that all share the same texture (or texture atlas). It's also useful if running in Canvas mode and you have a lot of un-rotated or un-scaled + * Sprites as it skips all of the Canvas setTransform calls, which helps performance, especially on mobile devices. + * + * Please note that any Sprite that is part of a SpriteBatch will not have its bounds updated, so will fail checks such as outOfBounds. + * + * @class Phaser.SpriteBatch + * @extends Phaser.Group + * @constructor + * @param {Phaser.Game} game - A reference to the currently running game. + * @param {Phaser.Group|Phaser.Sprite|null} parent - The parent Group, DisplayObject or DisplayObjectContainer that this Group will be added to. If `undefined` or `null` it will use game.world. + * @param {string} [name=group] - A name for this Group. Not used internally but useful for debugging. + * @param {boolean} [addToStage=false] - If set to true this Group will be added directly to the Game.Stage instead of Game.World. + */ Phaser.SpriteBatch = function (game, parent, name, addToStage) { - if (parent === undefined || parent === null) { parent = game.world; } Phaser.Group.call(this, game, parent, name, addToStage); /** - * @property {number} type - Internal Phaser Type value. - * @protected - */ + * @property {number} type - Internal Phaser Type value. + * @protected + */ this.type = Phaser.SPRITEBATCH; /** - * @property {Object} fastSpriteBatch - WebGL Batch Shader. - * @private - */ + * @property {Object} fastSpriteBatch - WebGL Batch Shader. + * @private + */ this.fastSpriteBatch = null; /** - * @property {boolean} ready - Internal flag. - * @private - */ + * @property {boolean} ready - Internal flag. + * @private + */ this.ready = false; - }; Phaser.SpriteBatch.prototype = Object.create(Phaser.Group.prototype); @@ -52,16 +50,15 @@ Phaser.SpriteBatch.prototype = Object.create(Phaser.Group.prototype); Phaser.SpriteBatch.prototype.constructor = Phaser.SpriteBatch; /** -* Renders the Sprite Batch using the WebGL renderer. -* -* @private -* @method -* @memberof Phaser.SpriteBatch -* @param {RenderSession} renderSession -*/ + * Renders the Sprite Batch using the WebGL renderer. + * + * @private + * @method + * @memberof Phaser.SpriteBatch + * @param {RenderSession} renderSession + */ Phaser.SpriteBatch.prototype._renderWebGL = function (renderSession) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { return; @@ -87,20 +84,18 @@ Phaser.SpriteBatch.prototype._renderWebGL = function (renderSession) this.fastSpriteBatch.render(this); renderSession.spriteBatch.start(); - }; /** -* Renders the Sprite Batch using the Canvas renderer. -* -* @private -* @method -* @memberof Phaser.SpriteBatch -* @param {RenderSession} renderSession -*/ + * Renders the Sprite Batch using the Canvas renderer. + * + * @private + * @method + * @memberof Phaser.SpriteBatch + * @param {RenderSession} renderSession + */ Phaser.SpriteBatch.prototype._renderCanvas = function (renderSession) { - if (!this.visible || this.alpha <= 0 || !this.children.length) { return; @@ -187,5 +182,4 @@ Phaser.SpriteBatch.prototype._renderCanvas = function (renderSession) frame.height); } } - }; diff --git a/src/gameobjects/Text.js b/src/gameobjects/Text.js index b94f45aae..ef75f26f0 100644 --- a/src/gameobjects/Text.js +++ b/src/gameobjects/Text.js @@ -1,45 +1,44 @@ /** -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* Create a new game object for displaying Text. -* -* This uses a local hidden Canvas object and renders the type into it. It then makes a texture from this for rendering to the view. -* Because of this you can only display fonts that are currently loaded and available to the browser: fonts must be pre-loaded. -* -* See {@link http://www.jordanm.co.uk/tinytype this compatibility table} for the available default fonts across mobile browsers. -* -* @class Phaser.Text -* @extends Phaser.Sprite -* @constructor -* @param {Phaser.Game} game - Current game instance. -* @param {number} x - X position of the new text object. -* @param {number} y - Y position of the new text object. -* @param {string} text - The actual text that will be written. -* @param {object} [style] - The style properties to be set on the Text. -* @param {string} [style.font='bold 20pt Arial'] - The style and size of the font. -* @param {string} [style.fontStyle=(from font)] - The style of the font (eg. 'italic'): overrides the value in `style.font`. -* @param {string} [style.fontVariant=(from font)] - The variant of the font (eg. 'small-caps'): overrides the value in `style.font`. -* @param {string} [style.fontWeight=(from font)] - The weight of the font (eg. 'bold'): overrides the value in `style.font`. -* @param {string|number} [style.fontSize=(from font)] - The size of the font (eg. 32 or '32px'): overrides the value in `style.font`. -* @param {string} [style.backgroundColor=null] - A canvas fillstyle that will be used as the background for the whole Text object. Set to `null` to disable. -* @param {string} [style.fill='black'] - A canvas fillstyle that will be used on the text eg 'red', '#00FF00'. -* @param {string} [style.align='left'] - Horizontal alignment of each line in multiline text. Can be: 'left', 'center' or 'right'. Does not affect single lines of text (see `textBounds` and `boundsAlignH` for that). -* @param {string} [style.boundsAlignH='left'] - Horizontal alignment of the text within the `textBounds`. Can be: 'left', 'center' or 'right'. -* @param {string} [style.boundsAlignV='top'] - Vertical alignment of the text within the `textBounds`. Can be: 'top', 'middle' or 'bottom'. -* @param {string} [style.stroke='black'] - A canvas stroke style that will be used on the text stroke eg 'blue', '#FCFF00'. -* @param {number} [style.strokeThickness=0] - A number that represents the thickness of the stroke. Default is 0 (no stroke). -* @param {boolean} [style.wordWrap=false] - Indicates if word wrap should be used. -* @param {number} [style.wordWrapWidth=100] - The width in pixels at which text will wrap. -* @param {number} [style.maxLines=0] - The maximum number of lines to be shown for wrapped text. -* @param {number} [style.tabs=0] - The size (in pixels) of the tabs, for when text includes tab characters. 0 disables. Can be an array of varying tab sizes, one per tab stop. -*/ + * Create a new game object for displaying Text. + * + * This uses a local hidden Canvas object and renders the type into it. It then makes a texture from this for rendering to the view. + * Because of this you can only display fonts that are currently loaded and available to the browser: fonts must be pre-loaded. + * + * See {@link http://www.jordanm.co.uk/tinytype this compatibility table} for the available default fonts across mobile browsers. + * + * @class Phaser.Text + * @extends Phaser.Sprite + * @constructor + * @param {Phaser.Game} game - Current game instance. + * @param {number} x - X position of the new text object. + * @param {number} y - Y position of the new text object. + * @param {string} text - The actual text that will be written. + * @param {object} [style] - The style properties to be set on the Text. + * @param {string} [style.font='bold 20pt Arial'] - The style and size of the font. + * @param {string} [style.fontStyle=(from font)] - The style of the font (eg. 'italic'): overrides the value in `style.font`. + * @param {string} [style.fontVariant=(from font)] - The variant of the font (eg. 'small-caps'): overrides the value in `style.font`. + * @param {string} [style.fontWeight=(from font)] - The weight of the font (eg. 'bold'): overrides the value in `style.font`. + * @param {string|number} [style.fontSize=(from font)] - The size of the font (eg. 32 or '32px'): overrides the value in `style.font`. + * @param {string} [style.backgroundColor=null] - A canvas fillstyle that will be used as the background for the whole Text object. Set to `null` to disable. + * @param {string} [style.fill='black'] - A canvas fillstyle that will be used on the text eg 'red', '#00FF00'. + * @param {string} [style.align='left'] - Horizontal alignment of each line in multiline text. Can be: 'left', 'center' or 'right'. Does not affect single lines of text (see `textBounds` and `boundsAlignH` for that). + * @param {string} [style.boundsAlignH='left'] - Horizontal alignment of the text within the `textBounds`. Can be: 'left', 'center' or 'right'. + * @param {string} [style.boundsAlignV='top'] - Vertical alignment of the text within the `textBounds`. Can be: 'top', 'middle' or 'bottom'. + * @param {string} [style.stroke='black'] - A canvas stroke style that will be used on the text stroke eg 'blue', '#FCFF00'. + * @param {number} [style.strokeThickness=0] - A number that represents the thickness of the stroke. Default is 0 (no stroke). + * @param {boolean} [style.wordWrap=false] - Indicates if word wrap should be used. + * @param {number} [style.wordWrapWidth=100] - The width in pixels at which text will wrap. + * @param {number} [style.maxLines=0] - The maximum number of lines to be shown for wrapped text. + * @param {number} [style.tabs=0] - The size (in pixels) of the tabs, for when text includes tab characters. 0 disables. Can be an array of varying tab sizes, one per tab stop. + */ Phaser.Text = function (game, x, y, text, style) { - x = x || 0; y = y || 0; @@ -60,30 +59,30 @@ Phaser.Text = function (game, x, y, text, style) Phaser.Sprite.call(this, game, x, y, PIXI.Texture.fromCanvas(this.canvas)); /** - * @property {number} type - The const type of this object. - * @default - */ + * @property {number} type - The const type of this object. + * @default + */ this.type = Phaser.TEXT; /** - * @property {number} physicsType - The const physics body type of this object. - * @readonly - */ + * @property {number} physicsType - The const physics body type of this object. + * @readonly + */ this.physicsType = Phaser.SPRITE; /** - * Specify a padding value which is added to the line width and height when calculating the Text size. - * Allows you to add extra spacing if Phaser is unable to accurately determine the true font dimensions. - * @property {Phaser.Point} padding - */ + * Specify a padding value which is added to the line width and height when calculating the Text size. + * Allows you to add extra spacing if Phaser is unable to accurately determine the true font dimensions. + * @property {Phaser.Point} padding + */ this.padding = new Phaser.Point(); /** - * The textBounds property allows you to specify a rectangular region upon which text alignment is based. - * See `Text.setTextBounds` for more details. - * @property {Phaser.Rectangle} textBounds - * @readOnly - */ + * The textBounds property allows you to specify a rectangular region upon which text alignment is based. + * See `Text.setTextBounds` for more details. + * @property {Phaser.Rectangle} textBounds + * @readOnly + */ this.textBounds = null; /** @@ -92,44 +91,44 @@ Phaser.Text = function (game, x, y, text, style) this.context = this.canvas.getContext('2d'); /** - * @property {array} colors - An array of the color values as specified by {@link Phaser.Text#addColor addColor}. - */ + * @property {array} colors - An array of the color values as specified by {@link Phaser.Text#addColor addColor}. + */ this.colors = []; /** - * @property {array} strokeColors - An array of the stroke color values as specified by {@link Phaser.Text#addStrokeColor addStrokeColor}. - */ + * @property {array} strokeColors - An array of the stroke color values as specified by {@link Phaser.Text#addStrokeColor addStrokeColor}. + */ this.strokeColors = []; /** - * @property {array} fontStyles - An array of the font styles values as specified by {@link Phaser.Text#addFontStyle addFontStyle}. - */ + * @property {array} fontStyles - An array of the font styles values as specified by {@link Phaser.Text#addFontStyle addFontStyle}. + */ this.fontStyles = []; /** - * @property {array} fontWeights - An array of the font weights values as specified by {@link Phaser.Text#addFontWeight addFontWeight}. - */ + * @property {array} fontWeights - An array of the font weights values as specified by {@link Phaser.Text#addFontWeight addFontWeight}. + */ this.fontWeights = []; /** - * Should the linePositionX and Y values be automatically rounded before rendering the Text? - * You may wish to enable this if you want to remove the effect of sub-pixel aliasing from text. - * @property {boolean} autoRound - * @default - */ + * Should the linePositionX and Y values be automatically rounded before rendering the Text? + * You may wish to enable this if you want to remove the effect of sub-pixel aliasing from text. + * @property {boolean} autoRound + * @default + */ this.autoRound = false; /** - * Will this Text object use Basic or Advanced Word Wrapping? - * - * Advanced wrapping breaks long words if they are the first of a line, and repeats the process as necessary. - * White space is condensed (e.g., consecutive spaces are replaced with one). - * Lines are trimmed of white space before processing. - * - * It throws an error if wordWrapWidth is less than a single character. - * @property {boolean} useAdvancedWrap - * @default - */ + * Will this Text object use Basic or Advanced Word Wrapping? + * + * Advanced wrapping breaks long words if they are the first of a line, and repeats the process as necessary. + * White space is condensed (e.g., consecutive spaces are replaced with one). + * Lines are trimmed of white space before processing. + * + * It throws an error if wordWrapWidth is less than a single character. + * @property {boolean} useAdvancedWrap + * @default + */ this.useAdvancedWrap = false; /** @@ -141,21 +140,24 @@ Phaser.Text = function (game, x, y, text, style) this.splitRegExp = /(?:\r\n|\r|\n)/; - /** The maximum number of characters that can be set. - * @property {number} characterLimitSize - */ + /** + * The maximum number of characters that can be set. + * @property {number} characterLimitSize + */ this.characterLimitSize = -1; - /** The suffix that is applied to truncated text that is longer than the - * characterLimitSize. - * @property {string} characterLimitSuffix - */ + /** + * The suffix that is applied to truncated text that is longer than the + * characterLimitSize. + * @property {string} characterLimitSuffix + */ this.characterLimitSuffix = ''; - /** The text to use to measure the font width and height. - * @property {string} _testString - * @private - */ + /** + * The text to use to measure the font width and height. + * @property {string} _testString + * @private + */ this._testString = '|MÉq'; /** @@ -165,44 +167,44 @@ Phaser.Text = function (game, x, y, text, style) this._res = game.renderer.resolution; /** - * @property {string} _text - Internal cache var. - * @private - */ + * @property {string} _text - Internal cache var. + * @private + */ this._text = text; /** - * @property {object} _fontComponents - The font, broken down into components, set in `setStyle`. - * @private - */ + * @property {object} _fontComponents - The font, broken down into components, set in `setStyle`. + * @private + */ this._fontComponents = null; /** - * @property {number} lineSpacing - Additional spacing (in pixels) between each line of text if multi-line. - * @private - */ + * @property {number} lineSpacing - Additional spacing (in pixels) between each line of text if multi-line. + * @private + */ this._lineSpacing = 0; /** - * @property {number} _charCount - Internal character counter used by the text coloring. - * @private - */ + * @property {number} _charCount - Internal character counter used by the text coloring. + * @private + */ this._charCount = 0; /** - * @property {number} _width - Internal width var. - * @private - */ + * @property {number} _width - Internal width var. + * @private + */ this._width = 0; /** - * @property {number} _height - Internal height var. - * @private - */ + * @property {number} _height - Internal height var. + * @private + */ this._height = 0; /** - * @property {object} style - * @private + * @property {object} style + * @private */ this.style = {}; @@ -212,74 +214,68 @@ Phaser.Text = function (game, x, y, text, style) { this.updateText(); } - }; Phaser.Text.prototype = Object.create(Phaser.Sprite.prototype); Phaser.Text.prototype.constructor = Phaser.Text; /** -* Automatically called by World.preUpdate. -* -* @method Phaser.Text#preUpdate -* @protected -*/ + * Automatically called by World.preUpdate. + * + * @method Phaser.Text#preUpdate + * @protected + */ Phaser.Text.prototype.preUpdate = function () { - if (!this.preUpdatePhysics() || !this.preUpdateLifeSpan() || !this.preUpdateInWorld()) { return false; } return this.preUpdateCore(); - }; /** -* Override this function to handle any special update requirements. -* -* @method Phaser.Text#update -* @protected -*/ + * Override this function to handle any special update requirements. + * + * @method Phaser.Text#update + * @protected + */ Phaser.Text.prototype.update = function () { }; /** -* Destroy this Text object, removing it from the group it belongs to. -* -* @method Phaser.Text#destroy -* @param {boolean} [destroyChildren=true] - Should every child of this object have its destroy method called? -*/ + * Destroy this Text object, removing it from the group it belongs to. + * + * @method Phaser.Text#destroy + * @param {boolean} [destroyChildren=true] - Should every child of this object have its destroy method called? + */ Phaser.Text.prototype.destroy = function (destroyChildren) { - this.texture.destroy(true); Phaser.Component.Destroy.prototype.destroy.call(this, destroyChildren); - }; /** -* Sets a drop shadow effect on the Text. You can specify the horizontal and vertical distance of the drop shadow with the `x` and `y` parameters. -* The color controls the shade of the shadow (default is black) and can be either an `rgba` or `hex` value. -* The blur is the strength of the shadow. A value of zero means a hard shadow, a value of 10 means a very soft shadow. -* To remove a shadow already in place you can call this method with no parameters set. -* -* @method Phaser.Text#setShadow -* @param {number} [x=0] - The shadowOffsetX value in pixels. This is how far offset horizontally the shadow effect will be. -* @param {number} [y=0] - The shadowOffsetY value in pixels. This is how far offset vertically the shadow effect will be. -* @param {string} [color='rgba(0,0,0,1)'] - The color of the shadow, as given in CSS rgba or hex format. Set the alpha component to 0 to disable the shadow. -* @param {number} [blur=0] - The shadowBlur value. Make the shadow softer by applying a Gaussian blur to it. A number from 0 (no blur) up to approx. 10 (depending on scene). -* @param {boolean} [shadowStroke=true] - Apply the drop shadow to the Text stroke (if set). -* @param {boolean} [shadowFill=true] - Apply the drop shadow to the Text fill (if set). -* @return {Phaser.Text} This Text instance. -*/ + * Sets a drop shadow effect on the Text. You can specify the horizontal and vertical distance of the drop shadow with the `x` and `y` parameters. + * The color controls the shade of the shadow (default is black) and can be either an `rgba` or `hex` value. + * The blur is the strength of the shadow. A value of zero means a hard shadow, a value of 10 means a very soft shadow. + * To remove a shadow already in place you can call this method with no parameters set. + * + * @method Phaser.Text#setShadow + * @param {number} [x=0] - The shadowOffsetX value in pixels. This is how far offset horizontally the shadow effect will be. + * @param {number} [y=0] - The shadowOffsetY value in pixels. This is how far offset vertically the shadow effect will be. + * @param {string} [color='rgba(0,0,0,1)'] - The color of the shadow, as given in CSS rgba or hex format. Set the alpha component to 0 to disable the shadow. + * @param {number} [blur=0] - The shadowBlur value. Make the shadow softer by applying a Gaussian blur to it. A number from 0 (no blur) up to approx. 10 (depending on scene). + * @param {boolean} [shadowStroke=true] - Apply the drop shadow to the Text stroke (if set). + * @param {boolean} [shadowFill=true] - Apply the drop shadow to the Text fill (if set). + * @return {Phaser.Text} This Text instance. + */ Phaser.Text.prototype.setShadow = function (x, y, color, blur, shadowStroke, shadowFill) { - if (x === undefined) { x = 0; } if (y === undefined) { y = 0; } if (color === undefined) { color = 'rgba(0, 0, 0, 1)'; } @@ -296,36 +292,34 @@ Phaser.Text.prototype.setShadow = function (x, y, color, blur, shadowStroke, sha this.dirty = true; return this; - }; /** -* Set the style of the text by passing a single style object to it. -* -* @method Phaser.Text#setStyle -* @param {object} [style] - The style properties to be set on the Text. -* @param {string} [style.font='bold 20pt Arial'] - The style and size of the font. -* @param {string} [style.fontStyle=(from font)] - The style of the font (eg. 'italic'): overrides the value in `style.font`. -* @param {string} [style.fontVariant=(from font)] - The variant of the font (eg. 'small-caps'): overrides the value in `style.font`. -* @param {string} [style.fontWeight=(from font)] - The weight of the font (eg. 'bold'): overrides the value in `style.font`. -* @param {string|number} [style.fontSize=(from font)] - The size of the font (eg. 32 or '32px'): overrides the value in `style.font`. -* @param {string} [style.backgroundColor=null] - A canvas fillstyle that will be used as the background for the whole Text object. Set to `null` to disable. -* @param {string} [style.fill='black'] - A canvas fillstyle that will be used on the text eg 'red', '#00FF00'. -* @param {string} [style.align='left'] - Horizontal alignment of each line in multiline text. Can be: 'left', 'center' or 'right'. Does not affect single lines of text (see `textBounds` and `boundsAlignH` for that). -* @param {string} [style.boundsAlignH='left'] - Horizontal alignment of the text within the `textBounds`. Can be: 'left', 'center' or 'right'. -* @param {string} [style.boundsAlignV='top'] - Vertical alignment of the text within the `textBounds`. Can be: 'top', 'middle' or 'bottom'. -* @param {string} [style.stroke='black'] - A canvas stroke style that will be used on the text stroke eg 'blue', '#FCFF00'. -* @param {number} [style.strokeThickness=0] - A number that represents the thickness of the stroke. Default is 0 (no stroke). -* @param {boolean} [style.wordWrap=false] - Indicates if word wrap should be used. -* @param {number} [style.wordWrapWidth=100] - The width in pixels at which text will wrap. -* @param {number} [style.maxLines=0] - The maximum number of lines to be shown for wrapped text. -* @param {number|array} [style.tabs=0] - The size (in pixels) of the tabs, for when text includes tab characters. 0 disables. Can be an array of varying tab sizes, one per tab stop. -* @param {boolean} [update=false] - Immediately update the Text object after setting the new style? Or wait for the next frame. -* @return {Phaser.Text} This Text instance. -*/ + * Set the style of the text by passing a single style object to it. + * + * @method Phaser.Text#setStyle + * @param {object} [style] - The style properties to be set on the Text. + * @param {string} [style.font='bold 20pt Arial'] - The style and size of the font. + * @param {string} [style.fontStyle=(from font)] - The style of the font (eg. 'italic'): overrides the value in `style.font`. + * @param {string} [style.fontVariant=(from font)] - The variant of the font (eg. 'small-caps'): overrides the value in `style.font`. + * @param {string} [style.fontWeight=(from font)] - The weight of the font (eg. 'bold'): overrides the value in `style.font`. + * @param {string|number} [style.fontSize=(from font)] - The size of the font (eg. 32 or '32px'): overrides the value in `style.font`. + * @param {string} [style.backgroundColor=null] - A canvas fillstyle that will be used as the background for the whole Text object. Set to `null` to disable. + * @param {string} [style.fill='black'] - A canvas fillstyle that will be used on the text eg 'red', '#00FF00'. + * @param {string} [style.align='left'] - Horizontal alignment of each line in multiline text. Can be: 'left', 'center' or 'right'. Does not affect single lines of text (see `textBounds` and `boundsAlignH` for that). + * @param {string} [style.boundsAlignH='left'] - Horizontal alignment of the text within the `textBounds`. Can be: 'left', 'center' or 'right'. + * @param {string} [style.boundsAlignV='top'] - Vertical alignment of the text within the `textBounds`. Can be: 'top', 'middle' or 'bottom'. + * @param {string} [style.stroke='black'] - A canvas stroke style that will be used on the text stroke eg 'blue', '#FCFF00'. + * @param {number} [style.strokeThickness=0] - A number that represents the thickness of the stroke. Default is 0 (no stroke). + * @param {boolean} [style.wordWrap=false] - Indicates if word wrap should be used. + * @param {number} [style.wordWrapWidth=100] - The width in pixels at which text will wrap. + * @param {number} [style.maxLines=0] - The maximum number of lines to be shown for wrapped text. + * @param {number|array} [style.tabs=0] - The size (in pixels) of the tabs, for when text includes tab characters. 0 disables. Can be an array of varying tab sizes, one per tab stop. + * @param {boolean} [update=false] - Immediately update the Text object after setting the new style? Or wait for the next frame. + * @return {Phaser.Text} This Text instance. + */ Phaser.Text.prototype.setStyle = function (style, update) { - if (update === undefined) { update = false; } var newStyle = Object.assign({}, style); @@ -386,18 +380,16 @@ Phaser.Text.prototype.setStyle = function (style, update) } return this; - }; /** -* Renders text to the internal canvas. -* -* @method Phaser.Text#updateText -* @private -*/ + * Renders text to the internal canvas. + * + * @method Phaser.Text#updateText + * @private + */ Phaser.Text.prototype.updateText = function () { - this.texture.baseTexture.resolution = this._res; this.context.font = this.style.font; @@ -624,23 +616,21 @@ Phaser.Text.prototype.updateText = function () this.updateTexture(); this.dirty = false; - }; /** -* Renders a line of text that contains tab characters if Text.tab > 0. -* Called automatically by updateText. -* -* @method Phaser.Text#renderTabLine -* @private -* @param {string} line - The line of text to render. -* @param {integer} x - The x position to start rendering from. -* @param {integer} y - The y position to start rendering from. -* @param {boolean} fill - If true uses fillText, if false uses strokeText. -*/ + * Renders a line of text that contains tab characters if Text.tab > 0. + * Called automatically by updateText. + * + * @method Phaser.Text#renderTabLine + * @private + * @param {string} line - The line of text to render. + * @param {integer} x - The x position to start rendering from. + * @param {integer} y - The y position to start rendering from. + * @param {boolean} fill - If true uses fillText, if false uses strokeText. + */ Phaser.Text.prototype.renderTabLine = function (line, x, y, fill) { - var text = line.split(/(?:\t)/); var tabs = this.style.tabs; var snap = 0; @@ -689,19 +679,17 @@ Phaser.Text.prototype.renderTabLine = function (line, x, y, fill) x = snap + section; } } - }; /** -* Sets the Shadow on the Text.context based on the Style settings, or disables it if not enabled. -* This is called automatically by Text.updateText. -* -* @method Phaser.Text#updateShadow -* @param {boolean} state - If true the shadow will be set to the Style values, otherwise it will be set to zero. -*/ + * Sets the Shadow on the Text.context based on the Style settings, or disables it if not enabled. + * This is called automatically by Text.updateText. + * + * @method Phaser.Text#updateShadow + * @param {boolean} state - If true the shadow will be set to the Style values, otherwise it will be set to zero. + */ Phaser.Text.prototype.updateShadow = function (state) { - if (state) { this.context.shadowOffsetX = this.style.shadowOffsetX; @@ -716,20 +704,18 @@ Phaser.Text.prototype.updateShadow = function (state) this.context.shadowColor = 0; this.context.shadowBlur = 0; } - }; /** -* Measures a line of text character by character taking into the account the specified character styles. -* -* @method Phaser.Text#measureLine -* @private -* @param {string} line - The line of text to measure. -* @return {integer} length of the line. -*/ + * Measures a line of text character by character taking into the account the specified character styles. + * + * @method Phaser.Text#measureLine + * @private + * @param {string} line - The line of text to measure. + * @return {integer} length of the line. + */ Phaser.Text.prototype.measureLine = function (line) { - var lineLength = 0; for (var i = 0; i < line.length; i++) @@ -782,14 +768,13 @@ Phaser.Text.prototype.measureLine = function (line) }; /** -* Updates a line of text, applying fill and stroke per-character colors or style and weight per-character font if applicable. -* -* @method Phaser.Text#updateLine -* @private -*/ + * Updates a line of text, applying fill and stroke per-character colors or style and weight per-character font if applicable. + * + * @method Phaser.Text#updateLine + * @private + */ Phaser.Text.prototype.updateLine = function (line, x, y) { - for (var i = 0; i < line.length; i++) { var letter = line[i]; @@ -837,178 +822,162 @@ Phaser.Text.prototype.updateLine = function (line, x, y) this._charCount++; } - }; /** -* Clears any text fill or stroke colors that were set by `addColor` or `addStrokeColor`. -* -* @method Phaser.Text#clearColors -* @return {Phaser.Text} This Text instance. -*/ + * Clears any text fill or stroke colors that were set by `addColor` or `addStrokeColor`. + * + * @method Phaser.Text#clearColors + * @return {Phaser.Text} This Text instance. + */ Phaser.Text.prototype.clearColors = function () { - this.colors = []; this.strokeColors = []; this.dirty = true; return this; - }; /** -* Clears any text styles or weights font that were set by `addFontStyle` or `addFontWeight`. -* -* @method Phaser.Text#clearFontValues -* @return {Phaser.Text} This Text instance. -*/ + * Clears any text styles or weights font that were set by `addFontStyle` or `addFontWeight`. + * + * @method Phaser.Text#clearFontValues + * @return {Phaser.Text} This Text instance. + */ Phaser.Text.prototype.clearFontValues = function () { - this.fontStyles = []; this.fontWeights = []; this.dirty = true; return this; - }; /** -* Set specific colors for certain characters within the Text. -* -* It works by taking a color value, which is a typical HTML string such as `#ff0000` or `rgb(255,0,0)` and a position. -* The position value is the index of the character in the Text string to start applying this color to. -* Once set the color remains in use until either another color or the end of the string is encountered. -* For example if the Text was `Photon Storm` and you did `Text.addColor('#ffff00', 6)` it would color in the word `Storm` in yellow. -* -* If you wish to change the stroke color see addStrokeColor instead. -* -* @method Phaser.Text#addColor -* @param {string} color - A canvas fillstyle that will be used on the text eg `red`, `#00FF00`, `rgba()`. -* @param {number} position - The index of the character in the string to start applying this color value from. -* @return {Phaser.Text} This Text instance. -*/ + * Set specific colors for certain characters within the Text. + * + * It works by taking a color value, which is a typical HTML string such as `#ff0000` or `rgb(255,0,0)` and a position. + * The position value is the index of the character in the Text string to start applying this color to. + * Once set the color remains in use until either another color or the end of the string is encountered. + * For example if the Text was `Photon Storm` and you did `Text.addColor('#ffff00', 6)` it would color in the word `Storm` in yellow. + * + * If you wish to change the stroke color see addStrokeColor instead. + * + * @method Phaser.Text#addColor + * @param {string} color - A canvas fillstyle that will be used on the text eg `red`, `#00FF00`, `rgba()`. + * @param {number} position - The index of the character in the string to start applying this color value from. + * @return {Phaser.Text} This Text instance. + */ Phaser.Text.prototype.addColor = function (color, position) { - this.colors[position] = color; this.dirty = true; return this; - }; /** -* Set specific stroke colors for certain characters within the Text. -* -* It works by taking a color value, which is a typical HTML string such as `#ff0000` or `rgb(255,0,0)` and a position. -* The position value is the index of the character in the Text string to start applying this color to. -* Once set the color remains in use until either another color or the end of the string is encountered. -* For example if the Text was `Photon Storm` and you did `Text.addColor('#ffff00', 6)` it would color in the word `Storm` in yellow. -* -* This has no effect if stroke is disabled or has a thickness of 0. -* -* If you wish to change the text fill color see addColor instead. -* -* @method Phaser.Text#addStrokeColor -* @param {string} color - A canvas fillstyle that will be used on the text stroke eg `red`, `#00FF00`, `rgba()`. -* @param {number} position - The index of the character in the string to start applying this color value from. -* @return {Phaser.Text} This Text instance. -*/ + * Set specific stroke colors for certain characters within the Text. + * + * It works by taking a color value, which is a typical HTML string such as `#ff0000` or `rgb(255,0,0)` and a position. + * The position value is the index of the character in the Text string to start applying this color to. + * Once set the color remains in use until either another color or the end of the string is encountered. + * For example if the Text was `Photon Storm` and you did `Text.addColor('#ffff00', 6)` it would color in the word `Storm` in yellow. + * + * This has no effect if stroke is disabled or has a thickness of 0. + * + * If you wish to change the text fill color see addColor instead. + * + * @method Phaser.Text#addStrokeColor + * @param {string} color - A canvas fillstyle that will be used on the text stroke eg `red`, `#00FF00`, `rgba()`. + * @param {number} position - The index of the character in the string to start applying this color value from. + * @return {Phaser.Text} This Text instance. + */ Phaser.Text.prototype.addStrokeColor = function (color, position) { - this.strokeColors[position] = color; this.dirty = true; return this; - }; /** -* Set specific font styles for certain characters within the Text. -* -* It works by taking a font style value, which is a typical string such as `normal`, `italic` or `oblique`. -* The position value is the index of the character in the Text string to start applying this font style to. -* Once set the font style remains in use until either another font style or the end of the string is encountered. -* For example if the Text was `Photon Storm` and you did `Text.addFontStyle('italic', 6)` it would font style in the word `Storm` in italic. -* -* If you wish to change the text font weight see addFontWeight instead. -* -* @method Phaser.Text#addFontStyle -* @param {string} style - A canvas font-style that will be used on the text style eg `normal`, `italic`, `oblique`. -* @param {number} position - The index of the character in the string to start applying this font style value from. -* @return {Phaser.Text} This Text instance. -*/ + * Set specific font styles for certain characters within the Text. + * + * It works by taking a font style value, which is a typical string such as `normal`, `italic` or `oblique`. + * The position value is the index of the character in the Text string to start applying this font style to. + * Once set the font style remains in use until either another font style or the end of the string is encountered. + * For example if the Text was `Photon Storm` and you did `Text.addFontStyle('italic', 6)` it would font style in the word `Storm` in italic. + * + * If you wish to change the text font weight see addFontWeight instead. + * + * @method Phaser.Text#addFontStyle + * @param {string} style - A canvas font-style that will be used on the text style eg `normal`, `italic`, `oblique`. + * @param {number} position - The index of the character in the string to start applying this font style value from. + * @return {Phaser.Text} This Text instance. + */ Phaser.Text.prototype.addFontStyle = function (style, position) { - this.fontStyles[position] = style; this.dirty = true; return this; - }; /** -* Set specific font weights for certain characters within the Text. -* -* It works by taking a font weight value, which is a typical string such as `normal`, `bold`, `bolder`, etc. -* The position value is the index of the character in the Text string to start applying this font weight to. -* Once set the font weight remains in use until either another font weight or the end of the string is encountered. -* For example if the Text was `Photon Storm` and you did `Text.addFontWeight('bold', 6)` it would font weight in the word `Storm` in bold. -* -* If you wish to change the text font style see addFontStyle instead. -* -* @method Phaser.Text#addFontWeight -* @param {string} style - A canvas font-weight that will be used on the text weight eg `normal`, `bold`, `bolder`, `lighter`, etc. -* @param {number} position - The index of the character in the string to start applying this font weight value from. -* @return {Phaser.Text} This Text instance. -*/ + * Set specific font weights for certain characters within the Text. + * + * It works by taking a font weight value, which is a typical string such as `normal`, `bold`, `bolder`, etc. + * The position value is the index of the character in the Text string to start applying this font weight to. + * Once set the font weight remains in use until either another font weight or the end of the string is encountered. + * For example if the Text was `Photon Storm` and you did `Text.addFontWeight('bold', 6)` it would font weight in the word `Storm` in bold. + * + * If you wish to change the text font style see addFontStyle instead. + * + * @method Phaser.Text#addFontWeight + * @param {string} style - A canvas font-weight that will be used on the text weight eg `normal`, `bold`, `bolder`, `lighter`, etc. + * @param {number} position - The index of the character in the string to start applying this font weight value from. + * @return {Phaser.Text} This Text instance. + */ Phaser.Text.prototype.addFontWeight = function (weight, position) { - this.fontWeights[position] = weight; this.dirty = true; return this; - }; /** -* Runs the given text through the Text.runWordWrap function and returns -* the results as an array, where each element of the array corresponds to a wrapped -* line of text. -* -* Useful if you wish to control pagination on long pieces of content. -* -* @method Phaser.Text#precalculateWordWrap -* @param {string} text - The text for which the wrapping will be calculated. -* @return {array} An array of strings with the pieces of wrapped text. -*/ + * Runs the given text through the Text.runWordWrap function and returns + * the results as an array, where each element of the array corresponds to a wrapped + * line of text. + * + * Useful if you wish to control pagination on long pieces of content. + * + * @method Phaser.Text#precalculateWordWrap + * @param {string} text - The text for which the wrapping will be calculated. + * @return {array} An array of strings with the pieces of wrapped text. + */ Phaser.Text.prototype.precalculateWordWrap = function (text) { - this.texture.baseTexture.resolution = this._res; this.context.font = this.style.font; var wrappedLines = this.runWordWrap(text); return wrappedLines.split(/(?:\r\n|\r|\n)/); - }; /** -* Greedy wrapping algorithm that will wrap words as the line grows longer than its horizontal bounds. -* -* @method Phaser.Text#runWordWrap -* @param {string} text - The text to perform word wrap detection against. -* @private -*/ + * Greedy wrapping algorithm that will wrap words as the line grows longer than its horizontal bounds. + * + * @method Phaser.Text#runWordWrap + * @param {string} text - The text to perform word wrap detection against. + * @private + */ Phaser.Text.prototype.runWordWrap = function (text) { - if (this.useAdvancedWrap) { return this.advancedWordWrap(text); @@ -1017,29 +986,29 @@ Phaser.Text.prototype.runWordWrap = function (text) { return this.basicWordWrap(text); } - }; /** -* Advanced wrapping algorithm that will wrap words as the line grows longer than its horizontal bounds. -* White space is condensed (e.g., consecutive spaces are replaced with one). -* Lines are trimmed of white space before processing. -* Throws an error if the user was smart enough to specify a wordWrapWidth less than a single character. -* -* @method Phaser.Text#advancedWordWrap -* @param {string} text - The text to perform word wrap detection against. -* @private -*/ + * Advanced wrapping algorithm that will wrap words as the line grows longer than its horizontal bounds. + * White space is condensed (e.g., consecutive spaces are replaced with one). + * Lines are trimmed of white space before processing. + * Throws an error if the user was smart enough to specify a wordWrapWidth less than a single character. + * + * @method Phaser.Text#advancedWordWrap + * @param {string} text - The text to perform word wrap detection against. + * @private + */ Phaser.Text.prototype.advancedWordWrap = function (text) { - var context = this.context; var wordWrapWidth = this.style.wordWrapWidth; var output = ''; - // (1) condense whitespace - // (2) split into lines + /* + * (1) condense whitespace + * (2) split into lines + */ var lines = text .replace(/ +/gi, ' ') .split(/\r?\n/gi); @@ -1054,8 +1023,10 @@ Phaser.Text.prototype.advancedWordWrap = function (text) // trim whitespace line = line.replace(/^ *|\s*$/gi, ''); - // if entire line is less than wordWrapWidth - // append the entire line and exit early + /* + * if entire line is less than wordWrapWidth + * append the entire line and exit early + */ var lineWidth = context.measureText(line).width; if (lineWidth < wordWrapWidth) @@ -1095,8 +1066,10 @@ Phaser.Text.prototype.advancedWordWrap = function (text) } } - // if wordWrapWidth is too small for even a single - // letter, shame user failure with a fatal error + /* + * if wordWrapWidth is too small for even a single + * letter, shame user failure with a fatal error + */ if (!newWord.length) { throw new Error('This text\'s wordWrapWidth setting is less than a single character!'); @@ -1143,19 +1116,17 @@ Phaser.Text.prototype.advancedWordWrap = function (text) output = output.replace(/[\s|\n]*$/gi, ''); return output; - }; /** -* Greedy wrapping algorithm that will wrap words as the line grows longer than its horizontal bounds. -* -* @method Phaser.Text#basicWordWrap -* @param {string} text - The text to perform word wrap detection against. -* @private -*/ + * Greedy wrapping algorithm that will wrap words as the line grows longer than its horizontal bounds. + * + * @method Phaser.Text#basicWordWrap + * @param {string} text - The text to perform word wrap detection against. + * @private + */ Phaser.Text.prototype.basicWordWrap = function (text) { - var result = ''; var lines = text.split('\n'); @@ -1193,19 +1164,17 @@ Phaser.Text.prototype.basicWordWrap = function (text) } return result; - }; /** -* Updates the internal `style.font` if it now differs according to generation from components. -* -* @method Phaser.Text#updateFont -* @private -* @param {object} components - Font components. -*/ + * Updates the internal `style.font` if it now differs according to generation from components. + * + * @method Phaser.Text#updateFont + * @private + * @param {object} components - Font components. + */ Phaser.Text.prototype.updateFont = function (components) { - var font = this.componentsToFont(components); if (this.style.font !== font) @@ -1218,27 +1187,27 @@ Phaser.Text.prototype.updateFont = function (components) this.updateTransform(); } } - }; /** -* Converting a short CSS-font string into the relevant components. -* -* @method Phaser.Text#fontToComponents -* @private -* @param {string} font - a CSS font string -*/ + * Converting a short CSS-font string into the relevant components. + * + * @method Phaser.Text#fontToComponents + * @private + * @param {string} font - a CSS font string + */ Phaser.Text.prototype.fontToComponents = function (font) { - - // The format is specified in http://www.w3.org/TR/CSS2/fonts.html#font-shorthand: - // style - normal | italic | oblique | inherit - // variant - normal | small-caps | inherit - // weight - normal | bold | bolder | lighter | 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900 | inherit - // size - xx-small | x-small | small | medium | large | x-large | xx-large, - // larger | smaller - // {number} (em | ex | ch | rem | vh | vw | vmin | vmax | px | mm | cm | in | pt | pc | %) - // font-family - rest (but identifiers or quoted with comma separation) + /* + * The format is specified in http://www.w3.org/TR/CSS2/fonts.html#font-shorthand: + * style - normal | italic | oblique | inherit + * variant - normal | small-caps | inherit + * weight - normal | bold | bolder | lighter | 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900 | inherit + * size - xx-small | x-small | small | medium | large | x-large | xx-large, + * larger | smaller + * {number} (em | ex | ch | rem | vh | vw | vmin | vmax | px | mm | cm | in | pt | pc | %) + * font-family - rest (but identifiers or quoted with comma separation) + */ var m = font.match(/^\s*(?:\b(normal|italic|oblique|inherit)?\b)\s*(?:\b(normal|small-caps|inherit)?\b)\s*(?:\b(normal|bold|bolder|lighter|100|200|300|400|500|600|700|800|900|inherit)?\b)\s*(?:\b(xx-small|x-small|small|medium|large|x-large|xx-large|larger|smaller|0|\d*(?:[.]\d*)?(?:%|[a-z]{2,5}))?\b)\s*(.*)\s*$/); if (m) @@ -1266,19 +1235,17 @@ Phaser.Text.prototype.fontToComponents = function (font) return {font: font}; } - }; /** -* Converts individual font components (see `fontToComponents`) to a short CSS font string. -* -* @method Phaser.Text#componentsToFont -* @private -* @param {object} components - Font components. -*/ + * Converts individual font components (see `fontToComponents`) to a short CSS font string. + * + * @method Phaser.Text#componentsToFont + * @private + * @param {object} components - Font components. + */ Phaser.Text.prototype.componentsToFont = function (components) { - var parts = []; var v; @@ -1304,27 +1271,25 @@ Phaser.Text.prototype.componentsToFont = function (components) } return parts.join(' '); - }; /** -* The text to be displayed by this Text object. -* Use a \n to insert a carriage return and split the text. -* The text will be rendered with any style currently set. -* -* Use the optional `immediate` argument if you need the Text display to update immediately. -* -* If not it will re-create the texture of this Text object during the next time the render -* loop is called. -* -* @method Phaser.Text#setText -* @param {string} [text] - The text to be displayed. Set to an empty string to clear text that is already present. -* @param {boolean} [immediate=false] - Update the texture used by this Text object immediately (true) or automatically during the next render loop (false). -* @return {Phaser.Text} This Text instance. -*/ + * The text to be displayed by this Text object. + * Use a \n to insert a carriage return and split the text. + * The text will be rendered with any style currently set. + * + * Use the optional `immediate` argument if you need the Text display to update immediately. + * + * If not it will re-create the texture of this Text object during the next time the render + * loop is called. + * + * @method Phaser.Text#setText + * @param {string} [text] - The text to be displayed. Set to an empty string to clear text that is already present. + * @param {boolean} [immediate=false] - Update the texture used by this Text object immediately (true) or automatically during the next render loop (false). + * @return {Phaser.Text} This Text instance. + */ Phaser.Text.prototype.setText = function (text, immediate) { - if (immediate === undefined) { immediate = false; } text = text.toString() || ''; @@ -1346,7 +1311,6 @@ Phaser.Text.prototype.setText = function (text, immediate) } return this; - }; /** @@ -1372,7 +1336,6 @@ Phaser.Text.prototype.setText = function (text, immediate) */ Phaser.Text.prototype.parseList = function (list) { - if (!Array.isArray(list)) { return this; @@ -1408,7 +1371,6 @@ Phaser.Text.prototype.parseList = function (list) this.dirty = true; return this; - }; /** @@ -1444,7 +1406,6 @@ Phaser.Text.prototype.parseList = function (list) */ Phaser.Text.prototype.setTextBounds = function (x, y, width, height) { - if (x === undefined) { this.textBounds = null; @@ -1469,7 +1430,6 @@ Phaser.Text.prototype.setTextBounds = function (x, y, width, height) this.updateTexture(); return this; - }; /** @@ -1480,7 +1440,6 @@ Phaser.Text.prototype.setTextBounds = function (x, y, width, height) */ Phaser.Text.prototype.updateTexture = function () { - var base = this.texture.baseTexture; var crop = this.texture.crop; var frame = this.texture.frame; @@ -1537,19 +1496,17 @@ Phaser.Text.prototype.updateTexture = function () this.texture.requiresReTint = true; this.texture.baseTexture.dirty(); - }; /** -* Renders the object using the WebGL renderer -* -* @method Phaser.Text#_renderWebGL -* @private -* @param {RenderSession} renderSession - The Render Session to render the Text on. -*/ + * Renders the object using the WebGL renderer + * + * @method Phaser.Text#_renderWebGL + * @private + * @param {RenderSession} renderSession - The Render Session to render the Text on. + */ Phaser.Text.prototype._renderWebGL = function (renderSession) { - if (this.dirty) { this.updateText(); @@ -1557,19 +1514,17 @@ Phaser.Text.prototype._renderWebGL = function (renderSession) } PIXI.Sprite.prototype._renderWebGL.call(this, renderSession); - }; /** -* Renders the object using the Canvas renderer. -* -* @method Phaser.Text#_renderCanvas -* @private -* @param {RenderSession} renderSession - The Render Session to render the Text on. -*/ + * Renders the object using the Canvas renderer. + * + * @method Phaser.Text#_renderCanvas + * @private + * @param {RenderSession} renderSession - The Render Session to render the Text on. + */ Phaser.Text.prototype._renderCanvas = function (renderSession) { - if (this.dirty) { this.updateText(); @@ -1577,19 +1532,17 @@ Phaser.Text.prototype._renderCanvas = function (renderSession) } PIXI.Sprite.prototype._renderCanvas.call(this, renderSession); - }; /** -* Calculates the ascent, descent and fontSize of a given font style. -* -* @method Phaser.Text#determineFontProperties -* @private -* @param {object} fontStyle -*/ + * Calculates the ascent, descent and fontSize of a given font style. + * + * @method Phaser.Text#determineFontProperties + * @private + * @param {object} fontStyle + */ Phaser.Text.prototype.determineFontProperties = function (fontStyle) { - var properties = Phaser.Text.fontPropertiesCache[fontStyle]; var measureText = this.testString || '|MÉq'; @@ -1699,20 +1652,18 @@ Phaser.Text.prototype.determineFontProperties = function (fontStyle) } return properties; - }; /** -* Returns the bounds of the Text as a rectangle. -* The bounds calculation takes the worldTransform into account. -* -* @method Phaser.Text#getBounds -* @param {Phaser.Matrix} matrix - The transformation matrix of the Text. -* @return {Phaser.Rectangle} The framing rectangle -*/ + * Returns the bounds of the Text as a rectangle. + * The bounds calculation takes the worldTransform into account. + * + * @method Phaser.Text#getBounds + * @param {Phaser.Matrix} matrix - The transformation matrix of the Text. + * @return {Phaser.Rectangle} The framing rectangle + */ Phaser.Text.prototype.getBounds = function (matrix) { - if (this.dirty) { this.updateText(); @@ -1720,20 +1671,18 @@ Phaser.Text.prototype.getBounds = function (matrix) } return PIXI.Sprite.prototype.getBounds.call(this, matrix); - }; /** -* Sets the character limit of the text, with a suffix. -* If the text is longer than this limit, it is truncated and the suffix is appended. -* -* @method Phaser.Text#setCharacterLimit -* @param {number} [characterLimit] - The x coordinate of the Text Bounds region. -* @param {string} [suffix] - The suffix to append to the truncated text. -*/ + * Sets the character limit of the text, with a suffix. + * If the text is longer than this limit, it is truncated and the suffix is appended. + * + * @method Phaser.Text#setCharacterLimit + * @param {number} [characterLimit] - The x coordinate of the Text Bounds region. + * @param {string} [suffix] - The suffix to append to the truncated text. + */ Phaser.Text.prototype.setCharacterLimit = function (characterLimit, suffix) { - this.characterLimitSuffix = (suffix === undefined) ? '' : suffix; this.characterLimitSize = characterLimit; @@ -1741,13 +1690,13 @@ Phaser.Text.prototype.setCharacterLimit = function (characterLimit, suffix) }; /** -* The text to be displayed by this Text object. -* Use a \n to insert a carriage return and split the text. -* The text will be rendered with any style currently set. -* -* @name Phaser.Text#text -* @property {string} text -*/ + * The text to be displayed by this Text object. + * Use a \n to insert a carriage return and split the text. + * The text will be rendered with any style currently set. + * + * @name Phaser.Text#text + * @property {string} text + */ Object.defineProperty(Phaser.Text.prototype, 'text', { get: function () @@ -1757,7 +1706,6 @@ Object.defineProperty(Phaser.Text.prototype, 'text', { set: function (value) { - if (value !== this._text) { this._text = value.toString() || ''; @@ -1768,22 +1716,21 @@ Object.defineProperty(Phaser.Text.prototype, 'text', { this.updateTransform(); } } - } }); /** -* Change the font used. -* -* This is equivalent of the `font` property specified to {@link Phaser.Text#setStyle setStyle}, except -* that unlike using `setStyle` this will not change any current font fill/color settings. -* -* The CSS font string can also be individually altered with the `font`, `fontSize`, `fontWeight`, `fontStyle`, and `fontVariant` properties. -* -* @name Phaser.Text#cssFont -* @property {string} cssFont -*/ + * Change the font used. + * + * This is equivalent of the `font` property specified to {@link Phaser.Text#setStyle setStyle}, except + * that unlike using `setStyle` this will not change any current font fill/color settings. + * + * The CSS font string can also be individually altered with the `font`, `fontSize`, `fontWeight`, `fontStyle`, and `fontVariant` properties. + * + * @name Phaser.Text#cssFont + * @property {string} cssFont + */ Object.defineProperty(Phaser.Text.prototype, 'cssFont', { get: function () @@ -1801,16 +1748,16 @@ Object.defineProperty(Phaser.Text.prototype, 'cssFont', { }); /** -* Change the font family that the text will be rendered in, such as 'Arial'. -* -* Multiple CSS font families and generic fallbacks can be specified as long as -* {@link http://www.w3.org/TR/CSS2/fonts.html#propdef-font-family CSS font-family rules} are followed. -* -* To change the entire font string use {@link Phaser.Text#cssFont cssFont} instead: eg. `text.cssFont = 'bold 20pt Arial'`. -* -* @name Phaser.Text#font -* @property {string} font -*/ + * Change the font family that the text will be rendered in, such as 'Arial'. + * + * Multiple CSS font families and generic fallbacks can be specified as long as + * {@link http://www.w3.org/TR/CSS2/fonts.html#propdef-font-family CSS font-family rules} are followed. + * + * To change the entire font string use {@link Phaser.Text#cssFont cssFont} instead: eg. `text.cssFont = 'bold 20pt Arial'`. + * + * @name Phaser.Text#font + * @property {string} font + */ Object.defineProperty(Phaser.Text.prototype, 'font', { get: function () @@ -1820,7 +1767,6 @@ Object.defineProperty(Phaser.Text.prototype, 'font', { set: function (value) { - value = value || 'Arial'; value = value.trim(); @@ -1832,25 +1778,23 @@ Object.defineProperty(Phaser.Text.prototype, 'font', { this._fontComponents.fontFamily = value; this.updateFont(this._fontComponents); - } }); /** -* The size of the font. -* -* If the font size is specified in pixels (eg. `32` or `'32px`') then a number (ie. `32`) representing -* the font size in pixels is returned; otherwise the value with CSS unit is returned as a string (eg. `'12pt'`). -* -* @name Phaser.Text#fontSize -* @property {number|string} fontSize -*/ + * The size of the font. + * + * If the font size is specified in pixels (eg. `32` or `'32px`') then a number (ie. `32`) representing + * the font size in pixels is returned; otherwise the value with CSS unit is returned as a string (eg. `'12pt'`). + * + * @name Phaser.Text#fontSize + * @property {number|string} fontSize + */ Object.defineProperty(Phaser.Text.prototype, 'fontSize', { get: function () { - var size = this._fontComponents.fontSize; if (size && (/(?:^0$|px$)/).exec(size)) @@ -1861,12 +1805,10 @@ Object.defineProperty(Phaser.Text.prototype, 'fontSize', { { return size; } - }, set: function (value) { - value = value || '0'; if (typeof value === 'number') @@ -1876,16 +1818,15 @@ Object.defineProperty(Phaser.Text.prototype, 'fontSize', { this._fontComponents.fontSize = value; this.updateFont(this._fontComponents); - } }); /** -* The weight of the font: 'normal', 'bold', or {@link http://www.w3.org/TR/CSS2/fonts.html#propdef-font-weight a valid CSS font weight}. -* @name Phaser.Text#fontWeight -* @property {string} fontWeight -*/ + * The weight of the font: 'normal', 'bold', or {@link http://www.w3.org/TR/CSS2/fonts.html#propdef-font-weight a valid CSS font weight}. + * @name Phaser.Text#fontWeight + * @property {string} fontWeight + */ Object.defineProperty(Phaser.Text.prototype, 'fontWeight', { get: function () @@ -1895,20 +1836,18 @@ Object.defineProperty(Phaser.Text.prototype, 'fontWeight', { set: function (value) { - value = value || 'normal'; this._fontComponents.fontWeight = value; this.updateFont(this._fontComponents); - } }); /** -* The style of the font: 'normal', 'italic', 'oblique' -* @name Phaser.Text#fontStyle -* @property {string} fontStyle -*/ + * The style of the font: 'normal', 'italic', 'oblique' + * @name Phaser.Text#fontStyle + * @property {string} fontStyle + */ Object.defineProperty(Phaser.Text.prototype, 'fontStyle', { get: function () @@ -1918,20 +1857,18 @@ Object.defineProperty(Phaser.Text.prototype, 'fontStyle', { set: function (value) { - value = value || 'normal'; this._fontComponents.fontStyle = value; this.updateFont(this._fontComponents); - } }); /** -* The variant the font: 'normal', 'small-caps' -* @name Phaser.Text#fontVariant -* @property {string} fontVariant -*/ + * The variant the font: 'normal', 'small-caps' + * @name Phaser.Text#fontVariant + * @property {string} fontVariant + */ Object.defineProperty(Phaser.Text.prototype, 'fontVariant', { get: function () @@ -1941,19 +1878,17 @@ Object.defineProperty(Phaser.Text.prototype, 'fontVariant', { set: function (value) { - value = value || 'normal'; this._fontComponents.fontVariant = value; this.updateFont(this._fontComponents); - } }); /** -* @name Phaser.Text#fill -* @property {object} fill - A canvas fillstyle that will be used on the text eg 'red', '#00FF00'. -*/ + * @name Phaser.Text#fill + * @property {object} fill - A canvas fillstyle that will be used on the text eg 'red', '#00FF00'. + */ Object.defineProperty(Phaser.Text.prototype, 'fill', { get: function () @@ -1963,24 +1898,22 @@ Object.defineProperty(Phaser.Text.prototype, 'fill', { set: function (value) { - if (value !== this.style.fill) { this.style.fill = value; this.dirty = true; } - } }); /** -* Controls the horizontal alignment for multiline text. -* Can be: 'left', 'center' or 'right'. -* Does not affect single lines of text. For that please see `setTextBounds`. -* @name Phaser.Text#align -* @property {string} align -*/ + * Controls the horizontal alignment for multiline text. + * Can be: 'left', 'center' or 'right'. + * Does not affect single lines of text. For that please see `setTextBounds`. + * @name Phaser.Text#align + * @property {string} align + */ Object.defineProperty(Phaser.Text.prototype, 'align', { get: function () @@ -1990,24 +1923,22 @@ Object.defineProperty(Phaser.Text.prototype, 'align', { set: function (value) { - value = value.toLowerCase(); if (value !== this.style.align) { this.style.align = value; this.dirty = true; } - } }); /** -* The resolution of the canvas the text is rendered to. -* This defaults to match the resolution of the renderer, but can be changed on a per Text object basis. -* @name Phaser.Text#resolution -* @property {integer} resolution -*/ + * The resolution of the canvas the text is rendered to. + * This defaults to match the resolution of the renderer, but can be changed on a per Text object basis. + * @name Phaser.Text#resolution + * @property {integer} resolution + */ Object.defineProperty(Phaser.Text.prototype, 'resolution', { get: function () @@ -2017,26 +1948,24 @@ Object.defineProperty(Phaser.Text.prototype, 'resolution', { set: function (value) { - if (value !== this._res) { this._res = value; this.dirty = true; } - } }); /** -* The size (in pixels) of the tabs, for when text includes tab characters. 0 disables. -* Can be an integer or an array of varying tab sizes, one tab per element. -* For example if you set tabs to 100 then when Text encounters a tab it will jump ahead 100 pixels. -* If you set tabs to be `[100,200]` then it will set the first tab at 100px and the second at 200px. -* -* @name Phaser.Text#tabs -* @property {integer|array} tabs -*/ + * The size (in pixels) of the tabs, for when text includes tab characters. 0 disables. + * Can be an integer or an array of varying tab sizes, one tab per element. + * For example if you set tabs to 100 then when Text encounters a tab it will jump ahead 100 pixels. + * If you set tabs to be `[100,200]` then it will set the first tab at 100px and the second at 200px. + * + * @name Phaser.Text#tabs + * @property {integer|array} tabs + */ Object.defineProperty(Phaser.Text.prototype, 'tabs', { get: function () @@ -2046,22 +1975,20 @@ Object.defineProperty(Phaser.Text.prototype, 'tabs', { set: function (value) { - if (value !== this.style.tabs) { this.style.tabs = value; this.dirty = true; } - } }); /** -* Horizontal alignment of the text within the `textBounds`. Can be: 'left', 'center' or 'right'. -* @name Phaser.Text#boundsAlignH -* @property {string} boundsAlignH -*/ + * Horizontal alignment of the text within the `textBounds`. Can be: 'left', 'center' or 'right'. + * @name Phaser.Text#boundsAlignH + * @property {string} boundsAlignH + */ Object.defineProperty(Phaser.Text.prototype, 'boundsAlignH', { get: function () @@ -2071,23 +1998,21 @@ Object.defineProperty(Phaser.Text.prototype, 'boundsAlignH', { set: function (value) { - value = value.toLowerCase(); if (value !== this.style.boundsAlignH) { this.style.boundsAlignH = value; this.dirty = true; } - } }); /** -* Vertical alignment of the text within the `textBounds`. Can be: 'top', 'middle' or 'bottom'. -* @name Phaser.Text#boundsAlignV -* @property {string} boundsAlignV -*/ + * Vertical alignment of the text within the `textBounds`. Can be: 'top', 'middle' or 'bottom'. + * @name Phaser.Text#boundsAlignV + * @property {string} boundsAlignV + */ Object.defineProperty(Phaser.Text.prototype, 'boundsAlignV', { get: function () @@ -2097,22 +2022,20 @@ Object.defineProperty(Phaser.Text.prototype, 'boundsAlignV', { set: function (value) { - value = value.toLowerCase(); if (value !== this.style.boundsAlignV) { this.style.boundsAlignV = value; this.dirty = true; } - } }); /** -* @name Phaser.Text#stroke -* @property {string} stroke - A canvas fillstyle that will be used on the text stroke eg 'blue', '#FCFF00'. -*/ + * @name Phaser.Text#stroke + * @property {string} stroke - A canvas fillstyle that will be used on the text stroke eg 'blue', '#FCFF00'. + */ Object.defineProperty(Phaser.Text.prototype, 'stroke', { get: function () @@ -2122,21 +2045,19 @@ Object.defineProperty(Phaser.Text.prototype, 'stroke', { set: function (value) { - if (value !== this.style.stroke) { this.style.stroke = value; this.dirty = true; } - } }); /** -* @name Phaser.Text#strokeThickness -* @property {number} strokeThickness - A number that represents the thickness of the stroke. Default is 0 (no stroke) -*/ + * @name Phaser.Text#strokeThickness + * @property {number} strokeThickness - A number that represents the thickness of the stroke. Default is 0 (no stroke) + */ Object.defineProperty(Phaser.Text.prototype, 'strokeThickness', { get: function () @@ -2146,21 +2067,19 @@ Object.defineProperty(Phaser.Text.prototype, 'strokeThickness', { set: function (value) { - if (value !== this.style.strokeThickness) { this.style.strokeThickness = Number(value); this.dirty = true; } - } }); /** -* @name Phaser.Text#wordWrap -* @property {boolean} wordWrap - Indicates if word wrap should be used. -*/ + * @name Phaser.Text#wordWrap + * @property {boolean} wordWrap - Indicates if word wrap should be used. + */ Object.defineProperty(Phaser.Text.prototype, 'wordWrap', { get: function () @@ -2170,21 +2089,19 @@ Object.defineProperty(Phaser.Text.prototype, 'wordWrap', { set: function (value) { - if (value !== this.style.wordWrap) { this.style.wordWrap = value; this.dirty = true; } - } }); /** -* @name Phaser.Text#wordWrapWidth -* @property {number} wordWrapWidth - The width at which text will wrap. -*/ + * @name Phaser.Text#wordWrapWidth + * @property {number} wordWrapWidth - The width at which text will wrap. + */ Object.defineProperty(Phaser.Text.prototype, 'wordWrapWidth', { get: function () @@ -2194,21 +2111,19 @@ Object.defineProperty(Phaser.Text.prototype, 'wordWrapWidth', { set: function (value) { - if (value !== this.style.wordWrapWidth) { this.style.wordWrapWidth = value; this.dirty = true; } - } }); /** -* @name Phaser.Text#lineSpacing -* @property {number} lineSpacing - Additional spacing (in pixels) between each line of text if multi-line. -*/ + * @name Phaser.Text#lineSpacing + * @property {number} lineSpacing - Additional spacing (in pixels) between each line of text if multi-line. + */ Object.defineProperty(Phaser.Text.prototype, 'lineSpacing', { get: function () @@ -2218,7 +2133,6 @@ Object.defineProperty(Phaser.Text.prototype, 'lineSpacing', { set: function (value) { - if (value !== this._lineSpacing) { this._lineSpacing = parseFloat(value); @@ -2229,15 +2143,14 @@ Object.defineProperty(Phaser.Text.prototype, 'lineSpacing', { this.updateTransform(); } } - } }); /** -* @name Phaser.Text#shadowOffsetX -* @property {number} shadowOffsetX - The shadowOffsetX value in pixels. This is how far offset horizontally the shadow effect will be. -*/ + * @name Phaser.Text#shadowOffsetX + * @property {number} shadowOffsetX - The shadowOffsetX value in pixels. This is how far offset horizontally the shadow effect will be. + */ Object.defineProperty(Phaser.Text.prototype, 'shadowOffsetX', { get: function () @@ -2247,21 +2160,19 @@ Object.defineProperty(Phaser.Text.prototype, 'shadowOffsetX', { set: function (value) { - if (value !== this.style.shadowOffsetX) { this.style.shadowOffsetX = value; this.dirty = true; } - } }); /** -* @name Phaser.Text#shadowOffsetY -* @property {number} shadowOffsetY - The shadowOffsetY value in pixels. This is how far offset vertically the shadow effect will be. -*/ + * @name Phaser.Text#shadowOffsetY + * @property {number} shadowOffsetY - The shadowOffsetY value in pixels. This is how far offset vertically the shadow effect will be. + */ Object.defineProperty(Phaser.Text.prototype, 'shadowOffsetY', { get: function () @@ -2271,21 +2182,19 @@ Object.defineProperty(Phaser.Text.prototype, 'shadowOffsetY', { set: function (value) { - if (value !== this.style.shadowOffsetY) { this.style.shadowOffsetY = value; this.dirty = true; } - } }); /** -* @name Phaser.Text#shadowColor -* @property {string} shadowColor - The color of the shadow, as given in CSS rgba format. Set the alpha component to 0 to disable the shadow. -*/ + * @name Phaser.Text#shadowColor + * @property {string} shadowColor - The color of the shadow, as given in CSS rgba format. Set the alpha component to 0 to disable the shadow. + */ Object.defineProperty(Phaser.Text.prototype, 'shadowColor', { get: function () @@ -2295,21 +2204,19 @@ Object.defineProperty(Phaser.Text.prototype, 'shadowColor', { set: function (value) { - if (value !== this.style.shadowColor) { this.style.shadowColor = value; this.dirty = true; } - } }); /** -* @name Phaser.Text#shadowBlur -* @property {number} shadowBlur - The shadowBlur value. Make the shadow softer by applying a Gaussian blur to it. A number from 0 (no blur) up to approx. 10 (depending on scene). -*/ + * @name Phaser.Text#shadowBlur + * @property {number} shadowBlur - The shadowBlur value. Make the shadow softer by applying a Gaussian blur to it. A number from 0 (no blur) up to approx. 10 (depending on scene). + */ Object.defineProperty(Phaser.Text.prototype, 'shadowBlur', { get: function () @@ -2319,21 +2226,19 @@ Object.defineProperty(Phaser.Text.prototype, 'shadowBlur', { set: function (value) { - if (value !== this.style.shadowBlur) { this.style.shadowBlur = value; this.dirty = true; } - } }); /** -* @name Phaser.Text#shadowStroke -* @property {boolean} shadowStroke - Sets if the drop shadow is applied to the Text stroke. -*/ + * @name Phaser.Text#shadowStroke + * @property {boolean} shadowStroke - Sets if the drop shadow is applied to the Text stroke. + */ Object.defineProperty(Phaser.Text.prototype, 'shadowStroke', { get: function () @@ -2343,21 +2248,19 @@ Object.defineProperty(Phaser.Text.prototype, 'shadowStroke', { set: function (value) { - if (value !== this.style.shadowStroke) { this.style.shadowStroke = value; this.dirty = true; } - } }); /** -* @name Phaser.Text#shadowFill -* @property {boolean} shadowFill - Sets if the drop shadow is applied to the Text fill. -*/ + * @name Phaser.Text#shadowFill + * @property {boolean} shadowFill - Sets if the drop shadow is applied to the Text fill. + */ Object.defineProperty(Phaser.Text.prototype, 'shadowFill', { get: function () @@ -2367,27 +2270,24 @@ Object.defineProperty(Phaser.Text.prototype, 'shadowFill', { set: function (value) { - if (value !== this.style.shadowFill) { this.style.shadowFill = value; this.dirty = true; } - } }); /** -* The width of the Text object in pixels. This is width of the Texture frame / the Text.resolution. -* @name Phaser.Text#width -* @property {number} width - The width of the Text. Setting this will modify the scale to achieve the value requested. -*/ + * The width of the Text object in pixels. This is width of the Texture frame / the Text.resolution. + * @name Phaser.Text#width + * @property {number} width - The width of the Text. Setting this will modify the scale to achieve the value requested. + */ Object.defineProperty(Phaser.Text.prototype, 'width', { get: function () { - if (this.dirty) { this.updateText(); @@ -2399,7 +2299,6 @@ Object.defineProperty(Phaser.Text.prototype, 'width', { set: function (value) { - this.scale.x = value / this.texture.frame.width; this._width = value; } @@ -2407,15 +2306,14 @@ Object.defineProperty(Phaser.Text.prototype, 'width', { }); /** -* The height of the Text object in pixels. This is height of the Texture frame / the Text.resolution. -* @name Phaser.Text#height -* @property {number} height - The height of the Text. Setting this will modify the scale to achieve the value requested. -*/ + * The height of the Text object in pixels. This is height of the Texture frame / the Text.resolution. + * @name Phaser.Text#height + * @property {number} height - The height of the Text. Setting this will modify the scale to achieve the value requested. + */ Object.defineProperty(Phaser.Text.prototype, 'height', { get: function () { - if (this.dirty) { this.updateText(); @@ -2427,7 +2325,6 @@ Object.defineProperty(Phaser.Text.prototype, 'height', { set: function (value) { - this.scale.y = value / this.texture.frame.height; this._height = value; } @@ -2435,25 +2332,21 @@ Object.defineProperty(Phaser.Text.prototype, 'height', { }); /** -* The text used to measure the font's width and height -* @name Phaser.Text#testString -* @default '|MÉq' -*/ + * The text used to measure the font's width and height + * @name Phaser.Text#testString + * @default '|MÉq' + */ Object.defineProperty(Phaser.Text.prototype, 'testString', { get: function () { - return this._testString; - }, set: function (value) { - this._testString = value; this.updateText(); - } }); diff --git a/src/gameobjects/TileSprite.js b/src/gameobjects/TileSprite.js index 0004c4b33..ea7d38972 100644 --- a/src/gameobjects/TileSprite.js +++ b/src/gameobjects/TileSprite.js @@ -1,64 +1,63 @@ /** -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* A TileSprite is a Sprite that has a repeating texture. The texture can be scrolled and scaled independently of the TileSprite itself. -* Textures will automatically wrap and are designed so that you can create game backdrops using seamless textures as a source. -* -* TileSprites have no input handler or physics bodies by default, both need enabling in the same way as for normal Sprites. -* -* You shouldn't ever create a TileSprite any larger than your actual screen size. If you want to create a large repeating background -* that scrolls across the whole map of your game, then you create a TileSprite that fits the screen size and then use the `tilePosition` -* property to scroll the texture as the player moves. If you create a TileSprite that is thousands of pixels in size then it will -* consume huge amounts of memory and cause performance issues. Remember: use `tilePosition` to scroll your texture and `tileScale` to -* adjust the scale of the texture - don't resize the sprite itself or make it larger than it needs. -* -* An important note about texture dimensions: -* -* When running under Canvas a TileSprite can use any texture size without issue. When running under WebGL the texture should ideally be -* a power of two in size (i.e. 4, 8, 16, 32, 64, 128, 256, 512, etc pixels width by height). If the texture isn't a power of two -* it will be rendered to a blank canvas that is the correct size, which means you may have 'blank' areas appearing to the right and -* bottom of your frame. To avoid this ensure your textures are perfect powers of two. -* -* TileSprites support animations in the same way that Sprites do. You add and play animations using the AnimationManager. However -* if your game is running under WebGL please note that each frame of the animation must be a power of two in size, or it will receive -* additional padding to enforce it to be so. -* -* @class Phaser.TileSprite -* @constructor -* @extends PIXI.Sprite -* @extends Phaser.Component.Core -* @extends Phaser.Component.Angle -* @extends Phaser.Component.Animation -* @extends Phaser.Component.AutoCull -* @extends Phaser.Component.Bounds -* @extends Phaser.Component.BringToTop -* @extends Phaser.Component.Destroy -* @extends Phaser.Component.FixedToCamera -* @extends Phaser.Component.Health -* @extends Phaser.Component.InCamera -* @extends Phaser.Component.InputEnabled -* @extends Phaser.Component.InWorld -* @extends Phaser.Component.LifeSpan -* @extends Phaser.Component.LoadTexture -* @extends Phaser.Component.Overlap -* @extends Phaser.Component.PhysicsBody -* @extends Phaser.Component.Reset -* @extends Phaser.Component.Smoothed -* @param {Phaser.Game} game - A reference to the currently running game. -* @param {number} [x=0] - The x coordinate (in world space) to position the TileSprite at. -* @param {number} [y=0] - The y coordinate (in world space) to position the TileSprite at. -* @param {number} [width=256] - The width of the TileSprite. -* @param {number} [height=256] - The height of the TileSprite. -* @param {string|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 Phaser Image Cache entry, or an instance of a PIXI.Texture or BitmapData. -* @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. -*/ + * A TileSprite is a Sprite that has a repeating texture. The texture can be scrolled and scaled independently of the TileSprite itself. + * Textures will automatically wrap and are designed so that you can create game backdrops using seamless textures as a source. + * + * TileSprites have no input handler or physics bodies by default, both need enabling in the same way as for normal Sprites. + * + * You shouldn't ever create a TileSprite any larger than your actual screen size. If you want to create a large repeating background + * that scrolls across the whole map of your game, then you create a TileSprite that fits the screen size and then use the `tilePosition` + * property to scroll the texture as the player moves. If you create a TileSprite that is thousands of pixels in size then it will + * consume huge amounts of memory and cause performance issues. Remember: use `tilePosition` to scroll your texture and `tileScale` to + * adjust the scale of the texture - don't resize the sprite itself or make it larger than it needs. + * + * An important note about texture dimensions: + * + * When running under Canvas a TileSprite can use any texture size without issue. When running under WebGL the texture should ideally be + * a power of two in size (i.e. 4, 8, 16, 32, 64, 128, 256, 512, etc pixels width by height). If the texture isn't a power of two + * it will be rendered to a blank canvas that is the correct size, which means you may have 'blank' areas appearing to the right and + * bottom of your frame. To avoid this ensure your textures are perfect powers of two. + * + * TileSprites support animations in the same way that Sprites do. You add and play animations using the AnimationManager. However + * if your game is running under WebGL please note that each frame of the animation must be a power of two in size, or it will receive + * additional padding to enforce it to be so. + * + * @class Phaser.TileSprite + * @constructor + * @extends PIXI.Sprite + * @extends Phaser.Component.Core + * @extends Phaser.Component.Angle + * @extends Phaser.Component.Animation + * @extends Phaser.Component.AutoCull + * @extends Phaser.Component.Bounds + * @extends Phaser.Component.BringToTop + * @extends Phaser.Component.Destroy + * @extends Phaser.Component.FixedToCamera + * @extends Phaser.Component.Health + * @extends Phaser.Component.InCamera + * @extends Phaser.Component.InputEnabled + * @extends Phaser.Component.InWorld + * @extends Phaser.Component.LifeSpan + * @extends Phaser.Component.LoadTexture + * @extends Phaser.Component.Overlap + * @extends Phaser.Component.PhysicsBody + * @extends Phaser.Component.Reset + * @extends Phaser.Component.Smoothed + * @param {Phaser.Game} game - A reference to the currently running game. + * @param {number} [x=0] - The x coordinate (in world space) to position the TileSprite at. + * @param {number} [y=0] - The y coordinate (in world space) to position the TileSprite at. + * @param {number} [width=256] - The width of the TileSprite. + * @param {number} [height=256] - The height of the TileSprite. + * @param {string|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 Phaser Image Cache entry, or an instance of a PIXI.Texture or BitmapData. + * @param {string|number} frame - If this TileSprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. + */ Phaser.TileSprite = function (game, x, y, width, height, key, frame) { - x = x || 0; y = y || 0; width = width || 256; @@ -69,73 +68,73 @@ Phaser.TileSprite = function (game, x, y, width, height, key, frame) PIXI.Sprite.call(this, new PIXI.Texture(Phaser.Cache.DEFAULT.baseTexture), width, height); /** - * @property {number} type - The const type of this object. - * @readonly - */ + * @property {number} type - The const type of this object. + * @readonly + */ this.type = Phaser.TILESPRITE; /** - * @property {number} physicsType - The const physics body type of this object. - * @readonly - */ + * @property {number} physicsType - The const physics body type of this object. + * @readonly + */ this.physicsType = Phaser.SPRITE; /** - * @property {Phaser.Point} _scroll - Internal cache var. - * @private - */ + * @property {Phaser.Point} _scroll - Internal cache var. + * @private + */ this._scroll = new Phaser.Point(); /** - * @property {Phaser.Point} tileScale - The scale applied to the image being tiled. - */ + * @property {Phaser.Point} tileScale - The scale applied to the image being tiled. + */ this.tileScale = new Phaser.Point(1, 1); /** - * @property {Phaser.Point} tileScaleOffset - The scale offset applied to the image being tiled. - */ + * @property {Phaser.Point} tileScaleOffset - The scale offset applied to the image being tiled. + */ this.tileScaleOffset = new Phaser.Point(1, 1); /** - * @property {Phaser.Point} tilePosition - The offset position of the image being tiled. - */ + * @property {Phaser.Point} tilePosition - The offset position of the image being tiled. + */ this.tilePosition = new Phaser.Point(); /** - * If enabled a green rectangle will be drawn behind the generated tiling texture, - * allowing you to visually debug the texture being used. - * - * @property {boolean} textureDebug - */ + * If enabled a green rectangle will be drawn behind the generated tiling texture, + * allowing you to visually debug the texture being used. + * + * @property {boolean} textureDebug + */ this.textureDebug = false; /** - * The CanvasBuffer object that the tiled texture is drawn to. - * - * @property {PIXI.CanvasBuffer} canvasBuffer - */ + * The CanvasBuffer object that the tiled texture is drawn to. + * + * @property {PIXI.CanvasBuffer} canvasBuffer + */ this.canvasBuffer = null; /** - * An internal Texture object that holds the tiling texture that was generated from TilingSprite.texture. - * - * @property {PIXI.Texture} tilingTexture - */ + * An internal Texture object that holds the tiling texture that was generated from TilingSprite.texture. + * + * @property {PIXI.Texture} tilingTexture + */ this.tilingTexture = null; /** - * The Context fill pattern that is used to draw the TilingSprite in Canvas mode only (will be null in WebGL). - * - * @property {object} tilePattern - */ + * The Context fill pattern that is used to draw the TilingSprite in Canvas mode only (will be null in WebGL). + * + * @property {object} tilePattern + */ this.tilePattern = null; /** - * If true the TileSprite will run `generateTexture` on its **next** render pass. - * This is set by the likes of Phaser.LoadTexture.setFrame. - * - * @property {boolean} refreshTexture - */ + * If true the TileSprite will run `generateTexture` on its **next** render pass. + * This is set by the likes of Phaser.LoadTexture.setFrame. + * + * @property {boolean} refreshTexture + */ this.refreshTexture = true; this.frameWidth = 0; @@ -145,7 +144,6 @@ Phaser.TileSprite = function (game, x, y, width, height, key, frame) this._height = height; Phaser.Component.Core.init.call(this, game, x, y, key, frame); - }; Phaser.TileSprite.prototype = Object.create(PIXI.Sprite.prototype); @@ -177,15 +175,14 @@ Phaser.TileSprite.prototype.preUpdateInWorld = Phaser.Component.InWorld.preUpdat Phaser.TileSprite.prototype.preUpdateCore = Phaser.Component.Core.preUpdate; /** -* Automatically called by World.preUpdate. -* -* @method Phaser.TileSprite#preUpdate -* @memberof Phaser.TileSprite -* @return {boolean} -*/ + * Automatically called by World.preUpdate. + * + * @method Phaser.TileSprite#preUpdate + * @memberof Phaser.TileSprite + * @return {boolean} + */ Phaser.TileSprite.prototype.preUpdate = function () { - if (this._scroll.x !== 0) { this.tilePosition.x += this._scroll.x * this.game.time.physicsElapsed; @@ -202,57 +199,51 @@ Phaser.TileSprite.prototype.preUpdate = function () } return this.preUpdateCore(); - }; /** -* Sets this TileSprite to automatically scroll in the given direction until stopped via TileSprite.stopScroll(). -* The scroll speed is specified in pixels per second. -* A negative x value will scroll to the left. A positive x value will scroll to the right. -* A negative y value will scroll up. A positive y value will scroll down. -* -* @method Phaser.TileSprite#autoScroll -* @memberof Phaser.TileSprite -* @param {number} x - Horizontal scroll speed in pixels per second. -* @param {number} y - Vertical scroll speed in pixels per second. -* @return {Phaser.TileSprite} This instance. -*/ + * Sets this TileSprite to automatically scroll in the given direction until stopped via TileSprite.stopScroll(). + * The scroll speed is specified in pixels per second. + * A negative x value will scroll to the left. A positive x value will scroll to the right. + * A negative y value will scroll up. A positive y value will scroll down. + * + * @method Phaser.TileSprite#autoScroll + * @memberof Phaser.TileSprite + * @param {number} x - Horizontal scroll speed in pixels per second. + * @param {number} y - Vertical scroll speed in pixels per second. + * @return {Phaser.TileSprite} This instance. + */ Phaser.TileSprite.prototype.autoScroll = function (x, y) { - this._scroll.set(x, y); return this; - }; /** -* Stops an automatically scrolling TileSprite. -* -* @method Phaser.TileSprite#stopScroll -* @memberof Phaser.TileSprite -* @return {Phaser.TileSprite} This instance. -*/ + * Stops an automatically scrolling TileSprite. + * + * @method Phaser.TileSprite#stopScroll + * @memberof Phaser.TileSprite + * @return {Phaser.TileSprite} This instance. + */ Phaser.TileSprite.prototype.stopScroll = function () { - this._scroll.set(0, 0); return this; - }; /** -* Destroys the TileSprite. This removes it from its parent group, destroys the event and animation handlers if present -* and nulls its reference to game, freeing it up for garbage collection. -* -* @method Phaser.TileSprite#destroy -* @memberof Phaser.TileSprite -* @param {boolean} [destroyChildren=true] - Should every child of this object have its destroy method called? -*/ + * Destroys the TileSprite. This removes it from its parent group, destroys the event and animation handlers if present + * and nulls its reference to game, freeing it up for garbage collection. + * + * @method Phaser.TileSprite#destroy + * @memberof Phaser.TileSprite + * @param {boolean} [destroyChildren=true] - Should every child of this object have its destroy method called? + */ Phaser.TileSprite.prototype.destroy = function (destroyChildren) { - Phaser.Component.Destroy.prototype.destroy.call(this, destroyChildren); PIXI.Sprite.prototype.destroy.call(this); @@ -272,44 +263,40 @@ Phaser.TileSprite.prototype.destroy = function (destroyChildren) this.tilingTexture.destroy(true); this.tilingTexture = null; } - }; /** -* Resets the TileSprite. This places the TileSprite at the given x/y world coordinates, resets the tilePosition and then -* sets alive, exists, visible and renderable all to true. Also resets the outOfBounds state. -* If the TileSprite has a physics body that too is reset. -* -* @method Phaser.TileSprite#reset -* @memberof Phaser.TileSprite -* @param {number} x - The x coordinate (in world space) to position the Sprite at. -* @param {number} y - The y coordinate (in world space) to position the Sprite at. -* @return {Phaser.TileSprite} This instance. -*/ + * Resets the TileSprite. This places the TileSprite at the given x/y world coordinates, resets the tilePosition and then + * sets alive, exists, visible and renderable all to true. Also resets the outOfBounds state. + * If the TileSprite has a physics body that too is reset. + * + * @method Phaser.TileSprite#reset + * @memberof Phaser.TileSprite + * @param {number} x - The x coordinate (in world space) to position the Sprite at. + * @param {number} y - The y coordinate (in world space) to position the Sprite at. + * @return {Phaser.TileSprite} This instance. + */ Phaser.TileSprite.prototype.reset = function (x, y) { - Phaser.Component.Reset.prototype.reset.call(this, x, y); this.tilePosition.x = 0; this.tilePosition.y = 0; return this; - }; /** -* Changes the texture being rendered by this TileSprite. -* Causes a texture refresh to take place on the next render. -* -* @method Phaser.TileSprite#setTexture -* @memberof Phaser.TileSprite -* @param {PIXI.Texture} texture - The texture to apply to this TileSprite. -* @return {Phaser.TileSprite} This instance. -*/ + * Changes the texture being rendered by this TileSprite. + * Causes a texture refresh to take place on the next render. + * + * @method Phaser.TileSprite#setTexture + * @memberof Phaser.TileSprite + * @param {PIXI.Texture} texture - The texture to apply to this TileSprite. + * @return {Phaser.TileSprite} This instance. + */ Phaser.TileSprite.prototype.setTexture = function (texture) { - if (this.texture !== texture) { this.texture = texture; @@ -318,20 +305,18 @@ Phaser.TileSprite.prototype.setTexture = function (texture) } return this; - }; /** -* Renders the TileSprite using the WebGL Renderer. -* -* @private -* @method Phaser.TileSprite#_renderWebGL -* @memberof Phaser.TileSprite -* @param {object} renderSession -*/ + * Renders the TileSprite using the WebGL Renderer. + * + * @private + * @method Phaser.TileSprite#_renderWebGL + * @memberof Phaser.TileSprite + * @param {object} renderSession + */ Phaser.TileSprite.prototype._renderWebGL = function (renderSession) { - if (!this.visible || !this.renderable || this.alpha === 0) { return; @@ -399,20 +384,18 @@ Phaser.TileSprite.prototype._renderWebGL = function (renderSession) { renderSession.spriteBatch.start(); } - }; /** -* Renders the TileSprite using the Canvas Renderer. -* -* @private -* @method Phaser.TileSprite#_renderCanvas -* @memberof Phaser.TileSprite -* @param {object} renderSession -*/ + * Renders the TileSprite using the Canvas Renderer. + * + * @private + * @method Phaser.TileSprite#_renderCanvas + * @memberof Phaser.TileSprite + * @param {object} renderSession + */ Phaser.TileSprite.prototype._renderCanvas = function (renderSession) { - if (!this.visible || !this.renderable || this.alpha === 0) { return; @@ -515,16 +498,15 @@ Phaser.TileSprite.prototype._renderCanvas = function (renderSession) renderSession.currentBlendMode = sessionBlendMode; context.globalCompositeOperation = PIXI.blendModesCanvas[sessionBlendMode]; } - }; /** -* Override the Sprite method. -* -* @private -* @method Phaser.TileSprite#onTextureUpdate -* @memberof Phaser.TileSprite -*/ + * Override the Sprite method. + * + * @private + * @method Phaser.TileSprite#onTextureUpdate + * @memberof Phaser.TileSprite + */ Phaser.TileSprite.prototype.onTextureUpdate = function () { @@ -533,15 +515,14 @@ Phaser.TileSprite.prototype.onTextureUpdate = function () }; /** -* Internal method that generates a new tiling texture. -* -* @method Phaser.TileSprite#generateTilingTexture -* @memberof Phaser.TileSprite -* @param {boolean} forcePowerOfTwo - Whether we want to force the texture to be a power of two -*/ + * Internal method that generates a new tiling texture. + * + * @method Phaser.TileSprite#generateTilingTexture + * @memberof Phaser.TileSprite + * @param {boolean} forcePowerOfTwo - Whether we want to force the texture to be a power of two + */ Phaser.TileSprite.prototype.generateTilingTexture = function (forcePowerOfTwo) { - if (!this.texture.baseTexture.hasLoaded) { return; @@ -619,19 +600,17 @@ Phaser.TileSprite.prototype.generateTilingTexture = function (forcePowerOfTwo) this.refreshTexture = false; this.tilingTexture.baseTexture._powerOf2 = true; - }; /** -* Returns the framing rectangle of the Tile Sprite. -* -* @method Phaser.TileSprite#getBounds -* @memberof Phaser.TileSprite -* @return {Phaser.Rectangle} The bounds of the Tile Sprite. -*/ + * Returns the framing rectangle of the Tile Sprite. + * + * @method Phaser.TileSprite#getBounds + * @memberof Phaser.TileSprite + * @return {Phaser.Rectangle} The bounds of the Tile Sprite. + */ Phaser.TileSprite.prototype.getBounds = function () { - var width = this._width; var height = this._height; @@ -701,53 +680,44 @@ Phaser.TileSprite.prototype.getBounds = function () this._currentBounds = bounds; return bounds; - }; /** -* The width of the sprite, setting this will actually modify the scale to achieve the value set -* -* @property width -* @type Number -*/ + * The width of the sprite, setting this will actually modify the scale to achieve the value set + * + * @property width + * @type Number + */ Object.defineProperty(Phaser.TileSprite.prototype, 'width', { get: function () { - return this._width; - }, set: function (value) { - this._width = value; - } }); /** -* The height of the TilingSprite, setting this will actually modify the scale to achieve the value set -* -* @property height -* @type Number -*/ + * The height of the TilingSprite, setting this will actually modify the scale to achieve the value set + * + * @property height + * @type Number + */ Object.defineProperty(Phaser.TileSprite.prototype, 'height', { get: function () { - return this._height; - }, set: function (value) { - this._height = value; - } }); diff --git a/src/gameobjects/Video.js b/src/gameobjects/Video.js index fd55dd528..14d213887 100644 --- a/src/gameobjects/Video.js +++ b/src/gameobjects/Video.js @@ -1,244 +1,243 @@ /** -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* A Video object that takes a previously loaded Video from the Phaser Cache and handles playback of it. -* -* Alternatively it takes a getUserMedia feed from an active webcam and streams the contents of that to -* the Video instead (see `startMediaStream` method) -* -* The video can then be applied to a Sprite as a texture. If multiple Sprites share the same Video texture and playback -* changes (i.e. you pause the video, or seek to a new time) then this change will be seen across all Sprites simultaneously. -* -* Due to a bug in IE11 you cannot play a video texture to a Sprite in WebGL. For IE11 force Canvas mode. -* -* If you need each Sprite to be able to play a video fully independently then you will need one Video object per Sprite. -* Please understand the obvious performance implications of doing this, and the memory required to hold videos in RAM. -* -* On some mobile browsers such as iOS Safari, you cannot play a video until the user has explicitly touched the screen. -* This works in the same way as audio unlocking. Phaser will handle the touch unlocking for you, however unlike with audio -* it's worth noting that every single Video needs to be touch unlocked, not just the first one. You can use the `changeSource` -* method to try and work around this limitation, but see the method help for details. -* -* Small screen devices, especially iPod and iPhone will launch the video in its own native video player, -* outside of the Safari browser. There is no way to avoid this, it's a device imposed limitation. -* -* Note: On iOS if you need to detect when the user presses the 'Done' button (before the video ends) -* then you need to add your own event listener -* -* @class Phaser.Video -* @constructor -* @param {Phaser.Game} game - A reference to the currently running game. -* @param {string|null} [key=null] - The key of the video file in the Phaser.Cache that this Video object will play. Set to `null` or leave undefined if you wish to use a webcam as the source. See `startMediaStream` to start webcam capture. -* @param {string|null} [url=null] - If the video hasn't been loaded then you can provide a full URL to the file here (make sure to set key to null) -*/ + * A Video object that takes a previously loaded Video from the Phaser Cache and handles playback of it. + * + * Alternatively it takes a getUserMedia feed from an active webcam and streams the contents of that to + * the Video instead (see `startMediaStream` method) + * + * The video can then be applied to a Sprite as a texture. If multiple Sprites share the same Video texture and playback + * changes (i.e. you pause the video, or seek to a new time) then this change will be seen across all Sprites simultaneously. + * + * Due to a bug in IE11 you cannot play a video texture to a Sprite in WebGL. For IE11 force Canvas mode. + * + * If you need each Sprite to be able to play a video fully independently then you will need one Video object per Sprite. + * Please understand the obvious performance implications of doing this, and the memory required to hold videos in RAM. + * + * On some mobile browsers such as iOS Safari, you cannot play a video until the user has explicitly touched the screen. + * This works in the same way as audio unlocking. Phaser will handle the touch unlocking for you, however unlike with audio + * it's worth noting that every single Video needs to be touch unlocked, not just the first one. You can use the `changeSource` + * method to try and work around this limitation, but see the method help for details. + * + * Small screen devices, especially iPod and iPhone will launch the video in its own native video player, + * outside of the Safari browser. There is no way to avoid this, it's a device imposed limitation. + * + * Note: On iOS if you need to detect when the user presses the 'Done' button (before the video ends) + * then you need to add your own event listener + * + * @class Phaser.Video + * @constructor + * @param {Phaser.Game} game - A reference to the currently running game. + * @param {string|null} [key=null] - The key of the video file in the Phaser.Cache that this Video object will play. Set to `null` or leave undefined if you wish to use a webcam as the source. See `startMediaStream` to start webcam capture. + * @param {string|null} [url=null] - If the video hasn't been loaded then you can provide a full URL to the file here (make sure to set key to null) + */ Phaser.Video = function (game, key, url) { - if (key === undefined) { key = null; } if (url === undefined) { url = null; } /** - * @property {Phaser.Game} game - A reference to the currently running game. - */ + * @property {Phaser.Game} game - A reference to the currently running game. + */ this.game = game; /** - * @property {string} key - The key of the Video in the Cache, if stored there. Will be `null` if this Video is using the webcam instead. - * @default null - */ + * @property {string} key - The key of the Video in the Cache, if stored there. Will be `null` if this Video is using the webcam instead. + * @default null + */ this.key = key; /** - * @property {number} width - The width of the video in pixels. - * @default - */ + * @property {number} width - The width of the video in pixels. + * @default + */ this.width = 0; /** - * @property {number} height - The height of the video in pixels. - * @default - */ + * @property {number} height - The height of the video in pixels. + * @default + */ this.height = 0; /** - * @property {number} type - The const type of this object. - * @default - */ + * @property {number} type - The const type of this object. + * @default + */ this.type = Phaser.VIDEO; /** - * @property {boolean} disableTextureUpload - If true this video will never send its image data to the GPU when its dirty flag is true. This only applies in WebGL. - */ + * @property {boolean} disableTextureUpload - If true this video will never send its image data to the GPU when its dirty flag is true. This only applies in WebGL. + */ this.disableTextureUpload = false; /** - * @property {boolean} touchLocked - true if this video is currently locked awaiting a touch event. This happens on some mobile devices, such as iOS. - * @default - */ + * @property {boolean} touchLocked - true if this video is currently locked awaiting a touch event. This happens on some mobile devices, such as iOS. + * @default + */ this.touchLocked = false; /** - * @property {Phaser.Signal} onPlay - This signal is dispatched when the Video starts to play. It sends 3 parameters: a reference to the Video object, if the video is set to loop or not and the playback rate. - */ + * @property {Phaser.Signal} onPlay - This signal is dispatched when the Video starts to play. It sends 3 parameters: a reference to the Video object, if the video is set to loop or not and the playback rate. + */ this.onPlay = new Phaser.Signal(); /** - * @property {Phaser.Signal} onChangeSource - This signal is dispatched if the Video source is changed. It sends 3 parameters: a reference to the Video object and the new width and height of the new video source. - */ + * @property {Phaser.Signal} onChangeSource - This signal is dispatched if the Video source is changed. It sends 3 parameters: a reference to the Video object and the new width and height of the new video source. + */ this.onChangeSource = new Phaser.Signal(); /** - * @property {Phaser.Signal} onComplete - This signal is dispatched when the Video completes playback, i.e. enters an 'ended' state. On iOS specifically it also fires if the user hits the 'Done' button at any point during playback. Videos set to loop will never dispatch this signal. - */ + * @property {Phaser.Signal} onComplete - This signal is dispatched when the Video completes playback, i.e. enters an 'ended' state. On iOS specifically it also fires if the user hits the 'Done' button at any point during playback. Videos set to loop will never dispatch this signal. + */ this.onComplete = new Phaser.Signal(); /** - * @property {Phaser.Signal} onAccess - This signal is dispatched if the user allows access to their webcam. - */ + * @property {Phaser.Signal} onAccess - This signal is dispatched if the user allows access to their webcam. + */ this.onAccess = new Phaser.Signal(); /** - * @property {Phaser.Signal} onError - This signal is dispatched if an error occurs either getting permission to use the webcam (for a Video Stream) or when trying to play back a video file. - */ + * @property {Phaser.Signal} onError - This signal is dispatched if an error occurs either getting permission to use the webcam (for a Video Stream) or when trying to play back a video file. + */ this.onError = new Phaser.Signal(); /** - * This signal is dispatched if when asking for permission to use the webcam no response is given within a the Video.timeout limit. - * This may be because the user has picked `Not now` in the permissions window, or there is a delay in establishing the LocalMediaStream. - * @property {Phaser.Signal} onTimeout - */ + * This signal is dispatched if when asking for permission to use the webcam no response is given within a the Video.timeout limit. + * This may be because the user has picked `Not now` in the permissions window, or there is a delay in establishing the LocalMediaStream. + * @property {Phaser.Signal} onTimeout + */ this.onTimeout = new Phaser.Signal(); /** - * This signal is dispatched when the Video is unlocked. - * @property {Phaser.Signal} onTouchUnlock - */ + * This signal is dispatched when the Video is unlocked. + * @property {Phaser.Signal} onTouchUnlock + */ this.onTouchUnlock = new Phaser.Signal(); /** - * Start playing the video when it's unlocked. - * @property {boolean} playWhenUnlocked - * @default - */ + * Start playing the video when it's unlocked. + * @property {boolean} playWhenUnlocked + * @default + */ this.playWhenUnlocked = true; /** - * @property {integer} timeout - The amount of ms allowed to elapsed before the Video.onTimeout signal is dispatched while waiting for webcam access. - * @default - */ + * @property {integer} timeout - The amount of ms allowed to elapsed before the Video.onTimeout signal is dispatched while waiting for webcam access. + * @default + */ this.timeout = 15000; /** - * @property {integer} _timeOutID - setTimeout ID. - * @private - */ + * @property {integer} _timeOutID - setTimeout ID. + * @private + */ this._timeOutID = null; /** - * @property {HTMLVideoElement} video - The HTML Video Element that is added to the document. - */ + * @property {HTMLVideoElement} video - The HTML Video Element that is added to the document. + */ this.video = null; /** - * @property {MediaStream} videoStream - The Video Stream data. Only set if this Video is streaming from the webcam via `startMediaStream`. - */ + * @property {MediaStream} videoStream - The Video Stream data. Only set if this Video is streaming from the webcam via `startMediaStream`. + */ this.videoStream = null; /** - * @property {boolean} isStreaming - Is there a streaming video source? I.e. from a webcam. - */ + * @property {boolean} isStreaming - Is there a streaming video source? I.e. from a webcam. + */ this.isStreaming = false; /** - * When starting playback of a video Phaser will monitor its readyState using a setTimeout call. - * The setTimeout happens once every `Video.retryInterval` ms. It will carry on monitoring the video - * state in this manner until the `retryLimit` is reached and then abort. - * @property {integer} retryLimit - * @default - */ + * When starting playback of a video Phaser will monitor its readyState using a setTimeout call. + * The setTimeout happens once every `Video.retryInterval` ms. It will carry on monitoring the video + * state in this manner until the `retryLimit` is reached and then abort. + * @property {integer} retryLimit + * @default + */ this.retryLimit = 20; /** - * @property {integer} retry - The current retry attempt. - * @default - */ + * @property {integer} retry - The current retry attempt. + * @default + */ this.retry = 0; /** - * @property {integer} retryInterval - The number of ms between each retry at monitoring the status of a downloading video. - * @default - */ + * @property {integer} retryInterval - The number of ms between each retry at monitoring the status of a downloading video. + * @default + */ this.retryInterval = 500; /** - * @property {integer} _retryID - The callback ID of the retry setTimeout. - * @private - */ + * @property {integer} _retryID - The callback ID of the retry setTimeout. + * @private + */ this._retryID = null; /** - * @property {boolean} _codeMuted - Internal mute tracking var. - * @private - * @default - */ + * @property {boolean} _codeMuted - Internal mute tracking var. + * @private + * @default + */ this._codeMuted = false; /** - * @property {boolean} _muted - Internal mute tracking var. - * @private - * @default - */ + * @property {boolean} _muted - Internal mute tracking var. + * @private + * @default + */ this._muted = false; /** - * @property {boolean} _codePaused - Internal paused tracking var. - * @private - * @default - */ + * @property {boolean} _codePaused - Internal paused tracking var. + * @private + * @default + */ this._codePaused = false; /** - * @property {boolean} _paused - Internal paused tracking var. - * @private - * @default - */ + * @property {boolean} _paused - Internal paused tracking var. + * @private + * @default + */ this._paused = false; /** - * @property {boolean} _pending - Internal var tracking play pending. - * @private - * @default - */ + * @property {boolean} _pending - Internal var tracking play pending. + * @private + * @default + */ this._pending = false; /** - * @property {boolean} _pendingChangeSource - Internal var tracking play pending. - * @private - * @default - */ + * @property {boolean} _pendingChangeSource - Internal var tracking play pending. + * @private + * @default + */ this._pendingChangeSource = false; /** - * @property {boolean} _autoplay - Internal var tracking autoplay when changing source. - * @private - * @default - */ + * @property {boolean} _autoplay - Internal var tracking autoplay when changing source. + * @private + * @default + */ this._autoplay = false; /** - * @property {function} _endCallback - The addEventListener ended function. - * @private - */ + * @property {function} _endCallback - The addEventListener ended function. + * @private + */ this._endCallback = null; /** - * @property {function} _playCallback - The addEventListener playing function. - * @private - */ + * @property {function} _playCallback - The addEventListener playing function. + * @private + */ this._playCallback = null; if (key && this.game.cache.checkVideoKey(key)) @@ -263,9 +262,9 @@ Phaser.Video = function (game, key, url) } /** - * @property {PIXI.BaseTexture} baseTexture - The PIXI.BaseTexture. - * @default - */ + * @property {PIXI.BaseTexture} baseTexture - The PIXI.BaseTexture. + * @default + */ if (this.video && !url) { this.baseTexture = new PIXI.BaseTexture(this.video, null, this.game.resolution); @@ -278,15 +277,15 @@ Phaser.Video = function (game, key, url) } /** - * @property {PIXI.Texture} texture - The PIXI.Texture. - * @default - */ + * @property {PIXI.Texture} texture - The PIXI.Texture. + * @default + */ this.texture = new PIXI.Texture(this.baseTexture); /** - * @property {Phaser.Frame} textureFrame - The Frame this video uses for rendering. - * @default - */ + * @property {Phaser.Frame} textureFrame - The Frame this video uses for rendering. + * @default + */ this.textureFrame = new Phaser.Frame(0, 0, 0, this.width, this.height, 'video'); this.texture.setFrame(this.textureFrame); @@ -299,13 +298,13 @@ Phaser.Video = function (game, key, url) } /** - * A snapshot grabbed from the video. This is initially black. Populate it by calling Video.grab(). - * When called the BitmapData is updated with a grab taken from the current video playing or active video stream. - * If Phaser has been compiled without BitmapData support this property will always be `null`. - * - * @property {Phaser.BitmapData} snapshot - * @readOnly - */ + * A snapshot grabbed from the video. This is initially black. Populate it by calling Video.grab(). + * When called the BitmapData is updated with a grab taken from the current video playing or active video stream. + * If Phaser has been compiled without BitmapData support this property will always be `null`. + * + * @property {Phaser.BitmapData} snapshot + * @readOnly + */ this.snapshot = null; if (Phaser.BitmapData) @@ -322,7 +321,6 @@ Phaser.Video = function (game, key, url) { _video.locked = false; } - }; Phaser.Video.prototype = { @@ -337,7 +335,6 @@ Phaser.Video.prototype = { */ connectToMediaStream: function (video, stream) { - if (video && stream) { this.video = video; @@ -351,7 +348,6 @@ Phaser.Video.prototype = { } return this; - }, /** @@ -375,7 +371,6 @@ Phaser.Video.prototype = { */ startMediaStream: function (captureAudio, width, height) { - if (captureAudio === undefined) { captureAudio = false; } if (width === undefined) { width = null; } if (height === undefined) { height = null; } @@ -432,7 +427,6 @@ Phaser.Video.prototype = { } return this; - }, /** @@ -441,11 +435,9 @@ Phaser.Video.prototype = { */ getUserMediaTimeout: function () { - clearTimeout(this._timeOutID); this.onTimeout.dispatch(this); - }, /** @@ -454,11 +446,9 @@ Phaser.Video.prototype = { */ getUserMediaError: function (event) { - clearTimeout(this._timeOutID); this.onError.dispatch(this, event); - }, /** @@ -467,7 +457,6 @@ Phaser.Video.prototype = { */ getUserMediaSuccess: function (stream) { - clearTimeout(this._timeOutID); // Attach the stream to the video @@ -491,12 +480,10 @@ Phaser.Video.prototype = { this.video.onloadeddata = function () { - var retry = 10; function checkStream () { - if (retry > 0) { if (self.video.videoWidth > 0) @@ -531,9 +518,7 @@ Phaser.Video.prototype = { } checkStream(); - }; - }, /** @@ -546,7 +531,6 @@ Phaser.Video.prototype = { */ createVideoFromBlob: function (blob) { - var _this = this; this.video = document.createElement('video'); @@ -558,7 +542,6 @@ Phaser.Video.prototype = { this.video.canplay = true; return this; - }, /** @@ -571,7 +554,6 @@ Phaser.Video.prototype = { */ createVideoFromURL: function (url, autoplay) { - if (autoplay === undefined) { autoplay = false; } // Invalidate the texture while we wait for the new one to load (crashes IE11 otherwise) @@ -603,7 +585,6 @@ Phaser.Video.prototype = { this.key = url; return this; - }, /** @@ -617,7 +598,6 @@ Phaser.Video.prototype = { */ updateTexture: function (event, width, height) { - var change = false; if (width === undefined || width === null) { width = this.video.videoWidth; change = true; } @@ -655,7 +635,6 @@ Phaser.Video.prototype = { this.onPlay.dispatch(this, this.loop, this.playbackRate); } } - }, /** @@ -666,9 +645,7 @@ Phaser.Video.prototype = { */ complete: function () { - this.onComplete.dispatch(this); - }, /** @@ -683,7 +660,6 @@ Phaser.Video.prototype = { */ play: function (loop, playbackRate) { - if (this._pendingChangeSource) { return this; @@ -750,7 +726,6 @@ Phaser.Video.prototype = { } return this; - }, /** @@ -761,11 +736,9 @@ Phaser.Video.prototype = { */ playHandler: function () { - this.video.removeEventListener('playing', this._playCallback, true); this.updateTexture(); - }, /** @@ -784,7 +757,6 @@ Phaser.Video.prototype = { */ stop: function () { - if (this.game.sound.onMute) { this.game.sound.onMute.remove(this.setMute, this); @@ -850,20 +822,18 @@ Phaser.Video.prototype = { } return this; - }, /** - * Updates the given Display Objects so they use this Video as their texture. - * This will replace any texture they will currently have set. - * - * @method Phaser.Video#add - * @param {Phaser.Sprite|Phaser.Sprite[]|Phaser.Image|Phaser.Image[]} object - Either a single Sprite/Image or an Array of Sprites/Images. - * @return {Phaser.Video} This Video object for method chaining. - */ + * Updates the given Display Objects so they use this Video as their texture. + * This will replace any texture they will currently have set. + * + * @method Phaser.Video#add + * @param {Phaser.Sprite|Phaser.Sprite[]|Phaser.Image|Phaser.Image[]} object - Either a single Sprite/Image or an Array of Sprites/Images. + * @return {Phaser.Video} This Video object for method chaining. + */ add: function (object) { - if (Array.isArray(object)) { for (var i = 0; i < object.length; i++) @@ -880,24 +850,22 @@ Phaser.Video.prototype = { } return this; - }, /** - * Creates a new Phaser.Image object, assigns this Video to be its texture, adds it to the world then returns it. - * - * @method Phaser.Video#addToWorld - * @param {number} [x=0] - The x coordinate to place the Image at. - * @param {number} [y=0] - The y coordinate to place the Image at. - * @param {number} [anchorX=0] - Set the x anchor point of the Image. A value between 0 and 1, where 0 is the top-left and 1 is bottom-right. - * @param {number} [anchorY=0] - Set the y anchor point of the Image. A value between 0 and 1, where 0 is the top-left and 1 is bottom-right. - * @param {number} [scaleX=1] - The horizontal scale factor of the Image. A value of 1 means no scaling. 2 would be twice the size, and so on. - * @param {number} [scaleY=1] - The vertical scale factor of the Image. A value of 1 means no scaling. 2 would be twice the size, and so on. - * @return {Phaser.Image} The newly added Image object. - */ + * Creates a new Phaser.Image object, assigns this Video to be its texture, adds it to the world then returns it. + * + * @method Phaser.Video#addToWorld + * @param {number} [x=0] - The x coordinate to place the Image at. + * @param {number} [y=0] - The y coordinate to place the Image at. + * @param {number} [anchorX=0] - Set the x anchor point of the Image. A value between 0 and 1, where 0 is the top-left and 1 is bottom-right. + * @param {number} [anchorY=0] - Set the y anchor point of the Image. A value between 0 and 1, where 0 is the top-left and 1 is bottom-right. + * @param {number} [scaleX=1] - The horizontal scale factor of the Image. A value of 1 means no scaling. 2 would be twice the size, and so on. + * @param {number} [scaleY=1] - The vertical scale factor of the Image. A value of 1 means no scaling. 2 would be twice the size, and so on. + * @return {Phaser.Image} The newly added Image object. + */ addToWorld: function (x, y, anchorX, anchorY, scaleX, scaleY) { - scaleX = scaleX || 1; scaleY = scaleY || 1; @@ -907,35 +875,31 @@ Phaser.Video.prototype = { image.scale.set(scaleX, scaleY); return image; - }, /** - * If the game is running in WebGL this will push the texture up to the GPU if it's dirty. - * This is called automatically if the Video is being used by a Sprite, otherwise you need to remember to call it in your render function. - * If you wish to suppress this functionality set Video.disableTextureUpload to `true`. - * - * @method Phaser.Video#render - */ + * If the game is running in WebGL this will push the texture up to the GPU if it's dirty. + * This is called automatically if the Video is being used by a Sprite, otherwise you need to remember to call it in your render function. + * If you wish to suppress this functionality set Video.disableTextureUpload to `true`. + * + * @method Phaser.Video#render + */ render: function () { - if (!this.disableTextureUpload && this.playing) { this.baseTexture.dirty(); } - }, /** - * Internal handler called automatically by the Video.mute setter. - * - * @method Phaser.Video#setMute - * @private - */ + * Internal handler called automatically by the Video.mute setter. + * + * @method Phaser.Video#setMute + * @private + */ setMute: function () { - if (this._muted) { return; @@ -944,18 +908,16 @@ Phaser.Video.prototype = { this._muted = true; this.video.muted = true; - }, /** - * Internal handler called automatically by the Video.mute setter. - * - * @method Phaser.Video#unsetMute - * @private - */ + * Internal handler called automatically by the Video.mute setter. + * + * @method Phaser.Video#unsetMute + * @private + */ unsetMute: function () { - if (!this._muted || this._codeMuted) { return; @@ -964,18 +926,16 @@ Phaser.Video.prototype = { this._muted = false; this.video.muted = false; - }, /** - * Internal handler called automatically by the Video.paused setter. - * - * @method Phaser.Video#setPause - * @private - */ + * Internal handler called automatically by the Video.paused setter. + * + * @method Phaser.Video#setPause + * @private + */ setPause: function () { - if (this._paused || this.touchLocked) { return; @@ -984,18 +944,16 @@ Phaser.Video.prototype = { this._paused = true; this.video.pause(); - }, /** - * Internal handler called automatically by the Video.paused setter. - * - * @method Phaser.Video#setResume - * @private - */ + * Internal handler called automatically by the Video.paused setter. + * + * @method Phaser.Video#setResume + * @private + */ setResume: function () { - if (!this._paused || this._codePaused || this.touchLocked) { return; @@ -1007,7 +965,6 @@ Phaser.Video.prototype = { { this.video.play(); } - }, /** @@ -1033,7 +990,6 @@ Phaser.Video.prototype = { */ changeSource: function (src, autoplay) { - if (autoplay === undefined) { autoplay = true; } // Invalidate the texture while we wait for the new one to load (crashes IE11 otherwise) @@ -1059,18 +1015,16 @@ Phaser.Video.prototype = { } return this; - }, /** - * Internal callback that monitors the download progress of a video after changing its source. - * - * @method Phaser.Video#checkVideoProgress - * @private - */ + * Internal callback that monitors the download progress of a video after changing its source. + * + * @method Phaser.Video#checkVideoProgress + * @private + */ checkVideoProgress: function () { - // if (this.video.readyState === 2 || this.video.readyState === 4) if (this.video.readyState === 4) { @@ -1092,33 +1046,29 @@ Phaser.Video.prototype = { console.warn('Phaser.Video: Unable to start downloading video in time', this.isStreaming); } } - }, /** - * Sets the Input Manager touch callback to be Video.unlock. - * Required for mobile video unlocking. Mostly just used internally. - * - * @method Phaser.Video#setTouchLock - */ + * Sets the Input Manager touch callback to be Video.unlock. + * Required for mobile video unlocking. Mostly just used internally. + * + * @method Phaser.Video#setTouchLock + */ setTouchLock: function () { - this.game.input.addTouchLockCallback(this.unlock, this, true); this.touchLocked = true; - }, /** - * Enables the video on mobile devices, usually after the first touch. - * If the SoundManager hasn't been unlocked then this will automatically unlock that as well. - * Only one video can be pending unlock at any one time. - * - * @method Phaser.Video#unlock - */ + * Enables the video on mobile devices, usually after the first touch. + * If the SoundManager hasn't been unlocked then this will automatically unlock that as well. + * Only one video can be pending unlock at any one time. + * + * @method Phaser.Video#unlock + */ unlock: function () { - this.touchLocked = false; if (this.playWhenUnlocked) @@ -1141,7 +1091,6 @@ Phaser.Video.prototype = { this.onTouchUnlock.dispatch(this); return true; - }, /** @@ -1159,7 +1108,6 @@ Phaser.Video.prototype = { */ grab: function (clear, alpha, blendMode) { - if (clear === undefined) { clear = false; } if (alpha === undefined) { alpha = 1; } if (blendMode === undefined) { blendMode = null; } @@ -1178,7 +1126,6 @@ Phaser.Video.prototype = { this.snapshot.copy(this.video, 0, 0, this.width, this.height, 0, 0, this.width, this.height, 0, 0, 0, 1, 1, alpha, blendMode); return this.snapshot; - }, /** @@ -1189,7 +1136,6 @@ Phaser.Video.prototype = { */ removeVideoElement: function () { - if (!this.video) { return; @@ -1209,7 +1155,6 @@ Phaser.Video.prototype = { this.video.removeAttribute('src'); this.video = null; - }, /** @@ -1220,7 +1165,6 @@ Phaser.Video.prototype = { */ destroy: function () { - this.stop(); this.removeVideoElement(); @@ -1234,81 +1178,69 @@ Phaser.Video.prototype = { { window.clearTimeout(this._retryID); } - } }; /** -* @name Phaser.Video#currentTime -* @property {number} currentTime - The current time of the video in seconds. If set the video will attempt to seek to that point in time. -*/ + * @name Phaser.Video#currentTime + * @property {number} currentTime - The current time of the video in seconds. If set the video will attempt to seek to that point in time. + */ Object.defineProperty(Phaser.Video.prototype, 'currentTime', { get: function () { - return (this.video) ? this.video.currentTime : 0; - }, set: function (value) { - this.video.currentTime = value; - } }); /** -* @name Phaser.Video#duration -* @property {number} duration - The duration of the video in seconds. -* @readOnly -*/ + * @name Phaser.Video#duration + * @property {number} duration - The duration of the video in seconds. + * @readOnly + */ Object.defineProperty(Phaser.Video.prototype, 'duration', { get: function () { - return (this.video) ? this.video.duration : 0; - } }); /** -* @name Phaser.Video#progress -* @property {number} progress - The progress of this video. This is a value between 0 and 1, where 0 is the start and 1 is the end of the video. -* @readOnly -*/ + * @name Phaser.Video#progress + * @property {number} progress - The progress of this video. This is a value between 0 and 1, where 0 is the start and 1 is the end of the video. + * @readOnly + */ Object.defineProperty(Phaser.Video.prototype, 'progress', { get: function () { - return (this.video) ? (this.video.currentTime / this.video.duration) : 0; - } }); /** -* @name Phaser.Video#mute -* @property {boolean} mute - Gets or sets the muted state of the Video. -*/ + * @name Phaser.Video#mute + * @property {boolean} mute - Gets or sets the muted state of the Video. + */ Object.defineProperty(Phaser.Video.prototype, 'mute', { get: function () { - return this._muted; - }, set: function (value) { - value = value || null; if (value) @@ -1336,24 +1268,21 @@ Object.defineProperty(Phaser.Video.prototype, 'mute', { }); /** -* Gets or sets the paused state of the Video. -* If the video is still touch locked (such as on iOS devices) this call has no effect. -* -* @name Phaser.Video#paused -* @property {boolean} paused -*/ + * Gets or sets the paused state of the Video. + * If the video is still touch locked (such as on iOS devices) this call has no effect. + * + * @name Phaser.Video#paused + * @property {boolean} paused + */ Object.defineProperty(Phaser.Video.prototype, 'paused', { get: function () { - return this._paused; - }, set: function (value) { - value = value || null; if (this.touchLocked) @@ -1386,21 +1315,18 @@ Object.defineProperty(Phaser.Video.prototype, 'paused', { }); /** -* @name Phaser.Video#volume -* @property {number} volume - Gets or sets the volume of the Video, a value between 0 and 1. The value given is clamped to the range 0 to 1. -*/ + * @name Phaser.Video#volume + * @property {number} volume - Gets or sets the volume of the Video, a value between 0 and 1. The value given is clamped to the range 0 to 1. + */ Object.defineProperty(Phaser.Video.prototype, 'volume', { get: function () { - return (this.video) ? this.video.volume : 1; - }, set: function (value) { - if (value < 0) { value = 0; @@ -1414,56 +1340,48 @@ Object.defineProperty(Phaser.Video.prototype, 'volume', { { this.video.volume = value; } - } }); /** -* @name Phaser.Video#playbackRate -* @property {number} playbackRate - Gets or sets the playback rate of the Video. This is the speed at which the video is playing. -*/ + * @name Phaser.Video#playbackRate + * @property {number} playbackRate - Gets or sets the playback rate of the Video. This is the speed at which the video is playing. + */ Object.defineProperty(Phaser.Video.prototype, 'playbackRate', { get: function () { - return (this.video) ? this.video.playbackRate : 1; - }, set: function (value) { - if (this.video) { this.video.playbackRate = value; } - } }); /** -* Gets or sets if the Video is set to loop. -* Please note that at present some browsers (i.e. Chrome) do not support *seamless* video looping. -* If the video isn't yet set this will always return false. -* -* @name Phaser.Video#loop -* @property {boolean} loop -*/ + * Gets or sets if the Video is set to loop. + * Please note that at present some browsers (i.e. Chrome) do not support *seamless* video looping. + * If the video isn't yet set this will always return false. + * + * @name Phaser.Video#loop + * @property {boolean} loop + */ Object.defineProperty(Phaser.Video.prototype, 'loop', { get: function () { - return (this.video) ? this.video.loop : false; - }, set: function (value) { - if (value && this.video) { this.video.loop = 'loop'; @@ -1472,23 +1390,20 @@ Object.defineProperty(Phaser.Video.prototype, 'loop', { { this.video.loop = ''; } - } }); /** -* @name Phaser.Video#playing -* @property {boolean} playing - True if the video is currently playing (and not paused or ended), otherwise false. -* @readOnly -*/ + * @name Phaser.Video#playing + * @property {boolean} playing - True if the video is currently playing (and not paused or ended), otherwise false. + * @readOnly + */ Object.defineProperty(Phaser.Video.prototype, 'playing', { get: function () { - return (this.video) ? !(this.video.paused && this.video.ended) : false; - } }); diff --git a/src/gameobjects/components/Angle.js b/src/gameobjects/components/Angle.js index d24146bdd..8a4d2644f 100644 --- a/src/gameobjects/components/Angle.js +++ b/src/gameobjects/components/Angle.js @@ -1,45 +1,41 @@ /** -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* The Angle Component provides access to an `angle` property; the rotation of a Game Object in degrees. -* -* @class -*/ + * The Angle Component provides access to an `angle` property; the rotation of a Game Object in degrees. + * + * @class + */ Phaser.Component.Angle = function () {}; Phaser.Component.Angle.prototype = { /** - * The angle property is the rotation of the Game Object in *degrees* from its original orientation. - * - * Values from 0 to 180 represent clockwise rotation; values from 0 to -180 represent counterclockwise rotation. - * - * Values outside this range are added to or subtracted from 360 to obtain a value within the range. - * For example, the statement player.angle = 450 is the same as player.angle = 90. - * - * If you wish to work in radians instead of degrees you can use the property `rotation` instead. - * Working in radians is slightly faster as it doesn't have to perform any calculations. - * - * @property {number} angle - */ + * The angle property is the rotation of the Game Object in *degrees* from its original orientation. + * + * Values from 0 to 180 represent clockwise rotation; values from 0 to -180 represent counterclockwise rotation. + * + * Values outside this range are added to or subtracted from 360 to obtain a value within the range. + * For example, the statement player.angle = 450 is the same as player.angle = 90. + * + * If you wish to work in radians instead of degrees you can use the property `rotation` instead. + * Working in radians is slightly faster as it doesn't have to perform any calculations. + * + * @property {number} angle + */ angle: { get: function () { - return Phaser.Math.wrapAngle(Phaser.Math.radToDeg(this.rotation)); - }, set: function (value) { - this.rotation = Phaser.Math.degToRad(Phaser.Math.wrapAngle(value)); - } } diff --git a/src/gameobjects/components/Animation.js b/src/gameobjects/components/Animation.js index 3a5a77b57..4b69f41fc 100644 --- a/src/gameobjects/components/Animation.js +++ b/src/gameobjects/components/Animation.js @@ -1,41 +1,39 @@ /** -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* The Animation Component provides a `play` method, which is a proxy to the `AnimationManager.play` method. -* -* @class -*/ + * The Animation Component provides a `play` method, which is a proxy to the `AnimationManager.play` method. + * + * @class + */ Phaser.Component.Animation = function () {}; Phaser.Component.Animation.prototype = { /** - * Plays an Animation. - * - * The animation should have previously been created via `animations.add`. - * - * If the animation is already playing calling this again won't do anything. - * If you need to reset an already running animation do so directly on the Animation object itself or via `AnimationManager.stop`. - * - * @method - * @param {string} name - The name of the animation to be played, e.g. "fire", "walk", "jump". Must have been previously created via 'AnimationManager.add'. - * @param {number} [frameRate=null] - The framerate to play the animation at. The speed is given in frames per second. If not provided the previously set frameRate of the Animation is used. - * @param {boolean} [loop=false] - Should the animation be looped after playback. If not provided the previously set loop value of the Animation is used. - * @param {boolean} [killOnComplete=false] - If set to true when the animation completes (only happens if loop=false) the parent Sprite will be killed. - * @return {Phaser.Animation} A reference to playing Animation. - */ + * Plays an Animation. + * + * The animation should have previously been created via `animations.add`. + * + * If the animation is already playing calling this again won't do anything. + * If you need to reset an already running animation do so directly on the Animation object itself or via `AnimationManager.stop`. + * + * @method + * @param {string} name - The name of the animation to be played, e.g. "fire", "walk", "jump". Must have been previously created via 'AnimationManager.add'. + * @param {number} [frameRate=null] - The framerate to play the animation at. The speed is given in frames per second. If not provided the previously set frameRate of the Animation is used. + * @param {boolean} [loop=false] - Should the animation be looped after playback. If not provided the previously set loop value of the Animation is used. + * @param {boolean} [killOnComplete=false] - If set to true when the animation completes (only happens if loop=false) the parent Sprite will be killed. + * @return {Phaser.Animation} A reference to playing Animation. + */ play: function (name, frameRate, loop, killOnComplete) { - if (this.animations) { return this.animations.play(name, frameRate, loop, killOnComplete); } - } }; diff --git a/src/gameobjects/components/AutoCull.js b/src/gameobjects/components/AutoCull.js index 0c3e076ac..5a1f80b80 100644 --- a/src/gameobjects/components/AutoCull.js +++ b/src/gameobjects/components/AutoCull.js @@ -1,44 +1,43 @@ /** -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* The AutoCull Component is responsible for providing methods that check if a Game Object is within the bounds of the World Camera. -* It is used by the InWorld component. -* -* @class -*/ + * The AutoCull Component is responsible for providing methods that check if a Game Object is within the bounds of the World Camera. + * It is used by the InWorld component. + * + * @class + */ Phaser.Component.AutoCull = function () {}; Phaser.Component.AutoCull.prototype = { /** - * A Game Object with `autoCull` set to true will check its bounds against the World Camera every frame. - * If it is not intersecting the Camera bounds at any point then it has its `renderable` property set to `false`. - * This keeps the Game Object alive and still processing updates, but forces it to skip the render step entirely. - * - * This is a relatively expensive operation, especially if enabled on hundreds of Game Objects. So enable it only if you know it's required, - * or you have tested performance and find it acceptable. - * - * @property {boolean} autoCull - * @default - */ + * A Game Object with `autoCull` set to true will check its bounds against the World Camera every frame. + * If it is not intersecting the Camera bounds at any point then it has its `renderable` property set to `false`. + * This keeps the Game Object alive and still processing updates, but forces it to skip the render step entirely. + * + * This is a relatively expensive operation, especially if enabled on hundreds of Game Objects. So enable it only if you know it's required, + * or you have tested performance and find it acceptable. + * + * @property {boolean} autoCull + * @default + */ autoCull: false, /** - * Checks if the Game Objects bounds intersect with the Game Camera bounds. - * Returns `true` if they do, otherwise `false` if fully outside of the Cameras bounds. - * - * @property {boolean} inCamera - * @readonly - */ + * Checks if the Game Objects bounds intersect with the Game Camera bounds. + * Returns `true` if they do, otherwise `false` if fully outside of the Cameras bounds. + * + * @property {boolean} inCamera + * @readonly + */ inCamera: { get: function () { - if (!this.autoCull && !this.checkWorldBounds) { this._bounds.copyFrom(this.getBounds()); @@ -47,7 +46,6 @@ Phaser.Component.AutoCull.prototype = { } return this.game.world.camera.view.intersects(this._bounds); - } } diff --git a/src/gameobjects/components/Bounds.js b/src/gameobjects/components/Bounds.js index a7f39a7ae..5a8277bbc 100644 --- a/src/gameobjects/components/Bounds.js +++ b/src/gameobjects/components/Bounds.js @@ -1,242 +1,213 @@ /** -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* The Bounds component contains properties related to the bounds of the Game Object. -* -* @class -*/ + * The Bounds component contains properties related to the bounds of the Game Object. + * + * @class + */ Phaser.Component.Bounds = function () {}; Phaser.Component.Bounds.prototype = { /** - * The amount the Game Object is visually offset from its x coordinate. - * This is the same as `width * anchor.x`. - * It will only be > 0 if anchor.x is not equal to zero. - * - * @property {number} offsetX - * @readOnly - */ + * The amount the Game Object is visually offset from its x coordinate. + * This is the same as `width * anchor.x`. + * It will only be > 0 if anchor.x is not equal to zero. + * + * @property {number} offsetX + * @readOnly + */ offsetX: { get: function () { - return this.anchor.x * this.width; - } }, /** - * The amount the Game Object is visually offset from its y coordinate. - * This is the same as `height * anchor.y`. - * It will only be > 0 if anchor.y is not equal to zero. - * - * @property {number} offsetY - * @readOnly - */ + * The amount the Game Object is visually offset from its y coordinate. + * This is the same as `height * anchor.y`. + * It will only be > 0 if anchor.y is not equal to zero. + * + * @property {number} offsetY + * @readOnly + */ offsetY: { get: function () { - return this.anchor.y * this.height; - } }, /** - * The local center x coordinate of the Game Object. - * This is the same as `(x - offsetX) + (width / 2)`. - * - * @property {number} centerX - */ + * The local center x coordinate of the Game Object. + * This is the same as `(x - offsetX) + (width / 2)`. + * + * @property {number} centerX + */ centerX: { get: function () { - return (this.x - this.offsetX) + (this.width * 0.5); - }, set: function (value) { - this.x = (value + this.offsetX) - (this.width * 0.5); - } }, /** - * The local center y coordinate of the Game Object. - * This is the same as `(y - offsetY) + (height / 2)`. - * - * @property {number} centerY - */ + * The local center y coordinate of the Game Object. + * This is the same as `(y - offsetY) + (height / 2)`. + * + * @property {number} centerY + */ centerY: { get: function () { - return (this.y - this.offsetY) + (this.height * 0.5); - }, set: function (value) { - this.y = (value + this.offsetY) - (this.height * 0.5); - } }, /** - * The left coordinate of the Game Object. - * This is the same as `x - offsetX`. - * - * @property {number} left - */ + * The left coordinate of the Game Object. + * This is the same as `x - offsetX`. + * + * @property {number} left + */ left: { get: function () { - return this.x - this.offsetX; - }, set: function (value) { - this.x = value + this.offsetX; - } }, /** - * The right coordinate of the Game Object. - * This is the same as `x + width - offsetX`. - * - * @property {number} right - */ + * The right coordinate of the Game Object. + * This is the same as `x + width - offsetX`. + * + * @property {number} right + */ right: { get: function () { - return (this.x + this.width) - this.offsetX; - }, set: function (value) { - this.x = value - (this.width) + this.offsetX; - } }, /** - * The y coordinate of the Game Object. - * This is the same as `y - offsetY`. - * - * @property {number} top - */ + * The y coordinate of the Game Object. + * This is the same as `y - offsetY`. + * + * @property {number} top + */ top: { get: function () { - return this.y - this.offsetY; - }, set: function (value) { - this.y = value + this.offsetY; - } }, /** - * The sum of the y and height properties. - * This is the same as `y + height - offsetY`. - * - * @property {number} bottom - */ + * The sum of the y and height properties. + * This is the same as `y + height - offsetY`. + * + * @property {number} bottom + */ bottom: { get: function () { - return (this.y + this.height) - this.offsetY; - }, set: function (value) { - this.y = value - (this.height) + this.offsetY; - } }, /** - * Aligns this Game Object within another Game Object, or Rectangle, known as the - * 'container', to one of 9 possible positions. - * - * The container must be a Game Object, or Phaser.Rectangle object. This can include properties - * such as `World.bounds` or `Camera.view`, for aligning Game Objects within the world - * and camera bounds. Or it can include other Sprites, Images, Text objects, BitmapText, - * TileSprites or Buttons. - * - * Please note that aligning a Sprite to another Game Object does **not** make it a child of - * the container. It simply modifies its position coordinates so it aligns with it. - * - * The position constants you can use are: - * - * `Phaser.TOP_LEFT`, `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, - * `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`, - * `Phaser.BOTTOM_CENTER` and `Phaser.BOTTOM_RIGHT`. - * - * The Game Objects are placed in such a way that their _bounds_ align with the - * container, taking into consideration rotation, scale and the anchor property. - * This allows you to neatly align Game Objects, irrespective of their position value. - * - * The optional `offsetX` and `offsetY` arguments allow you to apply extra spacing to the final - * aligned position of the Game Object. For example: - * - * `sprite.alignIn(background, Phaser.BOTTOM_RIGHT, -20, -20)` - * - * Would align the `sprite` to the bottom-right, but moved 20 pixels in from the corner. - * Think of the offsets as applying an adjustment to the containers bounds before the alignment takes place. - * So providing a negative offset will 'shrink' the container bounds by that amount, and providing a positive - * one expands it. - * - * @method - * @param {Phaser.Rectangle|Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapText|Phaser.Button|Phaser.Graphics|Phaser.TileSprite} container - The Game Object or Rectangle with which to align this Game Object to. Can also include properties such as `World.bounds` or `Camera.view`. - * @param {integer} [position] - The position constant. One of `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`. - * @param {integer} [offsetX=0] - A horizontal adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. - * @param {integer} [offsetY=0] - A vertical adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. - * @return {Object} This Game Object. - */ + * Aligns this Game Object within another Game Object, or Rectangle, known as the + * 'container', to one of 9 possible positions. + * + * The container must be a Game Object, or Phaser.Rectangle object. This can include properties + * such as `World.bounds` or `Camera.view`, for aligning Game Objects within the world + * and camera bounds. Or it can include other Sprites, Images, Text objects, BitmapText, + * TileSprites or Buttons. + * + * Please note that aligning a Sprite to another Game Object does **not** make it a child of + * the container. It simply modifies its position coordinates so it aligns with it. + * + * The position constants you can use are: + * + * `Phaser.TOP_LEFT`, `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, + * `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`, + * `Phaser.BOTTOM_CENTER` and `Phaser.BOTTOM_RIGHT`. + * + * The Game Objects are placed in such a way that their _bounds_ align with the + * container, taking into consideration rotation, scale and the anchor property. + * This allows you to neatly align Game Objects, irrespective of their position value. + * + * The optional `offsetX` and `offsetY` arguments allow you to apply extra spacing to the final + * aligned position of the Game Object. For example: + * + * `sprite.alignIn(background, Phaser.BOTTOM_RIGHT, -20, -20)` + * + * Would align the `sprite` to the bottom-right, but moved 20 pixels in from the corner. + * Think of the offsets as applying an adjustment to the containers bounds before the alignment takes place. + * So providing a negative offset will 'shrink' the container bounds by that amount, and providing a positive + * one expands it. + * + * @method + * @param {Phaser.Rectangle|Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapText|Phaser.Button|Phaser.Graphics|Phaser.TileSprite} container - The Game Object or Rectangle with which to align this Game Object to. Can also include properties such as `World.bounds` or `Camera.view`. + * @param {integer} [position] - The position constant. One of `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`. + * @param {integer} [offsetX=0] - A horizontal adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. + * @param {integer} [offsetY=0] - A vertical adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. + * @return {Object} This Game Object. + */ alignIn: function (container, position, offsetX, offsetY) { - if (offsetX === undefined) { offsetX = 0; } if (offsetY === undefined) { offsetY = 0; } @@ -290,52 +261,50 @@ Phaser.Component.Bounds.prototype = { } return this; - }, /** - * Aligns this Game Object to the side of another Game Object, or Rectangle, known as the - * 'parent', in one of 11 possible positions. - * - * The parent must be a Game Object, or Phaser.Rectangle object. This can include properties - * such as `World.bounds` or `Camera.view`, for aligning Game Objects within the world - * and camera bounds. Or it can include other Sprites, Images, Text objects, BitmapText, - * TileSprites or Buttons. - * - * Please note that aligning a Sprite to another Game Object does **not** make it a child of - * the parent. It simply modifies its position coordinates so it aligns with it. - * - * The position constants you can use are: - * - * `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_TOP`, - * `Phaser.LEFT_CENTER`, `Phaser.LEFT_BOTTOM`, `Phaser.RIGHT_TOP`, `Phaser.RIGHT_CENTER`, - * `Phaser.RIGHT_BOTTOM`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` - * and `Phaser.BOTTOM_RIGHT`. - * - * The Game Objects are placed in such a way that their _bounds_ align with the - * parent, taking into consideration rotation, scale and the anchor property. - * This allows you to neatly align Game Objects, irrespective of their position value. - * - * The optional `offsetX` and `offsetY` arguments allow you to apply extra spacing to the final - * aligned position of the Game Object. For example: - * - * `sprite.alignTo(background, Phaser.BOTTOM_RIGHT, -20, -20)` - * - * Would align the `sprite` to the bottom-right, but moved 20 pixels in from the corner. - * Think of the offsets as applying an adjustment to the parents bounds before the alignment takes place. - * So providing a negative offset will 'shrink' the parent bounds by that amount, and providing a positive - * one expands it. - * - * @method - * @param {Phaser.Rectangle|Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapText|Phaser.Button|Phaser.Graphics|Phaser.TileSprite} parent - The Game Object or Rectangle with which to align this Game Object to. Can also include properties such as `World.bounds` or `Camera.view`. - * @param {integer} [position] - The position constant. One of `Phaser.TOP_LEFT`, `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_TOP`, `Phaser.LEFT_CENTER`, `Phaser.LEFT_BOTTOM`, `Phaser.RIGHT_TOP`, `Phaser.RIGHT_CENTER`, `Phaser.RIGHT_BOTTOM`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`. - * @param {integer} [offsetX=0] - A horizontal adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. - * @param {integer} [offsetY=0] - A vertical adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. - * @return {Object} This Game Object. - */ + * Aligns this Game Object to the side of another Game Object, or Rectangle, known as the + * 'parent', in one of 11 possible positions. + * + * The parent must be a Game Object, or Phaser.Rectangle object. This can include properties + * such as `World.bounds` or `Camera.view`, for aligning Game Objects within the world + * and camera bounds. Or it can include other Sprites, Images, Text objects, BitmapText, + * TileSprites or Buttons. + * + * Please note that aligning a Sprite to another Game Object does **not** make it a child of + * the parent. It simply modifies its position coordinates so it aligns with it. + * + * The position constants you can use are: + * + * `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_TOP`, + * `Phaser.LEFT_CENTER`, `Phaser.LEFT_BOTTOM`, `Phaser.RIGHT_TOP`, `Phaser.RIGHT_CENTER`, + * `Phaser.RIGHT_BOTTOM`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` + * and `Phaser.BOTTOM_RIGHT`. + * + * The Game Objects are placed in such a way that their _bounds_ align with the + * parent, taking into consideration rotation, scale and the anchor property. + * This allows you to neatly align Game Objects, irrespective of their position value. + * + * The optional `offsetX` and `offsetY` arguments allow you to apply extra spacing to the final + * aligned position of the Game Object. For example: + * + * `sprite.alignTo(background, Phaser.BOTTOM_RIGHT, -20, -20)` + * + * Would align the `sprite` to the bottom-right, but moved 20 pixels in from the corner. + * Think of the offsets as applying an adjustment to the parents bounds before the alignment takes place. + * So providing a negative offset will 'shrink' the parent bounds by that amount, and providing a positive + * one expands it. + * + * @method + * @param {Phaser.Rectangle|Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapText|Phaser.Button|Phaser.Graphics|Phaser.TileSprite} parent - The Game Object or Rectangle with which to align this Game Object to. Can also include properties such as `World.bounds` or `Camera.view`. + * @param {integer} [position] - The position constant. One of `Phaser.TOP_LEFT`, `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_TOP`, `Phaser.LEFT_CENTER`, `Phaser.LEFT_BOTTOM`, `Phaser.RIGHT_TOP`, `Phaser.RIGHT_CENTER`, `Phaser.RIGHT_BOTTOM`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`. + * @param {integer} [offsetX=0] - A horizontal adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. + * @param {integer} [offsetY=0] - A vertical adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. + * @return {Object} This Game Object. + */ alignTo: function (parent, position, offsetX, offsetY) { - if (offsetX === undefined) { offsetX = 0; } if (offsetY === undefined) { offsetY = 0; } @@ -404,7 +373,6 @@ Phaser.Component.Bounds.prototype = { } return this; - } }; diff --git a/src/gameobjects/components/BringToTop.js b/src/gameobjects/components/BringToTop.js index 640cf3ad4..badfd8afb 100644 --- a/src/gameobjects/components/BringToTop.js +++ b/src/gameobjects/components/BringToTop.js @@ -1,100 +1,92 @@ /** -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* The BringToTop Component features quick access to Group and DisplayObject sorting-related methods. -* -* @class -*/ + * The BringToTop Component features quick access to Group and DisplayObject sorting-related methods. + * + * @class + */ Phaser.Component.BringToTop = function () {}; /** -* Brings this Game Object to the top of its parent's display list (the last position). -* Visually this means it will render over the top of all other children of the same parent. -* -* If this Game Object hasn't been added to a custom Group then this method will bring it to the top of the Game World, -* because the World is the root Group from which all Game Objects descend. -* -* @method -* @return {PIXI.DisplayObject} This instance. -*/ + * Brings this Game Object to the top of its parent's display list (the last position). + * Visually this means it will render over the top of all other children of the same parent. + * + * If this Game Object hasn't been added to a custom Group then this method will bring it to the top of the Game World, + * because the World is the root Group from which all Game Objects descend. + * + * @method + * @return {PIXI.DisplayObject} This instance. + */ Phaser.Component.BringToTop.prototype.bringToTop = function () { - if (this.parent && this.parent.bringChildToTop) { this.parent.bringChildToTop(this); } return this; - }; /** -* Sends this Game Object to the bottom of its parent's display list (the first position). -* Visually this means it will render below all other children of the same parent. -* -* If this Game Object hasn't been added to a custom Group then this method will send it to the bottom of the Game World, -* because the World is the root Group from which all Game Objects descend. -* -* @method -* @return {PIXI.DisplayObject} This instance. -*/ + * Sends this Game Object to the bottom of its parent's display list (the first position). + * Visually this means it will render below all other children of the same parent. + * + * If this Game Object hasn't been added to a custom Group then this method will send it to the bottom of the Game World, + * because the World is the root Group from which all Game Objects descend. + * + * @method + * @return {PIXI.DisplayObject} This instance. + */ Phaser.Component.BringToTop.prototype.sendToBack = function () { - if (this.parent && this.parent.sendChildToBack) { this.parent.sendChildToBack(this); } return this; - }; /** -* Moves this Game Object up one place in its parent's display list. -* This call has no effect if the Game Object is already at the top of the display list. -* -* If this Game Object hasn't been added to a custom Group then this method will move it one object up within the Game World, -* because the World is the root Group from which all Game Objects descend. -* -* @method -* @return {PIXI.DisplayObject} This instance. -*/ + * Moves this Game Object up one place in its parent's display list. + * This call has no effect if the Game Object is already at the top of the display list. + * + * If this Game Object hasn't been added to a custom Group then this method will move it one object up within the Game World, + * because the World is the root Group from which all Game Objects descend. + * + * @method + * @return {PIXI.DisplayObject} This instance. + */ Phaser.Component.BringToTop.prototype.moveUp = function () { - if (this.parent) { this.parent.moveUp(this); } return this; - }; /** -* Moves this Game Object down one place in its parents display list. -* This call has no effect if the Game Object is already at the bottom of the display list. -* -* If this Game Object hasn't been added to a custom Group then this method will move it one object down within the Game World, -* because the World is the root Group from which all Game Objects descend. -* -* @method -* @return {PIXI.DisplayObject} This instance. -*/ + * Moves this Game Object down one place in its parents display list. + * This call has no effect if the Game Object is already at the bottom of the display list. + * + * If this Game Object hasn't been added to a custom Group then this method will move it one object down within the Game World, + * because the World is the root Group from which all Game Objects descend. + * + * @method + * @return {PIXI.DisplayObject} This instance. + */ Phaser.Component.BringToTop.prototype.moveDown = function () { - if (this.parent) { this.parent.moveDown(this); } return this; - }; diff --git a/src/gameobjects/components/Component.js b/src/gameobjects/components/Component.js index 6aef46bf0..333e6fc87 100644 --- a/src/gameobjects/components/Component.js +++ b/src/gameobjects/components/Component.js @@ -1,7 +1,7 @@ /** -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ Phaser.Component = function () {}; diff --git a/src/gameobjects/components/Core.js b/src/gameobjects/components/Core.js index 15d01b8d0..58d640321 100644 --- a/src/gameobjects/components/Core.js +++ b/src/gameobjects/components/Core.js @@ -1,27 +1,26 @@ /** -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* Core Component Features. -* -* @class -*/ + * Core Component Features. + * + * @class + */ Phaser.Component.Core = function () {}; /** -* Installs / registers mixin components. -* -* The `this` context should be that of the applicable object instance or prototype. -* -* @method -* @protected -*/ + * Installs / registers mixin components. + * + * The `this` context should be that of the applicable object instance or prototype. + * + * @method + * @protected + */ Phaser.Component.Core.install = function (components) { - // Always install 'Core' first Phaser.Utils.mixinPrototype(this, Phaser.Component.Core.prototype); @@ -41,20 +40,18 @@ Phaser.Component.Core.install = function (components) this.components[id] = true; } - }; /** -* Initializes the mixin components. -* -* The `this` context should be an instance of the component mixin target. -* -* @method -* @protected -*/ + * Initializes the mixin components. + * + * The `this` context should be an instance of the component mixin target. + * + * @method + * @protected + */ Phaser.Component.Core.init = function (game, x, y, key, frame) { - this.game = game; this.key = key; this.data = {}; @@ -87,12 +84,10 @@ Phaser.Component.Core.init = function (game, x, y, key, frame) { this.cameraOffset = new Phaser.Point(x, y); } - }; Phaser.Component.Core.preUpdate = function () { - if (this.pendingDestroy) { this.destroy(); @@ -128,169 +123,165 @@ Phaser.Component.Core.preUpdate = function () this.preUpdateChildren(); return true; - }; Phaser.Component.Core.prototype = { /** - * A reference to the currently running Game. - * @property {Phaser.Game} game - */ + * A reference to the currently running Game. + * @property {Phaser.Game} game + */ game: null, /** - * A user defined name given to this Game Object. - * This value isn't ever used internally by Phaser, it is meant as a game level property. - * @property {string} name - * @default - */ + * A user defined name given to this Game Object. + * This value isn't ever used internally by Phaser, it is meant as a game level property. + * @property {string} name + * @default + */ name: '', /** - * An empty Object that belongs to this Game Object. - * This value isn't ever used internally by Phaser, but may be used by your own code, or - * by Phaser Plugins, to store data that needs to be associated with the Game Object, - * without polluting the Game Object directly. - * @property {Object} data - * @default - */ + * An empty Object that belongs to this Game Object. + * This value isn't ever used internally by Phaser, but may be used by your own code, or + * by Phaser Plugins, to store data that needs to be associated with the Game Object, + * without polluting the Game Object directly. + * @property {Object} data + * @default + */ data: {}, /** - * The components this Game Object has installed. - * @property {object} components - * @protected - */ + * The components this Game Object has installed. + * @property {object} components + * @protected + */ components: {}, /** - * The z depth of this Game Object within its parent Group. - * No two objects in a Group can have the same z value. - * This value is adjusted automatically whenever the Group hierarchy changes. - * If you wish to re-order the layering of a Game Object then see methods like Group.moveUp or Group.bringToTop. - * @property {number} z - * @readOnly - */ + * The z depth of this Game Object within its parent Group. + * No two objects in a Group can have the same z value. + * This value is adjusted automatically whenever the Group hierarchy changes. + * If you wish to re-order the layering of a Game Object then see methods like Group.moveUp or Group.bringToTop. + * @property {number} z + * @readOnly + */ z: 0, /** - * All Phaser Game Objects have an Events class which contains all of the events that are dispatched when certain things happen to this - * Game Object, or any of its components. - * @see Phaser.Events - * @property {Phaser.Events} events - */ + * All Phaser Game Objects have an Events class which contains all of the events that are dispatched when certain things happen to this + * Game Object, or any of its components. + * @see Phaser.Events + * @property {Phaser.Events} events + */ events: undefined, /** - * If the Game Object is enabled for animation (such as a Phaser.Sprite) this is a reference to its AnimationManager instance. - * Through it you can create, play, pause and stop animations. - * @see Phaser.AnimationManager - * @property {Phaser.AnimationManager} animations - */ + * If the Game Object is enabled for animation (such as a Phaser.Sprite) this is a reference to its AnimationManager instance. + * Through it you can create, play, pause and stop animations. + * @see Phaser.AnimationManager + * @property {Phaser.AnimationManager} animations + */ animations: undefined, /** - * The key of the image or texture used by this Game Object during rendering. - * If it is a string it's the string used to retrieve the texture from the Phaser Image Cache. - * It can also be an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. - * If a Game Object is created without a key it is automatically assigned the key `__default` which is a 32x32 transparent PNG stored within the Cache. - * If a Game Object is given a key which doesn't exist in the Image Cache it is re-assigned the key `__missing` which is a 32x32 PNG of a green box with a line through it. - * @property {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} key - */ + * The key of the image or texture used by this Game Object during rendering. + * If it is a string it's the string used to retrieve the texture from the Phaser Image Cache. + * It can also be an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. + * If a Game Object is created without a key it is automatically assigned the key `__default` which is a 32x32 transparent PNG stored within the Cache. + * If a Game Object is given a key which doesn't exist in the Image Cache it is re-assigned the key `__missing` which is a 32x32 PNG of a green box with a line through it. + * @property {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} key + */ key: '', /** - * The world coordinates of this Game Object in pixels. - * Depending on where in the display list this Game Object is placed this value can differ from `position`, - * which contains the x/y coordinates relative to the Game Objects parent. - * @property {Phaser.Point} world - */ + * The world coordinates of this Game Object in pixels. + * Depending on where in the display list this Game Object is placed this value can differ from `position`, + * which contains the x/y coordinates relative to the Game Objects parent. + * @property {Phaser.Point} world + */ world: null, /** - * A debug flag designed for use with `Game.enableStep`. - * @property {boolean} debug - * @default - */ + * A debug flag designed for use with `Game.enableStep`. + * @property {boolean} debug + * @default + */ debug: false, /** - * The position the Game Object was located in the previous frame. - * @property {Phaser.Point} previousPosition - * @readOnly - */ + * The position the Game Object was located in the previous frame. + * @property {Phaser.Point} previousPosition + * @readOnly + */ previousPosition: null, /** - * The rotation the Game Object was in set to in the previous frame. Value is in radians. - * @property {number} previousRotation - * @readOnly - */ + * The rotation the Game Object was in set to in the previous frame. Value is in radians. + * @property {number} previousRotation + * @readOnly + */ previousRotation: 0, /** - * The render order ID is used internally by the renderer and Input Manager and should not be modified. - * This property is mostly used internally by the renderers, but is exposed for the use of plugins. - * @property {number} renderOrderID - * @readOnly - */ + * The render order ID is used internally by the renderer and Input Manager and should not be modified. + * This property is mostly used internally by the renderers, but is exposed for the use of plugins. + * @property {number} renderOrderID + * @readOnly + */ renderOrderID: 0, /** - * A Game Object is considered `fresh` if it has just been created or reset and is yet to receive a renderer transform update. - * This property is mostly used internally by the physics systems, but is exposed for the use of plugins. - * @property {boolean} fresh - * @readOnly - */ + * A Game Object is considered `fresh` if it has just been created or reset and is yet to receive a renderer transform update. + * This property is mostly used internally by the physics systems, but is exposed for the use of plugins. + * @property {boolean} fresh + * @readOnly + */ fresh: true, /** - * A Game Object is that is pendingDestroy is flagged to have its destroy method called on the next logic update. - * You can set it directly to allow you to flag an object to be destroyed on its next update. - * - * This is extremely useful if you wish to destroy an object from within one of its own callbacks - * such as with Buttons or other Input events. - * - * @property {boolean} pendingDestroy - */ + * A Game Object is that is pendingDestroy is flagged to have its destroy method called on the next logic update. + * You can set it directly to allow you to flag an object to be destroyed on its next update. + * + * This is extremely useful if you wish to destroy an object from within one of its own callbacks + * such as with Buttons or other Input events. + * + * @property {boolean} pendingDestroy + */ pendingDestroy: false, /** - * @property {Phaser.Rectangle} _bounds - Internal cache var. - * @private - */ + * @property {Phaser.Rectangle} _bounds - Internal cache var. + * @private + */ _bounds: null, /** - * @property {boolean} _exists - Internal cache var. - * @private - */ + * @property {boolean} _exists - Internal cache var. + * @private + */ _exists: true, /** - * Controls if this Game Object is processed by the core game loop. - * If this Game Object has a physics body it also controls if its physics body is updated or not. - * When `exists` is set to `false` it will remove its physics body from the physics world if it has one. - * It also toggles the `visible` property to false as well. - * - * Setting `exists` to true will add its physics body back in to the physics world, if it has one. - * It will also set the `visible` property to `true`. - * - * @property {boolean} exists - */ + * Controls if this Game Object is processed by the core game loop. + * If this Game Object has a physics body it also controls if its physics body is updated or not. + * When `exists` is set to `false` it will remove its physics body from the physics world if it has one. + * It also toggles the `visible` property to false as well. + * + * Setting `exists` to true will add its physics body back in to the physics world, if it has one. + * It will also set the `visible` property to `true`. + * + * @property {boolean} exists + */ exists: { get: function () { - return this._exists; - }, set: function (value) { - if (value) { this._exists = true; @@ -313,20 +304,18 @@ Phaser.Component.Core.prototype = { this.visible = false; } - } }, /** - * Internal method called by preUpdate. - * - * @method - * @protected - */ + * Internal method called by preUpdate. + * + * @method + * @protected + */ preUpdateChildren: function () { - // This can't loop in reverse, we need the renderOrderID to be in sequence var i = 0; @@ -341,30 +330,28 @@ Phaser.Component.Core.prototype = { i++; } } - }, /** - * Override this method in your own custom objects to handle any update requirements. - * It is called immediately after `preUpdate` and before `postUpdate`. - * Remember if this Game Object has any children you should call update on those too. - * - * @method - */ + * Override this method in your own custom objects to handle any update requirements. + * It is called immediately after `preUpdate` and before `postUpdate`. + * Remember if this Game Object has any children you should call update on those too. + * + * @method + */ update: function () { }, /** - * Internal method called by the World postUpdate cycle. - * - * @method - * @protected - */ + * Internal method called by the World postUpdate cycle. + * + * @method + * @protected + */ postUpdate: function () { - if (this.customRender) { this.key.render(); @@ -384,7 +371,6 @@ Phaser.Component.Core.prototype = { { this.children[i].postUpdate(); } - } }; diff --git a/src/gameobjects/components/Crop.js b/src/gameobjects/components/Crop.js index c83eeb86e..0eaadd507 100644 --- a/src/gameobjects/components/Crop.js +++ b/src/gameobjects/components/Crop.js @@ -1,54 +1,53 @@ /** -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* The Crop component provides the ability to crop a texture based Game Object to a defined rectangle, -* which can be updated in real-time. -* -* @class -*/ + * The Crop component provides the ability to crop a texture based Game Object to a defined rectangle, + * which can be updated in real-time. + * + * @class + */ Phaser.Component.Crop = function () {}; Phaser.Component.Crop.prototype = { /** - * The Rectangle used to crop the texture this Game Object uses. - * Set this property via `crop`. - * If you modify this property directly you must call `updateCrop` in order to have the change take effect. - * @property {Phaser.Rectangle} cropRect - * @default - */ + * The Rectangle used to crop the texture this Game Object uses. + * Set this property via `crop`. + * If you modify this property directly you must call `updateCrop` in order to have the change take effect. + * @property {Phaser.Rectangle} cropRect + * @default + */ cropRect: null, /** - * @property {Phaser.Rectangle} _crop - Internal cache var. - * @private - */ + * @property {Phaser.Rectangle} _crop - Internal cache var. + * @private + */ _crop: null, /** - * Crop allows you to crop the texture being used to display this Game Object. - * Setting a crop rectangle modifies the core texture frame. The Game Object width and height properties will be adjusted accordingly. - * - * Cropping takes place from the top-left and can be modified in real-time either by providing an updated rectangle object to this method, - * or by modifying `cropRect` property directly and then calling `updateCrop`. - * - * The rectangle object given to this method can be either a `Phaser.Rectangle` or any other object - * so long as it has public `x`, `y`, `width`, `height`, `right` and `bottom` properties. - * - * A reference to the rectangle is stored in `cropRect` unless the `copy` parameter is `true`, - * in which case the values are duplicated to a local object. - * - * @method - * @param {Phaser.Rectangle} rect - The Rectangle used during cropping. Pass null or no parameters to clear a previously set crop rectangle. - * @param {boolean} [copy=false] - If false `cropRect` will be stored as a reference to the given rect. If true it will copy the rect values into a local Phaser Rectangle object stored in cropRect. - */ + * Crop allows you to crop the texture being used to display this Game Object. + * Setting a crop rectangle modifies the core texture frame. The Game Object width and height properties will be adjusted accordingly. + * + * Cropping takes place from the top-left and can be modified in real-time either by providing an updated rectangle object to this method, + * or by modifying `cropRect` property directly and then calling `updateCrop`. + * + * The rectangle object given to this method can be either a `Phaser.Rectangle` or any other object + * so long as it has public `x`, `y`, `width`, `height`, `right` and `bottom` properties. + * + * A reference to the rectangle is stored in `cropRect` unless the `copy` parameter is `true`, + * in which case the values are duplicated to a local object. + * + * @method + * @param {Phaser.Rectangle} rect - The Rectangle used during cropping. Pass null or no parameters to clear a previously set crop rectangle. + * @param {boolean} [copy=false] - If false `cropRect` will be stored as a reference to the given rect. If true it will copy the rect values into a local Phaser Rectangle object stored in cropRect. + */ crop: function (rect, copy) { - if (copy === undefined) { copy = false; } if (rect) @@ -75,18 +74,16 @@ Phaser.Component.Crop.prototype = { this.resetFrame(); } - }, /** - * If you have set a crop rectangle on this Game Object via `crop` and since modified the `cropRect` property, - * or the rectangle it references, then you need to update the crop frame by calling this method. - * - * @method - */ + * If you have set a crop rectangle on this Game Object via `crop` and since modified the `cropRect` property, + * or the rectangle it references, then you need to update the crop frame by calling this method. + * + * @method + */ updateCrop: function () { - if (!this.cropRect) { return; @@ -123,7 +120,6 @@ Phaser.Component.Crop.prototype = { { this.texture.requiresReTint = true; } - } }; diff --git a/src/gameobjects/components/Delta.js b/src/gameobjects/components/Delta.js index 5b18c212d..3ab784793 100644 --- a/src/gameobjects/components/Delta.js +++ b/src/gameobjects/components/Delta.js @@ -1,69 +1,63 @@ /** -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* The Delta component provides access to delta values between the Game Objects current and previous position. -* -* @class -*/ + * The Delta component provides access to delta values between the Game Objects current and previous position. + * + * @class + */ Phaser.Component.Delta = function () {}; Phaser.Component.Delta.prototype = { /** - * Returns the delta x value. The difference between world.x now and in the previous frame. - * - * The value will be positive if the Game Object has moved to the right or negative if to the left. - * - * @property {number} deltaX - * @readonly - */ + * Returns the delta x value. The difference between world.x now and in the previous frame. + * + * The value will be positive if the Game Object has moved to the right or negative if to the left. + * + * @property {number} deltaX + * @readonly + */ deltaX: { get: function () { - return this.world.x - this.previousPosition.x; - } }, /** - * Returns the delta y value. The difference between world.y now and in the previous frame. - * - * The value will be positive if the Game Object has moved down or negative if up. - * - * @property {number} deltaY - * @readonly - */ + * Returns the delta y value. The difference between world.y now and in the previous frame. + * + * The value will be positive if the Game Object has moved down or negative if up. + * + * @property {number} deltaY + * @readonly + */ deltaY: { get: function () { - return this.world.y - this.previousPosition.y; - } }, /** - * Returns the delta z value. The difference between rotation now and in the previous frame. - * - * @property {number} deltaZ - The delta value. - * @readonly - */ + * Returns the delta z value. The difference between rotation now and in the previous frame. + * + * @property {number} deltaZ - The delta value. + * @readonly + */ deltaZ: { get: function () { - return this.rotation - this.previousRotation; - } } diff --git a/src/gameobjects/components/Destroy.js b/src/gameobjects/components/Destroy.js index 46d431a68..cf6de9127 100644 --- a/src/gameobjects/components/Destroy.js +++ b/src/gameobjects/components/Destroy.js @@ -1,42 +1,41 @@ /** -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* The Destroy component is responsible for destroying a Game Object. -* -* @class -*/ + * The Destroy component is responsible for destroying a Game Object. + * + * @class + */ Phaser.Component.Destroy = function () {}; Phaser.Component.Destroy.prototype = { /** - * As a Game Object runs through its destroy method this flag is set to true, - * and can be checked in any sub-systems or plugins it is being destroyed from. - * @property {boolean} destroyPhase - * @readOnly - */ + * As a Game Object runs through its destroy method this flag is set to true, + * and can be checked in any sub-systems or plugins it is being destroyed from. + * @property {boolean} destroyPhase + * @readOnly + */ destroyPhase: false, /** - * Destroys the Game Object. This removes it from its parent group, destroys the input, event and animation handlers if present - * and nulls its reference to `game`, freeing it up for garbage collection. - * - * If this Game Object has the Events component it will also dispatch the `onDestroy` event. - * - * You can optionally also destroy the BaseTexture this Game Object is using. Be careful if you've - * more than one Game Object sharing the same BaseTexture. - * - * @method - * @param {boolean} [destroyChildren=true] - Should every child of this object have its destroy method called as well? - * @param {boolean} [destroyTexture=false] - Destroy the BaseTexture this Game Object is using? Note that if another Game Object is sharing the same BaseTexture it will invalidate it. - */ + * Destroys the Game Object. This removes it from its parent group, destroys the input, event and animation handlers if present + * and nulls its reference to `game`, freeing it up for garbage collection. + * + * If this Game Object has the Events component it will also dispatch the `onDestroy` event. + * + * You can optionally also destroy the BaseTexture this Game Object is using. Be careful if you've + * more than one Game Object sharing the same BaseTexture. + * + * @method + * @param {boolean} [destroyChildren=true] - Should every child of this object have its destroy method called as well? + * @param {boolean} [destroyTexture=false] - Destroy the BaseTexture this Game Object is using? Note that if another Game Object is sharing the same BaseTexture it will invalidate it. + */ destroy: function (destroyChildren, destroyTexture) { - if (this.game === null || this.destroyPhase) { return; } if (destroyChildren === undefined) { destroyChildren = true; } @@ -161,7 +160,6 @@ Phaser.Component.Destroy.prototype = { this.destroyPhase = false; this.pendingDestroy = false; - } }; diff --git a/src/gameobjects/components/Events.js b/src/gameobjects/components/Events.js index 16b3bc2b7..f78ade412 100644 --- a/src/gameobjects/components/Events.js +++ b/src/gameobjects/components/Events.js @@ -1,42 +1,40 @@ /** -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* The Events component is a collection of events fired by the parent Game Object. -* -* Phaser uses what are known as 'Signals' for all event handling. All of the events in -* this class are signals you can subscribe to, much in the same way you'd "listen" for -* an event. -* -* For example to tell when a Sprite has been added to a new group, you can bind a function -* to the {@link #onAddedToGroup} signal: -* -* `sprite.events.onAddedToGroup.add(yourFunction, this);` -* -* Where `yourFunction` is the function you want called when this event occurs. -* -* For more details about how signals work please see the {@link Phaser.Signal} class. -* -* The Input-related events will only be dispatched if the Sprite has had {@link Phaser.Component.InputEnabled#inputEnabled inputEnabled} set to `true` -* and the Animation-related events only apply to game objects with animations like {@link Phaser.Sprite}. -* -* @class Phaser.Events -* @constructor -* @param {Phaser.Sprite} sprite - A reference to the game object / Sprite that owns this Events object. -*/ + * The Events component is a collection of events fired by the parent Game Object. + * + * Phaser uses what are known as 'Signals' for all event handling. All of the events in + * this class are signals you can subscribe to, much in the same way you'd "listen" for + * an event. + * + * For example to tell when a Sprite has been added to a new group, you can bind a function + * to the {@link #onAddedToGroup} signal: + * + * `sprite.events.onAddedToGroup.add(yourFunction, this);` + * + * Where `yourFunction` is the function you want called when this event occurs. + * + * For more details about how signals work please see the {@link Phaser.Signal} class. + * + * The Input-related events will only be dispatched if the Sprite has had {@link Phaser.Component.InputEnabled#inputEnabled inputEnabled} set to `true` + * and the Animation-related events only apply to game objects with animations like {@link Phaser.Sprite}. + * + * @class Phaser.Events + * @constructor + * @param {Phaser.Sprite} sprite - A reference to the game object / Sprite that owns this Events object. + */ Phaser.Events = function (sprite) { - /** - * @property {Phaser.Sprite} parent - The Sprite that owns these events. - */ + * @property {Phaser.Sprite} parent - The Sprite that owns these events. + */ this.parent = sprite; // The signals are automatically added by the corresponding proxy properties - }; Phaser.Events.prototype = { @@ -48,7 +46,6 @@ Phaser.Events.prototype = { */ destroy: function () { - this._parent = null; if (this._onDestroy) { this._onDestroy.dispose(); } @@ -70,230 +67,231 @@ Phaser.Events.prototype = { if (this._onAnimationStart) { this._onAnimationStart.dispose(); } if (this._onAnimationComplete) { this._onAnimationComplete.dispose(); } if (this._onAnimationLoop) { this._onAnimationLoop.dispose(); } - }, // The following properties are sentinels that will be replaced with getters /** - * This signal is dispatched when this Game Object is added to a new {@link Phaser.Group Group}. - * It is sent two arguments: - * - * - {any} The Game Object that was added to the Group. - * - {Phaser.Group} The Group it was added to. - * - * @property {Phaser.Signal} onAddedToGroup - */ + * This signal is dispatched when this Game Object is added to a new {@link Phaser.Group Group}. + * It is sent two arguments: + * + * - {any} The Game Object that was added to the Group. + * - {Phaser.Group} The Group it was added to. + * + * @property {Phaser.Signal} onAddedToGroup + */ onAddedToGroup: null, /** - * This signal is dispatched when the Game Object is removed from a {@link Phaser.Group Group}. - * It is sent two arguments: - * - * - {any} The Game Object that was removed from the Group. - * - {Phaser.Group} The Group it was removed from. - * - * @property {Phaser.Signal} onRemovedFromGroup - */ + * This signal is dispatched when the Game Object is removed from a {@link Phaser.Group Group}. + * It is sent two arguments: + * + * - {any} The Game Object that was removed from the Group. + * - {Phaser.Group} The Group it was removed from. + * + * @property {Phaser.Signal} onRemovedFromGroup + */ onRemovedFromGroup: null, /** - * This signal is dispatched when the Game Object is destroyed. - * This happens when {@link Phaser.Sprite#destroy Sprite.destroy()} is called, or {@link Phaser.Group#destroy Group.destroy()} with `destroyChildren` set to true. - * It is sent one argument: - * - * - {any} The Game Object that was destroyed. - * - * @property {Phaser.Signal} onDestroy - */ + * This signal is dispatched when the Game Object is destroyed. + * This happens when {@link Phaser.Sprite#destroy Sprite.destroy()} is called, or {@link Phaser.Group#destroy Group.destroy()} with `destroyChildren` set to true. + * It is sent one argument: + * + * - {any} The Game Object that was destroyed. + * + * @property {Phaser.Signal} onDestroy + */ onDestroy: null, /** - * This signal is dispatched when the Game Object is killed. - * This happens when {@link Phaser.Sprite#kill Sprite.kill()} is called. - * Please understand the difference between {@link Phaser.Sprite#kill kill} and {@link Phaser.Sprite#destroy destroy} by looking at their respective methods. - * It is sent one argument: - * - * - {any} The Game Object that was killed. - * - * @property {Phaser.Signal} onKilled - */ + * This signal is dispatched when the Game Object is killed. + * This happens when {@link Phaser.Sprite#kill Sprite.kill()} is called. + * Please understand the difference between {@link Phaser.Sprite#kill kill} and {@link Phaser.Sprite#destroy destroy} by looking at their respective methods. + * It is sent one argument: + * + * - {any} The Game Object that was killed. + * + * @property {Phaser.Signal} onKilled + */ onKilled: null, /** - * This signal is dispatched when the Game Object is revived from a previously killed state. - * This happens when {@link Phaser.Sprite#revive Sprite.revive()} is called. - * It is sent one argument: - * - * - {any} The Game Object that was revived. - * - * @property {Phaser.Signal} onRevived - */ + * This signal is dispatched when the Game Object is revived from a previously killed state. + * This happens when {@link Phaser.Sprite#revive Sprite.revive()} is called. + * It is sent one argument: + * + * - {any} The Game Object that was revived. + * + * @property {Phaser.Signal} onRevived + */ onRevived: null, /** - * This signal is dispatched when the Game Object leaves the Phaser.World {@link Phaser.World#bounds bounds}. - * This signal is only if {@link Phaser.Sprite#checkWorldBounds Sprite.checkWorldBounds} is set to `true`. - * It is sent one argument: - * - * - {any} The Game Object that left the World bounds. - * - * @property {Phaser.Signal} onOutOfBounds - */ + * This signal is dispatched when the Game Object leaves the Phaser.World {@link Phaser.World#bounds bounds}. + * This signal is only if {@link Phaser.Sprite#checkWorldBounds Sprite.checkWorldBounds} is set to `true`. + * It is sent one argument: + * + * - {any} The Game Object that left the World bounds. + * + * @property {Phaser.Signal} onOutOfBounds + */ onOutOfBounds: null, /** - * This signal is dispatched when the Game Object returns within the Phaser.World {@link Phaser.World#bounds bounds}, having previously been outside of them. - * This signal is only if {@link Phaser.Sprite#checkWorldBounds Sprite.checkWorldBounds} is set to `true`. - * It is sent one argument: - * - * - {any} The Game Object that entered the World bounds. - * - * @property {Phaser.Signal} onEnterBounds - */ + * This signal is dispatched when the Game Object returns within the Phaser.World {@link Phaser.World#bounds bounds}, having previously been outside of them. + * This signal is only if {@link Phaser.Sprite#checkWorldBounds Sprite.checkWorldBounds} is set to `true`. + * It is sent one argument: + * + * - {any} The Game Object that entered the World bounds. + * + * @property {Phaser.Signal} onEnterBounds + */ onEnterBounds: null, /** - * This signal is dispatched if the Game Object has {@link Phaser.Component.InputEnabled#inputEnabled inputEnabled} set to `true`, - * and receives an over event from a {@link Phaser.Pointer}. - * It is sent two arguments: - * - * - {any} The Game Object that received the event. - * - {Phaser.Pointer} The Phaser.Pointer object that caused the event. - * - * @property {Phaser.Signal} onInputOver - */ + * This signal is dispatched if the Game Object has {@link Phaser.Component.InputEnabled#inputEnabled inputEnabled} set to `true`, + * and receives an over event from a {@link Phaser.Pointer}. + * It is sent two arguments: + * + * - {any} The Game Object that received the event. + * - {Phaser.Pointer} The Phaser.Pointer object that caused the event. + * + * @property {Phaser.Signal} onInputOver + */ onInputOver: null, /** - * This signal is dispatched if the Game Object has {@link Phaser.Component.InputEnabled#inputEnabled inputEnabled} set to `true`, - * and receives an out event from a {@link Phaser.Pointer}, which was previously over it. - * It is sent two arguments: - * - * - {any} The Game Object that received the event. - * - {Phaser.Pointer} The Phaser.Pointer object that caused the event. - * - * @property {Phaser.Signal} onInputOut - */ + * This signal is dispatched if the Game Object has {@link Phaser.Component.InputEnabled#inputEnabled inputEnabled} set to `true`, + * and receives an out event from a {@link Phaser.Pointer}, which was previously over it. + * It is sent two arguments: + * + * - {any} The Game Object that received the event. + * - {Phaser.Pointer} The Phaser.Pointer object that caused the event. + * + * @property {Phaser.Signal} onInputOut + */ onInputOut: null, /** - * This signal is dispatched if the Game Object has {@link Phaser.Component.InputEnabled#inputEnabled inputEnabled} set to `true`, - * and receives a down event from a {@link Phaser.Pointer}. This effectively means the Pointer has been - * pressed down (but not yet released) on the Game Object. - * It is sent two arguments: - * - * - {any} The Game Object that received the event. - * - {Phaser.Pointer} The Phaser.Pointer object that caused the event. - * - * @property {Phaser.Signal} onInputDown - */ + * This signal is dispatched if the Game Object has {@link Phaser.Component.InputEnabled#inputEnabled inputEnabled} set to `true`, + * and receives a down event from a {@link Phaser.Pointer}. This effectively means the Pointer has been + * pressed down (but not yet released) on the Game Object. + * It is sent two arguments: + * + * - {any} The Game Object that received the event. + * - {Phaser.Pointer} The Phaser.Pointer object that caused the event. + * + * @property {Phaser.Signal} onInputDown + */ onInputDown: null, /** - * This signal is dispatched if the Game Object has {@link Phaser.Component.InputEnabled#inputEnabled inputEnabled} set to `true`, - * and receives an up event from a {@link Phaser.Pointer}. This effectively means the Pointer had been - * pressed down, and was then released on the Game Object. - * It is sent three arguments: - * - * - {any} The Game Object that received the event. - * - {Phaser.Pointer} The Phaser.Pointer object that caused the event. - * - {boolean} isOver - Is the Pointer still over the Game Object? - * - * @property {Phaser.Signal} onInputUp - */ + * This signal is dispatched if the Game Object has {@link Phaser.Component.InputEnabled#inputEnabled inputEnabled} set to `true`, + * and receives an up event from a {@link Phaser.Pointer}. This effectively means the Pointer had been + * pressed down, and was then released on the Game Object. + * It is sent three arguments: + * + * - {any} The Game Object that received the event. + * - {Phaser.Pointer} The Phaser.Pointer object that caused the event. + * - {boolean} isOver - Is the Pointer still over the Game Object? + * + * @property {Phaser.Signal} onInputUp + */ onInputUp: null, /** - * This signal is dispatched if the Game Object has been {@link Phaser.Component.InputEnabled#inputEnabled inputEnabled} and {@link Phaser.InputHandler#enableDrag enableDrag} has been set. - * It is sent when a {@link Phaser.Pointer} starts to drag the Game Object, taking into consideration the various - * drag limitations that may be set. - * It is sent four arguments: - * - * - {any} The Game Object that received the event. - * - {Phaser.Pointer} The Phaser.Pointer object that caused the event. - * - {number} The x coordinate that the drag started from. - * - {number} The y coordinate that the drag started from. - * - * @property {Phaser.Signal} onDragStart - */ + * This signal is dispatched if the Game Object has been {@link Phaser.Component.InputEnabled#inputEnabled inputEnabled} and {@link Phaser.InputHandler#enableDrag enableDrag} has been set. + * It is sent when a {@link Phaser.Pointer} starts to drag the Game Object, taking into consideration the various + * drag limitations that may be set. + * It is sent four arguments: + * + * - {any} The Game Object that received the event. + * - {Phaser.Pointer} The Phaser.Pointer object that caused the event. + * - {number} The x coordinate that the drag started from. + * - {number} The y coordinate that the drag started from. + * + * @property {Phaser.Signal} onDragStart + */ onDragStart: null, /** - * This signal is dispatched if the Game Object has been {@link Phaser.Component.InputEnabled#inputEnabled inputEnabled} and {@link Phaser.InputHandler#enableDrag enableDrag} has been set. - * It is sent when a {@link Phaser.Pointer} is actively dragging the Game Object. - * Be warned: This is a high volume Signal. Be careful what you bind to it. - * It is sent six arguments: - * - * - {any} The Game Object that received the event. - * - {Phaser.Pointer} The Phaser.Pointer object that caused the event. - * - {number} The new x coordinate of the Game Object. - * - {number} The new y coordinate of the Game Object. - * - {Phaser.Point} A Point object that contains the point the Game Object was snapped to, if `snapOnDrag` has been enabled. - * - {boolean} The `fromStart` boolean, indicates if this is the first update immediately after the drag has started. - * - * @property {Phaser.Signal} onDragUpdate - */ + * This signal is dispatched if the Game Object has been {@link Phaser.Component.InputEnabled#inputEnabled inputEnabled} and {@link Phaser.InputHandler#enableDrag enableDrag} has been set. + * It is sent when a {@link Phaser.Pointer} is actively dragging the Game Object. + * Be warned: This is a high volume Signal. Be careful what you bind to it. + * It is sent six arguments: + * + * - {any} The Game Object that received the event. + * - {Phaser.Pointer} The Phaser.Pointer object that caused the event. + * - {number} The new x coordinate of the Game Object. + * - {number} The new y coordinate of the Game Object. + * - {Phaser.Point} A Point object that contains the point the Game Object was snapped to, if `snapOnDrag` has been enabled. + * - {boolean} The `fromStart` boolean, indicates if this is the first update immediately after the drag has started. + * + * @property {Phaser.Signal} onDragUpdate + */ onDragUpdate: null, /** - * This signal is dispatched if the Game Object has been {@link Phaser.Component.InputEnabled#inputEnabled inputEnabled} and {@link Phaser.InputHandler#enableDrag enableDrag} has been set. - * It is sent when a {@link Phaser.Pointer} stops dragging the Game Object. - * It is sent two arguments: - * - * - {any} The Game Object that received the event. - * - {Phaser.Pointer} The Phaser.Pointer object that caused the event. - * - * @property {Phaser.Signal} onDragStop - */ + * This signal is dispatched if the Game Object has been {@link Phaser.Component.InputEnabled#inputEnabled inputEnabled} and {@link Phaser.InputHandler#enableDrag enableDrag} has been set. + * It is sent when a {@link Phaser.Pointer} stops dragging the Game Object. + * It is sent two arguments: + * + * - {any} The Game Object that received the event. + * - {Phaser.Pointer} The Phaser.Pointer object that caused the event. + * + * @property {Phaser.Signal} onDragStop + */ onDragStop: null, /** - * This signal is dispatched if the Game Object has the {@link Phaser.AnimationManager AnimationManager} component, - * and an Animation has been played. - * You can also listen to {@link Phaser.Animation#onStart} rather than via the Game Objects events. - * It is sent two arguments: - * - * - {any} The Game Object that received the event. - * - {Phaser.Animation} The Phaser.Animation that was started. - * - * @property {Phaser.Signal} onAnimationStart - */ + * This signal is dispatched if the Game Object has the {@link Phaser.AnimationManager AnimationManager} component, + * and an Animation has been played. + * You can also listen to {@link Phaser.Animation#onStart} rather than via the Game Objects events. + * It is sent two arguments: + * + * - {any} The Game Object that received the event. + * - {Phaser.Animation} The Phaser.Animation that was started. + * + * @property {Phaser.Signal} onAnimationStart + */ onAnimationStart: null, /** - * This signal is dispatched if the Game Object has the {@link Phaser.AnimationManager AnimationManager} component, - * and an Animation has been stopped (via {@link Phaser.AnimationManager#stop animation.stop()} and the `dispatchComplete` argument has been set. - * You can also listen to {@link Phaser.Animation#onComplete} rather than via the Game Objects events. - * It is sent two arguments: - * - * - {any} The Game Object that received the event. - * - {Phaser.Animation} The Phaser.Animation that was stopped. - * - * @property {Phaser.Signal} onAnimationComplete - */ + * This signal is dispatched if the Game Object has the {@link Phaser.AnimationManager AnimationManager} component, + * and an Animation has been stopped (via {@link Phaser.AnimationManager#stop animation.stop()} and the `dispatchComplete` argument has been set. + * You can also listen to {@link Phaser.Animation#onComplete} rather than via the Game Objects events. + * It is sent two arguments: + * + * - {any} The Game Object that received the event. + * - {Phaser.Animation} The Phaser.Animation that was stopped. + * + * @property {Phaser.Signal} onAnimationComplete + */ onAnimationComplete: null, /** - * This signal is dispatched if the Game Object has the {@link Phaser.AnimationManager AnimationManager} component, - * and an Animation has looped playback. - * You can also listen to {@link Phaser.Animation#onLoop} rather than via the Game Objects events. - * It is sent two arguments: - * - * - {any} The Game Object that received the event. - * - {Phaser.Animation} The Phaser.Animation that looped. - * - * @property {Phaser.Signal} onAnimationLoop - */ + * This signal is dispatched if the Game Object has the {@link Phaser.AnimationManager AnimationManager} component, + * and an Animation has looped playback. + * You can also listen to {@link Phaser.Animation#onLoop} rather than via the Game Objects events. + * It is sent two arguments: + * + * - {any} The Game Object that received the event. + * - {Phaser.Animation} The Phaser.Animation that looped. + * + * @property {Phaser.Signal} onAnimationLoop + */ onAnimationLoop: null }; Phaser.Events.prototype.constructor = Phaser.Events; -// Create an auto-create proxy getter and dispatch method for all events. -// The backing property is the same as the event name, prefixed with '_' -// and the dispatch method is the same as the event name postfixed with '$dispatch'. +/* + * Create an auto-create proxy getter and dispatch method for all events. + * The backing property is the same as the event name, prefixed with '_' + * and the dispatch method is the same as the event name postfixed with '$dispatch'. + */ for (var prop in Phaser.Events.prototype) { if (!Phaser.Events.prototype.hasOwnProperty(prop) || @@ -320,7 +318,5 @@ for (var prop in Phaser.Events.prototype) { return this[backing] ? this[backing].dispatch.apply(this[backing], arguments) : null; }; - })(prop, '_' + prop); - } diff --git a/src/gameobjects/components/FixedToCamera.js b/src/gameobjects/components/FixedToCamera.js index 4c76ae9ad..f1df2ff08 100644 --- a/src/gameobjects/components/FixedToCamera.js +++ b/src/gameobjects/components/FixedToCamera.js @@ -1,15 +1,15 @@ /** -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* The FixedToCamera component enables a Game Object to be rendered relative to the game camera coordinates, regardless -* of where in the world the camera is. This is used for things like sticking game UI to the camera that scrolls as it moves around the world. -* -* @class -*/ + * The FixedToCamera component enables a Game Object to be rendered relative to the game camera coordinates, regardless + * of where in the world the camera is. This is used for things like sticking game UI to the camera that scrolls as it moves around the world. + * + * @class + */ Phaser.Component.FixedToCamera = function () {}; /** @@ -20,51 +20,46 @@ Phaser.Component.FixedToCamera = function () {}; */ Phaser.Component.FixedToCamera.postUpdate = function () { - if (this.fixedToCamera) { this.position.x = (this.game.camera.view.x + this.cameraOffset.x) / this.game.camera.scale.x; this.position.y = (this.game.camera.view.y + this.cameraOffset.y) / this.game.camera.scale.y; } - }; Phaser.Component.FixedToCamera.prototype = { /** - * @property {boolean} _fixedToCamera - * @private - */ + * @property {boolean} _fixedToCamera + * @private + */ _fixedToCamera: false, /** - * A Game Object that is "fixed" to the camera is rendered at a given x/y offsets from the top left of the camera. The offsets - * are stored in the `cameraOffset` property, which is initialized with the current object coordinates. - * - * The values are adjusted at the rendering stage, overriding the Game Objects actual world position. - * - * The end result is that the Game Object will appear to be 'fixed' to the camera, regardless of where in the game world - * the camera is viewing. This is useful if for example this Game Object is a UI item that you wish to be visible at all times - * regardless where in the world the camera is. - * - * Note that the `cameraOffset` values are in addition to any parent of this Game Object on the display list. - * - * Be careful not to set `fixedToCamera` on Game Objects which are in Groups that already have `fixedToCamera` enabled on them. - * - * @property {boolean} fixedToCamera - */ + * A Game Object that is "fixed" to the camera is rendered at a given x/y offsets from the top left of the camera. The offsets + * are stored in the `cameraOffset` property, which is initialized with the current object coordinates. + * + * The values are adjusted at the rendering stage, overriding the Game Objects actual world position. + * + * The end result is that the Game Object will appear to be 'fixed' to the camera, regardless of where in the game world + * the camera is viewing. This is useful if for example this Game Object is a UI item that you wish to be visible at all times + * regardless where in the world the camera is. + * + * Note that the `cameraOffset` values are in addition to any parent of this Game Object on the display list. + * + * Be careful not to set `fixedToCamera` on Game Objects which are in Groups that already have `fixedToCamera` enabled on them. + * + * @property {boolean} fixedToCamera + */ fixedToCamera: { get: function () { - return this._fixedToCamera; - }, set: function (value) { - if (value) { this._fixedToCamera = true; @@ -74,17 +69,16 @@ Phaser.Component.FixedToCamera.prototype = { { this._fixedToCamera = false; } - } }, /** - * The x/y coordinate offset applied to the top-left of the camera that this Game Object will be drawn at if `fixedToCamera` is true. - * - * The values are relative to the top-left of the camera view and in addition to any parent of the Game Object on the display list. - * @property {Phaser.Point} cameraOffset - */ + * The x/y coordinate offset applied to the top-left of the camera that this Game Object will be drawn at if `fixedToCamera` is true. + * + * The values are relative to the top-left of the camera view and in addition to any parent of the Game Object on the display list. + * @property {Phaser.Point} cameraOffset + */ cameraOffset: new Phaser.Point() }; diff --git a/src/gameobjects/components/Health.js b/src/gameobjects/components/Health.js index ed5761f5e..ba4c4f04f 100644 --- a/src/gameobjects/components/Health.js +++ b/src/gameobjects/components/Health.js @@ -1,51 +1,50 @@ /** -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* The Health component provides the ability for Game Objects to have a `health` property -* that can be damaged and reset through game code. -* Requires the LifeSpan component. -* -* @class -*/ + * The Health component provides the ability for Game Objects to have a `health` property + * that can be damaged and reset through game code. + * Requires the LifeSpan component. + * + * @class + */ Phaser.Component.Health = function () {}; Phaser.Component.Health.prototype = { /** - * The Game Objects health value. This is a handy property for setting and manipulating health on a Game Object. - * - * It can be used in combination with the `damage` method or modified directly. - * - * @property {number} health - * @default - */ + * The Game Objects health value. This is a handy property for setting and manipulating health on a Game Object. + * + * It can be used in combination with the `damage` method or modified directly. + * + * @property {number} health + * @default + */ health: 1, /** - * The Game Objects maximum health value. This works in combination with the `heal` method to ensure - * the health value never exceeds the maximum. - * - * @property {number} maxHealth - * @default - */ + * The Game Objects maximum health value. This works in combination with the `heal` method to ensure + * the health value never exceeds the maximum. + * + * @property {number} maxHealth + * @default + */ maxHealth: 100, /** - * Damages the Game Object. This removes the given amount of health from the `health` property. - * - * If health is taken below or is equal to zero then the `kill` method is called. - * - * @method - * @param {number} amount - The amount to subtract from the current `health` value. - * @return {Phaser.Sprite} This instance. - */ + * Damages the Game Object. This removes the given amount of health from the `health` property. + * + * If health is taken below or is equal to zero then the `kill` method is called. + * + * @method + * @param {number} amount - The amount to subtract from the current `health` value. + * @return {Phaser.Sprite} This instance. + */ damage: function (amount) { - if (this.alive) { this.health -= amount; @@ -57,20 +56,18 @@ Phaser.Component.Health.prototype = { } return this; - }, /** - * Sets the health property of the Game Object to the given amount. - * Will never exceed the `maxHealth` value. - * - * @method - * @param {number} amount - The amount to set the `health` value to. The total will never exceed `maxHealth`. - * @return {Phaser.Sprite} This instance. - */ + * Sets the health property of the Game Object to the given amount. + * Will never exceed the `maxHealth` value. + * + * @method + * @param {number} amount - The amount to set the `health` value to. The total will never exceed `maxHealth`. + * @return {Phaser.Sprite} This instance. + */ setHealth: function (amount) { - this.health = amount; if (this.health > this.maxHealth) @@ -79,19 +76,17 @@ Phaser.Component.Health.prototype = { } return this; - }, /** - * Heal the Game Object. This adds the given amount of health to the `health` property. - * - * @method - * @param {number} amount - The amount to add to the current `health` value. The total will never exceed `maxHealth`. - * @return {Phaser.Sprite} This instance. - */ + * Heal the Game Object. This adds the given amount of health to the `health` property. + * + * @method + * @param {number} amount - The amount to add to the current `health` value. The total will never exceed `maxHealth`. + * @return {Phaser.Sprite} This instance. + */ heal: function (amount) { - if (this.alive) { this.health += amount; @@ -103,7 +98,6 @@ Phaser.Component.Health.prototype = { } return this; - } }; diff --git a/src/gameobjects/components/InCamera.js b/src/gameobjects/components/InCamera.js index 3e30d7e58..6c45b0946 100644 --- a/src/gameobjects/components/InCamera.js +++ b/src/gameobjects/components/InCamera.js @@ -1,35 +1,33 @@ /** -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* The InCamera component checks if the Game Object intersects with the Game Camera. -* -* @class -*/ + * The InCamera component checks if the Game Object intersects with the Game Camera. + * + * @class + */ Phaser.Component.InCamera = function () {}; Phaser.Component.InCamera.prototype = { /** - * Checks if this Game Objects bounds intersects with the Game Cameras bounds. - * - * It will be `true` if they intersect, or `false` if the Game Object is fully outside of the Cameras bounds. - * - * An object outside the bounds can be considered for camera culling if it has the AutoCull component. - * - * @property {boolean} inCamera - * @readonly - */ + * Checks if this Game Objects bounds intersects with the Game Cameras bounds. + * + * It will be `true` if they intersect, or `false` if the Game Object is fully outside of the Cameras bounds. + * + * An object outside the bounds can be considered for camera culling if it has the AutoCull component. + * + * @property {boolean} inCamera + * @readonly + */ inCamera: { get: function () { - return this.game.world.camera.view.intersects(this._bounds); - } } diff --git a/src/gameobjects/components/InWorld.js b/src/gameobjects/components/InWorld.js index 6f306e95f..f79089afc 100644 --- a/src/gameobjects/components/InWorld.js +++ b/src/gameobjects/components/InWorld.js @@ -1,16 +1,16 @@ /** -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* The InWorld component checks if a Game Object is within the Game World Bounds. -* An object is considered as being "in bounds" so long as its own bounds intersects at any point with the World bounds. -* If the AutoCull component is enabled on the Game Object then it will check the Game Object against the Camera bounds as well. -* -* @class -*/ + * The InWorld component checks if a Game Object is within the Game World Bounds. + * An object is considered as being "in bounds" so long as its own bounds intersects at any point with the World bounds. + * If the AutoCull component is enabled on the Game Object then it will check the Game Object against the Camera bounds as well. + * + * @class + */ Phaser.Component.InWorld = function () {}; /** @@ -21,7 +21,6 @@ Phaser.Component.InWorld = function () {}; */ Phaser.Component.InWorld.preUpdate = function () { - if (this.pendingDestroy) { this.destroy(); @@ -80,36 +79,35 @@ Phaser.Component.InWorld.preUpdate = function () } return true; - }; Phaser.Component.InWorld.prototype = { /** - * If this is set to `true` the Game Object checks if it is within the World bounds each frame. - * - * When it is no longer intersecting the world bounds it dispatches the `onOutOfBounds` event. - * - * If it was *previously* out of bounds but is now intersecting the world bounds again it dispatches the `onEnterBounds` event. - * - * It also optionally kills the Game Object if `outOfBoundsKill` is `true`. - * - * When `checkWorldBounds` is enabled it forces the Game Object to calculate its full bounds every frame. - * - * This is a relatively expensive operation, especially if enabled on hundreds of Game Objects. So enable it only if you know it's required, - * or you have tested performance and find it acceptable. - * - * @property {boolean} checkWorldBounds - * @default - */ + * If this is set to `true` the Game Object checks if it is within the World bounds each frame. + * + * When it is no longer intersecting the world bounds it dispatches the `onOutOfBounds` event. + * + * If it was *previously* out of bounds but is now intersecting the world bounds again it dispatches the `onEnterBounds` event. + * + * It also optionally kills the Game Object if `outOfBoundsKill` is `true`. + * + * When `checkWorldBounds` is enabled it forces the Game Object to calculate its full bounds every frame. + * + * This is a relatively expensive operation, especially if enabled on hundreds of Game Objects. So enable it only if you know it's required, + * or you have tested performance and find it acceptable. + * + * @property {boolean} checkWorldBounds + * @default + */ checkWorldBounds: false, /** - * If this and the `checkWorldBounds` property are both set to `true` then the `kill` method is called as soon as `inWorld` returns false. - * - * @property {boolean} outOfBoundsKill - * @default - */ + * If this and the `checkWorldBounds` property are both set to `true` then the `kill` method is called as soon as `inWorld` returns false. + * + * @property {boolean} outOfBoundsKill + * @default + */ outOfBoundsKill: false, /** @@ -122,24 +120,22 @@ Phaser.Component.InWorld.prototype = { outOfCameraBoundsKill: false, /** - * @property {boolean} _outOfBoundsFired - Internal state var. - * @private - */ + * @property {boolean} _outOfBoundsFired - Internal state var. + * @private + */ _outOfBoundsFired: false, /** - * Checks if the Game Objects bounds are within, or intersect at any point with the Game World bounds. - * - * @property {boolean} inWorld - * @readonly - */ + * Checks if the Game Objects bounds are within, or intersect at any point with the Game World bounds. + * + * @property {boolean} inWorld + * @readonly + */ inWorld: { get: function () { - return this.game.world.bounds.intersects(this.getBounds()); - } } diff --git a/src/gameobjects/components/InputEnabled.js b/src/gameobjects/components/InputEnabled.js index 1ebb59cb9..b7fbb7c20 100644 --- a/src/gameobjects/components/InputEnabled.js +++ b/src/gameobjects/components/InputEnabled.js @@ -1,56 +1,53 @@ /** -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* The InputEnabled component allows a Game Object to have its own InputHandler and process input related events. -* -* @class -*/ + * The InputEnabled component allows a Game Object to have its own InputHandler and process input related events. + * + * @class + */ Phaser.Component.InputEnabled = function () {}; Phaser.Component.InputEnabled.prototype = { /** - * The Input Handler for this Game Object. - * - * By default it is disabled. If you wish this Game Object to process input events you should enable it with: `inputEnabled = true`. - * - * After you have done this, this property will be a reference to the Phaser InputHandler. - * @property {Phaser.InputHandler|null} input - */ + * The Input Handler for this Game Object. + * + * By default it is disabled. If you wish this Game Object to process input events you should enable it with: `inputEnabled = true`. + * + * After you have done this, this property will be a reference to the Phaser InputHandler. + * @property {Phaser.InputHandler|null} input + */ input: null, /** - * By default a Game Object won't process any input events. By setting `inputEnabled` to true a Phaser.InputHandler is created - * for this Game Object and it will then start to process click / touch events and more. - * - * You can then access the Input Handler via `this.input`. - * - * Note that Input related events are dispatched from `this.events`, i.e.: `events.onInputDown`. - * - * If you set this property to false it will stop the Input Handler from processing any more input events. - * - * If you want to _temporarily_ disable input for a Game Object, then it's better to set - * `input.enabled = false`, as it won't reset any of the Input Handlers internal properties. - * You can then toggle this back on as needed. - * - * @property {boolean} inputEnabled - */ + * By default a Game Object won't process any input events. By setting `inputEnabled` to true a Phaser.InputHandler is created + * for this Game Object and it will then start to process click / touch events and more. + * + * You can then access the Input Handler via `this.input`. + * + * Note that Input related events are dispatched from `this.events`, i.e.: `events.onInputDown`. + * + * If you set this property to false it will stop the Input Handler from processing any more input events. + * + * If you want to _temporarily_ disable input for a Game Object, then it's better to set + * `input.enabled = false`, as it won't reset any of the Input Handlers internal properties. + * You can then toggle this back on as needed. + * + * @property {boolean} inputEnabled + */ inputEnabled: { get: function () { - return (this.input && this.input.enabled); - }, set: function (value) { - if (value) { if (this.input === null) @@ -68,7 +65,6 @@ Phaser.Component.InputEnabled.prototype = { { this.input.stop(); } - } } diff --git a/src/gameobjects/components/LifeSpan.js b/src/gameobjects/components/LifeSpan.js index caf37cbc8..7e9302478 100644 --- a/src/gameobjects/components/LifeSpan.js +++ b/src/gameobjects/components/LifeSpan.js @@ -1,14 +1,14 @@ /** -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* LifeSpan Component Features. -* -* @class -*/ + * LifeSpan Component Features. + * + * @class + */ Phaser.Component.LifeSpan = function () {}; /** @@ -19,7 +19,6 @@ Phaser.Component.LifeSpan = function () {}; */ Phaser.Component.LifeSpan.preUpdate = function () { - if (this.pendingDestroy) { this.destroy(); @@ -38,53 +37,51 @@ Phaser.Component.LifeSpan.preUpdate = function () } return true; - }; Phaser.Component.LifeSpan.prototype = { /** - * A useful flag to control if the Game Object is alive or dead. - * - * This is set automatically by the Health components `damage` method should the object run out of health. - * Or you can toggle it via your game code. - * - * This property is mostly just provided to be used by your game - it doesn't effect rendering or logic updates. - * However you can use `Group.getFirstAlive` in conjunction with this property for fast object pooling and recycling. - * @property {boolean} alive - * @default - */ + * A useful flag to control if the Game Object is alive or dead. + * + * This is set automatically by the Health components `damage` method should the object run out of health. + * Or you can toggle it via your game code. + * + * This property is mostly just provided to be used by your game - it doesn't effect rendering or logic updates. + * However you can use `Group.getFirstAlive` in conjunction with this property for fast object pooling and recycling. + * @property {boolean} alive + * @default + */ alive: true, /** - * The lifespan allows you to give a Game Object a lifespan in milliseconds. - * - * Once the Game Object is 'born' you can set this to a positive value. - * - * It is automatically decremented by the millisecond equivalent of `game.time.physicsElapsed` each frame. - * When it reaches zero it will call the `kill` method. - * - * Very handy for particles, bullets, collectibles, or any other short-lived entity. - * - * @property {number} lifespan - * @default - */ + * The lifespan allows you to give a Game Object a lifespan in milliseconds. + * + * Once the Game Object is 'born' you can set this to a positive value. + * + * It is automatically decremented by the millisecond equivalent of `game.time.physicsElapsed` each frame. + * When it reaches zero it will call the `kill` method. + * + * Very handy for particles, bullets, collectibles, or any other short-lived entity. + * + * @property {number} lifespan + * @default + */ lifespan: 0, /** - * Brings a 'dead' Game Object back to life, optionally resetting its health value in the process. - * - * A resurrected Game Object has its `alive`, `exists` and `visible` properties all set to true. - * - * It will dispatch the `onRevived` event. Listen to `events.onRevived` for the signal. - * - * @method - * @param {number} [health=100] - The health to give the Game Object. Only set if the GameObject has the Health component. - * @return {PIXI.DisplayObject} This instance. - */ + * Brings a 'dead' Game Object back to life, optionally resetting its health value in the process. + * + * A resurrected Game Object has its `alive`, `exists` and `visible` properties all set to true. + * + * It will dispatch the `onRevived` event. Listen to `events.onRevived` for the signal. + * + * @method + * @param {number} [health=100] - The health to give the Game Object. Only set if the GameObject has the Health component. + * @return {PIXI.DisplayObject} This instance. + */ revive: function (health) { - if (health === undefined) { health = 100; } this.alive = true; @@ -102,25 +99,23 @@ Phaser.Component.LifeSpan.prototype = { } return this; - }, /** - * Kills a Game Object. A killed Game Object has its `alive`, `exists` and `visible` properties all set to false. - * - * It will dispatch the `onKilled` event. You can listen to `events.onKilled` for the signal. - * - * Note that killing a Game Object is a way for you to quickly recycle it in an object pool, - * it doesn't destroy the object or free it up from memory. - * - * If you don't need this Game Object any more you should call `destroy` instead. - * - * @method - * @return {PIXI.DisplayObject} This instance. - */ + * Kills a Game Object. A killed Game Object has its `alive`, `exists` and `visible` properties all set to false. + * + * It will dispatch the `onKilled` event. You can listen to `events.onKilled` for the signal. + * + * Note that killing a Game Object is a way for you to quickly recycle it in an object pool, + * it doesn't destroy the object or free it up from memory. + * + * If you don't need this Game Object any more you should call `destroy` instead. + * + * @method + * @return {PIXI.DisplayObject} This instance. + */ kill: function () { - this.alive = false; this.exists = false; this.visible = false; @@ -131,7 +126,6 @@ Phaser.Component.LifeSpan.prototype = { } return this; - } }; diff --git a/src/gameobjects/components/LoadTexture.js b/src/gameobjects/components/LoadTexture.js index 223aa47f4..ee386bc8b 100644 --- a/src/gameobjects/components/LoadTexture.js +++ b/src/gameobjects/components/LoadTexture.js @@ -1,56 +1,55 @@ /** -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* The LoadTexture component manages the loading of a texture into the Game Object and the changing of frames. -* -* @class -*/ + * The LoadTexture component manages the loading of a texture into the Game Object and the changing of frames. + * + * @class + */ Phaser.Component.LoadTexture = function () {}; Phaser.Component.LoadTexture.prototype = { /** - * @property {boolean} customRender - Does this texture require a custom render call? (as set by BitmapData, Video, etc) - * @private - */ + * @property {boolean} customRender - Does this texture require a custom render call? (as set by BitmapData, Video, etc) + * @private + */ customRender: false, /** - * @property {Phaser.Rectangle} _frame - Internal cache var. - * @private - */ + * @property {Phaser.Rectangle} _frame - Internal cache var. + * @private + */ _frame: null, /** - * Changes the base texture the Game Object is using. The old texture is removed and the new one is referenced or fetched from the Cache. - * - * If your Game Object is using a frame from a texture atlas and you just wish to change to another frame, then see the `frame` or `frameName` properties instead. - * - * You should only use `loadTexture` if you want to replace the base texture entirely. - * - * Calling this method causes a WebGL texture update, so use sparingly or in low-intensity portions of your game, or if you know the new texture is already on the GPU. - * - * You can use the new const `Phaser.PENDING_ATLAS` as the texture key for any sprite. - * Doing this then sets the key to be the `frame` argument (the frame is set to zero). - * - * This allows you to create sprites using `load.image` during development, and then change them - * to use a Texture Atlas later in development by simply searching your code for 'PENDING_ATLAS' - * and swapping it to be the key of the atlas data. - * - * Note: You cannot use a RenderTexture as a texture for a TileSprite. - * - * @method - * @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|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 Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. - * @param {string|number} [frame] - If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. - * @param {boolean} [stopAnimation=true] - If an animation is already playing on this Sprite you can choose to stop it or let it carry on playing. - */ + * Changes the base texture the Game Object is using. The old texture is removed and the new one is referenced or fetched from the Cache. + * + * If your Game Object is using a frame from a texture atlas and you just wish to change to another frame, then see the `frame` or `frameName` properties instead. + * + * You should only use `loadTexture` if you want to replace the base texture entirely. + * + * Calling this method causes a WebGL texture update, so use sparingly or in low-intensity portions of your game, or if you know the new texture is already on the GPU. + * + * You can use the new const `Phaser.PENDING_ATLAS` as the texture key for any sprite. + * Doing this then sets the key to be the `frame` argument (the frame is set to zero). + * + * This allows you to create sprites using `load.image` during development, and then change them + * to use a Texture Atlas later in development by simply searching your code for 'PENDING_ATLAS' + * and swapping it to be the key of the atlas data. + * + * Note: You cannot use a RenderTexture as a texture for a TileSprite. + * + * @method + * @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|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 Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. + * @param {string|number} [frame] - If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. + * @param {boolean} [stopAnimation=true] - If an animation is already playing on this Sprite you can choose to stop it or let it carry on playing. + */ loadTexture: function (key, frame, stopAnimation) { - if (key === Phaser.PENDING_ATLAS) { key = frame; @@ -144,20 +143,18 @@ Phaser.Component.LoadTexture.prototype = { { this.texture.baseTexture.scaleMode = 1; } - }, /** - * Sets the texture frame the Game Object uses for rendering. - * - * This is primarily an internal method used by `loadTexture`, but is exposed for the use of plugins and custom classes. - * - * @method - * @param {Phaser.Frame} frame - The Frame to be used by the texture. - */ + * Sets the texture frame the Game Object uses for rendering. + * + * This is primarily an internal method used by `loadTexture`, but is exposed for the use of plugins and custom classes. + * + * @method + * @param {Phaser.Frame} frame - The Frame to be used by the texture. + */ setFrame: function (frame) { - this._frame = frame; this.texture.frame.x = frame.x; @@ -212,56 +209,51 @@ Phaser.Component.LoadTexture.prototype = { { this.refreshTexture = true; } - }, /** - * Resizes the Frame dimensions that the Game Object uses for rendering. - * - * You shouldn't normally need to ever call this, but in the case of special texture types such as Video or BitmapData - * it can be useful to adjust the dimensions directly in this way. - * - * @method - * @param {object} parent - The parent texture object that caused the resize, i.e. a Phaser.Video object. - * @param {integer} width - The new width of the texture. - * @param {integer} height - The new height of the texture. - */ + * Resizes the Frame dimensions that the Game Object uses for rendering. + * + * You shouldn't normally need to ever call this, but in the case of special texture types such as Video or BitmapData + * it can be useful to adjust the dimensions directly in this way. + * + * @method + * @param {object} parent - The parent texture object that caused the resize, i.e. a Phaser.Video object. + * @param {integer} width - The new width of the texture. + * @param {integer} height - The new height of the texture. + */ resizeFrame: function (parent, width, height) { - this.texture.frame.resize(width, height); this.texture.setFrame(this.texture.frame); - }, /** - * Resets the texture frame dimensions that the Game Object uses for rendering. - * - * @method - */ + * Resets the texture frame dimensions that the Game Object uses for rendering. + * + * @method + */ resetFrame: function () { - if (this._frame) { this.setFrame(this._frame); } - }, /** - * Gets or sets the current frame index of the texture being used to render this Game Object. - * - * To change the frame set `frame` to the index of the new frame in the sprite sheet you wish this Game Object to use, - * for example: `player.frame = 4`. - * - * If the frame index given doesn't exist it will revert to the first frame found in the texture. - * - * If you are using a texture atlas then you should use the `frameName` property instead. - * - * If you wish to fully replace the texture being used see `loadTexture`. - * @property {integer} frame - */ + * Gets or sets the current frame index of the texture being used to render this Game Object. + * + * To change the frame set `frame` to the index of the new frame in the sprite sheet you wish this Game Object to use, + * for example: `player.frame = 4`. + * + * If the frame index given doesn't exist it will revert to the first frame found in the texture. + * + * If you are using a texture atlas then you should use the `frameName` property instead. + * + * If you wish to fully replace the texture being used see `loadTexture`. + * @property {integer} frame + */ frame: { get: function () @@ -277,18 +269,18 @@ Phaser.Component.LoadTexture.prototype = { }, /** - * Gets or sets the current frame name of the texture being used to render this Game Object. - * - * To change the frame set `frameName` to the name of the new frame in the texture atlas you wish this Game Object to use, - * for example: `player.frameName = "idle"`. - * - * If the frame name given doesn't exist it will revert to the first frame found in the texture and throw a console warning. - * - * If you are using a sprite sheet then you should use the `frame` property instead. - * - * If you wish to fully replace the texture being used see `loadTexture`. - * @property {string} frameName - */ + * Gets or sets the current frame name of the texture being used to render this Game Object. + * + * To change the frame set `frameName` to the name of the new frame in the texture atlas you wish this Game Object to use, + * for example: `player.frameName = "idle"`. + * + * If the frame name given doesn't exist it will revert to the first frame found in the texture and throw a console warning. + * + * If you are using a sprite sheet then you should use the `frame` property instead. + * + * If you wish to fully replace the texture being used see `loadTexture`. + * @property {string} frameName + */ frameName: { get: function () diff --git a/src/gameobjects/components/Overlap.js b/src/gameobjects/components/Overlap.js index 65e4dd013..e1596fa9c 100644 --- a/src/gameobjects/components/Overlap.js +++ b/src/gameobjects/components/Overlap.js @@ -1,36 +1,34 @@ /** -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* The Overlap component allows a Game Object to check if it overlaps with the bounds of another Game Object. -* -* @class -*/ + * The Overlap component allows a Game Object to check if it overlaps with the bounds of another Game Object. + * + * @class + */ Phaser.Component.Overlap = function () {}; Phaser.Component.Overlap.prototype = { /** - * Checks to see if the bounds of this Game Object overlaps with the bounds of the given Display Object, - * which can be a Sprite, Image, TileSprite or anything that extends those such as Button or provides a `getBounds` method and result. - * - * This check ignores the `hitArea` property if set and runs a `getBounds` comparison on both objects to determine the result. - * - * Therefore it's relatively expensive to use in large quantities, i.e. with lots of Sprites at a high frequency. - * It should be fine for low-volume testing where physics isn't required. - * - * @method - * @param {Phaser.Sprite|Phaser.Image|Phaser.TileSprite|Phaser.Button|PIXI.DisplayObject} displayObject - The display object to check against. - * @return {boolean} True if the bounds of this Game Object intersects at any point with the bounds of the given display object. - */ + * Checks to see if the bounds of this Game Object overlaps with the bounds of the given Display Object, + * which can be a Sprite, Image, TileSprite or anything that extends those such as Button or provides a `getBounds` method and result. + * + * This check ignores the `hitArea` property if set and runs a `getBounds` comparison on both objects to determine the result. + * + * Therefore it's relatively expensive to use in large quantities, i.e. with lots of Sprites at a high frequency. + * It should be fine for low-volume testing where physics isn't required. + * + * @method + * @param {Phaser.Sprite|Phaser.Image|Phaser.TileSprite|Phaser.Button|PIXI.DisplayObject} displayObject - The display object to check against. + * @return {boolean} True if the bounds of this Game Object intersects at any point with the bounds of the given display object. + */ overlap: function (displayObject) { - return Phaser.Rectangle.intersects(this.getBounds(), displayObject.getBounds()); - } }; diff --git a/src/gameobjects/components/PhysicsBody.js b/src/gameobjects/components/PhysicsBody.js index b325465c0..a9a4477cf 100644 --- a/src/gameobjects/components/PhysicsBody.js +++ b/src/gameobjects/components/PhysicsBody.js @@ -1,15 +1,15 @@ /** -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* The PhysicsBody component manages the Game Objects physics body and physics enabling. -* It also overrides the x and y properties, ensuring that any manual adjustment of them is reflected in the physics body itself. -* -* @class -*/ + * The PhysicsBody component manages the Game Objects physics body and physics enabling. + * It also overrides the x and y properties, ensuring that any manual adjustment of them is reflected in the physics body itself. + * + * @class + */ Phaser.Component.PhysicsBody = function () {}; /** @@ -20,7 +20,6 @@ Phaser.Component.PhysicsBody = function () {}; */ Phaser.Component.PhysicsBody.preUpdate = function () { - if (this.pendingDestroy) { this.destroy(); @@ -58,7 +57,6 @@ Phaser.Component.PhysicsBody.preUpdate = function () } return true; - }; /** @@ -69,89 +67,79 @@ Phaser.Component.PhysicsBody.preUpdate = function () */ Phaser.Component.PhysicsBody.postUpdate = function () { - if (this.exists && this.body) { this.body.postUpdate(); } - }; Phaser.Component.PhysicsBody.prototype = { /** - * `body` is the Game Objects physics body. Once a Game Object is enabled for physics you access all associated - * properties and methods via it. - * - * By default Game Objects won't add themselves to any physics system and their `body` property will be `null`. - * - * To enable this Game Object for physics you need to call `game.physics.enable(object, system)` where `object` is this object - * and `system` is the Physics system you are using. If none is given it defaults to `Phaser.Physics.Arcade`. - * - * You can alternatively call `game.physics.arcade.enable(object)`, or add this Game Object to a physics enabled Group. - * - * Important: Enabling a Game Object for P2 or Ninja physics will automatically set its `anchor` property to 0.5, - * so the physics body is centered on the Game Object. - * - * If you need a different result then adjust or re-create the Body shape offsets manually or reset the anchor after enabling physics. - * - * @property {Phaser.Physics.Arcade.Body|Phaser.Physics.P2.Body|Phaser.Physics.Ninja.Body|null} body - * @default - */ + * `body` is the Game Objects physics body. Once a Game Object is enabled for physics you access all associated + * properties and methods via it. + * + * By default Game Objects won't add themselves to any physics system and their `body` property will be `null`. + * + * To enable this Game Object for physics you need to call `game.physics.enable(object, system)` where `object` is this object + * and `system` is the Physics system you are using. If none is given it defaults to `Phaser.Physics.Arcade`. + * + * You can alternatively call `game.physics.arcade.enable(object)`, or add this Game Object to a physics enabled Group. + * + * Important: Enabling a Game Object for P2 or Ninja physics will automatically set its `anchor` property to 0.5, + * so the physics body is centered on the Game Object. + * + * If you need a different result then adjust or re-create the Body shape offsets manually or reset the anchor after enabling physics. + * + * @property {Phaser.Physics.Arcade.Body|Phaser.Physics.P2.Body|Phaser.Physics.Ninja.Body|null} body + * @default + */ body: null, /** - * The position of the Game Object on the x axis relative to the local coordinates of the parent. - * - * @property {number} x - */ + * The position of the Game Object on the x axis relative to the local coordinates of the parent. + * + * @property {number} x + */ x: { get: function () { - return this.position.x; - }, set: function (value) { - this.position.x = value; if (this.body && !this.body.dirty) { this.body._reset = true; } - } }, /** - * The position of the Game Object on the y axis relative to the local coordinates of the parent. - * - * @property {number} y - */ + * The position of the Game Object on the y axis relative to the local coordinates of the parent. + * + * @property {number} y + */ y: { get: function () { - return this.position.y; - }, set: function (value) { - this.position.y = value; if (this.body && !this.body.dirty) { this.body._reset = true; } - } } diff --git a/src/gameobjects/components/Reset.js b/src/gameobjects/components/Reset.js index 228528801..1515f3e92 100644 --- a/src/gameobjects/components/Reset.js +++ b/src/gameobjects/components/Reset.js @@ -1,35 +1,34 @@ /** -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* The Reset component allows a Game Object to be reset and repositioned to a new location. -* -* @class -*/ + * The Reset component allows a Game Object to be reset and repositioned to a new location. + * + * @class + */ Phaser.Component.Reset = function () {}; /** -* Resets the Game Object. -* -* This moves the Game Object to the given x/y world coordinates and sets `fresh`, `exists`, -* `visible` and `renderable` to true. -* -* If this Game Object has the LifeSpan component it will also set `alive` to true and `health` to the given value. -* -* If this Game Object has a Physics Body it will reset the Body. -* -* @method -* @param {number} x - The x coordinate (in world space) to position the Game Object at. -* @param {number} y - The y coordinate (in world space) to position the Game Object at. -* @param {number} [health=1] - The health to give the Game Object if it has the Health component. -* @return {PIXI.DisplayObject} This instance. -*/ + * Resets the Game Object. + * + * This moves the Game Object to the given x/y world coordinates and sets `fresh`, `exists`, + * `visible` and `renderable` to true. + * + * If this Game Object has the LifeSpan component it will also set `alive` to true and `health` to the given value. + * + * If this Game Object has a Physics Body it will reset the Body. + * + * @method + * @param {number} x - The x coordinate (in world space) to position the Game Object at. + * @param {number} y - The y coordinate (in world space) to position the Game Object at. + * @param {number} [health=1] - The health to give the Game Object if it has the Health component. + * @return {PIXI.DisplayObject} This instance. + */ Phaser.Component.Reset.prototype.reset = function (x, y, health) { - if (health === undefined) { health = 1; } this.world.set(x, y); @@ -60,5 +59,4 @@ Phaser.Component.Reset.prototype.reset = function (x, y, health) } return this; - }; diff --git a/src/gameobjects/components/ScaleMinMax.js b/src/gameobjects/components/ScaleMinMax.js index 2fba7f3e0..26dadeb58 100644 --- a/src/gameobjects/components/ScaleMinMax.js +++ b/src/gameobjects/components/ScaleMinMax.js @@ -1,48 +1,48 @@ /** -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* The ScaleMinMax component allows a Game Object to limit how far it can be scaled by its parent. -* -* @class -*/ + * The ScaleMinMax component allows a Game Object to limit how far it can be scaled by its parent. + * + * @class + */ Phaser.Component.ScaleMinMax = function () {}; Phaser.Component.ScaleMinMax.prototype = { /** - * The callback that will apply any scale limiting to the worldTransform. - * @property {function} transformCallback - */ + * The callback that will apply any scale limiting to the worldTransform. + * @property {function} transformCallback + */ transformCallback: null, /** - * The context under which `transformCallback` is called. - * @property {object} transformCallbackContext - */ + * The context under which `transformCallback` is called. + * @property {object} transformCallbackContext + */ transformCallbackContext: this, /** - * The minimum scale this Game Object will scale down to. - * - * It allows you to prevent a parent from scaling this Game Object lower than the given value. - * - * Set it to `null` to remove the limit. - * @property {Phaser.Point} scaleMin - */ + * The minimum scale this Game Object will scale down to. + * + * It allows you to prevent a parent from scaling this Game Object lower than the given value. + * + * Set it to `null` to remove the limit. + * @property {Phaser.Point} scaleMin + */ scaleMin: null, /** - * The maximum scale this Game Object will scale up to. - * - * It allows you to prevent a parent from scaling this Game Object higher than the given value. - * - * Set it to `null` to remove the limit. - * @property {Phaser.Point} scaleMax - */ + * The maximum scale this Game Object will scale up to. + * + * It allows you to prevent a parent from scaling this Game Object higher than the given value. + * + * Set it to `null` to remove the limit. + * @property {Phaser.Point} scaleMax + */ scaleMax: null, /** @@ -54,7 +54,6 @@ Phaser.Component.ScaleMinMax.prototype = { */ checkTransform: function (wt) { - if (this.scaleMin) { if (wt.a < this.scaleMin.x) @@ -80,7 +79,6 @@ Phaser.Component.ScaleMinMax.prototype = { wt.d = this.scaleMax.y; } } - }, /** @@ -110,7 +108,6 @@ Phaser.Component.ScaleMinMax.prototype = { */ setScaleMinMax: function (minX, minY, maxX, maxY) { - if (minY === undefined) { // 1 parameter, set all to it @@ -160,7 +157,6 @@ Phaser.Component.ScaleMinMax.prototype = { this.transformCallback = this.checkTransform; this.transformCallbackContext = this; } - } }; diff --git a/src/gameobjects/components/Smoothed.js b/src/gameobjects/components/Smoothed.js index e15a6974f..48031a8d8 100644 --- a/src/gameobjects/components/Smoothed.js +++ b/src/gameobjects/components/Smoothed.js @@ -1,39 +1,36 @@ /** -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* The Smoothed component allows a Game Object to control anti-aliasing of an image based texture. -* -* @class -*/ + * The Smoothed component allows a Game Object to control anti-aliasing of an image based texture. + * + * @class + */ Phaser.Component.Smoothed = function () {}; Phaser.Component.Smoothed.prototype = { /** - * Enable or disable texture smoothing for this Game Object. - * - * It only takes effect if the Game Object is using an image based texture. - * - * Smoothing is enabled by default. - * - * @property {boolean} smoothed - */ + * Enable or disable texture smoothing for this Game Object. + * + * It only takes effect if the Game Object is using an image based texture. + * + * Smoothing is enabled by default. + * + * @property {boolean} smoothed + */ smoothed: { get: function () { - return !this.texture.baseTexture.scaleMode; - }, set: function (value) { - if (value) { if (this.texture) diff --git a/src/geom/Circle.js b/src/geom/Circle.js index b54a2f258..d62ceef94 100644 --- a/src/geom/Circle.js +++ b/src/geom/Circle.js @@ -1,46 +1,45 @@ /** -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* Creates a new Circle object with the center coordinate specified by the x and y parameters and the diameter specified by the diameter parameter. -* If you call this function without parameters, a circle with x, y, diameter and radius properties set to 0 is created. -* -* @class Phaser.Circle -* @constructor -* @param {number} [x=0] - The x coordinate of the center of the circle. -* @param {number} [y=0] - The y coordinate of the center of the circle. -* @param {number} [diameter=0] - The diameter of the circle. -*/ + * Creates a new Circle object with the center coordinate specified by the x and y parameters and the diameter specified by the diameter parameter. + * If you call this function without parameters, a circle with x, y, diameter and radius properties set to 0 is created. + * + * @class Phaser.Circle + * @constructor + * @param {number} [x=0] - The x coordinate of the center of the circle. + * @param {number} [y=0] - The y coordinate of the center of the circle. + * @param {number} [diameter=0] - The diameter of the circle. + */ Phaser.Circle = function (x, y, diameter) { - x = x || 0; y = y || 0; diameter = diameter || 0; /** - * @property {number} x - The x coordinate of the center of the circle. - */ + * @property {number} x - The x coordinate of the center of the circle. + */ this.x = x; /** - * @property {number} y - The y coordinate of the center of the circle. - */ + * @property {number} y - The y coordinate of the center of the circle. + */ this.y = y; /** - * @property {number} _diameter - The diameter of the circle. - * @private - */ + * @property {number} _diameter - The diameter of the circle. + * @private + */ this._diameter = diameter; /** - * @property {number} _radius - The radius of the circle. - * @private - */ + * @property {number} _radius - The radius of the circle. + * @private + */ this._radius = 0; if (diameter > 0) @@ -49,39 +48,35 @@ Phaser.Circle = function (x, y, diameter) } /** - * @property {number} type - The const type of this object. - * @readonly - */ + * @property {number} type - The const type of this object. + * @readonly + */ this.type = Phaser.CIRCLE; - }; Phaser.Circle.prototype = { /** - * The circumference of the circle. - * - * @method Phaser.Circle#circumference - * @return {number} The circumference of the circle. - */ + * The circumference of the circle. + * + * @method Phaser.Circle#circumference + * @return {number} The circumference of the circle. + */ circumference: function () { - return 2 * (Math.PI * this._radius); - }, /** - * Returns a uniformly distributed random point from anywhere within this Circle. - * - * @method Phaser.Circle#random - * @param {Phaser.Point|object} [out] - A Phaser.Point, or any object with public x/y properties, that the values will be set in. - * If no object is provided a new Phaser.Point object will be created. In high performance areas avoid this by re-using an existing object. - * @return {Phaser.Point} An object containing the random point in its `x` and `y` properties. - */ + * Returns a uniformly distributed random point from anywhere within this Circle. + * + * @method Phaser.Circle#random + * @param {Phaser.Point|object} [out] - A Phaser.Point, or any object with public x/y properties, that the values will be set in. + * If no object is provided a new Phaser.Point object will be created. In high performance areas avoid this by re-using an existing object. + * @return {Phaser.Point} An object containing the random point in its `x` and `y` properties. + */ random: function (out) { - if (out === undefined) { out = new Phaser.Point(); } var t = 2 * Math.PI * Math.random(); @@ -94,97 +89,85 @@ Phaser.Circle.prototype = { out.y = this.y + (y * this.radius); return out; - }, /** - * Returns the framing rectangle of the circle as a Phaser.Rectangle object. - * - * @method Phaser.Circle#getBounds - * @return {Phaser.Rectangle} The bounds of the Circle. - */ + * Returns the framing rectangle of the circle as a Phaser.Rectangle object. + * + * @method Phaser.Circle#getBounds + * @return {Phaser.Rectangle} The bounds of the Circle. + */ getBounds: function () { - return new Phaser.Rectangle(this.x - this.radius, this.y - this.radius, this.diameter, this.diameter); - }, /** - * Sets the members of Circle to the specified values. - * @method Phaser.Circle#setTo - * @param {number} x - The x coordinate of the center of the circle. - * @param {number} y - The y coordinate of the center of the circle. - * @param {number} diameter - The diameter of the circle. - * @return {Circle} This circle object. - */ + * Sets the members of Circle to the specified values. + * @method Phaser.Circle#setTo + * @param {number} x - The x coordinate of the center of the circle. + * @param {number} y - The y coordinate of the center of the circle. + * @param {number} diameter - The diameter of the circle. + * @return {Circle} This circle object. + */ setTo: function (x, y, diameter) { - this.x = x; this.y = y; this._diameter = diameter; this._radius = diameter * 0.5; return this; - }, /** - * Copies the x, y and diameter properties from any given object to this Circle. - * @method Phaser.Circle#copyFrom - * @param {any} source - The object to copy from. - * @return {Circle} This Circle object. - */ + * Copies the x, y and diameter properties from any given object to this Circle. + * @method Phaser.Circle#copyFrom + * @param {any} source - The object to copy from. + * @return {Circle} This Circle object. + */ copyFrom: function (source) { - return this.setTo(source.x, source.y, source.diameter); - }, /** - * Copies the x, y and diameter properties from this Circle to any given object. - * @method Phaser.Circle#copyTo - * @param {any} dest - The object to copy to. - * @return {object} This dest object. - */ + * Copies the x, y and diameter properties from this Circle to any given object. + * @method Phaser.Circle#copyTo + * @param {any} dest - The object to copy to. + * @return {object} This dest object. + */ copyTo: function (dest) { - dest.x = this.x; dest.y = this.y; dest.diameter = this._diameter; return dest; - }, /** - * Returns the distance from the center of the Circle object to the given object - * (can be Circle, Point or anything with x/y properties) - * @method Phaser.Circle#distance - * @param {object} dest - The target object. Must have visible x and y properties that represent the center of the object. - * @param {boolean} [round=false] - Round the distance to the nearest integer. - * @return {number} The distance between this Point object and the destination Point object. - */ + * Returns the distance from the center of the Circle object to the given object + * (can be Circle, Point or anything with x/y properties) + * @method Phaser.Circle#distance + * @param {object} dest - The target object. Must have visible x and y properties that represent the center of the object. + * @param {boolean} [round=false] - Round the distance to the nearest integer. + * @return {number} The distance between this Point object and the destination Point object. + */ distance: function (dest, round) { - var distance = Phaser.Math.distance(this.x, this.y, dest.x, dest.y); return round ? Math.round(distance) : distance; - }, /** - * Returns a new Circle object with the same values for the x, y, width, and height properties as this Circle object. - * @method Phaser.Circle#clone - * @param {Phaser.Circle} [output] - Optional Circle object. If given the values will be set into the object, otherwise a brand new Circle object will be created and returned. - * @return {Phaser.Circle} The cloned Circle object. - */ + * Returns a new Circle object with the same values for the x, y, width, and height properties as this Circle object. + * @method Phaser.Circle#clone + * @param {Phaser.Circle} [output] - Optional Circle object. If given the values will be set into the object, otherwise a brand new Circle object will be created and returned. + * @return {Phaser.Circle} The cloned Circle object. + */ clone: function (output) { - if (output === undefined || output === null) { output = new Phaser.Circle(this.x, this.y, this.diameter); @@ -195,36 +178,31 @@ Phaser.Circle.prototype = { } return output; - }, /** - * Return true if the given x/y coordinates are within this Circle object. - * @method Phaser.Circle#contains - * @param {number} x - The X value of the coordinate to test. - * @param {number} y - The Y value of the coordinate to test. - * @return {boolean} True if the coordinates are within this circle, otherwise false. - */ + * Return true if the given x/y coordinates are within this Circle object. + * @method Phaser.Circle#contains + * @param {number} x - The X value of the coordinate to test. + * @param {number} y - The Y value of the coordinate to test. + * @return {boolean} True if the coordinates are within this circle, otherwise false. + */ contains: function (x, y) { - return Phaser.Circle.contains(this, x, y); - }, /** - * Returns a Point object containing the coordinates of a point on the circumference of the Circle based on the given angle. - * @method Phaser.Circle#circumferencePoint - * @param {number} angle - The angle in radians (unless asDegrees is true) to return the point from. - * @param {boolean} [asDegrees=false] - Is the given angle in radians (false) or degrees (true)? - * @param {Phaser.Point} [out] - An optional Point object to put the result in to. If none specified a new Point object will be created. - * @return {Phaser.Point} The Point object holding the result. - */ + * Returns a Point object containing the coordinates of a point on the circumference of the Circle based on the given angle. + * @method Phaser.Circle#circumferencePoint + * @param {number} angle - The angle in radians (unless asDegrees is true) to return the point from. + * @param {boolean} [asDegrees=false] - Is the given angle in radians (false) or degrees (true)? + * @param {Phaser.Point} [out] - An optional Point object to put the result in to. If none specified a new Point object will be created. + * @return {Phaser.Point} The Point object holding the result. + */ circumferencePoint: function (angle, asDegrees, out) { - return Phaser.Circle.circumferencePoint(this, angle, asDegrees, out); - }, @@ -244,7 +222,6 @@ Phaser.Circle.prototype = { */ sample: function (steps, startAngle, endAngle, asDegrees, out) { - if (!steps) { steps = 60; } if (startAngle == null) { startAngle = 0; } if (endAngle == null) { endAngle = Phaser.Math.PI2; } @@ -264,42 +241,39 @@ Phaser.Circle.prototype = { } return out; - }, /** - * Adjusts the location of the Circle object, as determined by its center coordinate, by the specified amounts. - * @method Phaser.Circle#offset - * @param {number} dx - Moves the x value of the Circle object by this amount. - * @param {number} dy - Moves the y value of the Circle object by this amount. - * @return {Circle} This Circle object. - */ + * Adjusts the location of the Circle object, as determined by its center coordinate, by the specified amounts. + * @method Phaser.Circle#offset + * @param {number} dx - Moves the x value of the Circle object by this amount. + * @param {number} dy - Moves the y value of the Circle object by this amount. + * @return {Circle} This Circle object. + */ offset: function (dx, dy) { - this.x += dx; this.y += dy; return this; - }, /** - * Adjusts the location of the Circle object using a Point object as a parameter. This method is similar to the Circle.offset() method, except that it takes a Point object as a parameter. - * @method Phaser.Circle#offsetPoint - * @param {Point} point A Point object to use to offset this Circle object (or any valid object with exposed x and y properties). - * @return {Circle} This Circle object. - */ + * Adjusts the location of the Circle object using a Point object as a parameter. This method is similar to the Circle.offset() method, except that it takes a Point object as a parameter. + * @method Phaser.Circle#offsetPoint + * @param {Point} point A Point object to use to offset this Circle object (or any valid object with exposed x and y properties). + * @return {Circle} This Circle object. + */ offsetPoint: function (point) { return this.offset(point.x, point.y); }, /** - * Returns a string representation of this object. - * @method Phaser.Circle#toString - * @return {string} a string representation of the instance. - */ + * Returns a string representation of this object. + * @method Phaser.Circle#toString + * @return {string} a string representation of the instance. + */ toString: function () { return '[{Phaser.Circle (x=' + this.x + ' y=' + this.y + ' diameter=' + this.diameter + ' radius=' + this.radius + ')}]'; @@ -310,11 +284,11 @@ Phaser.Circle.prototype = { Phaser.Circle.prototype.constructor = Phaser.Circle; /** -* The largest distance between any two points on the circle. The same as the radius * 2. -* -* @name Phaser.Circle#diameter -* @property {number} diameter - Gets or sets the diameter of the circle. -*/ + * The largest distance between any two points on the circle. The same as the radius * 2. + * + * @name Phaser.Circle#diameter + * @property {number} diameter - Gets or sets the diameter of the circle. + */ Object.defineProperty(Phaser.Circle.prototype, 'diameter', { get: function () @@ -324,7 +298,6 @@ Object.defineProperty(Phaser.Circle.prototype, 'diameter', { set: function (value) { - if (value > 0) { this._diameter = value; @@ -335,10 +308,10 @@ Object.defineProperty(Phaser.Circle.prototype, 'diameter', { }); /** -* The length of a line extending from the center of the circle to any point on the circle itself. The same as half the diameter. -* @name Phaser.Circle#radius -* @property {number} radius - Gets or sets the radius of the circle. -*/ + * The length of a line extending from the center of the circle to any point on the circle itself. The same as half the diameter. + * @name Phaser.Circle#radius + * @property {number} radius - Gets or sets the radius of the circle. + */ Object.defineProperty(Phaser.Circle.prototype, 'radius', { get: function () @@ -348,22 +321,20 @@ Object.defineProperty(Phaser.Circle.prototype, 'radius', { set: function (value) { - if (value > 0) { this._radius = value; this._diameter = value * 2; } - } }); /** -* The x coordinate of the leftmost point of the circle. Changing the left property of a Circle object has no effect on the x and y properties. However it does affect the diameter, whereas changing the x value does not affect the diameter property. -* @name Phaser.Circle#left -* @propety {number} left - Gets or sets the value of the leftmost point of the circle. -*/ + * The x coordinate of the leftmost point of the circle. Changing the left property of a Circle object has no effect on the x and y properties. However it does affect the diameter, whereas changing the x value does not affect the diameter property. + * @name Phaser.Circle#left + * @propety {number} left - Gets or sets the value of the leftmost point of the circle. + */ Object.defineProperty(Phaser.Circle.prototype, 'left', { get: function () @@ -373,7 +344,6 @@ Object.defineProperty(Phaser.Circle.prototype, 'left', { set: function (value) { - if (value > this.x) { this._radius = 0; @@ -383,16 +353,15 @@ Object.defineProperty(Phaser.Circle.prototype, 'left', { { this.radius = this.x - value; } - } }); /** -* The x coordinate of the rightmost point of the circle. Changing the right property of a Circle object has no effect on the x and y properties. However it does affect the diameter, whereas changing the x value does not affect the diameter property. -* @name Phaser.Circle#right -* @property {number} right - Gets or sets the value of the rightmost point of the circle. -*/ + * The x coordinate of the rightmost point of the circle. Changing the right property of a Circle object has no effect on the x and y properties. However it does affect the diameter, whereas changing the x value does not affect the diameter property. + * @name Phaser.Circle#right + * @property {number} right - Gets or sets the value of the rightmost point of the circle. + */ Object.defineProperty(Phaser.Circle.prototype, 'right', { get: function () @@ -402,7 +371,6 @@ Object.defineProperty(Phaser.Circle.prototype, 'right', { set: function (value) { - if (value < this.x) { this._radius = 0; @@ -412,16 +380,15 @@ Object.defineProperty(Phaser.Circle.prototype, 'right', { { this.radius = value - this.x; } - } }); /** -* The sum of the y minus the radius property. Changing the top property of a Circle object has no effect on the x and y properties, but does change the diameter. -* @name Phaser.Circle#top -* @property {number} top - Gets or sets the top of the circle. -*/ + * The sum of the y minus the radius property. Changing the top property of a Circle object has no effect on the x and y properties, but does change the diameter. + * @name Phaser.Circle#top + * @property {number} top - Gets or sets the top of the circle. + */ Object.defineProperty(Phaser.Circle.prototype, 'top', { get: function () @@ -431,7 +398,6 @@ Object.defineProperty(Phaser.Circle.prototype, 'top', { set: function (value) { - if (value > this.y) { this._radius = 0; @@ -441,16 +407,15 @@ Object.defineProperty(Phaser.Circle.prototype, 'top', { { this.radius = this.y - value; } - } }); /** -* The sum of the y and radius properties. Changing the bottom property of a Circle object has no effect on the x and y properties, but does change the diameter. -* @name Phaser.Circle#bottom -* @property {number} bottom - Gets or sets the bottom of the circle. -*/ + * The sum of the y and radius properties. Changing the bottom property of a Circle object has no effect on the x and y properties, but does change the diameter. + * @name Phaser.Circle#bottom + * @property {number} bottom - Gets or sets the bottom of the circle. + */ Object.defineProperty(Phaser.Circle.prototype, 'bottom', { get: function () @@ -460,7 +425,6 @@ Object.defineProperty(Phaser.Circle.prototype, 'bottom', { set: function (value) { - if (value < this.y) { this._radius = 0; @@ -470,22 +434,20 @@ Object.defineProperty(Phaser.Circle.prototype, 'bottom', { { this.radius = value - this.y; } - } }); /** -* The area of this Circle. -* @name Phaser.Circle#area -* @property {number} area - The area of this circle. -* @readonly -*/ + * The area of this Circle. + * @name Phaser.Circle#area + * @property {number} area - The area of this circle. + * @readonly + */ Object.defineProperty(Phaser.Circle.prototype, 'area', { get: function () { - if (this._radius > 0) { return Math.PI * this._radius * this._radius; @@ -494,17 +456,16 @@ Object.defineProperty(Phaser.Circle.prototype, 'area', { { return 0; } - } }); /** -* Determines whether or not this Circle object is empty. Will return a value of true if the Circle objects diameter is less than or equal to 0; otherwise false. -* If set to true it will reset all of the Circle objects properties to 0. A Circle object is empty if its diameter is less than or equal to 0. -* @name Phaser.Circle#empty -* @property {boolean} empty - Gets or sets the empty state of the circle. -*/ + * Determines whether or not this Circle object is empty. Will return a value of true if the Circle objects diameter is less than or equal to 0; otherwise false. + * If set to true it will reset all of the Circle objects properties to 0. A Circle object is empty if its diameter is less than or equal to 0. + * @name Phaser.Circle#empty + * @property {boolean} empty - Gets or sets the empty state of the circle. + */ Object.defineProperty(Phaser.Circle.prototype, 'empty', { get: function () @@ -514,27 +475,24 @@ Object.defineProperty(Phaser.Circle.prototype, 'empty', { set: function (value) { - if (value === true) { this.setTo(0, 0, 0); } - } }); /** -* Return true if the given x/y coordinates are within the Circle object. -* @method Phaser.Circle.contains -* @param {Phaser.Circle} a - The Circle to be checked. -* @param {number} x - The X value of the coordinate to test. -* @param {number} y - The Y value of the coordinate to test. -* @return {boolean} True if the coordinates are within this circle, otherwise false. -*/ + * Return true if the given x/y coordinates are within the Circle object. + * @method Phaser.Circle.contains + * @param {Phaser.Circle} a - The Circle to be checked. + * @param {number} x - The X value of the coordinate to test. + * @param {number} y - The Y value of the coordinate to test. + * @return {boolean} True if the coordinates are within this circle, otherwise false. + */ Phaser.Circle.contains = function (a, x, y) { - // Check if x/y are within the bounds first if (a.radius > 0 && x >= a.left && x <= a.right && y >= a.top && y <= a.bottom) { @@ -547,50 +505,44 @@ Phaser.Circle.contains = function (a, x, y) { return false; } - }; /** -* Determines whether the two Circle objects match. This method compares the x, y and diameter properties. -* @method Phaser.Circle.equals -* @param {Phaser.Circle} a - The first Circle object. -* @param {Phaser.Circle} b - The second Circle object. -* @return {boolean} A value of true if the object has exactly the same values for the x, y and diameter properties as this Circle object; otherwise false. -*/ + * Determines whether the two Circle objects match. This method compares the x, y and diameter properties. + * @method Phaser.Circle.equals + * @param {Phaser.Circle} a - The first Circle object. + * @param {Phaser.Circle} b - The second Circle object. + * @return {boolean} A value of true if the object has exactly the same values for the x, y and diameter properties as this Circle object; otherwise false. + */ Phaser.Circle.equals = function (a, b) { - return (a.x === b.x && a.y === b.y && a.diameter === b.diameter); - }; /** -* Determines whether the two Circle objects intersect. -* This method checks the radius distances between the two Circle objects to see if they intersect. -* @method Phaser.Circle.intersects -* @param {Phaser.Circle} a - The first Circle object. -* @param {Phaser.Circle} b - The second Circle object. -* @return {boolean} A value of true if the specified object intersects with this Circle object; otherwise false. -*/ + * Determines whether the two Circle objects intersect. + * This method checks the radius distances between the two Circle objects to see if they intersect. + * @method Phaser.Circle.intersects + * @param {Phaser.Circle} a - The first Circle object. + * @param {Phaser.Circle} b - The second Circle object. + * @return {boolean} A value of true if the specified object intersects with this Circle object; otherwise false. + */ Phaser.Circle.intersects = function (a, b) { - return (Phaser.Math.distance(a.x, a.y, b.x, b.y) <= (a.radius + b.radius)); - }; /** -* Returns a Point object containing the coordinates of a point on the circumference of the Circle based on the given angle. -* @method Phaser.Circle.circumferencePoint -* @param {Phaser.Circle} a - The first Circle object. -* @param {number} angle - The angle in radians (unless asDegrees is true) to return the point from. -* @param {boolean} [asDegrees=false] - Is the given angle in radians (false) or degrees (true)? -* @param {Phaser.Point} [out] - An optional Point object to put the result in to. If none specified a new Point object will be created. -* @return {Phaser.Point} The Point object holding the result. -*/ + * Returns a Point object containing the coordinates of a point on the circumference of the Circle based on the given angle. + * @method Phaser.Circle.circumferencePoint + * @param {Phaser.Circle} a - The first Circle object. + * @param {number} angle - The angle in radians (unless asDegrees is true) to return the point from. + * @param {boolean} [asDegrees=false] - Is the given angle in radians (false) or degrees (true)? + * @param {Phaser.Point} [out] - An optional Point object to put the result in to. If none specified a new Point object will be created. + * @return {Phaser.Point} The Point object holding the result. + */ Phaser.Circle.circumferencePoint = function (a, angle, asDegrees, out) { - if (asDegrees === undefined) { asDegrees = false; } if (out === undefined) { out = new Phaser.Point(); } @@ -603,19 +555,17 @@ Phaser.Circle.circumferencePoint = function (a, angle, asDegrees, out) out.y = a.y + a.radius * Math.sin(angle); return out; - }; /** -* Checks if the given Circle and Rectangle objects intersect. -* @method Phaser.Circle.intersectsRectangle -* @param {Phaser.Circle} c - The Circle object to test. -* @param {Phaser.Rectangle} r - The Rectangle object to test. -* @return {boolean} True if the two objects intersect, otherwise false. -*/ + * Checks if the given Circle and Rectangle objects intersect. + * @method Phaser.Circle.intersectsRectangle + * @param {Phaser.Circle} c - The Circle object to test. + * @param {Phaser.Rectangle} r - The Rectangle object to test. + * @return {boolean} True if the two objects intersect, otherwise false. + */ Phaser.Circle.intersectsRectangle = function (c, r) { - var cx = Math.abs(c.x - r.x - r.halfWidth); var xDist = r.halfWidth + c.radius; @@ -644,17 +594,16 @@ Phaser.Circle.intersectsRectangle = function (c, r) var maxCornerDistSq = c.radius * c.radius; return xCornerDistSq + yCornerDistSq <= maxCornerDistSq; - }; /** -* Checks if the given Circle and Line objects intersect. -* @method Phaser.Circle.intersectsLine -* @param {Phaser.Circle} c - The Circle object to test. -* @param {Phaser.Line} l - The Line object to test. -* @param {boolean} [returnpoints] - optional Array Object, Return an array of intersection points if true, otherwise return boolean. -* @return {boolean} True if the two objects intersect, otherwise false. -*/ + * Checks if the given Circle and Line objects intersect. + * @method Phaser.Circle.intersectsLine + * @param {Phaser.Circle} c - The Circle object to test. + * @param {Phaser.Line} l - The Line object to test. + * @param {boolean} [returnpoints] - optional Array Object, Return an array of intersection points if true, otherwise return boolean. + * @return {boolean} True if the two objects intersect, otherwise false. + */ Phaser.Circle.intersectsLine = function (c, l, returnPoints) { var h = c.x; diff --git a/src/geom/Ellipse.js b/src/geom/Ellipse.js index 97ad7514c..fb8cc9ec4 100644 --- a/src/geom/Ellipse.js +++ b/src/geom/Ellipse.js @@ -1,133 +1,122 @@ /** -* @author Richard Davey -* @author Chad Engler -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @author Chad Engler + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* Creates a Ellipse object. A curve on a plane surrounding two focal points. -* -* @class Phaser.Ellipse -* @constructor -* @param {number} [x=0] - The X coordinate of the upper-left corner of the framing rectangle of this ellipse. -* @param {number} [y=0] - The Y coordinate of the upper-left corner of the framing rectangle of this ellipse. -* @param {number} [width=0] - The overall width of this ellipse. -* @param {number} [height=0] - The overall height of this ellipse. -*/ + * Creates a Ellipse object. A curve on a plane surrounding two focal points. + * + * @class Phaser.Ellipse + * @constructor + * @param {number} [x=0] - The X coordinate of the upper-left corner of the framing rectangle of this ellipse. + * @param {number} [y=0] - The Y coordinate of the upper-left corner of the framing rectangle of this ellipse. + * @param {number} [width=0] - The overall width of this ellipse. + * @param {number} [height=0] - The overall height of this ellipse. + */ Phaser.Ellipse = function (x, y, width, height) { - x = x || 0; y = y || 0; width = width || 0; height = height || 0; /** - * @property {number} x - The X coordinate of the upper-left corner of the framing rectangle of this ellipse. - */ + * @property {number} x - The X coordinate of the upper-left corner of the framing rectangle of this ellipse. + */ this.x = x; /** - * @property {number} y - The Y coordinate of the upper-left corner of the framing rectangle of this ellipse. - */ + * @property {number} y - The Y coordinate of the upper-left corner of the framing rectangle of this ellipse. + */ this.y = y; /** - * @property {number} width - The overall width of this ellipse. - */ + * @property {number} width - The overall width of this ellipse. + */ this.width = width; /** - * @property {number} height - The overall height of this ellipse. - */ + * @property {number} height - The overall height of this ellipse. + */ this.height = height; /** - * @property {number} type - The const type of this object. - * @readonly - */ + * @property {number} type - The const type of this object. + * @readonly + */ this.type = Phaser.ELLIPSE; - }; Phaser.Ellipse.prototype = { /** - * Sets the members of the Ellipse to the specified values. - * @method Phaser.Ellipse#setTo - * @param {number} x - The X coordinate of the upper-left corner of the framing rectangle of this ellipse. - * @param {number} y - The Y coordinate of the upper-left corner of the framing rectangle of this ellipse. - * @param {number} width - The overall width of this ellipse. - * @param {number} height - The overall height of this ellipse. - * @return {Phaser.Ellipse} This Ellipse object. - */ + * Sets the members of the Ellipse to the specified values. + * @method Phaser.Ellipse#setTo + * @param {number} x - The X coordinate of the upper-left corner of the framing rectangle of this ellipse. + * @param {number} y - The Y coordinate of the upper-left corner of the framing rectangle of this ellipse. + * @param {number} width - The overall width of this ellipse. + * @param {number} height - The overall height of this ellipse. + * @return {Phaser.Ellipse} This Ellipse object. + */ setTo: function (x, y, width, height) { - this.x = x; this.y = y; this.width = width; this.height = height; return this; - }, /** - * Returns the framing rectangle of the ellipse as a Phaser.Rectangle object. - * - * @method Phaser.Ellipse#getBounds - * @return {Phaser.Rectangle} The bounds of the Ellipse. - */ + * Returns the framing rectangle of the ellipse as a Phaser.Rectangle object. + * + * @method Phaser.Ellipse#getBounds + * @return {Phaser.Rectangle} The bounds of the Ellipse. + */ getBounds: function () { - return new Phaser.Rectangle(this.x - this.width, this.y - this.height, this.width, this.height); - }, /** - * Copies the x, y, width and height properties from any given object to this Ellipse. - * - * @method Phaser.Ellipse#copyFrom - * @param {any} source - The object to copy from. - * @return {Phaser.Ellipse} This Ellipse object. - */ + * Copies the x, y, width and height properties from any given object to this Ellipse. + * + * @method Phaser.Ellipse#copyFrom + * @param {any} source - The object to copy from. + * @return {Phaser.Ellipse} This Ellipse object. + */ copyFrom: function (source) { - return this.setTo(source.x, source.y, source.width, source.height); - }, /** - * Copies the x, y, width and height properties from this Ellipse to any given object. - * @method Phaser.Ellipse#copyTo - * @param {any} dest - The object to copy to. - * @return {object} This dest object. - */ + * Copies the x, y, width and height properties from this Ellipse to any given object. + * @method Phaser.Ellipse#copyTo + * @param {any} dest - The object to copy to. + * @return {object} This dest object. + */ copyTo: function (dest) { - dest.x = this.x; dest.y = this.y; dest.width = this.width; dest.height = this.height; return dest; - }, /** - * Returns a new Ellipse object with the same values for the x, y, width, and height properties as this Ellipse object. - * @method Phaser.Ellipse#clone - * @param {Phaser.Ellipse} [output] - Optional Ellipse object. If given the values will be set into the object, otherwise a brand new Ellipse object will be created and returned. - * @return {Phaser.Ellipse} The cloned Ellipse object. - */ + * Returns a new Ellipse object with the same values for the x, y, width, and height properties as this Ellipse object. + * @method Phaser.Ellipse#clone + * @param {Phaser.Ellipse} [output] - Optional Ellipse object. If given the values will be set into the object, otherwise a brand new Ellipse object will be created and returned. + * @return {Phaser.Ellipse} The cloned Ellipse object. + */ clone: function (output) { - if (output === undefined || output === null) { output = new Phaser.Ellipse(this.x, this.y, this.width, this.height); @@ -138,35 +127,31 @@ Phaser.Ellipse.prototype = { } return output; - }, /** - * Return true if the given x/y coordinates are within this Ellipse object. - * - * @method Phaser.Ellipse#contains - * @param {number} x - The X value of the coordinate to test. - * @param {number} y - The Y value of the coordinate to test. - * @return {boolean} True if the coordinates are within this ellipse, otherwise false. - */ + * Return true if the given x/y coordinates are within this Ellipse object. + * + * @method Phaser.Ellipse#contains + * @param {number} x - The X value of the coordinate to test. + * @param {number} y - The Y value of the coordinate to test. + * @return {boolean} True if the coordinates are within this ellipse, otherwise false. + */ contains: function (x, y) { - return Phaser.Ellipse.contains(this, x, y); - }, /** - * Returns a uniformly distributed random point from anywhere within this Ellipse. - * - * @method Phaser.Ellipse#random - * @param {Phaser.Point|object} [out] - A Phaser.Point, or any object with public x/y properties, that the values will be set in. - * If no object is provided a new Phaser.Point object will be created. In high performance areas avoid this by re-using an existing object. - * @return {Phaser.Point} An object containing the random point in its `x` and `y` properties. - */ + * Returns a uniformly distributed random point from anywhere within this Ellipse. + * + * @method Phaser.Ellipse#random + * @param {Phaser.Point|object} [out] - A Phaser.Point, or any object with public x/y properties, that the values will be set in. + * If no object is provided a new Phaser.Point object will be created. In high performance areas avoid this by re-using an existing object. + * @return {Phaser.Point} An object containing the random point in its `x` and `y` properties. + */ random: function (out) { - if (out === undefined) { out = new Phaser.Point(); } var p = Math.random() * Math.PI * 2; @@ -176,14 +161,13 @@ Phaser.Ellipse.prototype = { out.y = this.centerY + 0.5 * r * Math.sin(p) * this.height; return out; - }, /** - * Returns a string representation of this object. - * @method Phaser.Ellipse#toString - * @return {string} A string representation of the instance. - */ + * Returns a string representation of this object. + * @method Phaser.Ellipse#toString + * @return {string} A string representation of the instance. + */ toString: function () { return '[{Phaser.Ellipse (x=' + this.x + ' y=' + this.y + ' width=' + this.width + ' height=' + this.height + ')}]'; @@ -194,10 +178,10 @@ Phaser.Ellipse.prototype = { Phaser.Ellipse.prototype.constructor = Phaser.Ellipse; /** -* The left coordinate of the Ellipse. The same as the X coordinate. -* @name Phaser.Ellipse#left -* @propety {number} left - Gets or sets the value of the leftmost point of the ellipse. -*/ + * The left coordinate of the Ellipse. The same as the X coordinate. + * @name Phaser.Ellipse#left + * @propety {number} left - Gets or sets the value of the leftmost point of the ellipse. + */ Object.defineProperty(Phaser.Ellipse.prototype, 'left', { get: function () @@ -207,18 +191,16 @@ Object.defineProperty(Phaser.Ellipse.prototype, 'left', { set: function (value) { - this.x = value; - } }); /** -* The x coordinate of the rightmost point of the Ellipse. Changing the right property of an Ellipse object has no effect on the x property, but does adjust the width. -* @name Phaser.Ellipse#right -* @property {number} right - Gets or sets the value of the rightmost point of the ellipse. -*/ + * The x coordinate of the rightmost point of the Ellipse. Changing the right property of an Ellipse object has no effect on the x property, but does adjust the width. + * @name Phaser.Ellipse#right + * @property {number} right - Gets or sets the value of the rightmost point of the ellipse. + */ Object.defineProperty(Phaser.Ellipse.prototype, 'right', { get: function () @@ -228,7 +210,6 @@ Object.defineProperty(Phaser.Ellipse.prototype, 'right', { set: function (value) { - if (value < this.x) { this.width = 0; @@ -242,10 +223,10 @@ Object.defineProperty(Phaser.Ellipse.prototype, 'right', { }); /** -* The top of the Ellipse. The same as its y property. -* @name Phaser.Ellipse#top -* @property {number} top - Gets or sets the top of the ellipse. -*/ + * The top of the Ellipse. The same as its y property. + * @name Phaser.Ellipse#top + * @property {number} top - Gets or sets the top of the ellipse. + */ Object.defineProperty(Phaser.Ellipse.prototype, 'top', { get: function () @@ -261,10 +242,10 @@ Object.defineProperty(Phaser.Ellipse.prototype, 'top', { }); /** -* The sum of the y and height properties. Changing the bottom property of an Ellipse doesn't adjust the y property, but does change the height. -* @name Phaser.Ellipse#bottom -* @property {number} bottom - Gets or sets the bottom of the ellipse. -*/ + * The sum of the y and height properties. Changing the bottom property of an Ellipse doesn't adjust the y property, but does change the height. + * @name Phaser.Ellipse#bottom + * @property {number} bottom - Gets or sets the bottom of the ellipse. + */ Object.defineProperty(Phaser.Ellipse.prototype, 'bottom', { get: function () @@ -274,7 +255,6 @@ Object.defineProperty(Phaser.Ellipse.prototype, 'bottom', { set: function (value) { - if (value < this.y) { this.height = 0; @@ -288,11 +268,11 @@ Object.defineProperty(Phaser.Ellipse.prototype, 'bottom', { }); /** -* The x coordinate of the center of the Ellipse. -* @name Phaser.Ellipse#centerX -* @property {number} centerX -* @readonly -*/ + * The x coordinate of the center of the Ellipse. + * @name Phaser.Ellipse#centerX + * @property {number} centerX + * @readonly + */ Object.defineProperty(Phaser.Ellipse.prototype, 'centerX', { get: function () @@ -303,11 +283,11 @@ Object.defineProperty(Phaser.Ellipse.prototype, 'centerX', { }); /** -* The y coordinate of the center of the Ellipse. -* @name Phaser.Ellipse#centerY -* @property {number} centerY -* @readonly -*/ + * The y coordinate of the center of the Ellipse. + * @name Phaser.Ellipse#centerY + * @property {number} centerY + * @readonly + */ Object.defineProperty(Phaser.Ellipse.prototype, 'centerY', { get: function () @@ -318,11 +298,11 @@ Object.defineProperty(Phaser.Ellipse.prototype, 'centerY', { }); /** -* Determines whether or not this Ellipse object is empty. Will return a value of true if the Ellipse objects dimensions are less than or equal to 0; otherwise false. -* If set to true it will reset all of the Ellipse objects properties to 0. An Ellipse object is empty if its width or height is less than or equal to 0. -* @name Phaser.Ellipse#empty -* @property {boolean} empty - Gets or sets the empty state of the ellipse. -*/ + * Determines whether or not this Ellipse object is empty. Will return a value of true if the Ellipse objects dimensions are less than or equal to 0; otherwise false. + * If set to true it will reset all of the Ellipse objects properties to 0. An Ellipse object is empty if its width or height is less than or equal to 0. + * @name Phaser.Ellipse#empty + * @property {boolean} empty - Gets or sets the empty state of the ellipse. + */ Object.defineProperty(Phaser.Ellipse.prototype, 'empty', { get: function () @@ -332,28 +312,25 @@ Object.defineProperty(Phaser.Ellipse.prototype, 'empty', { set: function (value) { - if (value === true) { this.setTo(0, 0, 0, 0); } - } }); /** -* Return true if the given x/y coordinates are within the Ellipse object. -* -* @method Phaser.Ellipse.contains -* @param {Phaser.Ellipse} a - The Ellipse to be checked. -* @param {number} x - The X value of the coordinate to test. -* @param {number} y - The Y value of the coordinate to test. -* @return {boolean} True if the coordinates are within this ellipse, otherwise false. -*/ + * Return true if the given x/y coordinates are within the Ellipse object. + * + * @method Phaser.Ellipse.contains + * @param {Phaser.Ellipse} a - The Ellipse to be checked. + * @param {number} x - The X value of the coordinate to test. + * @param {number} y - The Y value of the coordinate to test. + * @return {boolean} True if the coordinates are within this ellipse, otherwise false. + */ Phaser.Ellipse.contains = function (a, x, y) { - if (a.width <= 0 || a.height <= 0) { return false; @@ -367,17 +344,16 @@ Phaser.Ellipse.contains = function (a, x, y) normy *= normy; return (normx + normy < 0.25); - }; /** -* Checks if the given Ellipse and Line objects intersect. -* @method Phaser.Ellipse.intersectsLine -* @param {Phaser.Ellipse} e - The Ellipse object to test. -* @param {Phaser.Line} l - The Line object to test. -* @param {boolean} [returnPoints] - optional Array Object, Return an array of intersection points if true, otherwise return boolean. -* @return {boolean} True if the two objects intersect, otherwise false. -*/ + * Checks if the given Ellipse and Line objects intersect. + * @method Phaser.Ellipse.intersectsLine + * @param {Phaser.Ellipse} e - The Ellipse object to test. + * @param {Phaser.Line} l - The Line object to test. + * @param {boolean} [returnPoints] - optional Array Object, Return an array of intersection points if true, otherwise return boolean. + * @return {boolean} True if the two objects intersect, otherwise false. + */ Phaser.Ellipse.intersectsLine = function (e, l, returnPoints) { var h = e.x; diff --git a/src/geom/Hermite.js b/src/geom/Hermite.js index 1eb7a4488..c782ffe43 100644 --- a/src/geom/Hermite.js +++ b/src/geom/Hermite.js @@ -1,120 +1,118 @@ /** -* @author Richard Davey -* @author Pete Baron -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @author Pete Baron + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* A data representation of a Hermite Curve (see http://en.wikipedia.org/wiki/Cubic_Hermite_spline) -* -* A Hermite curve has a start and end point and tangent vectors for both of them. -* The curve will always pass through the two control points and the shape of it is controlled -* by the length and direction of the tangent vectors. At the control points the curve will -* be facing exactly in the vector direction. -* -* As these curves change speed (speed = distance between points separated by an equal change in -* 't' value - see Hermite.getPoint) this class attempts to reduce the variation by pre-calculating -* the `accuracy` number of points on the curve. The straight-line distances to these points are stored -* in the private 'points' array, and this information is used by Hermite.findT() to convert a pixel -* distance along the curve into a 'time' value. -* -* Higher `accuracy` values will result in more even movement, but require more memory for the points -* list. 5 works, but 10 seems to be an ideal value for the length of curves found in most games on -* a desktop screen. If you use very long curves (more than 400 pixels) you may need to increase -* this value further. -* -* @class Phaser.Hermite -* @constructor -* @param {number} p1x - The x coordinate of the start of the curve. -* @param {number} p1y - The y coordinate of the start of the curve. -* @param {number} p2x - The x coordinate of the end of the curve. -* @param {number} p2y - The y coordinate of the end of the curve. -* @param {number} v1x - The x component of the tangent vector for the start of the curve. -* @param {number} v1y - The y component of the tangent vector for the start of the curve. -* @param {number} v2x - The x component of the tangent vector for the end of the curve. -* @param {number} v2y - The y component of the tangent vector for the end of the curve. -* @param {number} [accuracy=10] The amount of points to pre-calculate on the curve. -*/ + * A data representation of a Hermite Curve (see http://en.wikipedia.org/wiki/Cubic_Hermite_spline) + * + * A Hermite curve has a start and end point and tangent vectors for both of them. + * The curve will always pass through the two control points and the shape of it is controlled + * by the length and direction of the tangent vectors. At the control points the curve will + * be facing exactly in the vector direction. + * + * As these curves change speed (speed = distance between points separated by an equal change in + * 't' value - see Hermite.getPoint) this class attempts to reduce the variation by pre-calculating + * the `accuracy` number of points on the curve. The straight-line distances to these points are stored + * in the private 'points' array, and this information is used by Hermite.findT() to convert a pixel + * distance along the curve into a 'time' value. + * + * Higher `accuracy` values will result in more even movement, but require more memory for the points + * list. 5 works, but 10 seems to be an ideal value for the length of curves found in most games on + * a desktop screen. If you use very long curves (more than 400 pixels) you may need to increase + * this value further. + * + * @class Phaser.Hermite + * @constructor + * @param {number} p1x - The x coordinate of the start of the curve. + * @param {number} p1y - The y coordinate of the start of the curve. + * @param {number} p2x - The x coordinate of the end of the curve. + * @param {number} p2y - The y coordinate of the end of the curve. + * @param {number} v1x - The x component of the tangent vector for the start of the curve. + * @param {number} v1y - The y component of the tangent vector for the start of the curve. + * @param {number} v2x - The x component of the tangent vector for the end of the curve. + * @param {number} v2y - The y component of the tangent vector for the end of the curve. + * @param {number} [accuracy=10] The amount of points to pre-calculate on the curve. + */ Phaser.Hermite = function (p1x, p1y, p2x, p2y, v1x, v1y, v2x, v2y, accuracy) { - if (accuracy === undefined) { accuracy = 10; } /** - * @property {number} _accuracy - The amount of points to pre-calculate on the curve. - * @private - */ + * @property {number} _accuracy - The amount of points to pre-calculate on the curve. + * @private + */ this._accuracy = accuracy; /** - * @property {number} _p1x - The x coordinate of the start of the curve. - * @private - */ + * @property {number} _p1x - The x coordinate of the start of the curve. + * @private + */ this._p1x = p1x; /** - * @property {number} _p1y - The y coordinate of the start of the curve. - * @private - */ + * @property {number} _p1y - The y coordinate of the start of the curve. + * @private + */ this._p1y = p1y; /** - * @property {number} _p2x - The x coordinate of the end of the curve. - * @private - */ + * @property {number} _p2x - The x coordinate of the end of the curve. + * @private + */ this._p2x = p2x; /** - * @property {number} _p2y - The y coordinate of the end of the curve. - * @private - */ + * @property {number} _p2y - The y coordinate of the end of the curve. + * @private + */ this._p2y = p2y; /** - * @property {number} _v1x - The x component of the tangent vector for the start of the curve. - * @private - */ + * @property {number} _v1x - The x component of the tangent vector for the start of the curve. + * @private + */ this._v1x = v1x; /** - * @property {number} _v1y - The y component of the tangent vector for the start of the curve. - * @private - */ + * @property {number} _v1y - The y component of the tangent vector for the start of the curve. + * @private + */ this._v1y = v1y; /** - * @property {number} _v2x - The x component of the tangent vector for the end of the curve. - * @private - */ + * @property {number} _v2x - The x component of the tangent vector for the end of the curve. + * @private + */ this._v2x = v2x; /** - * @property {number} _v2y - The y component of the tangent vector for the end of the curve. - * @private - */ + * @property {number} _v2y - The y component of the tangent vector for the end of the curve. + * @private + */ this._v2y = v2y; /** - * @property {array} _points - A local array of cached points. - * @private - */ + * @property {array} _points - A local array of cached points. + * @private + */ this._points = []; /** - * @property {Phaser.Point} _temp1 - A local cached Point object. - * @private - */ + * @property {Phaser.Point} _temp1 - A local cached Point object. + * @private + */ this._temp1 = new Phaser.Point(); /** - * @property {Phaser.Point} _temp2 - A local cached Point object. - * @private - */ + * @property {Phaser.Point} _temp2 - A local cached Point object. + * @private + */ this._temp2 = new Phaser.Point(); this.recalculate(); - }; Phaser.Hermite.prototype.constructor = Phaser.Hermite; @@ -122,18 +120,17 @@ Phaser.Hermite.prototype.constructor = Phaser.Hermite; Phaser.Hermite.prototype = { /** - * Performs the curve calculations. - * - * This is called automatically if you change any of the curves public properties, such as `Hermite.p1x` or `Hermite.v2y`. - * - * If you adjust any of the internal private values, then call this to update the points. - * - * @method Phaser.Hermite#recalculate - * @return {Phaser.Hermite} This object. - */ + * Performs the curve calculations. + * + * This is called automatically if you change any of the curves public properties, such as `Hermite.p1x` or `Hermite.v2y`. + * + * If you adjust any of the internal private values, then call this to update the points. + * + * @method Phaser.Hermite#recalculate + * @return {Phaser.Hermite} This object. + */ recalculate: function () { - this._ax = (2 * this._p1x - 2 * this._p2x + this._v1x + this._v2x); this._ay = (2 * this._p1y - 2 * this._p2y + this._v1y + this._v2y); this._bx = (-3 * this._p1x + 3 * this._p2x - 2 * this._v1x - this._v2x); @@ -142,18 +139,16 @@ Phaser.Hermite.prototype = { this.length = this.calculateEvenPoints(); return this; - }, /** - * Calculate a number of points along the curve, based on `Hermite.accuracy`, and stores them in the private `_points` array. - * - * @method Phaser.Hermite#calculateEvenPoints - * @return {number} The total length of the curve approximated as straight line distances between the points. - */ + * Calculate a number of points along the curve, based on `Hermite.accuracy`, and stores them in the private `_points` array. + * + * @method Phaser.Hermite#calculateEvenPoints + * @return {number} The total length of the curve approximated as straight line distances between the points. + */ calculateEvenPoints: function () { - var totalLength = 0; this._temp1.setTo(0, 0); // pnt @@ -170,21 +165,19 @@ Phaser.Hermite.prototype = { } return totalLength; - }, /** - * Convert a distance along this curve into a `time` value which will be between 0 and 1. - * - * For example if this curve has a length of 100 pixels then `findT(50)` would return `0.5`. - * - * @method Phaser.Hermite#findT - * @param {integer} distance - The distance into the curve in pixels. Should be a positive integer. - * @return {number} The time (`t`) value, a float between 0 and 1. - */ + * Convert a distance along this curve into a `time` value which will be between 0 and 1. + * + * For example if this curve has a length of 100 pixels then `findT(50)` would return `0.5`. + * + * @method Phaser.Hermite#findT + * @param {integer} distance - The distance into the curve in pixels. Should be a positive integer. + * @return {number} The time (`t`) value, a float between 0 and 1. + */ findT: function (distance) { - if (distance <= 0) { return 0; @@ -208,19 +201,17 @@ Phaser.Hermite.prototype = { var d = distance - this._points[ti - 1]; return ((ti - 1) / this._accuracy) + d / (dt * this._accuracy); - }, /** - * Get the X component of a point on the curve based on the `t` (time) value, which must be between 0 and 1. - * - * @method Phaser.Hermite#getX - * @param {number} [t=0] - The time value along the curve from which to extract a point. This is a value between 0 and 1, where 0 represents the start of the curve and 1 the end. - * @return {number} The X component of a point on the curve based on the `t` (time) value. - */ + * Get the X component of a point on the curve based on the `t` (time) value, which must be between 0 and 1. + * + * @method Phaser.Hermite#getX + * @param {number} [t=0] - The time value along the curve from which to extract a point. This is a value between 0 and 1, where 0 represents the start of the curve and 1 the end. + * @return {number} The X component of a point on the curve based on the `t` (time) value. + */ getX: function (t) { - if (t === undefined) { t = 0; @@ -242,19 +233,17 @@ Phaser.Hermite.prototype = { var t3 = t * t2; return (t3 * this._ax + t2 * this._bx + t * this._v1x + this._p1x); - }, /** - * Get the Y component of a point on the curve based on the `t` (time) value, which must be between 0 and 1. - * - * @method Phaser.Hermite#getY - * @param {number} [t=0] - The time value along the curve from which to extract a point. This is a value between 0 and 1, where 0 represents the start of the curve and 1 the end. - * @return {number} The Y component of a point on the curve based on the `t` (time) value. - */ + * Get the Y component of a point on the curve based on the `t` (time) value, which must be between 0 and 1. + * + * @method Phaser.Hermite#getY + * @param {number} [t=0] - The time value along the curve from which to extract a point. This is a value between 0 and 1, where 0 represents the start of the curve and 1 the end. + * @return {number} The Y component of a point on the curve based on the `t` (time) value. + */ getY: function (t) { - if (t === undefined) { t = 0; @@ -276,20 +265,18 @@ Phaser.Hermite.prototype = { var t3 = t * t2; return (t3 * this._ay + t2 * this._by + t * this._v1y + this._p1y); - }, /** - * Get a point on the curve using the `t` (time) value, which must be between 0 and 1. - * - * @method Phaser.Hermite#getPoint - * @param {number} [t=0] - The time value along the curve from which to extract a point. This is a value between 0 and 1, where 0 represents the start of the curve and 1 the end. - * @param {Phaser.Point|Object} [point] - An optional Phaser.Point, or Object containing public `x` and `y` properties. If given the resulting values will be stored in the Objects `x` and `y` properties. If omitted a new Phaser.Point object is created. - * @return {Phaser.Point} An Object with the x, y coordinate of the curve at the specified `t` value set in its `x` and `y` properties. - */ + * Get a point on the curve using the `t` (time) value, which must be between 0 and 1. + * + * @method Phaser.Hermite#getPoint + * @param {number} [t=0] - The time value along the curve from which to extract a point. This is a value between 0 and 1, where 0 represents the start of the curve and 1 the end. + * @param {Phaser.Point|Object} [point] - An optional Phaser.Point, or Object containing public `x` and `y` properties. If given the resulting values will be stored in the Objects `x` and `y` properties. If omitted a new Phaser.Point object is created. + * @return {Phaser.Point} An Object with the x, y coordinate of the curve at the specified `t` value set in its `x` and `y` properties. + */ getPoint: function (t, point) { - if (t === undefined) { t = 0; } if (point === undefined) { point = new Phaser.Point(); } @@ -310,20 +297,18 @@ Phaser.Hermite.prototype = { point.y = t3 * this._ay + t2 * this._by + t * this._v1y + this._p1y; return point; - }, /** - * Get a point on the curve using the distance, in pixels, along the curve. - * - * @method Phaser.Hermite#getPointWithDistance - * @param {integer} [distance=0] - The distance along the curve to get the point from, given in pixels. - * @param {Phaser.Point|Object} [point] - An optional Phaser.Point, or Object containing public `x` and `y` properties. If given the resulting values will be stored in the Objects `x` and `y` properties. If omitted a new Phaser.Point object is created. - * @return {Phaser.Point} The point on the line at the specified 'distance' along the curve. - */ + * Get a point on the curve using the distance, in pixels, along the curve. + * + * @method Phaser.Hermite#getPointWithDistance + * @param {integer} [distance=0] - The distance along the curve to get the point from, given in pixels. + * @param {Phaser.Point|Object} [point] - An optional Phaser.Point, or Object containing public `x` and `y` properties. If given the resulting values will be stored in the Objects `x` and `y` properties. If omitted a new Phaser.Point object is created. + * @return {Phaser.Point} The point on the line at the specified 'distance' along the curve. + */ getPointWithDistance: function (distance, point) { - if (distance === undefined) { distance = 0; } if (point === undefined) { point = new Phaser.Point(); } @@ -338,38 +323,34 @@ Phaser.Hermite.prototype = { } return point; - }, /** - * Calculate and return the angle, in radians, of the curves tangent based on time. - * - * @method Phaser.Hermite#getAngle - * @param {number} [t=0] - The `t` (time) value at which to find the angle. Must be between 0 and 1. - * @return {number} The angle of the line at the specified `t` time value along the curve. The value is in radians. - */ + * Calculate and return the angle, in radians, of the curves tangent based on time. + * + * @method Phaser.Hermite#getAngle + * @param {number} [t=0] - The `t` (time) value at which to find the angle. Must be between 0 and 1. + * @return {number} The angle of the line at the specified `t` time value along the curve. The value is in radians. + */ getAngle: function (t) { - if (t === undefined) { t = 0; } this.getPoint(t - 0.01, this._temp1); this.getPoint(t + 0.01, this._temp2); return Math.atan2(this._temp2.y - this._temp1.y, this._temp2.x - this._temp1.x); - }, /** - * Calculate and return the angle, in radians, of the curves tangent at the given pixel distance along the curves length. - * - * @method Phaser.Hermite#getAngleWithDistance - * @param {number} [distance=0] - The distance along the curve to get the angle from, in pixels. - * @return {number} The angle of the line at the specified distance along the curve. The value is in radians. - */ + * Calculate and return the angle, in radians, of the curves tangent at the given pixel distance along the curves length. + * + * @method Phaser.Hermite#getAngleWithDistance + * @param {number} [distance=0] - The distance along the curve to get the angle from, in pixels. + * @return {number} The angle of the line at the specified distance along the curve. The value is in radians. + */ getAngleWithDistance: function (distance) { - if (distance === undefined) { distance = 0; } if (distance <= 0) @@ -380,24 +361,21 @@ Phaser.Hermite.prototype = { { return this.getAngle(this.findT(distance)); } - }, /** - * Get the angle of the curves entry point. - * - * @method Phaser.Hermite#getEntryTangent - * @param {Phaser.Point|Object} point - The Phaser.Point object, or an Object with public `x` and `y` properties, in which the tangent vector values will be stored. - * @return {Phaser.Point} A Point object containing the tangent vector of this Hermite curve. - */ + * Get the angle of the curves entry point. + * + * @method Phaser.Hermite#getEntryTangent + * @param {Phaser.Point|Object} point - The Phaser.Point object, or an Object with public `x` and `y` properties, in which the tangent vector values will be stored. + * @return {Phaser.Point} A Point object containing the tangent vector of this Hermite curve. + */ getEntryTangent: function (point) { - point.x = this._v1x; point.y = this._v1y; return point; - } }; @@ -405,235 +383,199 @@ Phaser.Hermite.prototype = { Object.defineProperties(Phaser.Hermite.prototype, { /** - * @name Phaser.Hermite#accuracy - * @property {number} accuracy - The amount of points to pre-calculate on the curve. - */ + * @name Phaser.Hermite#accuracy + * @property {number} accuracy - The amount of points to pre-calculate on the curve. + */ accuracy: { get: function () { - return this._accuracy; - }, set: function (value) { - if (value !== this._accuracy) { this._accuracy = value; this.recalculate(); } - } }, /** - * @name Phaser.Hermite#p1x - * @property {number} p1x - The x coordinate of the start of the curve. Setting this value will recalculate the curve. - */ + * @name Phaser.Hermite#p1x + * @property {number} p1x - The x coordinate of the start of the curve. Setting this value will recalculate the curve. + */ p1x: { get: function () { - return this._p1x; - }, set: function (value) { - if (value !== this._p1x) { this._p1x = value; this.recalculate(); } - } }, /** - * @name Phaser.Hermite#p1y - * @property {number} p1y - The y coordinate of the start of the curve. Setting this value will recalculate the curve. - */ + * @name Phaser.Hermite#p1y + * @property {number} p1y - The y coordinate of the start of the curve. Setting this value will recalculate the curve. + */ p1y: { get: function () { - return this._p1y; - }, set: function (value) { - if (value !== this._p1y) { this._p1y = value; this.recalculate(); } - } }, /** - * @name Phaser.Hermite#p2x - * @property {number} p2x - The x coordinate of the end of the curve. Setting this value will recalculate the curve. - */ + * @name Phaser.Hermite#p2x + * @property {number} p2x - The x coordinate of the end of the curve. Setting this value will recalculate the curve. + */ p2x: { get: function () { - return this._p2x; - }, set: function (value) { - if (value !== this._p2x) { this._p2x = value; this.recalculate(); } - } }, /** - * @name Phaser.Hermite#p2y - * @property {number} p2y - The y coordinate of the end of the curve. Setting this value will recalculate the curve. - */ + * @name Phaser.Hermite#p2y + * @property {number} p2y - The y coordinate of the end of the curve. Setting this value will recalculate the curve. + */ p2y: { get: function () { - return this._p2y; - }, set: function (value) { - if (value !== this._p2y) { this._p2y = value; this.recalculate(); } - } }, /** - * @name Phaser.Hermite#v1x - * @property {number} v1x - The x component of the tangent vector for the start of the curve. Setting this value will recalculate the curve. - */ + * @name Phaser.Hermite#v1x + * @property {number} v1x - The x component of the tangent vector for the start of the curve. Setting this value will recalculate the curve. + */ v1x: { get: function () { - return this._v1x; - }, set: function (value) { - if (value !== this._v1x) { this._v1x = value; this.recalculate(); } - } }, /** - * @name Phaser.Hermite#v1y - * @property {number} v1y - The y component of the tangent vector for the start of the curve. Setting this value will recalculate the curve. - */ + * @name Phaser.Hermite#v1y + * @property {number} v1y - The y component of the tangent vector for the start of the curve. Setting this value will recalculate the curve. + */ v1y: { get: function () { - return this._v1y; - }, set: function (value) { - if (value !== this._v1y) { this._v1y = value; this.recalculate(); } - } }, /** - * @name Phaser.Hermite#v2x - * @property {number} v2x - The x component of the tangent vector for the end of the curve. Setting this value will recalculate the curve. - */ + * @name Phaser.Hermite#v2x + * @property {number} v2x - The x component of the tangent vector for the end of the curve. Setting this value will recalculate the curve. + */ v2x: { get: function () { - return this._v2x; - }, set: function (value) { - if (value !== this._v2x) { this._v2x = value; this.recalculate(); } - } }, /** - * @name Phaser.Hermite#v2y - * @property {number} v2y - The y component of the tangent vector for the end of the curve. Setting this value will recalculate the curve. - */ + * @name Phaser.Hermite#v2y + * @property {number} v2y - The y component of the tangent vector for the end of the curve. Setting this value will recalculate the curve. + */ v2y: { get: function () { - return this._v2y; - }, set: function (value) { - if (value !== this._v2y) { this._v2y = value; this.recalculate(); } - } } diff --git a/src/geom/Line.js b/src/geom/Line.js index df4c9c730..dba153d7c 100644 --- a/src/geom/Line.js +++ b/src/geom/Line.js @@ -1,96 +1,89 @@ /** -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* Creates a new Line object with a start and an end point. -* -* @class Phaser.Line -* @constructor -* @param {number} [x1=0] - The x coordinate of the start of the line. -* @param {number} [y1=0] - The y coordinate of the start of the line. -* @param {number} [x2=0] - The x coordinate of the end of the line. -* @param {number} [y2=0] - The y coordinate of the end of the line. -*/ + * Creates a new Line object with a start and an end point. + * + * @class Phaser.Line + * @constructor + * @param {number} [x1=0] - The x coordinate of the start of the line. + * @param {number} [y1=0] - The y coordinate of the start of the line. + * @param {number} [x2=0] - The x coordinate of the end of the line. + * @param {number} [y2=0] - The y coordinate of the end of the line. + */ Phaser.Line = function (x1, y1, x2, y2) { - x1 = x1 || 0; y1 = y1 || 0; x2 = x2 || 0; y2 = y2 || 0; /** - * @property {Phaser.Point} start - The start point of the line. - */ + * @property {Phaser.Point} start - The start point of the line. + */ this.start = new Phaser.Point(x1, y1); /** - * @property {Phaser.Point} end - The end point of the line. - */ + * @property {Phaser.Point} end - The end point of the line. + */ this.end = new Phaser.Point(x2, y2); /** - * @property {number} type - The const type of this object. - * @readonly - */ + * @property {number} type - The const type of this object. + * @readonly + */ this.type = Phaser.LINE; - }; Phaser.Line.prototype = { /** - * Sets the components of the Line to the specified values. - * - * @method Phaser.Line#setTo - * @param {number} [x1=0] - The x coordinate of the start of the line. - * @param {number} [y1=0] - The y coordinate of the start of the line. - * @param {number} [x2=0] - The x coordinate of the end of the line. - * @param {number} [y2=0] - The y coordinate of the end of the line. - * @return {Phaser.Line} This line object - */ + * Sets the components of the Line to the specified values. + * + * @method Phaser.Line#setTo + * @param {number} [x1=0] - The x coordinate of the start of the line. + * @param {number} [y1=0] - The y coordinate of the start of the line. + * @param {number} [x2=0] - The x coordinate of the end of the line. + * @param {number} [y2=0] - The y coordinate of the end of the line. + * @return {Phaser.Line} This line object + */ setTo: function (x1, y1, x2, y2) { - this.start.setTo(x1, y1); this.end.setTo(x2, y2); return this; - }, /** - * Sets the line to match the x/y coordinates of the two given points. - * - * @param {any} start - A {@link Phaser.Point} or point-like object. - * @param {any} end - A {@link Phaser.Point} or point-like object. - * @return {Phaser.Line} - This line object. - */ + * Sets the line to match the x/y coordinates of the two given points. + * + * @param {any} start - A {@link Phaser.Point} or point-like object. + * @param {any} end - A {@link Phaser.Point} or point-like object. + * @return {Phaser.Line} - This line object. + */ fromPoints: function (start, end) { - this.setTo(start.x, start.y, end.x, end.y); return this; - }, /** - * Sets the line to match the x/y coordinates of the two given sprites. - * Can optionally be calculated from their center coordinates. - * - * @method Phaser.Line#fromSprite - * @param {Phaser.Sprite} startSprite - The coordinates of this Sprite will be set to the Line.start point. - * @param {Phaser.Sprite} endSprite - The coordinates of this Sprite will be set to the Line.start point. - * @param {boolean} [useCenter=false] - If true it will use startSprite.centerX, if false startSprite.x. - * @return {Phaser.Line} This line object - */ + * Sets the line to match the x/y coordinates of the two given sprites. + * Can optionally be calculated from their center coordinates. + * + * @method Phaser.Line#fromSprite + * @param {Phaser.Sprite} startSprite - The coordinates of this Sprite will be set to the Line.start point. + * @param {Phaser.Sprite} endSprite - The coordinates of this Sprite will be set to the Line.start point. + * @param {boolean} [useCenter=false] - If true it will use startSprite.centerX, if false startSprite.x. + * @return {Phaser.Line} This line object + */ fromSprite: function (startSprite, endSprite, useCenter) { - if (useCenter === undefined) { useCenter = false; } if (useCenter) @@ -99,45 +92,41 @@ Phaser.Line.prototype = { } return this.fromPoints(startSprite, endSprite); - }, /** - * Sets this line to start at the given `x` and `y` coordinates and for the segment to extend at `angle` for the given `length`. - * - * @method Phaser.Line#fromAngle - * @param {number} x - The x coordinate of the start of the line. - * @param {number} y - The y coordinate of the start of the line. - * @param {number} angle - The angle of the line in radians. - * @param {number} length - The length of the line in pixels. - * @return {Phaser.Line} This line object - */ + * Sets this line to start at the given `x` and `y` coordinates and for the segment to extend at `angle` for the given `length`. + * + * @method Phaser.Line#fromAngle + * @param {number} x - The x coordinate of the start of the line. + * @param {number} y - The y coordinate of the start of the line. + * @param {number} angle - The angle of the line in radians. + * @param {number} length - The length of the line in pixels. + * @return {Phaser.Line} This line object + */ fromAngle: function (x, y, angle, length) { - this.start.setTo(x, y); this.end.setTo(x + (Math.cos(angle) * length), y + (Math.sin(angle) * length)); return this; - }, /** - * Rotates the line by the amount specified in `angle`. - * - * Rotation takes place from the center of the line. - * If you wish to rotate around a different point see Line.rotateAround. - * - * If you wish to rotate the ends of the Line then see Line.start.rotate or Line.end.rotate. - * - * @method Phaser.Line#rotate - * @param {number} angle - The angle in radians (unless asDegrees is true) to rotate the line by. - * @param {boolean} [asDegrees=false] - Is the given angle in radians (false) or degrees (true)? - * @return {Phaser.Line} This line object - */ + * Rotates the line by the amount specified in `angle`. + * + * Rotation takes place from the center of the line. + * If you wish to rotate around a different point see Line.rotateAround. + * + * If you wish to rotate the ends of the Line then see Line.start.rotate or Line.end.rotate. + * + * @method Phaser.Line#rotate + * @param {number} angle - The angle in radians (unless asDegrees is true) to rotate the line by. + * @param {boolean} [asDegrees=false] - Is the given angle in radians (false) or degrees (true)? + * @return {Phaser.Line} This line object + */ rotate: function (angle, asDegrees) { - var cx = (this.start.x + this.end.x) / 2; var cy = (this.start.y + this.end.y) / 2; @@ -145,97 +134,87 @@ Phaser.Line.prototype = { this.end.rotate(cx, cy, angle, asDegrees); return this; - }, /** - * Rotates the line by the amount specified in `angle`. - * - * Rotation takes place around the coordinates given. - * - * @method Phaser.Line#rotateAround - * @param {number} x - The x coordinate to offset the rotation from. - * @param {number} y - The y coordinate to offset the rotation from. - * @param {number} angle - The angle in radians (unless asDegrees is true) to rotate the line by. - * @param {boolean} [asDegrees=false] - Is the given angle in radians (false) or degrees (true)? - * @return {Phaser.Line} This line object - */ + * Rotates the line by the amount specified in `angle`. + * + * Rotation takes place around the coordinates given. + * + * @method Phaser.Line#rotateAround + * @param {number} x - The x coordinate to offset the rotation from. + * @param {number} y - The y coordinate to offset the rotation from. + * @param {number} angle - The angle in radians (unless asDegrees is true) to rotate the line by. + * @param {boolean} [asDegrees=false] - Is the given angle in radians (false) or degrees (true)? + * @return {Phaser.Line} This line object + */ rotateAround: function (x, y, angle, asDegrees) { - this.start.rotate(x, y, angle, asDegrees); this.end.rotate(x, y, angle, asDegrees); return this; - }, /** - * Checks for intersection between this line and another Line. - * If asSegment is true it will check for segment intersection. If asSegment is false it will check for line intersection. - * Returns the intersection segment of AB and EF as a Point, or null if there is no intersection. - * - * @method Phaser.Line#intersects - * @param {Phaser.Line} line - The line to check against this one. - * @param {boolean} [asSegment=true] - If true it will check for segment intersection, otherwise full line intersection. - * @param {Phaser.Point} [result] - A Point object to store the result in, if not given a new one will be created. - * @return {Phaser.Point} The intersection segment of the two lines as a Point, or null if there is no intersection. - */ + * Checks for intersection between this line and another Line. + * If asSegment is true it will check for segment intersection. If asSegment is false it will check for line intersection. + * Returns the intersection segment of AB and EF as a Point, or null if there is no intersection. + * + * @method Phaser.Line#intersects + * @param {Phaser.Line} line - The line to check against this one. + * @param {boolean} [asSegment=true] - If true it will check for segment intersection, otherwise full line intersection. + * @param {Phaser.Point} [result] - A Point object to store the result in, if not given a new one will be created. + * @return {Phaser.Point} The intersection segment of the two lines as a Point, or null if there is no intersection. + */ intersects: function (line, asSegment, result) { - return Phaser.Line.intersectsPoints(this.start, this.end, line.start, line.end, asSegment, result); - }, /** - * Returns the reflected angle between two lines. - * This is the outgoing angle based on the angle of this line and the normalAngle of the given line. - * - * @method Phaser.Line#reflect - * @param {Phaser.Line} line - The line to reflect off this line. - * @return {number} The reflected angle in radians. - */ + * Returns the reflected angle between two lines. + * This is the outgoing angle based on the angle of this line and the normalAngle of the given line. + * + * @method Phaser.Line#reflect + * @param {Phaser.Line} line - The line to reflect off this line. + * @return {number} The reflected angle in radians. + */ reflect: function (line) { - return Phaser.Line.reflect(this, line); - }, /** - * Returns a Point object where the x and y values correspond to the center (or midpoint) of the Line segment. - * - * @method Phaser.Line#midPoint - * @param {Phaser.Point} [out] - A Phaser.Point object into which the result will be populated. If not given a new Point object is created. - * @return {Phaser.Point} A Phaser.Point object with the x and y values set to the center of the line segment. - */ + * Returns a Point object where the x and y values correspond to the center (or midpoint) of the Line segment. + * + * @method Phaser.Line#midPoint + * @param {Phaser.Point} [out] - A Phaser.Point object into which the result will be populated. If not given a new Point object is created. + * @return {Phaser.Point} A Phaser.Point object with the x and y values set to the center of the line segment. + */ midPoint: function (out) { - if (out === undefined) { out = new Phaser.Point(); } out.x = (this.start.x + this.end.x) / 2; out.y = (this.start.y + this.end.y) / 2; return out; - }, /** - * Centers this Line on the given coordinates. - * - * The line is centered by positioning the start and end points so that the lines midpoint matches - * the coordinates given. - * - * @method Phaser.Line#centerOn - * @param {number} x - The x position to center the line on. - * @param {number} y - The y position to center the line on. - * @return {Phaser.Line} This line object - */ + * Centers this Line on the given coordinates. + * + * The line is centered by positioning the start and end points so that the lines midpoint matches + * the coordinates given. + * + * @method Phaser.Line#centerOn + * @param {number} x - The x position to center the line on. + * @param {number} y - The y position to center the line on. + * @return {Phaser.Line} This line object + */ centerOn: function (x, y) { - var cx = (this.start.x + this.end.x) / 2; var cy = (this.start.y + this.end.y) / 2; @@ -244,57 +223,51 @@ Phaser.Line.prototype = { this.start.add(tx, ty); this.end.add(tx, ty); - }, /** - * Tests if the given coordinates fall on this line. See {@link #pointOnSegment} to test against just the line segment. - * - * @method Phaser.Line#pointOnLine - * @param {number} x - The line to check against this one. - * @param {number} y - The line to check against this one. - * @param {number} [epsilon=0] - Range for a fuzzy comparison, e.g., 0.0001. - * @return {boolean} True if the point is on the line, false if not. - */ + * Tests if the given coordinates fall on this line. See {@link #pointOnSegment} to test against just the line segment. + * + * @method Phaser.Line#pointOnLine + * @param {number} x - The line to check against this one. + * @param {number} y - The line to check against this one. + * @param {number} [epsilon=0] - Range for a fuzzy comparison, e.g., 0.0001. + * @return {boolean} True if the point is on the line, false if not. + */ pointOnLine: function (x, y, epsilon) { - return Phaser.Math.fuzzyEqual((x - this.start.x) * (this.end.y - this.start.y), (this.end.x - this.start.x) * (y - this.start.y), epsilon || 0); - }, /** - * Tests if the given coordinates fall on this line and within the segment. See {@link #pointOnLine} to test against just the line. - * - * @method Phaser.Line#pointOnSegment - * @param {number} x - The line to check against this one. - * @param {number} y - The line to check against this one. - * @param {number} [epsilon=0] - Range for a fuzzy comparison, e.g., 0.0001. - * @return {boolean} True if the point is on the line and segment, false if not. - */ + * Tests if the given coordinates fall on this line and within the segment. See {@link #pointOnLine} to test against just the line. + * + * @method Phaser.Line#pointOnSegment + * @param {number} x - The line to check against this one. + * @param {number} y - The line to check against this one. + * @param {number} [epsilon=0] - Range for a fuzzy comparison, e.g., 0.0001. + * @return {boolean} True if the point is on the line and segment, false if not. + */ pointOnSegment: function (x, y, epsilon) { - var xMin = Math.min(this.start.x, this.end.x); var xMax = Math.max(this.start.x, this.end.x); var yMin = Math.min(this.start.y, this.end.y); var yMax = Math.max(this.start.y, this.end.y); return (this.pointOnLine(x, y, epsilon) && (x >= xMin && x <= xMax) && (y >= yMin && y <= yMax)); - }, /** - * Picks a random point from anywhere on the Line segment and returns it. - * - * @method Phaser.Line#random - * @param {Phaser.Point|object} [out] - A Phaser.Point, or any object with public x/y properties, that the values will be set in. - * If no object is provided a new Phaser.Point object will be created. In high performance areas avoid this by re-using an object. - * @return {Phaser.Point} An object containing the random point in its `x` and `y` properties. - */ + * Picks a random point from anywhere on the Line segment and returns it. + * + * @method Phaser.Line#random + * @param {Phaser.Point|object} [out] - A Phaser.Point, or any object with public x/y properties, that the values will be set in. + * If no object is provided a new Phaser.Point object will be created. In high performance areas avoid this by re-using an object. + * @return {Phaser.Point} An object containing the random point in its `x` and `y` properties. + */ random: function (out) { - if (out === undefined) { out = new Phaser.Point(); } var t = Math.random(); @@ -303,21 +276,19 @@ Phaser.Line.prototype = { out.y = this.start.y + t * (this.end.y - this.start.y); return out; - }, /** - * Using Bresenham's line algorithm this will return an array of all coordinates on this line. - * The start and end points are rounded before this runs as the algorithm works on integers. - * - * @method Phaser.Line#coordinatesOnLine - * @param {number} [stepRate=1] - How many steps will we return? 1 = every coordinate on the line, 2 = every other coordinate, etc. - * @param {array} [results] - The array to store the results in. If not provided a new one will be generated. - * @return {array} An array of coordinates. - */ + * Using Bresenham's line algorithm this will return an array of all coordinates on this line. + * The start and end points are rounded before this runs as the algorithm works on integers. + * + * @method Phaser.Line#coordinatesOnLine + * @param {number} [stepRate=1] - How many steps will we return? 1 = every coordinate on the line, 2 = every other coordinate, etc. + * @param {array} [results] - The array to store the results in. If not provided a new one will be generated. + * @return {array} An array of coordinates. + */ coordinatesOnLine: function (stepRate, results) { - if (stepRate === undefined) { stepRate = 1; } if (results === undefined) { results = []; } @@ -358,11 +329,9 @@ Phaser.Line.prototype = { } i++; - } return results; - }, /** @@ -373,7 +342,6 @@ Phaser.Line.prototype = { */ clone: function (output) { - if (output === undefined || output === null) { output = new Phaser.Line(this.start.x, this.start.y, this.end.x, this.end.y); @@ -384,16 +352,15 @@ Phaser.Line.prototype = { } return output; - } }; /** -* @name Phaser.Line#length -* @property {number} length - Gets the length of the line segment. -* @readonly -*/ + * @name Phaser.Line#length + * @property {number} length - Gets the length of the line segment. + * @readonly + */ Object.defineProperty(Phaser.Line.prototype, 'length', { get: function () @@ -404,10 +371,10 @@ Object.defineProperty(Phaser.Line.prototype, 'length', { }); /** -* @name Phaser.Line#angle -* @property {number} angle - Gets the angle of the line in radians. -* @readonly -*/ + * @name Phaser.Line#angle + * @property {number} angle - Gets the angle of the line in radians. + * @readonly + */ Object.defineProperty(Phaser.Line.prototype, 'angle', { get: function () @@ -418,10 +385,10 @@ Object.defineProperty(Phaser.Line.prototype, 'angle', { }); /** -* @name Phaser.Line#slope -* @property {number} slope - Gets the slope of the line (y/x). -* @readonly -*/ + * @name Phaser.Line#slope + * @property {number} slope - Gets the slope of the line (y/x). + * @readonly + */ Object.defineProperty(Phaser.Line.prototype, 'slope', { get: function () @@ -432,10 +399,10 @@ Object.defineProperty(Phaser.Line.prototype, 'slope', { }); /** -* @name Phaser.Line#perpSlope -* @property {number} perpSlope - Gets the perpendicular slope of the line (x/y). -* @readonly -*/ + * @name Phaser.Line#perpSlope + * @property {number} perpSlope - Gets the perpendicular slope of the line (x/y). + * @readonly + */ Object.defineProperty(Phaser.Line.prototype, 'perpSlope', { get: function () @@ -446,10 +413,10 @@ Object.defineProperty(Phaser.Line.prototype, 'perpSlope', { }); /** -* @name Phaser.Line#x -* @property {number} x - Gets the x coordinate of the top left of the bounds around this line. -* @readonly -*/ + * @name Phaser.Line#x + * @property {number} x - Gets the x coordinate of the top left of the bounds around this line. + * @readonly + */ Object.defineProperty(Phaser.Line.prototype, 'x', { get: function () @@ -460,10 +427,10 @@ Object.defineProperty(Phaser.Line.prototype, 'x', { }); /** -* @name Phaser.Line#y -* @property {number} y - Gets the y coordinate of the top left of the bounds around this line. -* @readonly -*/ + * @name Phaser.Line#y + * @property {number} y - Gets the y coordinate of the top left of the bounds around this line. + * @readonly + */ Object.defineProperty(Phaser.Line.prototype, 'y', { get: function () @@ -474,10 +441,10 @@ Object.defineProperty(Phaser.Line.prototype, 'y', { }); /** -* @name Phaser.Line#left -* @property {number} left - Gets the left-most point of this line. -* @readonly -*/ + * @name Phaser.Line#left + * @property {number} left - Gets the left-most point of this line. + * @readonly + */ Object.defineProperty(Phaser.Line.prototype, 'left', { get: function () @@ -488,10 +455,10 @@ Object.defineProperty(Phaser.Line.prototype, 'left', { }); /** -* @name Phaser.Line#right -* @property {number} right - Gets the right-most point of this line. -* @readonly -*/ + * @name Phaser.Line#right + * @property {number} right - Gets the right-most point of this line. + * @readonly + */ Object.defineProperty(Phaser.Line.prototype, 'right', { get: function () @@ -502,10 +469,10 @@ Object.defineProperty(Phaser.Line.prototype, 'right', { }); /** -* @name Phaser.Line#top -* @property {number} top - Gets the top-most point of this line. -* @readonly -*/ + * @name Phaser.Line#top + * @property {number} top - Gets the top-most point of this line. + * @readonly + */ Object.defineProperty(Phaser.Line.prototype, 'top', { get: function () @@ -516,10 +483,10 @@ Object.defineProperty(Phaser.Line.prototype, 'top', { }); /** -* @name Phaser.Line#bottom -* @property {number} bottom - Gets the bottom-most point of this line. -* @readonly -*/ + * @name Phaser.Line#bottom + * @property {number} bottom - Gets the bottom-most point of this line. + * @readonly + */ Object.defineProperty(Phaser.Line.prototype, 'bottom', { get: function () @@ -530,10 +497,10 @@ Object.defineProperty(Phaser.Line.prototype, 'bottom', { }); /** -* @name Phaser.Line#width -* @property {number} width - Gets the width of this bounds of this line. -* @readonly -*/ + * @name Phaser.Line#width + * @property {number} width - Gets the width of this bounds of this line. + * @readonly + */ Object.defineProperty(Phaser.Line.prototype, 'width', { get: function () @@ -544,10 +511,10 @@ Object.defineProperty(Phaser.Line.prototype, 'width', { }); /** -* @name Phaser.Line#height -* @property {number} height - Gets the height of this bounds of this line. -* @readonly -*/ + * @name Phaser.Line#height + * @property {number} height - Gets the height of this bounds of this line. + * @readonly + */ Object.defineProperty(Phaser.Line.prototype, 'height', { get: function () @@ -558,10 +525,10 @@ Object.defineProperty(Phaser.Line.prototype, 'height', { }); /** -* @name Phaser.Line#normalX -* @property {number} normalX - Gets the x component of the left-hand normal of this line. -* @readonly -*/ + * @name Phaser.Line#normalX + * @property {number} normalX - Gets the x component of the left-hand normal of this line. + * @readonly + */ Object.defineProperty(Phaser.Line.prototype, 'normalX', { get: function () @@ -572,10 +539,10 @@ Object.defineProperty(Phaser.Line.prototype, 'normalX', { }); /** -* @name Phaser.Line#normalY -* @property {number} normalY - Gets the y component of the left-hand normal of this line. -* @readonly -*/ + * @name Phaser.Line#normalY + * @property {number} normalY - Gets the y component of the left-hand normal of this line. + * @readonly + */ Object.defineProperty(Phaser.Line.prototype, 'normalY', { get: function () @@ -586,10 +553,10 @@ Object.defineProperty(Phaser.Line.prototype, 'normalY', { }); /** -* @name Phaser.Line#normalAngle -* @property {number} normalAngle - Gets the angle in radians of the normal of this line (line.angle - 90 degrees.) -* @readonly -*/ + * @name Phaser.Line#normalAngle + * @property {number} normalAngle - Gets the angle in radians of the normal of this line (line.angle - 90 degrees.) + * @readonly + */ Object.defineProperty(Phaser.Line.prototype, 'normalAngle', { get: function () @@ -600,23 +567,22 @@ Object.defineProperty(Phaser.Line.prototype, 'normalAngle', { }); /** -* Checks for intersection between two lines as defined by the given start and end points. -* If asSegment is true it will check for line segment intersection. If asSegment is false it will check for line intersection. -* Returns the intersection segment of AB and EF as a Point, or null if there is no intersection. -* Adapted from code by Keith Hair -* -* @method Phaser.Line.intersectsPoints -* @param {Phaser.Point} a - The start of the first Line to be checked. -* @param {Phaser.Point} b - The end of the first line to be checked. -* @param {Phaser.Point} e - The start of the second Line to be checked. -* @param {Phaser.Point} f - The end of the second line to be checked. -* @param {boolean} [asSegment=true] - If true it will check for segment intersection, otherwise full line intersection. -* @param {Phaser.Point|object} [result] - A Point object to store the result in, if not given a new one will be created. -* @return {Phaser.Point} The intersection segment of the two lines as a Point, or null if there is no intersection. -*/ + * Checks for intersection between two lines as defined by the given start and end points. + * If asSegment is true it will check for line segment intersection. If asSegment is false it will check for line intersection. + * Returns the intersection segment of AB and EF as a Point, or null if there is no intersection. + * Adapted from code by Keith Hair + * + * @method Phaser.Line.intersectsPoints + * @param {Phaser.Point} a - The start of the first Line to be checked. + * @param {Phaser.Point} b - The end of the first line to be checked. + * @param {Phaser.Point} e - The start of the second Line to be checked. + * @param {Phaser.Point} f - The end of the second line to be checked. + * @param {boolean} [asSegment=true] - If true it will check for segment intersection, otherwise full line intersection. + * @param {Phaser.Point|object} [result] - A Point object to store the result in, if not given a new one will be created. + * @return {Phaser.Point} The intersection segment of the two lines as a Point, or null if there is no intersection. + */ Phaser.Line.intersectsPoints = function (a, b, e, f, asSegment, result) { - if (asSegment === undefined) { asSegment = true; } if (result === undefined) { result = new Phaser.Point(); } @@ -653,51 +619,47 @@ Phaser.Line.intersectsPoints = function (a, b, e, f, asSegment, result) } return result; - }; /** -* Checks for intersection between two lines. -* If asSegment is true it will check for segment intersection. -* If asSegment is false it will check for line intersection. -* Returns the intersection segment of AB and EF as a Point, or null if there is no intersection. -* Adapted from code by Keith Hair -* -* @method Phaser.Line.intersects -* @param {Phaser.Line} a - The first Line to be checked. -* @param {Phaser.Line} b - The second Line to be checked. -* @param {boolean} [asSegment=true] - If true it will check for segment intersection, otherwise full line intersection. -* @param {Phaser.Point} [result] - A Point object to store the result in, if not given a new one will be created. -* @return {Phaser.Point} The intersection segment of the two lines as a Point, or null if there is no intersection. -*/ + * Checks for intersection between two lines. + * If asSegment is true it will check for segment intersection. + * If asSegment is false it will check for line intersection. + * Returns the intersection segment of AB and EF as a Point, or null if there is no intersection. + * Adapted from code by Keith Hair + * + * @method Phaser.Line.intersects + * @param {Phaser.Line} a - The first Line to be checked. + * @param {Phaser.Line} b - The second Line to be checked. + * @param {boolean} [asSegment=true] - If true it will check for segment intersection, otherwise full line intersection. + * @param {Phaser.Point} [result] - A Point object to store the result in, if not given a new one will be created. + * @return {Phaser.Point} The intersection segment of the two lines as a Point, or null if there is no intersection. + */ Phaser.Line.intersects = function (a, b, asSegment, result) { - return Phaser.Line.intersectsPoints(a.start, a.end, b.start, b.end, asSegment, result); - }; /** -* Checks for intersection between the Line and a Rectangle shape, or a rectangle-like -* object, with public `x`, `y`, `right` and `bottom` properties, such as a Sprite or Body. -* -* An intersection is considered valid if: -* -* The line starts within or ends within the rectangle; or -* The line segment intersects one of the 4 rectangle edges; and -* The line has a non-zero length; and -* The rectangle is not empty. -* -* For the purposes of this function rectangles are considered 'solid'. -* -* @method Phaser.Line.intersectsRectangle -* @param {Phaser.Line} line - The line to check for intersection with. -* @param {Phaser.Rectangle|object} rect - The rectangle, or rectangle-like object, to check for intersection with. -* @return {boolean} True if the line intersects with the rectangle edges, or starts or ends within the rectangle. -*/ + * Checks for intersection between the Line and a Rectangle shape, or a rectangle-like + * object, with public `x`, `y`, `right` and `bottom` properties, such as a Sprite or Body. + * + * An intersection is considered valid if: + * + * The line starts within or ends within the rectangle; or + * The line segment intersects one of the 4 rectangle edges; and + * The line has a non-zero length; and + * The rectangle is not empty. + * + * For the purposes of this function rectangles are considered 'solid'. + * + * @method Phaser.Line.intersectsRectangle + * @param {Phaser.Line} line - The line to check for intersection with. + * @param {Phaser.Rectangle|object} rect - The rectangle, or rectangle-like object, to check for intersection with. + * @return {boolean} True if the line intersects with the rectangle edges, or starts or ends within the rectangle. + */ Phaser.Line.intersectsRectangle = function (line, rect) { - // Quick bail out if (line.length === 0 || rect.empty) { @@ -717,8 +679,10 @@ Phaser.Line.intersectsRectangle = function (line, rect) var t = 0; - // If the start or end of the line is inside the rect then we assume - // collision, as rects are solid for our use-case. + /* + * If the start or end of the line is inside the rect then we assume + * collision, as rects are solid for our use-case. + */ if ((x1 >= bx1 && x1 <= bx2 && y1 >= by1 && y1 <= by2) || (x2 >= bx1 && x2 <= bx2 && y2 >= by1 && y2 <= by2)) @@ -769,22 +733,20 @@ Phaser.Line.intersectsRectangle = function (line, rect) } return false; - }; /** -* Finds the closest intersection between the Line and a Rectangle shape, or a rectangle-like -* object, such as a Sprite or Body. -* -* @method Phaser.Line.intersectionWithRectangle -* @param {Phaser.Line} line - The line to check for intersection with. -* @param {Phaser.Rectangle} rect - The rectangle, or rectangle-like object, to check for intersection with. -* @param {Phaser.Point} [result] - A Point object to store the result in. -* @return {?Phaser.Point} - The intersection closest to the Line's start, or null if there is no intersection. -*/ + * Finds the closest intersection between the Line and a Rectangle shape, or a rectangle-like + * object, such as a Sprite or Body. + * + * @method Phaser.Line.intersectionWithRectangle + * @param {Phaser.Line} line - The line to check for intersection with. + * @param {Phaser.Rectangle} rect - The rectangle, or rectangle-like object, to check for intersection with. + * @param {Phaser.Point} [result] - A Point object to store the result in. + * @return {?Phaser.Point} - The intersection closest to the Line's start, or null if there is no intersection. + */ Phaser.Line.intersectionWithRectangle = function (line, rect, result) { - var self = Phaser.Line.intersectionWithRectangle; if (!result) @@ -836,21 +798,18 @@ Phaser.Line.intersectionWithRectangle = function (line, rect, result) } return null; - }; /** -* Returns the reflected angle between two lines. -* This is the outgoing angle based on the angle of Line 1 and the normalAngle of Line 2. -* -* @method Phaser.Line.reflect -* @param {Phaser.Line} a - The base line. -* @param {Phaser.Line} b - The line to be reflected from the base line. -* @return {number} The reflected angle in radians. -*/ + * Returns the reflected angle between two lines. + * This is the outgoing angle based on the angle of Line 1 and the normalAngle of Line 2. + * + * @method Phaser.Line.reflect + * @param {Phaser.Line} a - The base line. + * @param {Phaser.Line} b - The line to be reflected from the base line. + * @return {number} The reflected angle in radians. + */ Phaser.Line.reflect = function (a, b) { - return 2 * b.normalAngle - 3.141592653589793 - a.angle; - }; diff --git a/src/geom/Matrix.js b/src/geom/Matrix.js index d14c5b5ed..ac8593f24 100644 --- a/src/geom/Matrix.js +++ b/src/geom/Matrix.js @@ -1,31 +1,30 @@ /** -* @author Mat Groves http://matgroves.com/ @Doormat23 -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Mat Groves http://matgroves.com/ @Doormat23 + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* The Matrix is a 3x3 matrix mostly used for display transforms within the renderer. -* -* It is represented like so: -* -* | a | c | tx | -* | b | d | ty | -* | 0 | 0 | 1 | -* -* @class Phaser.Matrix -* @constructor -* @param {number} [a=1] - Horizontal scaling -* @param {number} [b=0] - Horizontal skewing -* @param {number} [c=0] - Vertical skewing -* @param {number} [d=1] - Vertical scaling -* @param {number} [tx=0] - Horizontal translation -* @param {number} [ty=0] - Vertical translation -*/ + * The Matrix is a 3x3 matrix mostly used for display transforms within the renderer. + * + * It is represented like so: + * + * | a | c | tx | + * | b | d | ty | + * | 0 | 0 | 1 | + * + * @class Phaser.Matrix + * @constructor + * @param {number} [a=1] - Horizontal scaling + * @param {number} [b=0] - Horizontal skewing + * @param {number} [c=0] - Vertical skewing + * @param {number} [d=1] - Vertical scaling + * @param {number} [tx=0] - Horizontal translation + * @param {number} [ty=0] - Vertical translation + */ Phaser.Matrix = function (a, b, c, d, tx, ty) { - if (a === undefined || a === null) { a = 1; } if (b === undefined || b === null) { b = 0; } if (c === undefined || c === null) { c = 0; } @@ -34,89 +33,85 @@ Phaser.Matrix = function (a, b, c, d, tx, ty) if (ty === undefined || ty === null) { ty = 0; } /** - * @property {number} a - * @default 1 - */ + * @property {number} a + * @default 1 + */ this.a = a; /** - * @property {number} b - * @default 0 - */ + * @property {number} b + * @default 0 + */ this.b = b; /** - * @property {number} c - * @default 0 - */ + * @property {number} c + * @default 0 + */ this.c = c; /** - * @property {number} d - * @default 1 - */ + * @property {number} d + * @default 1 + */ this.d = d; /** - * @property {number} tx - * @default 0 - */ + * @property {number} tx + * @default 0 + */ this.tx = tx; /** - * @property {number} ty - * @default 0 - */ + * @property {number} ty + * @default 0 + */ this.ty = ty; /** - * @property {number} type - The const type of this object. - * @readonly - */ + * @property {number} type - The const type of this object. + * @readonly + */ this.type = Phaser.MATRIX; - }; Phaser.Matrix.prototype = { /** - * Sets the values of this Matrix to the values in the given array. - * - * The Array elements should be set as follows: - * - * a = array[0] - * b = array[1] - * c = array[3] - * d = array[4] - * tx = array[2] - * ty = array[5] - * - * @method Phaser.Matrix#fromArray - * @param {Array} array - The array to copy from. - * @return {Phaser.Matrix} This Matrix object. - */ + * Sets the values of this Matrix to the values in the given array. + * + * The Array elements should be set as follows: + * + * a = array[0] + * b = array[1] + * c = array[3] + * d = array[4] + * tx = array[2] + * ty = array[5] + * + * @method Phaser.Matrix#fromArray + * @param {Array} array - The array to copy from. + * @return {Phaser.Matrix} This Matrix object. + */ fromArray: function (array) { - return this.setTo(array[0], array[1], array[3], array[4], array[2], array[5]); - }, /** - * Sets the values of this Matrix to the given values. - * - * @method Phaser.Matrix#setTo - * @param {number} a - Horizontal scaling - * @param {number} b - Horizontal skewing - * @param {number} c - Vertical skewing - * @param {number} d - Vertical scaling - * @param {number} tx - Horizontal translation - * @param {number} ty - Vertical translation - * @return {Phaser.Matrix} This Matrix object. - */ + * Sets the values of this Matrix to the given values. + * + * @method Phaser.Matrix#setTo + * @param {number} a - Horizontal scaling + * @param {number} b - Horizontal skewing + * @param {number} c - Vertical skewing + * @param {number} d - Vertical scaling + * @param {number} tx - Horizontal translation + * @param {number} ty - Vertical translation + * @return {Phaser.Matrix} This Matrix object. + */ setTo: function (a, b, c, d, tx, ty) { - this.a = a; this.b = b; this.c = c; @@ -125,7 +120,6 @@ Phaser.Matrix.prototype = { this.ty = ty; return this; - }, /** @@ -139,7 +133,6 @@ Phaser.Matrix.prototype = { */ clone: function (output) { - if (output === undefined || output === null) { output = new Phaser.Matrix(this.a, this.b, this.c, this.d, this.tx, this.ty); @@ -155,35 +148,31 @@ Phaser.Matrix.prototype = { } return output; - }, /** - * Copies the properties from this Matrix to the given Matrix. - * - * @method Phaser.Matrix#copyTo - * @param {Phaser.Matrix} matrix - The Matrix to copy from. - * @return {Phaser.Matrix} The destination Matrix object. - */ + * Copies the properties from this Matrix to the given Matrix. + * + * @method Phaser.Matrix#copyTo + * @param {Phaser.Matrix} matrix - The Matrix to copy from. + * @return {Phaser.Matrix} The destination Matrix object. + */ copyTo: function (matrix) { - matrix.copyFrom(this); return matrix; - }, /** - * Copies the properties from the given Matrix into this Matrix. - * - * @method Phaser.Matrix#copyFrom - * @param {Phaser.Matrix} matrix - The Matrix to copy from. - * @return {Phaser.Matrix} This Matrix object. - */ + * Copies the properties from the given Matrix into this Matrix. + * + * @method Phaser.Matrix#copyFrom + * @param {Phaser.Matrix} matrix - The Matrix to copy from. + * @return {Phaser.Matrix} This Matrix object. + */ copyFrom: function (matrix) { - this.a = matrix.a; this.b = matrix.b; this.c = matrix.c; @@ -192,20 +181,18 @@ Phaser.Matrix.prototype = { this.ty = matrix.ty; return this; - }, /** - * Creates a Float32 Array with values populated from this Matrix object. - * - * @method Phaser.Matrix#toArray - * @param {boolean} [transpose=false] - Whether the values in the array are transposed or not. - * @param {Float32Array} [array] - If provided the values will be set into this array, otherwise a new Float32Array is created. - * @return {Float32Array} The newly created array which contains the matrix. - */ + * Creates a Float32 Array with values populated from this Matrix object. + * + * @method Phaser.Matrix#toArray + * @param {boolean} [transpose=false] - Whether the values in the array are transposed or not. + * @param {Float32Array} [array] - If provided the values will be set into this array, otherwise a new Float32Array is created. + * @return {Float32Array} The newly created array which contains the matrix. + */ toArray: function (transpose, array) { - if (array === undefined) { array = new Float32Array(9); } if (transpose) @@ -234,44 +221,40 @@ Phaser.Matrix.prototype = { } return array; - }, /** - * Get a new position with the current transformation applied. - * - * Can be used to go from a childs coordinate space to the world coordinate space (e.g. rendering) - * - * @method Phaser.Matrix#apply - * @param {Phaser.Point} pos - The origin Point. - * @param {Phaser.Point} [newPos] - The point that the new position is assigned to. This can be same as input point. - * @return {Phaser.Point} The new point, transformed through this matrix. - */ + * Get a new position with the current transformation applied. + * + * Can be used to go from a childs coordinate space to the world coordinate space (e.g. rendering) + * + * @method Phaser.Matrix#apply + * @param {Phaser.Point} pos - The origin Point. + * @param {Phaser.Point} [newPos] - The point that the new position is assigned to. This can be same as input point. + * @return {Phaser.Point} The new point, transformed through this matrix. + */ apply: function (pos, newPos) { - if (newPos === undefined) { newPos = new Phaser.Point(); } newPos.x = this.a * pos.x + this.c * pos.y + this.tx; newPos.y = this.b * pos.x + this.d * pos.y + this.ty; return newPos; - }, /** - * Get a new position with the inverse of the current transformation applied. - * - * Can be used to go from the world coordinate space to a childs coordinate space. (e.g. input) - * - * @method Phaser.Matrix#applyInverse - * @param {Phaser.Point} pos - The origin Point. - * @param {Phaser.Point} [newPos] - The point that the new position is assigned to. This can be same as input point. - * @return {Phaser.Point} The new point, inverse transformed through this matrix. - */ + * Get a new position with the inverse of the current transformation applied. + * + * Can be used to go from the world coordinate space to a childs coordinate space. (e.g. input) + * + * @method Phaser.Matrix#applyInverse + * @param {Phaser.Point} pos - The origin Point. + * @param {Phaser.Point} [newPos] - The point that the new position is assigned to. This can be same as input point. + * @return {Phaser.Point} The new point, inverse transformed through this matrix. + */ applyInverse: function (pos, newPos) { - if (newPos === undefined) { newPos = new Phaser.Point(); } var id = 1 / (this.a * this.d + this.c * -this.b); @@ -282,39 +265,35 @@ Phaser.Matrix.prototype = { newPos.y = this.a * id * y + -this.b * id * x + (-this.ty * this.a + this.tx * this.b) * id; return newPos; - }, /** - * Translates the matrix on the x and y. - * This is the same as Matrix.tx += x. - * - * @method Phaser.Matrix#translate - * @param {number} x - The x value to translate on. - * @param {number} y - The y value to translate on. - * @return {Phaser.Matrix} This Matrix object. - */ + * Translates the matrix on the x and y. + * This is the same as Matrix.tx += x. + * + * @method Phaser.Matrix#translate + * @param {number} x - The x value to translate on. + * @param {number} y - The y value to translate on. + * @return {Phaser.Matrix} This Matrix object. + */ translate: function (x, y) { - this.tx += x; this.ty += y; return this; - }, /** - * Applies a scale transformation to this matrix. - * - * @method Phaser.Matrix#scale - * @param {number} x - The amount to scale horizontally. - * @param {number} y - The amount to scale vertically. - * @return {Phaser.Matrix} This Matrix object. - */ + * Applies a scale transformation to this matrix. + * + * @method Phaser.Matrix#scale + * @param {number} x - The amount to scale horizontally. + * @param {number} y - The amount to scale vertically. + * @return {Phaser.Matrix} This Matrix object. + */ scale: function (x, y) { - this.a *= x; this.d *= y; this.c *= x; @@ -323,19 +302,17 @@ Phaser.Matrix.prototype = { this.ty *= y; return this; - }, /** - * Applies a rotation transformation to this matrix. - * - * @method Phaser.Matrix#rotate - * @param {number} angle - The angle to rotate by, given in radians. - * @return {Phaser.Matrix} This Matrix object. - */ + * Applies a rotation transformation to this matrix. + * + * @method Phaser.Matrix#rotate + * @param {number} angle - The angle to rotate by, given in radians. + * @return {Phaser.Matrix} This Matrix object. + */ rotate: function (angle) { - var cos = Math.cos(angle); var sin = Math.sin(angle); @@ -351,19 +328,17 @@ Phaser.Matrix.prototype = { this.ty = tx1 * sin + this.ty * cos; return this; - }, /** - * Appends the given Matrix to this Matrix. - * - * @method Phaser.Matrix#append - * @param {Phaser.Matrix} matrix - The matrix to append to this one. - * @return {Phaser.Matrix} This Matrix object. - */ + * Appends the given Matrix to this Matrix. + * + * @method Phaser.Matrix#append + * @param {Phaser.Matrix} matrix - The matrix to append to this one. + * @return {Phaser.Matrix} This Matrix object. + */ append: function (matrix) { - var a1 = this.a; var b1 = this.b; var c1 = this.c; @@ -378,20 +353,17 @@ Phaser.Matrix.prototype = { this.ty = matrix.tx * b1 + matrix.ty * d1 + this.ty; return this; - }, /** - * Resets this Matrix to an identity (default) matrix. - * - * @method Phaser.Matrix#identity - * @return {Phaser.Matrix} This Matrix object. - */ + * Resets this Matrix to an identity (default) matrix. + * + * @method Phaser.Matrix#identity + * @return {Phaser.Matrix} This Matrix object. + */ identity: function () { - return this.setTo(1, 0, 0, 1, 0, 0); - } }; diff --git a/src/geom/Point.js b/src/geom/Point.js index 0a53b1a26..c629041d1 100644 --- a/src/geom/Point.js +++ b/src/geom/Point.js @@ -1,109 +1,99 @@ /** -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* A Point object represents a location in a two-dimensional coordinate system, where x represents the horizontal axis and y represents the vertical axis. -* The following code creates a point at (0,0): -* `var myPoint = new Phaser.Point();` -* You can also use them as 2D Vectors and you'll find different vector related methods in this class. -* -* @class Phaser.Point -* @constructor -* @param {number} [x=0] - The horizontal position of this Point. -* @param {number} [y=0] - The vertical position of this Point. -*/ + * A Point object represents a location in a two-dimensional coordinate system, where x represents the horizontal axis and y represents the vertical axis. + * The following code creates a point at (0,0): + * `var myPoint = new Phaser.Point();` + * You can also use them as 2D Vectors and you'll find different vector related methods in this class. + * + * @class Phaser.Point + * @constructor + * @param {number} [x=0] - The horizontal position of this Point. + * @param {number} [y=0] - The vertical position of this Point. + */ Phaser.Point = function (x, y) { - x = x || 0; y = y || 0; /** - * @property {number} x - The x value of the point. - */ + * @property {number} x - The x value of the point. + */ this.x = x; /** - * @property {number} y - The y value of the point. - */ + * @property {number} y - The y value of the point. + */ this.y = y; /** - * @property {number} type - The const type of this object. - * @readonly - */ + * @property {number} type - The const type of this object. + * @readonly + */ this.type = Phaser.POINT; - }; Phaser.Point.prototype = { /** - * Copies the x and y properties from any given object to this Point. - * - * @method Phaser.Point#copyFrom - * @param {any} source - The object to copy from. - * @return {Phaser.Point} This Point object. - */ + * Copies the x and y properties from any given object to this Point. + * + * @method Phaser.Point#copyFrom + * @param {any} source - The object to copy from. + * @return {Phaser.Point} This Point object. + */ copyFrom: function (source) { - return this.setTo(source.x, source.y); - }, /** - * Inverts the x and y values of this Point - * - * @method Phaser.Point#invert - * @return {Phaser.Point} This Point object. - */ + * Inverts the x and y values of this Point + * + * @method Phaser.Point#invert + * @return {Phaser.Point} This Point object. + */ invert: function () { - return this.setTo(this.y, this.x); - }, /** - * Sets the `x` and `y` values of this Point object to the given values. - * If you omit the `y` value then the `x` value will be applied to both, for example: - * `Point.setTo(2)` is the same as `Point.setTo(2, 2)` - * - * Identical to {@link #set}. - * - * @method Phaser.Point#setTo - * @param {number} x - The horizontal value of this point. - * @param {number} [y] - The vertical value of this point. If not given the x value will be used in its place. - * @return {Phaser.Point} This Point object. Useful for chaining method calls. - */ + * Sets the `x` and `y` values of this Point object to the given values. + * If you omit the `y` value then the `x` value will be applied to both, for example: + * `Point.setTo(2)` is the same as `Point.setTo(2, 2)` + * + * Identical to {@link #set}. + * + * @method Phaser.Point#setTo + * @param {number} x - The horizontal value of this point. + * @param {number} [y] - The vertical value of this point. If not given the x value will be used in its place. + * @return {Phaser.Point} This Point object. Useful for chaining method calls. + */ setTo: function (x, y) { - return Phaser.Point.set(this, x, y); - }, /** - * Sets the `x` and `y` values of this Point object to the given values. - * If you omit the `y` value then the `x` value will be applied to both, for example: - * `Point.set(2)` is the same as `Point.set(2, 2)` - * - * Identical to {@link #setTo}. - * - * @method Phaser.Point#set - * @param {number} x - The horizontal value of this point. - * @param {number} [y] - The vertical value of this point. If not given the x value will be used in its place. - * @return {Phaser.Point} This Point object. Useful for chaining method calls. - */ + * Sets the `x` and `y` values of this Point object to the given values. + * If you omit the `y` value then the `x` value will be applied to both, for example: + * `Point.set(2)` is the same as `Point.set(2, 2)` + * + * Identical to {@link #setTo}. + * + * @method Phaser.Point#set + * @param {number} x - The horizontal value of this point. + * @param {number} [y] - The vertical value of this point. If not given the x value will be used in its place. + * @return {Phaser.Point} This Point object. Useful for chaining method calls. + */ set: function (x, y) { - return Phaser.Point.set(this, x, y); - }, /** @@ -117,141 +107,124 @@ Phaser.Point.prototype = { */ setToPolar: function (azimuth, radius, asDegrees) { - if (radius == null) { radius = 1; } if (asDegrees) { azimuth = Phaser.Math.degToRad(azimuth); } return this.setTo(Math.cos(azimuth) * radius, Math.sin(azimuth) * radius); - }, /** - * Adds the given x and y values to this Point. - * - * @method Phaser.Point#add - * @param {number} x - The value to add to Point.x. - * @param {number} y - The value to add to Point.y. - * @return {Phaser.Point} This Point object. Useful for chaining method calls. - */ + * Adds the given x and y values to this Point. + * + * @method Phaser.Point#add + * @param {number} x - The value to add to Point.x. + * @param {number} y - The value to add to Point.y. + * @return {Phaser.Point} This Point object. Useful for chaining method calls. + */ add: function (x, y) { - this.x += x; this.y += y; return this; - }, /** - * Subtracts the given x and y values from this Point. - * - * @method Phaser.Point#subtract - * @param {number} x - The value to subtract from Point.x. - * @param {number} y - The value to subtract from Point.y. - * @return {Phaser.Point} This Point object. Useful for chaining method calls. - */ + * Subtracts the given x and y values from this Point. + * + * @method Phaser.Point#subtract + * @param {number} x - The value to subtract from Point.x. + * @param {number} y - The value to subtract from Point.y. + * @return {Phaser.Point} This Point object. Useful for chaining method calls. + */ subtract: function (x, y) { - this.x -= x; this.y -= y; return this; - }, /** - * Multiplies Point.x and Point.y by the given x and y values. Sometimes known as `Scale`. - * - * @method Phaser.Point#multiply - * @param {number} x - The value to multiply Point.x by. - * @param {number} y - The value to multiply Point.x by. - * @return {Phaser.Point} This Point object. Useful for chaining method calls. - */ + * Multiplies Point.x and Point.y by the given x and y values. Sometimes known as `Scale`. + * + * @method Phaser.Point#multiply + * @param {number} x - The value to multiply Point.x by. + * @param {number} y - The value to multiply Point.x by. + * @return {Phaser.Point} This Point object. Useful for chaining method calls. + */ multiply: function (x, y) { - this.x *= x; this.y *= y; return this; - }, /** - * Divides Point.x and Point.y by the given x and y values. - * - * @method Phaser.Point#divide - * @param {number} x - The value to divide Point.x by. - * @param {number} y - The value to divide Point.x by. - * @return {Phaser.Point} This Point object. Useful for chaining method calls. - */ + * Divides Point.x and Point.y by the given x and y values. + * + * @method Phaser.Point#divide + * @param {number} x - The value to divide Point.x by. + * @param {number} y - The value to divide Point.x by. + * @return {Phaser.Point} This Point object. Useful for chaining method calls. + */ divide: function (x, y) { - this.x /= x; this.y /= y; return this; - }, /** - * Clamps the x value of this Point to be between the given min and max. - * - * @method Phaser.Point#clampX - * @param {number} min - The minimum value to clamp this Point to. - * @param {number} max - The maximum value to clamp this Point to. - * @return {Phaser.Point} This Point object. - */ + * Clamps the x value of this Point to be between the given min and max. + * + * @method Phaser.Point#clampX + * @param {number} min - The minimum value to clamp this Point to. + * @param {number} max - The maximum value to clamp this Point to. + * @return {Phaser.Point} This Point object. + */ clampX: function (min, max) { - this.x = Phaser.Math.clamp(this.x, min, max); return this; - }, /** - * Clamps the y value of this Point to be between the given min and max - * - * @method Phaser.Point#clampY - * @param {number} min - The minimum value to clamp this Point to. - * @param {number} max - The maximum value to clamp this Point to. - * @return {Phaser.Point} This Point object. - */ + * Clamps the y value of this Point to be between the given min and max + * + * @method Phaser.Point#clampY + * @param {number} min - The minimum value to clamp this Point to. + * @param {number} max - The maximum value to clamp this Point to. + * @return {Phaser.Point} This Point object. + */ clampY: function (min, max) { - this.y = Phaser.Math.clamp(this.y, min, max); return this; - }, /** - * Clamps this Point object values to be between the given min and max. - * - * @method Phaser.Point#clamp - * @param {number} min - The minimum value to clamp this Point to. - * @param {number} max - The maximum value to clamp this Point to. - * @return {Phaser.Point} This Point object. - */ + * Clamps this Point object values to be between the given min and max. + * + * @method Phaser.Point#clamp + * @param {number} min - The minimum value to clamp this Point to. + * @param {number} max - The maximum value to clamp this Point to. + * @return {Phaser.Point} This Point object. + */ clamp: function (min, max) { - this.x = Phaser.Math.clamp(this.x, min, max); this.y = Phaser.Math.clamp(this.y, min, max); return this; - }, /** - * If this Point is not within the given object, moves it inside (at the nearest edge). - * - * @method Phaser.Point#clip - * @param {any} rect - A {@link Phaser.Rectangle} or any object with left, top, right, and bottom properties. - * @return {Phaser.Point} This Point object. - */ + * If this Point is not within the given object, moves it inside (at the nearest edge). + * + * @method Phaser.Point#clip + * @param {any} rect - A {@link Phaser.Rectangle} or any object with left, top, right, and bottom properties. + * @return {Phaser.Point} This Point object. + */ clip: function (rect) { - var left = rect.left, top = rect.top, right = rect.right, @@ -263,19 +236,17 @@ Phaser.Point.prototype = { else if (this.y > bottom) { this.y = bottom; } return this; - }, /** - * Creates a copy of the given Point. - * - * @method Phaser.Point#clone - * @param {Phaser.Point} [output] Optional Point object. If given the values will be set into this object, otherwise a brand new Point object will be created and returned. - * @return {Phaser.Point} The new Point object. - */ + * Creates a copy of the given Point. + * + * @method Phaser.Point#clone + * @param {Phaser.Point} [output] Optional Point object. If given the values will be set into this object, otherwise a brand new Point object will be created and returned. + * @return {Phaser.Point} The new Point object. + */ clone: function (output) { - if (output === undefined || output === null) { output = new Phaser.Point(this.x, this.y); @@ -286,111 +257,95 @@ Phaser.Point.prototype = { } return output; - }, /** - * Copies the x and y properties from this Point to any given object. - * - * @method Phaser.Point#copyTo - * @param {any} dest - The object to copy to. - * @return {object} The dest object. - */ + * Copies the x and y properties from this Point to any given object. + * + * @method Phaser.Point#copyTo + * @param {any} dest - The object to copy to. + * @return {object} The dest object. + */ copyTo: function (dest) { - dest.x = this.x; dest.y = this.y; return dest; - }, /** - * Returns the distance of this Point object to the given object (can be a Circle, Point or anything with x/y properties) - * - * @method Phaser.Point#distance - * @param {object} dest - The target object. Must have visible x and y properties that represent the center of the object. - * @param {boolean} [round] - Round the distance to the nearest integer (default false). - * @return {number} The distance between this Point object and the destination Point object. - */ + * Returns the distance of this Point object to the given object (can be a Circle, Point or anything with x/y properties) + * + * @method Phaser.Point#distance + * @param {object} dest - The target object. Must have visible x and y properties that represent the center of the object. + * @param {boolean} [round] - Round the distance to the nearest integer (default false). + * @return {number} The distance between this Point object and the destination Point object. + */ distance: function (dest, round) { - return Phaser.Point.distance(this, dest, round); - }, /** - * Determines whether the given objects x/y values are equal to this Point object. - * - * @method Phaser.Point#equals - * @param {Phaser.Point|any} a - The object to compare with this Point. - * @return {boolean} A value of true if the x and y points are equal, otherwise false. - */ + * Determines whether the given objects x/y values are equal to this Point object. + * + * @method Phaser.Point#equals + * @param {Phaser.Point|any} a - The object to compare with this Point. + * @return {boolean} A value of true if the x and y points are equal, otherwise false. + */ equals: function (a) { - return a.x === this.x && a.y === this.y; - }, /** - * Determines whether a set of x-y coordinates are equal to this Point's. - * - * @method Phaser.Point#equalsXY - * @param {number} x - The x-coordinate to compare with this Point. - * @param {number} y - The y-coordinate to compare with this Point. - * @return {boolean} A value of true if the Point's coordinates are identical to the arguments, otherwise false. - */ + * Determines whether a set of x-y coordinates are equal to this Point's. + * + * @method Phaser.Point#equalsXY + * @param {number} x - The x-coordinate to compare with this Point. + * @param {number} y - The y-coordinate to compare with this Point. + * @return {boolean} A value of true if the Point's coordinates are identical to the arguments, otherwise false. + */ equalsXY: function (x, y) { - return this.x === x && this.y === y; - }, fuzzyEquals: function (a, epsilon) { - return Phaser.Point.fuzzyEquals(this, a, epsilon); - }, fuzzyEqualsXY: function (x, y, epsilon) { - return Phaser.Point.fuzzyEqualsXY(this, x, y, epsilon); - }, /** - * Returns the angle between this Point object and another object with public x and y properties. - * - * @method Phaser.Point#angle - * @param {Phaser.Point|any} a - The object to get the angle from this Point to. - * @param {boolean} [asDegrees=false] - Return a value in radians (false) or degrees (true)? - * @return {number} The angle, where this Point is the vertex. Within [-pi, pi] or [-180deg, 180deg]. - */ + * Returns the angle between this Point object and another object with public x and y properties. + * + * @method Phaser.Point#angle + * @param {Phaser.Point|any} a - The object to get the angle from this Point to. + * @param {boolean} [asDegrees=false] - Return a value in radians (false) or degrees (true)? + * @return {number} The angle, where this Point is the vertex. Within [-pi, pi] or [-180deg, 180deg]. + */ angle: function (a, asDegrees) { - return this.angleXY(a.x, a.y, asDegrees); - }, /** - * Returns the angle between this Point object and an x-y coordinate pair. - * - * @method Phaser.Point#angleXY - * @param {number} x - The x-coordinate - * @param {number} y - The y-coordinate - * @param {boolean} [asDegrees=false] - Return a value in radians (false) or degrees (true)? - * @return {number} The angle, where this Point is the vertex. Within [-pi, pi] or [-180deg, 180deg]. - */ + * Returns the angle between this Point object and an x-y coordinate pair. + * + * @method Phaser.Point#angleXY + * @param {number} x - The x-coordinate + * @param {number} y - The y-coordinate + * @param {boolean} [asDegrees=false] - Return a value in radians (false) or degrees (true)? + * @return {number} The angle, where this Point is the vertex. Within [-pi, pi] or [-180deg, 180deg]. + */ angleXY: function (x, y, asDegrees) { - var angle = Math.atan2(y - this.y, x - this.x); if (asDegrees) @@ -401,19 +356,17 @@ Phaser.Point.prototype = { { return angle; } - }, /** - * Returns the arctangent of this Point. - * - * @method Phaser.Point#atan - * @param {boolean} [asDegrees=false] - Return a value in radians (false) or degrees (true)? - * @return {number} The angle, where the vertex is (0, 0). Within [-pi, pi] or [-180deg, 180deg]. - */ + * Returns the arctangent of this Point. + * + * @method Phaser.Point#atan + * @param {boolean} [asDegrees=false] - Return a value in radians (false) or degrees (true)? + * @return {number} The angle, where the vertex is (0, 0). Within [-pi, pi] or [-180deg, 180deg]. + */ atan: function (asDegrees) { - var angle = Math.atan2(this.y, this.x); if (asDegrees) @@ -424,76 +377,66 @@ Phaser.Point.prototype = { { return angle; } - }, /** - * Rotates this Point around the x/y coordinates given to the desired angle. - * - * @method Phaser.Point#rotate - * @param {number} x - The x coordinate of the anchor point. - * @param {number} y - The y coordinate of the anchor point. - * @param {number} angle - The angle in radians (unless asDegrees is true) to rotate the Point to. - * @param {boolean} [asDegrees=false] - Is the given angle in radians (false) or degrees (true)? - * @param {number} [distance] - An optional distance constraint between the Point and the anchor. - * @return {Phaser.Point} The modified point object. - */ + * Rotates this Point around the x/y coordinates given to the desired angle. + * + * @method Phaser.Point#rotate + * @param {number} x - The x coordinate of the anchor point. + * @param {number} y - The y coordinate of the anchor point. + * @param {number} angle - The angle in radians (unless asDegrees is true) to rotate the Point to. + * @param {boolean} [asDegrees=false] - Is the given angle in radians (false) or degrees (true)? + * @param {number} [distance] - An optional distance constraint between the Point and the anchor. + * @return {Phaser.Point} The modified point object. + */ rotate: function (x, y, angle, asDegrees, distance) { - return Phaser.Point.rotate(this, x, y, angle, asDegrees, distance); - }, /** - * Calculates the length of the Point object. - * - * @method Phaser.Point#getMagnitude - * @return {number} The length of the Point. - */ + * Calculates the length of the Point object. + * + * @method Phaser.Point#getMagnitude + * @return {number} The length of the Point. + */ getMagnitude: function () { - return Math.sqrt((this.x * this.x) + (this.y * this.y)); - }, /** - * Calculates the length squared of the Point object. - * - * @method Phaser.Point#getMagnitudeSq - * @return {number} The length ^ 2 of the Point. - */ + * Calculates the length squared of the Point object. + * + * @method Phaser.Point#getMagnitudeSq + * @return {number} The length ^ 2 of the Point. + */ getMagnitudeSq: function () { - return (this.x * this.x) + (this.y * this.y); - }, /** - * Alters the length of the Point without changing the direction. - * - * @method Phaser.Point#setMagnitude - * @param {number} magnitude - The desired magnitude of the resulting Point. - * @return {Phaser.Point} This Point object. - */ + * Alters the length of the Point without changing the direction. + * + * @method Phaser.Point#setMagnitude + * @param {number} magnitude - The desired magnitude of the resulting Point. + * @return {Phaser.Point} This Point object. + */ setMagnitude: function (magnitude) { - return this.normalize().multiply(magnitude, magnitude); - }, /** - * Alters the Point object so that its length is 1, but it retains the same direction. - * - * @method Phaser.Point#normalize - * @return {Phaser.Point} This Point object. - */ + * Alters the Point object so that its length is 1, but it retains the same direction. + * + * @method Phaser.Point#normalize + * @return {Phaser.Point} This Point object. + */ normalize: function () { - if (!this.isZero()) { var m = this.getMagnitude(); @@ -502,179 +445,154 @@ Phaser.Point.prototype = { } return this; - }, /** - * Alters the Point object so its magnitude is at most the max value. - * - * @method Phaser.Point#limit - * @param {number} max - The maximum magnitude for the Point. - * @return {Phaser.Point} This Point object. - * @see Phaser.Point#expand - */ + * Alters the Point object so its magnitude is at most the max value. + * + * @method Phaser.Point#limit + * @param {number} max - The maximum magnitude for the Point. + * @return {Phaser.Point} This Point object. + * @see Phaser.Point#expand + */ limit: function (max) { - if (this.getMagnitudeSq() > max * max) { this.setMagnitude(max); } return this; - }, /** - * Alters the Point object so its magnitude is at least the min value. - * - * @method Phaser.Point#expand - * @param {number} min - The minimum magnitude for the Point. - * @return {Phaser.Point} This Point object. - * @see Phaser.Point#limit - */ + * Alters the Point object so its magnitude is at least the min value. + * + * @method Phaser.Point#expand + * @param {number} min - The minimum magnitude for the Point. + * @return {Phaser.Point} This Point object. + * @see Phaser.Point#limit + */ expand: function (min) { - if (this.getMagnitudeSq() < min * min) { this.setMagnitude(min); } return this; - }, /** - * Determine if this point is at 0,0. - * - * @method Phaser.Point#isZero - * @return {boolean} True if this Point is 0,0, otherwise false. - */ + * Determine if this point is at 0,0. + * + * @method Phaser.Point#isZero + * @return {boolean} True if this Point is 0,0, otherwise false. + */ isZero: function () { - return (this.x === 0 && this.y === 0); - }, /** - * The dot product of this and another Point object. - * - * @method Phaser.Point#dot - * @param {Phaser.Point} a - The Point object to get the dot product combined with this Point. - * @return {number} The result. - */ + * The dot product of this and another Point object. + * + * @method Phaser.Point#dot + * @param {Phaser.Point} a - The Point object to get the dot product combined with this Point. + * @return {number} The result. + */ dot: function (a) { - return ((this.x * a.x) + (this.y * a.y)); - }, /** - * The cross product of this and another Point object. - * - * @method Phaser.Point#cross - * @param {Phaser.Point} a - The Point object to get the cross product combined with this Point. - * @return {number} The result. - */ + * The cross product of this and another Point object. + * + * @method Phaser.Point#cross + * @param {Phaser.Point} a - The Point object to get the cross product combined with this Point. + * @return {number} The result. + */ cross: function (a) { - return ((this.x * a.y) - (this.y * a.x)); - }, /** - * Make this Point perpendicular (90 degrees rotation) - * - * @method Phaser.Point#perp - * @return {Phaser.Point} This Point object. - */ + * Make this Point perpendicular (90 degrees rotation) + * + * @method Phaser.Point#perp + * @return {Phaser.Point} This Point object. + */ perp: function () { - return this.setTo(-this.y, this.x); - }, /** - * Make this Point perpendicular (-90 degrees rotation) - * - * @method Phaser.Point#rperp - * @return {Phaser.Point} This Point object. - */ + * Make this Point perpendicular (-90 degrees rotation) + * + * @method Phaser.Point#rperp + * @return {Phaser.Point} This Point object. + */ rperp: function () { - return this.setTo(this.y, -this.x); - }, /** - * Right-hand normalize (make unit length) this Point. - * - * @method Phaser.Point#normalRightHand - * @return {Phaser.Point} This Point object. - */ + * Right-hand normalize (make unit length) this Point. + * + * @method Phaser.Point#normalRightHand + * @return {Phaser.Point} This Point object. + */ normalRightHand: function () { - return this.setTo(this.y * -1, this.x); - }, /** - * Math.floor() both the x and y properties of this Point. - * - * @method Phaser.Point#floor - * @return {Phaser.Point} This Point object. - */ + * Math.floor() both the x and y properties of this Point. + * + * @method Phaser.Point#floor + * @return {Phaser.Point} This Point object. + */ floor: function () { - return this.setTo(Math.floor(this.x), Math.floor(this.y)); - }, /** - * Math.ceil() both the x and y properties of this Point. - * - * @method Phaser.Point#ceil - * @return {Phaser.Point} This Point object. - */ + * Math.ceil() both the x and y properties of this Point. + * + * @method Phaser.Point#ceil + * @return {Phaser.Point} This Point object. + */ ceil: function () { - return this.setTo(Math.ceil(this.x), Math.ceil(this.y)); - }, /** - * Math.round() both the x and y properties of this Point. - * - * @method Phaser.Point#round - * @return {Phaser.Point} This Point object. - */ + * Math.round() both the x and y properties of this Point. + * + * @method Phaser.Point#round + * @return {Phaser.Point} This Point object. + */ round: function () { - return this.setTo(Math.round(this.x), Math.round(this.y)); - }, /** - * Returns a string representation of this object. - * - * @method Phaser.Point#toString - * @return {string} A string representation of the instance. - */ + * Returns a string representation of this object. + * + * @method Phaser.Point#toString + * @return {string} A string representation of the instance. + */ toString: function () { - return '[{Point (x=' + this.x + ' y=' + this.y + ')}]'; - } }; @@ -682,260 +600,229 @@ Phaser.Point.prototype = { Phaser.Point.prototype.constructor = Phaser.Point; /** -* Adds the coordinates of two points together to create a new point. -* -* @method Phaser.Point.add -* @param {Phaser.Point} a - The first Point object. -* @param {Phaser.Point} b - The second Point object. -* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. -* @return {Phaser.Point} The new Point object. -*/ + * Adds the coordinates of two points together to create a new point. + * + * @method Phaser.Point.add + * @param {Phaser.Point} a - The first Point object. + * @param {Phaser.Point} b - The second Point object. + * @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. + * @return {Phaser.Point} The new Point object. + */ Phaser.Point.add = function (a, b, out) { - if (out === undefined) { out = new Phaser.Point(); } out.x = a.x + b.x; out.y = a.y + b.y; return out; - }; /** -* Subtracts the coordinates of two points to create a new point. -* -* @method Phaser.Point.subtract -* @param {Phaser.Point} a - The first Point object. -* @param {Phaser.Point} b - The second Point object. -* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. -* @return {Phaser.Point} The new Point object. -*/ + * Subtracts the coordinates of two points to create a new point. + * + * @method Phaser.Point.subtract + * @param {Phaser.Point} a - The first Point object. + * @param {Phaser.Point} b - The second Point object. + * @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. + * @return {Phaser.Point} The new Point object. + */ Phaser.Point.subtract = function (a, b, out) { - if (out === undefined) { out = new Phaser.Point(); } out.x = a.x - b.x; out.y = a.y - b.y; return out; - }; /** -* Multiplies the coordinates of two points to create a new point. -* -* @method Phaser.Point.multiply -* @param {Phaser.Point} a - The first Point object. -* @param {Phaser.Point} b - The second Point object. -* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. -* @return {Phaser.Point} The new Point object. -*/ + * Multiplies the coordinates of two points to create a new point. + * + * @method Phaser.Point.multiply + * @param {Phaser.Point} a - The first Point object. + * @param {Phaser.Point} b - The second Point object. + * @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. + * @return {Phaser.Point} The new Point object. + */ Phaser.Point.multiply = function (a, b, out) { - if (out === undefined) { out = new Phaser.Point(); } out.x = a.x * b.x; out.y = a.y * b.y; return out; - }; /** -* Divides the coordinates of two points to create a new point. -* -* @method Phaser.Point.divide -* @param {Phaser.Point} a - The first Point object. -* @param {Phaser.Point} b - The second Point object. -* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. -* @return {Phaser.Point} The new Point object. -*/ + * Divides the coordinates of two points to create a new point. + * + * @method Phaser.Point.divide + * @param {Phaser.Point} a - The first Point object. + * @param {Phaser.Point} b - The second Point object. + * @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. + * @return {Phaser.Point} The new Point object. + */ Phaser.Point.divide = function (a, b, out) { - if (out === undefined) { out = new Phaser.Point(); } out.x = a.x / b.x; out.y = a.y / b.y; return out; - }; /** -* Determines whether the two given Point objects are equal. They are considered equal if they have the same x and y values. -* -* @method Phaser.Point.equals -* @param {Phaser.Point} a - The first Point object. -* @param {Phaser.Point} b - The second Point object. -* @return {boolean} A value of true if the Points are equal, otherwise false. -*/ + * Determines whether the two given Point objects are equal. They are considered equal if they have the same x and y values. + * + * @method Phaser.Point.equals + * @param {Phaser.Point} a - The first Point object. + * @param {Phaser.Point} b - The second Point object. + * @return {boolean} A value of true if the Points are equal, otherwise false. + */ Phaser.Point.equals = function (a, b) { - return a.x === b.x && a.y === b.y; - }; Phaser.Point.equalsXY = function (a, x, y) { - return a.x === x && a.y === y; - }; Phaser.Point.fuzzyEquals = function (a, b, epsilon) { - return Phaser.Math.fuzzyEqual(a.x, b.x, epsilon) && Phaser.Math.fuzzyEqual(a.y, b.y, epsilon); - }; Phaser.Point.fuzzyEqualsXY = function (a, x, y, epsilon) { - return Phaser.Math.fuzzyEqual(a.x, x, epsilon) && Phaser.Math.fuzzyEqual(a.y, y, epsilon); - }; /** -* Returns the angle between two Point objects. -* -* @method Phaser.Point.angle -* @param {Phaser.Point} a - The first Point object. -* @param {Phaser.Point} b - The second Point object. -* @return {number} The angle, where b is the vertex. Within [-pi, pi]. -*/ + * Returns the angle between two Point objects. + * + * @method Phaser.Point.angle + * @param {Phaser.Point} a - The first Point object. + * @param {Phaser.Point} b - The second Point object. + * @return {number} The angle, where b is the vertex. Within [-pi, pi]. + */ Phaser.Point.angle = function (a, b) { - return Math.atan2(a.y - b.y, a.x - b.x); - }; /** -* Creates a negative Point. -* -* @method Phaser.Point.negative -* @param {Phaser.Point} a - The first Point object. -* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. -* @return {Phaser.Point} The new Point object. -*/ + * Creates a negative Point. + * + * @method Phaser.Point.negative + * @param {Phaser.Point} a - The first Point object. + * @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. + * @return {Phaser.Point} The new Point object. + */ Phaser.Point.negative = function (a, out) { - if (out === undefined) { out = new Phaser.Point(); } return out.setTo(-a.x, -a.y); - }; /** -* Adds two 2D Points together and multiplies the result by the given scalar. -* -* @method Phaser.Point.multiplyAdd -* @param {Phaser.Point} a - The first Point object. -* @param {Phaser.Point} b - The second Point object. -* @param {number} s - The scaling value. -* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. -* @return {Phaser.Point} The new Point object. -*/ + * Adds two 2D Points together and multiplies the result by the given scalar. + * + * @method Phaser.Point.multiplyAdd + * @param {Phaser.Point} a - The first Point object. + * @param {Phaser.Point} b - The second Point object. + * @param {number} s - The scaling value. + * @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. + * @return {Phaser.Point} The new Point object. + */ Phaser.Point.multiplyAdd = function (a, b, s, out) { - if (out === undefined) { out = new Phaser.Point(); } return out.setTo(a.x + b.x * s, a.y + b.y * s); - }; /** -* Interpolates the two given Points, based on the `f` value (between 0 and 1) and returns a new Point. -* -* @method Phaser.Point.interpolate -* @param {Phaser.Point} a - The first Point object. -* @param {Phaser.Point} b - The second Point object. -* @param {number} f - The level of interpolation between the two points. Indicates where the new point will be, along the line between pt1 and pt2. If f=1, pt1 is returned; if f=0, pt2 is returned. -* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. -* @return {Phaser.Point} The new Point object. -*/ + * Interpolates the two given Points, based on the `f` value (between 0 and 1) and returns a new Point. + * + * @method Phaser.Point.interpolate + * @param {Phaser.Point} a - The first Point object. + * @param {Phaser.Point} b - The second Point object. + * @param {number} f - The level of interpolation between the two points. Indicates where the new point will be, along the line between pt1 and pt2. If f=1, pt1 is returned; if f=0, pt2 is returned. + * @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. + * @return {Phaser.Point} The new Point object. + */ Phaser.Point.interpolate = function (a, b, f, out) { - if (out === undefined) { out = new Phaser.Point(); } return out.setTo(a.x + (b.x - a.x) * f, a.y + (b.y - a.y) * f); - }; /** -* Return a perpendicular vector (90 degrees rotation) -* -* @method Phaser.Point.perp -* @param {Phaser.Point} a - The Point object. -* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. -* @return {Phaser.Point} The new Point object. -*/ + * Return a perpendicular vector (90 degrees rotation) + * + * @method Phaser.Point.perp + * @param {Phaser.Point} a - The Point object. + * @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. + * @return {Phaser.Point} The new Point object. + */ Phaser.Point.perp = function (a, out) { - if (out === undefined) { out = new Phaser.Point(); } return out.setTo(-a.y, a.x); - }; /** -* Return a perpendicular vector (-90 degrees rotation) -* -* @method Phaser.Point.rperp -* @param {Phaser.Point} a - The Point object. -* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. -* @return {Phaser.Point} The new Point object. -*/ + * Return a perpendicular vector (-90 degrees rotation) + * + * @method Phaser.Point.rperp + * @param {Phaser.Point} a - The Point object. + * @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. + * @return {Phaser.Point} The new Point object. + */ Phaser.Point.rperp = function (a, out) { - if (out === undefined) { out = new Phaser.Point(); } return out.setTo(a.y, -a.x); - }; /** -* Returns the euclidian distance of this Point object to the given object (can be a Circle, Point or anything with x/y properties). -* -* @method Phaser.Point.distance -* @param {object} a - The target object. Must have visible x and y properties that represent the center of the object. -* @param {object} b - The target object. Must have visible x and y properties that represent the center of the object. -* @param {boolean} [round=false] - Round the distance to the nearest integer. -* @return {number} The distance between this Point object and the destination Point object. -*/ + * Returns the euclidian distance of this Point object to the given object (can be a Circle, Point or anything with x/y properties). + * + * @method Phaser.Point.distance + * @param {object} a - The target object. Must have visible x and y properties that represent the center of the object. + * @param {object} b - The target object. Must have visible x and y properties that represent the center of the object. + * @param {boolean} [round=false] - Round the distance to the nearest integer. + * @return {number} The distance between this Point object and the destination Point object. + */ Phaser.Point.distance = function (a, b, round) { - var distance = Phaser.Math.distance(a.x, a.y, b.x, b.y); return round ? Math.round(distance) : distance; - }; /** -* Project two Points onto another Point. -* -* @method Phaser.Point.project -* @param {Phaser.Point} a - The first Point object. -* @param {Phaser.Point} b - The second Point object. -* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. -* @return {Phaser.Point} The new Point object. -*/ + * Project two Points onto another Point. + * + * @method Phaser.Point.project + * @param {Phaser.Point} a - The first Point object. + * @param {Phaser.Point} b - The second Point object. + * @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. + * @return {Phaser.Point} The new Point object. + */ Phaser.Point.project = function (a, b, out) { - if (out === undefined) { out = new Phaser.Point(); } var amt = a.dot(b) / b.getMagnitudeSq(); @@ -946,21 +833,19 @@ Phaser.Point.project = function (a, b, out) } return out; - }; /** -* Project two Points onto a Point of unit length. -* -* @method Phaser.Point.projectUnit -* @param {Phaser.Point} a - The first Point object. -* @param {Phaser.Point} b - The second Point object. -* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. -* @return {Phaser.Point} The new Point object. -*/ + * Project two Points onto a Point of unit length. + * + * @method Phaser.Point.projectUnit + * @param {Phaser.Point} a - The first Point object. + * @param {Phaser.Point} b - The second Point object. + * @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. + * @return {Phaser.Point} The new Point object. + */ Phaser.Point.projectUnit = function (a, b, out) { - if (out === undefined) { out = new Phaser.Point(); } var amt = a.dot(b); @@ -971,37 +856,33 @@ Phaser.Point.projectUnit = function (a, b, out) } return out; - }; /** -* Right-hand normalize (make unit length) a Point. -* -* @method Phaser.Point.normalRightHand -* @param {Phaser.Point} a - The Point object. -* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. -* @return {Phaser.Point} The new Point object. -*/ + * Right-hand normalize (make unit length) a Point. + * + * @method Phaser.Point.normalRightHand + * @param {Phaser.Point} a - The Point object. + * @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. + * @return {Phaser.Point} The new Point object. + */ Phaser.Point.normalRightHand = function (a, out) { - if (out === undefined) { out = new Phaser.Point(); } return out.setTo(a.y * -1, a.x); - }; /** -* Normalize (make unit length) a Point. -* -* @method Phaser.Point.normalize -* @param {Phaser.Point} a - The Point object. -* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. -* @return {Phaser.Point} The new Point object. -*/ + * Normalize (make unit length) a Point. + * + * @method Phaser.Point.normalize + * @param {Phaser.Point} a - The Point object. + * @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. + * @return {Phaser.Point} The new Point object. + */ Phaser.Point.normalize = function (a, out) { - if (out === undefined) { out = new Phaser.Point(); } var m = a.getMagnitude(); @@ -1012,29 +893,27 @@ Phaser.Point.normalize = function (a, out) } return out; - }; /** -* Rotates a Point object, or any object with exposed x/y properties, around the given coordinates by -* the angle specified. If the angle between the point and coordinates was 45 deg and the angle argument -* is 45 deg then the resulting angle will be 90 deg, as the angle argument is added to the current angle. -* -* The distance allows you to specify a distance constraint for the rotation between the point and the -* coordinates. If none is given the distance between the two is calculated and used. -* -* @method Phaser.Point.rotate -* @param {Phaser.Point} a - The Point object to rotate. -* @param {number} x - The x coordinate of the anchor point -* @param {number} y - The y coordinate of the anchor point -* @param {number} angle - The angle in radians (unless asDegrees is true) to rotate the Point by. -* @param {boolean} [asDegrees=false] - Is the given angle in radians (false) or degrees (true)? -* @param {number} [distance] - An optional distance constraint between the Point and the anchor. -* @return {Phaser.Point} The modified point object. -*/ + * Rotates a Point object, or any object with exposed x/y properties, around the given coordinates by + * the angle specified. If the angle between the point and coordinates was 45 deg and the angle argument + * is 45 deg then the resulting angle will be 90 deg, as the angle argument is added to the current angle. + * + * The distance allows you to specify a distance constraint for the rotation between the point and the + * coordinates. If none is given the distance between the two is calculated and used. + * + * @method Phaser.Point.rotate + * @param {Phaser.Point} a - The Point object to rotate. + * @param {number} x - The x coordinate of the anchor point + * @param {number} y - The y coordinate of the anchor point + * @param {number} angle - The angle in radians (unless asDegrees is true) to rotate the Point by. + * @param {boolean} [asDegrees=false] - Is the given angle in radians (false) or degrees (true)? + * @param {number} [distance] - An optional distance constraint between the Point and the anchor. + * @return {Phaser.Point} The modified point object. + */ Phaser.Point.rotate = function (a, x, y, angle, asDegrees, distance) { - if (asDegrees) { angle = Phaser.Math.degToRad(angle); } if (distance === undefined) @@ -1058,20 +937,18 @@ Phaser.Point.rotate = function (a, x, y, angle, asDegrees, distance) } return a; - }; /** -* Calculates centroid (or midpoint) from an array of points. If only one point is provided, that point is returned. -* -* @method Phaser.Point.centroid -* @param {Phaser.Point[]} points - The array of one or more points. -* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. -* @return {Phaser.Point} The new Point object. -*/ + * Calculates centroid (or midpoint) from an array of points. If only one point is provided, that point is returned. + * + * @method Phaser.Point.centroid + * @param {Phaser.Point[]} points - The array of one or more points. + * @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. + * @return {Phaser.Point} The new Point object. + */ Phaser.Point.centroid = function (points, out) { - if (out === undefined) { out = new Phaser.Point(); } if (Object.prototype.toString.call(points) !== '[object Array]') @@ -1100,23 +977,21 @@ Phaser.Point.centroid = function (points, out) out.divide(pointslength, pointslength); return out; - }; /** -* Parses an object for x and/or y properties and returns a new Phaser.Point with matching values. -* If the object doesn't contain those properties a Point with x/y of zero will be returned. -* -* @method Phaser.Point.parse -* @static -* @param {object} obj - The object to parse. -* @param {string} [xProp='x'] - The property used to set the Point.x value. -* @param {string} [yProp='y'] - The property used to set the Point.y value. -* @return {Phaser.Point} The new Point object. -*/ + * Parses an object for x and/or y properties and returns a new Phaser.Point with matching values. + * If the object doesn't contain those properties a Point with x/y of zero will be returned. + * + * @method Phaser.Point.parse + * @static + * @param {object} obj - The object to parse. + * @param {string} [xProp='x'] - The property used to set the Point.x value. + * @param {string} [yProp='y'] - The property used to set the Point.y value. + * @return {Phaser.Point} The new Point object. + */ Phaser.Point.parse = function (obj, xProp, yProp) { - xProp = xProp || 'x'; yProp = yProp || 'y'; @@ -1133,17 +1008,16 @@ Phaser.Point.parse = function (obj, xProp, yProp) } return point; - }; /** -* Truncates the x and y values, removing any fractional parts. -* -* @method Phaser.Point.trunc -* @static -* @param {object} obj - The Point. -* @return {object} The modified Point. -*/ + * Truncates the x and y values, removing any fractional parts. + * + * @method Phaser.Point.trunc + * @static + * @param {object} obj - The Point. + * @return {object} The modified Point. + */ Phaser.Point.trunc = function (obj) { obj.x = Phaser.Math.trunc(obj.x); @@ -1162,48 +1036,43 @@ Phaser.Point.trunc = function (obj) */ Phaser.Point.isPoint = function (obj) { - return (obj != null) && (typeof obj.x === 'number') && (typeof obj.y === 'number'); - }; /** -* Sets the `x` and `y` values of an object and returns the object. -* -* @method Phaser.Point#set -* @static -* @param {object} obj - An object with numeric x and y properties. -* @param {number} x - The x value. -* @param {number} [y] - The y value. If not given the x value will be used in its place. -* @return {object} The object. Useful for chaining method calls. -*/ + * Sets the `x` and `y` values of an object and returns the object. + * + * @method Phaser.Point#set + * @static + * @param {object} obj - An object with numeric x and y properties. + * @param {number} x - The x value. + * @param {number} [y] - The y value. If not given the x value will be used in its place. + * @return {object} The object. Useful for chaining method calls. + */ Phaser.Point.set = function (obj, x, y) { - obj.x = x || 0; obj.y = y || ((y !== 0) ? obj.x : 0); return obj; - }; /** -* Sorts an array of points in a clockwise direction, relative to a reference point. -* -* The sort is clockwise relative to the display, starting from a 12 o'clock position. -* (In the Cartesian plane, it is anticlockwise, starting from the -y direction.) -* -* Example sequence: (0, -1), (1, 0), (0, 1), (-1, 0) -* -* @method Phaser.Point#sortClockwise -* @static -* @param {array} points - An array of Points or point-like objects (e.g., sprites). -* @param {object|Phaser.Point} [center] - The reference point. If omitted, the {@link #centroid} (midpoint) of the points is used. -* @return {array} The sorted array. -*/ + * Sorts an array of points in a clockwise direction, relative to a reference point. + * + * The sort is clockwise relative to the display, starting from a 12 o'clock position. + * (In the Cartesian plane, it is anticlockwise, starting from the -y direction.) + * + * Example sequence: (0, -1), (1, 0), (0, 1), (-1, 0) + * + * @method Phaser.Point#sortClockwise + * @static + * @param {array} points - An array of Points or point-like objects (e.g., sprites). + * @param {object|Phaser.Point} [center] - The reference point. If omitted, the {@link #centroid} (midpoint) of the points is used. + * @return {array} The sorted array. + */ Phaser.Point.sortClockwise = function (points, center) { - // Adapted from (ciamej) if (!center) @@ -1249,8 +1118,10 @@ Phaser.Point.sortClockwise = function (points, center) return 1; } - // Points a and b are on the same line from the center - // Check which point is closer to the center + /* + * Points a and b are on the same line from the center + * Check which point is closer to the center + */ var d1 = (a.x - cx) * (a.x - cx) + (a.y - cy) * (a.y - cy); var d2 = (b.x - cx) * (b.x - cx) + (b.y - cy) * (b.y - cy); @@ -1258,7 +1129,6 @@ Phaser.Point.sortClockwise = function (points, center) }; return points.sort(sort); - }; diff --git a/src/geom/Polygon.js b/src/geom/Polygon.js index 7d7377da4..128de0aaa 100644 --- a/src/geom/Polygon.js +++ b/src/geom/Polygon.js @@ -1,38 +1,37 @@ /** -* @author Richard Davey -* @author Adrien Brault -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @author Adrien Brault + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* Creates a new Polygon. -* -* The points can be set from a variety of formats: -* -* - An array of Point objects: `[new Phaser.Point(x1, y1), ...]` -* - An array of objects with public x/y properties: `[obj1, obj2, ...]` -* - An array of paired numbers that represent point coordinates: `[x1,y1, x2,y2, ...]` -* - As separate Point arguments: `setTo(new Phaser.Point(x1, y1), ...)` -* - As separate objects with public x/y properties arguments: `setTo(obj1, obj2, ...)` -* - As separate arguments representing point coordinates: `setTo(x1,y1, x2,y2, ...)` -* -* @class Phaser.Polygon -* @constructor -* @param {Phaser.Point[]|number[]|...Phaser.Point|...number} points - The points to set. -*/ + * Creates a new Polygon. + * + * The points can be set from a variety of formats: + * + * - An array of Point objects: `[new Phaser.Point(x1, y1), ...]` + * - An array of objects with public x/y properties: `[obj1, obj2, ...]` + * - An array of paired numbers that represent point coordinates: `[x1,y1, x2,y2, ...]` + * - As separate Point arguments: `setTo(new Phaser.Point(x1, y1), ...)` + * - As separate objects with public x/y properties arguments: `setTo(obj1, obj2, ...)` + * - As separate arguments representing point coordinates: `setTo(x1,y1, x2,y2, ...)` + * + * @class Phaser.Polygon + * @constructor + * @param {Phaser.Point[]|number[]|...Phaser.Point|...number} points - The points to set. + */ Phaser.Polygon = function () { - /** - * @property {number} area - The area of this Polygon. - */ + * @property {number} area - The area of this Polygon. + */ this.area = 0; /** - * @property {array} _points - An array of Points that make up this Polygon. - * @private - */ + * @property {array} _points - An array of Points that make up this Polygon. + * @private + */ this._points = []; if (arguments.length > 0) @@ -41,20 +40,19 @@ Phaser.Polygon = function () } /** - * @property {boolean} closed - Is the Polygon closed or not? - */ + * @property {boolean} closed - Is the Polygon closed or not? + */ this.closed = true; /** - * @property {boolean} flattened - Has this Polygon been flattened by a call to `Polygon.flatten` ? - */ + * @property {boolean} flattened - Has this Polygon been flattened by a call to `Polygon.flatten` ? + */ this.flattened = false; /** * @property {number} type - The base object type. */ this.type = Phaser.POLYGON; - }; Phaser.Polygon.prototype = { @@ -68,7 +66,6 @@ Phaser.Polygon.prototype = { */ toNumberArray: function (output) { - if (output === undefined) { output = []; } for (var i = 0; i < this._points.length; i++) @@ -87,7 +84,6 @@ Phaser.Polygon.prototype = { } return output; - }, /** @@ -100,13 +96,11 @@ Phaser.Polygon.prototype = { */ flatten: function () { - this._points = this.toNumberArray(); this.flattened = true; return this; - }, /** @@ -119,7 +113,6 @@ Phaser.Polygon.prototype = { */ clone: function (output) { - var points = this._points.slice(); if (output === undefined || output === null) @@ -132,20 +125,18 @@ Phaser.Polygon.prototype = { } return output; - }, /** - * Checks whether the x and y coordinates are contained within this polygon. - * - * @method Phaser.Polygon#contains - * @param {number} x - The X value of the coordinate to test. - * @param {number} y - The Y value of the coordinate to test. - * @return {boolean} True if the coordinates are within this polygon, otherwise false. - */ + * Checks whether the x and y coordinates are contained within this polygon. + * + * @method Phaser.Polygon#contains + * @param {number} x - The X value of the coordinate to test. + * @param {number} y - The Y value of the coordinate to test. + * @return {boolean} True if the coordinates are within this polygon, otherwise false. + */ contains: function (x, y) { - // Adapted from http://www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/pnpoly.html by Jonas Raoni Soares Silva var inside = false; @@ -165,7 +156,6 @@ Phaser.Polygon.prototype = { inside = !inside; } } - } else { @@ -185,7 +175,6 @@ Phaser.Polygon.prototype = { } return inside; - }, /** @@ -209,7 +198,6 @@ Phaser.Polygon.prototype = { */ setTo: function (points) { - this.area = 0; this._points = []; @@ -253,7 +241,6 @@ Phaser.Polygon.prototype = { } return this; - }, /** @@ -266,7 +253,6 @@ Phaser.Polygon.prototype = { */ calculateArea: function (y0) { - var p1; var p2; var avgHeight; @@ -291,7 +277,6 @@ Phaser.Polygon.prototype = { } return this.area; - } }; @@ -299,14 +284,14 @@ Phaser.Polygon.prototype = { Phaser.Polygon.prototype.constructor = Phaser.Polygon; /** -* The points of this polygon. -* -* You can modify these with {@link Phaser.Polygon#setTo setTo}. -* -* @name Phaser.Polygon#points -* @property {Phaser.Point[]} points - The array of vertex points. -* @readonly -*/ + * The points of this polygon. + * + * You can modify these with {@link Phaser.Polygon#setTo setTo}. + * + * @name Phaser.Polygon#points + * @property {Phaser.Point[]} points - The array of vertex points. + * @readonly + */ Object.defineProperty(Phaser.Polygon.prototype, 'points', { get: function () diff --git a/src/geom/Rectangle.js b/src/geom/Rectangle.js index fc0ac6880..f35899a3d 100644 --- a/src/geom/Rectangle.js +++ b/src/geom/Rectangle.js @@ -1,444 +1,393 @@ /** -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* Creates a new Rectangle object with the top-left corner specified by the x and y parameters and with the specified width and height parameters. -* If you call this function without parameters, a Rectangle with x, y, width, and height properties set to 0 is created. -* -* @class Phaser.Rectangle -* @constructor -* @param {number} x - The x coordinate of the top-left corner of the Rectangle. -* @param {number} y - The y coordinate of the top-left corner of the Rectangle. -* @param {number} width - The width of the Rectangle. Should always be either zero or a positive value. -* @param {number} height - The height of the Rectangle. Should always be either zero or a positive value. -*/ + * Creates a new Rectangle object with the top-left corner specified by the x and y parameters and with the specified width and height parameters. + * If you call this function without parameters, a Rectangle with x, y, width, and height properties set to 0 is created. + * + * @class Phaser.Rectangle + * @constructor + * @param {number} x - The x coordinate of the top-left corner of the Rectangle. + * @param {number} y - The y coordinate of the top-left corner of the Rectangle. + * @param {number} width - The width of the Rectangle. Should always be either zero or a positive value. + * @param {number} height - The height of the Rectangle. Should always be either zero or a positive value. + */ Phaser.Rectangle = function (x, y, width, height) { - x = x || 0; y = y || 0; width = width || 0; height = height || 0; /** - * @property {number} x - The x coordinate of the top-left corner of the Rectangle. - */ + * @property {number} x - The x coordinate of the top-left corner of the Rectangle. + */ this.x = x; /** - * @property {number} y - The y coordinate of the top-left corner of the Rectangle. - */ + * @property {number} y - The y coordinate of the top-left corner of the Rectangle. + */ this.y = y; /** - * @property {number} width - The width of the Rectangle. This value should never be set to a negative. - */ + * @property {number} width - The width of the Rectangle. This value should never be set to a negative. + */ this.width = width; /** - * @property {number} height - The height of the Rectangle. This value should never be set to a negative. - */ + * @property {number} height - The height of the Rectangle. This value should never be set to a negative. + */ this.height = height; /** - * @property {number} type - The const type of this object. - * @readonly - */ + * @property {number} type - The const type of this object. + * @readonly + */ this.type = Phaser.RECTANGLE; - }; Phaser.Rectangle.prototype = { /** - * Adjusts the location of the Rectangle object, as determined by its top-left corner, by the specified amounts. - * @method Phaser.Rectangle#offset - * @param {number} dx - Moves the x value of the Rectangle object by this amount. - * @param {number} dy - Moves the y value of the Rectangle object by this amount. - * @return {Phaser.Rectangle} This Rectangle object. - */ + * Adjusts the location of the Rectangle object, as determined by its top-left corner, by the specified amounts. + * @method Phaser.Rectangle#offset + * @param {number} dx - Moves the x value of the Rectangle object by this amount. + * @param {number} dy - Moves the y value of the Rectangle object by this amount. + * @return {Phaser.Rectangle} This Rectangle object. + */ offset: function (dx, dy) { - this.x += dx; this.y += dy; return this; - }, /** - * Adjusts the location of the Rectangle object using a Point object as a parameter. This method is similar to the Rectangle.offset() method, except that it takes a Point object as a parameter. - * @method Phaser.Rectangle#offsetPoint - * @param {Phaser.Point} point - A Point object to use to offset this Rectangle object. - * @return {Phaser.Rectangle} This Rectangle object. - */ + * Adjusts the location of the Rectangle object using a Point object as a parameter. This method is similar to the Rectangle.offset() method, except that it takes a Point object as a parameter. + * @method Phaser.Rectangle#offsetPoint + * @param {Phaser.Point} point - A Point object to use to offset this Rectangle object. + * @return {Phaser.Rectangle} This Rectangle object. + */ offsetPoint: function (point) { - return this.offset(point.x, point.y); - }, /** - * Sets the members of Rectangle to the specified values. - * @method Phaser.Rectangle#setTo - * @param {number} x - The x coordinate of the top-left corner of the Rectangle. - * @param {number} y - The y coordinate of the top-left corner of the Rectangle. - * @param {number} width - The width of the Rectangle. Should always be either zero or a positive value. - * @param {number} height - The height of the Rectangle. Should always be either zero or a positive value. - * @return {Phaser.Rectangle} This Rectangle object - */ + * Sets the members of Rectangle to the specified values. + * @method Phaser.Rectangle#setTo + * @param {number} x - The x coordinate of the top-left corner of the Rectangle. + * @param {number} y - The y coordinate of the top-left corner of the Rectangle. + * @param {number} width - The width of the Rectangle. Should always be either zero or a positive value. + * @param {number} height - The height of the Rectangle. Should always be either zero or a positive value. + * @return {Phaser.Rectangle} This Rectangle object + */ setTo: function (x, y, width, height) { - this.x = x; this.y = y; this.width = width; this.height = height; return this; - }, /** - * Scales the width and height of this Rectangle by the given amounts. - * - * @method Phaser.Rectangle#scale - * @param {number} x - The amount to scale the width of the Rectangle by. A value of 0.5 would reduce by half, a value of 2 would double the width, etc. - * @param {number} [y] - The amount to scale the height of the Rectangle by. A value of 0.5 would reduce by half, a value of 2 would double the height, etc. - * @return {Phaser.Rectangle} This Rectangle object - */ + * Scales the width and height of this Rectangle by the given amounts. + * + * @method Phaser.Rectangle#scale + * @param {number} x - The amount to scale the width of the Rectangle by. A value of 0.5 would reduce by half, a value of 2 would double the width, etc. + * @param {number} [y] - The amount to scale the height of the Rectangle by. A value of 0.5 would reduce by half, a value of 2 would double the height, etc. + * @return {Phaser.Rectangle} This Rectangle object + */ scale: function (x, y) { - if (y === undefined) { y = x; } this.width *= x; this.height *= y; return this; - }, /** - * Centers this Rectangle so that the center coordinates match the given x and y values. - * - * @method Phaser.Rectangle#centerOn - * @param {number} x - The x coordinate to place the center of the Rectangle at. - * @param {number} y - The y coordinate to place the center of the Rectangle at. - * @return {Phaser.Rectangle} This Rectangle object - */ + * Centers this Rectangle so that the center coordinates match the given x and y values. + * + * @method Phaser.Rectangle#centerOn + * @param {number} x - The x coordinate to place the center of the Rectangle at. + * @param {number} y - The y coordinate to place the center of the Rectangle at. + * @return {Phaser.Rectangle} This Rectangle object + */ centerOn: function (x, y) { - this.centerX = x; this.centerY = y; return this; - }, /** - * Runs Math.floor() on both the x and y values of this Rectangle. - * @method Phaser.Rectangle#floor - */ + * Runs Math.floor() on both the x and y values of this Rectangle. + * @method Phaser.Rectangle#floor + */ floor: function () { - this.x = Math.floor(this.x); this.y = Math.floor(this.y); - }, /** - * Runs Math.floor() on the x, y, width and height values of this Rectangle. - * @method Phaser.Rectangle#floorAll - */ + * Runs Math.floor() on the x, y, width and height values of this Rectangle. + * @method Phaser.Rectangle#floorAll + */ floorAll: function () { - this.x = Math.floor(this.x); this.y = Math.floor(this.y); this.width = Math.floor(this.width); this.height = Math.floor(this.height); - }, /** - * Runs Math.ceil() on both the x and y values of this Rectangle. - * @method Phaser.Rectangle#ceil - */ + * Runs Math.ceil() on both the x and y values of this Rectangle. + * @method Phaser.Rectangle#ceil + */ ceil: function () { - this.x = Math.ceil(this.x); this.y = Math.ceil(this.y); - }, /** - * Runs Math.ceil() on the x, y, width and height values of this Rectangle. - * @method Phaser.Rectangle#ceilAll - */ + * Runs Math.ceil() on the x, y, width and height values of this Rectangle. + * @method Phaser.Rectangle#ceilAll + */ ceilAll: function () { - this.x = Math.ceil(this.x); this.y = Math.ceil(this.y); this.width = Math.ceil(this.width); this.height = Math.ceil(this.height); - }, /** - * Copies the x, y, width and height properties from any given object to this Rectangle. - * @method Phaser.Rectangle#copyFrom - * @param {any} source - The object to copy from. - * @return {Phaser.Rectangle} This Rectangle object. - */ + * Copies the x, y, width and height properties from any given object to this Rectangle. + * @method Phaser.Rectangle#copyFrom + * @param {any} source - The object to copy from. + * @return {Phaser.Rectangle} This Rectangle object. + */ copyFrom: function (source) { - return this.setTo(source.x, source.y, source.width, source.height); - }, /** - * Copies the left, top, width and height properties from any given object to this Rectangle. - * @method Phaser.Rectangle#copyFromBounds - * @param {any} source - The object to copy from. - * @return {Phaser.Rectangle} This Rectangle object. - */ + * Copies the left, top, width and height properties from any given object to this Rectangle. + * @method Phaser.Rectangle#copyFromBounds + * @param {any} source - The object to copy from. + * @return {Phaser.Rectangle} This Rectangle object. + */ copyFromBounds: function (source) { - return this.setTo(source.left, source.top, source.width, source.height); - }, /** - * Copies the x, y, width and height properties from this Rectangle to any given object. - * @method Phaser.Rectangle#copyTo - * @param {any} source - The object to copy to. - * @return {object} This object. - */ + * Copies the x, y, width and height properties from this Rectangle to any given object. + * @method Phaser.Rectangle#copyTo + * @param {any} source - The object to copy to. + * @return {object} This object. + */ copyTo: function (dest) { - dest.x = this.x; dest.y = this.y; dest.width = this.width; dest.height = this.height; return dest; - }, /** - * Increases the size of the Rectangle object by the specified amounts. The center point of the Rectangle object stays the same, and its size increases to the left and right by the dx value, and to the top and the bottom by the dy value. - * @method Phaser.Rectangle#inflate - * @param {number} dx - The amount to be added to the left side of the Rectangle. - * @param {number} dy - The amount to be added to the bottom side of the Rectangle. - * @return {Phaser.Rectangle} This Rectangle object. - */ + * Increases the size of the Rectangle object by the specified amounts. The center point of the Rectangle object stays the same, and its size increases to the left and right by the dx value, and to the top and the bottom by the dy value. + * @method Phaser.Rectangle#inflate + * @param {number} dx - The amount to be added to the left side of the Rectangle. + * @param {number} dy - The amount to be added to the bottom side of the Rectangle. + * @return {Phaser.Rectangle} This Rectangle object. + */ inflate: function (dx, dy) { - return Phaser.Rectangle.inflate(this, dx, dy); - }, /** - * The size of the Rectangle object, expressed as a Point object with the values of the width and height properties. - * @method Phaser.Rectangle#size - * @param {Phaser.Point} [output] - Optional Point object. If given the values will be set into the object, otherwise a brand new Point object will be created and returned. - * @return {Phaser.Point} The size of the Rectangle object. - */ + * The size of the Rectangle object, expressed as a Point object with the values of the width and height properties. + * @method Phaser.Rectangle#size + * @param {Phaser.Point} [output] - Optional Point object. If given the values will be set into the object, otherwise a brand new Point object will be created and returned. + * @return {Phaser.Point} The size of the Rectangle object. + */ size: function (output) { - return Phaser.Rectangle.size(this, output); - }, /** - * Resize the Rectangle by providing a new width and height. - * The x and y positions remain unchanged. - * - * @method Phaser.Rectangle#resize - * @param {number} width - The width of the Rectangle. Should always be either zero or a positive value. - * @param {number} height - The height of the Rectangle. Should always be either zero or a positive value. - * @return {Phaser.Rectangle} This Rectangle object - */ + * Resize the Rectangle by providing a new width and height. + * The x and y positions remain unchanged. + * + * @method Phaser.Rectangle#resize + * @param {number} width - The width of the Rectangle. Should always be either zero or a positive value. + * @param {number} height - The height of the Rectangle. Should always be either zero or a positive value. + * @return {Phaser.Rectangle} This Rectangle object + */ resize: function (width, height) { - this.width = width; this.height = height; return this; - }, /** - * Returns a new Rectangle object with the same values for the x, y, width, and height properties as the original Rectangle object. - * @method Phaser.Rectangle#clone - * @param {Phaser.Rectangle} [output] - Optional Rectangle object. If given the values will be set into the object, otherwise a brand new Rectangle object will be created and returned. - * @return {Phaser.Rectangle} - */ + * Returns a new Rectangle object with the same values for the x, y, width, and height properties as the original Rectangle object. + * @method Phaser.Rectangle#clone + * @param {Phaser.Rectangle} [output] - Optional Rectangle object. If given the values will be set into the object, otherwise a brand new Rectangle object will be created and returned. + * @return {Phaser.Rectangle} + */ clone: function (output) { - return Phaser.Rectangle.clone(this, output); - }, /** - * Determines whether the specified coordinates are contained within the region defined by this Rectangle object. - * @method Phaser.Rectangle#contains - * @param {number} x - The x coordinate of the point to test. - * @param {number} y - The y coordinate of the point to test. - * @return {boolean} A value of true if the Rectangle object contains the specified point; otherwise false. - */ + * Determines whether the specified coordinates are contained within the region defined by this Rectangle object. + * @method Phaser.Rectangle#contains + * @param {number} x - The x coordinate of the point to test. + * @param {number} y - The y coordinate of the point to test. + * @return {boolean} A value of true if the Rectangle object contains the specified point; otherwise false. + */ contains: function (x, y) { - return Phaser.Rectangle.contains(this, x, y); - }, /** - * Determines whether the first Rectangle object is fully contained within the second Rectangle object. - * A Rectangle object is said to contain another if the second Rectangle object falls entirely within the boundaries of the first. - * @method Phaser.Rectangle#containsRect - * @param {Phaser.Rectangle} b - The second Rectangle object. - * @return {boolean} A value of true if the Rectangle object contains the specified point; otherwise false. - */ + * Determines whether the first Rectangle object is fully contained within the second Rectangle object. + * A Rectangle object is said to contain another if the second Rectangle object falls entirely within the boundaries of the first. + * @method Phaser.Rectangle#containsRect + * @param {Phaser.Rectangle} b - The second Rectangle object. + * @return {boolean} A value of true if the Rectangle object contains the specified point; otherwise false. + */ containsRect: function (b) { - return Phaser.Rectangle.containsRect(b, this); - }, /** - * Determines whether the two Rectangles are equal. - * This method compares the x, y, width and height properties of each Rectangle. - * @method Phaser.Rectangle#equals - * @param {Phaser.Rectangle} b - The second Rectangle object. - * @return {boolean} A value of true if the two Rectangles have exactly the same values for the x, y, width and height properties; otherwise false. - */ + * Determines whether the two Rectangles are equal. + * This method compares the x, y, width and height properties of each Rectangle. + * @method Phaser.Rectangle#equals + * @param {Phaser.Rectangle} b - The second Rectangle object. + * @return {boolean} A value of true if the two Rectangles have exactly the same values for the x, y, width and height properties; otherwise false. + */ equals: function (b) { - return Phaser.Rectangle.equals(this, b); - }, /** - * If the Rectangle object specified in the toIntersect parameter intersects with this Rectangle object, returns the area of intersection as a Rectangle object. If the Rectangles do not intersect, this method returns an empty Rectangle object with its properties set to 0. - * @method Phaser.Rectangle#intersection - * @param {Phaser.Rectangle} b - The second Rectangle object. - * @param {Phaser.Rectangle} out - Optional Rectangle object. If given the intersection values will be set into this object, otherwise a brand new Rectangle object will be created and returned. - * @return {Phaser.Rectangle} A Rectangle object that equals the area of intersection. If the Rectangles do not intersect, this method returns an empty Rectangle object; that is, a Rectangle with its x, y, width, and height properties set to 0. - */ + * If the Rectangle object specified in the toIntersect parameter intersects with this Rectangle object, returns the area of intersection as a Rectangle object. If the Rectangles do not intersect, this method returns an empty Rectangle object with its properties set to 0. + * @method Phaser.Rectangle#intersection + * @param {Phaser.Rectangle} b - The second Rectangle object. + * @param {Phaser.Rectangle} out - Optional Rectangle object. If given the intersection values will be set into this object, otherwise a brand new Rectangle object will be created and returned. + * @return {Phaser.Rectangle} A Rectangle object that equals the area of intersection. If the Rectangles do not intersect, this method returns an empty Rectangle object; that is, a Rectangle with its x, y, width, and height properties set to 0. + */ intersection: function (b, out) { - return Phaser.Rectangle.intersection(this, b, out); - }, /** - * Determines whether this Rectangle and another given Rectangle intersect with each other. - * This method checks the x, y, width, and height properties of the two Rectangles. - * - * @method Phaser.Rectangle#intersects - * @param {Phaser.Rectangle} b - The second Rectangle object. - * @return {boolean} A value of true if the specified object intersects with this Rectangle object; otherwise false. - */ + * Determines whether this Rectangle and another given Rectangle intersect with each other. + * This method checks the x, y, width, and height properties of the two Rectangles. + * + * @method Phaser.Rectangle#intersects + * @param {Phaser.Rectangle} b - The second Rectangle object. + * @return {boolean} A value of true if the specified object intersects with this Rectangle object; otherwise false. + */ intersects: function (b) { - return Phaser.Rectangle.intersects(this, b); - }, /** - * Determines whether the coordinates given intersects (overlaps) with this Rectangle. - * - * @method Phaser.Rectangle#intersectsRaw - * @param {number} left - The x coordinate of the left of the area. - * @param {number} right - The right coordinate of the area. - * @param {number} top - The y coordinate of the area. - * @param {number} bottom - The bottom coordinate of the area. - * @param {number} tolerance - A tolerance value to allow for an intersection test with padding, default to 0 - * @return {boolean} A value of true if the specified object intersects with the Rectangle; otherwise false. - */ + * Determines whether the coordinates given intersects (overlaps) with this Rectangle. + * + * @method Phaser.Rectangle#intersectsRaw + * @param {number} left - The x coordinate of the left of the area. + * @param {number} right - The right coordinate of the area. + * @param {number} top - The y coordinate of the area. + * @param {number} bottom - The bottom coordinate of the area. + * @param {number} tolerance - A tolerance value to allow for an intersection test with padding, default to 0 + * @return {boolean} A value of true if the specified object intersects with the Rectangle; otherwise false. + */ intersectsRaw: function (left, right, top, bottom, tolerance) { - return Phaser.Rectangle.intersectsRaw(this, left, right, top, bottom, tolerance); - }, /** - * Adds two Rectangles together to create a new Rectangle object, by filling in the horizontal and vertical space between the two Rectangles. - * @method Phaser.Rectangle#union - * @param {Phaser.Rectangle} b - The second Rectangle object. - * @param {Phaser.Rectangle} [out] - Optional Rectangle object. If given the new values will be set into this object, otherwise a brand new Rectangle object will be created and returned. - * @return {Phaser.Rectangle} A Rectangle object that is the union of the two Rectangles. - */ + * Adds two Rectangles together to create a new Rectangle object, by filling in the horizontal and vertical space between the two Rectangles. + * @method Phaser.Rectangle#union + * @param {Phaser.Rectangle} b - The second Rectangle object. + * @param {Phaser.Rectangle} [out] - Optional Rectangle object. If given the new values will be set into this object, otherwise a brand new Rectangle object will be created and returned. + * @return {Phaser.Rectangle} A Rectangle object that is the union of the two Rectangles. + */ union: function (b, out) { - return Phaser.Rectangle.union(this, b, out); - }, /** - * Returns a uniformly distributed random point from anywhere within this Rectangle. - * - * @method Phaser.Rectangle#random - * @param {Phaser.Point|object} [out] - A Phaser.Point, or any object with public x/y properties, that the values will be set in. - * If no object is provided a new Phaser.Point object will be created. In high performance areas avoid this by re-using an existing object. - * @return {Phaser.Point} An object containing the random point in its `x` and `y` properties. - */ + * Returns a uniformly distributed random point from anywhere within this Rectangle. + * + * @method Phaser.Rectangle#random + * @param {Phaser.Point|object} [out] - A Phaser.Point, or any object with public x/y properties, that the values will be set in. + * If no object is provided a new Phaser.Point object will be created. In high performance areas avoid this by re-using an existing object. + * @return {Phaser.Point} An object containing the random point in its `x` and `y` properties. + */ random: function (out) { - if (out === undefined) { out = new Phaser.Point(); } out.x = this.randomX; out.y = this.randomY; return out; - }, /** - * Returns a point based on the given position constant, which can be one of: - * - * `Phaser.TOP_LEFT`, `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, - * `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` - * and `Phaser.BOTTOM_RIGHT`. - * - * This method returns the same values as calling Rectangle.bottomLeft, etc, but those - * calls always create a new Point object, where-as this one allows you to use your own. - * - * @method Phaser.Rectangle#getPoint - * @param {integer} [position] - One of the Phaser position constants, such as `Phaser.TOP_RIGHT`. - * @param {Phaser.Point} [out] - A Phaser.Point that the values will be set in. - * If no object is provided a new Phaser.Point object will be created. In high performance areas avoid this by re-using an existing object. - * @return {Phaser.Point} An object containing the point in its `x` and `y` properties. - */ + * Returns a point based on the given position constant, which can be one of: + * + * `Phaser.TOP_LEFT`, `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, + * `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` + * and `Phaser.BOTTOM_RIGHT`. + * + * This method returns the same values as calling Rectangle.bottomLeft, etc, but those + * calls always create a new Point object, where-as this one allows you to use your own. + * + * @method Phaser.Rectangle#getPoint + * @param {integer} [position] - One of the Phaser position constants, such as `Phaser.TOP_RIGHT`. + * @param {Phaser.Point} [out] - A Phaser.Point that the values will be set in. + * If no object is provided a new Phaser.Point object will be created. In high performance areas avoid this by re-using an existing object. + * @return {Phaser.Point} An object containing the point in its `x` and `y` properties. + */ getPoint: function (position, out) { - if (out === undefined) { out = new Phaser.Point(); } switch (position) @@ -471,7 +420,6 @@ Phaser.Rectangle.prototype = { case Phaser.BOTTOM_RIGHT: return out.set(this.right, this.bottom); } - }, /** @@ -486,7 +434,6 @@ Phaser.Rectangle.prototype = { */ sides: function (top, right, bottom, left) { - if (!arguments.length) { top = new Phaser.Line(); @@ -511,28 +458,25 @@ Phaser.Rectangle.prototype = { } return null; - }, /** - * Returns a string representation of this object. - * @method Phaser.Rectangle#toString - * @return {string} A string representation of the instance. - */ + * Returns a string representation of this object. + * @method Phaser.Rectangle#toString + * @return {string} A string representation of the instance. + */ toString: function () { - return '[{Rectangle (x=' + this.x + ' y=' + this.y + ' width=' + this.width + ' height=' + this.height + ' empty=' + this.empty + ')}]'; - } }; /** -* @name Phaser.Rectangle#halfWidth -* @property {number} halfWidth - Half of the width of the Rectangle. -* @readonly -*/ + * @name Phaser.Rectangle#halfWidth + * @property {number} halfWidth - Half of the width of the Rectangle. + * @readonly + */ Object.defineProperty(Phaser.Rectangle.prototype, 'halfWidth', { get: function () @@ -543,10 +487,10 @@ Object.defineProperty(Phaser.Rectangle.prototype, 'halfWidth', { }); /** -* @name Phaser.Rectangle#halfHeight -* @property {number} halfHeight - Half of the height of the Rectangle. -* @readonly -*/ + * @name Phaser.Rectangle#halfHeight + * @property {number} halfHeight - Half of the height of the Rectangle. + * @readonly + */ Object.defineProperty(Phaser.Rectangle.prototype, 'halfHeight', { get: function () @@ -557,10 +501,10 @@ Object.defineProperty(Phaser.Rectangle.prototype, 'halfHeight', { }); /** -* The sum of the y and height properties. Changing the bottom property of a Rectangle object has no effect on the x, y and width properties, but does change the height property. -* @name Phaser.Rectangle#bottom -* @property {number} bottom - The sum of the y and height properties. -*/ + * The sum of the y and height properties. Changing the bottom property of a Rectangle object has no effect on the x, y and width properties, but does change the height property. + * @name Phaser.Rectangle#bottom + * @property {number} bottom - The sum of the y and height properties. + */ Object.defineProperty(Phaser.Rectangle.prototype, 'bottom', { get: function () @@ -570,7 +514,6 @@ Object.defineProperty(Phaser.Rectangle.prototype, 'bottom', { set: function (value) { - if (value <= this.y) { this.height = 0; @@ -579,16 +522,15 @@ Object.defineProperty(Phaser.Rectangle.prototype, 'bottom', { { this.height = value - this.y; } - } }); /** -* The location of the Rectangles bottom left corner as a Point object. -* @name Phaser.Rectangle#bottomLeft -* @property {Phaser.Point} bottomLeft - Gets or sets the location of the Rectangles bottom left corner as a Point object. -*/ + * The location of the Rectangles bottom left corner as a Point object. + * @name Phaser.Rectangle#bottomLeft + * @property {Phaser.Point} bottomLeft - Gets or sets the location of the Rectangles bottom left corner as a Point object. + */ Object.defineProperty(Phaser.Rectangle.prototype, 'bottomLeft', { get: function () @@ -605,10 +547,10 @@ Object.defineProperty(Phaser.Rectangle.prototype, 'bottomLeft', { }); /** -* The location of the Rectangles bottom right corner as a Point object. -* @name Phaser.Rectangle#bottomRight -* @property {Phaser.Point} bottomRight - Gets or sets the location of the Rectangles bottom right corner as a Point object. -*/ + * The location of the Rectangles bottom right corner as a Point object. + * @name Phaser.Rectangle#bottomRight + * @property {Phaser.Point} bottomRight - Gets or sets the location of the Rectangles bottom right corner as a Point object. + */ Object.defineProperty(Phaser.Rectangle.prototype, 'bottomRight', { get: function () @@ -625,10 +567,10 @@ Object.defineProperty(Phaser.Rectangle.prototype, 'bottomRight', { }); /** -* The x coordinate of the left of the Rectangle. Changing the left property of a Rectangle object has no effect on the y and height properties. However it does affect the width property, whereas changing the x value does not affect the width property. -* @name Phaser.Rectangle#left -* @property {number} left - The x coordinate of the left of the Rectangle. -*/ + * The x coordinate of the left of the Rectangle. Changing the left property of a Rectangle object has no effect on the y and height properties. However it does affect the width property, whereas changing the x value does not affect the width property. + * @name Phaser.Rectangle#left + * @property {number} left - The x coordinate of the left of the Rectangle. + */ Object.defineProperty(Phaser.Rectangle.prototype, 'left', { get: function () @@ -652,10 +594,10 @@ Object.defineProperty(Phaser.Rectangle.prototype, 'left', { }); /** -* The sum of the x and width properties. Changing the right property of a Rectangle object has no effect on the x, y and height properties, however it does affect the width property. -* @name Phaser.Rectangle#right -* @property {number} right - The sum of the x and width properties. -*/ + * The sum of the x and width properties. Changing the right property of a Rectangle object has no effect on the x, y and height properties, however it does affect the width property. + * @name Phaser.Rectangle#right + * @property {number} right - The sum of the x and width properties. + */ Object.defineProperty(Phaser.Rectangle.prototype, 'right', { get: function () @@ -678,11 +620,11 @@ Object.defineProperty(Phaser.Rectangle.prototype, 'right', { }); /** -* The volume of the Rectangle derived from width * height. -* @name Phaser.Rectangle#volume -* @property {number} volume - The volume of the Rectangle derived from width * height. -* @readonly -*/ + * The volume of the Rectangle derived from width * height. + * @name Phaser.Rectangle#volume + * @property {number} volume - The volume of the Rectangle derived from width * height. + * @readonly + */ Object.defineProperty(Phaser.Rectangle.prototype, 'volume', { get: function () @@ -693,11 +635,11 @@ Object.defineProperty(Phaser.Rectangle.prototype, 'volume', { }); /** -* The perimeter size of the Rectangle. This is the sum of all 4 sides. -* @name Phaser.Rectangle#perimeter -* @property {number} perimeter - The perimeter size of the Rectangle. This is the sum of all 4 sides. -* @readonly -*/ + * The perimeter size of the Rectangle. This is the sum of all 4 sides. + * @name Phaser.Rectangle#perimeter + * @property {number} perimeter - The perimeter size of the Rectangle. This is the sum of all 4 sides. + * @readonly + */ Object.defineProperty(Phaser.Rectangle.prototype, 'perimeter', { get: function () @@ -708,10 +650,10 @@ Object.defineProperty(Phaser.Rectangle.prototype, 'perimeter', { }); /** -* The x coordinate of the center of the Rectangle. -* @name Phaser.Rectangle#centerX -* @property {number} centerX - The x coordinate of the center of the Rectangle. -*/ + * The x coordinate of the center of the Rectangle. + * @name Phaser.Rectangle#centerX + * @property {number} centerX - The x coordinate of the center of the Rectangle. + */ Object.defineProperty(Phaser.Rectangle.prototype, 'centerX', { get: function () @@ -727,10 +669,10 @@ Object.defineProperty(Phaser.Rectangle.prototype, 'centerX', { }); /** -* The y coordinate of the center of the Rectangle. -* @name Phaser.Rectangle#centerY -* @property {number} centerY - The y coordinate of the center of the Rectangle. -*/ + * The y coordinate of the center of the Rectangle. + * @name Phaser.Rectangle#centerY + * @property {number} centerY - The y coordinate of the center of the Rectangle. + */ Object.defineProperty(Phaser.Rectangle.prototype, 'centerY', { get: function () @@ -746,45 +688,41 @@ Object.defineProperty(Phaser.Rectangle.prototype, 'centerY', { }); /** -* A random value between the left and right values (inclusive) of the Rectangle. -* -* @name Phaser.Rectangle#randomX -* @property {number} randomX - A random value between the left and right values (inclusive) of the Rectangle. -*/ + * A random value between the left and right values (inclusive) of the Rectangle. + * + * @name Phaser.Rectangle#randomX + * @property {number} randomX - A random value between the left and right values (inclusive) of the Rectangle. + */ Object.defineProperty(Phaser.Rectangle.prototype, 'randomX', { get: function () { - return this.x + (Math.random() * this.width); - } }); /** -* A random value between the top and bottom values (inclusive) of the Rectangle. -* -* @name Phaser.Rectangle#randomY -* @property {number} randomY - A random value between the top and bottom values (inclusive) of the Rectangle. -*/ + * A random value between the top and bottom values (inclusive) of the Rectangle. + * + * @name Phaser.Rectangle#randomY + * @property {number} randomY - A random value between the top and bottom values (inclusive) of the Rectangle. + */ Object.defineProperty(Phaser.Rectangle.prototype, 'randomY', { get: function () { - return this.y + (Math.random() * this.height); - } }); /** -* The y coordinate of the top of the Rectangle. Changing the top property of a Rectangle object has no effect on the x and width properties. -* However it does affect the height property, whereas changing the y value does not affect the height property. -* @name Phaser.Rectangle#top -* @property {number} top - The y coordinate of the top of the Rectangle. -*/ + * The y coordinate of the top of the Rectangle. Changing the top property of a Rectangle object has no effect on the x and width properties. + * However it does affect the height property, whereas changing the y value does not affect the height property. + * @name Phaser.Rectangle#top + * @property {number} top - The y coordinate of the top of the Rectangle. + */ Object.defineProperty(Phaser.Rectangle.prototype, 'top', { get: function () @@ -808,10 +746,10 @@ Object.defineProperty(Phaser.Rectangle.prototype, 'top', { }); /** -* The location of the Rectangles top left corner as a Point object. -* @name Phaser.Rectangle#topLeft -* @property {Phaser.Point} topLeft - The location of the Rectangles top left corner as a Point object. -*/ + * The location of the Rectangles top left corner as a Point object. + * @name Phaser.Rectangle#topLeft + * @property {Phaser.Point} topLeft - The location of the Rectangles top left corner as a Point object. + */ Object.defineProperty(Phaser.Rectangle.prototype, 'topLeft', { get: function () @@ -828,10 +766,10 @@ Object.defineProperty(Phaser.Rectangle.prototype, 'topLeft', { }); /** -* The location of the Rectangles top right corner as a Point object. -* @name Phaser.Rectangle#topRight -* @property {Phaser.Point} topRight - The location of the Rectangles top left corner as a Point object. -*/ + * The location of the Rectangles top right corner as a Point object. + * @name Phaser.Rectangle#topRight + * @property {Phaser.Point} topRight - The location of the Rectangles top left corner as a Point object. + */ Object.defineProperty(Phaser.Rectangle.prototype, 'topRight', { get: function () @@ -848,11 +786,11 @@ Object.defineProperty(Phaser.Rectangle.prototype, 'topRight', { }); /** -* Determines whether or not this Rectangle object is empty. A Rectangle object is empty if its width or height is less than or equal to 0. -* If set to true then all of the Rectangle properties are set to 0. -* @name Phaser.Rectangle#empty -* @property {boolean} empty - Gets or sets the Rectangles empty state. -*/ + * Determines whether or not this Rectangle object is empty. A Rectangle object is empty if its width or height is less than or equal to 0. + * If set to true then all of the Rectangle properties are set to 0. + * @name Phaser.Rectangle#empty + * @property {boolean} empty - Gets or sets the Rectangles empty state. + */ Object.defineProperty(Phaser.Rectangle.prototype, 'empty', { get: function () @@ -862,12 +800,10 @@ Object.defineProperty(Phaser.Rectangle.prototype, 'empty', { set: function (value) { - if (value === true) { this.setTo(0, 0, 0, 0); } - } }); @@ -875,49 +811,44 @@ Object.defineProperty(Phaser.Rectangle.prototype, 'empty', { Phaser.Rectangle.prototype.constructor = Phaser.Rectangle; /** -* Increases the size of the Rectangle object by the specified amounts. The center point of the Rectangle object stays the same, and its size increases to the left and right by the dx value, and to the top and the bottom by the dy value. -* @method Phaser.Rectangle.inflate -* @param {Phaser.Rectangle} a - The Rectangle object. -* @param {number} dx - The amount to be added to the left side of the Rectangle. -* @param {number} dy - The amount to be added to the bottom side of the Rectangle. -* @return {Phaser.Rectangle} This Rectangle object. -*/ + * Increases the size of the Rectangle object by the specified amounts. The center point of the Rectangle object stays the same, and its size increases to the left and right by the dx value, and to the top and the bottom by the dy value. + * @method Phaser.Rectangle.inflate + * @param {Phaser.Rectangle} a - The Rectangle object. + * @param {number} dx - The amount to be added to the left side of the Rectangle. + * @param {number} dy - The amount to be added to the bottom side of the Rectangle. + * @return {Phaser.Rectangle} This Rectangle object. + */ Phaser.Rectangle.inflate = function (a, dx, dy) { - a.x -= dx; a.width += 2 * dx; a.y -= dy; a.height += 2 * dy; return a; - }; /** -* Increases the size of the Rectangle object. This method is similar to the Rectangle.inflate() method except it takes a Point object as a parameter. -* @method Phaser.Rectangle.inflatePoint -* @param {Phaser.Rectangle} a - The Rectangle object. -* @param {Phaser.Point} point - The x property of this Point object is used to increase the horizontal dimension of the Rectangle object. The y property is used to increase the vertical dimension of the Rectangle object. -* @return {Phaser.Rectangle} The Rectangle object. -*/ + * Increases the size of the Rectangle object. This method is similar to the Rectangle.inflate() method except it takes a Point object as a parameter. + * @method Phaser.Rectangle.inflatePoint + * @param {Phaser.Rectangle} a - The Rectangle object. + * @param {Phaser.Point} point - The x property of this Point object is used to increase the horizontal dimension of the Rectangle object. The y property is used to increase the vertical dimension of the Rectangle object. + * @return {Phaser.Rectangle} The Rectangle object. + */ Phaser.Rectangle.inflatePoint = function (a, point) { - return Phaser.Rectangle.inflate(a, point.x, point.y); - }; /** -* The size of the Rectangle object, expressed as a Point object with the values of the width and height properties. -* @method Phaser.Rectangle.size -* @param {Phaser.Rectangle} a - The Rectangle object. -* @param {Phaser.Point} [output] - Optional Point object. If given the values will be set into the object, otherwise a brand new Point object will be created and returned. -* @return {Phaser.Point} The size of the Rectangle object -*/ + * The size of the Rectangle object, expressed as a Point object with the values of the width and height properties. + * @method Phaser.Rectangle.size + * @param {Phaser.Rectangle} a - The Rectangle object. + * @param {Phaser.Point} [output] - Optional Point object. If given the values will be set into the object, otherwise a brand new Point object will be created and returned. + * @return {Phaser.Point} The size of the Rectangle object + */ Phaser.Rectangle.size = function (a, output) { - if (output === undefined || output === null) { output = new Phaser.Point(a.width, a.height); @@ -928,19 +859,17 @@ Phaser.Rectangle.size = function (a, output) } return output; - }; /** -* Returns a new Rectangle object with the same values for the x, y, width, and height properties as the original Rectangle object. -* @method Phaser.Rectangle.clone -* @param {Phaser.Rectangle} a - The Rectangle object. -* @param {Phaser.Rectangle} [output] - Optional Rectangle object. If given the values will be set into the object, otherwise a brand new Rectangle object will be created and returned. -* @return {Phaser.Rectangle} -*/ + * Returns a new Rectangle object with the same values for the x, y, width, and height properties as the original Rectangle object. + * @method Phaser.Rectangle.clone + * @param {Phaser.Rectangle} a - The Rectangle object. + * @param {Phaser.Rectangle} [output] - Optional Rectangle object. If given the values will be set into the object, otherwise a brand new Rectangle object will be created and returned. + * @return {Phaser.Rectangle} + */ Phaser.Rectangle.clone = function (a, output) { - if (output === undefined || output === null) { output = new Phaser.Rectangle(a.x, a.y, a.width, a.height); @@ -951,91 +880,81 @@ Phaser.Rectangle.clone = function (a, output) } return output; - }; /** -* Returns a new Rectangle object with the same values for the left, top, width, and height properties as the original object. -* @method Phaser.Rectangle.createFromBounds -* @param {any} a - An object with `left`, `top`, `width`, and `height` properties. -* @param {Phaser.Rectangle} [output] - Optional Rectangle object. If given the values will be set into the object, otherwise a brand new Rectangle object will be created and returned. -* @return {Phaser.Rectangle} -*/ + * Returns a new Rectangle object with the same values for the left, top, width, and height properties as the original object. + * @method Phaser.Rectangle.createFromBounds + * @param {any} a - An object with `left`, `top`, `width`, and `height` properties. + * @param {Phaser.Rectangle} [output] - Optional Rectangle object. If given the values will be set into the object, otherwise a brand new Rectangle object will be created and returned. + * @return {Phaser.Rectangle} + */ Phaser.Rectangle.createFromBounds = function (a, output) { - if (output === undefined || output === null) { output = new Phaser.Rectangle(a.x, a.y, a.width, a.height); } return output.copyFromBounds(a); - }; /** -* Determines whether the specified coordinates are contained within the region defined by this Rectangle object. -* @method Phaser.Rectangle.contains -* @param {Phaser.Rectangle} a - The Rectangle object. -* @param {number} x - The x coordinate of the point to test. -* @param {number} y - The y coordinate of the point to test. -* @return {boolean} A value of true if the Rectangle object contains the specified point; otherwise false. -*/ + * Determines whether the specified coordinates are contained within the region defined by this Rectangle object. + * @method Phaser.Rectangle.contains + * @param {Phaser.Rectangle} a - The Rectangle object. + * @param {number} x - The x coordinate of the point to test. + * @param {number} y - The y coordinate of the point to test. + * @return {boolean} A value of true if the Rectangle object contains the specified point; otherwise false. + */ Phaser.Rectangle.contains = function (a, x, y) { - if (a.width <= 0 || a.height <= 0) { return false; } return (x >= a.x && x < a.right && y >= a.y && y < a.bottom); - }; /** -* Determines whether the specified coordinates are contained within the region defined by the given raw values. -* @method Phaser.Rectangle.containsRaw -* @param {number} rx - The x coordinate of the top left of the area. -* @param {number} ry - The y coordinate of the top left of the area. -* @param {number} rw - The width of the area. -* @param {number} rh - The height of the area. -* @param {number} x - The x coordinate of the point to test. -* @param {number} y - The y coordinate of the point to test. -* @return {boolean} A value of true if the Rectangle object contains the specified point; otherwise false. -*/ + * Determines whether the specified coordinates are contained within the region defined by the given raw values. + * @method Phaser.Rectangle.containsRaw + * @param {number} rx - The x coordinate of the top left of the area. + * @param {number} ry - The y coordinate of the top left of the area. + * @param {number} rw - The width of the area. + * @param {number} rh - The height of the area. + * @param {number} x - The x coordinate of the point to test. + * @param {number} y - The y coordinate of the point to test. + * @return {boolean} A value of true if the Rectangle object contains the specified point; otherwise false. + */ Phaser.Rectangle.containsRaw = function (rx, ry, rw, rh, x, y) { - return (x >= rx && x < (rx + rw) && y >= ry && y < (ry + rh)); - }; /** -* Determines whether the specified point is contained within the rectangular region defined by this Rectangle object. This method is similar to the Rectangle.contains() method, except that it takes a Point object as a parameter. -* @method Phaser.Rectangle.containsPoint -* @param {Phaser.Rectangle} a - The Rectangle object. -* @param {Phaser.Point} point - The point object being checked. Can be Point or any object with .x and .y values. -* @return {boolean} A value of true if the Rectangle object contains the specified point; otherwise false. -*/ + * Determines whether the specified point is contained within the rectangular region defined by this Rectangle object. This method is similar to the Rectangle.contains() method, except that it takes a Point object as a parameter. + * @method Phaser.Rectangle.containsPoint + * @param {Phaser.Rectangle} a - The Rectangle object. + * @param {Phaser.Point} point - The point object being checked. Can be Point or any object with .x and .y values. + * @return {boolean} A value of true if the Rectangle object contains the specified point; otherwise false. + */ Phaser.Rectangle.containsPoint = function (a, point) { - return Phaser.Rectangle.contains(a, point.x, point.y); - }; /** -* Determines whether the first Rectangle object is fully contained within the second Rectangle object. -* A Rectangle object is said to contain another if the second Rectangle object falls entirely within the boundaries of the first. -* @method Phaser.Rectangle.containsRect -* @param {Phaser.Rectangle} a - The first Rectangle object. -* @param {Phaser.Rectangle} b - The second Rectangle object. -* @return {boolean} A value of true if the Rectangle object contains the specified point; otherwise false. -*/ + * Determines whether the first Rectangle object is fully contained within the second Rectangle object. + * A Rectangle object is said to contain another if the second Rectangle object falls entirely within the boundaries of the first. + * @method Phaser.Rectangle.containsRect + * @param {Phaser.Rectangle} a - The first Rectangle object. + * @param {Phaser.Rectangle} b - The second Rectangle object. + * @return {boolean} A value of true if the Rectangle object contains the specified point; otherwise false. + */ Phaser.Rectangle.containsRect = function (a, b) { - // If the given rect has a larger volume than this one then it can never contain it if (a.volume > b.volume) { @@ -1043,49 +962,43 @@ Phaser.Rectangle.containsRect = function (a, b) } return (a.x >= b.x && a.y >= b.y && a.right < b.right && a.bottom < b.bottom); - }; /** -* Determines whether the two Rectangles are equal. -* This method compares the x, y, width and height properties of each Rectangle. -* @method Phaser.Rectangle.equals -* @param {Phaser.Rectangle} a - The first Rectangle object. -* @param {Phaser.Rectangle} b - The second Rectangle object. -* @return {boolean} A value of true if the two Rectangles have exactly the same values for the x, y, width and height properties; otherwise false. -*/ + * Determines whether the two Rectangles are equal. + * This method compares the x, y, width and height properties of each Rectangle. + * @method Phaser.Rectangle.equals + * @param {Phaser.Rectangle} a - The first Rectangle object. + * @param {Phaser.Rectangle} b - The second Rectangle object. + * @return {boolean} A value of true if the two Rectangles have exactly the same values for the x, y, width and height properties; otherwise false. + */ Phaser.Rectangle.equals = function (a, b) { - return (a.x === b.x && a.y === b.y && a.width === b.width && a.height === b.height); - }; /** -* Determines if the two objects (either Rectangles or Rectangle-like) have the same width and height values under strict equality. -* @method Phaser.Rectangle.sameDimensions -* @param {Rectangle-like} a - The first Rectangle object. -* @param {Rectangle-like} b - The second Rectangle object. -* @return {boolean} True if the object have equivalent values for the width and height properties. -*/ + * Determines if the two objects (either Rectangles or Rectangle-like) have the same width and height values under strict equality. + * @method Phaser.Rectangle.sameDimensions + * @param {Rectangle-like} a - The first Rectangle object. + * @param {Rectangle-like} b - The second Rectangle object. + * @return {boolean} True if the object have equivalent values for the width and height properties. + */ Phaser.Rectangle.sameDimensions = function (a, b) { - return (a.width === b.width && a.height === b.height); - }; /** -* If the Rectangle object specified in the toIntersect parameter intersects with this Rectangle object, returns the area of intersection as a Rectangle object. If the Rectangles do not intersect, this method returns an empty Rectangle object with its properties set to 0. -* @method Phaser.Rectangle.intersection -* @param {Phaser.Rectangle} a - The first Rectangle object. -* @param {Phaser.Rectangle} b - The second Rectangle object. -* @param {Phaser.Rectangle} [output] - Optional Rectangle object. If given the intersection values will be set into this object, otherwise a brand new Rectangle object will be created and returned. -* @return {Phaser.Rectangle} A Rectangle object that equals the area of intersection. If the Rectangles do not intersect, this method returns an empty Rectangle object; that is, a Rectangle with its x, y, width, and height properties set to 0. -*/ + * If the Rectangle object specified in the toIntersect parameter intersects with this Rectangle object, returns the area of intersection as a Rectangle object. If the Rectangles do not intersect, this method returns an empty Rectangle object with its properties set to 0. + * @method Phaser.Rectangle.intersection + * @param {Phaser.Rectangle} a - The first Rectangle object. + * @param {Phaser.Rectangle} b - The second Rectangle object. + * @param {Phaser.Rectangle} [output] - Optional Rectangle object. If given the intersection values will be set into this object, otherwise a brand new Rectangle object will be created and returned. + * @return {Phaser.Rectangle} A Rectangle object that equals the area of intersection. If the Rectangles do not intersect, this method returns an empty Rectangle object; that is, a Rectangle with its x, y, width, and height properties set to 0. + */ Phaser.Rectangle.intersection = function (a, b, output) { - if (output === undefined) { output = new Phaser.Rectangle(); @@ -1100,79 +1013,71 @@ Phaser.Rectangle.intersection = function (a, b, output) } return output; - }; /** -* Determines whether the two Rectangles intersect with each other. -* This method checks the x, y, width, and height properties of the Rectangles. -* @method Phaser.Rectangle.intersects -* @param {Phaser.Rectangle} a - The first Rectangle object. -* @param {Phaser.Rectangle} b - The second Rectangle object. -* @return {boolean} A value of true if the specified object intersects with this Rectangle object; otherwise false. -*/ + * Determines whether the two Rectangles intersect with each other. + * This method checks the x, y, width, and height properties of the Rectangles. + * @method Phaser.Rectangle.intersects + * @param {Phaser.Rectangle} a - The first Rectangle object. + * @param {Phaser.Rectangle} b - The second Rectangle object. + * @return {boolean} A value of true if the specified object intersects with this Rectangle object; otherwise false. + */ Phaser.Rectangle.intersects = function (a, b) { - if (a.width <= 0 || a.height <= 0 || b.width <= 0 || b.height <= 0) { return false; } return !(a.right < b.x || a.bottom < b.y || a.x > b.right || a.y > b.bottom); - }; /** -* Determines whether the object specified intersects (overlaps) with the given values. -* @method Phaser.Rectangle.intersectsRaw -* @param {number} left - The x coordinate of the left of the area. -* @param {number} right - The right coordinate of the area. -* @param {number} top - The y coordinate of the area. -* @param {number} bottom - The bottom coordinate of the area. -* @param {number} tolerance - A tolerance value to allow for an intersection test with padding, default to 0 -* @return {boolean} A value of true if the specified object intersects with the Rectangle; otherwise false. -*/ + * Determines whether the object specified intersects (overlaps) with the given values. + * @method Phaser.Rectangle.intersectsRaw + * @param {number} left - The x coordinate of the left of the area. + * @param {number} right - The right coordinate of the area. + * @param {number} top - The y coordinate of the area. + * @param {number} bottom - The bottom coordinate of the area. + * @param {number} tolerance - A tolerance value to allow for an intersection test with padding, default to 0 + * @return {boolean} A value of true if the specified object intersects with the Rectangle; otherwise false. + */ Phaser.Rectangle.intersectsRaw = function (a, left, right, top, bottom, tolerance) { - if (tolerance === undefined) { tolerance = 0; } return !(left > a.right + tolerance || right < a.left - tolerance || top > a.bottom + tolerance || bottom < a.top - tolerance); - }; /** -* Adds two Rectangles together to create a new Rectangle object, by filling in the horizontal and vertical space between the two Rectangles. -* @method Phaser.Rectangle.union -* @param {Phaser.Rectangle} a - The first Rectangle object. -* @param {Phaser.Rectangle} b - The second Rectangle object. -* @param {Phaser.Rectangle} [output] - Optional Rectangle object. If given the new values will be set into this object, otherwise a brand new Rectangle object will be created and returned. -* @return {Phaser.Rectangle} A Rectangle object that is the union of the two Rectangles. -*/ + * Adds two Rectangles together to create a new Rectangle object, by filling in the horizontal and vertical space between the two Rectangles. + * @method Phaser.Rectangle.union + * @param {Phaser.Rectangle} a - The first Rectangle object. + * @param {Phaser.Rectangle} b - The second Rectangle object. + * @param {Phaser.Rectangle} [output] - Optional Rectangle object. If given the new values will be set into this object, otherwise a brand new Rectangle object will be created and returned. + * @return {Phaser.Rectangle} A Rectangle object that is the union of the two Rectangles. + */ Phaser.Rectangle.union = function (a, b, output) { - if (output === undefined) { output = new Phaser.Rectangle(); } return output.setTo(Math.min(a.x, b.x), Math.min(a.y, b.y), Math.max(a.right, b.right) - Math.min(a.left, b.left), Math.max(a.bottom, b.bottom) - Math.min(a.top, b.top)); - }; /** -* Calculates the Axis Aligned Bounding Box (or aabb) from an array of points. -* -* @method Phaser.Rectangle.aabb -* @param {Phaser.Point[]} points - The array of one or more points. -* @param {Phaser.Rectangle} [out] - Optional Rectangle to store the value in, if not supplied a new Rectangle object will be created. -* @return {Phaser.Rectangle} The new Rectangle object. -*/ + * Calculates the Axis Aligned Bounding Box (or aabb) from an array of points. + * + * @method Phaser.Rectangle.aabb + * @param {Phaser.Point[]} points - The array of one or more points. + * @param {Phaser.Rectangle} [out] - Optional Rectangle to store the value in, if not supplied a new Rectangle object will be created. + * @return {Phaser.Rectangle} The new Rectangle object. + */ Phaser.Rectangle.aabb = function (points, out) { - if (out === undefined) { out = new Phaser.Rectangle(); @@ -1213,8 +1118,8 @@ Phaser.Rectangle.aabb = function (points, out) PIXI.Rectangle = Phaser.Rectangle; /** -* A Rectangle with width and height zero. -* @constant Phaser.EmptyRectangle -* @type {Phaser.Rectangle} -*/ + * A Rectangle with width and height zero. + * @constant Phaser.EmptyRectangle + * @type {Phaser.Rectangle} + */ Phaser.EmptyRectangle = new Phaser.Rectangle(0, 0, 0, 0); diff --git a/src/geom/RoundedRectangle.js b/src/geom/RoundedRectangle.js index 873999f0c..79ca94630 100644 --- a/src/geom/RoundedRectangle.js +++ b/src/geom/RoundedRectangle.js @@ -1,22 +1,22 @@ /** -* @author Mat Groves http://matgroves.com/ -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Mat Groves http://matgroves.com/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* The Rounded Rectangle object is an area defined by its position and has nice rounded corners, -* as indicated by its top-left corner point (x, y) and by its width and its height. -* -* @class Phaser.RoundedRectangle -* @constructor -* @param {number} [x=0] - The x coordinate of the top-left corner of the Rectangle. -* @param {number} [y=0] - The y coordinate of the top-left corner of the Rectangle. -* @param {number} [width=0] - The width of the Rectangle. Should always be either zero or a positive value. -* @param {number} [height=0] - The height of the Rectangle. Should always be either zero or a positive value. -* @param {number} [radius=20] - Controls the radius of the rounded corners. -*/ + * The Rounded Rectangle object is an area defined by its position and has nice rounded corners, + * as indicated by its top-left corner point (x, y) and by its width and its height. + * + * @class Phaser.RoundedRectangle + * @constructor + * @param {number} [x=0] - The x coordinate of the top-left corner of the Rectangle. + * @param {number} [y=0] - The y coordinate of the top-left corner of the Rectangle. + * @param {number} [width=0] - The width of the Rectangle. Should always be either zero or a positive value. + * @param {number} [height=0] - The height of the Rectangle. Should always be either zero or a positive value. + * @param {number} [radius=20] - Controls the radius of the rounded corners. + */ Phaser.RoundedRectangle = function (x, y, width, height, radius) { if (x === undefined) { x = 0; } @@ -26,64 +26,61 @@ Phaser.RoundedRectangle = function (x, y, width, height, radius) if (radius === undefined) { radius = 20; } /** - * @property {number} x - The x coordinate of the top-left corner of the Rectangle. - */ + * @property {number} x - The x coordinate of the top-left corner of the Rectangle. + */ this.x = x; /** - * @property {number} y - The y coordinate of the top-left corner of the Rectangle. - */ + * @property {number} y - The y coordinate of the top-left corner of the Rectangle. + */ this.y = y; /** - * @property {number} width - The width of the Rectangle. This value should never be set to a negative. - */ + * @property {number} width - The width of the Rectangle. This value should never be set to a negative. + */ this.width = width; /** - * @property {number} height - The height of the Rectangle. This value should never be set to a negative. - */ + * @property {number} height - The height of the Rectangle. This value should never be set to a negative. + */ this.height = height; /** - * @property {number} radius - The radius of the rounded corners. - */ + * @property {number} radius - The radius of the rounded corners. + */ this.radius = radius || 20; /** - * @property {number} type - The const type of this object. - * @readonly - */ + * @property {number} type - The const type of this object. + * @readonly + */ this.type = Phaser.ROUNDEDRECTANGLE; }; Phaser.RoundedRectangle.prototype = { /** - * Returns a new RoundedRectangle object with the same values for the x, y, width, height and - * radius properties as this RoundedRectangle object. - * - * @method Phaser.RoundedRectangle#clone - * @return {Phaser.RoundedRectangle} - */ + * Returns a new RoundedRectangle object with the same values for the x, y, width, height and + * radius properties as this RoundedRectangle object. + * + * @method Phaser.RoundedRectangle#clone + * @return {Phaser.RoundedRectangle} + */ clone: function () { - return new Phaser.RoundedRectangle(this.x, this.y, this.width, this.height, this.radius); - }, /** - * Determines whether the specified coordinates are contained within the region defined by this Rounded Rectangle object. - * - * @method Phaser.RoundedRectangle#contains - * @param {number} x - The x coordinate of the point to test. - * @param {number} y - The y coordinate of the point to test. - * @return {boolean} A value of true if the RoundedRectangle Rectangle object contains the specified point; otherwise false. - */ + * Determines whether the specified coordinates are contained within the region defined by this Rounded Rectangle object. + * + * @method Phaser.RoundedRectangle#contains + * @param {number} x - The x coordinate of the point to test. + * @param {number} y - The y coordinate of the point to test. + * @return {boolean} A value of true if the RoundedRectangle Rectangle object contains the specified point; otherwise false. + */ contains: function (x, y) { - if (this.width <= 0 || this.height <= 0) { return false; @@ -102,7 +99,6 @@ Phaser.RoundedRectangle.prototype = { } return false; - } }; diff --git a/src/input/DeviceButton.js b/src/input/DeviceButton.js index a69b56fbc..1ac90e128 100644 --- a/src/input/DeviceButton.js +++ b/src/input/DeviceButton.js @@ -1,159 +1,156 @@ /** -* @author Richard Davey -* @author @karlmacklin -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @author @karlmacklin + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* DeviceButtons belong to both `Phaser.Pointer` and `Phaser.SinglePad` (Gamepad) instances. -* -* For Pointers they represent the various buttons that can exist on mice and pens, such as the left button, right button, -* middle button and advanced buttons like back and forward. -* -* Access them via `Pointer.leftbutton`, `Pointer.rightButton` and so on. -* -* On Gamepads they represent all buttons on the pad: from shoulder buttons to action buttons. -* -* At the time of writing this there are device limitations you should be aware of: -* -* - On Windows, if you install a mouse driver, and its utility software allows you to customize button actions -* (e.g., IntelliPoint and SetPoint), the middle (wheel) button, the 4th button, and the 5th button might not be set, -* even when they are pressed. -* - On Linux (GTK), the 4th button and the 5th button are not supported. -* - On Mac OS X 10.5 there is no platform API for implementing any advanced buttons. -* -* @class Phaser.DeviceButton -* @constructor -* @param {Phaser.Pointer|Phaser.SinglePad} parent - A reference to the parent of this button. Either a Pointer or a Gamepad. -* @param {number} buttonCode - The button code this DeviceButton is responsible for. -*/ + * DeviceButtons belong to both `Phaser.Pointer` and `Phaser.SinglePad` (Gamepad) instances. + * + * For Pointers they represent the various buttons that can exist on mice and pens, such as the left button, right button, + * middle button and advanced buttons like back and forward. + * + * Access them via `Pointer.leftbutton`, `Pointer.rightButton` and so on. + * + * On Gamepads they represent all buttons on the pad: from shoulder buttons to action buttons. + * + * At the time of writing this there are device limitations you should be aware of: + * + * - On Windows, if you install a mouse driver, and its utility software allows you to customize button actions + * (e.g., IntelliPoint and SetPoint), the middle (wheel) button, the 4th button, and the 5th button might not be set, + * even when they are pressed. + * - On Linux (GTK), the 4th button and the 5th button are not supported. + * - On Mac OS X 10.5 there is no platform API for implementing any advanced buttons. + * + * @class Phaser.DeviceButton + * @constructor + * @param {Phaser.Pointer|Phaser.SinglePad} parent - A reference to the parent of this button. Either a Pointer or a Gamepad. + * @param {number} buttonCode - The button code this DeviceButton is responsible for. + */ Phaser.DeviceButton = function (parent, buttonCode) { - /** - * @property {Phaser.Pointer|Phaser.SinglePad} parent - A reference to the Pointer or Gamepad that owns this button. - */ + * @property {Phaser.Pointer|Phaser.SinglePad} parent - A reference to the Pointer or Gamepad that owns this button. + */ this.parent = parent; /** - * @property {Phaser.Game} game - A reference to the currently running game. - */ + * @property {Phaser.Game} game - A reference to the currently running game. + */ this.game = parent.game; /** - * @property {object} event - The DOM event that caused the change in button state. - * @default - */ + * @property {object} event - The DOM event that caused the change in button state. + * @default + */ this.event = null; /** - * @property {boolean} isDown - The "down" state of the button. - * @default - */ + * @property {boolean} isDown - The "down" state of the button. + * @default + */ this.isDown = false; /** - * @property {boolean} isUp - The "up" state of the button. - * @default - */ + * @property {boolean} isUp - The "up" state of the button. + * @default + */ this.isUp = true; /** - * @property {number} timeDown - The timestamp when the button was last pressed down. - * @default - */ + * @property {number} timeDown - The timestamp when the button was last pressed down. + * @default + */ this.timeDown = 0; /** - * @property {number} timeUp - The timestamp when the button was last released. - * @default - */ + * @property {number} timeUp - The timestamp when the button was last released. + * @default + */ this.timeUp = 0; /** - * Gamepad only. - * If a button is held down this holds down the number of times the button has 'repeated'. - * @property {number} repeats - * @default - */ + * Gamepad only. + * If a button is held down this holds down the number of times the button has 'repeated'. + * @property {number} repeats + * @default + */ this.repeats = 0; /** - * True if the alt key was held down when this button was last pressed or released. - * Not supported on Gamepads. - * @property {boolean} altKey - * @default - */ + * True if the alt key was held down when this button was last pressed or released. + * Not supported on Gamepads. + * @property {boolean} altKey + * @default + */ this.altKey = false; /** - * True if the shift key was held down when this button was last pressed or released. - * Not supported on Gamepads. - * @property {boolean} shiftKey - * @default - */ + * True if the shift key was held down when this button was last pressed or released. + * Not supported on Gamepads. + * @property {boolean} shiftKey + * @default + */ this.shiftKey = false; /** - * True if the control key was held down when this button was last pressed or released. - * Not supported on Gamepads. - * @property {boolean} ctrlKey - * @default - */ + * True if the control key was held down when this button was last pressed or released. + * Not supported on Gamepads. + * @property {boolean} ctrlKey + * @default + */ this.ctrlKey = false; /** - * @property {number} value - Button value. Mainly useful for checking analog buttons (like shoulder triggers) on Gamepads. - * @default - */ + * @property {number} value - Button value. Mainly useful for checking analog buttons (like shoulder triggers) on Gamepads. + * @default + */ this.value = 0; /** - * @property {number} buttonCode - The buttoncode of this button if a Gamepad, or the DOM button event value if a Pointer. - */ + * @property {number} buttonCode - The buttoncode of this button if a Gamepad, or the DOM button event value if a Pointer. + */ this.buttonCode = buttonCode; /** - * This Signal is dispatched every time this DeviceButton is pressed down. - * It is only dispatched once (until the button is released again). - * When dispatched it sends 2 arguments: A reference to this DeviceButton and the value of the button. - * @property {Phaser.Signal} onDown - */ + * This Signal is dispatched every time this DeviceButton is pressed down. + * It is only dispatched once (until the button is released again). + * When dispatched it sends 2 arguments: A reference to this DeviceButton and the value of the button. + * @property {Phaser.Signal} onDown + */ this.onDown = new Phaser.Signal(); /** - * This Signal is dispatched every time this DeviceButton is released from a down state. - * It is only dispatched once (until the button is pressed again). - * When dispatched it sends 2 arguments: A reference to this DeviceButton and the value of the button. - * @property {Phaser.Signal} onUp - */ + * This Signal is dispatched every time this DeviceButton is released from a down state. + * It is only dispatched once (until the button is pressed again). + * When dispatched it sends 2 arguments: A reference to this DeviceButton and the value of the button. + * @property {Phaser.Signal} onUp + */ this.onUp = new Phaser.Signal(); /** - * Gamepad only. - * This Signal is dispatched every time this DeviceButton changes floating value (between, but not exactly, 0 and 1). - * When dispatched it sends 2 arguments: A reference to this DeviceButton and the value of the button. - * @property {Phaser.Signal} onFloat - */ + * Gamepad only. + * This Signal is dispatched every time this DeviceButton changes floating value (between, but not exactly, 0 and 1). + * When dispatched it sends 2 arguments: A reference to this DeviceButton and the value of the button. + * @property {Phaser.Signal} onFloat + */ this.onFloat = new Phaser.Signal(); - }; Phaser.DeviceButton.prototype = { /** - * Called automatically by Phaser.Pointer and Phaser.SinglePad. - * Handles the button down state. - * - * @method Phaser.DeviceButton#start - * @protected - * @param {object} [event] - The DOM event that triggered the button change. - * @param {number} [value] - The button value. Only get for Gamepads. - */ + * Called automatically by Phaser.Pointer and Phaser.SinglePad. + * Handles the button down state. + * + * @method Phaser.DeviceButton#start + * @protected + * @param {object} [event] - The DOM event that triggered the button change. + * @param {number} [value] - The button value. Only get for Gamepads. + */ start: function (event, value) { - if (this.isDown) { return; @@ -175,21 +172,19 @@ Phaser.DeviceButton.prototype = { } this.onDown.dispatch(this, value); - }, /** - * Called automatically by Phaser.Pointer and Phaser.SinglePad. - * Handles the button up state. - * - * @method Phaser.DeviceButton#stop - * @protected - * @param {object} [event] - The DOM event that triggered the button change. - * @param {number} [value] - The button value. Only get for Gamepads. - */ + * Called automatically by Phaser.Pointer and Phaser.SinglePad. + * Handles the button up state. + * + * @method Phaser.DeviceButton#stop + * @protected + * @param {object} [event] - The DOM event that triggered the button change. + * @param {number} [value] - The button value. Only get for Gamepads. + */ stop: function (event, value) { - if (this.isUp) { return; @@ -210,22 +205,20 @@ Phaser.DeviceButton.prototype = { } this.onUp.dispatch(this, value); - }, /** - * Called automatically by Phaser.Pointer. - * Starts or stops button based on condition. - * - * @method Phaser.DeviceButton#startStop - * @protected - * @param {boolean} [condition] - The condition that decides between start or stop. - * @param {object} [event] - The DOM event that triggered the button change. - * @param {number} [value] - The button value. Only get for Gamepads. - */ + * Called automatically by Phaser.Pointer. + * Starts or stops button based on condition. + * + * @method Phaser.DeviceButton#startStop + * @protected + * @param {boolean} [condition] - The condition that decides between start or stop. + * @param {object} [event] - The DOM event that triggered the button change. + * @param {number} [value] - The button value. Only get for Gamepads. + */ startStop: function (condition, event, value) { - if (condition) { this.start(event, value); @@ -234,70 +227,62 @@ Phaser.DeviceButton.prototype = { { this.stop(event, value); } - }, /** - * Called automatically by Phaser.SinglePad. - * - * @method Phaser.DeviceButton#padFloat - * @protected - * @param {number} value - Button value - */ + * Called automatically by Phaser.SinglePad. + * + * @method Phaser.DeviceButton#padFloat + * @protected + * @param {number} value - Button value + */ padFloat: function (value) { - this.isDown = false; this.isUp = false; this.value = value; this.onFloat.dispatch(this, value); - }, /** - * Returns the "just pressed" state of this button. - * Just pressed is considered true if the button was pressed down within the duration given (default 250ms). - * - * @method Phaser.DeviceButton#justPressed - * @param {number} [duration=250] - The duration in ms below which the button is considered as being just pressed. - * @return {boolean} True if the button is just pressed otherwise false. - */ + * Returns the "just pressed" state of this button. + * Just pressed is considered true if the button was pressed down within the duration given (default 250ms). + * + * @method Phaser.DeviceButton#justPressed + * @param {number} [duration=250] - The duration in ms below which the button is considered as being just pressed. + * @return {boolean} True if the button is just pressed otherwise false. + */ justPressed: function (duration) { - duration = duration || 250; return (this.isDown && (this.timeDown + duration) > this.game.time.time); - }, /** - * Returns the "just released" state of this button. - * Just released is considered as being true if the button was released within the duration given (default 250ms). - * - * @method Phaser.DeviceButton#justReleased - * @param {number} [duration=250] - The duration in ms below which the button is considered as being just released. - * @return {boolean} True if the button is just released otherwise false. - */ + * Returns the "just released" state of this button. + * Just released is considered as being true if the button was released within the duration given (default 250ms). + * + * @method Phaser.DeviceButton#justReleased + * @param {number} [duration=250] - The duration in ms below which the button is considered as being just released. + * @return {boolean} True if the button is just released otherwise false. + */ justReleased: function (duration) { - duration = duration || 250; return (this.isUp && (this.timeUp + duration) > this.game.time.time); - }, /** - * Resets this DeviceButton, changing it to an isUp state and resetting the duration and repeats counters. - * - * @method Phaser.DeviceButton#reset - */ + * Resets this DeviceButton, changing it to an isUp state and resetting the duration and repeats counters. + * + * @method Phaser.DeviceButton#reset + */ reset: function () { - this.isDown = false; this.isUp = true; @@ -307,25 +292,22 @@ Phaser.DeviceButton.prototype = { this.altKey = false; this.shiftKey = false; this.ctrlKey = false; - }, /** - * Destroys this DeviceButton, this disposes of the onDown, onUp and onFloat signals - * and clears the parent and game references. - * - * @method Phaser.DeviceButton#destroy - */ + * Destroys this DeviceButton, this disposes of the onDown, onUp and onFloat signals + * and clears the parent and game references. + * + * @method Phaser.DeviceButton#destroy + */ destroy: function () { - this.onDown.dispose(); this.onUp.dispose(); this.onFloat.dispose(); this.parent = null; this.game = null; - } }; @@ -333,25 +315,23 @@ Phaser.DeviceButton.prototype = { Phaser.DeviceButton.prototype.constructor = Phaser.DeviceButton; /** -* How long the button has been held down for in milliseconds. -* If not currently down it returns -1. -* -* @name Phaser.DeviceButton#duration -* @property {number} duration -* @readonly -*/ + * How long the button has been held down for in milliseconds. + * If not currently down it returns -1. + * + * @name Phaser.DeviceButton#duration + * @property {number} duration + * @readonly + */ Object.defineProperty(Phaser.DeviceButton.prototype, 'duration', { get: function () { - if (this.isUp) { return -1; } return this.game.time.time - this.timeDown; - } }); diff --git a/src/input/Gamepad.js b/src/input/Gamepad.js index 660b109fe..24d2a32a6 100644 --- a/src/input/Gamepad.js +++ b/src/input/Gamepad.js @@ -1,153 +1,150 @@ /** -* @author @karlmacklin -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author @karlmacklin + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* The Gamepad class handles gamepad input and dispatches gamepad events. -* -* Remember to call `gamepad.start()`. -* -* HTML5 GAMEPAD API SUPPORT IS AT AN EXPERIMENTAL STAGE! -* At moment of writing this (end of 2013) only Chrome supports parts of it out of the box. Firefox supports it -* via prefs flags (about:config, search gamepad). The browsers map the same controllers differently. -* This class has constants for Windows 7 Chrome mapping of XBOX 360 controller. -* -* @class Phaser.Gamepad -* @constructor -* @param {Phaser.Game} game - A reference to the currently running game. -*/ + * The Gamepad class handles gamepad input and dispatches gamepad events. + * + * Remember to call `gamepad.start()`. + * + * HTML5 GAMEPAD API SUPPORT IS AT AN EXPERIMENTAL STAGE! + * At moment of writing this (end of 2013) only Chrome supports parts of it out of the box. Firefox supports it + * via prefs flags (about:config, search gamepad). The browsers map the same controllers differently. + * This class has constants for Windows 7 Chrome mapping of XBOX 360 controller. + * + * @class Phaser.Gamepad + * @constructor + * @param {Phaser.Game} game - A reference to the currently running game. + */ Phaser.Gamepad = function (game) { - /** - * @property {Phaser.Game} game - Local reference to game. - */ + * @property {Phaser.Game} game - Local reference to game. + */ this.game = game; /** - * @property {object} _gamepadIndexMap - Maps the browsers gamepad indices to our Phaser Gamepads - * @private - */ + * @property {object} _gamepadIndexMap - Maps the browsers gamepad indices to our Phaser Gamepads + * @private + */ this._gamepadIndexMap = {}; /** - * @property {Array} _rawPads - The raw state of the gamepads from the browser - * @private - */ + * @property {Array} _rawPads - The raw state of the gamepads from the browser + * @private + */ this._rawPads = []; /** - * @property {boolean} _active - Private flag for whether or not the API is polled - * @private - * @default - */ + * @property {boolean} _active - Private flag for whether or not the API is polled + * @private + * @default + */ this._active = false; /** - * Gamepad input will only be processed if enabled. - * @property {boolean} enabled - * @default - */ + * Gamepad input will only be processed if enabled. + * @property {boolean} enabled + * @default + */ this.enabled = true; /** - * Whether or not gamepads are supported in the current browser. Note that as of Dec. 2013 this check is actually not accurate at all due to poor implementation. - * @property {boolean} _gamepadSupportAvailable - Are gamepads supported in this browser or not? - * @private - */ + * Whether or not gamepads are supported in the current browser. Note that as of Dec. 2013 this check is actually not accurate at all due to poor implementation. + * @property {boolean} _gamepadSupportAvailable - Are gamepads supported in this browser or not? + * @private + */ this._gamepadSupportAvailable = !!navigator.webkitGetGamepads || !!navigator.webkitGamepads || (navigator.userAgent.indexOf('Firefox/') !== -1) || !!navigator.getGamepads; /** - * Used to check for differences between earlier polls and current state of gamepads. - * @property {Array} _prevRawGamepadTypes - * @private - * @default - */ + * Used to check for differences between earlier polls and current state of gamepads. + * @property {Array} _prevRawGamepadTypes + * @private + * @default + */ this._prevRawGamepadTypes = []; /** - * Used to check for differences between earlier polls and current state of gamepads. - * @property {Array} _prevTimestamps - * @private - * @default - */ + * Used to check for differences between earlier polls and current state of gamepads. + * @property {Array} _prevTimestamps + * @private + * @default + */ this._prevTimestamps = []; /** - * @property {object} callbackContext - The context under which the callbacks are run. - */ + * @property {object} callbackContext - The context under which the callbacks are run. + */ this.callbackContext = this; /** - * @property {function} onConnectCallback - This callback is invoked every time any gamepad is connected - */ + * @property {function} onConnectCallback - This callback is invoked every time any gamepad is connected + */ this.onConnectCallback = null; /** - * @property {function} onDisconnectCallback - This callback is invoked every time any gamepad is disconnected - */ + * @property {function} onDisconnectCallback - This callback is invoked every time any gamepad is disconnected + */ this.onDisconnectCallback = null; /** - * @property {function} onDownCallback - This callback is invoked every time any gamepad button is pressed down. - */ + * @property {function} onDownCallback - This callback is invoked every time any gamepad button is pressed down. + */ this.onDownCallback = null; /** - * @property {function} onUpCallback - This callback is invoked every time any gamepad button is released. - */ + * @property {function} onUpCallback - This callback is invoked every time any gamepad button is released. + */ this.onUpCallback = null; /** - * @property {function} onAxisCallback - This callback is invoked every time any gamepad axis is changed. - */ + * @property {function} onAxisCallback - This callback is invoked every time any gamepad axis is changed. + */ this.onAxisCallback = null; /** - * @property {function} onFloatCallback - This callback is invoked every time any gamepad button is changed to a value where value > 0 and value < 1. - */ + * @property {function} onFloatCallback - This callback is invoked every time any gamepad button is changed to a value where value > 0 and value < 1. + */ this.onFloatCallback = null; /** - * @property {function} _ongamepadconnected - Private callback for Firefox gamepad connection handling - * @private - */ + * @property {function} _ongamepadconnected - Private callback for Firefox gamepad connection handling + * @private + */ this._ongamepadconnected = null; /** - * @property {function} _gamepaddisconnected - Private callback for Firefox gamepad connection handling - * @private - */ + * @property {function} _gamepaddisconnected - Private callback for Firefox gamepad connection handling + * @private + */ this._gamepaddisconnected = null; /** - * @property {Array} _gamepads - The four Phaser Gamepads. - * @private - */ + * @property {Array} _gamepads - The four Phaser Gamepads. + * @private + */ this._gamepads = [ new Phaser.SinglePad(game, this), new Phaser.SinglePad(game, this), new Phaser.SinglePad(game, this), new Phaser.SinglePad(game, this) ]; - }; Phaser.Gamepad.prototype = { /** - * Add callbacks to the main Gamepad handler to handle connect/disconnect/button down/button up/axis change/float value buttons. - * - * @method Phaser.Gamepad#addCallbacks - * @param {object} context - The context under which the callbacks are run. - * @param {object} callbacks - Object that takes six different callback methods: - * onConnectCallback, onDisconnectCallback, onDownCallback, onUpCallback, onAxisCallback, onFloatCallback - */ + * Add callbacks to the main Gamepad handler to handle connect/disconnect/button down/button up/axis change/float value buttons. + * + * @method Phaser.Gamepad#addCallbacks + * @param {object} context - The context under which the callbacks are run. + * @param {object} callbacks - Object that takes six different callback methods: + * onConnectCallback, onDisconnectCallback, onDownCallback, onUpCallback, onAxisCallback, onFloatCallback + */ addCallbacks: function (context, callbacks) { - if (typeof callbacks !== 'undefined') { this.onConnectCallback = (typeof callbacks.onConnect === 'function') ? callbacks.onConnect : this.onConnectCallback; @@ -158,18 +155,16 @@ Phaser.Gamepad.prototype = { this.onFloatCallback = (typeof callbacks.onFloat === 'function') ? callbacks.onFloat : this.onFloatCallback; this.callbackContext = context; } - }, /** - * Starts the Gamepad event handling. - * This MUST be called manually before Phaser will start polling the Gamepad API. - * - * @method Phaser.Gamepad#start - */ + * Starts the Gamepad event handling. + * This MUST be called manually before Phaser will start polling the Gamepad API. + * + * @method Phaser.Gamepad#start + */ start: function () { - if (this._active) { // Avoid setting multiple listeners @@ -192,7 +187,6 @@ Phaser.Gamepad.prototype = { window.addEventListener('gamepadconnected', this._onGamepadConnected, false); window.addEventListener('gamepaddisconnected', this._onGamepadDisconnected, false); - }, /** @@ -204,11 +198,9 @@ Phaser.Gamepad.prototype = { */ onGamepadConnected: function (event) { - var newPad = event.gamepad; this._rawPads.push(newPad); this._gamepads[newPad.index].connect(newPad); - }, /** @@ -220,7 +212,6 @@ Phaser.Gamepad.prototype = { */ onGamepadDisconnected: function (event) { - var removedPad = event.gamepad; for (var i in this._rawPads) @@ -232,35 +223,31 @@ Phaser.Gamepad.prototype = { } this._gamepads[removedPad.index].disconnect(); - }, /** - * Main gamepad update loop. Should not be called manually. - * @method Phaser.Gamepad#update - * @protected - */ + * Main gamepad update loop. Should not be called manually. + * @method Phaser.Gamepad#update + * @protected + */ update: function () { - this._pollGamepads(); this.pad1.pollStatus(); this.pad2.pollStatus(); this.pad3.pollStatus(); this.pad4.pollStatus(); - }, /** - * Updating connected gamepads (for Google Chrome). Should not be called manually. - * - * @method Phaser.Gamepad#_pollGamepads - * @private - */ + * Updating connected gamepads (for Google Chrome). Should not be called manually. + * + * @method Phaser.Gamepad#_pollGamepads + * @private + */ _pollGamepads: function () { - if (!this._active) { return; @@ -380,60 +367,53 @@ Phaser.Gamepad.prototype = { }, /** - * Sets the deadZone variable for all four gamepads - * @method Phaser.Gamepad#setDeadZones - */ + * Sets the deadZone variable for all four gamepads + * @method Phaser.Gamepad#setDeadZones + */ setDeadZones: function (value) { - for (var i = 0; i < this._gamepads.length; i++) { this._gamepads[i].deadZone = value; } - }, /** - * Stops the Gamepad event handling. - * - * @method Phaser.Gamepad#stop - */ + * Stops the Gamepad event handling. + * + * @method Phaser.Gamepad#stop + */ stop: function () { - this._active = false; window.removeEventListener('gamepadconnected', this._onGamepadConnected); window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnected); - }, /** - * Reset all buttons/axes of all gamepads - * @method Phaser.Gamepad#reset - */ + * Reset all buttons/axes of all gamepads + * @method Phaser.Gamepad#reset + */ reset: function () { - this.update(); for (var i = 0; i < this._gamepads.length; i++) { this._gamepads[i].reset(); } - }, /** - * Returns the "just pressed" state of a button from ANY gamepad connected. Just pressed is considered true if the button was pressed down within the duration given (default 250ms). - * @method Phaser.Gamepad#justPressed - * @param {number} buttonCode - The buttonCode of the button to check for. - * @param {number} [duration=250] - The duration below which the button is considered as being just pressed. - * @return {boolean} True if the button is just pressed otherwise false. - */ + * Returns the "just pressed" state of a button from ANY gamepad connected. Just pressed is considered true if the button was pressed down within the duration given (default 250ms). + * @method Phaser.Gamepad#justPressed + * @param {number} buttonCode - The buttonCode of the button to check for. + * @param {number} [duration=250] - The duration below which the button is considered as being just pressed. + * @return {boolean} True if the button is just pressed otherwise false. + */ justPressed: function (buttonCode, duration) { - for (var i = 0; i < this._gamepads.length; i++) { if (this._gamepads[i].justPressed(buttonCode, duration) === true) @@ -443,19 +423,17 @@ Phaser.Gamepad.prototype = { } return false; - }, /** - * Returns the "just released" state of a button from ANY gamepad connected. Just released is considered as being true if the button was released within the duration given (default 250ms). - * @method Phaser.Gamepad#justPressed - * @param {number} buttonCode - The buttonCode of the button to check for. - * @param {number} [duration=250] - The duration below which the button is considered as being just released. - * @return {boolean} True if the button is just released otherwise false. - */ + * Returns the "just released" state of a button from ANY gamepad connected. Just released is considered as being true if the button was released within the duration given (default 250ms). + * @method Phaser.Gamepad#justPressed + * @param {number} buttonCode - The buttonCode of the button to check for. + * @param {number} [duration=250] - The duration below which the button is considered as being just released. + * @return {boolean} True if the button is just released otherwise false. + */ justReleased: function (buttonCode, duration) { - for (var i = 0; i < this._gamepads.length; i++) { if (this._gamepads[i].justReleased(buttonCode, duration) === true) @@ -465,18 +443,16 @@ Phaser.Gamepad.prototype = { } return false; - }, /** - * Returns true if the button is currently pressed down, on ANY gamepad. - * @method Phaser.Gamepad#isDown - * @param {number} buttonCode - The buttonCode of the button to check for. - * @return {boolean} True if a button is currently down. - */ + * Returns true if the button is currently pressed down, on ANY gamepad. + * @method Phaser.Gamepad#isDown + * @param {number} buttonCode - The buttonCode of the button to check for. + * @return {boolean} True if a button is currently down. + */ isDown: function (buttonCode) { - for (var i = 0; i < this._gamepads.length; i++) { if (this._gamepads[i].isDown(buttonCode) === true) @@ -495,14 +471,12 @@ Phaser.Gamepad.prototype = { */ destroy: function () { - this.stop(); for (var i = 0; i < this._gamepads.length; i++) { this._gamepads[i].destroy(); } - } }; @@ -510,11 +484,11 @@ Phaser.Gamepad.prototype = { Phaser.Gamepad.prototype.constructor = Phaser.Gamepad; /** -* If the gamepad input is active or not - if not active it should not be updated from Input.js -* @name Phaser.Gamepad#active -* @property {boolean} active - If the gamepad input is active or not. -* @readonly -*/ + * If the gamepad input is active or not - if not active it should not be updated from Input.js + * @name Phaser.Gamepad#active + * @property {boolean} active - If the gamepad input is active or not. + * @readonly + */ Object.defineProperty(Phaser.Gamepad.prototype, 'active', { get: function () @@ -525,11 +499,11 @@ Object.defineProperty(Phaser.Gamepad.prototype, 'active', { }); /** -* Whether or not gamepads are supported in current browser. -* @name Phaser.Gamepad#supported -* @property {boolean} supported - Whether or not gamepads are supported in current browser. -* @readonly -*/ + * Whether or not gamepads are supported in current browser. + * @name Phaser.Gamepad#supported + * @property {boolean} supported - Whether or not gamepads are supported in current browser. + * @readonly + */ Object.defineProperty(Phaser.Gamepad.prototype, 'supported', { get: function () @@ -540,11 +514,11 @@ Object.defineProperty(Phaser.Gamepad.prototype, 'supported', { }); /** -* How many live gamepads are currently connected. -* @name Phaser.Gamepad#padsConnected -* @property {number} padsConnected - How many live gamepads are currently connected. -* @readonly -*/ + * How many live gamepads are currently connected. + * @name Phaser.Gamepad#padsConnected + * @property {number} padsConnected - How many live gamepads are currently connected. + * @readonly + */ Object.defineProperty(Phaser.Gamepad.prototype, 'padsConnected', { get: function () @@ -555,11 +529,11 @@ Object.defineProperty(Phaser.Gamepad.prototype, 'padsConnected', { }); /** -* Gamepad #1 -* @name Phaser.Gamepad#pad1 -* @property {Phaser.SinglePad} pad1 - Gamepad #1; -* @readonly -*/ + * Gamepad #1 + * @name Phaser.Gamepad#pad1 + * @property {Phaser.SinglePad} pad1 - Gamepad #1; + * @readonly + */ Object.defineProperty(Phaser.Gamepad.prototype, 'pad1', { get: function () @@ -570,11 +544,11 @@ Object.defineProperty(Phaser.Gamepad.prototype, 'pad1', { }); /** -* Gamepad #2 -* @name Phaser.Gamepad#pad2 -* @property {Phaser.SinglePad} pad2 - Gamepad #2 -* @readonly -*/ + * Gamepad #2 + * @name Phaser.Gamepad#pad2 + * @property {Phaser.SinglePad} pad2 - Gamepad #2 + * @readonly + */ Object.defineProperty(Phaser.Gamepad.prototype, 'pad2', { get: function () @@ -585,11 +559,11 @@ Object.defineProperty(Phaser.Gamepad.prototype, 'pad2', { }); /** -* Gamepad #3 -* @name Phaser.Gamepad#pad3 -* @property {Phaser.SinglePad} pad3 - Gamepad #3 -* @readonly -*/ + * Gamepad #3 + * @name Phaser.Gamepad#pad3 + * @property {Phaser.SinglePad} pad3 - Gamepad #3 + * @readonly + */ Object.defineProperty(Phaser.Gamepad.prototype, 'pad3', { get: function () @@ -600,11 +574,11 @@ Object.defineProperty(Phaser.Gamepad.prototype, 'pad3', { }); /** -* Gamepad #4 -* @name Phaser.Gamepad#pad4 -* @property {Phaser.SinglePad} pad4 - Gamepad #4 -* @readonly -*/ + * Gamepad #4 + * @name Phaser.Gamepad#pad4 + * @property {Phaser.SinglePad} pad4 - Gamepad #4 + * @readonly + */ Object.defineProperty(Phaser.Gamepad.prototype, 'pad4', { get: function () @@ -642,9 +616,11 @@ Phaser.Gamepad.AXIS_7 = 7; Phaser.Gamepad.AXIS_8 = 8; Phaser.Gamepad.AXIS_9 = 9; -// Below mapping applies to XBOX 360 Wired and Wireless controller on Google Chrome (tested on Windows 7). -// - Firefox uses different map! Separate amount of buttons and axes. DPAD = axis and not a button. -// In other words - discrepancies when using gamepads. +/* + * Below mapping applies to XBOX 360 Wired and Wireless controller on Google Chrome (tested on Windows 7). + * - Firefox uses different map! Separate amount of buttons and axes. DPAD = axis and not a button. + * In other words - discrepancies when using gamepads. + */ Phaser.Gamepad.XBOX360_A = 0; Phaser.Gamepad.XBOX360_B = 1; diff --git a/src/input/Input.js b/src/input/Input.js index eeb8aa61b..08d831e5f 100644 --- a/src/input/Input.js +++ b/src/input/Input.js @@ -1,162 +1,161 @@ /** -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* Phaser.Input is the Input Manager for all types of Input across Phaser, including mouse, keyboard, touch and MSPointer. -* The Input manager is updated automatically by the core game loop. -* -* @class Phaser.Input -* @constructor -* @param {Phaser.Game} game - Current game instance. -*/ + * Phaser.Input is the Input Manager for all types of Input across Phaser, including mouse, keyboard, touch and MSPointer. + * The Input manager is updated automatically by the core game loop. + * + * @class Phaser.Input + * @constructor + * @param {Phaser.Game} game - Current game instance. + */ Phaser.Input = function (game) { - /** - * @property {Phaser.Game} game - A reference to the currently running game. - */ + * @property {Phaser.Game} game - A reference to the currently running game. + */ this.game = game; /** - * @property {HTMLCanvasElement} hitCanvas - The canvas to which single pixels are drawn in order to perform pixel-perfect hit detection. - * @default - */ + * @property {HTMLCanvasElement} hitCanvas - The canvas to which single pixels are drawn in order to perform pixel-perfect hit detection. + * @default + */ this.hitCanvas = null; /** - * @property {CanvasRenderingContext2D} hitContext - The context of the pixel perfect hit canvas. - * @default - */ + * @property {CanvasRenderingContext2D} hitContext - The context of the pixel perfect hit canvas. + * @default + */ this.hitContext = null; /** - * An array of callbacks that will be fired every time the activePointer receives a move event from the DOM. - * To add a callback to this array please use `Input.addMoveCallback`. - * @property {array} moveCallbacks - * @protected - */ + * An array of callbacks that will be fired every time the activePointer receives a move event from the DOM. + * To add a callback to this array please use `Input.addMoveCallback`. + * @property {array} moveCallbacks + * @protected + */ this.moveCallbacks = []; /** - * @property {function} customCandidateHandler - See Input.setInteractiveCandidateHandler. - * @private - */ + * @property {function} customCandidateHandler - See Input.setInteractiveCandidateHandler. + * @private + */ this.customCandidateHandler = null; /** - * @property {object} customCandidateHandlerContext - See Input.setInteractiveCandidateHandler. - * @private - */ + * @property {object} customCandidateHandlerContext - See Input.setInteractiveCandidateHandler. + * @private + */ this.customCandidateHandlerContext = null; /** - * @property {number} pollRate - How often should the input pointers be checked for updates? A value of 0 means every single frame (60fps); a value of 1 means every other frame (30fps) and so on. - * @default - */ + * @property {number} pollRate - How often should the input pointers be checked for updates? A value of 0 means every single frame (60fps); a value of 1 means every other frame (30fps) and so on. + * @default + */ this.pollRate = 0; /** - * When enabled, input (eg. Keyboard, Mouse, Touch) will be processed - as long as the individual sources are enabled themselves. - * - * When not enabled, _all_ input sources are ignored. To disable just one type of input; for example, the Mouse, use `input.mouse.enabled = false`. - * @property {boolean} enabled - * @default - */ + * When enabled, input (eg. Keyboard, Mouse, Touch) will be processed - as long as the individual sources are enabled themselves. + * + * When not enabled, _all_ input sources are ignored. To disable just one type of input; for example, the Mouse, use `input.mouse.enabled = false`. + * @property {boolean} enabled + * @default + */ this.enabled = true; /** - * @property {number} multiInputOverride - Controls the expected behavior when using a mouse and touch together on a multi-input device. - * @default - */ + * @property {number} multiInputOverride - Controls the expected behavior when using a mouse and touch together on a multi-input device. + * @default + */ this.multiInputOverride = Phaser.Input.MOUSE_TOUCH_COMBINE; /** - * @property {Phaser.Point} position - A point object representing the current position of the Pointer. - * @default - */ + * @property {Phaser.Point} position - A point object representing the current position of the Pointer. + * @default + */ this.position = null; /** - * @property {Phaser.Point} speed - A point object representing the speed of the Pointer. Only really useful in single Pointer games; otherwise see the Pointer objects directly. - */ + * @property {Phaser.Point} speed - A point object representing the speed of the Pointer. Only really useful in single Pointer games; otherwise see the Pointer objects directly. + */ this.speed = null; /** - * A Circle object centered on the x/y screen coordinates of the Input. - * Default size of 44px (Apples recommended "finger tip" size) but can be changed to anything. - * @property {Phaser.Circle} circle - */ + * A Circle object centered on the x/y screen coordinates of the Input. + * Default size of 44px (Apples recommended "finger tip" size) but can be changed to anything. + * @property {Phaser.Circle} circle + */ this.circle = null; /** - * @property {Phaser.Point} scale - The scale by which all input coordinates are multiplied; calculated by the ScaleManager. In an un-scaled game the values will be x = 1 and y = 1. - */ + * @property {Phaser.Point} scale - The scale by which all input coordinates are multiplied; calculated by the ScaleManager. In an un-scaled game the values will be x = 1 and y = 1. + */ this.scale = null; /** - * The maximum number of Pointers allowed to be *active* at any one time. - * A value of -1 is only limited by the total number of pointers (MAX_POINTERS). For lots of games it's useful to set this to 1. - * At least 2 Pointers will always be *created*, unless MAX_POINTERS is smaller. - * @property {integer} maxPointers - * @default -1 (Limited by total pointers.) - * @see Phaser.Input.MAX_POINTERS - */ + * The maximum number of Pointers allowed to be *active* at any one time. + * A value of -1 is only limited by the total number of pointers (MAX_POINTERS). For lots of games it's useful to set this to 1. + * At least 2 Pointers will always be *created*, unless MAX_POINTERS is smaller. + * @property {integer} maxPointers + * @default -1 (Limited by total pointers.) + * @see Phaser.Input.MAX_POINTERS + */ this.maxPointers = -1; /** - * @property {number} tapRate - The number of milliseconds that the Pointer has to be pressed down and then released to be considered a tap or click. - * @default - */ + * @property {number} tapRate - The number of milliseconds that the Pointer has to be pressed down and then released to be considered a tap or click. + * @default + */ this.tapRate = 200; /** - * @property {number} doubleTapRate - The number of milliseconds between taps of the same Pointer for it to be considered a double tap / click. - * @default - */ + * @property {number} doubleTapRate - The number of milliseconds between taps of the same Pointer for it to be considered a double tap / click. + * @default + */ this.doubleTapRate = 300; /** - * @property {number} holdRate - The number of milliseconds that the Pointer has to be pressed down for it to fire a onHold event. - * @default - */ + * @property {number} holdRate - The number of milliseconds that the Pointer has to be pressed down for it to fire a onHold event. + * @default + */ this.holdRate = 2000; /** - * @property {number} justPressedRate - The number of milliseconds below which the Pointer is considered justPressed. - * @default - */ + * @property {number} justPressedRate - The number of milliseconds below which the Pointer is considered justPressed. + * @default + */ this.justPressedRate = 200; /** - * @property {number} justReleasedRate - The number of milliseconds below which the Pointer is considered justReleased . - * @default - */ + * @property {number} justReleasedRate - The number of milliseconds below which the Pointer is considered justReleased . + * @default + */ this.justReleasedRate = 200; /** - * Sets if the Pointer objects should record a history of x/y coordinates they have passed through. - * The history is cleared each time the Pointer is pressed down. - * The history is updated at the rate specified in Input.pollRate - * @property {boolean} recordPointerHistory - * @default - */ + * Sets if the Pointer objects should record a history of x/y coordinates they have passed through. + * The history is cleared each time the Pointer is pressed down. + * The history is updated at the rate specified in Input.pollRate + * @property {boolean} recordPointerHistory + * @default + */ this.recordPointerHistory = false; /** - * @property {number} recordRate - The rate in milliseconds at which the Pointer objects should update their tracking history. - * @default - */ + * @property {number} recordRate - The rate in milliseconds at which the Pointer objects should update their tracking history. + * @default + */ this.recordRate = 100; /** - * The total number of entries that can be recorded into the Pointer objects tracking history. - * If the Pointer is tracking one event every 100ms; then a trackLimit of 100 would store the last 10 seconds worth of history. - * @property {number} recordLimit - * @default - */ + * The total number of entries that can be recorded into the Pointer objects tracking history. + * If the Pointer is tracking one event every 100ms; then a trackLimit of 100 would store the last 10 seconds worth of history. + * @property {number} recordLimit + * @default + */ this.recordLimit = 100; /** @@ -169,272 +168,270 @@ Phaser.Input = function (game) this.touchLockCallbacks = []; /** - * @property {Phaser.Pointer} pointer1 - A Pointer object. - */ + * @property {Phaser.Pointer} pointer1 - A Pointer object. + */ this.pointer1 = null; /** - * @property {Phaser.Pointer} pointer2 - A Pointer object. - */ + * @property {Phaser.Pointer} pointer2 - A Pointer object. + */ this.pointer2 = null; /** - * @property {Phaser.Pointer} pointer3 - A Pointer object. - */ + * @property {Phaser.Pointer} pointer3 - A Pointer object. + */ this.pointer3 = null; /** - * @property {Phaser.Pointer} pointer4 - A Pointer object. - */ + * @property {Phaser.Pointer} pointer4 - A Pointer object. + */ this.pointer4 = null; /** - * @property {Phaser.Pointer} pointer5 - A Pointer object. - */ + * @property {Phaser.Pointer} pointer5 - A Pointer object. + */ this.pointer5 = null; /** - * @property {Phaser.Pointer} pointer6 - A Pointer object. - */ + * @property {Phaser.Pointer} pointer6 - A Pointer object. + */ this.pointer6 = null; /** - * @property {Phaser.Pointer} pointer7 - A Pointer object. - */ + * @property {Phaser.Pointer} pointer7 - A Pointer object. + */ this.pointer7 = null; /** - * @property {Phaser.Pointer} pointer8 - A Pointer object. - */ + * @property {Phaser.Pointer} pointer8 - A Pointer object. + */ this.pointer8 = null; /** - * @property {Phaser.Pointer} pointer9 - A Pointer object. - */ + * @property {Phaser.Pointer} pointer9 - A Pointer object. + */ this.pointer9 = null; /** - * @property {Phaser.Pointer} pointer10 - A Pointer object. - */ + * @property {Phaser.Pointer} pointer10 - A Pointer object. + */ this.pointer10 = null; /** - * A pool of non-mouse (contact) pointers that have been added to the game. - * They're activated and updated by {@link Phaser.Input#mspointer} and {@link Phaser.Input#touch}. - * The properties `pointer1..10` are aliases for `pointers[0..9]`. - * @property {Phaser.Pointer[]} pointers - * @public - * @readonly - */ + * A pool of non-mouse (contact) pointers that have been added to the game. + * They're activated and updated by {@link Phaser.Input#mspointer} and {@link Phaser.Input#touch}. + * The properties `pointer1..10` are aliases for `pointers[0..9]`. + * @property {Phaser.Pointer[]} pointers + * @public + * @readonly + */ this.pointers = []; /** - * The most recently active Pointer object. - * - * When you've limited max pointers to 1 this will accurately be either the first finger touched or mouse. - * - * @property {Phaser.Pointer} activePointer - */ + * The most recently active Pointer object. + * + * When you've limited max pointers to 1 this will accurately be either the first finger touched or mouse. + * + * @property {Phaser.Pointer} activePointer + */ this.activePointer = null; /** - * The mouse has its own unique Phaser.Pointer object which you can use if making a desktop specific game. - * - * The mouse pointer is updated by {@link Phaser.Input#mouse} and {@link Phaser.Input#mspointer}. - * - * @property {Pointer} mousePointer - */ + * The mouse has its own unique Phaser.Pointer object which you can use if making a desktop specific game. + * + * The mouse pointer is updated by {@link Phaser.Input#mouse} and {@link Phaser.Input#mspointer}. + * + * @property {Pointer} mousePointer + */ this.mousePointer = null; /** - * The Mouse Input manager. - * - * You should not usually access this manager directly, but instead use Input.mousePointer or Input.activePointer - * which normalizes all the input values for you, regardless of browser. - * - * @property {Phaser.Mouse} mouse - */ + * The Mouse Input manager. + * + * You should not usually access this manager directly, but instead use Input.mousePointer or Input.activePointer + * which normalizes all the input values for you, regardless of browser. + * + * @property {Phaser.Mouse} mouse + */ this.mouse = null; /** - * The Keyboard Input manager. - * - * @property {Phaser.Keyboard} keyboard - */ + * The Keyboard Input manager. + * + * @property {Phaser.Keyboard} keyboard + */ this.keyboard = null; /** - * The Touch Input manager. - * - * You should not usually access this manager directly, but instead use Input.activePointer - * which normalizes all the input values for you, regardless of browser. - * - * @property {Phaser.Touch} touch - */ + * The Touch Input manager. + * + * You should not usually access this manager directly, but instead use Input.activePointer + * which normalizes all the input values for you, regardless of browser. + * + * @property {Phaser.Touch} touch + */ this.touch = null; /** - * The MSPointer Input manager. - * - * You should not usually access this manager directly, but instead use Input.activePointer - * which normalizes all the input values for you, regardless of browser. - * - * @property {Phaser.MSPointer} mspointer - */ + * The MSPointer Input manager. + * + * You should not usually access this manager directly, but instead use Input.activePointer + * which normalizes all the input values for you, regardless of browser. + * + * @property {Phaser.MSPointer} mspointer + */ this.mspointer = null; /** - * The Gamepad Input manager. - * - * @property {Phaser.Gamepad} gamepad - */ + * The Gamepad Input manager. + * + * @property {Phaser.Gamepad} gamepad + */ this.gamepad = null; /** - * If the Input Manager has been reset locked then all calls made to InputManager.reset, - * such as from a State change, are ignored. - * @property {boolean} resetLocked - * @default - */ + * If the Input Manager has been reset locked then all calls made to InputManager.reset, + * such as from a State change, are ignored. + * @property {boolean} resetLocked + * @default + */ this.resetLocked = false; /** - * A Signal that is dispatched each time a {@link Phaser.Pointer pointer} is pressed down. - * It is sent two arguments: - * - * - {Phaser.Pointer} The pointer that caused the event. - * - {Event} The original DOM event. - * - * @property {Phaser.Signal} onDown - */ + * A Signal that is dispatched each time a {@link Phaser.Pointer pointer} is pressed down. + * It is sent two arguments: + * + * - {Phaser.Pointer} The pointer that caused the event. + * - {Event} The original DOM event. + * + * @property {Phaser.Signal} onDown + */ this.onDown = null; /** - * A Signal that is dispatched each time a {@link Phaser.Pointer pointer} is released. - * It is sent two arguments: - * - * - {Phaser.Pointer} The pointer that caused the event. - * - {Event} The original DOM event. - * - * @property {Phaser.Signal} onUp - */ + * A Signal that is dispatched each time a {@link Phaser.Pointer pointer} is released. + * It is sent two arguments: + * + * - {Phaser.Pointer} The pointer that caused the event. + * - {Event} The original DOM event. + * + * @property {Phaser.Signal} onUp + */ this.onUp = null; /** - * A Signal that is dispatched each time a {@link Phaser.Pointer pointer} is tapped. - * It is sent two arguments: - * - * - {Phaser.Pointer} The pointer that caused the event. - * - {boolean} True if this was a double tap. - * - * @property {Phaser.Signal} onTap - */ + * A Signal that is dispatched each time a {@link Phaser.Pointer pointer} is tapped. + * It is sent two arguments: + * + * - {Phaser.Pointer} The pointer that caused the event. + * - {boolean} True if this was a double tap. + * + * @property {Phaser.Signal} onTap + */ this.onTap = null; /** - * A Signal that is dispatched each time a {@link Phaser.Pointer pointer} is held down. - * It is sent one argument: - * - * - {Phaser.Pointer} The pointer that caused the event. - * - * @property {Phaser.Signal} onHold - */ + * A Signal that is dispatched each time a {@link Phaser.Pointer pointer} is held down. + * It is sent one argument: + * + * - {Phaser.Pointer} The pointer that caused the event. + * + * @property {Phaser.Signal} onHold + */ this.onHold = null; /** - * You can tell all Pointers to ignore any Game Object with a `priorityID` lower than this value. - * This is useful when stacking UI layers. Set to zero to disable. - * @property {number} minPriorityID - * @default - */ + * You can tell all Pointers to ignore any Game Object with a `priorityID` lower than this value. + * This is useful when stacking UI layers. Set to zero to disable. + * @property {number} minPriorityID + * @default + */ this.minPriorityID = 0; /** - * A list of interactive objects. The InputHandler components add and remove themselves from this list. - * @property {Phaser.ArraySet} interactiveItems - */ + * A list of interactive objects. The InputHandler components add and remove themselves from this list. + * @property {Phaser.ArraySet} interactiveItems + */ this.interactiveItems = new Phaser.ArraySet(); /** - * @property {Phaser.Point} _localPoint - Internal cache var. - * @private - */ + * @property {Phaser.Point} _localPoint - Internal cache var. + * @private + */ this._localPoint = new Phaser.Point(); /** - * @property {number} _pollCounter - Internal var holding the current poll counter. - * @private - */ + * @property {number} _pollCounter - Internal var holding the current poll counter. + * @private + */ this._pollCounter = 0; /** - * @property {Phaser.Point} _oldPosition - A point object representing the previous position of the Pointer. - * @private - */ + * @property {Phaser.Point} _oldPosition - A point object representing the previous position of the Pointer. + * @private + */ this._oldPosition = null; /** - * @property {number} _x - x coordinate of the most recent Pointer event - * @private - */ + * @property {number} _x - x coordinate of the most recent Pointer event + * @private + */ this._x = 0; /** - * @property {number} _y - Y coordinate of the most recent Pointer event - * @private - */ + * @property {number} _y - Y coordinate of the most recent Pointer event + * @private + */ this._y = 0; - }; /** -* @constant -* @type {number} -*/ + * @constant + * @type {number} + */ Phaser.Input.MOUSE_OVERRIDES_TOUCH = 0; /** -* @constant -* @type {number} -*/ + * @constant + * @type {number} + */ Phaser.Input.TOUCH_OVERRIDES_MOUSE = 1; /** -* @constant -* @type {number} -*/ + * @constant + * @type {number} + */ Phaser.Input.MOUSE_TOUCH_COMBINE = 2; /** -* The maximum number of pointers that can be added. This excludes the mouse pointer. -* @constant -* @type {integer} -*/ + * The maximum number of pointers that can be added. This excludes the mouse pointer. + * @constant + * @type {integer} + */ Phaser.Input.MAX_POINTERS = 10; Phaser.Input.prototype = { /** - * @typedef {object} InputConfig - * @property {boolean} [keyboard=true] - * @property {boolean} [maxPointers=-1] - * @property {boolean} [mouse=true] - * @property {boolean} [mouseWheel=true] - * @property {boolean} [mspointer=true] - * @property {boolean} [pointerLock=true] - * @property {boolean} [touch=true] - */ + * @typedef {object} InputConfig + * @property {boolean} [keyboard=true] + * @property {boolean} [maxPointers=-1] + * @property {boolean} [mouse=true] + * @property {boolean} [mouseWheel=true] + * @property {boolean} [mspointer=true] + * @property {boolean} [pointerLock=true] + * @property {boolean} [touch=true] + */ /** - * Starts the Input Manager running. - * - * @method Phaser.Input#boot - * @protected - * @param {InputConfig} config - */ + * Starts the Input Manager running. + * + * @method Phaser.Input#boot + * @protected + * @param {InputConfig} config + */ boot: function (config) { - if ('maxPointers' in config) { this.maxPointers = config.maxPointers; @@ -516,17 +513,15 @@ Phaser.Input.prototype = { }; this.game.canvas.addEventListener('click', this._onClickTrampoline, false); - }, /** - * Stops all of the Input Managers from running. - * - * @method Phaser.Input#destroy - */ + * Stops all of the Input Managers from running. + * + * @method Phaser.Input#destroy + */ destroy: function () { - this.mouse.stop(); this.mouseWheel.stop(); this.touch.stop(); @@ -548,64 +543,59 @@ Phaser.Input.prototype = { Phaser.CanvasPool.remove(this); this.game.canvas.removeEventListener('click', this._onClickTrampoline); - }, /** - * Adds a callback that is fired every time `Pointer.processInteractiveObjects` is called. - * The purpose of `processInteractiveObjects` is to work out which Game Object the Pointer is going to - * interact with. It works by polling all of the valid game objects, and then slowly discounting those - * that don't meet the criteria (i.e. they aren't under the Pointer, are disabled, invisible, etc). - * - * Eventually a short-list of 'candidates' is created. These are all of the Game Objects which are valid - * for input and overlap with the Pointer. If you need fine-grained control over which of the items is - * selected then you can use this callback to do so. - * - * The callback will be sent 3 parameters: - * - * 1) A reference to the Phaser.Pointer object that is processing the Items. - * 2) An array containing all potential interactive candidates. This is an array of `InputHandler` objects, not Sprites. - * 3) The current 'favorite' candidate, based on its priorityID and position in the display list. - * - * Your callback MUST return one of the candidates sent to it. - * - * @method Phaser.Input#setInteractiveCandidateHandler - * @param {function} callback - The callback that will be called each time `Pointer.processInteractiveObjects` is called. Set to `null` to disable. - * @param {object} context - The context in which the callback will be called. - */ + * Adds a callback that is fired every time `Pointer.processInteractiveObjects` is called. + * The purpose of `processInteractiveObjects` is to work out which Game Object the Pointer is going to + * interact with. It works by polling all of the valid game objects, and then slowly discounting those + * that don't meet the criteria (i.e. they aren't under the Pointer, are disabled, invisible, etc). + * + * Eventually a short-list of 'candidates' is created. These are all of the Game Objects which are valid + * for input and overlap with the Pointer. If you need fine-grained control over which of the items is + * selected then you can use this callback to do so. + * + * The callback will be sent 3 parameters: + * + * 1) A reference to the Phaser.Pointer object that is processing the Items. + * 2) An array containing all potential interactive candidates. This is an array of `InputHandler` objects, not Sprites. + * 3) The current 'favorite' candidate, based on its priorityID and position in the display list. + * + * Your callback MUST return one of the candidates sent to it. + * + * @method Phaser.Input#setInteractiveCandidateHandler + * @param {function} callback - The callback that will be called each time `Pointer.processInteractiveObjects` is called. Set to `null` to disable. + * @param {object} context - The context in which the callback will be called. + */ setInteractiveCandidateHandler: function (callback, context) { - this.customCandidateHandler = callback; this.customCandidateHandlerContext = context; - }, /** - * Adds a callback that is fired every time the activePointer receives a DOM move event such as a mousemove or touchmove. - * - * The callback will be sent 5 parameters: - * - * - A reference to the Phaser.Pointer object that moved - * - The x position of the pointer - * - The y position - * - A boolean indicating if the movement was the result of a 'click' event (such as a mouse click or touch down) - * - The DOM move event - * - * It will be called every time the activePointer moves, which in a multi-touch game can be a lot of times, so this is best - * to only use if you've limited input to a single pointer (i.e. mouse or touch). - * - * The callback is added to the Phaser.Input.moveCallbacks array and should be removed with Phaser.Input.deleteMoveCallback. - * - * @method Phaser.Input#addMoveCallback - * @param {function} callback - The callback that will be called each time the activePointer receives a DOM move event. - * @param {object} context - The context in which the callback will be called. - */ + * Adds a callback that is fired every time the activePointer receives a DOM move event such as a mousemove or touchmove. + * + * The callback will be sent 5 parameters: + * + * - A reference to the Phaser.Pointer object that moved + * - The x position of the pointer + * - The y position + * - A boolean indicating if the movement was the result of a 'click' event (such as a mouse click or touch down) + * - The DOM move event + * + * It will be called every time the activePointer moves, which in a multi-touch game can be a lot of times, so this is best + * to only use if you've limited input to a single pointer (i.e. mouse or touch). + * + * The callback is added to the Phaser.Input.moveCallbacks array and should be removed with Phaser.Input.deleteMoveCallback. + * + * @method Phaser.Input#addMoveCallback + * @param {function} callback - The callback that will be called each time the activePointer receives a DOM move event. + * @param {object} context - The context in which the callback will be called. + */ addMoveCallback: function (callback, context) { - this.moveCallbacks.push({ callback: callback, context: context }); - }, @@ -625,11 +615,9 @@ Phaser.Input.prototype = { */ addTouchLockCallback: function (callback, context, onEnd) { - if (onEnd === undefined) { onEnd = false; } this.touchLockCallbacks.push({ callback: callback, context: context, onEnd: onEnd }); - }, /** @@ -642,7 +630,6 @@ Phaser.Input.prototype = { */ removeTouchLockCallback: function (callback, context) { - var i = this.touchLockCallbacks.length; while (i--) @@ -655,7 +642,6 @@ Phaser.Input.prototype = { } return false; - }, /** @@ -682,15 +668,14 @@ Phaser.Input.prototype = { }, /** - * Removes the callback from the Phaser.Input.moveCallbacks array. - * - * @method Phaser.Input#deleteMoveCallback - * @param {function} callback - The callback to be removed. - * @param {object} context - The context in which the callback exists. - */ + * Removes the callback from the Phaser.Input.moveCallbacks array. + * + * @method Phaser.Input#deleteMoveCallback + * @param {function} callback - The callback to be removed. + * @param {object} context - The context in which the callback exists. + */ deleteMoveCallback: function (callback, context) { - var i = this.moveCallbacks.length; while (i--) @@ -701,20 +686,18 @@ Phaser.Input.prototype = { return; } } - }, /** - * Add a new Pointer object to the Input Manager. - * By default Input creates 3 pointer objects: `mousePointer` (not include in part of general pointer pool), `pointer1` and `pointer2`. - * This method adds an additional pointer, up to a maximum of Phaser.Input.MAX_POINTERS (default of 10). - * - * @method Phaser.Input#addPointer - * @return {Phaser.Pointer|null} The new Pointer object that was created; null if a new pointer could not be added. - */ + * Add a new Pointer object to the Input Manager. + * By default Input creates 3 pointer objects: `mousePointer` (not include in part of general pointer pool), `pointer1` and `pointer2`. + * This method adds an additional pointer, up to a maximum of Phaser.Input.MAX_POINTERS (default of 10). + * + * @method Phaser.Input#addPointer + * @return {Phaser.Pointer|null} The new Pointer object that was created; null if a new pointer could not be added. + */ addPointer: function () { - if (this.pointers.length >= Phaser.Input.MAX_POINTERS) { console.warn('Phaser.Input.addPointer: Maximum limit of ' + Phaser.Input.MAX_POINTERS + ' pointers reached.'); @@ -728,18 +711,16 @@ Phaser.Input.prototype = { this['pointer' + id] = pointer; return pointer; - }, /** - * Updates the Input Manager. Called by the core Game loop. - * - * @method Phaser.Input#update - * @protected - */ + * Updates the Input Manager. Called by the core Game loop. + * + * @method Phaser.Input#update + * @protected + */ update: function () { - if (this.keyboard) { this.keyboard.update(); @@ -768,7 +749,6 @@ Phaser.Input.prototype = { } this._pollCounter = 0; - }, /** @@ -779,28 +759,25 @@ Phaser.Input.prototype = { */ pauseUpdate: function () { - if (this.gamepad && this.gamepad.active) { this.gamepad.update(); } - }, /** - * Reset all of the Pointers and Input states. - * - * The optional `hard` parameter will reset any events or callbacks that may be bound. - * Input.reset is called automatically during a State change or if a game loses focus / visibility. - * To control control the reset manually set {@link Phaser.InputManager.resetLocked} to `true`. - * - * @method Phaser.Input#reset - * @public - * @param {boolean} [hard=false] - A soft reset won't reset any events or callbacks that are bound. A hard reset will. - */ + * Reset all of the Pointers and Input states. + * + * The optional `hard` parameter will reset any events or callbacks that may be bound. + * Input.reset is called automatically during a State change or if a game loses focus / visibility. + * To control control the reset manually set {@link Phaser.InputManager.resetLocked} to `true`. + * + * @method Phaser.Input#reset + * @public + * @param {boolean} [hard=false] - A soft reset won't reset any events or callbacks that are bound. A hard reset will. + */ reset: function (hard) { - if (!this.game.isBooted || this.resetLocked) { return; @@ -839,36 +816,32 @@ Phaser.Input.prototype = { } this._pollCounter = 0; - }, /** - * Resets the speed and old position properties. - * - * @method Phaser.Input#resetSpeed - * @param {number} x - Sets the oldPosition.x value. - * @param {number} y - Sets the oldPosition.y value. - */ + * Resets the speed and old position properties. + * + * @method Phaser.Input#resetSpeed + * @param {number} x - Sets the oldPosition.x value. + * @param {number} y - Sets the oldPosition.y value. + */ resetSpeed: function (x, y) { - this._oldPosition.setTo(x, y); this.speed.setTo(0, 0); - }, /** - * Find the first free Pointer object and start it, passing in the event data. - * This is called automatically by Phaser.Touch and Phaser.MSPointer. - * - * @method Phaser.Input#startPointer - * @protected - * @param {any} event - The event data from the Touch event. - * @return {Phaser.Pointer} The Pointer object that was started or null if no Pointer object is available. - */ + * Find the first free Pointer object and start it, passing in the event data. + * This is called automatically by Phaser.Touch and Phaser.MSPointer. + * + * @method Phaser.Input#startPointer + * @protected + * @param {any} event - The event data from the Touch event. + * @return {Phaser.Pointer} The Pointer object that was started or null if no Pointer object is available. + */ startPointer: function (event) { - if (this.maxPointers >= 0 && this.countActivePointers(this.maxPointers) >= this.maxPointers) { return null; @@ -895,21 +868,19 @@ Phaser.Input.prototype = { } return null; - }, /** - * Updates the matching Pointer object, passing in the event data. - * This is called automatically and should not normally need to be invoked. - * - * @method Phaser.Input#updatePointer - * @protected - * @param {any} event - The event data from the Touch event. - * @return {Phaser.Pointer} The Pointer object that was updated; null if no pointer was updated. - */ + * Updates the matching Pointer object, passing in the event data. + * This is called automatically and should not normally need to be invoked. + * + * @method Phaser.Input#updatePointer + * @protected + * @param {any} event - The event data from the Touch event. + * @return {Phaser.Pointer} The Pointer object that was updated; null if no pointer was updated. + */ updatePointer: function (event) { - if (this.pointer1.active && this.pointer1.identifier === event.identifier) { return this.pointer1.move(event); @@ -931,20 +902,18 @@ Phaser.Input.prototype = { } return null; - }, /** - * Stops the matching Pointer object, passing in the event data. - * - * @method Phaser.Input#stopPointer - * @protected - * @param {any} event - The event data from the Touch event. - * @return {Phaser.Pointer} The Pointer object that was stopped or null if no Pointer object is available. - */ + * Stops the matching Pointer object, passing in the event data. + * + * @method Phaser.Input#stopPointer + * @protected + * @param {any} event - The event data from the Touch event. + * @return {Phaser.Pointer} The Pointer object that was stopped or null if no Pointer object is available. + */ stopPointer: function (event) { - if (this.pointer1.active && this.pointer1.identifier === event.identifier) { return this.pointer1.stop(event); @@ -966,20 +935,18 @@ Phaser.Input.prototype = { } return null; - }, /** - * Returns the total number of active pointers, not exceeding the specified limit - * - * @name Phaser.Input#countActivePointers - * @private - * @property {integer} [limit=(max pointers)] - Stop counting after this. - * @return {integer} The number of active pointers, or limit - whichever is less. - */ + * Returns the total number of active pointers, not exceeding the specified limit + * + * @name Phaser.Input#countActivePointers + * @private + * @property {integer} [limit=(max pointers)] - Stop counting after this. + * @return {integer} The number of active pointers, or limit - whichever is less. + */ countActivePointers: function (limit) { - if (limit === undefined) { limit = this.pointers.length; } var count = limit; @@ -995,19 +962,17 @@ Phaser.Input.prototype = { } return (limit - count); - }, /** - * Get the first Pointer with the given active state. - * - * @method Phaser.Input#getPointer - * @param {boolean} [isActive=false] - The state the Pointer should be in - active or inactive? - * @return {Phaser.Pointer} A Pointer object or null if no Pointer object matches the requested state. - */ + * Get the first Pointer with the given active state. + * + * @method Phaser.Input#getPointer + * @param {boolean} [isActive=false] - The state the Pointer should be in - active or inactive? + * @return {Phaser.Pointer} A Pointer object or null if no Pointer object matches the requested state. + */ getPointer: function (isActive) { - if (isActive === undefined) { isActive = false; } for (var i = 0; i < this.pointers.length; i++) @@ -1021,23 +986,21 @@ Phaser.Input.prototype = { } return null; - }, /** - * Get the Pointer object whos `identifier` property matches the given identifier value. - * - * The identifier property is not set until the Pointer has been used at least once, as its populated by the DOM event. - * Also it can change every time you press the pointer down, and is not fixed once set. - * Note: Not all browsers set the identifier property and it's not part of the W3C spec, so you may need getPointerFromId instead. - * - * @method Phaser.Input#getPointerFromIdentifier - * @param {number} identifier - The Pointer.identifier value to search for. - * @return {Phaser.Pointer} A Pointer object or null if no Pointer object matches the requested identifier. - */ + * Get the Pointer object whos `identifier` property matches the given identifier value. + * + * The identifier property is not set until the Pointer has been used at least once, as its populated by the DOM event. + * Also it can change every time you press the pointer down, and is not fixed once set. + * Note: Not all browsers set the identifier property and it's not part of the W3C spec, so you may need getPointerFromId instead. + * + * @method Phaser.Input#getPointerFromIdentifier + * @param {number} identifier - The Pointer.identifier value to search for. + * @return {Phaser.Pointer} A Pointer object or null if no Pointer object matches the requested identifier. + */ getPointerFromIdentifier: function (identifier) { - for (var i = 0; i < this.pointers.length; i++) { var pointer = this.pointers[i]; @@ -1049,22 +1012,20 @@ Phaser.Input.prototype = { } return null; - }, /** - * Get the Pointer object whos `pointerId` property matches the given value. - * - * The pointerId property is not set until the Pointer has been used at least once, as its populated by the DOM event. - * Also it can change every time you press the pointer down if the browser recycles it. - * - * @method Phaser.Input#getPointerFromId - * @param {number} pointerId - The `pointerId` (not 'id') value to search for. - * @return {Phaser.Pointer} A Pointer object or null if no Pointer object matches the requested identifier. - */ + * Get the Pointer object whos `pointerId` property matches the given value. + * + * The pointerId property is not set until the Pointer has been used at least once, as its populated by the DOM event. + * Also it can change every time you press the pointer down if the browser recycles it. + * + * @method Phaser.Input#getPointerFromId + * @param {number} pointerId - The `pointerId` (not 'id') value to search for. + * @return {Phaser.Pointer} A Pointer object or null if no Pointer object matches the requested identifier. + */ getPointerFromId: function (pointerId) { - for (var i = 0; i < this.pointers.length; i++) { var pointer = this.pointers[i]; @@ -1076,20 +1037,18 @@ Phaser.Input.prototype = { } return null; - }, /** - * This will return the local coordinates of the specified displayObject based on the given Pointer. - * - * @method Phaser.Input#getLocalPosition - * @param {Phaser.Sprite|Phaser.Image} displayObject - The DisplayObject to get the local coordinates for. - * @param {Phaser.Pointer} pointer - The Pointer to use in the check against the displayObject. - * @return {Phaser.Point} A point containing the coordinates of the Pointer position relative to the DisplayObject. - */ + * This will return the local coordinates of the specified displayObject based on the given Pointer. + * + * @method Phaser.Input#getLocalPosition + * @param {Phaser.Sprite|Phaser.Image} displayObject - The DisplayObject to get the local coordinates for. + * @param {Phaser.Pointer} pointer - The Pointer to use in the check against the displayObject. + * @return {Phaser.Point} A point containing the coordinates of the Pointer position relative to the DisplayObject. + */ getLocalPosition: function (displayObject, pointer, output) { - if (output === undefined) { output = new Phaser.Point(); } var wt = displayObject.worldTransform; @@ -1099,20 +1058,18 @@ Phaser.Input.prototype = { wt.d * id * pointer.x + -wt.c * id * pointer.y + (wt.ty * wt.c - wt.tx * wt.d) * id, wt.a * id * pointer.y + -wt.b * id * pointer.x + (-wt.ty * wt.a + wt.tx * wt.b) * id ); - }, /** - * Tests if the pointer hits the given object. - * - * @method Phaser.Input#hitTest - * @param {DisplayObject} displayObject - The displayObject to test for a hit. - * @param {Phaser.Pointer} pointer - The pointer to use for the test. - * @param {Phaser.Point} localPoint - The local translated point. - */ + * Tests if the pointer hits the given object. + * + * @method Phaser.Input#hitTest + * @param {DisplayObject} displayObject - The displayObject to test for a hit. + * @param {Phaser.Pointer} pointer - The pointer to use for the test. + * @param {Phaser.Point} localPoint - The local translated point. + */ hitTest: function (displayObject, pointer, localPoint) { - if (!displayObject.worldVisible) { return false; @@ -1207,28 +1164,28 @@ Phaser.Input.prototype = { }, /** - * Used for click trampolines. See {@link Phaser.Pointer.addClickTrampoline}. - * - * @method Phaser.Input#onClickTrampoline - * @private - */ + * Used for click trampolines. See {@link Phaser.Pointer.addClickTrampoline}. + * + * @method Phaser.Input#onClickTrampoline + * @private + */ onClickTrampoline: function () { - - // It might not always be the active pointer, but this does work on - // Desktop browsers (read: IE) with Mouse or MSPointer input. + /* + * It might not always be the active pointer, but this does work on + * Desktop browsers (read: IE) with Mouse or MSPointer input. + */ this.activePointer.processClickTrampolines(); - }, /** - * Call a handler on all enabled interactive items, for a given pointer. - * - * @method Phaser.Input#callAll - * @param {string} handler - Exact method name. - * @param {Phaser.Pointer} - The pointer triggering the handler. - * @private - */ + * Call a handler on all enabled interactive items, for a given pointer. + * + * @method Phaser.Input#callAll + * @param {string} handler - Exact method name. + * @param {Phaser.Pointer} - The pointer triggering the handler. + * @private + */ callAll: function (handler, pointer) { var list = this.interactiveItems.list; @@ -1250,11 +1207,11 @@ Phaser.Input.prototype = { Phaser.Input.prototype.constructor = Phaser.Input; /** -* The X coordinate of the most recently active pointer. -* This value takes game scaling into account automatically. See Pointer.screenX/clientX for source values. -* @name Phaser.Input#x -* @property {number} x -*/ + * The X coordinate of the most recently active pointer. + * This value takes game scaling into account automatically. See Pointer.screenX/clientX for source values. + * @name Phaser.Input#x + * @property {number} x + */ Object.defineProperty(Phaser.Input.prototype, 'x', { get: function () @@ -1270,11 +1227,11 @@ Object.defineProperty(Phaser.Input.prototype, 'x', { }); /** -* The Y coordinate of the most recently active pointer. -* This value takes game scaling into account automatically. See Pointer.screenY/clientY for source values. -* @name Phaser.Input#y -* @property {number} y -*/ + * The Y coordinate of the most recently active pointer. + * This value takes game scaling into account automatically. See Pointer.screenY/clientY for source values. + * @name Phaser.Input#y + * @property {number} y + */ Object.defineProperty(Phaser.Input.prototype, 'y', { get: function () @@ -1290,11 +1247,11 @@ Object.defineProperty(Phaser.Input.prototype, 'y', { }); /** -* True if the Input is currently poll rate locked. -* @name Phaser.Input#pollLocked -* @property {boolean} pollLocked -* @readonly -*/ + * True if the Input is currently poll rate locked. + * @name Phaser.Input#pollLocked + * @property {boolean} pollLocked + * @readonly + */ Object.defineProperty(Phaser.Input.prototype, 'pollLocked', { get: function () @@ -1305,11 +1262,11 @@ Object.defineProperty(Phaser.Input.prototype, 'pollLocked', { }); /** -* The total number of inactive Pointers. -* @name Phaser.Input#totalInactivePointers -* @property {number} totalInactivePointers -* @readonly -*/ + * The total number of inactive Pointers. + * @name Phaser.Input#totalInactivePointers + * @property {number} totalInactivePointers + * @readonly + */ Object.defineProperty(Phaser.Input.prototype, 'totalInactivePointers', { get: function () @@ -1320,11 +1277,11 @@ Object.defineProperty(Phaser.Input.prototype, 'totalInactivePointers', { }); /** -* The total number of active Pointers, not counting the mouse pointer. -* @name Phaser.Input#totalActivePointers -* @property {integers} totalActivePointers -* @readonly -*/ + * The total number of active Pointers, not counting the mouse pointer. + * @name Phaser.Input#totalActivePointers + * @property {integers} totalActivePointers + * @readonly + */ Object.defineProperty(Phaser.Input.prototype, 'totalActivePointers', { get: function () @@ -1335,11 +1292,11 @@ Object.defineProperty(Phaser.Input.prototype, 'totalActivePointers', { }); /** -* The world X coordinate of the most recently active pointer. -* @name Phaser.Input#worldX -* @property {number} worldX - The world X coordinate of the most recently active pointer. -* @readonly -*/ + * The world X coordinate of the most recently active pointer. + * @name Phaser.Input#worldX + * @property {number} worldX - The world X coordinate of the most recently active pointer. + * @readonly + */ Object.defineProperty(Phaser.Input.prototype, 'worldX', { get: function () @@ -1350,11 +1307,11 @@ Object.defineProperty(Phaser.Input.prototype, 'worldX', { }); /** -* The world Y coordinate of the most recently active pointer. -* @name Phaser.Input#worldY -* @property {number} worldY - The world Y coordinate of the most recently active pointer. -* @readonly -*/ + * The world Y coordinate of the most recently active pointer. + * @name Phaser.Input#worldY + * @property {number} worldY - The world Y coordinate of the most recently active pointer. + * @readonly + */ Object.defineProperty(Phaser.Input.prototype, 'worldY', { get: function () diff --git a/src/input/InputHandler.js b/src/input/InputHandler.js index 43fdaf571..7d29fd0ea 100644 --- a/src/input/InputHandler.js +++ b/src/input/InputHandler.js @@ -1,263 +1,262 @@ /** -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* The Input Handler is bound to a specific Sprite and is responsible for managing all Input events on that Sprite. -* -* @class Phaser.InputHandler -* @constructor -* @param {Phaser.Sprite} sprite - The Sprite object to which this Input Handler belongs. -*/ + * The Input Handler is bound to a specific Sprite and is responsible for managing all Input events on that Sprite. + * + * @class Phaser.InputHandler + * @constructor + * @param {Phaser.Sprite} sprite - The Sprite object to which this Input Handler belongs. + */ Phaser.InputHandler = function (sprite) { - /** - * @property {Phaser.Sprite} sprite - The Sprite object to which this Input Handler belongs. - */ + * @property {Phaser.Sprite} sprite - The Sprite object to which this Input Handler belongs. + */ this.sprite = sprite; /** - * @property {Phaser.Game} game - A reference to the currently running game. - */ + * @property {Phaser.Game} game - A reference to the currently running game. + */ this.game = sprite.game; /** - * @property {boolean} enabled - If enabled the Input Handler will process input requests and monitor pointer activity. - * @default - */ + * @property {boolean} enabled - If enabled the Input Handler will process input requests and monitor pointer activity. + * @default + */ this.enabled = false; /** - * @property {boolean} checked - A disposable flag used by the Pointer class when performing priority checks. - * @protected - */ + * @property {boolean} checked - A disposable flag used by the Pointer class when performing priority checks. + * @protected + */ this.checked = false; /** - * The priorityID is used to determine which game objects should get priority when input events occur. For example if you have - * several Sprites that overlap, by default the one at the top of the display list is given priority for input events. You can - * stop this from happening by controlling the priorityID value. The higher the value, the more important they are considered to the Input events. - * @property {number} priorityID - * @default - */ + * The priorityID is used to determine which game objects should get priority when input events occur. For example if you have + * several Sprites that overlap, by default the one at the top of the display list is given priority for input events. You can + * stop this from happening by controlling the priorityID value. The higher the value, the more important they are considered to the Input events. + * @property {number} priorityID + * @default + */ this.priorityID = 0; /** - * @property {boolean} useHandCursor - On a desktop browser you can set the 'hand' cursor to appear when moving over the Sprite. - * @default - */ + * @property {boolean} useHandCursor - On a desktop browser you can set the 'hand' cursor to appear when moving over the Sprite. + * @default + */ this.useHandCursor = false; /** - * @property {boolean} _setHandCursor - Did this Sprite trigger the hand cursor? - * @private - */ + * @property {boolean} _setHandCursor - Did this Sprite trigger the hand cursor? + * @private + */ this._setHandCursor = false; /** - * @property {boolean} isDragged - true if the Sprite is being currently dragged. - * @default - */ + * @property {boolean} isDragged - true if the Sprite is being currently dragged. + * @default + */ this.isDragged = false; /** - * @property {boolean} allowHorizontalDrag - Controls if the Sprite is allowed to be dragged horizontally. - * @default - */ + * @property {boolean} allowHorizontalDrag - Controls if the Sprite is allowed to be dragged horizontally. + * @default + */ this.allowHorizontalDrag = true; /** - * @property {boolean} allowVerticalDrag - Controls if the Sprite is allowed to be dragged vertically. - * @default - */ + * @property {boolean} allowVerticalDrag - Controls if the Sprite is allowed to be dragged vertically. + * @default + */ this.allowVerticalDrag = true; /** - * @property {boolean} bringToTop - If true when this Sprite is clicked or dragged it will automatically be bought to the top of the Group it is within. - * @default - */ + * @property {boolean} bringToTop - If true when this Sprite is clicked or dragged it will automatically be bought to the top of the Group it is within. + * @default + */ this.bringToTop = false; /** - * @property {Phaser.Point} snapOffset - A Point object that contains by how far the Sprite snap is offset. - * @default - */ + * @property {Phaser.Point} snapOffset - A Point object that contains by how far the Sprite snap is offset. + * @default + */ this.snapOffset = null; /** - * @property {boolean} snapOnDrag - When the Sprite is dragged this controls if the center of the Sprite will snap to the pointer on drag or not. - * @default - */ + * @property {boolean} snapOnDrag - When the Sprite is dragged this controls if the center of the Sprite will snap to the pointer on drag or not. + * @default + */ this.snapOnDrag = false; /** - * @property {boolean} snapOnRelease - When the Sprite is dragged this controls if the Sprite will be snapped on release. - * @default - */ + * @property {boolean} snapOnRelease - When the Sprite is dragged this controls if the Sprite will be snapped on release. + * @default + */ this.snapOnRelease = false; /** - * @property {number} snapX - When a Sprite has snapping enabled this holds the width of the snap grid. - * @default - */ + * @property {number} snapX - When a Sprite has snapping enabled this holds the width of the snap grid. + * @default + */ this.snapX = 0; /** - * @property {number} snapY - When a Sprite has snapping enabled this holds the height of the snap grid. - * @default - */ + * @property {number} snapY - When a Sprite has snapping enabled this holds the height of the snap grid. + * @default + */ this.snapY = 0; /** - * @property {number} snapOffsetX - This defines the top-left X coordinate of the snap grid. - * @default - */ + * @property {number} snapOffsetX - This defines the top-left X coordinate of the snap grid. + * @default + */ this.snapOffsetX = 0; /** - * @property {number} snapOffsetY - This defines the top-left Y coordinate of the snap grid.. - * @default - */ + * @property {number} snapOffsetY - This defines the top-left Y coordinate of the snap grid.. + * @default + */ this.snapOffsetY = 0; /** - * Set to true to use pixel perfect hit detection when checking if the pointer is over this Sprite. - * The x/y coordinates of the pointer are tested against the image in combination with the InputHandler.pixelPerfectAlpha value. - * This feature only works for display objects with image based textures such as Sprites. It won't work on BitmapText or Rope. - * Warning: This is expensive, especially on mobile (where it's not even needed!) so only enable if required. Also see the less-expensive InputHandler.pixelPerfectClick. - * @property {boolean} pixelPerfectOver - Use a pixel perfect check when testing for pointer over. - * @default - */ + * Set to true to use pixel perfect hit detection when checking if the pointer is over this Sprite. + * The x/y coordinates of the pointer are tested against the image in combination with the InputHandler.pixelPerfectAlpha value. + * This feature only works for display objects with image based textures such as Sprites. It won't work on BitmapText or Rope. + * Warning: This is expensive, especially on mobile (where it's not even needed!) so only enable if required. Also see the less-expensive InputHandler.pixelPerfectClick. + * @property {boolean} pixelPerfectOver - Use a pixel perfect check when testing for pointer over. + * @default + */ this.pixelPerfectOver = false; /** - * Set to true to use pixel perfect hit detection when checking if the pointer is over this Sprite when it's clicked or touched. - * The x/y coordinates of the pointer are tested against the image in combination with the InputHandler.pixelPerfectAlpha value. - * This feature only works for display objects with image based textures such as Sprites. It won't work on BitmapText or Rope. - * Warning: This is expensive so only enable if you really need it. - * @property {boolean} pixelPerfectClick - Use a pixel perfect check when testing for clicks or touches on the Sprite. - * @default - */ + * Set to true to use pixel perfect hit detection when checking if the pointer is over this Sprite when it's clicked or touched. + * The x/y coordinates of the pointer are tested against the image in combination with the InputHandler.pixelPerfectAlpha value. + * This feature only works for display objects with image based textures such as Sprites. It won't work on BitmapText or Rope. + * Warning: This is expensive so only enable if you really need it. + * @property {boolean} pixelPerfectClick - Use a pixel perfect check when testing for clicks or touches on the Sprite. + * @default + */ this.pixelPerfectClick = false; /** - * @property {number} pixelPerfectAlpha - The alpha tolerance threshold. If the alpha value of the pixel matches or is above this value, it's considered a hit. - * @default - */ + * @property {number} pixelPerfectAlpha - The alpha tolerance threshold. If the alpha value of the pixel matches or is above this value, it's considered a hit. + * @default + */ this.pixelPerfectAlpha = 255; /** - * @property {boolean} draggable - Is this sprite allowed to be dragged by the mouse? true = yes, false = no - * @default - */ + * @property {boolean} draggable - Is this sprite allowed to be dragged by the mouse? true = yes, false = no + * @default + */ this.draggable = false; /** - * @property {Phaser.Rectangle} boundsRect - A region of the game world within which the sprite is restricted during drag. - * @default - */ + * @property {Phaser.Rectangle} boundsRect - A region of the game world within which the sprite is restricted during drag. + * @default + */ this.boundsRect = null; /** - * @property {Phaser.Sprite} boundsSprite - A Sprite the bounds of which this sprite is restricted during drag. - * @default - */ + * @property {Phaser.Sprite} boundsSprite - A Sprite the bounds of which this sprite is restricted during drag. + * @default + */ this.boundsSprite = null; /** - * @property {boolean} scaleLayer - EXPERIMENTAL: Please do not use this property unless you know what it does. Likely to change in the future. - */ + * @property {boolean} scaleLayer - EXPERIMENTAL: Please do not use this property unless you know what it does. Likely to change in the future. + */ this.scaleLayer = false; /** - * @property {Phaser.Point} dragOffset - The offset from the Sprites position that dragging takes place from. - */ + * @property {Phaser.Point} dragOffset - The offset from the Sprites position that dragging takes place from. + */ this.dragOffset = new Phaser.Point(); /** - * @property {boolean} dragFromCenter - Is the Sprite dragged from its center, or the point at which the Pointer was pressed down upon it? - */ + * @property {boolean} dragFromCenter - Is the Sprite dragged from its center, or the point at which the Pointer was pressed down upon it? + */ this.dragFromCenter = false; /** - * @property {boolean} dragStopBlocksInputUp - If enabled, when the Sprite stops being dragged, it will only dispatch the `onDragStop` event, and not the `onInputUp` event. If set to `false` it will dispatch both events. - */ + * @property {boolean} dragStopBlocksInputUp - If enabled, when the Sprite stops being dragged, it will only dispatch the `onDragStop` event, and not the `onInputUp` event. If set to `false` it will dispatch both events. + */ this.dragStopBlocksInputUp = false; /** - * @property {Phaser.Point} dragStartPoint - The Point from which the most recent drag started from. Useful if you need to return an object to its starting position. - */ + * @property {Phaser.Point} dragStartPoint - The Point from which the most recent drag started from. Useful if you need to return an object to its starting position. + */ this.dragStartPoint = new Phaser.Point(); /** - * @property {integer} dragDistanceThreshold - The distance, in pixels, the pointer has to move while being held down, before the Sprite thinks it is being dragged. - */ + * @property {integer} dragDistanceThreshold - The distance, in pixels, the pointer has to move while being held down, before the Sprite thinks it is being dragged. + */ this.dragDistanceThreshold = 0; /** - * @property {integer} dragTimeThreshold - The amount of time, in ms, the pointer has to be held down over the Sprite before it thinks it is being dragged. - */ + * @property {integer} dragTimeThreshold - The amount of time, in ms, the pointer has to be held down over the Sprite before it thinks it is being dragged. + */ this.dragTimeThreshold = 0; /** - * @property {Phaser.Point} downPoint - A Point object containing the coordinates of the Pointer when it was first pressed down onto this Sprite. - */ + * @property {Phaser.Point} downPoint - A Point object containing the coordinates of the Pointer when it was first pressed down onto this Sprite. + */ this.downPoint = new Phaser.Point(); /** - * @property {Phaser.Point} snapPoint - If the sprite is set to snap while dragging this holds the point of the most recent 'snap' event. - */ + * @property {Phaser.Point} snapPoint - If the sprite is set to snap while dragging this holds the point of the most recent 'snap' event. + */ this.snapPoint = new Phaser.Point(); /** - * @property {Phaser.Point} _dragPoint - Internal cache var. - * @private - */ + * @property {Phaser.Point} _dragPoint - Internal cache var. + * @private + */ this._dragPoint = new Phaser.Point(); /** - * @property {boolean} _dragPhase - Internal cache var. - * @private - */ + * @property {boolean} _dragPhase - Internal cache var. + * @private + */ this._dragPhase = false; /** - * @property {boolean} _pendingDrag - Internal cache var. - * @private - */ + * @property {boolean} _pendingDrag - Internal cache var. + * @private + */ this._pendingDrag = false; /** - * @property {boolean} _dragTimePass - Internal cache var. - * @private - */ + * @property {boolean} _dragTimePass - Internal cache var. + * @private + */ this._dragTimePass = false; /** - * @property {boolean} _dragDistancePass - Internal cache var. - * @private - */ + * @property {boolean} _dragDistancePass - Internal cache var. + * @private + */ this._dragDistancePass = false; /** - * @property {boolean} _wasEnabled - Internal cache var. - * @private - */ + * @property {boolean} _wasEnabled - Internal cache var. + * @private + */ this._wasEnabled = false; /** - * @property {Phaser.Point} _tempPoint - Internal cache var. - * @private - */ + * @property {Phaser.Point} _tempPoint - Internal cache var. + * @private + */ this._tempPoint = new Phaser.Point(); /** - * @property {array} _pointerData - Internal cache var. - * @private - */ + * @property {array} _pointerData - Internal cache var. + * @private + */ this._pointerData = []; this._pointerData.push({ @@ -277,22 +276,20 @@ Phaser.InputHandler = function (sprite) downDuration: 0, isDragged: false }); - }; Phaser.InputHandler.prototype = { /** - * Starts the Input Handler running. This is called automatically when you enable input on a Sprite, or can be called directly if you need to set a specific priority. - * - * @method Phaser.InputHandler#start - * @param {number} [priority=0] - Higher priority sprites take click priority over low-priority sprites when they are stacked on-top of each other. - * @param {boolean} [useHandCursor=false] - If true the Sprite will show the hand cursor on mouse-over (doesn't apply to mobile browsers) - * @return {Phaser.Sprite} The Sprite object to which the Input Handler is bound. - */ + * Starts the Input Handler running. This is called automatically when you enable input on a Sprite, or can be called directly if you need to set a specific priority. + * + * @method Phaser.InputHandler#start + * @param {number} [priority=0] - Higher priority sprites take click priority over low-priority sprites when they are stacked on-top of each other. + * @param {boolean} [useHandCursor=false] - If true the Sprite will show the hand cursor on mouse-over (doesn't apply to mobile browsers) + * @return {Phaser.Sprite} The Sprite object to which the Input Handler is bound. + */ start: function (priority, useHandCursor) { - priority = priority || 0; if (useHandCursor === undefined) { useHandCursor = false; } @@ -326,25 +323,22 @@ Phaser.InputHandler.prototype = { this.snapOffset = new Phaser.Point(); this.enabled = true; this._wasEnabled = true; - } this.sprite.events.onAddedToGroup.add(this.addedToGroup, this); this.sprite.events.onRemovedFromGroup.add(this.removedFromGroup, this); return this.sprite; - }, /** - * Handles when the parent Sprite is added to a new Group. - * - * @method Phaser.InputHandler#addedToGroup - * @private - */ + * Handles when the parent Sprite is added to a new Group. + * + * @method Phaser.InputHandler#addedToGroup + * @private + */ addedToGroup: function () { - if (this._dragPhase) { return; @@ -354,18 +348,16 @@ Phaser.InputHandler.prototype = { { this.start(); } - }, /** - * Handles when the parent Sprite is removed from a Group. - * - * @method Phaser.InputHandler#removedFromGroup - * @private - */ + * Handles when the parent Sprite is removed from a Group. + * + * @method Phaser.InputHandler#removedFromGroup + * @private + */ removedFromGroup: function () { - if (this._dragPhase) { return; @@ -380,16 +372,14 @@ Phaser.InputHandler.prototype = { { this._wasEnabled = false; } - }, /** - * Resets the Input Handler and disables it. - * @method Phaser.InputHandler#reset - */ + * Resets the Input Handler and disables it. + * @method Phaser.InputHandler#reset + */ reset: function () { - this.enabled = false; for (var i = 0; i < 10; i++) @@ -413,12 +403,11 @@ Phaser.InputHandler.prototype = { }, /** - * Stops the Input Handler from running. - * @method Phaser.InputHandler#stop - */ + * Stops the Input Handler from running. + * @method Phaser.InputHandler#stop + */ stop: function () { - // Turning off if (this.enabled === false) { @@ -430,16 +419,14 @@ Phaser.InputHandler.prototype = { this.enabled = false; this.game.input.interactiveItems.remove(this); } - }, /** - * Clean up memory. - * @method Phaser.InputHandler#destroy - */ + * Clean up memory. + * @method Phaser.InputHandler#destroy + */ destroy: function () { - if (this.sprite) { if (this._setHandCursor) @@ -457,23 +444,21 @@ Phaser.InputHandler.prototype = { this.boundsSprite = null; this.sprite = null; } - }, /** - * Checks if the object this InputHandler is bound to is valid for consideration in the Pointer move event. - * This is called by Phaser.Pointer and shouldn't typically be called directly. - * - * @method Phaser.InputHandler#validForInput - * @protected - * @param {number} highestID - The highest ID currently processed by the Pointer. - * @param {number} highestRenderID - The highest Render Order ID currently processed by the Pointer. - * @param {boolean} [includePixelPerfect=true] - If this object has `pixelPerfectClick` or `pixelPerfectOver` set should it be considered as valid? - * @return {boolean} True if the object this InputHandler is bound to should be considered as valid for input detection. - */ + * Checks if the object this InputHandler is bound to is valid for consideration in the Pointer move event. + * This is called by Phaser.Pointer and shouldn't typically be called directly. + * + * @method Phaser.InputHandler#validForInput + * @protected + * @param {number} highestID - The highest ID currently processed by the Pointer. + * @param {number} highestRenderID - The highest Render Order ID currently processed by the Pointer. + * @param {boolean} [includePixelPerfect=true] - If this object has `pixelPerfectClick` or `pixelPerfectOver` set should it be considered as valid? + * @return {boolean} True if the object this InputHandler is bound to should be considered as valid for input detection. + */ validForInput: function (highestID, highestRenderID, includePixelPerfect) { - if (includePixelPerfect === undefined) { includePixelPerfect = true; } if (!this.enabled || @@ -497,132 +482,116 @@ Phaser.InputHandler.prototype = { } return false; - }, /** - * Is this object using pixel perfect checking? - * - * @method Phaser.InputHandler#isPixelPerfect - * @return {boolean} True if the this InputHandler has either `pixelPerfectClick` or `pixelPerfectOver` set to `true`. - */ + * Is this object using pixel perfect checking? + * + * @method Phaser.InputHandler#isPixelPerfect + * @return {boolean} True if the this InputHandler has either `pixelPerfectClick` or `pixelPerfectOver` set to `true`. + */ isPixelPerfect: function () { - return (this.pixelPerfectClick || this.pixelPerfectOver); - }, /** - * The x coordinate of the Input pointer, relative to the top-left of the parent Sprite. - * This value is only set when the pointer is over this Sprite. - * - * @method Phaser.InputHandler#pointerX - * @param {integer} [pointerId=0] - * @return {number} The x coordinate of the Input pointer. - */ + * The x coordinate of the Input pointer, relative to the top-left of the parent Sprite. + * This value is only set when the pointer is over this Sprite. + * + * @method Phaser.InputHandler#pointerX + * @param {integer} [pointerId=0] + * @return {number} The x coordinate of the Input pointer. + */ pointerX: function (pointerId) { - pointerId = pointerId || 0; return this._pointerData[pointerId].x; - }, /** - * The y coordinate of the Input pointer, relative to the top-left of the parent Sprite - * This value is only set when the pointer is over this Sprite. - * - * @method Phaser.InputHandler#pointerY - * @param {integer} [pointerId=0] - * @return {number} The y coordinate of the Input pointer. - */ + * The y coordinate of the Input pointer, relative to the top-left of the parent Sprite + * This value is only set when the pointer is over this Sprite. + * + * @method Phaser.InputHandler#pointerY + * @param {integer} [pointerId=0] + * @return {number} The y coordinate of the Input pointer. + */ pointerY: function (pointerId) { - pointerId = pointerId || 0; return this._pointerData[pointerId].y; - }, /** - * If the Pointer is down this returns true. - * This *only* checks if the Pointer is down, not if it's down over any specific Sprite. - * - * @method Phaser.InputHandler#pointerDown - * @param {integer} [pointerId=0] - * @return {boolean} - True if the given pointer is down, otherwise false. - */ + * If the Pointer is down this returns true. + * This *only* checks if the Pointer is down, not if it's down over any specific Sprite. + * + * @method Phaser.InputHandler#pointerDown + * @param {integer} [pointerId=0] + * @return {boolean} - True if the given pointer is down, otherwise false. + */ pointerDown: function (pointerId) { - pointerId = pointerId || 0; return this._pointerData[pointerId].isDown; - }, /** - * If the Pointer is up this returns true. - * This *only* checks if the Pointer is up, not if it's up over any specific Sprite. - * - * @method Phaser.InputHandler#pointerUp - * @param {integer} [pointerId=0] - * @return {boolean} - True if the given pointer is up, otherwise false. - */ + * If the Pointer is up this returns true. + * This *only* checks if the Pointer is up, not if it's up over any specific Sprite. + * + * @method Phaser.InputHandler#pointerUp + * @param {integer} [pointerId=0] + * @return {boolean} - True if the given pointer is up, otherwise false. + */ pointerUp: function (pointerId) { - pointerId = pointerId || 0; return this._pointerData[pointerId].isUp; - }, /** - * A timestamp representing when the Pointer first touched the touchscreen. - * - * @method Phaser.InputHandler#pointerTimeDown - * @param {integer} [pointerId=(check all)] - * @return {number} - */ + * A timestamp representing when the Pointer first touched the touchscreen. + * + * @method Phaser.InputHandler#pointerTimeDown + * @param {integer} [pointerId=(check all)] + * @return {number} + */ pointerTimeDown: function (pointerId) { - pointerId = pointerId || 0; return this._pointerData[pointerId].timeDown; - }, /** - * A timestamp representing when the Pointer left the touchscreen. - * - * @method Phaser.InputHandler#pointerTimeUp - * @param {integer} [pointerId=0] - * @return {number} - */ + * A timestamp representing when the Pointer left the touchscreen. + * + * @method Phaser.InputHandler#pointerTimeUp + * @param {integer} [pointerId=0] + * @return {number} + */ pointerTimeUp: function (pointerId) { - pointerId = pointerId || 0; return this._pointerData[pointerId].timeUp; - }, /** - * Is the Pointer over this Sprite? - * - * @method Phaser.InputHandler#pointerOver - * @param {integer} [pointerId=(check all)] The ID number of a Pointer to check. If you don't provide a number it will check all Pointers. - * @return {boolean} - True if the given pointer (if a index was given, or any pointer if not) is over this object. - */ + * Is the Pointer over this Sprite? + * + * @method Phaser.InputHandler#pointerOver + * @param {integer} [pointerId=(check all)] The ID number of a Pointer to check. If you don't provide a number it will check all Pointers. + * @return {boolean} - True if the given pointer (if a index was given, or any pointer if not) is over this object. + */ pointerOver: function (pointerId) { - if (!this.enabled) { return false; @@ -644,19 +613,17 @@ Phaser.InputHandler.prototype = { { return this._pointerData[pointerId].isOver; } - }, /** - * Is the Pointer outside of this Sprite? - * - * @method Phaser.InputHandler#pointerOut - * @param {integer} [pointerId=(check all)] The ID number of a Pointer to check. If you don't provide a number it will check all Pointers. - * @return {boolean} True if the given pointer (if a index was given, or any pointer if not) is out of this object. - */ + * Is the Pointer outside of this Sprite? + * + * @method Phaser.InputHandler#pointerOut + * @param {integer} [pointerId=(check all)] The ID number of a Pointer to check. If you don't provide a number it will check all Pointers. + * @return {boolean} True if the given pointer (if a index was given, or any pointer if not) is out of this object. + */ pointerOut: function (pointerId) { - if (!this.enabled) { return false; @@ -676,69 +643,61 @@ Phaser.InputHandler.prototype = { { return this._pointerData[pointerId].isOut; } - }, /** - * A timestamp representing when the Pointer first touched the touchscreen. - * - * @method Phaser.InputHandler#pointerTimeOver - * @param {integer} [pointerId=0] - * @return {number} - */ + * A timestamp representing when the Pointer first touched the touchscreen. + * + * @method Phaser.InputHandler#pointerTimeOver + * @param {integer} [pointerId=0] + * @return {number} + */ pointerTimeOver: function (pointerId) { - pointerId = pointerId || 0; return this._pointerData[pointerId].timeOver; - }, /** - * A timestamp representing when the Pointer left the touchscreen. - * - * @method Phaser.InputHandler#pointerTimeOut - * @param {integer} [pointerId=0] - * @return {number} - */ + * A timestamp representing when the Pointer left the touchscreen. + * + * @method Phaser.InputHandler#pointerTimeOut + * @param {integer} [pointerId=0] + * @return {number} + */ pointerTimeOut: function (pointerId) { - pointerId = pointerId || 0; return this._pointerData[pointerId].timeOut; - }, /** - * Is this sprite being dragged by the mouse or not? - * - * @method Phaser.InputHandler#pointerDragged - * @param {integer} [pointerId=0] - * @return {boolean} True if the pointer is dragging an object, otherwise false. - */ + * Is this sprite being dragged by the mouse or not? + * + * @method Phaser.InputHandler#pointerDragged + * @param {integer} [pointerId=0] + * @return {boolean} True if the pointer is dragging an object, otherwise false. + */ pointerDragged: function (pointerId) { - pointerId = pointerId || 0; return this._pointerData[pointerId].isDragged; - }, /** - * Checks if the given pointer is both down and over the Sprite this InputHandler belongs to. - * Use the `fastTest` flag is to quickly check just the bounding hit area even if `InputHandler.pixelPerfectOver` is `true`. - * - * @method Phaser.InputHandler#checkPointerDown - * @param {Phaser.Pointer} pointer - * @param {boolean} [fastTest=false] - Force a simple hit area check even if `pixelPerfectOver` is true for this object? - * @return {boolean} True if the pointer is down, otherwise false. - */ + * Checks if the given pointer is both down and over the Sprite this InputHandler belongs to. + * Use the `fastTest` flag is to quickly check just the bounding hit area even if `InputHandler.pixelPerfectOver` is `true`. + * + * @method Phaser.InputHandler#checkPointerDown + * @param {Phaser.Pointer} pointer + * @param {boolean} [fastTest=false] - Force a simple hit area check even if `pixelPerfectOver` is true for this object? + * @return {boolean} True if the pointer is down, otherwise false. + */ checkPointerDown: function (pointer, fastTest) { - if (!pointer.isDown || !this.enabled || !this.sprite || @@ -770,21 +729,19 @@ Phaser.InputHandler.prototype = { } return false; - }, /** - * Checks if the given pointer is over the Sprite this InputHandler belongs to. - * Use the `fastTest` flag is to quickly check just the bounding hit area even if `InputHandler.pixelPerfectOver` is `true`. - * - * @method Phaser.InputHandler#checkPointerOver - * @param {Phaser.Pointer} pointer - * @param {boolean} [fastTest=false] - Force a simple hit area check even if `pixelPerfectOver` is true for this object? - * @return {boolean} - */ + * Checks if the given pointer is over the Sprite this InputHandler belongs to. + * Use the `fastTest` flag is to quickly check just the bounding hit area even if `InputHandler.pixelPerfectOver` is `true`. + * + * @method Phaser.InputHandler#checkPointerOver + * @param {Phaser.Pointer} pointer + * @param {boolean} [fastTest=false] - Force a simple hit area check even if `pixelPerfectOver` is true for this object? + * @return {boolean} + */ checkPointerOver: function (pointer, fastTest) { - if (!this.enabled || !this.sprite || !this.sprite.parent || @@ -815,22 +772,20 @@ Phaser.InputHandler.prototype = { } return false; - }, /** - * Runs a pixel perfect check against the given x/y coordinates of the Sprite this InputHandler is bound to. - * It compares the alpha value of the pixel and if >= InputHandler.pixelPerfectAlpha it returns true. - * - * @method Phaser.InputHandler#checkPixel - * @param {number} x - The x coordinate to check. - * @param {number} y - The y coordinate to check. - * @param {Phaser.Pointer} [pointer] - The pointer to get the x/y coordinate from if not passed as the first two parameters. - * @return {boolean} true if there is the alpha of the pixel is >= InputHandler.pixelPerfectAlpha - */ + * Runs a pixel perfect check against the given x/y coordinates of the Sprite this InputHandler is bound to. + * It compares the alpha value of the pixel and if >= InputHandler.pixelPerfectAlpha it returns true. + * + * @method Phaser.InputHandler#checkPixel + * @param {number} x - The x coordinate to check. + * @param {number} y - The y coordinate to check. + * @param {Phaser.Pointer} [pointer] - The pointer to get the x/y coordinate from if not passed as the first two parameters. + * @return {boolean} true if there is the alpha of the pixel is >= InputHandler.pixelPerfectAlpha + */ checkPixel: function (x, y, pointer) { - // Grab a pixel from our image into the hitCanvas and then test it if (this.sprite.texture.baseTexture.source) { @@ -885,21 +840,19 @@ Phaser.InputHandler.prototype = { } return false; - }, /** - * Internal Update method. This is called automatically and handles the Pointer - * and drag update loops. - * - * @method Phaser.InputHandler#update - * @protected - * @param {Phaser.Pointer} pointer - * @return {boolean} True if the pointer is still active, otherwise false. - */ + * Internal Update method. This is called automatically and handles the Pointer + * and drag update loops. + * + * @method Phaser.InputHandler#update + * @protected + * @param {Phaser.Pointer} pointer + * @return {boolean} True if the pointer is still active, otherwise false. + */ update: function (pointer) { - if (this.sprite === null || this.sprite.parent === undefined) { // Abort. We've been destroyed. @@ -947,16 +900,15 @@ Phaser.InputHandler.prototype = { }, /** - * Internal method handling the pointer over event. - * - * @method Phaser.InputHandler#_pointerOverHandler - * @private - * @param {Phaser.Pointer} pointer - The pointer that triggered the event - * @param {boolean} [silent=false] - If silent is `true` then this method will not dispatch any Signals from the parent Sprite. - */ + * Internal method handling the pointer over event. + * + * @method Phaser.InputHandler#_pointerOverHandler + * @private + * @param {Phaser.Pointer} pointer - The pointer that triggered the event + * @param {boolean} [silent=false] - If silent is `true` then this method will not dispatch any Signals from the parent Sprite. + */ _pointerOverHandler: function (pointer, silent) { - if (this.sprite === null) { // Abort. We've been destroyed. @@ -991,20 +943,18 @@ Phaser.InputHandler.prototype = { this.sprite.parent.onChildInputOver.dispatch(this.sprite, pointer); } } - }, /** - * Internal method handling the pointer out event. - * - * @method Phaser.InputHandler#_pointerOutHandler - * @private - * @param {Phaser.Pointer} pointer - The pointer that triggered the event. - * @param {boolean} [silent=false] - If silent is `true` then this method will not dispatch any Signals from the parent Sprite. - */ + * Internal method handling the pointer out event. + * + * @method Phaser.InputHandler#_pointerOutHandler + * @private + * @param {Phaser.Pointer} pointer - The pointer that triggered the event. + * @param {boolean} [silent=false] - If silent is `true` then this method will not dispatch any Signals from the parent Sprite. + */ _pointerOutHandler: function (pointer, silent) { - if (this.sprite === null) { // Abort. We've been destroyed. @@ -1032,19 +982,17 @@ Phaser.InputHandler.prototype = { this.sprite.parent.onChildInputOut.dispatch(this.sprite, pointer); } } - }, /** - * Internal method handling the touched / clicked event. - * - * @method Phaser.InputHandler#_touchedHandler - * @private - * @param {Phaser.Pointer} pointer - The pointer that triggered the event. - */ + * Internal method handling the touched / clicked event. + * + * @method Phaser.InputHandler#_touchedHandler + * @private + * @param {Phaser.Pointer} pointer - The pointer that triggered the event. + */ _touchedHandler: function (pointer) { - if (this.sprite === null) { // Abort. We've been destroyed. @@ -1116,19 +1064,17 @@ Phaser.InputHandler.prototype = { this.sprite.bringToTop(); } } - }, /** - * Internal method handling the drag threshold timer. - * - * @method Phaser.InputHandler#dragTimeElapsed - * @private - * @param {Phaser.Pointer} pointer - */ + * Internal method handling the drag threshold timer. + * + * @method Phaser.InputHandler#dragTimeElapsed + * @private + * @param {Phaser.Pointer} pointer + */ dragTimeElapsed: function (pointer) { - this._dragTimePass = true; if (this._pendingDrag && this.sprite) @@ -1138,18 +1084,16 @@ Phaser.InputHandler.prototype = { this.startDrag(pointer); } } - }, /** - * Internal method handling the pointer released event. - * @method Phaser.InputHandler#_releasedHandler - * @private - * @param {Phaser.Pointer} pointer - */ + * Internal method handling the pointer released event. + * @method Phaser.InputHandler#_releasedHandler + * @private + * @param {Phaser.Pointer} pointer + */ _releasedHandler: function (pointer) { - if (this.sprite === null) { // Abort. We've been destroyed. @@ -1208,21 +1152,19 @@ Phaser.InputHandler.prototype = { this.stopDrag(pointer); } } - }, /** - * Called as a Pointer actively drags this Game Object. - * - * @method Phaser.InputHandler#updateDrag - * @private - * @param {Phaser.Pointer} pointer - The Pointer causing the drag update. - * @param {boolean} fromStart - True if this is the first update, immediately after the drag has started. - * @return {boolean} - */ + * Called as a Pointer actively drags this Game Object. + * + * @method Phaser.InputHandler#updateDrag + * @private + * @param {Phaser.Pointer} pointer - The Pointer causing the drag update. + * @param {boolean} fromStart - True if this is the first update, immediately after the drag has started. + * @return {boolean} + */ updateDrag: function (pointer, fromStart) { - var camera = this.game.camera; var dragOffset = this.dragOffset; var dragPoint = this._dragPoint; @@ -1328,91 +1270,81 @@ Phaser.InputHandler.prototype = { this.sprite.events.onDragUpdate.dispatch(sprite, pointer, px, py, snapPoint, fromStart, dx, dy); return true; - }, /** - * Returns true if the pointer has entered the Sprite within the specified delay time (defaults to 500ms, half a second) - * - * @method Phaser.InputHandler#justOver - * @param {integer} [pointerId=0] - * @param {number} delay - The time below which the pointer is considered as just over. - * @return {boolean} - */ + * Returns true if the pointer has entered the Sprite within the specified delay time (defaults to 500ms, half a second) + * + * @method Phaser.InputHandler#justOver + * @param {integer} [pointerId=0] + * @param {number} delay - The time below which the pointer is considered as just over. + * @return {boolean} + */ justOver: function (pointerId, delay) { - pointerId = pointerId || 0; delay = delay || 500; return (this._pointerData[pointerId].isOver && this.overDuration(pointerId) < delay); - }, /** - * Returns true if the pointer has left the Sprite within the specified delay time (defaults to 500ms, half a second) - * - * @method Phaser.InputHandler#justOut - * @param {integer} [pointerId=0] - * @param {number} delay - The time below which the pointer is considered as just out. - * @return {boolean} - */ + * Returns true if the pointer has left the Sprite within the specified delay time (defaults to 500ms, half a second) + * + * @method Phaser.InputHandler#justOut + * @param {integer} [pointerId=0] + * @param {number} delay - The time below which the pointer is considered as just out. + * @return {boolean} + */ justOut: function (pointerId, delay) { - pointerId = pointerId || 0; delay = delay || 500; return (this._pointerData[pointerId].isOut && (this.game.time.time - this._pointerData[pointerId].timeOut < delay)); - }, /** - * Returns true if the pointer has touched or clicked on the Sprite within the specified delay time (defaults to 500ms, half a second) - * - * @method Phaser.InputHandler#justPressed - * @param {integer} [pointerId=0] - * @param {number} delay - The time below which the pointer is considered as just over. - * @return {boolean} - */ + * Returns true if the pointer has touched or clicked on the Sprite within the specified delay time (defaults to 500ms, half a second) + * + * @method Phaser.InputHandler#justPressed + * @param {integer} [pointerId=0] + * @param {number} delay - The time below which the pointer is considered as just over. + * @return {boolean} + */ justPressed: function (pointerId, delay) { - pointerId = pointerId || 0; delay = delay || 500; return (this._pointerData[pointerId].isDown && this.downDuration(pointerId) < delay); - }, /** - * Returns true if the pointer was touching this Sprite, but has been released within the specified delay time (defaults to 500ms, half a second) - * - * @method Phaser.InputHandler#justReleased - * @param {integer} [pointerId=0] - * @param {number} delay - The time below which the pointer is considered as just out. - * @return {boolean} - */ + * Returns true if the pointer was touching this Sprite, but has been released within the specified delay time (defaults to 500ms, half a second) + * + * @method Phaser.InputHandler#justReleased + * @param {integer} [pointerId=0] + * @param {number} delay - The time below which the pointer is considered as just out. + * @return {boolean} + */ justReleased: function (pointerId, delay) { - pointerId = pointerId || 0; delay = delay || 500; return (this._pointerData[pointerId].isUp && (this.game.time.time - this._pointerData[pointerId].timeUp < delay)); - }, /** - * If the pointer is currently over this Sprite this returns how long it has been there for in milliseconds. - * - * @method Phaser.InputHandler#overDuration - * @param {integer} [pointerId=0] - * @return {number} The number of milliseconds the pointer has been over the Sprite, or -1 if not over. - */ + * If the pointer is currently over this Sprite this returns how long it has been there for in milliseconds. + * + * @method Phaser.InputHandler#overDuration + * @param {integer} [pointerId=0] + * @return {number} The number of milliseconds the pointer has been over the Sprite, or -1 if not over. + */ overDuration: function (pointerId) { - pointerId = pointerId || 0; if (this._pointerData[pointerId].isOver) @@ -1421,19 +1353,17 @@ Phaser.InputHandler.prototype = { } return -1; - }, /** - * If the pointer is currently over this Sprite this returns how long it has been there for in milliseconds. - * - * @method Phaser.InputHandler#downDuration - * @param {integer} [pointerId=0] - * @return {number} The number of milliseconds the pointer has been pressed down on the Sprite, or -1 if not over. - */ + * If the pointer is currently over this Sprite this returns how long it has been there for in milliseconds. + * + * @method Phaser.InputHandler#downDuration + * @param {integer} [pointerId=0] + * @return {number} The number of milliseconds the pointer has been pressed down on the Sprite, or -1 if not over. + */ downDuration: function (pointerId) { - pointerId = pointerId || 0; if (this._pointerData[pointerId].isDown) @@ -1442,40 +1372,38 @@ Phaser.InputHandler.prototype = { } return -1; - }, /** - * Allow this Sprite to be dragged by any valid pointer. - * - * When the drag begins the Sprite.events.onDragStart event will be dispatched. - * - * When the drag completes by way of the user letting go of the pointer that was dragging the sprite, the Sprite.events.onDragStop event is dispatched. - * - * You can control the thresholds over when a drag starts via the properties: - * - * `Pointer.dragDistanceThreshold` the distance, in pixels, that the pointer has to move - * before the drag will start. - * - * `Pointer.dragTimeThreshold` the time, in ms, that the pointer must be held down on - * the Sprite before the drag will start. - * - * You can set either (or both) of these properties after enabling a Sprite for drag. - * - * For the duration of the drag the Sprite.events.onDragUpdate event is dispatched. This event is only dispatched when the pointer actually - * changes position and moves. The event sends 8 parameters: `sprite`, `pointer`, `dragX`, `dragY`, `snapPoint`, `fromStart`, `deltaX`, and `deltaY`. - * - * @method Phaser.InputHandler#enableDrag - * @param {boolean} [lockCenter=false] - If false the Sprite will drag from where you click it minus the dragOffset. If true it will center itself to the tip of the mouse pointer. - * @param {boolean} [bringToTop=false] - If true the Sprite will be bought to the top of the rendering list in its current Group. - * @param {boolean} [pixelPerfect=false] - If true it will use a pixel perfect test to see if you clicked the Sprite. False uses the bounding box. - * @param {integer} [alphaThreshold=255] - If using pixel perfect collision this specifies the alpha level from 0 to 255 above which a collision is processed. - * @param {Phaser.Rectangle} [boundsRect=null] - If you want to restrict the drag of this sprite to a specific Rectangle, pass the Phaser.Rectangle here, otherwise it's free to drag anywhere. - * @param {Phaser.Sprite} [boundsSprite=null] - If you want to restrict the drag of this sprite to within the bounding box of another sprite, pass it here. - */ + * Allow this Sprite to be dragged by any valid pointer. + * + * When the drag begins the Sprite.events.onDragStart event will be dispatched. + * + * When the drag completes by way of the user letting go of the pointer that was dragging the sprite, the Sprite.events.onDragStop event is dispatched. + * + * You can control the thresholds over when a drag starts via the properties: + * + * `Pointer.dragDistanceThreshold` the distance, in pixels, that the pointer has to move + * before the drag will start. + * + * `Pointer.dragTimeThreshold` the time, in ms, that the pointer must be held down on + * the Sprite before the drag will start. + * + * You can set either (or both) of these properties after enabling a Sprite for drag. + * + * For the duration of the drag the Sprite.events.onDragUpdate event is dispatched. This event is only dispatched when the pointer actually + * changes position and moves. The event sends 8 parameters: `sprite`, `pointer`, `dragX`, `dragY`, `snapPoint`, `fromStart`, `deltaX`, and `deltaY`. + * + * @method Phaser.InputHandler#enableDrag + * @param {boolean} [lockCenter=false] - If false the Sprite will drag from where you click it minus the dragOffset. If true it will center itself to the tip of the mouse pointer. + * @param {boolean} [bringToTop=false] - If true the Sprite will be bought to the top of the rendering list in its current Group. + * @param {boolean} [pixelPerfect=false] - If true it will use a pixel perfect test to see if you clicked the Sprite. False uses the bounding box. + * @param {integer} [alphaThreshold=255] - If using pixel perfect collision this specifies the alpha level from 0 to 255 above which a collision is processed. + * @param {Phaser.Rectangle} [boundsRect=null] - If you want to restrict the drag of this sprite to a specific Rectangle, pass the Phaser.Rectangle here, otherwise it's free to drag anywhere. + * @param {Phaser.Sprite} [boundsSprite=null] - If you want to restrict the drag of this sprite to within the bounding box of another sprite, pass it here. + */ enableDrag: function (lockCenter, bringToTop, pixelPerfect, alphaThreshold, boundsRect, boundsSprite) { - if (lockCenter === undefined) { lockCenter = false; } if (bringToTop === undefined) { bringToTop = false; } if (pixelPerfect === undefined) { pixelPerfect = false; } @@ -1501,18 +1429,16 @@ Phaser.InputHandler.prototype = { { this.boundsSprite = boundsSprite; } - }, /** - * Stops this sprite from being able to be dragged. - * If it is currently the target of an active drag it will be stopped immediately; also disables any set callbacks. - * - * @method Phaser.InputHandler#disableDrag - */ + * Stops this sprite from being able to be dragged. + * If it is currently the target of an active drag it will be stopped immediately; also disables any set callbacks. + * + * @method Phaser.InputHandler#disableDrag + */ disableDrag: function () { - if (this._pointerData) { for (var i = 0; i < 10; i++) @@ -1525,18 +1451,16 @@ Phaser.InputHandler.prototype = { this.isDragged = false; this._draggedPointerID = -1; this._pendingDrag = false; - }, /** - * Called by Pointer when drag starts on this Sprite. Should not usually be called directly. - * - * @method Phaser.InputHandler#startDrag - * @param {Phaser.Pointer} pointer - */ + * Called by Pointer when drag starts on this Sprite. Should not usually be called directly. + * + * @method Phaser.InputHandler#startDrag + * @param {Phaser.Pointer} pointer + */ startDrag: function (pointer) { - var x = this.sprite.x; var y = this.sprite.y; var pointerLocalCoord = this.globalToLocal(pointer); @@ -1589,18 +1513,16 @@ Phaser.InputHandler.prototype = { this.sprite.events.onDragStart$dispatch(this.sprite, pointer, x, y); this._pendingDrag = false; - }, /** - * Warning: EXPERIMENTAL - * - * @method Phaser.InputHandler#globalToLocalX - * @param {number} x - */ + * Warning: EXPERIMENTAL + * + * @method Phaser.InputHandler#globalToLocalX + * @param {number} x + */ globalToLocalX: function (x) { - if (this.scaleLayer) { x -= this.game.scale.grid.boundsFluid.x; @@ -1608,18 +1530,16 @@ Phaser.InputHandler.prototype = { } return x; - }, /** - * Warning: EXPERIMENTAL - * - * @method Phaser.InputHandler#globalToLocalY - * @param {number} y - */ + * Warning: EXPERIMENTAL + * + * @method Phaser.InputHandler#globalToLocalY + * @param {number} y + */ globalToLocalY: function (y) { - if (this.scaleLayer) { y -= this.game.scale.grid.boundsFluid.y; @@ -1627,19 +1547,17 @@ Phaser.InputHandler.prototype = { } return y; - }, /** - * Convert global coordinates to local sprite coordinates - * - * @method Phaser.InputHandler#globalToLocal - * @param {Phaser.Point} globalCoord - The global coordinates to convert. - * @return {Phaser.Point} A point containing the local coordinates. - */ + * Convert global coordinates to local sprite coordinates + * + * @method Phaser.InputHandler#globalToLocal + * @param {Phaser.Point} globalCoord - The global coordinates to convert. + * @return {Phaser.Point} A point containing the local coordinates. + */ globalToLocal: function (globalCoord) { - if (this.sprite.parent) { return this.game.input.getLocalPosition(this.sprite.parent, {x: globalCoord.x, y: globalCoord.y}); @@ -1648,18 +1566,16 @@ Phaser.InputHandler.prototype = { { return globalCoord; } - }, /** - * Called by Pointer when drag is stopped on this Sprite. Should not usually be called directly. - * - * @method Phaser.InputHandler#stopDrag - * @param {Phaser.Pointer} pointer - */ + * Called by Pointer when drag is stopped on this Sprite. Should not usually be called directly. + * + * @method Phaser.InputHandler#stopDrag + * @param {Phaser.Pointer} pointer + */ stopDrag: function (pointer) { - this.isDragged = false; this._draggedPointerID = -1; this._pointerData[pointer.id].isDragged = false; @@ -1686,42 +1602,38 @@ Phaser.InputHandler.prototype = { { this._pointerOutHandler(pointer); } - }, /** - * Restricts this sprite to drag movement only on the given axis. Note: If both are set to false the sprite will never move! - * - * @method Phaser.InputHandler#setDragLock - * @param {boolean} [allowHorizontal=true] - To enable the sprite to be dragged horizontally set to true, otherwise false. - * @param {boolean} [allowVertical=true] - To enable the sprite to be dragged vertically set to true, otherwise false. - */ + * Restricts this sprite to drag movement only on the given axis. Note: If both are set to false the sprite will never move! + * + * @method Phaser.InputHandler#setDragLock + * @param {boolean} [allowHorizontal=true] - To enable the sprite to be dragged horizontally set to true, otherwise false. + * @param {boolean} [allowVertical=true] - To enable the sprite to be dragged vertically set to true, otherwise false. + */ setDragLock: function (allowHorizontal, allowVertical) { - if (allowHorizontal === undefined) { allowHorizontal = true; } if (allowVertical === undefined) { allowVertical = true; } this.allowHorizontalDrag = allowHorizontal; this.allowVerticalDrag = allowVertical; - }, /** - * Make this Sprite snap to the given grid either during drag or when it's released. - * For example 16x16 as the snapX and snapY would make the sprite snap to every 16 pixels. - * - * @method Phaser.InputHandler#enableSnap - * @param {number} snapX - The width of the grid cell to snap to. - * @param {number} snapY - The height of the grid cell to snap to. - * @param {boolean} [onDrag=true] - If true the sprite will snap to the grid while being dragged. - * @param {boolean} [onRelease=false] - If true the sprite will snap to the grid when released. - * @param {number} [snapOffsetX=0] - Used to offset the top-left starting point of the snap grid. - * @param {number} [snapOffsetY=0] - Used to offset the top-left starting point of the snap grid. - */ + * Make this Sprite snap to the given grid either during drag or when it's released. + * For example 16x16 as the snapX and snapY would make the sprite snap to every 16 pixels. + * + * @method Phaser.InputHandler#enableSnap + * @param {number} snapX - The width of the grid cell to snap to. + * @param {number} snapY - The height of the grid cell to snap to. + * @param {boolean} [onDrag=true] - If true the sprite will snap to the grid while being dragged. + * @param {boolean} [onRelease=false] - If true the sprite will snap to the grid when released. + * @param {number} [snapOffsetX=0] - Used to offset the top-left starting point of the snap grid. + * @param {number} [snapOffsetY=0] - Used to offset the top-left starting point of the snap grid. + */ enableSnap: function (snapX, snapY, onDrag, onRelease, snapOffsetX, snapOffsetY) { - if (onDrag === undefined) { onDrag = true; } if (onRelease === undefined) { onRelease = false; } if (snapOffsetX === undefined) { snapOffsetX = 0; } @@ -1733,30 +1645,26 @@ Phaser.InputHandler.prototype = { this.snapOffsetY = snapOffsetY; this.snapOnDrag = onDrag; this.snapOnRelease = onRelease; - }, /** - * Stops the sprite from snapping to a grid during drag or release. - * - * @method Phaser.InputHandler#disableSnap - */ + * Stops the sprite from snapping to a grid during drag or release. + * + * @method Phaser.InputHandler#disableSnap + */ disableSnap: function () { - this.snapOnDrag = false; this.snapOnRelease = false; - }, /** - * Bounds Rect check for the sprite drag - * - * @method Phaser.InputHandler#checkBoundsRect - */ + * Bounds Rect check for the sprite drag + * + * @method Phaser.InputHandler#checkBoundsRect + */ checkBoundsRect: function () { - if (this.sprite.fixedToCamera) { if (this.sprite.cameraOffset.x < this.boundsRect.left) @@ -1797,17 +1705,15 @@ Phaser.InputHandler.prototype = { this.sprite.y = this.boundsRect.bottom - (this.sprite.height - this.sprite.offsetY); } } - }, /** - * Parent Sprite Bounds check for the sprite drag. - * - * @method Phaser.InputHandler#checkBoundsSprite - */ + * Parent Sprite Bounds check for the sprite drag. + * + * @method Phaser.InputHandler#checkBoundsSprite + */ checkBoundsSprite: function () { - if (this.sprite.fixedToCamera && this.boundsSprite.fixedToCamera) { if (this.sprite.cameraOffset.x < this.boundsSprite.cameraOffset.x) @@ -1848,7 +1754,6 @@ Phaser.InputHandler.prototype = { this.sprite.y = this.boundsSprite.bottom - (this.sprite.height - this.sprite.offsetY); } } - } }; diff --git a/src/input/Key.js b/src/input/Key.js index 9b18cb8b4..e3f4c9a48 100644 --- a/src/input/Key.js +++ b/src/input/Key.js @@ -1,124 +1,123 @@ /** -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* If you need more fine-grained control over the handling of specific keys you can create and use Phaser.Key objects. -* -* @class Phaser.Key -* @constructor -* @param {Phaser.Game} game - Current game instance. -* @param {integer} keycode - The key code this Key is responsible for. See {@link Phaser.KeyCode}. -*/ + * If you need more fine-grained control over the handling of specific keys you can create and use Phaser.Key objects. + * + * @class Phaser.Key + * @constructor + * @param {Phaser.Game} game - Current game instance. + * @param {integer} keycode - The key code this Key is responsible for. See {@link Phaser.KeyCode}. + */ Phaser.Key = function (game, keycode) { - /** - * @property {Phaser.Game} game - A reference to the currently running game. - */ + * @property {Phaser.Game} game - A reference to the currently running game. + */ this.game = game; /** - * The enabled state of the key - see `enabled`. - * @property {boolean} _enabled - * @private - */ + * The enabled state of the key - see `enabled`. + * @property {boolean} _enabled + * @private + */ this._enabled = true; /** - * @property {object} event - Stores the most recent DOM event. - * @readonly - */ + * @property {object} event - Stores the most recent DOM event. + * @readonly + */ this.event = null; /** - * @property {boolean} isDown - The "down" state of the key. This will remain `true` for as long as the keyboard thinks this key is held down. - * @default - */ + * @property {boolean} isDown - The "down" state of the key. This will remain `true` for as long as the keyboard thinks this key is held down. + * @default + */ this.isDown = false; /** - * @property {boolean} isUp - The "up" state of the key. This will remain `true` for as long as the keyboard thinks this key is up. - * @default - */ + * @property {boolean} isUp - The "up" state of the key. This will remain `true` for as long as the keyboard thinks this key is up. + * @default + */ this.isUp = true; /** - * @property {boolean} altKey - The down state of the ALT key, if pressed at the same time as this key. - * @default - */ + * @property {boolean} altKey - The down state of the ALT key, if pressed at the same time as this key. + * @default + */ this.altKey = false; /** - * @property {boolean} ctrlKey - The down state of the CTRL key, if pressed at the same time as this key. - * @default - */ + * @property {boolean} ctrlKey - The down state of the CTRL key, if pressed at the same time as this key. + * @default + */ this.ctrlKey = false; /** - * @property {boolean} shiftKey - The down state of the SHIFT key, if pressed at the same time as this key. - * @default - */ + * @property {boolean} shiftKey - The down state of the SHIFT key, if pressed at the same time as this key. + * @default + */ this.shiftKey = false; /** - * @property {number} timeDown - The timestamp when the key was last pressed down. This is based on Game.time.now. - */ + * @property {number} timeDown - The timestamp when the key was last pressed down. This is based on Game.time.now. + */ this.timeDown = 0; /** - * If the key is down this value holds the duration of that key press and is constantly updated. - * If the key is up it holds the duration of the previous down session. - * @property {number} duration - The number of milliseconds this key has been held down for. - * @default - */ + * If the key is down this value holds the duration of that key press and is constantly updated. + * If the key is up it holds the duration of the previous down session. + * @property {number} duration - The number of milliseconds this key has been held down for. + * @default + */ this.duration = 0; /** - * @property {number} timeUp - The timestamp when the key was last released. This is based on Game.time.now. - * @default - */ + * @property {number} timeUp - The timestamp when the key was last released. This is based on Game.time.now. + * @default + */ this.timeUp = -2500; /** - * If the key is up this value holds the duration of that key release and is constantly updated. - * If the key is down it holds the duration of the previous up session. - * @property {number} duration - The number of milliseconds this key has been up for. - * @default - */ + * If the key is up this value holds the duration of that key release and is constantly updated. + * If the key is down it holds the duration of the previous up session. + * @property {number} duration - The number of milliseconds this key has been up for. + * @default + */ this.durationUp = -2500; /** - * @property {number} repeats - If a key is held down this holds down the number of times the key has 'repeated'. - * @default - */ + * @property {number} repeats - If a key is held down this holds down the number of times the key has 'repeated'. + * @default + */ this.repeats = 0; /** - * @property {number} keyCode - The keycode of this key. - */ + * @property {number} keyCode - The keycode of this key. + */ this.keyCode = keycode; /** - * @property {Phaser.Signal} onDown - This Signal is dispatched every time this Key is pressed down. It is only dispatched once (until the key is released again). - */ + * @property {Phaser.Signal} onDown - This Signal is dispatched every time this Key is pressed down. It is only dispatched once (until the key is released again). + */ this.onDown = new Phaser.Signal(); /** - * @property {function} onHoldCallback - A callback that is called while this Key is held down. Warning: Depending on refresh rate that could be 60+ times per second. - */ + * @property {function} onHoldCallback - A callback that is called while this Key is held down. Warning: Depending on refresh rate that could be 60+ times per second. + */ this.onHoldCallback = null; /** - * @property {object} onHoldContext - The context under which the onHoldCallback will be called. - */ + * @property {object} onHoldContext - The context under which the onHoldCallback will be called. + */ this.onHoldContext = null; /** - * @property {Phaser.Signal} onUp - This Signal is dispatched every time this Key is released. It is only dispatched once (until the key is pressed and released again). - */ + * @property {Phaser.Signal} onUp - This Signal is dispatched every time this Key is released. It is only dispatched once (until the key is pressed and released again). + */ this.onUp = new Phaser.Signal(); /** @@ -132,20 +131,18 @@ Phaser.Key = function (game, keycode) * @private */ this._justUp = false; - }; Phaser.Key.prototype = { /** - * Called automatically by Phaser.Keyboard. - * - * @method Phaser.Key#update - * @protected - */ + * Called automatically by Phaser.Keyboard. + * + * @method Phaser.Key#update + * @protected + */ update: function () { - if (!this._enabled) { return; } if (this.isDown) @@ -162,19 +159,17 @@ Phaser.Key.prototype = { { this.durationUp = this.game.time.time - this.timeUp; } - }, /** - * Called automatically by Phaser.Keyboard. - * - * @method Phaser.Key#processKeyDown - * @param {KeyboardEvent} event - The DOM event that triggered this. - * @protected - */ + * Called automatically by Phaser.Keyboard. + * + * @method Phaser.Key#processKeyDown + * @param {KeyboardEvent} event - The DOM event that triggered this. + * @protected + */ processKeyDown: function (event) { - if (!this._enabled) { return; } this.event = event; @@ -196,24 +191,24 @@ Phaser.Key.prototype = { this.durationUp = this.game.time.time - this.timeUp; this.repeats = 0; - // _justDown will remain true until it is read via the justDown Getter - // this enables the game to poll for past presses, or reset it at the start of a new game state + /* + * _justDown will remain true until it is read via the justDown Getter + * this enables the game to poll for past presses, or reset it at the start of a new game state + */ this._justDown = true; this.onDown.dispatch(this); - }, /** - * Called automatically by Phaser.Keyboard. - * - * @method Phaser.Key#processKeyUp - * @param {KeyboardEvent} event - The DOM event that triggered this. - * @protected - */ + * Called automatically by Phaser.Keyboard. + * + * @method Phaser.Key#processKeyUp + * @param {KeyboardEvent} event - The DOM event that triggered this. + * @protected + */ processKeyUp: function (event) { - if (!this._enabled) { return; } this.event = event; @@ -229,26 +224,26 @@ Phaser.Key.prototype = { this.duration = this.game.time.time - this.timeDown; this.durationUp = 0; - // _justUp will remain true until it is read via the justUp Getter - // this enables the game to poll for past presses, or reset it at the start of a new game state + /* + * _justUp will remain true until it is read via the justUp Getter + * this enables the game to poll for past presses, or reset it at the start of a new game state + */ this._justUp = true; this.onUp.dispatch(this); - }, /** - * Resets the state of this Key. - * - * This sets isDown to false, isUp to true, resets the time to be the current time, and _enables_ the key. - * In addition, if it is a "hard reset", it clears clears any callbacks associated with the onDown and onUp events and removes the onHoldCallback. - * - * @method Phaser.Key#reset - * @param {boolean} [hard=true] - A soft reset won't reset any events or callbacks; a hard reset will. - */ + * Resets the state of this Key. + * + * This sets isDown to false, isUp to true, resets the time to be the current time, and _enables_ the key. + * In addition, if it is a "hard reset", it clears clears any callbacks associated with the onDown and onUp events and removes the onHoldCallback. + * + * @method Phaser.Key#reset + * @param {boolean} [hard=true] - A soft reset won't reset any events or callbacks; a hard reset will. + */ reset: function (hard) { - if (hard === undefined) { hard = true; } this.isDown = false; @@ -267,141 +262,125 @@ Phaser.Key.prototype = { this.onHoldCallback = null; this.onHoldContext = null; } - }, /** - * Returns `true` if the Key was pressed down within the `duration` value given, or `false` if it either isn't down, - * or was pressed down longer ago than then given duration. - * - * @method Phaser.Key#downDuration - * @param {number} [duration=50] - The duration within which the key is considered as being just pressed. Given in ms. - * @return {boolean} True if the key was pressed down within the given duration. - */ + * Returns `true` if the Key was pressed down within the `duration` value given, or `false` if it either isn't down, + * or was pressed down longer ago than then given duration. + * + * @method Phaser.Key#downDuration + * @param {number} [duration=50] - The duration within which the key is considered as being just pressed. Given in ms. + * @return {boolean} True if the key was pressed down within the given duration. + */ downDuration: function (duration) { - if (duration === undefined) { duration = 50; } return (this.isDown && this.duration < duration); - }, /** - * Returns `true` if the Key has been up *only* within the `duration` value given, or `false` if it either isn't up, - * or was has been up longer than the given duration. - * - * @method Phaser.Key#upDuration - * @param {number} [duration=50] - The duration within which the key is considered as being just released. Given in ms. - * @return {boolean} True if the key was released within the given duration. - */ + * Returns `true` if the Key has been up *only* within the `duration` value given, or `false` if it either isn't up, + * or was has been up longer than the given duration. + * + * @method Phaser.Key#upDuration + * @param {number} [duration=50] - The duration within which the key is considered as being just released. Given in ms. + * @return {boolean} True if the key was released within the given duration. + */ upDuration: function (duration) { - if (duration === undefined) { duration = 50; } return (!this.isDown && ((this.game.time.time - this.timeUp) < duration)); - }, /** - * Returns `true` if the Key was just pressed down this update tick, or `false` if it either isn't down, - * or was pressed down on a previous update tick. - * - * @method Phaser.Key#justPressed - * @return {boolean} True if the key was just pressed down this update tick. - */ + * Returns `true` if the Key was just pressed down this update tick, or `false` if it either isn't down, + * or was pressed down on a previous update tick. + * + * @method Phaser.Key#justPressed + * @return {boolean} True if the key was just pressed down this update tick. + */ justPressed: function () { - return (this.isDown && this.duration === 0); - }, /** - * Returns `true` if the Key was just released this update tick, or `false` if it either isn't up, - * or was released on a previous update tick. - * - * @method Phaser.Key#justReleased - * @return {boolean} True if the key was just released this update tick. - */ + * Returns `true` if the Key was just released this update tick, or `false` if it either isn't up, + * or was released on a previous update tick. + * + * @method Phaser.Key#justReleased + * @return {boolean} True if the key was just released this update tick. + */ justReleased: function () { - return (!this.isDown && this.durationUp === 0); - } }; /** -* The justDown value allows you to test if this Key has just been pressed down or not. -* When you check this value it will return `true` if the Key is down, otherwise `false`. -* You can only call justDown once per key press. It will only return `true` once, until the Key is released and pressed down again. -* This allows you to use it in situations where you want to check if this key is down without using a Signal, such as in a core game loop. -* -* @name Phaser.Key#justDown -* @property {boolean} justDown -* @memberof Phaser.Key -* @default false -*/ + * The justDown value allows you to test if this Key has just been pressed down or not. + * When you check this value it will return `true` if the Key is down, otherwise `false`. + * You can only call justDown once per key press. It will only return `true` once, until the Key is released and pressed down again. + * This allows you to use it in situations where you want to check if this key is down without using a Signal, such as in a core game loop. + * + * @name Phaser.Key#justDown + * @property {boolean} justDown + * @memberof Phaser.Key + * @default false + */ Object.defineProperty(Phaser.Key.prototype, 'justDown', { get: function () { - var current = this._justDown; this._justDown = false; return current; - } }); /** -* The justUp value allows you to test if this Key has just been released or not. -* When you check this value it will return `true` if the Key is up, otherwise `false`. -* You can only call justUp once per key release. It will only return `true` once, until the Key is pressed down and released again. -* This allows you to use it in situations where you want to check if this key is up without using a Signal, such as in a core game loop. -* -* @name Phaser.Key#justUp -* @property {boolean} justUp -* @memberof Phaser.Key -* @default false -*/ + * The justUp value allows you to test if this Key has just been released or not. + * When you check this value it will return `true` if the Key is up, otherwise `false`. + * You can only call justUp once per key release. It will only return `true` once, until the Key is pressed down and released again. + * This allows you to use it in situations where you want to check if this key is up without using a Signal, such as in a core game loop. + * + * @name Phaser.Key#justUp + * @property {boolean} justUp + * @memberof Phaser.Key + * @default false + */ Object.defineProperty(Phaser.Key.prototype, 'justUp', { get: function () { - var current = this._justUp; this._justUp = false; return current; - } }); /** -* An enabled key processes its update and dispatches events. -* A key can be disabled momentarily at runtime instead of deleting it. -* @name Phaser.Key#enabled -* @property {boolean} enabled -* @memberof Phaser.Key -* @default true -*/ + * An enabled key processes its update and dispatches events. + * A key can be disabled momentarily at runtime instead of deleting it. + * @name Phaser.Key#enabled + * @property {boolean} enabled + * @memberof Phaser.Key + * @default true + */ Object.defineProperty(Phaser.Key.prototype, 'enabled', { get: function () { - return this._enabled; - }, set: function (value) { - value = !!value; if (value !== this._enabled) diff --git a/src/input/Keyboard.js b/src/input/Keyboard.js index 91fd6398f..e70658df3 100644 --- a/src/input/Keyboard.js +++ b/src/input/Keyboard.js @@ -1,136 +1,133 @@ /** -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* The Keyboard class monitors keyboard input and dispatches keyboard events. -* -* _Note_: many keyboards are unable to process certain combinations of keys due to hardware limitations known as ghosting. -* See http://www.html5gamedevs.com/topic/4876-impossible-to-use-more-than-2-keyboard-input-buttons-at-the-same-time/ for more details. -* -* Also please be aware that certain browser extensions can disable or override Phaser keyboard handling. -* For example the Chrome extension vimium is known to disable Phaser from using the D key. And there are others. -* So please check your extensions before opening Phaser issues. -* -* @class Phaser.Keyboard -* @constructor -* @param {Phaser.Game} game - A reference to the currently running game. -*/ + * The Keyboard class monitors keyboard input and dispatches keyboard events. + * + * _Note_: many keyboards are unable to process certain combinations of keys due to hardware limitations known as ghosting. + * See http://www.html5gamedevs.com/topic/4876-impossible-to-use-more-than-2-keyboard-input-buttons-at-the-same-time/ for more details. + * + * Also please be aware that certain browser extensions can disable or override Phaser keyboard handling. + * For example the Chrome extension vimium is known to disable Phaser from using the D key. And there are others. + * So please check your extensions before opening Phaser issues. + * + * @class Phaser.Keyboard + * @constructor + * @param {Phaser.Game} game - A reference to the currently running game. + */ Phaser.Keyboard = function (game) { - /** - * @property {Phaser.Game} game - Local reference to game. - */ + * @property {Phaser.Game} game - Local reference to game. + */ this.game = game; /** - * Whether the handler has started. - * @property {boolean} active - * @default - */ + * Whether the handler has started. + * @property {boolean} active + * @default + */ this.active = false; /** - * Keyboard input will only be processed if enabled. - * @property {boolean} enabled - * @default - */ + * Keyboard input will only be processed if enabled. + * @property {boolean} enabled + * @default + */ this.enabled = true; /** - * @property {KeyboardEvent} event - The most recent DOM event from keydown or keyup. This is updated every time a new key is pressed or released. - */ + * @property {KeyboardEvent} event - The most recent DOM event from keydown or keyup. This is updated every time a new key is pressed or released. + */ this.event = null; /** - * @property {object} pressEvent - The most recent DOM event from keypress. - */ + * @property {object} pressEvent - The most recent DOM event from keypress. + */ this.pressEvent = null; /** - * @property {object} callbackContext - The context under which the callbacks are run. - */ + * @property {object} callbackContext - The context under which the callbacks are run. + */ this.callbackContext = this; /** - * @property {function} onDownCallback - This callback is invoked every time a key is pressed down, including key repeats when a key is held down. One argument is passed: {KeyboardEvent} event. - */ + * @property {function} onDownCallback - This callback is invoked every time a key is pressed down, including key repeats when a key is held down. One argument is passed: {KeyboardEvent} event. + */ this.onDownCallback = null; /** - * @property {function} onPressCallback - This callback is invoked every time a DOM onkeypress event is raised, which is only for printable keys. Two arguments are passed: {string} `String.fromCharCode(event.charCode)` and {KeyboardEvent} event. - */ + * @property {function} onPressCallback - This callback is invoked every time a DOM onkeypress event is raised, which is only for printable keys. Two arguments are passed: {string} `String.fromCharCode(event.charCode)` and {KeyboardEvent} event. + */ this.onPressCallback = null; /** - * @property {function} onUpCallback - This callback is invoked every time a key is released. One argument is passed: {KeyboardEvent} event. - */ + * @property {function} onUpCallback - This callback is invoked every time a key is released. One argument is passed: {KeyboardEvent} event. + */ this.onUpCallback = null; /** - * @property {array} _keys - The array the Phaser.Key objects are stored in. - * @private - */ + * @property {array} _keys - The array the Phaser.Key objects are stored in. + * @private + */ this._keys = []; /** - * @property {array} _capture - The array the key capture values are stored in. - * @private - */ + * @property {array} _capture - The array the key capture values are stored in. + * @private + */ this._capture = []; /** - * @property {function} _onKeyDown - * @private - * @default - */ + * @property {function} _onKeyDown + * @private + * @default + */ this._onKeyDown = null; /** - * @property {function} _onKeyPress - * @private - * @default - */ + * @property {function} _onKeyPress + * @private + * @default + */ this._onKeyPress = null; /** - * @property {function} _onKeyUp - * @private - * @default - */ + * @property {function} _onKeyUp + * @private + * @default + */ this._onKeyUp = null; /** - * @property {number} _i - Internal cache var - * @private - */ + * @property {number} _i - Internal cache var + * @private + */ this._i = 0; /** - * @property {number} _k - Internal cache var - * @private - */ + * @property {number} _k - Internal cache var + * @private + */ this._k = 0; - }; Phaser.Keyboard.prototype = { /** - * Add callbacks to the Keyboard handler so that each time a key is pressed down or released the callbacks are activated. - * - * @method Phaser.Keyboard#addCallbacks - * @param {object} context - The context under which the callbacks are run. - * @param {function} [onDown=null] - This callback is invoked every time a key is pressed down. - * @param {function} [onUp=null] - This callback is invoked every time a key is released. - * @param {function} [onPress=null] - This callback is invoked every time the onkeypress event is raised. - */ + * Add callbacks to the Keyboard handler so that each time a key is pressed down or released the callbacks are activated. + * + * @method Phaser.Keyboard#addCallbacks + * @param {object} context - The context under which the callbacks are run. + * @param {function} [onDown=null] - This callback is invoked every time a key is pressed down. + * @param {function} [onUp=null] - This callback is invoked every time a key is released. + * @param {function} [onPress=null] - This callback is invoked every time the onkeypress event is raised. + */ addCallbacks: function (context, onDown, onUp, onPress) { - this.callbackContext = context; if (onDown !== undefined && onDown !== null) @@ -147,35 +144,31 @@ Phaser.Keyboard.prototype = { { this.onPressCallback = onPress; } - }, /** - * Removes callbacks added by {@link #addCallbacks} and restores {@link #callbackContext}. - * - * @method Phaser.Keyboard#removeCallbacks - */ + * Removes callbacks added by {@link #addCallbacks} and restores {@link #callbackContext}. + * + * @method Phaser.Keyboard#removeCallbacks + */ removeCallbacks: function () { - this.callbackContext = this; this.onDownCallback = null; this.onUpCallback = null; this.onPressCallback = null; - }, /** - * If you need more fine-grained control over a Key you can create a new Phaser.Key object via this method. - * The Key object can then be polled, have events attached to it, etc. - * - * @method Phaser.Keyboard#addKey - * @param {integer} keycode - The {@link Phaser.KeyCode keycode} of the key. - * @return {Phaser.Key} The Key object which you can store locally and reference directly. - */ + * If you need more fine-grained control over a Key you can create a new Phaser.Key object via this method. + * The Key object can then be polled, have events attached to it, etc. + * + * @method Phaser.Keyboard#addKey + * @param {integer} keycode - The {@link Phaser.KeyCode keycode} of the key. + * @return {Phaser.Key} The Key object which you can store locally and reference directly. + */ addKey: function (keycode) { - if (!this._keys[keycode]) { this._keys[keycode] = new Phaser.Key(this.game, keycode); @@ -184,25 +177,23 @@ Phaser.Keyboard.prototype = { } return this._keys[keycode]; - }, /** - * A practical way to create an object containing user selected hotkeys. - * - * For example, - * - * addKeys( { 'up': Phaser.KeyCode.W, 'down': Phaser.KeyCode.S, 'left': Phaser.KeyCode.A, 'right': Phaser.KeyCode.D } ); - * - * would return an object containing properties (`up`, `down`, `left` and `right`) referring to {@link Phaser.Key} object. - * - * @method Phaser.Keyboard#addKeys - * @param {object} keys - A key mapping object, i.e. `{ 'up': Phaser.KeyCode.W, 'down': Phaser.KeyCode.S }` or `{ 'up': 52, 'down': 53 }`. - * @return {object} An object containing the properties mapped to {@link Phaser.Key} values. - */ + * A practical way to create an object containing user selected hotkeys. + * + * For example, + * + * addKeys( { 'up': Phaser.KeyCode.W, 'down': Phaser.KeyCode.S, 'left': Phaser.KeyCode.A, 'right': Phaser.KeyCode.D } ); + * + * would return an object containing properties (`up`, `down`, `left` and `right`) referring to {@link Phaser.Key} object. + * + * @method Phaser.Keyboard#addKeys + * @param {object} keys - A key mapping object, i.e. `{ 'up': Phaser.KeyCode.W, 'down': Phaser.KeyCode.S }` or `{ 'up': 52, 'down': 53 }`. + * @return {object} An object containing the properties mapped to {@link Phaser.Key} values. + */ addKeys: function (keys) { - var output = {}; for (var key in keys) @@ -211,51 +202,45 @@ Phaser.Keyboard.prototype = { } return output; - }, /** - * Removes a Key object from the Keyboard manager. - * - * @method Phaser.Keyboard#removeKey - * @param {integer} keycode - The {@link Phaser.KeyCode keycode} of the key to remove. - */ + * Removes a Key object from the Keyboard manager. + * + * @method Phaser.Keyboard#removeKey + * @param {integer} keycode - The {@link Phaser.KeyCode keycode} of the key to remove. + */ removeKey: function (keycode) { - if (this._keys[keycode]) { this._keys[keycode] = null; this.removeKeyCapture(keycode); } - }, /** - * Creates and returns an object containing 4 hotkeys for Up, Down, Left and Right. - * - * @method Phaser.Keyboard#createCursorKeys - * @return {object} An object containing properties: `up`, `down`, `left` and `right` of {@link Phaser.Key} objects. - */ + * Creates and returns an object containing 4 hotkeys for Up, Down, Left and Right. + * + * @method Phaser.Keyboard#createCursorKeys + * @return {object} An object containing properties: `up`, `down`, `left` and `right` of {@link Phaser.Key} objects. + */ createCursorKeys: function () { - return this.addKeys({ up: Phaser.KeyCode.UP, down: Phaser.KeyCode.DOWN, left: Phaser.KeyCode.LEFT, right: Phaser.KeyCode.RIGHT }); - }, /** - * Starts the Keyboard event listeners running (keydown, keyup and keypress). They are attached to the window. - * This is called automatically by Phaser.Input and should not normally be invoked directly. - * - * @method Phaser.Keyboard#start - * @protected - * @return {boolean} - */ + * Starts the Keyboard event listeners running (keydown, keyup and keypress). They are attached to the window. + * This is called automatically by Phaser.Input and should not normally be invoked directly. + * + * @method Phaser.Keyboard#start + * @protected + * @return {boolean} + */ start: function () { - if (this.game.device.cocoonJS) { return false; @@ -291,17 +276,15 @@ Phaser.Keyboard.prototype = { this.active = true; return true; - }, /** - * Stops the Keyboard event listeners from running (keydown, keyup and keypress). They are removed from the window. - * - * @method Phaser.Keyboard#stop - */ + * Stops the Keyboard event listeners from running (keydown, keyup and keypress). They are removed from the window. + * + * @method Phaser.Keyboard#stop + */ stop: function () { - window.removeEventListener('keydown', this._onKeyDown); window.removeEventListener('keyup', this._onKeyUp); window.removeEventListener('keypress', this._onKeyPress); @@ -311,42 +294,38 @@ Phaser.Keyboard.prototype = { this._onKeyPress = null; this.active = false; - }, /** - * Stops the Keyboard event listeners from running (keydown and keyup). They are removed from the window. - * Also clears all key captures and currently created Key objects. - * - * @method Phaser.Keyboard#destroy - */ + * Stops the Keyboard event listeners from running (keydown and keyup). They are removed from the window. + * Also clears all key captures and currently created Key objects. + * + * @method Phaser.Keyboard#destroy + */ destroy: function () { - this.stop(); this.clearCaptures(); this._keys.length = 0; this._i = 0; - }, /** - * By default when a key is pressed Phaser will not stop the event from propagating up to the browser. - * There are some keys this can be annoying for, like the arrow keys or space bar, which make the browser window scroll. - * - * The `addKeyCapture` method enables consuming keyboard event for specific keys so it doesn't bubble up to the the browser - * and cause the default browser behavior. - * - * Pass in either a single keycode or an array/hash of keycodes. - * - * @method Phaser.Keyboard#addKeyCapture - * @param {integer|integer[]|object} keycode - Either a single {@link Phaser.KeyCode keycode} or an array/hash of keycodes such as `[65, 67, 68]`. - */ + * By default when a key is pressed Phaser will not stop the event from propagating up to the browser. + * There are some keys this can be annoying for, like the arrow keys or space bar, which make the browser window scroll. + * + * The `addKeyCapture` method enables consuming keyboard event for specific keys so it doesn't bubble up to the the browser + * and cause the default browser behavior. + * + * Pass in either a single keycode or an array/hash of keycodes. + * + * @method Phaser.Keyboard#addKeyCapture + * @param {integer|integer[]|object} keycode - Either a single {@link Phaser.KeyCode keycode} or an array/hash of keycodes such as `[65, 67, 68]`. + */ addKeyCapture: function (keycode) { - if (typeof keycode === 'object') { for (var key in keycode) @@ -361,38 +340,33 @@ Phaser.Keyboard.prototype = { }, /** - * Removes an existing key capture. - * - * @method Phaser.Keyboard#removeKeyCapture - * @param {integer} keycode - The {@link Phaser.KeyCode keycode} to remove capturing of. - */ + * Removes an existing key capture. + * + * @method Phaser.Keyboard#removeKeyCapture + * @param {integer} keycode - The {@link Phaser.KeyCode keycode} to remove capturing of. + */ removeKeyCapture: function (keycode) { - delete this._capture[keycode]; - }, /** - * Clear all set key captures. - * - * @method Phaser.Keyboard#clearCaptures - */ + * Clear all set key captures. + * + * @method Phaser.Keyboard#clearCaptures + */ clearCaptures: function () { - this._capture = {}; - }, /** - * Updates all currently defined keys. - * - * @method Phaser.Keyboard#update - */ + * Updates all currently defined keys. + * + * @method Phaser.Keyboard#update + */ update: function () { - this._i = this._keys.length; while (this._i--) @@ -402,19 +376,17 @@ Phaser.Keyboard.prototype = { this._keys[this._i].update(); } } - }, /** - * Process the keydown event. - * - * @method Phaser.Keyboard#processKeyDown - * @param {KeyboardEvent} event - * @protected - */ + * Process the keydown event. + * + * @method Phaser.Keyboard#processKeyDown + * @param {KeyboardEvent} event + * @protected + */ processKeyDown: function (event) { - this.event = event; if (!this.game.input.enabled || !this.enabled) @@ -443,19 +415,17 @@ Phaser.Keyboard.prototype = { { this.onDownCallback.call(this.callbackContext, event); } - }, /** - * Process the keypress event. - * - * @method Phaser.Keyboard#processKeyPress - * @param {KeyboardEvent} event - * @protected - */ + * Process the keypress event. + * + * @method Phaser.Keyboard#processKeyPress + * @param {KeyboardEvent} event + * @protected + */ processKeyPress: function (event) { - this.pressEvent = event; if (!this.game.input.enabled || !this.enabled) @@ -467,19 +437,17 @@ Phaser.Keyboard.prototype = { { this.onPressCallback.call(this.callbackContext, String.fromCharCode(event.charCode), event); } - }, /** - * Process the keyup event. - * - * @method Phaser.Keyboard#processKeyUp - * @param {KeyboardEvent} event - * @protected - */ + * Process the keyup event. + * + * @method Phaser.Keyboard#processKeyUp + * @param {KeyboardEvent} event + * @protected + */ processKeyUp: function (event) { - this.event = event; if (!this.game.input.enabled || !this.enabled) @@ -505,18 +473,16 @@ Phaser.Keyboard.prototype = { { this.onUpCallback.call(this.callbackContext, event); } - }, /** - * Resets all Keys. - * - * @method Phaser.Keyboard#reset - * @param {boolean} [hard=true] - A soft reset won't reset any events or callbacks that are bound to the Keys. A hard reset will. - */ + * Resets all Keys. + * + * @method Phaser.Keyboard#reset + * @param {boolean} [hard=true] - A soft reset won't reset any events or callbacks that are bound to the Keys. A hard reset will. + */ reset: function (hard) { - if (hard === undefined) { hard = true; } this.event = null; @@ -530,21 +496,19 @@ Phaser.Keyboard.prototype = { this._keys[i].reset(hard); } } - }, /** - * Returns `true` if the Key was pressed down within the `duration` value given, or `false` if it either isn't down, - * or was pressed down longer ago than then given duration. - * - * @method Phaser.Keyboard#downDuration - * @param {integer} keycode - The {@link Phaser.KeyCode keycode} of the key to check: i.e. Phaser.KeyCode.UP or Phaser.KeyCode.SPACEBAR. - * @param {number} [duration=50] - The duration within which the key is considered as being just pressed. Given in ms. - * @return {boolean} True if the key was pressed down within the given duration, false if not or null if the Key wasn't found. - */ + * Returns `true` if the Key was pressed down within the `duration` value given, or `false` if it either isn't down, + * or was pressed down longer ago than then given duration. + * + * @method Phaser.Keyboard#downDuration + * @param {integer} keycode - The {@link Phaser.KeyCode keycode} of the key to check: i.e. Phaser.KeyCode.UP or Phaser.KeyCode.SPACEBAR. + * @param {number} [duration=50] - The duration within which the key is considered as being just pressed. Given in ms. + * @return {boolean} True if the key was pressed down within the given duration, false if not or null if the Key wasn't found. + */ downDuration: function (keycode, duration) { - if (this._keys[keycode]) { return this._keys[keycode].downDuration(duration); @@ -553,21 +517,19 @@ Phaser.Keyboard.prototype = { { return null; } - }, /** - * Returns `true` if the Key has been up *only* within the `duration` value given, or `false` if it either isn't up, - * or was has been up longer than the given duration. - * - * @method Phaser.Keyboard#upDuration - * @param {Phaser.KeyCode|integer} keycode - The keycode of the key to check, i.e. Phaser.KeyCode.UP or Phaser.KeyCode.SPACEBAR. - * @param {number} [duration=50] - The duration within which the key is considered as being just released. Given in ms. - * @return {boolean} True if the key was released within the given duration, false if not or null if the Key wasn't found. - */ + * Returns `true` if the Key has been up *only* within the `duration` value given, or `false` if it either isn't up, + * or was has been up longer than the given duration. + * + * @method Phaser.Keyboard#upDuration + * @param {Phaser.KeyCode|integer} keycode - The keycode of the key to check, i.e. Phaser.KeyCode.UP or Phaser.KeyCode.SPACEBAR. + * @param {number} [duration=50] - The duration within which the key is considered as being just released. Given in ms. + * @return {boolean} True if the key was released within the given duration, false if not or null if the Key wasn't found. + */ upDuration: function (keycode, duration) { - if (this._keys[keycode]) { return this._keys[keycode].upDuration(duration); @@ -576,12 +538,10 @@ Phaser.Keyboard.prototype = { { return null; } - }, justPressed: function (keycode) { - if (this._keys[keycode]) { return this._keys[keycode].justPressed(); @@ -590,12 +550,10 @@ Phaser.Keyboard.prototype = { { return null; } - }, justReleased: function (keycode) { - if (this._keys[keycode]) { return this._keys[keycode].justReleased(); @@ -604,19 +562,17 @@ Phaser.Keyboard.prototype = { { return null; } - }, /** - * Returns true of the key is currently pressed down. Note that it can only detect key presses on the web browser. - * - * @method Phaser.Keyboard#isDown - * @param {integer} keycode - The {@link Phaser.KeyCode keycode} of the key to check: i.e. Phaser.KeyCode.UP or Phaser.KeyCode.SPACEBAR. - * @return {boolean} True if the key is currently down, false if not or null if the Key wasn't found. - */ + * Returns true of the key is currently pressed down. Note that it can only detect key presses on the web browser. + * + * @method Phaser.Keyboard#isDown + * @param {integer} keycode - The {@link Phaser.KeyCode keycode} of the key to check: i.e. Phaser.KeyCode.UP or Phaser.KeyCode.SPACEBAR. + * @return {boolean} True if the key is currently down, false if not or null if the Key wasn't found. + */ isDown: function (keycode) { - if (this._keys[keycode]) { return this._keys[keycode].isDown; @@ -625,22 +581,20 @@ Phaser.Keyboard.prototype = { { return null; } - } }; /** -* Returns the string value of the most recently pressed key. -* @name Phaser.Keyboard#lastChar -* @property {string} lastChar - The string value of the most recently pressed key. -* @readonly -*/ + * Returns the string value of the most recently pressed key. + * @name Phaser.Keyboard#lastChar + * @property {string} lastChar - The string value of the most recently pressed key. + * @readonly + */ Object.defineProperty(Phaser.Keyboard.prototype, 'lastChar', { get: function () { - if (this.event && this.event.charCode === 32) { return ''; @@ -653,24 +607,21 @@ Object.defineProperty(Phaser.Keyboard.prototype, 'lastChar', { { return null; } - } }); /** -* Returns the most recently pressed Key. This is a Phaser.Key object and it changes every time a key is pressed. -* @name Phaser.Keyboard#lastKey -* @property {Phaser.Key} lastKey - The most recently pressed Key. -* @readonly -*/ + * Returns the most recently pressed Key. This is a Phaser.Key object and it changes every time a key is pressed. + * @name Phaser.Keyboard#lastKey + * @property {Phaser.Key} lastKey - The most recently pressed Key. + * @readonly + */ Object.defineProperty(Phaser.Keyboard.prototype, 'lastKey', { get: function () { - return this._keys[this._k]; - } }); @@ -678,20 +629,20 @@ Object.defineProperty(Phaser.Keyboard.prototype, 'lastKey', { Phaser.Keyboard.prototype.constructor = Phaser.Keyboard; /** -* A key code represents a physical key on a keyboard. -* -* The KeyCode class contains commonly supported keyboard key codes which can be used -* as keycode`-parameters in several {@link Phaser.Keyboard} and {@link Phaser.Key} methods. -* -* _Note_: These values should only be used indirectly, eg. as `Phaser.KeyCode.KEY`. -* Future versions may replace the actual values, such that they remain compatible with `keycode`-parameters. -* The current implementation maps to the {@link https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode KeyboardEvent.keyCode} property. -* -* _Note_: Use `Phaser.KeyCode.KEY` instead of `Phaser.Keyboard.KEY` to refer to a key code; -* the latter approach is supported for compatibility. -* -* @class Phaser.KeyCode -*/ + * A key code represents a physical key on a keyboard. + * + * The KeyCode class contains commonly supported keyboard key codes which can be used + * as keycode`-parameters in several {@link Phaser.Keyboard} and {@link Phaser.Key} methods. + * + * _Note_: These values should only be used indirectly, eg. as `Phaser.KeyCode.KEY`. + * Future versions may replace the actual values, such that they remain compatible with `keycode`-parameters. + * The current implementation maps to the {@link https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode KeyboardEvent.keyCode} property. + * + * _Note_: Use `Phaser.KeyCode.KEY` instead of `Phaser.Keyboard.KEY` to refer to a key code; + * the latter approach is supported for compatibility. + * + * @class Phaser.KeyCode + */ Phaser.KeyCode = { /** @static */ A: 'A'.charCodeAt(0), diff --git a/src/input/MSPointer.js b/src/input/MSPointer.js index c5cc67d00..f0fb13c51 100644 --- a/src/input/MSPointer.js +++ b/src/input/MSPointer.js @@ -1,171 +1,168 @@ /** -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* The MSPointer class handles pointer interactions with the game via the {@link https://developers.google.com/web/updates/2016/10/pointer-events Pointer Events API}. (It's named after the nonstandard {@link https://msdn.microsoft.com/library/hh673557(v=vs.85).aspx MSPointerEvent}, ancestor of the current API.) -* -* It's {@link http://caniuse.com/#feat=pointer currently supported in IE 10+, Edge, Chrome (including Android), and Opera}. -* -* You should not normally access this class directly, but instead use a {@link Phaser.Pointer} object which -* normalises all game input for you including accurate button handling. -* -* Phaser does not yet support {@link http://www.w3.org/TR/pointerevents/#chorded-button-interactions chorded button interactions}. -* -* You can disable Phaser's use of Pointer Events: -* -* ```javascript -* new Phaser.Game({ mspointer: false }); -* ``` -* -* @class Phaser.MSPointer -* @constructor -* @param {Phaser.Game} game - A reference to the currently running game. -*/ + * The MSPointer class handles pointer interactions with the game via the {@link https://developers.google.com/web/updates/2016/10/pointer-events Pointer Events API}. (It's named after the nonstandard {@link https://msdn.microsoft.com/library/hh673557(v=vs.85).aspx MSPointerEvent}, ancestor of the current API.) + * + * It's {@link http://caniuse.com/#feat=pointer currently supported in IE 10+, Edge, Chrome (including Android), and Opera}. + * + * You should not normally access this class directly, but instead use a {@link Phaser.Pointer} object which + * normalises all game input for you including accurate button handling. + * + * Phaser does not yet support {@link http://www.w3.org/TR/pointerevents/#chorded-button-interactions chorded button interactions}. + * + * You can disable Phaser's use of Pointer Events: + * + * ```javascript + * new Phaser.Game({ mspointer: false }); + * ``` + * + * @class Phaser.MSPointer + * @constructor + * @param {Phaser.Game} game - A reference to the currently running game. + */ Phaser.MSPointer = function (game) { - /** - * @property {Phaser.Game} game - A reference to the currently running game. - */ + * @property {Phaser.Game} game - A reference to the currently running game. + */ this.game = game; /** - * @property {Phaser.Input} input - A reference to the Phaser Input Manager. - * @protected - */ + * @property {Phaser.Input} input - A reference to the Phaser Input Manager. + * @protected + */ this.input = game.input; /** - * @property {object} callbackContext - The context under which callbacks are called (defaults to game). - */ + * @property {object} callbackContext - The context under which callbacks are called (defaults to game). + */ this.callbackContext = this.game; /** - * @property {function} pointerDownCallback - A callback that can be fired on a pointerdown event. - */ + * @property {function} pointerDownCallback - A callback that can be fired on a pointerdown event. + */ this.pointerDownCallback = null; /** - * @property {function} pointerMoveCallback - A callback that can be fired on a pointermove event. - */ + * @property {function} pointerMoveCallback - A callback that can be fired on a pointermove event. + */ this.pointerMoveCallback = null; /** - * @property {function} pointerUpCallback - A callback that can be fired on a pointerup event. - */ + * @property {function} pointerUpCallback - A callback that can be fired on a pointerup event. + */ this.pointerUpCallback = null; /** - * @property {function} pointerOutCallback - A callback that can be fired on a pointerout event. - */ + * @property {function} pointerOutCallback - A callback that can be fired on a pointerout event. + */ this.pointerOutCallback = null; /** - * @property {function} pointerOverCallback - A callback that can be fired on a pointerover event. - */ + * @property {function} pointerOverCallback - A callback that can be fired on a pointerover event. + */ this.pointerOverCallback = null; /** - * @property {function} pointerCancelCallback - A callback that can be fired on a pointercancel event. - */ + * @property {function} pointerCancelCallback - A callback that can be fired on a pointercancel event. + */ this.pointerCancelCallback = null; /** - * If true the PointerEvent will call preventDefault(), canceling the corresponding MouseEvent or - * TouchEvent. - * - * If the {@link Phaser.Mouse Mouse} handler is active as well, you should set this to true to avoid - * duplicate events. - * - * "Mouse events can only be prevented when the pointer is down. Hovering pointers (e.g. a mouse with - * no buttons pressed) cannot have their mouse events prevented. And, the `mouseover` and `mouseout` - * events are never prevented (even if the pointer is down)." - * - * @property {boolean} capture - * @see https://www.w3.org/Submission/pointer-events/#mapping-for-devices-that-support-hover - */ + * If true the PointerEvent will call preventDefault(), canceling the corresponding MouseEvent or + * TouchEvent. + * + * If the {@link Phaser.Mouse Mouse} handler is active as well, you should set this to true to avoid + * duplicate events. + * + * "Mouse events can only be prevented when the pointer is down. Hovering pointers (e.g. a mouse with + * no buttons pressed) cannot have their mouse events prevented. And, the `mouseover` and `mouseout` + * events are never prevented (even if the pointer is down)." + * + * @property {boolean} capture + * @see https://www.w3.org/Submission/pointer-events/#mapping-for-devices-that-support-hover + */ this.capture = false; /** - * The most recent PointerEvent from the browser. Will be null if no event has ever been received. - * Access this property only inside a Pointer event handler and do not keep references to it. - * @property {MSPointerEvent|PointerEvent|null} event - * @default - */ + * The most recent PointerEvent from the browser. Will be null if no event has ever been received. + * Access this property only inside a Pointer event handler and do not keep references to it. + * @property {MSPointerEvent|PointerEvent|null} event + * @default + */ this.event = null; /** - * Whether the input handler is active. - * @property {boolean} active - * @readOnly - * @default - */ + * Whether the input handler is active. + * @property {boolean} active + * @readOnly + * @default + */ this.active = false; /** - * PointerEvent input will only be processed if enabled. - * @property {boolean} enabled - * @default - */ + * PointerEvent input will only be processed if enabled. + * @property {boolean} enabled + * @default + */ this.enabled = true; /** - * If true Pointer.stop() will be called if the pointer leaves the game canvas. - * @property {boolean} stopOnGameOut - * @default - */ + * If true Pointer.stop() will be called if the pointer leaves the game canvas. + * @property {boolean} stopOnGameOut + * @default + */ this.stopOnGameOut = false; /** - * @property {function} _onMSPointerDown - Internal function to handle MSPointer events. - * @private - */ + * @property {function} _onMSPointerDown - Internal function to handle MSPointer events. + * @private + */ this._onMSPointerDown = null; /** - * @property {function} _onMSPointerMove - Internal function to handle MSPointer events. - * @private - */ + * @property {function} _onMSPointerMove - Internal function to handle MSPointer events. + * @private + */ this._onMSPointerMove = null; /** - * @property {function} _onMSPointerUp - Internal function to handle MSPointer events. - * @private - */ + * @property {function} _onMSPointerUp - Internal function to handle MSPointer events. + * @private + */ this._onMSPointerUp = null; /** - * @property {function} _onMSPointerUpGlobal - Internal function to handle MSPointer events. - * @private - */ + * @property {function} _onMSPointerUpGlobal - Internal function to handle MSPointer events. + * @private + */ this._onMSPointerUpGlobal = null; /** - * @property {function} _onMSPointerOut - Internal function to handle MSPointer events. - * @private - */ + * @property {function} _onMSPointerOut - Internal function to handle MSPointer events. + * @private + */ this._onMSPointerOut = null; /** - * @property {function} _onMSPointerOver - Internal function to handle MSPointer events. - * @private - */ + * @property {function} _onMSPointerOver - Internal function to handle MSPointer events. + * @private + */ this._onMSPointerOver = null; - }; Phaser.MSPointer.prototype = { /** - * Starts the event listeners running. - * @method Phaser.MSPointer#start - */ + * Starts the event listeners running. + * @method Phaser.MSPointer#start + */ start: function () { - if (!this.game.device.mspointer) { return false; @@ -245,18 +242,16 @@ Phaser.MSPointer.prototype = { this.active = true; return true; - }, /** - * The function that handles the PointerDown event. - * - * @method Phaser.MSPointer#onPointerDown - * @param {PointerEvent} event - The native DOM event. - */ + * The function that handles the PointerDown event. + * + * @method Phaser.MSPointer#onPointerDown + * @param {PointerEvent} event - The native DOM event. + */ onPointerDown: function (event) { - this.game.input.executeTouchLockCallbacks(false, event); this.event = event; @@ -286,17 +281,15 @@ Phaser.MSPointer.prototype = { { this.input.startPointer(event); } - }, /** - * The function that handles the PointerMove event. - * @method Phaser.MSPointer#onPointerMove - * @param {PointerEvent} event - The native DOM event. - */ + * The function that handles the PointerMove event. + * @method Phaser.MSPointer#onPointerMove + * @param {PointerEvent} event - The native DOM event. + */ onPointerMove: function (event) { - this.event = event; if (this.capture) @@ -324,17 +317,15 @@ Phaser.MSPointer.prototype = { { this.input.updatePointer(event); } - }, /** - * The function that handles the PointerUp event. - * @method Phaser.MSPointer#onPointerUp - * @param {PointerEvent} event - The native DOM event. - */ + * The function that handles the PointerUp event. + * @method Phaser.MSPointer#onPointerUp + * @param {PointerEvent} event - The native DOM event. + */ onPointerUp: function (event) { - this.game.input.executeTouchLockCallbacks(true, event); this.event = event; @@ -364,18 +355,16 @@ Phaser.MSPointer.prototype = { { this.input.stopPointer(event); } - }, /** - * The internal method that handles the mouse up event from the window. - * - * @method Phaser.MSPointer#onPointerUpGlobal - * @param {PointerEvent} event - The native event from the browser. This gets stored in MSPointer.event. - */ + * The internal method that handles the mouse up event from the window. + * + * @method Phaser.MSPointer#onPointerUpGlobal + * @param {PointerEvent} event - The native event from the browser. This gets stored in MSPointer.event. + */ onPointerUpGlobal: function (event) { - event.identifier = event.pointerId; if (this.isMousePointerEvent(event) && !this.input.mousePointer.withinGame) @@ -391,18 +380,16 @@ Phaser.MSPointer.prototype = { this.onPointerUp(event); } } - }, /** - * The internal method that handles the pointer out event from the browser. - * - * @method Phaser.MSPointer#onPointerOut - * @param {PointerEvent} event - The native event from the browser. This gets stored in MSPointer.event. - */ + * The internal method that handles the pointer out event from the browser. + * + * @method Phaser.MSPointer#onPointerOut + * @param {PointerEvent} event - The native event from the browser. This gets stored in MSPointer.event. + */ onPointerOut: function (event) { - this.event = event; if (this.capture) @@ -442,18 +429,16 @@ Phaser.MSPointer.prototype = { this.input.callAll('_pointerOutHandler', pointer); } - }, /** - * The internal method that handles the pointer over event from the browser. - * - * @method Phaser.MSPointer#onPointerOut - * @param {PointerEvent} event - The native event from the browser. This gets stored in MSPointer.event. - */ + * The internal method that handles the pointer over event from the browser. + * + * @method Phaser.MSPointer#onPointerOut + * @param {PointerEvent} event - The native event from the browser. This gets stored in MSPointer.event. + */ onPointerOver: function (event) { - this.event = event; if (this.capture) @@ -474,18 +459,16 @@ Phaser.MSPointer.prototype = { { this.pointerOverCallback.call(this.callbackContext, event); } - }, /** - * The internal method that handles the pointer cancel event from the browser. - * - * @method Phaser.MSPointer#onPointerCancel - * @param {PointerEvent} event - */ + * The internal method that handles the pointer cancel event from the browser. + * + * @method Phaser.MSPointer#onPointerCancel + * @param {PointerEvent} event + */ onPointerCancel: function (event) { - this.event = event; if (this.pointerCancelCallback) @@ -508,16 +491,14 @@ Phaser.MSPointer.prototype = { { this.input.stopPointer(event); } - }, /** - * Stop the event listeners. - * @method Phaser.MSPointer#stop - */ + * Stop the event listeners. + * @method Phaser.MSPointer#stop + */ stop: function () { - var canvas = this.game.canvas; canvas.removeEventListener('MSPointerDown', this._onMSPointerDown, false); @@ -539,7 +520,6 @@ Phaser.MSPointer.prototype = { canvas.removeEventListener('pointerout', this._onMSPointerOut, true); this.active = false; - }, /** diff --git a/src/input/Mouse.js b/src/input/Mouse.js index 8eded0bde..8828489b3 100644 --- a/src/input/Mouse.js +++ b/src/input/Mouse.js @@ -1,187 +1,184 @@ /** -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* The Mouse class is responsible for handling all aspects of mouse interaction with the browser. -* -* It captures and processes mouse events that happen on the game canvas object. -* It also adds a single `mouseup` listener to `window` which is used to capture the mouse being released -* when not over the game. -* -* You should not normally access this class directly, but instead use a Phaser.Pointer object -* which normalises all game input for you, including accurate button handling. -* -* @class Phaser.Mouse -* @constructor -* @param {Phaser.Game} game - A reference to the currently running game. -*/ + * The Mouse class is responsible for handling all aspects of mouse interaction with the browser. + * + * It captures and processes mouse events that happen on the game canvas object. + * It also adds a single `mouseup` listener to `window` which is used to capture the mouse being released + * when not over the game. + * + * You should not normally access this class directly, but instead use a Phaser.Pointer object + * which normalises all game input for you, including accurate button handling. + * + * @class Phaser.Mouse + * @constructor + * @param {Phaser.Game} game - A reference to the currently running game. + */ Phaser.Mouse = function (game) { - /** - * @property {Phaser.Game} game - A reference to the currently running game. - */ + * @property {Phaser.Game} game - A reference to the currently running game. + */ this.game = game; /** - * @property {Phaser.Input} input - A reference to the Phaser Input Manager. - * @protected - */ + * @property {Phaser.Input} input - A reference to the Phaser Input Manager. + * @protected + */ this.input = game.input; /** - * @property {object} callbackContext - The context under which callbacks are called. - */ + * @property {object} callbackContext - The context under which callbacks are called. + */ this.callbackContext = this.game; /** - * A callback that can be fired when the mouse is pressed down. - * You should set {@link Phaser.Input.MSPointer#pointerDownCallback} as well. - * @property {function} mouseDownCallback - */ + * A callback that can be fired when the mouse is pressed down. + * You should set {@link Phaser.Input.MSPointer#pointerDownCallback} as well. + * @property {function} mouseDownCallback + */ this.mouseDownCallback = null; /** - * A callback that can be fired when the mouse is released from a pressed down state. - * You should set {@link Phaser.Input.MSPointer#pointerUpCallback} as well. - * @property {function} mouseUpCallback - */ + * A callback that can be fired when the mouse is released from a pressed down state. + * You should set {@link Phaser.Input.MSPointer#pointerUpCallback} as well. + * @property {function} mouseUpCallback + */ this.mouseUpCallback = null; /** - * A callback that can be fired when the mouse is no longer over the game canvas. - * You should set {@link Phaser.Input.MSPointer#pointerOutCallback} as well. - * - * @property {function} mouseOutCallback - */ + * A callback that can be fired when the mouse is no longer over the game canvas. + * You should set {@link Phaser.Input.MSPointer#pointerOutCallback} as well. + * + * @property {function} mouseOutCallback + */ this.mouseOutCallback = null; /** - * A callback that can be fired when the mouse enters the game canvas (usually after a mouseout). - * You should set {@link Phaser.Input.MSPointer#pointerOverCallback} as well. - * @property {function} mouseOverCallback - */ + * A callback that can be fired when the mouse enters the game canvas (usually after a mouseout). + * You should set {@link Phaser.Input.MSPointer#pointerOverCallback} as well. + * @property {function} mouseOverCallback + */ this.mouseOverCallback = null; /** - * @property {boolean} capture - If true the DOM mouse events will have event.preventDefault applied to them. - */ + * @property {boolean} capture - If true the DOM mouse events will have event.preventDefault applied to them. + */ this.capture = false; /** - * @property {boolean} - Whether the handler has started. - * @readOnly - * @see Phaser.Mouse#start - * @see Phaser.Mouse#stop - */ + * @property {boolean} - Whether the handler has started. + * @readOnly + * @see Phaser.Mouse#start + * @see Phaser.Mouse#stop + */ this.active = false; /** - * Whether mouse input is passed to the Input Manager and Mouse Pointer. - * When enabled is false, `game.input` and `game.input.mousePointer` are not updated by this handler. - * The handler is still running and will call any added callbacks and apply {@link Phaser.Mouse#capture}. - * @property {boolean} enabled - * @default - */ + * Whether mouse input is passed to the Input Manager and Mouse Pointer. + * When enabled is false, `game.input` and `game.input.mousePointer` are not updated by this handler. + * The handler is still running and will call any added callbacks and apply {@link Phaser.Mouse#capture}. + * @property {boolean} enabled + * @default + */ this.enabled = true; /** - * If true Pointer.stop will be called if the mouse leaves the game canvas. - * You should set {@link Phaser.Input.MSPointer#stopOnGameOut} as well. - * @property {boolean} stopOnGameOut - * @default - */ + * If true Pointer.stop will be called if the mouse leaves the game canvas. + * You should set {@link Phaser.Input.MSPointer#stopOnGameOut} as well. + * @property {boolean} stopOnGameOut + * @default + */ this.stopOnGameOut = false; /** - * The browser mouse DOM event. Will be null if no mouse event has ever been received. - * Access this property only inside a Mouse event handler and do not keep references to it. - * @property {MouseEvent|null} event - * @default - */ + * The browser mouse DOM event. Will be null if no mouse event has ever been received. + * Access this property only inside a Mouse event handler and do not keep references to it. + * @property {MouseEvent|null} event + * @default + */ this.event = null; /** - * @property {function} _onMouseDown - Internal event handler reference. - * @private - */ + * @property {function} _onMouseDown - Internal event handler reference. + * @private + */ this._onMouseDown = null; /** - * @property {function} _onMouseMove - Internal event handler reference. - * @private - */ + * @property {function} _onMouseMove - Internal event handler reference. + * @private + */ this._onMouseMove = null; /** - * @property {function} _onMouseUp - Internal event handler reference. - * @private - */ + * @property {function} _onMouseUp - Internal event handler reference. + * @private + */ this._onMouseUp = null; /** - * @property {function} _onMouseOut - Internal event handler reference. - * @private - */ + * @property {function} _onMouseOut - Internal event handler reference. + * @private + */ this._onMouseOut = null; /** - * @property {function} _onMouseOver - Internal event handler reference. - * @private - */ + * @property {function} _onMouseOver - Internal event handler reference. + * @private + */ this._onMouseOver = null; - }; /** -* @constant -* @type {number} -*/ + * @constant + * @type {number} + */ Phaser.Mouse.NO_BUTTON = -1; /** -* @constant -* @type {number} -*/ + * @constant + * @type {number} + */ Phaser.Mouse.LEFT_BUTTON = 0; /** -* @constant -* @type {number} -*/ + * @constant + * @type {number} + */ Phaser.Mouse.MIDDLE_BUTTON = 1; /** -* @constant -* @type {number} -*/ + * @constant + * @type {number} + */ Phaser.Mouse.RIGHT_BUTTON = 2; /** -* @constant -* @type {number} -*/ + * @constant + * @type {number} + */ Phaser.Mouse.BACK_BUTTON = 3; /** -* @constant -* @type {number} -*/ + * @constant + * @type {number} + */ Phaser.Mouse.FORWARD_BUTTON = 4; Phaser.Mouse.prototype = { /** - * Starts the event listeners running. - * @method Phaser.Mouse#start - * @return {boolean} - Whether the handler was started. - */ + * Starts the event listeners running. + * @method Phaser.Mouse#start + * @return {boolean} - Whether the handler was started. + */ start: function () { - var device = this.game.device; if (device.isAndroidStockBrowser() && this.input.touch.active) @@ -250,17 +247,15 @@ Phaser.Mouse.prototype = { this.active = true; return true; - }, /** - * The internal method that handles the mouse down event from the browser. - * @method Phaser.Mouse#onMouseDown - * @param {MouseEvent} event - The native event from the browser. This gets stored in Mouse.event. - */ + * The internal method that handles the mouse down event from the browser. + * @method Phaser.Mouse#onMouseDown + * @param {MouseEvent} event - The native event from the browser. This gets stored in Mouse.event. + */ onMouseDown: function (event) { - this.event = event; if (this.capture) @@ -281,17 +276,15 @@ Phaser.Mouse.prototype = { event.identifier = 0; this.input.mousePointer.start(event); - }, /** - * The internal method that handles the mouse move event from the browser. - * @method Phaser.Mouse#onMouseMove - * @param {MouseEvent} event - The native event from the browser. This gets stored in Mouse.event. - */ + * The internal method that handles the mouse move event from the browser. + * @method Phaser.Mouse#onMouseMove + * @param {MouseEvent} event - The native event from the browser. This gets stored in Mouse.event. + */ onMouseMove: function (event) { - this.event = event; if (this.capture) @@ -312,17 +305,15 @@ Phaser.Mouse.prototype = { event.identifier = 0; this.input.mousePointer.move(event); - }, /** - * The internal method that handles the mouse up event from the browser. - * @method Phaser.Mouse#onMouseUp - * @param {MouseEvent} event - The native event from the browser. This gets stored in Mouse.event. - */ + * The internal method that handles the mouse up event from the browser. + * @method Phaser.Mouse#onMouseUp + * @param {MouseEvent} event - The native event from the browser. This gets stored in Mouse.event. + */ onMouseUp: function (event) { - this.event = event; if (this.capture) @@ -343,18 +334,16 @@ Phaser.Mouse.prototype = { event.identifier = 0; this.input.mousePointer.stop(event); - }, /** - * The internal method that handles the mouse up event from the window. - * - * @method Phaser.Mouse#onMouseUpGlobal - * @param {MouseEvent} event - The native event from the browser. This gets stored in Mouse.event. - */ + * The internal method that handles the mouse up event from the window. + * + * @method Phaser.Mouse#onMouseUpGlobal + * @param {MouseEvent} event - The native event from the browser. This gets stored in Mouse.event. + */ onMouseUpGlobal: function (event) { - if (!this.input.mousePointer.withinGame) { if (this.mouseUpCallback) @@ -366,18 +355,16 @@ Phaser.Mouse.prototype = { this.input.mousePointer.stop(event); } - }, /** - * The internal method that handles the mouse out event from the window. - * - * @method Phaser.Mouse#onMouseOutGlobal - * @param {MouseEvent} event - The native event from the browser. This gets stored in Mouse.event. - */ + * The internal method that handles the mouse out event from the window. + * + * @method Phaser.Mouse#onMouseOutGlobal + * @param {MouseEvent} event - The native event from the browser. This gets stored in Mouse.event. + */ onMouseOutGlobal: function (event) { - this.event = event; if (this.capture) @@ -392,30 +379,30 @@ Phaser.Mouse.prototype = { return; } - // If we get a mouseout event from the window then basically - // something serious has gone down, usually along the lines of - // the browser opening a context-menu or similar. - // On OS X Chrome especially this is bad news, as it blocks - // us then getting a mouseup event, so we need to force that through. - // - // No matter what, we must cancel the left and right buttons + /* + * If we get a mouseout event from the window then basically + * something serious has gone down, usually along the lines of + * the browser opening a context-menu or similar. + * On OS X Chrome especially this is bad news, as it blocks + * us then getting a mouseup event, so we need to force that through. + * + * No matter what, we must cancel the left and right buttons + */ this.input.mousePointer.stop(event); // Clear the button states (again?) this.input.mousePointer.resetButtons(); - }, /** - * The internal method that handles the mouse out event from the browser. - * - * @method Phaser.Mouse#onMouseOut - * @param {MouseEvent} event - The native event from the browser. This gets stored in Mouse.event. - */ + * The internal method that handles the mouse out event from the browser. + * + * @method Phaser.Mouse#onMouseOut + * @param {MouseEvent} event - The native event from the browser. This gets stored in Mouse.event. + */ onMouseOut: function (event) { - this.event = event; if (this.capture) @@ -445,18 +432,16 @@ Phaser.Mouse.prototype = { this.input.callAll('_pointerOutHandler', this.input.mousePointer); } - }, /** - * The internal method that handles the mouse over event from the browser. - * - * @method Phaser.Mouse#onMouseOver - * @param {MouseEvent} event - The native event from the browser. This gets stored in Mouse.event. - */ + * The internal method that handles the mouse over event from the browser. + * + * @method Phaser.Mouse#onMouseOver + * @param {MouseEvent} event - The native event from the browser. This gets stored in Mouse.event. + */ onMouseOver: function (event) { - this.event = event; if (this.capture) @@ -477,16 +462,14 @@ Phaser.Mouse.prototype = { } this.input.mousePointer.updateButtons(event); - }, /** - * Stop the event listeners. - * @method Phaser.Mouse#stop - */ + * Stop the event listeners. + * @method Phaser.Mouse#stop + */ stop: function () { - var canvas = this.game.canvas; canvas.removeEventListener('mousedown', this._onMouseDown, true); @@ -499,7 +482,6 @@ Phaser.Mouse.prototype = { window.removeEventListener('mouseout', this._onMouseOutGlobal, true); this.active = false; - } }; diff --git a/src/input/MouseWheel.js b/src/input/MouseWheel.js index 1bb925b99..38c0487ed 100644 --- a/src/input/MouseWheel.js +++ b/src/input/MouseWheel.js @@ -1,117 +1,114 @@ /** -* The mouse wheel input handler. -* @class -* @constructor -* @param {Phaser.Game} game -*/ + * The mouse wheel input handler. + * @class + * @constructor + * @param {Phaser.Game} game + */ Phaser.MouseWheel = function (game) { - /** - * The currently running game. - * @type {Phaser.Game} - */ + * The currently running game. + * @type {Phaser.Game} + */ this.game = game; /** - * The Input Manager. - * @type {Phaser.Input} - */ + * The Input Manager. + * @type {Phaser.Input} + */ this.input = game.input; /** - * The element where event listeners are added (the game canvas). - * @type {HTMLElement} - */ + * The element where event listeners are added (the game canvas). + * @type {HTMLElement} + */ this.element = game.canvas; /** - * Whether the default mouse wheel actions (usually zoom or pan) are cancelled. - * @type {boolean} - * @default - */ + * Whether the default mouse wheel actions (usually zoom or pan) are cancelled. + * @type {boolean} + * @default + */ this.preventDefault = true; /** - * Whether the handler is active. - * @type {boolean} - * @readOnly - * @see Phaser.MouseWheel#start - * @see Phaser.MouseWheel#stop - */ + * Whether the handler is active. + * @type {boolean} + * @readOnly + * @see Phaser.MouseWheel#start + * @see Phaser.MouseWheel#stop + */ this.active = false; /** - * A callback to call for each wheel event. - * It receives an `event` parameter. - * @type {function} - */ + * A callback to call for each wheel event. + * It receives an `event` parameter. + * @type {function} + */ this.callback = null; /** - * The context for {@link Phaser.MouseWheel#callback}. - * The default is {@link Phaser.MouseWheel#game}. - * @type {any} - */ + * The context for {@link Phaser.MouseWheel#callback}. + * The default is {@link Phaser.MouseWheel#game}. + * @type {any} + */ this.callbackContext = game; /** - * The direction of the last wheel event. - * Between -1 (down) and 1 (up). - * @type {number} - * @readOnly - * @default - */ + * The direction of the last wheel event. + * Between -1 (down) and 1 (up). + * @type {number} + * @readOnly + * @default + */ this.delta = 0; /** - * The name of the wheel event supported by the device, if any. - * 'wheel' (standard), 'mousewheel' (deprecated), or 'DOMMouseScroll' (obsolete Firefox). - * @type {?string} - * @private - * @see https://developer.mozilla.org/en-US/docs/Web/Events/wheel - * @see https://developer.mozilla.org/en-US/docs/Web/Events/mousewheel - * @see https://developer.mozilla.org/en-US/docs/Web/Events/DOMMouseScroll - */ + * The name of the wheel event supported by the device, if any. + * 'wheel' (standard), 'mousewheel' (deprecated), or 'DOMMouseScroll' (obsolete Firefox). + * @type {?string} + * @private + * @see https://developer.mozilla.org/en-US/docs/Web/Events/wheel + * @see https://developer.mozilla.org/en-US/docs/Web/Events/mousewheel + * @see https://developer.mozilla.org/en-US/docs/Web/Events/DOMMouseScroll + */ this.wheelEventName = game.device.wheelEvent; /** - * The wheel event handler, bound to this instance. - * @type {function} - * @private - * @see Phaser.MouseWheel#onWheelHandler - */ + * The wheel event handler, bound to this instance. + * @type {function} + * @private + * @see Phaser.MouseWheel#onWheelHandler + */ this.boundOnWheelHandler = this.onWheelHandler.bind(this); /** - * Wheel proxy event object, if required. Shared for all wheel events for this mouse. - * @type {Phaser.WheelEventProxy} - * @private - */ + * Wheel proxy event object, if required. Shared for all wheel events for this mouse. + * @type {Phaser.WheelEventProxy} + * @private + */ this.eventProxy = null; - }; /** -* @constant -* @type {number} -*/ + * @constant + * @type {number} + */ Phaser.MouseWheel.UP = 1; /** -* @constant -* @type {number} -*/ + * @constant + * @type {number} + */ Phaser.MouseWheel.DOWN = -1; /** -* Activates the handler, unless unsupported or already activate. -* @method Phaser.MouseWheel#start -* @returns {boolean} - True if the handler was started, otherwise false. -*/ + * Activates the handler, unless unsupported or already activate. + * @method Phaser.MouseWheel#start + * @returns {boolean} - True if the handler was started, otherwise false. + */ Phaser.MouseWheel.prototype.start = function () { - if (!this.wheelEventName || this.active) { return false; @@ -131,16 +128,14 @@ Phaser.MouseWheel.prototype.start = function () this.active = true; return true; - }; /** -* Deactivates the handler. -* @method Phaser.MouseWheel#stop -*/ + * Deactivates the handler. + * @method Phaser.MouseWheel#stop + */ Phaser.MouseWheel.prototype.stop = function () { - if (!this.active) { return; @@ -149,18 +144,16 @@ Phaser.MouseWheel.prototype.stop = function () this.element.removeEventListener(this.wheelEventName, this.boundOnWheelHandler, true); this.active = false; - }; /** -* Processes the wheel event from the browser. -* @method Phaser.MouseWheel#onWheelHandler -* @private -* @param {WheelEvent|MouseWheelEvent|MouseScrollEvent} event -*/ + * Processes the wheel event from the browser. + * @method Phaser.MouseWheel#onWheelHandler + * @private + * @param {WheelEvent|MouseWheelEvent|MouseScrollEvent} event + */ Phaser.MouseWheel.prototype.onWheelHandler = function (event) { - if (this.eventProxy) { event = this.eventProxy.bindEvent(event); @@ -178,5 +171,4 @@ Phaser.MouseWheel.prototype.onWheelHandler = function (event) { this.callback.call(this.callbackContext, event); } - }; diff --git a/src/input/Pointer.js b/src/input/Pointer.js index aef5efc01..31ec9e5af 100644 --- a/src/input/Pointer.js +++ b/src/input/Pointer.js @@ -1,430 +1,427 @@ /** -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* A Pointer object is used by the Mouse, Touch and MSPoint managers and represents a single finger on the touch screen. -* -* @class Phaser.Pointer -* @constructor -* @param {Phaser.Game} game - A reference to the currently running game. -* @param {number} id - The ID of the Pointer object within the game. Each game can have up to 10 active pointers. -* @param {Phaser.PointerMode} pointerMode=(CURSOR|CONTACT) - The operational mode of this pointer, eg. CURSOR or CONTACT. -*/ + * A Pointer object is used by the Mouse, Touch and MSPoint managers and represents a single finger on the touch screen. + * + * @class Phaser.Pointer + * @constructor + * @param {Phaser.Game} game - A reference to the currently running game. + * @param {number} id - The ID of the Pointer object within the game. Each game can have up to 10 active pointers. + * @param {Phaser.PointerMode} pointerMode=(CURSOR|CONTACT) - The operational mode of this pointer, eg. CURSOR or CONTACT. + */ Phaser.Pointer = function (game, id, pointerMode) { - /** - * @property {Phaser.Game} game - A reference to the currently running game. - */ + * @property {Phaser.Game} game - A reference to the currently running game. + */ this.game = game; /** - * @property {number} id - The ID of the Pointer object within the game. Each game can have up to 10 active pointers. - */ + * @property {number} id - The ID of the Pointer object within the game. Each game can have up to 10 active pointers. + */ this.id = id; /** - * @property {number} type - The const type of this object. - * @readonly - */ + * @property {number} type - The const type of this object. + * @readonly + */ this.type = Phaser.POINTER; /** - * @property {boolean} exists - A Pointer object that exists is allowed to be checked for physics collisions and overlaps. - * @default - */ + * @property {boolean} exists - A Pointer object that exists is allowed to be checked for physics collisions and overlaps. + * @default + */ this.exists = true; /** - * @property {number} identifier - The identifier property of the Pointer as set by the DOM event when this Pointer is started. - * @default - */ + * @property {number} identifier - The identifier property of the Pointer as set by the DOM event when this Pointer is started. + * @default + */ this.identifier = 0; /** - * @property {number} pointerId - The pointerId property of the Pointer as set by the DOM event when this Pointer is started. The browser can and will recycle this value. - * @default - */ + * @property {number} pointerId - The pointerId property of the Pointer as set by the DOM event when this Pointer is started. The browser can and will recycle this value. + * @default + */ this.pointerId = null; /** - * @property {Phaser.PointerMode} pointerMode - The operational mode of this pointer. - */ + * @property {Phaser.PointerMode} pointerMode - The operational mode of this pointer. + */ this.pointerMode = pointerMode || (Phaser.PointerMode.CURSOR | Phaser.PointerMode.CONTACT); /** - * @property {any} target - The target property of the Pointer as set by the DOM event when this Pointer is started. - * @default - */ + * @property {any} target - The target property of the Pointer as set by the DOM event when this Pointer is started. + * @default + */ this.target = null; /** - * The button property of the most recent DOM event when this Pointer is started. - * You should not rely on this value for accurate button detection, instead use the Pointer properties - * `leftButton`, `rightButton`, `middleButton` and so on. - * @property {any} button - * @default - */ + * The button property of the most recent DOM event when this Pointer is started. + * You should not rely on this value for accurate button detection, instead use the Pointer properties + * `leftButton`, `rightButton`, `middleButton` and so on. + * @property {any} button + * @default + */ this.button = null; /** - * If this Pointer is a Mouse or Pen / Stylus then you can access its left button directly through this property. - * - * The DeviceButton has its own properties such as `isDown`, `duration` and methods like `justReleased` for more fine-grained - * button control. - * - * @property {Phaser.DeviceButton} leftButton - * @default - */ + * If this Pointer is a Mouse or Pen / Stylus then you can access its left button directly through this property. + * + * The DeviceButton has its own properties such as `isDown`, `duration` and methods like `justReleased` for more fine-grained + * button control. + * + * @property {Phaser.DeviceButton} leftButton + * @default + */ this.leftButton = new Phaser.DeviceButton(this, Phaser.Pointer.LEFT_BUTTON); /** - * If this Pointer is a Mouse or Pen / Stylus then you can access its middle button directly through this property. - * - * The DeviceButton has its own properties such as `isDown`, `duration` and methods like `justReleased` for more fine-grained - * button control. - * - * Please see the DeviceButton docs for details on browser button limitations. - * - * @property {Phaser.DeviceButton} middleButton - * @default - */ + * If this Pointer is a Mouse or Pen / Stylus then you can access its middle button directly through this property. + * + * The DeviceButton has its own properties such as `isDown`, `duration` and methods like `justReleased` for more fine-grained + * button control. + * + * Please see the DeviceButton docs for details on browser button limitations. + * + * @property {Phaser.DeviceButton} middleButton + * @default + */ this.middleButton = new Phaser.DeviceButton(this, Phaser.Pointer.MIDDLE_BUTTON); /** - * If this Pointer is a Mouse or Pen / Stylus then you can access its right button directly through this property. - * - * The DeviceButton has its own properties such as `isDown`, `duration` and methods like `justReleased` for more fine-grained - * button control. - * - * Please see the DeviceButton docs for details on browser button limitations. - * - * @property {Phaser.DeviceButton} rightButton - * @default - */ + * If this Pointer is a Mouse or Pen / Stylus then you can access its right button directly through this property. + * + * The DeviceButton has its own properties such as `isDown`, `duration` and methods like `justReleased` for more fine-grained + * button control. + * + * Please see the DeviceButton docs for details on browser button limitations. + * + * @property {Phaser.DeviceButton} rightButton + * @default + */ this.rightButton = new Phaser.DeviceButton(this, Phaser.Pointer.RIGHT_BUTTON); /** - * If this Pointer is a Mouse or Pen / Stylus then you can access its X1 (back) button directly through this property. - * - * The DeviceButton has its own properties such as `isDown`, `duration` and methods like `justReleased` for more fine-grained - * button control. - * - * Please see the DeviceButton docs for details on browser button limitations. - * - * @property {Phaser.DeviceButton} backButton - * @default - */ + * If this Pointer is a Mouse or Pen / Stylus then you can access its X1 (back) button directly through this property. + * + * The DeviceButton has its own properties such as `isDown`, `duration` and methods like `justReleased` for more fine-grained + * button control. + * + * Please see the DeviceButton docs for details on browser button limitations. + * + * @property {Phaser.DeviceButton} backButton + * @default + */ this.backButton = new Phaser.DeviceButton(this, Phaser.Pointer.BACK_BUTTON); /** - * If this Pointer is a Mouse or Pen / Stylus then you can access its X2 (forward) button directly through this property. - * - * The DeviceButton has its own properties such as `isDown`, `duration` and methods like `justReleased` for more fine-grained - * button control. - * - * Please see the DeviceButton docs for details on browser button limitations. - * - * @property {Phaser.DeviceButton} forwardButton - * @default - */ + * If this Pointer is a Mouse or Pen / Stylus then you can access its X2 (forward) button directly through this property. + * + * The DeviceButton has its own properties such as `isDown`, `duration` and methods like `justReleased` for more fine-grained + * button control. + * + * Please see the DeviceButton docs for details on browser button limitations. + * + * @property {Phaser.DeviceButton} forwardButton + * @default + */ this.forwardButton = new Phaser.DeviceButton(this, Phaser.Pointer.FORWARD_BUTTON); /** - * If this Pointer is a Pen / Stylus then you can access its eraser button directly through this property. - * - * The DeviceButton has its own properties such as `isDown`, `duration` and methods like `justReleased` for more fine-grained - * button control. - * - * Please see the DeviceButton docs for details on browser button limitations. - * - * @property {Phaser.DeviceButton} eraserButton - * @default - */ + * If this Pointer is a Pen / Stylus then you can access its eraser button directly through this property. + * + * The DeviceButton has its own properties such as `isDown`, `duration` and methods like `justReleased` for more fine-grained + * button control. + * + * Please see the DeviceButton docs for details on browser button limitations. + * + * @property {Phaser.DeviceButton} eraserButton + * @default + */ this.eraserButton = new Phaser.DeviceButton(this, Phaser.Pointer.ERASER_BUTTON); /** - * @property {boolean} _holdSent - Local private variable to store the status of dispatching a hold event. - * @private - * @default - */ + * @property {boolean} _holdSent - Local private variable to store the status of dispatching a hold event. + * @private + * @default + */ this._holdSent = false; /** - * @property {array} _history - Local private variable storing the short-term history of pointer movements. - * @private - */ + * @property {array} _history - Local private variable storing the short-term history of pointer movements. + * @private + */ this._history = []; /** - * @property {number} _nextDrop - Local private variable storing the time at which the next history drop should occur. - * @private - */ + * @property {number} _nextDrop - Local private variable storing the time at which the next history drop should occur. + * @private + */ this._nextDrop = 0; /** - * @property {boolean} _stateReset - Monitor events outside of a state reset loop. - * @private - */ + * @property {boolean} _stateReset - Monitor events outside of a state reset loop. + * @private + */ this._stateReset = false; /** - * @property {boolean} withinGame - true if the Pointer is over the game canvas, otherwise false. - */ + * @property {boolean} withinGame - true if the Pointer is over the game canvas, otherwise false. + */ this.withinGame = false; /** - * @property {number} clientX - The horizontal coordinate of the Pointer within the application's client area at which the event occurred (as opposed to the coordinates within the page). - */ + * @property {number} clientX - The horizontal coordinate of the Pointer within the application's client area at which the event occurred (as opposed to the coordinates within the page). + */ this.clientX = -1; /** - * @property {number} clientY - The vertical coordinate of the Pointer within the application's client area at which the event occurred (as opposed to the coordinates within the page). - */ + * @property {number} clientY - The vertical coordinate of the Pointer within the application's client area at which the event occurred (as opposed to the coordinates within the page). + */ this.clientY = -1; /** - * @property {number} pageX - The horizontal coordinate of the Pointer relative to whole document. - */ + * @property {number} pageX - The horizontal coordinate of the Pointer relative to whole document. + */ this.pageX = -1; /** - * @property {number} pageY - The vertical coordinate of the Pointer relative to whole document. - */ + * @property {number} pageY - The vertical coordinate of the Pointer relative to whole document. + */ this.pageY = -1; /** - * @property {number} screenX - The horizontal coordinate of the Pointer relative to the screen. - */ + * @property {number} screenX - The horizontal coordinate of the Pointer relative to the screen. + */ this.screenX = -1; /** - * @property {number} screenY - The vertical coordinate of the Pointer relative to the screen. - */ + * @property {number} screenY - The vertical coordinate of the Pointer relative to the screen. + */ this.screenY = -1; /** - * @property {number} rawMovementX - The horizontal raw relative movement of the Pointer in pixels at the last event, if this is a Mouse Pointer in a locked state. - * @default - * @see https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/movementX - */ + * @property {number} rawMovementX - The horizontal raw relative movement of the Pointer in pixels at the last event, if this is a Mouse Pointer in a locked state. + * @default + * @see https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/movementX + */ this.rawMovementX = 0; /** - * @property {number} rawMovementY - The vertical raw relative movement of the Pointer in pixels at the last event, if this is a Mouse Pointer in a locked state. - * @default - * @see https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/movementY - */ + * @property {number} rawMovementY - The vertical raw relative movement of the Pointer in pixels at the last event, if this is a Mouse Pointer in a locked state. + * @default + * @see https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/movementY + */ this.rawMovementY = 0; /** - * @property {number} movementX - The cumulative horizontal relative movement of the Pointer in pixels since resetMovement() was called, if this is a Mouse Pointer in a locked state. - * @default - */ + * @property {number} movementX - The cumulative horizontal relative movement of the Pointer in pixels since resetMovement() was called, if this is a Mouse Pointer in a locked state. + * @default + */ this.movementX = 0; /** - * @property {number} movementY - The cumulative vertical relative movement of the Pointer in pixels since resetMovement() was called, if this is a Mouse Pointer in a locked state.. - * @default - */ + * @property {number} movementY - The cumulative vertical relative movement of the Pointer in pixels since resetMovement() was called, if this is a Mouse Pointer in a locked state.. + * @default + */ this.movementY = 0; /** - * @property {number} x - The horizontal coordinate of the Pointer. This value is automatically scaled based on the game scale. - * @default - */ + * @property {number} x - The horizontal coordinate of the Pointer. This value is automatically scaled based on the game scale. + * @default + */ this.x = -1; /** - * @property {number} y - The vertical coordinate of the Pointer. This value is automatically scaled based on the game scale. - * @default - */ + * @property {number} y - The vertical coordinate of the Pointer. This value is automatically scaled based on the game scale. + * @default + */ this.y = -1; /** - * @property {boolean} isMouse - If the Pointer is a mouse or pen / stylus this is true, otherwise false. - */ + * @property {boolean} isMouse - If the Pointer is a mouse or pen / stylus this is true, otherwise false. + */ this.isMouse = (id === 0); /** - * If the Pointer is touching the touchscreen, or *any* mouse or pen button is held down, isDown is set to true. - * If you need to check a specific mouse or pen button then use the button properties, i.e. Pointer.rightButton.isDown. - * @property {boolean} isDown - * @default - */ + * If the Pointer is touching the touchscreen, or *any* mouse or pen button is held down, isDown is set to true. + * If you need to check a specific mouse or pen button then use the button properties, i.e. Pointer.rightButton.isDown. + * @property {boolean} isDown + * @default + */ this.isDown = false; /** - * If the Pointer is not touching the touchscreen, or *all* mouse or pen buttons are up, isUp is set to true. - * If you need to check a specific mouse or pen button then use the button properties, i.e. Pointer.rightButton.isUp. - * @property {boolean} isUp - * @default - */ + * If the Pointer is not touching the touchscreen, or *all* mouse or pen buttons are up, isUp is set to true. + * If you need to check a specific mouse or pen button then use the button properties, i.e. Pointer.rightButton.isUp. + * @property {boolean} isUp + * @default + */ this.isUp = true; /** - * @property {number} timeDown - A timestamp representing when the Pointer first touched the touchscreen. - * @default - */ + * @property {number} timeDown - A timestamp representing when the Pointer first touched the touchscreen. + * @default + */ this.timeDown = 0; /** - * @property {number} timeUp - A timestamp representing when the Pointer left the touchscreen. - * @default - */ + * @property {number} timeUp - A timestamp representing when the Pointer left the touchscreen. + * @default + */ this.timeUp = 0; /** - * @property {number} previousTapTime - A timestamp representing when the Pointer was last tapped or clicked. - * @default - */ + * @property {number} previousTapTime - A timestamp representing when the Pointer was last tapped or clicked. + * @default + */ this.previousTapTime = 0; /** - * @property {number} totalTouches - The total number of times this Pointer has been touched to the touchscreen. - * @default - */ + * @property {number} totalTouches - The total number of times this Pointer has been touched to the touchscreen. + * @default + */ this.totalTouches = 0; /** - * @property {number} msSinceLastClick - The number of milliseconds since the last click or touch event. - * @default - */ + * @property {number} msSinceLastClick - The number of milliseconds since the last click or touch event. + * @default + */ this.msSinceLastClick = Number.MAX_VALUE; /** - * @property {any} targetObject - The Game Object this Pointer is currently over / touching / dragging. - * @default - */ + * @property {any} targetObject - The Game Object this Pointer is currently over / touching / dragging. + * @default + */ this.targetObject = null; /** - * This array is erased and re-populated every time this Pointer is updated. It contains references to all - * of the Game Objects that were considered as being valid for processing by this Pointer, this frame. To be - * valid they must have suitable a `priorityID`, be Input enabled, visible and actually have the Pointer over - * them. You can check the contents of this array in events such as `onInputDown`, but beware it is reset - * every frame. - * @property {array} interactiveCandidates - * @default - */ + * This array is erased and re-populated every time this Pointer is updated. It contains references to all + * of the Game Objects that were considered as being valid for processing by this Pointer, this frame. To be + * valid they must have suitable a `priorityID`, be Input enabled, visible and actually have the Pointer over + * them. You can check the contents of this array in events such as `onInputDown`, but beware it is reset + * every frame. + * @property {array} interactiveCandidates + * @default + */ this.interactiveCandidates = []; /** - * @property {boolean} active - An active pointer is one that is currently pressed down on the display. A Mouse is always active. - * @default - */ + * @property {boolean} active - An active pointer is one that is currently pressed down on the display. A Mouse is always active. + * @default + */ this.active = false; /** - * @property {boolean} dirty - A dirty pointer needs to re-poll any interactive objects it may have been over, regardless if it has moved or not. - * @default - */ + * @property {boolean} dirty - A dirty pointer needs to re-poll any interactive objects it may have been over, regardless if it has moved or not. + * @default + */ this.dirty = false; /** - * @property {Phaser.Point} position - A Phaser.Point object containing the current x/y values of the pointer on the display. - */ + * @property {Phaser.Point} position - A Phaser.Point object containing the current x/y values of the pointer on the display. + */ this.position = new Phaser.Point(); /** - * @property {Phaser.Point} positionDown - A Phaser.Point object containing the x/y values of the pointer when it was last in a down state on the display. - */ + * @property {Phaser.Point} positionDown - A Phaser.Point object containing the x/y values of the pointer when it was last in a down state on the display. + */ this.positionDown = new Phaser.Point(); /** - * @property {Phaser.Point} positionUp - A Phaser.Point object containing the x/y values of the pointer when it was last released. - */ + * @property {Phaser.Point} positionUp - A Phaser.Point object containing the x/y values of the pointer when it was last released. + */ this.positionUp = new Phaser.Point(); /** - * A Phaser.Circle that is centered on the x/y coordinates of this pointer, useful for hit detection. - * The Circle size is 44px (Apples recommended "finger tip" size). - * @property {Phaser.Circle} circle - */ + * A Phaser.Circle that is centered on the x/y coordinates of this pointer, useful for hit detection. + * The Circle size is 44px (Apples recommended "finger tip" size). + * @property {Phaser.Circle} circle + */ this.circle = new Phaser.Circle(0, 0, 44); /** - * Click trampolines associated with this pointer. See `addClickTrampoline`. - * @property {object[]|null} _clickTrampolines - * @private - */ + * Click trampolines associated with this pointer. See `addClickTrampoline`. + * @property {object[]|null} _clickTrampolines + * @private + */ this._clickTrampolines = null; /** - * When the Pointer has click trampolines the last target object is stored here - * so it can be used to check for validity of the trampoline in a post-Up/'stop'. - * @property {object} _trampolineTargetObject - * @private - */ + * When the Pointer has click trampolines the last target object is stored here + * so it can be used to check for validity of the trampoline in a post-Up/'stop'. + * @property {object} _trampolineTargetObject + * @private + */ this._trampolineTargetObject = null; - }; /** -* No buttons at all. -* @constant -* @type {number} -*/ + * No buttons at all. + * @constant + * @type {number} + */ Phaser.Pointer.NO_BUTTON = 0; /** -* The Left Mouse button, or in PointerEvent devices a Touch contact or Pen contact. -* @constant -* @type {number} -*/ + * The Left Mouse button, or in PointerEvent devices a Touch contact or Pen contact. + * @constant + * @type {number} + */ Phaser.Pointer.LEFT_BUTTON = 1; /** -* The Right Mouse button, or in PointerEvent devices a Pen contact with a barrel button. -* @constant -* @type {number} -*/ + * The Right Mouse button, or in PointerEvent devices a Pen contact with a barrel button. + * @constant + * @type {number} + */ Phaser.Pointer.RIGHT_BUTTON = 2; /** -* The Middle Mouse button. -* @constant -* @type {number} -*/ + * The Middle Mouse button. + * @constant + * @type {number} + */ Phaser.Pointer.MIDDLE_BUTTON = 4; /** -* The X1 button. This is typically the mouse Back button, but is often reconfigured. -* On Linux (GTK) this is unsupported. On Windows if advanced pointer software (such as IntelliPoint) is installed this doesn't register. -* @constant -* @type {number} -*/ + * The X1 button. This is typically the mouse Back button, but is often reconfigured. + * On Linux (GTK) this is unsupported. On Windows if advanced pointer software (such as IntelliPoint) is installed this doesn't register. + * @constant + * @type {number} + */ Phaser.Pointer.BACK_BUTTON = 8; /** -* The X2 button. This is typically the mouse Forward button, but is often reconfigured. -* On Linux (GTK) this is unsupported. On Windows if advanced pointer software (such as IntelliPoint) is installed this doesn't register. -* @constant -* @type {number} -*/ + * The X2 button. This is typically the mouse Forward button, but is often reconfigured. + * On Linux (GTK) this is unsupported. On Windows if advanced pointer software (such as IntelliPoint) is installed this doesn't register. + * @constant + * @type {number} + */ Phaser.Pointer.FORWARD_BUTTON = 16; /** -* The Eraser pen button on PointerEvent supported devices only. -* @constant -* @type {number} -*/ + * The Eraser pen button on PointerEvent supported devices only. + * @constant + * @type {number} + */ Phaser.Pointer.ERASER_BUTTON = 32; Phaser.Pointer.prototype = { /** - * Resets the states of all the button booleans. - * - * @method Phaser.Pointer#resetButtons - * @protected - */ + * Resets the states of all the button booleans. + * + * @method Phaser.Pointer#resetButtons + * @protected + */ resetButtons: function () { - this.isDown = false; this.isUp = true; @@ -437,20 +434,18 @@ Phaser.Pointer.prototype = { this.forwardButton.reset(); this.eraserButton.reset(); } - }, /** - * Called by processButtonsUpDown. - * - * @method Phaser.Pointer#processButtonsDown - * @private - * @param {integer} button - {@link https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/button MouseEvent#button} value. - * @param {MouseEvent} event - The DOM event. - */ + * Called by processButtonsUpDown. + * + * @method Phaser.Pointer#processButtonsDown + * @private + * @param {integer} button - {@link https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/button MouseEvent#button} value. + * @param {MouseEvent} event - The DOM event. + */ processButtonsDown: function (button, event) { - switch (button) { case (Phaser.Mouse.LEFT_BUTTON): @@ -473,20 +468,18 @@ Phaser.Pointer.prototype = { this.forwardButton.start(event); break; } - }, /** - * Called by processButtonsUpDown. - * - * @method Phaser.Pointer#processButtonsUp - * @private - * @param {integer} button - {@link https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/button MouseEvent#button} value. - * @param {MouseEvent} event - The DOM event. - */ + * Called by processButtonsUpDown. + * + * @method Phaser.Pointer#processButtonsUp + * @private + * @param {integer} button - {@link https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/button MouseEvent#button} value. + * @param {MouseEvent} event - The DOM event. + */ processButtonsUp: function (button, event) { - switch (button) { case (Phaser.Mouse.LEFT_BUTTON): @@ -509,20 +502,18 @@ Phaser.Pointer.prototype = { this.forwardButton.stop(event); break; } - }, /** - * Called by updateButtons. - * - * @method Phaser.Pointer#processButtonsUpDown - * @private - * @param {integer} buttons - {@link https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/buttons MouseEvent#buttons} value. - * @param {MouseEvent} event - The DOM event. - */ + * Called by updateButtons. + * + * @method Phaser.Pointer#processButtonsUpDown + * @private + * @param {integer} buttons - {@link https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/buttons MouseEvent#buttons} value. + * @param {MouseEvent} event - The DOM event. + */ processButtonsUpDown: function (buttons, event) { - var type = event.type.toLowerCase().substr(-4); var down = (type === 'down'); var move = (type === 'move'); @@ -545,8 +536,10 @@ Phaser.Pointer.prototype = { } else { - // No buttons property (like Safari on OSX when using a trackpad) - // Attempt to use event.button property or fallback to default + /* + * No buttons property (like Safari on OSX when using a trackpad) + * Attempt to use event.button property or fallback to default + */ if (event.button !== undefined) { // On OS X (and other devices with trackpads) you have to press CTRL + the pad to initiate a right-click event. @@ -583,20 +576,18 @@ Phaser.Pointer.prototype = { this.rightButton.stop(event); } } - }, /** - * Called when the event.buttons property changes from zero. - * Contains a button bitmask. - * - * @method Phaser.Pointer#updateButtons - * @protected - * @param {MouseEvent} event - The DOM event. - */ + * Called when the event.buttons property changes from zero. + * Contains a button bitmask. + * + * @method Phaser.Pointer#updateButtons + * @protected + * @param {MouseEvent} event - The DOM event. + */ updateButtons: function (event) { - this.button = event.button; this.processButtonsUpDown(event.buttons, event); @@ -608,17 +599,15 @@ Phaser.Pointer.prototype = { this.isUp = false; this.isDown = true; } - }, /** - * Called when the Pointer is pressed onto the touchscreen. - * @method Phaser.Pointer#start - * @param {any} event - The DOM event from the browser. - */ + * Called when the Pointer is pressed onto the touchscreen. + * @method Phaser.Pointer#start + * @param {any} event - The DOM event from the browser. + */ start: function (event) { - var input = this.game.input; if (event.pointerId) @@ -679,16 +668,14 @@ Phaser.Pointer.prototype = { } return this; - }, /** - * Called by the Input Manager. - * @method Phaser.Pointer#update - */ + * Called by the Input Manager. + * @method Phaser.Pointer#update + */ update: function () { - var input = this.game.input; if (this.active) @@ -732,19 +719,17 @@ Phaser.Pointer.prototype = { } } } - }, /** - * Called when the Pointer is moved. - * - * @method Phaser.Pointer#move - * @param {MouseEvent|PointerEvent|TouchEvent} event - The event passed up from the input handler. - * @param {boolean} [fromClick=false] - Was this called from the click event? - */ + * Called when the Pointer is moved. + * + * @method Phaser.Pointer#move + * @param {MouseEvent|PointerEvent|TouchEvent} event - The event passed up from the input handler. + * @param {boolean} [fromClick=false] - Was this called from the click event? + */ move: function (event, fromClick) { - var input = this.game.input; if (input.pollLocked) @@ -824,27 +809,27 @@ Phaser.Pointer.prototype = { } return this; - }, /** - * Process all interactive objects to find out which ones were updated in the recent Pointer move. - * - * @method Phaser.Pointer#processInteractiveObjects - * @protected - * @param {boolean} [fromClick=false] - Was this called from the click event? - * @return {boolean} True if this method processes an object (i.e. a Sprite becomes the Pointers currentTarget), otherwise false. - */ + * Process all interactive objects to find out which ones were updated in the recent Pointer move. + * + * @method Phaser.Pointer#processInteractiveObjects + * @protected + * @param {boolean} [fromClick=false] - Was this called from the click event? + * @return {boolean} True if this method processes an object (i.e. a Sprite becomes the Pointers currentTarget), otherwise false. + */ processInteractiveObjects: function (fromClick) { - // Work out which object is on the top var highestRenderOrderID = 0; var highestInputPriorityID = -1; var candidateTarget = null; - // First pass gets all objects that the pointer is over that DON'T use pixelPerfect checks and get the highest ID - // We know they'll be valid for input detection but not which is the top just yet + /* + * First pass gets all objects that the pointer is over that DON'T use pixelPerfect checks and get the highest ID + * We know they'll be valid for input detection but not which is the top just yet + */ var currentNode = this.game.input.interactiveItems.first; @@ -873,9 +858,11 @@ Phaser.Pointer.prototype = { currentNode = this.game.input.interactiveItems.next; } - // Then in the second sweep we process ONLY the pixel perfect ones that are checked and who have a higher ID - // because if their ID is lower anyway then we can just automatically discount them - // (A node that was previously checked did not request a pixel-perfect check.) + /* + * Then in the second sweep we process ONLY the pixel perfect ones that are checked and who have a higher ID + * because if their ID is lower anyway then we can just automatically discount them + * (A node that was previously checked did not request a pixel-perfect check.) + */ currentNode = this.game.input.interactiveItems.first; @@ -905,24 +892,22 @@ Phaser.Pointer.prototype = { this.swapTarget(candidateTarget, false); return (this.targetObject !== null); - }, /** - * This will change the `Pointer.targetObject` object to be the one provided. - * - * This allows you to have fine-grained control over which object the Pointer is targeting. - * - * Note that even if you set a new Target here, it is still able to be replaced by any other valid - * target during the next Pointer update. - * - * @method Phaser.Pointer#swapTarget - * @param {Phaser.InputHandler} newTarget - The new target for this Pointer. Note this is an `InputHandler`, so don't pass a Sprite, instead pass `sprite.input` to it. - * @param {boolean} [silent=false] - If true the new target AND the old one will NOT dispatch their `onInputOver` or `onInputOut` events. - */ + * This will change the `Pointer.targetObject` object to be the one provided. + * + * This allows you to have fine-grained control over which object the Pointer is targeting. + * + * Note that even if you set a new Target here, it is still able to be replaced by any other valid + * target during the next Pointer update. + * + * @method Phaser.Pointer#swapTarget + * @param {Phaser.InputHandler} newTarget - The new target for this Pointer. Note this is an `InputHandler`, so don't pass a Sprite, instead pass `sprite.input` to it. + * @param {boolean} [silent=false] - If true the new target AND the old one will NOT dispatch their `onInputOver` or `onInputOut` events. + */ swapTarget: function (newTarget, silent) { - if (silent === undefined) { silent = false; } // Now we know the top-most item (if any) we can process it @@ -963,32 +948,28 @@ Phaser.Pointer.prototype = { this.targetObject._pointerOverHandler(this, silent); } } - }, /** - * Called when the Pointer leaves the target area. - * - * @method Phaser.Pointer#leave - * @param {MouseEvent|PointerEvent|TouchEvent} event - The event passed up from the input handler. - */ + * Called when the Pointer leaves the target area. + * + * @method Phaser.Pointer#leave + * @param {MouseEvent|PointerEvent|TouchEvent} event - The event passed up from the input handler. + */ leave: function (event) { - this.withinGame = false; this.move(event, false); - }, /** - * Called when the Pointer leaves the touchscreen. - * - * @method Phaser.Pointer#stop - * @param {MouseEvent|PointerEvent|TouchEvent} event - The event passed up from the input handler. - */ + * Called when the Pointer leaves the touchscreen. + * + * @method Phaser.Pointer#stop + * @param {MouseEvent|PointerEvent|TouchEvent} event - The event passed up from the input handler. + */ stop: function (event) { - var input = this.game.input; if (this._stateReset && this.withinGame) @@ -1054,63 +1035,57 @@ Phaser.Pointer.prototype = { this.targetObject = null; return this; - }, /** - * The Pointer is considered justPressed if the time it was pressed onto the touchscreen or clicked is less than justPressedRate. - * Note that calling justPressed doesn't reset the pressed status of the Pointer, it will return `true` for as long as the duration is valid. - * If you wish to check if the Pointer was pressed down just once then see the Sprite.events.onInputDown event. - * @method Phaser.Pointer#justPressed - * @param {number} [duration] - The time to check against. If none given it will use InputManager.justPressedRate. - * @return {boolean} true if the Pointer was pressed down within the duration given. - */ + * The Pointer is considered justPressed if the time it was pressed onto the touchscreen or clicked is less than justPressedRate. + * Note that calling justPressed doesn't reset the pressed status of the Pointer, it will return `true` for as long as the duration is valid. + * If you wish to check if the Pointer was pressed down just once then see the Sprite.events.onInputDown event. + * @method Phaser.Pointer#justPressed + * @param {number} [duration] - The time to check against. If none given it will use InputManager.justPressedRate. + * @return {boolean} true if the Pointer was pressed down within the duration given. + */ justPressed: function (duration) { - duration = duration || this.game.input.justPressedRate; return (this.isDown === true && (this.timeDown + duration) > this.game.time.time); - }, /** - * The Pointer is considered justReleased if the time it left the touchscreen is less than justReleasedRate. - * Note that calling justReleased doesn't reset the pressed status of the Pointer, it will return `true` for as long as the duration is valid. - * If you wish to check if the Pointer was released just once then see the Sprite.events.onInputUp event. - * @method Phaser.Pointer#justReleased - * @param {number} [duration] - The time to check against. If none given it will use InputManager.justReleasedRate. - * @return {boolean} true if the Pointer was released within the duration given. - */ + * The Pointer is considered justReleased if the time it left the touchscreen is less than justReleasedRate. + * Note that calling justReleased doesn't reset the pressed status of the Pointer, it will return `true` for as long as the duration is valid. + * If you wish to check if the Pointer was released just once then see the Sprite.events.onInputUp event. + * @method Phaser.Pointer#justReleased + * @param {number} [duration] - The time to check against. If none given it will use InputManager.justReleasedRate. + * @return {boolean} true if the Pointer was released within the duration given. + */ justReleased: function (duration) { - duration = duration || this.game.input.justReleasedRate; return (this.isUp && (this.timeUp + duration) > this.game.time.time); - }, /** - * Add a click trampoline to this pointer. - * - * A click trampoline is a callback that is run on the DOM 'click' event; this is primarily - * needed with certain browsers (ie. IE11) which restrict some actions like requestFullscreen - * to the DOM 'click' event and rejects it for 'pointer*' and 'mouse*' events. - * - * This is used internally by the ScaleManager; click trampoline usage is uncommon. - * Click trampolines can only be added to pointers that are currently down. - * - * @method Phaser.Pointer#addClickTrampoline - * @protected - * @param {string} name - The name of the trampoline; must be unique among active trampolines in this pointer. - * @param {function} callback - Callback to run/trampoline. - * @param {object} callbackContext - Context of the callback. - * @param {object[]|null} callbackArgs - Additional callback args, if any. Supplied as an array. - */ + * Add a click trampoline to this pointer. + * + * A click trampoline is a callback that is run on the DOM 'click' event; this is primarily + * needed with certain browsers (ie. IE11) which restrict some actions like requestFullscreen + * to the DOM 'click' event and rejects it for 'pointer*' and 'mouse*' events. + * + * This is used internally by the ScaleManager; click trampoline usage is uncommon. + * Click trampolines can only be added to pointers that are currently down. + * + * @method Phaser.Pointer#addClickTrampoline + * @protected + * @param {string} name - The name of the trampoline; must be unique among active trampolines in this pointer. + * @param {function} callback - Callback to run/trampoline. + * @param {object} callbackContext - Context of the callback. + * @param {object[]|null} callbackArgs - Additional callback args, if any. Supplied as an array. + */ addClickTrampoline: function (name, callback, callbackContext, callbackArgs) { - if (!this.isDown) { return; @@ -1134,17 +1109,15 @@ Phaser.Pointer.prototype = { callbackContext: callbackContext, callbackArgs: callbackArgs }); - }, /** - * Fire all click trampolines for which the pointers are still referring to the registered object. - * @method Phaser.Pointer#processClickTrampolines - * @private - */ + * Fire all click trampolines for which the pointers are still referring to the registered object. + * @method Phaser.Pointer#processClickTrampolines + * @private + */ processClickTrampolines: function () { - var trampolines = this._clickTrampolines; if (!trampolines) @@ -1164,16 +1137,14 @@ Phaser.Pointer.prototype = { this._clickTrampolines = null; this._trampolineTargetObject = null; - }, /** - * Resets the Pointer properties. Called by InputManager.reset when you perform a State change. - * @method Phaser.Pointer#reset - */ + * Resets the Pointer properties. Called by InputManager.reset when you perform a State change. + * @method Phaser.Pointer#reset + */ reset: function () { - if (this.isMouse === false) { this.active = false; @@ -1195,7 +1166,6 @@ Phaser.Pointer.prototype = { } this.targetObject = null; - }, /** @@ -1204,10 +1174,8 @@ Phaser.Pointer.prototype = { */ resetMovement: function () { - this.movementX = 0; this.movementY = 0; - } }; @@ -1215,89 +1183,83 @@ Phaser.Pointer.prototype = { Phaser.Pointer.prototype.constructor = Phaser.Pointer; /** -* How long the Pointer has been depressed on the touchscreen or *any* of the mouse buttons have been held down. -* If not currently down it returns -1. -* If you need to test a specific mouse or pen button then access the buttons directly, i.e. `Pointer.rightButton.duration`. -* -* @name Phaser.Pointer#duration -* @property {number} duration -* @readonly -*/ + * How long the Pointer has been depressed on the touchscreen or *any* of the mouse buttons have been held down. + * If not currently down it returns -1. + * If you need to test a specific mouse or pen button then access the buttons directly, i.e. `Pointer.rightButton.duration`. + * + * @name Phaser.Pointer#duration + * @property {number} duration + * @readonly + */ Object.defineProperty(Phaser.Pointer.prototype, 'duration', { get: function () { - if (this.isUp) { return -1; } return this.game.time.time - this.timeDown; - } }); /** -* Gets the X value of this Pointer in world coordinates based on the world camera. -* @name Phaser.Pointer#worldX -* @property {number} worldX - The X value of this Pointer in world coordinates based on the world camera. -* @readonly -*/ + * Gets the X value of this Pointer in world coordinates based on the world camera. + * @name Phaser.Pointer#worldX + * @property {number} worldX - The X value of this Pointer in world coordinates based on the world camera. + * @readonly + */ Object.defineProperty(Phaser.Pointer.prototype, 'worldX', { get: function () { - return this.game.world.camera.x + this.x; - } }); /** -* Gets the Y value of this Pointer in world coordinates based on the world camera. -* @name Phaser.Pointer#worldY -* @property {number} worldY - The Y value of this Pointer in world coordinates based on the world camera. -* @readonly -*/ + * Gets the Y value of this Pointer in world coordinates based on the world camera. + * @name Phaser.Pointer#worldY + * @property {number} worldY - The Y value of this Pointer in world coordinates based on the world camera. + * @readonly + */ Object.defineProperty(Phaser.Pointer.prototype, 'worldY', { get: function () { - return this.game.world.camera.y + this.y; - } }); /** -* Enumeration categorizing operational modes of pointers. -* -* PointerType values represent valid bitmasks. -* For example, a value representing both Mouse and Touch devices -* can be expressed as `PointerMode.CURSOR | PointerMode.CONTACT`. -* -* Values may be added for future mode categorizations. -* @class Phaser.PointerMode -*/ + * Enumeration categorizing operational modes of pointers. + * + * PointerType values represent valid bitmasks. + * For example, a value representing both Mouse and Touch devices + * can be expressed as `PointerMode.CURSOR | PointerMode.CONTACT`. + * + * Values may be added for future mode categorizations. + * @class Phaser.PointerMode + */ Phaser.PointerMode = { /** - * A 'CURSOR' is a pointer with a *passive cursor* such as a mouse, touchpad, watcom stylus, or even TV-control arrow-pad. - * - * It has the property that a cursor is passively moved without activating the input. - * This currently corresponds with {@link Phaser.Pointer#isMouse} property. - * @constant - */ + * A 'CURSOR' is a pointer with a *passive cursor* such as a mouse, touchpad, watcom stylus, or even TV-control arrow-pad. + * + * It has the property that a cursor is passively moved without activating the input. + * This currently corresponds with {@link Phaser.Pointer#isMouse} property. + * @constant + */ CURSOR: 1 << 0, /** - * A 'CONTACT' pointer has an *active cursor* that only tracks movement when actived; notably this is a touch-style input. - * @constant - */ + * A 'CONTACT' pointer has an *active cursor* that only tracks movement when actived; notably this is a touch-style input. + * @constant + */ CONTACT: 1 << 1 }; diff --git a/src/input/PointerLock.js b/src/input/PointerLock.js index f6fb8400e..3356598b5 100644 --- a/src/input/PointerLock.js +++ b/src/input/PointerLock.js @@ -1,99 +1,99 @@ /** -* The pointer lock input handler. -* @class -* @constructor -* @param {Phaser.Game} game -*/ + * The pointer lock input handler. + * @class + * @constructor + * @param {Phaser.Game} game + */ Phaser.PointerLock = function (game) { /** - * The currently running game. - * @type {Phaser.Game} - */ + * The currently running game. + * @type {Phaser.Game} + */ this.game = game; /** - * The Input Manager. - * @type {Phaser.Input} - */ + * The Input Manager. + * @type {Phaser.Input} + */ this.input = game.input; /** - * The element where event listeners are added. - * @type {HTMLElement} - */ + * The element where event listeners are added. + * @type {HTMLElement} + */ this.element = game.canvas; /** - * Whether the input handler is active. - * @type {boolean} - * @readOnly - */ + * Whether the input handler is active. + * @type {boolean} + * @readOnly + */ this.active = false; /** - * Whether the pointer is locked to the game canvas. - * @type {boolean} - */ + * Whether the pointer is locked to the game canvas. + * @type {boolean} + */ this.locked = false; /** - * A signal dispatched when the pointer is locked or unlocked. - * Its arguments are {@link Phaser.PointerLock#locked} and the original event from the browser. - * @type {Phaser.Signal} - */ + * A signal dispatched when the pointer is locked or unlocked. + * Its arguments are {@link Phaser.PointerLock#locked} and the original event from the browser. + * @type {Phaser.Signal} + */ this.onChange = new Phaser.Signal(); /** - * A signal dispatched when a request to lock or unlock the pointer fails. - * Its argument is the original event from the browser. - * @type {Phaser.Signal} - */ + * A signal dispatched when a request to lock or unlock the pointer fails. + * Its argument is the original event from the browser. + * @type {Phaser.Signal} + */ this.onError = new Phaser.Signal(); /** - * The 'pointerlockchange' handler, bound to this instance. - * @type {function} - * @private - */ + * The 'pointerlockchange' handler, bound to this instance. + * @type {function} + * @private + */ this.boundOnChangeHandler = this.onChangeHandler.bind(this); /** - * The 'pointerlockerror' handler, bound to this instance. - * @type {function} - * @private - */ + * The 'pointerlockerror' handler, bound to this instance. + * @type {function} + * @private + */ this.boundOnErrorHandler = this.onErrorHandler.bind(this); var device = game.device; /** - * The name of the 'pointerLockElement' property (or its equivalent) on this device. - * @type {?string} - * @private - */ + * The name of the 'pointerLockElement' property (or its equivalent) on this device. + * @type {?string} + * @private + */ this.pointerLockElement = device.pointerLockElement; /** - * The name of the 'pointerlockchange' event (or its equivalent) on this device. - * @type {?string} - * @private - */ + * The name of the 'pointerlockchange' event (or its equivalent) on this device. + * @type {?string} + * @private + */ this.pointerlockchange = device.pointerlockchange; /** - * The name of the 'pointerlockerror' event (or its equivalent) on this device. - * @type {?string} - * @private - */ + * The name of the 'pointerlockerror' event (or its equivalent) on this device. + * @type {?string} + * @private + */ this.pointerlockerror = device.pointerlockerror; }; /** -* Activates the handler, unless already active or Pointer Lock is unsupported on this device. -* @method Phaser.PointerLock#start -* @return {boolean} - True if the handler was started, otherwise false. -*/ + * Activates the handler, unless already active or Pointer Lock is unsupported on this device. + * @method Phaser.PointerLock#start + * @return {boolean} - True if the handler was started, otherwise false. + */ Phaser.PointerLock.prototype.start = function () { if (!this.game.device.pointerLock || this.active) @@ -120,9 +120,9 @@ Phaser.PointerLock.prototype.start = function () }; /** -* Deactivates the handler. -* @method Phaser.PointerLock#stop -*/ + * Deactivates the handler. + * @method Phaser.PointerLock#stop + */ Phaser.PointerLock.prototype.stop = function () { if (this.active) @@ -135,10 +135,10 @@ Phaser.PointerLock.prototype.stop = function () }; /** -* Requests the browser to lock the pointer to the game canvas. -* Use onChange and onError to track the result of the request. -* @method Phaser.PointerLock#request -*/ + * Requests the browser to lock the pointer to the game canvas. + * Use onChange and onError to track the result of the request. + * @method Phaser.PointerLock#request + */ Phaser.PointerLock.prototype.request = function () { if (!this.active || this.locked) @@ -150,22 +150,22 @@ Phaser.PointerLock.prototype.request = function () }; /** -* Releases the locked pointer. -* Use onChange and onError to track the result of the request. -* @method Phaser.PointerLock#exit -*/ + * Releases the locked pointer. + * Use onChange and onError to track the result of the request. + * @method Phaser.PointerLock#exit + */ Phaser.PointerLock.prototype.exit = function () { document.exitPointerLock(); }; /** -* Handles the 'pointerlockchange' event from the browser. -* @method Phaser.PointerLock#onChangeHandler -* @private -* @param {Event} event -* @emits Phaser.PointerLock#onChange -*/ + * Handles the 'pointerlockchange' event from the browser. + * @method Phaser.PointerLock#onChangeHandler + * @private + * @param {Event} event + * @emits Phaser.PointerLock#onChange + */ Phaser.PointerLock.prototype.onChangeHandler = function (event) { this.locked = (document[this.pointerLockElement] === this.element); @@ -174,12 +174,12 @@ Phaser.PointerLock.prototype.onChangeHandler = function (event) }; /** -* Handles the 'pointerlockerror' event from the browser. -* @method Phaser.PointerLock#onErrorHandler -* @private -* @param {Event} event -* @emits Phaser.PointerLock#onError -*/ + * Handles the 'pointerlockerror' event from the browser. + * @method Phaser.PointerLock#onErrorHandler + * @private + * @param {Event} event + * @emits Phaser.PointerLock#onError + */ Phaser.PointerLock.prototype.onErrorHandler = function (event) { this.onError.dispatch(event); diff --git a/src/input/SinglePad.js b/src/input/SinglePad.js index 1b3e29ecf..a04a1f0d5 100644 --- a/src/input/SinglePad.js +++ b/src/input/SinglePad.js @@ -1,135 +1,132 @@ /** -* @author @karlmacklin -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author @karlmacklin + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* A single Phaser Gamepad -* -* @class Phaser.SinglePad -* @constructor -* @param {Phaser.Game} game - Current game instance. -* @param {object} padParent - The parent Phaser.Gamepad object (all gamepads reside under this) -*/ + * A single Phaser Gamepad + * + * @class Phaser.SinglePad + * @constructor + * @param {Phaser.Game} game - Current game instance. + * @param {object} padParent - The parent Phaser.Gamepad object (all gamepads reside under this) + */ Phaser.SinglePad = function (game, padParent) { - /** - * @property {Phaser.Game} game - Local reference to game. - */ + * @property {Phaser.Game} game - Local reference to game. + */ this.game = game; /** - * @property {number} index - The gamepad index as per browsers data - * @readonly - */ + * @property {number} index - The gamepad index as per browsers data + * @readonly + */ this.index = null; /** - * @property {boolean} connected - Whether or not this particular gamepad is connected or not. - * @readonly - */ + * @property {boolean} connected - Whether or not this particular gamepad is connected or not. + * @readonly + */ this.connected = false; /** - * @property {object} callbackContext - The context under which the callbacks are run. - */ + * @property {object} callbackContext - The context under which the callbacks are run. + */ this.callbackContext = this; /** - * @property {function} onConnectCallback - This callback is invoked every time this gamepad is connected - */ + * @property {function} onConnectCallback - This callback is invoked every time this gamepad is connected + */ this.onConnectCallback = null; /** - * @property {function} onDisconnectCallback - This callback is invoked every time this gamepad is disconnected - */ + * @property {function} onDisconnectCallback - This callback is invoked every time this gamepad is disconnected + */ this.onDisconnectCallback = null; /** - * @property {function} onDownCallback - This callback is invoked every time a button is pressed down. - */ + * @property {function} onDownCallback - This callback is invoked every time a button is pressed down. + */ this.onDownCallback = null; /** - * @property {function} onUpCallback - This callback is invoked every time a gamepad button is released. - */ + * @property {function} onUpCallback - This callback is invoked every time a gamepad button is released. + */ this.onUpCallback = null; /** - * @property {function} onAxisCallback - This callback is invoked every time an axis is changed. - */ + * @property {function} onAxisCallback - This callback is invoked every time an axis is changed. + */ this.onAxisCallback = null; /** - * @property {function} onFloatCallback - This callback is invoked every time a button is changed to a value where value > 0 and value < 1. - */ + * @property {function} onFloatCallback - This callback is invoked every time a button is changed to a value where value > 0 and value < 1. + */ this.onFloatCallback = null; /** - * @property {number} deadZone - Dead zone for axis feedback - within this value you won't trigger updates. - */ + * @property {number} deadZone - Dead zone for axis feedback - within this value you won't trigger updates. + */ this.deadZone = 0.26; /** - * @property {Phaser.Gamepad} padParent - Main Phaser Gamepad object - * @private - */ + * @property {Phaser.Gamepad} padParent - Main Phaser Gamepad object + * @private + */ this._padParent = padParent; /** - * @property {object} _rawPad - The 'raw' gamepad data. - * @private - */ + * @property {object} _rawPad - The 'raw' gamepad data. + * @private + */ this._rawPad = null; /** - * @property {number} _prevTimestamp - Used to check for differences between earlier polls and current state of gamepads. - * @private - */ + * @property {number} _prevTimestamp - Used to check for differences between earlier polls and current state of gamepads. + * @private + */ this._prevTimestamp = null; /** - * @property {Array} _buttons - Array of Phaser.DeviceButton objects. This array is populated when the gamepad is connected. - * @private - */ + * @property {Array} _buttons - Array of Phaser.DeviceButton objects. This array is populated when the gamepad is connected. + * @private + */ this._buttons = []; /** - * @property {number} _buttonsLen - Length of the _buttons array. - * @private - */ + * @property {number} _buttonsLen - Length of the _buttons array. + * @private + */ this._buttonsLen = 0; /** - * @property {Array} _axes - Current axes state. - * @private - */ + * @property {Array} _axes - Current axes state. + * @private + */ this._axes = []; /** - * @property {number} _axesLen - Length of the _axes array. - * @private - */ + * @property {number} _axesLen - Length of the _axes array. + * @private + */ this._axesLen = 0; - }; Phaser.SinglePad.prototype = { /** - * Add callbacks to this Gamepad to handle connect / disconnect / button down / button up / axis change / float value buttons. - * - * @method Phaser.SinglePad#addCallbacks - * @param {object} context - The context under which the callbacks are run. - * @param {object} callbacks - Object that takes six different callbak methods: - * onConnectCallback, onDisconnectCallback, onDownCallback, onUpCallback, onAxisCallback, onFloatCallback - */ + * Add callbacks to this Gamepad to handle connect / disconnect / button down / button up / axis change / float value buttons. + * + * @method Phaser.SinglePad#addCallbacks + * @param {object} context - The context under which the callbacks are run. + * @param {object} callbacks - Object that takes six different callbak methods: + * onConnectCallback, onDisconnectCallback, onDownCallback, onUpCallback, onAxisCallback, onFloatCallback + */ addCallbacks: function (context, callbacks) { - if (typeof callbacks !== 'undefined') { this.onConnectCallback = (typeof callbacks.onConnect === 'function') ? callbacks.onConnect : this.onConnectCallback; @@ -144,16 +141,15 @@ Phaser.SinglePad.prototype = { }, /** - * Gets a DeviceButton object from this controller to be stored and referenced locally. - * The DeviceButton object can then be polled, have events attached to it, etc. - * - * @method Phaser.SinglePad#getButton - * @param {number} buttonCode - The buttonCode of the button, i.e. Phaser.Gamepad.BUTTON_0, Phaser.Gamepad.XBOX360_A, etc. - * @return {Phaser.DeviceButton} The DeviceButton object which you can store locally and reference directly. - */ + * Gets a DeviceButton object from this controller to be stored and referenced locally. + * The DeviceButton object can then be polled, have events attached to it, etc. + * + * @method Phaser.SinglePad#getButton + * @param {number} buttonCode - The buttonCode of the button, i.e. Phaser.Gamepad.BUTTON_0, Phaser.Gamepad.XBOX360_A, etc. + * @return {Phaser.DeviceButton} The DeviceButton object which you can store locally and reference directly. + */ getButton: function (buttonCode) { - if (this._buttons[buttonCode]) { return this._buttons[buttonCode]; @@ -162,17 +158,15 @@ Phaser.SinglePad.prototype = { { return null; } - }, /** - * Main update function called by Phaser.Gamepad. - * - * @method Phaser.SinglePad#pollStatus - */ + * Main update function called by Phaser.Gamepad. + * + * @method Phaser.SinglePad#pollStatus + */ pollStatus: function () { - if (!this.connected || !this.game.input.enabled || !this.game.input.gamepad.enabled || !this._rawPad || this._rawPad.timestamp && this._rawPad.timestamp === this._prevTimestamp) { return; @@ -214,18 +208,16 @@ Phaser.SinglePad.prototype = { } this._prevTimestamp = this._rawPad.timestamp; - }, /** - * Gamepad connect function, should be called by Phaser.Gamepad. - * - * @method Phaser.SinglePad#connect - * @param {object} rawPad - The raw gamepad object - */ + * Gamepad connect function, should be called by Phaser.Gamepad. + * + * @method Phaser.SinglePad#connect + * @param {object} rawPad - The raw gamepad object + */ connect: function (rawPad) { - var triggerCallback = !this.connected; this.connected = true; @@ -259,17 +251,15 @@ Phaser.SinglePad.prototype = { { this.onConnectCallback.call(this.callbackContext); } - }, /** - * Gamepad disconnect function, should be called by Phaser.Gamepad. - * - * @method Phaser.SinglePad#disconnect - */ + * Gamepad disconnect function, should be called by Phaser.Gamepad. + * + * @method Phaser.SinglePad#disconnect + */ disconnect: function () { - var triggerCallback = this.connected; var disconnectingIndex = this.index; @@ -298,7 +288,6 @@ Phaser.SinglePad.prototype = { { this.onDisconnectCallback.call(this.callbackContext); } - }, /** @@ -308,7 +297,6 @@ Phaser.SinglePad.prototype = { */ destroy: function () { - this._rawPad = undefined; for (var i = 0; i < this._buttonsLen; i++) @@ -328,18 +316,16 @@ Phaser.SinglePad.prototype = { this.onUpCallback = null; this.onAxisCallback = null; this.onFloatCallback = null; - }, /** - * Handles changes in axis. - * - * @method Phaser.SinglePad#processAxisChange - * @param {object} axisState - State of the relevant axis - */ + * Handles changes in axis. + * + * @method Phaser.SinglePad#processAxisChange + * @param {object} axisState - State of the relevant axis + */ processAxisChange: function (index, value) { - if (this._axes[index] === value) { return; @@ -356,19 +342,17 @@ Phaser.SinglePad.prototype = { { this.onAxisCallback.call(this.callbackContext, this, index, value); } - }, /** - * Handles button down press. - * - * @method Phaser.SinglePad#processButtonDown - * @param {number} buttonCode - Which buttonCode of this button - * @param {object} value - Button value - */ + * Handles button down press. + * + * @method Phaser.SinglePad#processButtonDown + * @param {number} buttonCode - Which buttonCode of this button + * @param {object} value - Button value + */ processButtonDown: function (buttonCode, value) { - if (this._buttons[buttonCode]) { this._buttons[buttonCode].start(null, value); @@ -383,19 +367,17 @@ Phaser.SinglePad.prototype = { { this.onDownCallback.call(this.callbackContext, buttonCode, value); } - }, /** - * Handles button release. - * - * @method Phaser.SinglePad#processButtonUp - * @param {number} buttonCode - Which buttonCode of this button - * @param {object} value - Button value - */ + * Handles button release. + * + * @method Phaser.SinglePad#processButtonUp + * @param {number} buttonCode - Which buttonCode of this button + * @param {object} value - Button value + */ processButtonUp: function (buttonCode, value) { - if (this._padParent.onUpCallback) { this._padParent.onUpCallback.call(this._padParent.callbackContext, buttonCode, value, this.index); @@ -410,19 +392,17 @@ Phaser.SinglePad.prototype = { { this._buttons[buttonCode].stop(null, value); } - }, /** - * Handles buttons with floating values (like analog buttons that acts almost like an axis but still registers like a button) - * - * @method Phaser.SinglePad#processButtonFloat - * @param {number} buttonCode - Which buttonCode of this button - * @param {object} value - Button value (will range somewhere between 0 and 1, but not specifically 0 or 1. - */ + * Handles buttons with floating values (like analog buttons that acts almost like an axis but still registers like a button) + * + * @method Phaser.SinglePad#processButtonFloat + * @param {number} buttonCode - Which buttonCode of this button + * @param {object} value - Button value (will range somewhere between 0 and 1, but not specifically 0 or 1. + */ processButtonFloat: function (buttonCode, value) { - if (this._padParent.onFloatCallback) { this._padParent.onFloatCallback.call(this._padParent.callbackContext, buttonCode, value, this.index); @@ -437,135 +417,120 @@ Phaser.SinglePad.prototype = { { this._buttons[buttonCode].padFloat(value); } - }, /** - * Returns value of requested axis. - * - * @method Phaser.SinglePad#axis - * @param {number} axisCode - The index of the axis to check - * @return {number} Axis value if available otherwise false - */ + * Returns value of requested axis. + * + * @method Phaser.SinglePad#axis + * @param {number} axisCode - The index of the axis to check + * @return {number} Axis value if available otherwise false + */ axis: function (axisCode) { - if (this._axes[axisCode]) { return this._axes[axisCode]; } return false; - }, /** - * Returns true if the button is pressed down. - * - * @method Phaser.SinglePad#isDown - * @param {number} buttonCode - The buttonCode of the button to check. - * @return {boolean} True if the button is pressed down. - */ + * Returns true if the button is pressed down. + * + * @method Phaser.SinglePad#isDown + * @param {number} buttonCode - The buttonCode of the button to check. + * @return {boolean} True if the button is pressed down. + */ isDown: function (buttonCode) { - if (this._buttons[buttonCode]) { return this._buttons[buttonCode].isDown; } return false; - }, /** - * Returns true if the button is not currently pressed. - * - * @method Phaser.SinglePad#isUp - * @param {number} buttonCode - The buttonCode of the button to check. - * @return {boolean} True if the button is not currently pressed down. - */ + * Returns true if the button is not currently pressed. + * + * @method Phaser.SinglePad#isUp + * @param {number} buttonCode - The buttonCode of the button to check. + * @return {boolean} True if the button is not currently pressed down. + */ isUp: function (buttonCode) { - if (this._buttons[buttonCode]) { return this._buttons[buttonCode].isUp; } return false; - }, /** - * Returns the "just released" state of a button from this gamepad. Just released is considered as being true if the button was released within the duration given (default 250ms). - * - * @method Phaser.SinglePad#justReleased - * @param {number} buttonCode - The buttonCode of the button to check for. - * @param {number} [duration=250] - The duration below which the button is considered as being just released. - * @return {boolean} True if the button is just released otherwise false. - */ + * Returns the "just released" state of a button from this gamepad. Just released is considered as being true if the button was released within the duration given (default 250ms). + * + * @method Phaser.SinglePad#justReleased + * @param {number} buttonCode - The buttonCode of the button to check for. + * @param {number} [duration=250] - The duration below which the button is considered as being just released. + * @return {boolean} True if the button is just released otherwise false. + */ justReleased: function (buttonCode, duration) { - if (this._buttons[buttonCode]) { return this._buttons[buttonCode].justReleased(duration); } - }, /** - * Returns the "just pressed" state of a button from this gamepad. Just pressed is considered true if the button was pressed down within the duration given (default 250ms). - * - * @method Phaser.SinglePad#justPressed - * @param {number} buttonCode - The buttonCode of the button to check for. - * @param {number} [duration=250] - The duration below which the button is considered as being just pressed. - * @return {boolean} True if the button is just pressed otherwise false. - */ + * Returns the "just pressed" state of a button from this gamepad. Just pressed is considered true if the button was pressed down within the duration given (default 250ms). + * + * @method Phaser.SinglePad#justPressed + * @param {number} buttonCode - The buttonCode of the button to check for. + * @param {number} [duration=250] - The duration below which the button is considered as being just pressed. + * @return {boolean} True if the button is just pressed otherwise false. + */ justPressed: function (buttonCode, duration) { - if (this._buttons[buttonCode]) { return this._buttons[buttonCode].justPressed(duration); } - }, /** - * Returns the value of a gamepad button. Intended mainly for cases when you have floating button values, for example - * analog trigger buttons on the XBOX 360 controller. - * - * @method Phaser.SinglePad#buttonValue - * @param {number} buttonCode - The buttonCode of the button to check. - * @return {number} Button value if available otherwise null. Be careful as this can incorrectly evaluate to 0. - */ + * Returns the value of a gamepad button. Intended mainly for cases when you have floating button values, for example + * analog trigger buttons on the XBOX 360 controller. + * + * @method Phaser.SinglePad#buttonValue + * @param {number} buttonCode - The buttonCode of the button to check. + * @return {number} Button value if available otherwise null. Be careful as this can incorrectly evaluate to 0. + */ buttonValue: function (buttonCode) { - if (this._buttons[buttonCode]) { return this._buttons[buttonCode].value; } return null; - }, /** - * Reset all buttons/axes of this gamepad. - * - * @method Phaser.SinglePad#reset - */ + * Reset all buttons/axes of this gamepad. + * + * @method Phaser.SinglePad#reset + */ reset: function () { - for (var j = 0; j < this._axes.length; j++) { this._axes[j] = 0; } - } }; diff --git a/src/input/Touch.js b/src/input/Touch.js index 61bffabc1..b81acf715 100644 --- a/src/input/Touch.js +++ b/src/input/Touch.js @@ -1,140 +1,137 @@ /** -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* Phaser.Touch handles touch events with your game. Note: Android 2.x only supports 1 touch event at once, no multi-touch. -* -* You should not normally access this class directly, but instead use a Phaser.Pointer object which normalises all game input for you. -* -* @class Phaser.Touch -* @constructor -* @param {Phaser.Game} game - A reference to the currently running game. -*/ + * Phaser.Touch handles touch events with your game. Note: Android 2.x only supports 1 touch event at once, no multi-touch. + * + * You should not normally access this class directly, but instead use a Phaser.Pointer object which normalises all game input for you. + * + * @class Phaser.Touch + * @constructor + * @param {Phaser.Game} game - A reference to the currently running game. + */ Phaser.Touch = function (game) { - /** - * @property {Phaser.Game} game - A reference to the currently running game. - */ + * @property {Phaser.Game} game - A reference to the currently running game. + */ this.game = game; /** - * Whether the input handler is active. - * @property {boolean} active - * @readOnly - */ + * Whether the input handler is active. + * @property {boolean} active + * @readOnly + */ this.active = false; /** - * Touch events will only be processed if enabled. - * @property {boolean} enabled - * @default - */ + * Touch events will only be processed if enabled. + * @property {boolean} enabled + * @default + */ this.enabled = true; /** - * @property {object} callbackContext - The context under which callbacks are called. - */ + * @property {object} callbackContext - The context under which callbacks are called. + */ this.callbackContext = this.game; /** - * @property {function} touchStartCallback - A callback that can be fired on a touchStart event. - */ + * @property {function} touchStartCallback - A callback that can be fired on a touchStart event. + */ this.touchStartCallback = null; /** - * @property {function} touchMoveCallback - A callback that can be fired on a touchMove event. - */ + * @property {function} touchMoveCallback - A callback that can be fired on a touchMove event. + */ this.touchMoveCallback = null; /** - * @property {function} touchEndCallback - A callback that can be fired on a touchEnd event. - */ + * @property {function} touchEndCallback - A callback that can be fired on a touchEnd event. + */ this.touchEndCallback = null; /** - * @property {function} touchEnterCallback - A callback that can be fired on a touchEnter event. - */ + * @property {function} touchEnterCallback - A callback that can be fired on a touchEnter event. + */ this.touchEnterCallback = null; /** - * @property {function} touchLeaveCallback - A callback that can be fired on a touchLeave event. - */ + * @property {function} touchLeaveCallback - A callback that can be fired on a touchLeave event. + */ this.touchLeaveCallback = null; /** - * @property {function} touchCancelCallback - A callback that can be fired on a touchCancel event. - */ + * @property {function} touchCancelCallback - A callback that can be fired on a touchCancel event. + */ this.touchCancelCallback = null; /** - * @property {boolean} preventDefault - If true the TouchEvent will have prevent.default called on it. - * @default - */ + * @property {boolean} preventDefault - If true the TouchEvent will have prevent.default called on it. + * @default + */ this.preventDefault = true; /** - * @property {TouchEvent} event - The browser touch DOM event. Will be set to null if no touch event has ever been received. - * @default - */ + * @property {TouchEvent} event - The browser touch DOM event. Will be set to null if no touch event has ever been received. + * @default + */ this.event = null; /** - * @property {function} _onTouchStart - Internal event handler reference. - * @private - */ + * @property {function} _onTouchStart - Internal event handler reference. + * @private + */ this._onTouchStart = null; /** - * @property {function} _onTouchMove - Internal event handler reference. - * @private - */ + * @property {function} _onTouchMove - Internal event handler reference. + * @private + */ this._onTouchMove = null; /** - * @property {function} _onTouchEnd - Internal event handler reference. - * @private - */ + * @property {function} _onTouchEnd - Internal event handler reference. + * @private + */ this._onTouchEnd = null; /** - * @property {function} _onTouchEnter - Internal event handler reference. - * @private - */ + * @property {function} _onTouchEnter - Internal event handler reference. + * @private + */ this._onTouchEnter = null; /** - * @property {function} _onTouchLeave - Internal event handler reference. - * @private - */ + * @property {function} _onTouchLeave - Internal event handler reference. + * @private + */ this._onTouchLeave = null; /** - * @property {function} _onTouchCancel - Internal event handler reference. - * @private - */ + * @property {function} _onTouchCancel - Internal event handler reference. + * @private + */ this._onTouchCancel = null; /** - * @property {function} _onTouchMove - Internal event handler reference. - * @private - */ + * @property {function} _onTouchMove - Internal event handler reference. + * @private + */ this._onTouchMove = null; - }; Phaser.Touch.prototype = { /** - * Starts the event listeners running. - * @method Phaser.Touch#start - */ + * Starts the event listeners running. + * @method Phaser.Touch#start + */ start: function () { - if (!this.game.device.touch) { return false; @@ -192,33 +189,29 @@ Phaser.Touch.prototype = { this.active = true; return true; - }, /** - * Consumes all touchmove events on the document (only enable this if you know you need it!). - * @method Phaser.Touch#consumeTouchMove - */ + * Consumes all touchmove events on the document (only enable this if you know you need it!). + * @method Phaser.Touch#consumeTouchMove + */ consumeDocumentTouches: function () { - this._documentTouchMove = function (event) { event.preventDefault(); }; document.addEventListener('touchmove', this._documentTouchMove, false); - }, /** - * The internal method that handles the touchstart event from the browser. - * @method Phaser.Touch#onTouchStart - * @param {TouchEvent} event - The native event from the browser. This gets stored in Touch.event. - */ + * The internal method that handles the touchstart event from the browser. + * @method Phaser.Touch#onTouchStart + * @param {TouchEvent} event - The native event from the browser. This gets stored in Touch.event. + */ onTouchStart: function (event) { - this.game.input.executeTouchLockCallbacks(false, event); this.event = event; @@ -238,25 +231,25 @@ Phaser.Touch.prototype = { event.preventDefault(); } - // event.targetTouches = list of all touches on the TARGET ELEMENT (i.e. game dom element) - // event.touches = list of all touches on the ENTIRE DOCUMENT, not just the target element - // event.changedTouches = the touches that CHANGED in this event, not the total number of them + /* + * event.targetTouches = list of all touches on the TARGET ELEMENT (i.e. game dom element) + * event.touches = list of all touches on the ENTIRE DOCUMENT, not just the target element + * event.changedTouches = the touches that CHANGED in this event, not the total number of them + */ for (var i = 0; i < event.changedTouches.length; i++) { this.game.input.startPointer(event.changedTouches[i]); } - }, /** - * Touch cancel - touches that were disrupted (perhaps by moving into a plugin or browser chrome). - * Occurs for example on iOS when you put down 4 fingers and the app selector UI appears. - * @method Phaser.Touch#onTouchCancel - * @param {TouchEvent} event - The native event from the browser. This gets stored in Touch.event. - */ + * Touch cancel - touches that were disrupted (perhaps by moving into a plugin or browser chrome). + * Occurs for example on iOS when you put down 4 fingers and the app selector UI appears. + * @method Phaser.Touch#onTouchCancel + * @param {TouchEvent} event - The native event from the browser. This gets stored in Touch.event. + */ onTouchCancel: function (event) { - this.event = event; if (this.touchCancelCallback) @@ -274,24 +267,24 @@ Phaser.Touch.prototype = { event.preventDefault(); } - // Touch cancel - touches that were disrupted (perhaps by moving into a plugin or browser chrome) - // http://www.w3.org/TR/touch-events/#dfn-touchcancel + /* + * Touch cancel - touches that were disrupted (perhaps by moving into a plugin or browser chrome) + * http://www.w3.org/TR/touch-events/#dfn-touchcancel + */ for (var i = 0; i < event.changedTouches.length; i++) { this.game.input.stopPointer(event.changedTouches[i]); } - }, /** - * For touch enter and leave its a list of the touch points that have entered or left the target. - * Doesn't appear to be supported by most browsers on a canvas element yet. - * @method Phaser.Touch#onTouchEnter - * @param {TouchEvent} event - The native event from the browser. This gets stored in Touch.event. - */ + * For touch enter and leave its a list of the touch points that have entered or left the target. + * Doesn't appear to be supported by most browsers on a canvas element yet. + * @method Phaser.Touch#onTouchEnter + * @param {TouchEvent} event - The native event from the browser. This gets stored in Touch.event. + */ onTouchEnter: function (event) { - this.event = event; if (this.touchEnterCallback) @@ -308,18 +301,16 @@ Phaser.Touch.prototype = { { event.preventDefault(); } - }, /** - * For touch enter and leave its a list of the touch points that have entered or left the target. - * Doesn't appear to be supported by most browsers on a canvas element yet. - * @method Phaser.Touch#onTouchLeave - * @param {TouchEvent} event - The native event from the browser. This gets stored in Touch.event. - */ + * For touch enter and leave its a list of the touch points that have entered or left the target. + * Doesn't appear to be supported by most browsers on a canvas element yet. + * @method Phaser.Touch#onTouchLeave + * @param {TouchEvent} event - The native event from the browser. This gets stored in Touch.event. + */ onTouchLeave: function (event) { - this.event = event; if (this.touchLeaveCallback) @@ -331,17 +322,15 @@ Phaser.Touch.prototype = { { event.preventDefault(); } - }, /** - * The handler for the touchmove events. - * @method Phaser.Touch#onTouchMove - * @param {TouchEvent} event - The native event from the browser. This gets stored in Touch.event. - */ + * The handler for the touchmove events. + * @method Phaser.Touch#onTouchMove + * @param {TouchEvent} event - The native event from the browser. This gets stored in Touch.event. + */ onTouchMove: function (event) { - this.event = event; if (this.touchMoveCallback) @@ -358,17 +347,15 @@ Phaser.Touch.prototype = { { this.game.input.updatePointer(event.changedTouches[i]); } - }, /** - * The handler for the touchend events. - * @method Phaser.Touch#onTouchEnd - * @param {TouchEvent} event - The native event from the browser. This gets stored in Touch.event. - */ + * The handler for the touchend events. + * @method Phaser.Touch#onTouchEnd + * @param {TouchEvent} event - The native event from the browser. This gets stored in Touch.event. + */ onTouchEnd: function (event) { - this.game.input.executeTouchLockCallbacks(true, event); this.event = event; @@ -383,23 +370,23 @@ Phaser.Touch.prototype = { event.preventDefault(); } - // For touch end its a list of the touch points that have been removed from the surface - // https://developer.mozilla.org/en-US/docs/DOM/TouchList - // event.changedTouches = the touches that CHANGED in this event, not the total number of them + /* + * For touch end its a list of the touch points that have been removed from the surface + * https://developer.mozilla.org/en-US/docs/DOM/TouchList + * event.changedTouches = the touches that CHANGED in this event, not the total number of them + */ for (var i = 0; i < event.changedTouches.length; i++) { this.game.input.stopPointer(event.changedTouches[i]); } - }, /** - * Stop the event listeners. - * @method Phaser.Touch#stop - */ + * Stop the event listeners. + * @method Phaser.Touch#stop + */ stop: function () { - if (!this.game.device.touch) { return; @@ -413,7 +400,6 @@ Phaser.Touch.prototype = { this.game.canvas.removeEventListener('touchcancel', this._onTouchCancel); this.active = false; - } }; diff --git a/src/input/WheelEventProxy.js b/src/input/WheelEventProxy.js index 4fe4e34cc..74cb376a2 100644 --- a/src/input/WheelEventProxy.js +++ b/src/input/WheelEventProxy.js @@ -1,36 +1,34 @@ /** -* A purely internal event support class to proxy 'wheelscroll' and 'DOMMouseWheel' -* events to 'wheel'-like events. -* -* See https://developer.mozilla.org/en-US/docs/Web/Events/mousewheel for choosing a scale and delta mode. -* -* @class Phaser.WheelEventProxy -* @private -* @constructor -* @param {number} scaleFactor - Scale factor as applied to wheelDelta/wheelDeltaX or details. -* @param {integer} deltaMode - The reported delta mode. -*/ + * A purely internal event support class to proxy 'wheelscroll' and 'DOMMouseWheel' + * events to 'wheel'-like events. + * + * See https://developer.mozilla.org/en-US/docs/Web/Events/mousewheel for choosing a scale and delta mode. + * + * @class Phaser.WheelEventProxy + * @private + * @constructor + * @param {number} scaleFactor - Scale factor as applied to wheelDelta/wheelDeltaX or details. + * @param {integer} deltaMode - The reported delta mode. + */ Phaser.WheelEventProxy = function (scaleFactor, deltaMode) { - /** - * @property {number} _scaleFactor - Scale factor as applied to wheelDelta/wheelDeltaX or details. - * @private - */ + * @property {number} _scaleFactor - Scale factor as applied to wheelDelta/wheelDeltaX or details. + * @private + */ this._scaleFactor = scaleFactor; /** - * @property {number} _deltaMode - The reported delta mode. - * @private - */ + * @property {number} _deltaMode - The reported delta mode. + * @private + */ this._deltaMode = deltaMode; /** - * @property {any} originalEvent - The original event _currently_ being proxied; the getters will follow suit. - * @private - */ + * @property {any} originalEvent - The original event _currently_ being proxied; the getters will follow suit. + * @private + */ this.originalEvent = null; - }; Phaser.WheelEventProxy.prototype = {}; @@ -38,19 +36,16 @@ Phaser.WheelEventProxy.prototype.constructor = Phaser.WheelEventProxy; Phaser.WheelEventProxy.prototype.bindEvent = function (event) { - // Generate stubs automatically if (!Phaser.WheelEventProxy._stubsGenerated && event) { var makeBinder = function (name) { - return function () { var v = this.originalEvent[name]; return typeof v !== 'function' ? v : v.bind(this.originalEvent); }; - }; for (var prop in event) @@ -65,7 +60,6 @@ Phaser.WheelEventProxy.prototype.bindEvent = function (event) this.originalEvent = event; return this; - }; Object.defineProperties(Phaser.WheelEventProxy.prototype, { diff --git a/src/loader/Cache.js b/src/loader/Cache.js index 9f50ea4d0..51fa0939f 100644 --- a/src/loader/Cache.js +++ b/src/loader/Cache.js @@ -1,55 +1,54 @@ /** -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* Phaser has one single cache in which it stores all assets. -* -* The cache is split up into sections, such as images, sounds, video, json, etc. All assets are stored using -* a unique string-based key as their identifier. Assets stored in different areas of the cache can have the -* same key, for example 'playerWalking' could be used as the key for both a sprite sheet and an audio file, -* because they are unique data types. -* -* The cache is automatically populated by the Phaser.Loader. When you use the loader to pull in external assets -* such as images they are automatically placed into their respective cache. Most common Game Objects, such as -* Sprites and Videos automatically query the cache to extract the assets they need on instantiation. -* -* You can access the cache from within a State via `this.cache`. From here you can call any public method it has, -* including adding new entries to it, deleting them or querying them. -* -* Understand that almost without exception when you get an item from the cache it will return a reference to the -* item stored in the cache, not a copy of it. Therefore if you retrieve an item and then modify it, the original -* object in the cache will also be updated, even if you don't put it back into the cache again. -* -* By default when you change State the cache is _not_ cleared, although there is an option to clear it should -* your game require it. In a typical game set-up the cache is populated once after the main game has loaded and -* then used as an asset store. -* -* @class Phaser.Cache -* @constructor -* @param {Phaser.Game} game - A reference to the currently running game. -*/ + * Phaser has one single cache in which it stores all assets. + * + * The cache is split up into sections, such as images, sounds, video, json, etc. All assets are stored using + * a unique string-based key as their identifier. Assets stored in different areas of the cache can have the + * same key, for example 'playerWalking' could be used as the key for both a sprite sheet and an audio file, + * because they are unique data types. + * + * The cache is automatically populated by the Phaser.Loader. When you use the loader to pull in external assets + * such as images they are automatically placed into their respective cache. Most common Game Objects, such as + * Sprites and Videos automatically query the cache to extract the assets they need on instantiation. + * + * You can access the cache from within a State via `this.cache`. From here you can call any public method it has, + * including adding new entries to it, deleting them or querying them. + * + * Understand that almost without exception when you get an item from the cache it will return a reference to the + * item stored in the cache, not a copy of it. Therefore if you retrieve an item and then modify it, the original + * object in the cache will also be updated, even if you don't put it back into the cache again. + * + * By default when you change State the cache is _not_ cleared, although there is an option to clear it should + * your game require it. In a typical game set-up the cache is populated once after the main game has loaded and + * then used as an asset store. + * + * @class Phaser.Cache + * @constructor + * @param {Phaser.Game} game - A reference to the currently running game. + */ Phaser.Cache = function (game) { - /** - * @property {Phaser.Game} game - Local reference to game. - */ + * @property {Phaser.Game} game - Local reference to game. + */ this.game = game; /** - * Automatically resolve resource URLs to absolute paths for use with the Cache.getURL method. - * @property {boolean} autoResolveURL - */ + * Automatically resolve resource URLs to absolute paths for use with the Cache.getURL method. + * @property {boolean} autoResolveURL + */ this.autoResolveURL = false; /** - * The main cache object into which all resources are placed. - * @property {object} _cache - * @private - */ + * The main cache object into which all resources are placed. + * @property {object} _cache + * @private + */ this._cache = { canvas: {}, image: {}, @@ -71,32 +70,32 @@ Phaser.Cache = function (game) }; /** - * @property {object} _urlMap - Maps URLs to resources. - * @private - */ + * @property {object} _urlMap - Maps URLs to resources. + * @private + */ this._urlMap = {}; /** - * @property {Image} _urlResolver - Used to resolve URLs to the absolute path. - * @private - */ + * @property {Image} _urlResolver - Used to resolve URLs to the absolute path. + * @private + */ this._urlResolver = new Image(); /** - * @property {string} _urlTemp - Temporary variable to hold a resolved url. - * @private - */ + * @property {string} _urlTemp - Temporary variable to hold a resolved url. + * @private + */ this._urlTemp = null; /** - * @property {Phaser.Signal} onSoundUnlock - This event is dispatched when the sound system is unlocked via a touch event on cellular devices. - */ + * @property {Phaser.Signal} onSoundUnlock - This event is dispatched when the sound system is unlocked via a touch event on cellular devices. + */ this.onSoundUnlock = new Phaser.Signal(); /** - * @property {array} _cacheMap - Const to cache object look-up array. - * @private - */ + * @property {array} _cacheMap - Const to cache object look-up array. + * @private + */ this._cacheMap = []; this._cacheMap[Phaser.Cache.CANVAS] = this._cache.canvas; @@ -123,117 +122,116 @@ Phaser.Cache = function (game) this._pendingCount = 0; /** - * Dispatched when the DEFAULT and MISSING images have loaded (or the {@link #READY_TIMEOUT load timeout} was exceeded). - * - * @property {Phaser.Signal} onReady - */ + * Dispatched when the DEFAULT and MISSING images have loaded (or the {@link #READY_TIMEOUT load timeout} was exceeded). + * + * @property {Phaser.Signal} onReady + */ this.onReady = new Phaser.Signal(); this._addImages(); - }; /** -* @constant -* @type {number} -*/ + * @constant + * @type {number} + */ Phaser.Cache.CANVAS = 1; /** -* @constant -* @type {number} -*/ + * @constant + * @type {number} + */ Phaser.Cache.IMAGE = 2; /** -* @constant -* @type {number} -*/ + * @constant + * @type {number} + */ Phaser.Cache.TEXTURE = 3; /** -* @constant -* @type {number} -*/ + * @constant + * @type {number} + */ Phaser.Cache.SOUND = 4; /** -* @constant -* @type {number} -*/ + * @constant + * @type {number} + */ Phaser.Cache.TEXT = 5; /** -* @constant -* @type {number} -*/ + * @constant + * @type {number} + */ Phaser.Cache.PHYSICS = 6; /** -* @constant -* @type {number} -*/ + * @constant + * @type {number} + */ Phaser.Cache.TILEMAP = 7; /** -* @constant -* @type {number} -*/ + * @constant + * @type {number} + */ Phaser.Cache.BINARY = 8; /** -* @constant -* @type {number} -*/ + * @constant + * @type {number} + */ Phaser.Cache.BITMAPDATA = 9; /** -* @constant -* @type {number} -*/ + * @constant + * @type {number} + */ Phaser.Cache.BITMAPFONT = 10; /** -* @constant -* @type {number} -*/ + * @constant + * @type {number} + */ Phaser.Cache.JSON = 11; /** -* @constant -* @type {number} -*/ + * @constant + * @type {number} + */ Phaser.Cache.XML = 12; /** -* @constant -* @type {number} -*/ + * @constant + * @type {number} + */ Phaser.Cache.VIDEO = 13; /** -* @constant -* @type {number} -*/ + * @constant + * @type {number} + */ Phaser.Cache.SHADER = 14; /** -* @constant -* @type {number} -*/ + * @constant + * @type {number} + */ Phaser.Cache.RENDER_TEXTURE = 15; /** -* @constant -* @type {number} -*/ + * @constant + * @type {number} + */ Phaser.Cache.DATA = 16; /** -* The default image used for a texture when no other is specified. -* @constant -* @type {PIXI.Texture} -*/ + * The default image used for a texture when no other is specified. + * @constant + * @type {PIXI.Texture} + */ Phaser.Cache.DEFAULT = null; /** @@ -251,10 +249,10 @@ Phaser.Cache.DEFAULT_KEY = '__default'; Phaser.Cache.DEFAULT_SRC = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgAQMAAABJtOi3AAAAA1BMVEX///+nxBvIAAAAAXRSTlMAQObYZgAAABVJREFUeF7NwIEAAAAAgKD9qdeocAMAoAABm3DkcAAAAABJRU5ErkJggg=='; /** -* The default image used for a texture when the source image is missing. -* @constant -* @type {PIXI.Texture} -*/ + * The default image used for a texture when the source image is missing. + * @constant + * @type {PIXI.Texture} + */ Phaser.Cache.MISSING = null; /** @@ -272,33 +270,34 @@ Phaser.Cache.MISSING_KEY = '__missing'; Phaser.Cache.MISSING_SRC = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAIAAAD8GO2jAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAJ9JREFUeNq01ssOwyAMRFG46v//Mt1ESmgh+DFmE2GPOBARKb2NVjo+17PXLD8a1+pl5+A+wSgFygymWYHBb0FtsKhJDdZlncG2IzJ4ayoMDv20wTmSMzClEgbWYNTAkQ0Z+OJ+A/eWnAaR9+oxCF4Os0H8htsMUp+pwcgBBiMNnAwF8GqIgL2hAzaGFFgZauDPKABmowZ4GL369/0rwACp2yA/ttmvsQAAAABJRU5ErkJggg=='; /** -* The maximum amount of time (ms) to wait for the built-in DEFAULT and MISSING images to load. -* @static -* @type {number} -* @default -*/ + * The maximum amount of time (ms) to wait for the built-in DEFAULT and MISSING images to load. + * @static + * @type {number} + * @default + */ Phaser.Cache.READY_TIMEOUT = 1000; Phaser.Cache.prototype = { - // //////////////// - // Add Methods // - // //////////////// - - /** - * Add a new canvas object in to the cache. - * - * @method Phaser.Cache#addCompressedTextureMetaData - * @private - * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. - * @param {string} url - * @param {string} extension - * @param {array} arrayBuffer - * @return {object} The compressed texture entry. - */ + /* + * //////////////// + * Add Methods // + * //////////////// + */ + + /** + * Add a new canvas object in to the cache. + * + * @method Phaser.Cache#addCompressedTextureMetaData + * @private + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url + * @param {string} extension + * @param {array} arrayBuffer + * @return {object} The compressed texture entry. + */ addCompressedTextureMetaData: function (key, url, extension, arrayBuffer) { - if (this.checkImageKey(key)) { this.removeImage(key); @@ -323,41 +322,37 @@ Phaser.Cache.prototype = { this._resolveURL(url, texture); return texture; - }, /** - * Add a new canvas object in to the cache. - * - * @method Phaser.Cache#addCanvas - * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. - * @param {HTMLCanvasElement} canvas - The Canvas DOM element. - * @param {CanvasRenderingContext2D} [context] - The context of the canvas element. If not specified it will default go `getContext('2d')`. - */ + * Add a new canvas object in to the cache. + * + * @method Phaser.Cache#addCanvas + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {HTMLCanvasElement} canvas - The Canvas DOM element. + * @param {CanvasRenderingContext2D} [context] - The context of the canvas element. If not specified it will default go `getContext('2d')`. + */ addCanvas: function (key, canvas, context) { - if (context === undefined) { context = canvas.getContext('2d'); } this._cache.canvas[key] = { canvas: canvas, context: context }; - }, /** - * Adds an Image file into the Cache. The file must have already been loaded, typically via Phaser.Loader, but can also have been loaded into the DOM. - * If an image already exists in the cache with the same key then it is removed and destroyed, and the new image inserted in its place. - * - * If the image has not yet been fetched (successfully or not), a `console.warn` message will be displayed. - * - * @method Phaser.Cache#addImage - * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. - * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. - * @param {object} data - Extra image data. - * @return {object} The full image object that was added to the cache. - */ + * Adds an Image file into the Cache. The file must have already been loaded, typically via Phaser.Loader, but can also have been loaded into the DOM. + * If an image already exists in the cache with the same key then it is removed and destroyed, and the new image inserted in its place. + * + * If the image has not yet been fetched (successfully or not), a `console.warn` message will be displayed. + * + * @method Phaser.Cache#addImage + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. + * @param {object} data - Extra image data. + * @return {object} The full image object that was added to the cache. + */ addImage: function (key, url, data) { - if (this.checkImageKey(key)) { this.removeImage(key); @@ -393,7 +388,6 @@ Phaser.Cache.prototype = { } return img; - }, /** @@ -402,7 +396,6 @@ Phaser.Cache.prototype = { */ addImageAsync: function (key, src, callback) { - var self = this; var img = new Image(); @@ -415,21 +408,19 @@ Phaser.Cache.prototype = { this._addPending(); img.src = src; - }, /** - * Adds a default image to be used in special cases such as WebGL Filters. - * It uses the special reserved key of `__default`. - * This method is called automatically when the Cache is created. - * This image is skipped when `Cache.destroy` is called due to its internal requirements. - * - * @method Phaser.Cache#addDefaultImage - * @protected - */ + * Adds a default image to be used in special cases such as WebGL Filters. + * It uses the special reserved key of `__default`. + * This method is called automatically when the Cache is created. + * This image is skipped when `Cache.destroy` is called due to its internal requirements. + * + * @method Phaser.Cache#addDefaultImage + * @protected + */ addDefaultImage: function () { - this.addImageAsync(Phaser.Cache.DEFAULT_KEY, Phaser.Cache.DEFAULT_SRC, function (obj) { // Because we don't want to invalidate the sprite batch for an invisible texture @@ -438,42 +429,38 @@ Phaser.Cache.prototype = { // Make it easily available within the rest of Phaser / Pixi Phaser.Cache.DEFAULT = new PIXI.Texture(obj.base); }); - }, /** - * Adds an image to be used when a key is wrong / missing. - * It uses the special reserved key of `__missing`. - * This method is called automatically when the Cache is created. - * This image is skipped when `Cache.destroy` is called due to its internal requirements. - * - * @method Phaser.Cache#addMissingImage - * @protected - */ + * Adds an image to be used when a key is wrong / missing. + * It uses the special reserved key of `__missing`. + * This method is called automatically when the Cache is created. + * This image is skipped when `Cache.destroy` is called due to its internal requirements. + * + * @method Phaser.Cache#addMissingImage + * @protected + */ addMissingImage: function () { - this.addImageAsync(Phaser.Cache.MISSING_KEY, Phaser.Cache.MISSING_SRC, function (obj) { // Make it easily available within the rest of Phaser / Pixi Phaser.Cache.MISSING = new PIXI.Texture(obj.base); }); - }, /** - * Adds a Sound file into the Cache. The file must have already been loaded, typically via Phaser.Loader. - * - * @method Phaser.Cache#addSound - * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. - * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. - * @param {object} data - Extra sound data. - * @param {boolean} webAudio - True if the file is using web audio. - * @param {boolean} audioTag - True if the file is using legacy HTML audio. - */ + * Adds a Sound file into the Cache. The file must have already been loaded, typically via Phaser.Loader. + * + * @method Phaser.Cache#addSound + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. + * @param {object} data - Extra sound data. + * @param {boolean} webAudio - True if the file is using web audio. + * @param {boolean} audioTag - True if the file is using legacy HTML audio. + */ addSound: function (key, url, data, webAudio, audioTag) { - if (webAudio === undefined) { webAudio = true; audioTag = false; } if (audioTag === undefined) { webAudio = false; audioTag = true; } @@ -495,88 +482,78 @@ Phaser.Cache.prototype = { }; this._resolveURL(url, this._cache.sound[key]); - }, /** - * Add a new text data. - * - * @method Phaser.Cache#addText - * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. - * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. - * @param {object} data - Extra text data. - */ + * Add a new text data. + * + * @method Phaser.Cache#addText + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. + * @param {object} data - Extra text data. + */ addText: function (key, url, data) { - this._cache.text[key] = { url: url, data: data }; this._resolveURL(url, this._cache.text[key]); - }, /** - * Add a new physics data object to the Cache. - * - * @method Phaser.Cache#addPhysicsData - * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. - * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. - * @param {object} JSONData - The physics data object (a JSON file). - * @param {number} format - The format of the physics data. - */ + * Add a new physics data object to the Cache. + * + * @method Phaser.Cache#addPhysicsData + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. + * @param {object} JSONData - The physics data object (a JSON file). + * @param {number} format - The format of the physics data. + */ addPhysicsData: function (key, url, JSONData, format) { - this._cache.physics[key] = { url: url, data: JSONData, format: format }; this._resolveURL(url, this._cache.physics[key]); - }, /** - * Add a new tilemap to the Cache. - * - * @method Phaser.Cache#addTilemap - * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. - * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. - * @param {object} mapData - The tilemap data object (either a CSV or JSON file). - * @param {number} format - The format of the tilemap data. - */ + * Add a new tilemap to the Cache. + * + * @method Phaser.Cache#addTilemap + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. + * @param {object} mapData - The tilemap data object (either a CSV or JSON file). + * @param {number} format - The format of the tilemap data. + */ addTilemap: function (key, url, mapData, format) { - this._cache.tilemap[key] = { url: url, data: mapData, format: format }; this._resolveURL(url, this._cache.tilemap[key]); - }, /** - * Add a binary object in to the cache. - * - * @method Phaser.Cache#addBinary - * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. - * @param {object} binaryData - The binary object to be added to the cache. - */ + * Add a binary object in to the cache. + * + * @method Phaser.Cache#addBinary + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {object} binaryData - The binary object to be added to the cache. + */ addBinary: function (key, binaryData) { - this._cache.binary[key] = binaryData; - }, /** - * Add a BitmapData object to the cache. - * - * @method Phaser.Cache#addBitmapData - * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. - * @param {Phaser.BitmapData} bitmapData - The BitmapData object to be addded to the cache. - * @param {Phaser.FrameData|null} [frameData=(auto create)] - Optional FrameData set associated with the given BitmapData. If not specified (or `undefined`) a new FrameData object is created containing the Bitmap's Frame. If `null` is supplied then no FrameData will be created. - * @return {Phaser.BitmapData} The BitmapData object to be addded to the cache. - */ + * Add a BitmapData object to the cache. + * + * @method Phaser.Cache#addBitmapData + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {Phaser.BitmapData} bitmapData - The BitmapData object to be addded to the cache. + * @param {Phaser.FrameData|null} [frameData=(auto create)] - Optional FrameData set associated with the given BitmapData. If not specified (or `undefined`) a new FrameData object is created containing the Bitmap's Frame. If `null` is supplied then no FrameData will be created. + * @return {Phaser.BitmapData} The BitmapData object to be addded to the cache. + */ addBitmapData: function (key, bitmapData, frameData) { - bitmapData.key = key; if (frameData === undefined) @@ -588,24 +565,22 @@ Phaser.Cache.prototype = { this._cache.bitmapData[key] = { data: bitmapData, frameData: frameData }; return bitmapData; - }, /** - * Add a new Bitmap Font to the Cache. - * - * @method Phaser.Cache#addBitmapFont - * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. - * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. - * @param {object} data - Extra font data. - * @param {object} atlasData - The Bitmap Font data. - * @param {string} [atlasType='xml'] - The format of the Bitmap Font data file: `json` or `xml`. - * @param {number} [xSpacing=0] - If you'd like to add additional horizontal spacing between the characters then set the pixel value here. - * @param {number} [ySpacing=0] - If you'd like to add additional vertical spacing between the lines then set the pixel value here. - */ + * Add a new Bitmap Font to the Cache. + * + * @method Phaser.Cache#addBitmapFont + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. + * @param {object} data - Extra font data. + * @param {object} atlasData - The Bitmap Font data. + * @param {string} [atlasType='xml'] - The format of the Bitmap Font data file: `json` or `xml`. + * @param {number} [xSpacing=0] - If you'd like to add additional horizontal spacing between the characters then set the pixel value here. + * @param {number} [ySpacing=0] - If you'd like to add additional vertical spacing between the lines then set the pixel value here. + */ addBitmapFont: function (key, url, data, atlasData, atlasType, xSpacing, ySpacing) { - var obj = { url: url, data: data, @@ -628,32 +603,30 @@ Phaser.Cache.prototype = { this._cache.bitmapFont[key] = obj; this._resolveURL(url, obj); - }, /** - * Add a new Bitmap Font to the Cache, where the font texture is part of a Texture Atlas. - * - * The atlas must already exist in the cache, and be available based on the given `atlasKey`. - * - * The `atlasFrame` specifies the name of the frame within the atlas that the Bitmap Font is - * stored in. - * - * The `dataKey` is the key of the XML or JSON Bitmap Font Data, which must already be in - * the Cache. - * - * @method Phaser.Cache#addBitmapFontFromAtlas - * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. - * @param {string} atlasKey - The key of the Texture Atlas in the Cache. - * @param {string} atlasFrame - The frame of the Texture Atlas that the Bitmap Font is in. - * @param {string} dataKey - The key of the Bitmap Font data in the Cache - * @param {string} [dataType='xml'] - The format of the Bitmap Font data: `json` or `xml`. - * @param {number} [xSpacing=0] - If you'd like to add additional horizontal spacing between the characters then set the pixel value here. - * @param {number} [ySpacing=0] - If you'd like to add additional vertical spacing between the lines then set the pixel value here. - */ + * Add a new Bitmap Font to the Cache, where the font texture is part of a Texture Atlas. + * + * The atlas must already exist in the cache, and be available based on the given `atlasKey`. + * + * The `atlasFrame` specifies the name of the frame within the atlas that the Bitmap Font is + * stored in. + * + * The `dataKey` is the key of the XML or JSON Bitmap Font Data, which must already be in + * the Cache. + * + * @method Phaser.Cache#addBitmapFontFromAtlas + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} atlasKey - The key of the Texture Atlas in the Cache. + * @param {string} atlasFrame - The frame of the Texture Atlas that the Bitmap Font is in. + * @param {string} dataKey - The key of the Bitmap Font data in the Cache + * @param {string} [dataType='xml'] - The format of the Bitmap Font data: `json` or `xml`. + * @param {number} [xSpacing=0] - If you'd like to add additional horizontal spacing between the characters then set the pixel value here. + * @param {number} [ySpacing=0] - If you'd like to add additional vertical spacing between the lines then set the pixel value here. + */ addBitmapFontFromAtlas: function (key, atlasKey, atlasFrame, dataKey, dataType, xSpacing, ySpacing) { - var frame = this.getFrameByName(atlasKey, atlasFrame); if (!frame) @@ -684,109 +657,97 @@ Phaser.Cache.prototype = { } this._cache.bitmapFont[key] = obj; - }, /** - * Add a new json object into the cache. - * - * @method Phaser.Cache#addJSON - * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. - * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. - * @param {object} data - Extra json data. - */ + * Add a new json object into the cache. + * + * @method Phaser.Cache#addJSON + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. + * @param {object} data - Extra json data. + */ addJSON: function (key, url, data) { - this._cache.json[key] = { url: url, data: data }; this._resolveURL(url, this._cache.json[key]); - }, /** - * Add a new xml object into the cache. - * - * @method Phaser.Cache#addXML - * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. - * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. - * @param {object} data - Extra text data. - */ + * Add a new xml object into the cache. + * + * @method Phaser.Cache#addXML + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. + * @param {object} data - Extra text data. + */ addXML: function (key, url, data) { - this._cache.xml[key] = { url: url, data: data }; this._resolveURL(url, this._cache.xml[key]); - }, /** - * Adds a Video file into the Cache. The file must have already been loaded, typically via Phaser.Loader. - * - * @method Phaser.Cache#addVideo - * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. - * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. - * @param {object} data - Extra video data. - * @param {boolean} isBlob - True if the file was preloaded via xhr and the data parameter is a Blob. false if a Video tag was created instead. - */ + * Adds a Video file into the Cache. The file must have already been loaded, typically via Phaser.Loader. + * + * @method Phaser.Cache#addVideo + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. + * @param {object} data - Extra video data. + * @param {boolean} isBlob - True if the file was preloaded via xhr and the data parameter is a Blob. false if a Video tag was created instead. + */ addVideo: function (key, url, data, isBlob) { - this._cache.video[key] = { url: url, data: data, isBlob: isBlob, locked: true }; this._resolveURL(url, this._cache.video[key]); - }, /** - * Adds a Fragment Shader in to the Cache. The file must have already been loaded, typically via Phaser.Loader. - * - * @method Phaser.Cache#addShader - * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. - * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. - * @param {object} data - Extra shader data. - */ + * Adds a Fragment Shader in to the Cache. The file must have already been loaded, typically via Phaser.Loader. + * + * @method Phaser.Cache#addShader + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. + * @param {object} data - Extra shader data. + */ addShader: function (key, url, data) { - this._cache.shader[key] = { url: url, data: data }; this._resolveURL(url, this._cache.shader[key]); - }, /** - * Add a new Phaser.RenderTexture in to the cache. - * - * @method Phaser.Cache#addRenderTexture - * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. - * @param {Phaser.RenderTexture} texture - The texture to use as the base of the RenderTexture. - */ + * Add a new Phaser.RenderTexture in to the cache. + * + * @method Phaser.Cache#addRenderTexture + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {Phaser.RenderTexture} texture - The texture to use as the base of the RenderTexture. + */ addRenderTexture: function (key, texture) { - this._cache.renderTexture[key] = { texture: texture, frame: new Phaser.Frame(0, 0, 0, texture.width, texture.height, '', '') }; - }, /** - * Add a new sprite sheet in to the cache. - * - * @method Phaser.Cache#addSpriteSheet - * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. - * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. - * @param {object} data - Extra sprite sheet data. - * @param {number} frameWidth - Width of the sprite sheet. - * @param {number} frameHeight - Height of the sprite sheet. - * @param {number} [frameMax=-1] - How many frames stored in the sprite sheet. If -1 then it divides the whole sheet evenly. - * @param {number} [margin=0] - If the frames have been drawn with a margin, specify the amount here. - * @param {number} [spacing=0] - If the frames have been drawn with spacing between them, specify the amount here. - * @param {number} [skipFrames=0] - Skip a number of frames. Useful when there are multiple sprite sheets in one image. - */ + * Add a new sprite sheet in to the cache. + * + * @method Phaser.Cache#addSpriteSheet + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. + * @param {object} data - Extra sprite sheet data. + * @param {number} frameWidth - Width of the sprite sheet. + * @param {number} frameHeight - Height of the sprite sheet. + * @param {number} [frameMax=-1] - How many frames stored in the sprite sheet. If -1 then it divides the whole sheet evenly. + * @param {number} [margin=0] - If the frames have been drawn with a margin, specify the amount here. + * @param {number} [spacing=0] - If the frames have been drawn with spacing between them, specify the amount here. + * @param {number} [skipFrames=0] - Skip a number of frames. Useful when there are multiple sprite sheets in one image. + */ addSpriteSheet: function (key, url, data, frameWidth, frameHeight, frameMax, margin, spacing, skipFrames) { - if (frameMax === undefined) { frameMax = -1; } if (margin === undefined) { margin = 0; } if (spacing === undefined) { spacing = 0; } @@ -806,22 +767,20 @@ Phaser.Cache.prototype = { this._cache.image[key] = obj; this._resolveURL(url, obj); - }, /** - * Add a new texture atlas to the Cache. - * - * @method Phaser.Cache#addTextureAtlas - * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. - * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. - * @param {object} data - Extra texture atlas data. - * @param {object} atlasData - Texture atlas frames data. - * @param {number} format - The format of the texture atlas. - */ + * Add a new texture atlas to the Cache. + * + * @method Phaser.Cache#addTextureAtlas + * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache. + * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`. + * @param {object} data - Extra texture atlas data. + * @param {object} atlasData - Texture atlas frames data. + * @param {number} format - The format of the texture atlas. + */ addTextureAtlas: function (key, url, data, atlasData, format) { - var obj = { key: key, url: url, @@ -853,36 +812,34 @@ Phaser.Cache.prototype = { this._cache.image[key] = obj; this._resolveURL(url, obj); - }, /** - * Add a data item to the cache. - * - * @method Phaser.Cache#addData - * @param {string} key - The key of the data item. - * @param {any} data - The data. - */ + * Add a data item to the cache. + * + * @method Phaser.Cache#addData + * @param {string} key - The key of the data item. + * @param {any} data - The data. + */ addData: function (key, data) { - this._cache.data[key] = data; - }, - // ////////////////////////// - // Sound Related Methods // - // ////////////////////////// + /* + * ////////////////////////// + * Sound Related Methods // + * ////////////////////////// + */ /** - * Reload a Sound file from the server. - * - * @method Phaser.Cache#reloadSound - * @param {string} key - The key of the asset within the cache. - */ + * Reload a Sound file from the server. + * + * @method Phaser.Cache#reloadSound + * @param {string} key - The key of the asset within the cache. + */ reloadSound: function (key) { - var _this = this; var sound = this.getSound(key); @@ -898,18 +855,16 @@ Phaser.Cache.prototype = { sound.data.load(); } - }, /** - * Fires the onSoundUnlock event when the sound has completed reloading. - * - * @method Phaser.Cache#reloadSoundComplete - * @param {string} key - The key of the asset within the cache. - */ + * Fires the onSoundUnlock event when the sound has completed reloading. + * + * @method Phaser.Cache#reloadSoundComplete + * @param {string} key - The key of the asset within the cache. + */ reloadSoundComplete: function (key) { - var sound = this.getSound(key); if (sound) @@ -917,374 +872,332 @@ Phaser.Cache.prototype = { sound.locked = false; this.onSoundUnlock.dispatch(key); } - }, /** - * Updates the sound object in the cache. - * - * @method Phaser.Cache#updateSound - * @param {string} key - The key of the asset within the cache. - */ + * Updates the sound object in the cache. + * + * @method Phaser.Cache#updateSound + * @param {string} key - The key of the asset within the cache. + */ updateSound: function (key, property, value) { - var sound = this.getSound(key); if (sound) { sound[property] = value; } - }, /** - * Add a new decoded sound. - * - * @method Phaser.Cache#decodedSound - * @param {string} key - The key of the asset within the cache. - * @param {object} data - Extra sound data. - */ + * Add a new decoded sound. + * + * @method Phaser.Cache#decodedSound + * @param {string} key - The key of the asset within the cache. + * @param {object} data - Extra sound data. + */ decodedSound: function (key, data) { - var sound = this.getSound(key); sound.data = data; sound.decoded = true; sound.isDecoding = false; - }, /** - * Check if the given sound has finished decoding. - * - * @method Phaser.Cache#isSoundDecoded - * @param {string} key - The key of the asset within the cache. - * @return {boolean} The decoded state of the Sound object. - */ + * Check if the given sound has finished decoding. + * + * @method Phaser.Cache#isSoundDecoded + * @param {string} key - The key of the asset within the cache. + * @return {boolean} The decoded state of the Sound object. + */ isSoundDecoded: function (key) { - var sound = this.getItem(key, Phaser.Cache.SOUND, 'isSoundDecoded'); if (sound) { return sound.decoded; } - }, /** - * Check if the given sound is ready for playback. - * A sound is considered ready when it has finished decoding and the device is no longer touch locked. - * - * @method Phaser.Cache#isSoundReady - * @param {string} key - The key of the asset within the cache. - * @return {boolean} True if the sound is decoded and the device is not touch locked. - */ + * Check if the given sound is ready for playback. + * A sound is considered ready when it has finished decoding and the device is no longer touch locked. + * + * @method Phaser.Cache#isSoundReady + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the sound is decoded and the device is not touch locked. + */ isSoundReady: function (key) { - var sound = this.getItem(key, Phaser.Cache.SOUND, 'isSoundDecoded'); if (sound) { return (sound.decoded && !this.game.sound.touchLocked); } - }, - // ////////////////////// - // Check Key Methods // - // ////////////////////// + /* + * ////////////////////// + * Check Key Methods // + * ////////////////////// + */ /** - * Checks if a key for the given cache object type exists. - * - * @method Phaser.Cache#checkKey - * @param {integer} cache - The cache to search. One of the Cache consts such as `Phaser.Cache.IMAGE` or `Phaser.Cache.SOUND`. - * @param {string} key - The key of the asset within the cache. - * @return {boolean} True if the key exists, otherwise false. - */ + * Checks if a key for the given cache object type exists. + * + * @method Phaser.Cache#checkKey + * @param {integer} cache - The cache to search. One of the Cache consts such as `Phaser.Cache.IMAGE` or `Phaser.Cache.SOUND`. + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists, otherwise false. + */ checkKey: function (cache, key) { - if (this._cacheMap[cache][key]) { return true; } return false; - }, /** - * Checks if the given URL has been loaded into the Cache. - * This method will only work if Cache.autoResolveURL was set to `true` before any preloading took place. - * The method will make a DOM src call to the URL given, so please be aware of this for certain file types, such as Sound files on Firefox - * which may cause double-load instances. - * - * @method Phaser.Cache#checkURL - * @param {string} url - The url to check for in the cache. - * @return {boolean} True if the url exists, otherwise false. - */ + * Checks if the given URL has been loaded into the Cache. + * This method will only work if Cache.autoResolveURL was set to `true` before any preloading took place. + * The method will make a DOM src call to the URL given, so please be aware of this for certain file types, such as Sound files on Firefox + * which may cause double-load instances. + * + * @method Phaser.Cache#checkURL + * @param {string} url - The url to check for in the cache. + * @return {boolean} True if the url exists, otherwise false. + */ checkURL: function (url) { - if (this._urlMap[this._resolveURL(url)]) { return true; } return false; - }, /** - * Checks if the given key exists in the Canvas Cache. - * - * @method Phaser.Cache#checkCanvasKey - * @param {string} key - The key of the asset within the cache. - * @return {boolean} True if the key exists in the cache, otherwise false. - */ + * Checks if the given key exists in the Canvas Cache. + * + * @method Phaser.Cache#checkCanvasKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ checkCanvasKey: function (key) { - return this.checkKey(Phaser.Cache.CANVAS, key); - }, /** - * Checks if the given key exists in the Data Cache. - * - * @method Phaser.Cache#checkDataKey - * @param {string} key - The key of the data item. - * @return {boolean} True if the key exists in the cache, otherwise false. - */ + * Checks if the given key exists in the Data Cache. + * + * @method Phaser.Cache#checkDataKey + * @param {string} key - The key of the data item. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ checkDataKey: function (key) { - return this.checkKey(Phaser.Cache.DATA, key); - }, /** - * Checks if the given key exists in the Image Cache. Note that this also includes Texture Atlases, Sprite Sheets and Retro Fonts. - * - * @method Phaser.Cache#checkImageKey - * @param {string} key - The key of the asset within the cache. - * @return {boolean} True if the key exists in the cache, otherwise false. - */ + * Checks if the given key exists in the Image Cache. Note that this also includes Texture Atlases, Sprite Sheets and Retro Fonts. + * + * @method Phaser.Cache#checkImageKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ checkImageKey: function (key) { - return this.checkKey(Phaser.Cache.IMAGE, key); - }, /** - * Checks if the given key exists in the Texture Cache. - * - * @method Phaser.Cache#checkTextureKey - * @param {string} key - The key of the asset within the cache. - * @return {boolean} True if the key exists in the cache, otherwise false. - */ + * Checks if the given key exists in the Texture Cache. + * + * @method Phaser.Cache#checkTextureKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ checkTextureKey: function (key) { - return this.checkKey(Phaser.Cache.TEXTURE, key); - }, /** - * Checks if the given key exists in the Sound Cache. - * - * @method Phaser.Cache#checkSoundKey - * @param {string} key - The key of the asset within the cache. - * @return {boolean} True if the key exists in the cache, otherwise false. - */ + * Checks if the given key exists in the Sound Cache. + * + * @method Phaser.Cache#checkSoundKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ checkSoundKey: function (key) { - return this.checkKey(Phaser.Cache.SOUND, key); - }, /** - * Checks if the given key exists in the Text Cache. - * - * @method Phaser.Cache#checkTextKey - * @param {string} key - The key of the asset within the cache. - * @return {boolean} True if the key exists in the cache, otherwise false. - */ + * Checks if the given key exists in the Text Cache. + * + * @method Phaser.Cache#checkTextKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ checkTextKey: function (key) { - return this.checkKey(Phaser.Cache.TEXT, key); - }, /** - * Checks if the given key exists in the Physics Cache. - * - * @method Phaser.Cache#checkPhysicsKey - * @param {string} key - The key of the asset within the cache. - * @return {boolean} True if the key exists in the cache, otherwise false. - */ + * Checks if the given key exists in the Physics Cache. + * + * @method Phaser.Cache#checkPhysicsKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ checkPhysicsKey: function (key) { - return this.checkKey(Phaser.Cache.PHYSICS, key); - }, /** - * Checks if the given key exists in the Tilemap Cache. - * - * @method Phaser.Cache#checkTilemapKey - * @param {string} key - The key of the asset within the cache. - * @return {boolean} True if the key exists in the cache, otherwise false. - */ + * Checks if the given key exists in the Tilemap Cache. + * + * @method Phaser.Cache#checkTilemapKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ checkTilemapKey: function (key) { - return this.checkKey(Phaser.Cache.TILEMAP, key); - }, /** - * Checks if the given key exists in the Binary Cache. - * - * @method Phaser.Cache#checkBinaryKey - * @param {string} key - The key of the asset within the cache. - * @return {boolean} True if the key exists in the cache, otherwise false. - */ + * Checks if the given key exists in the Binary Cache. + * + * @method Phaser.Cache#checkBinaryKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ checkBinaryKey: function (key) { - return this.checkKey(Phaser.Cache.BINARY, key); - }, /** - * Checks if the given key exists in the BitmapData Cache. - * - * @method Phaser.Cache#checkBitmapDataKey - * @param {string} key - The key of the asset within the cache. - * @return {boolean} True if the key exists in the cache, otherwise false. - */ + * Checks if the given key exists in the BitmapData Cache. + * + * @method Phaser.Cache#checkBitmapDataKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ checkBitmapDataKey: function (key) { - return this.checkKey(Phaser.Cache.BITMAPDATA, key); - }, /** - * Checks if the given key exists in the BitmapFont Cache. - * - * @method Phaser.Cache#checkBitmapFontKey - * @param {string} key - The key of the asset within the cache. - * @return {boolean} True if the key exists in the cache, otherwise false. - */ + * Checks if the given key exists in the BitmapFont Cache. + * + * @method Phaser.Cache#checkBitmapFontKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ checkBitmapFontKey: function (key) { - return this.checkKey(Phaser.Cache.BITMAPFONT, key); - }, /** - * Checks if the given key exists in the JSON Cache. - * - * @method Phaser.Cache#checkJSONKey - * @param {string} key - The key of the asset within the cache. - * @return {boolean} True if the key exists in the cache, otherwise false. - */ + * Checks if the given key exists in the JSON Cache. + * + * @method Phaser.Cache#checkJSONKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ checkJSONKey: function (key) { - return this.checkKey(Phaser.Cache.JSON, key); - }, /** - * Checks if the given key exists in the XML Cache. - * - * @method Phaser.Cache#checkXMLKey - * @param {string} key - The key of the asset within the cache. - * @return {boolean} True if the key exists in the cache, otherwise false. - */ + * Checks if the given key exists in the XML Cache. + * + * @method Phaser.Cache#checkXMLKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ checkXMLKey: function (key) { - return this.checkKey(Phaser.Cache.XML, key); - }, /** - * Checks if the given key exists in the Video Cache. - * - * @method Phaser.Cache#checkVideoKey - * @param {string} key - The key of the asset within the cache. - * @return {boolean} True if the key exists in the cache, otherwise false. - */ + * Checks if the given key exists in the Video Cache. + * + * @method Phaser.Cache#checkVideoKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ checkVideoKey: function (key) { - return this.checkKey(Phaser.Cache.VIDEO, key); - }, /** - * Checks if the given key exists in the Fragment Shader Cache. - * - * @method Phaser.Cache#checkShaderKey - * @param {string} key - The key of the asset within the cache. - * @return {boolean} True if the key exists in the cache, otherwise false. - */ + * Checks if the given key exists in the Fragment Shader Cache. + * + * @method Phaser.Cache#checkShaderKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ checkShaderKey: function (key) { - return this.checkKey(Phaser.Cache.SHADER, key); - }, /** - * Checks if the given key exists in the Render Texture Cache. - * - * @method Phaser.Cache#checkRenderTextureKey - * @param {string} key - The key of the asset within the cache. - * @return {boolean} True if the key exists in the cache, otherwise false. - */ + * Checks if the given key exists in the Render Texture Cache. + * + * @method Phaser.Cache#checkRenderTextureKey + * @param {string} key - The key of the asset within the cache. + * @return {boolean} True if the key exists in the cache, otherwise false. + */ checkRenderTextureKey: function (key) { - return this.checkKey(Phaser.Cache.RENDER_TEXTURE, key); - }, - // ////////////// - // Get Items // - // ////////////// + /* + * ////////////// + * Get Items // + * ////////////// + */ /** - * Get an item from a cache based on the given key and property. - * - * This method is mostly used internally by other Cache methods such as `getImage` but is exposed - * publicly for your own use as well. - * - * @method Phaser.Cache#getItem - * @param {string} key - The key of the asset within the cache. - * @param {integer} cache - The cache to search. One of the Cache consts such as `Phaser.Cache.IMAGE` or `Phaser.Cache.SOUND`. - * @param {string} [method] - The string name of the method calling getItem. Can be empty, in which case no console warning is output. - * @param {string} [property] - If you require a specific property from the cache item, specify it here. - * @return {object} The cached item if found, otherwise `null`. If the key is invalid and `method` is set then a console.warn is output. - */ + * Get an item from a cache based on the given key and property. + * + * This method is mostly used internally by other Cache methods such as `getImage` but is exposed + * publicly for your own use as well. + * + * @method Phaser.Cache#getItem + * @param {string} key - The key of the asset within the cache. + * @param {integer} cache - The cache to search. One of the Cache consts such as `Phaser.Cache.IMAGE` or `Phaser.Cache.SOUND`. + * @param {string} [method] - The string name of the method calling getItem. Can be empty, in which case no console warning is output. + * @param {string} [property] - If you require a specific property from the cache item, specify it here. + * @return {object} The cached item if found, otherwise `null`. If the key is invalid and `method` is set then a console.warn is output. + */ getItem: function (key, cache, method, property) { - if (!this.checkKey(cache, key)) { if (method) @@ -1303,46 +1216,42 @@ Phaser.Cache.prototype = { } return null; - }, /** - * Gets a Canvas object from the cache. - * - * The object is looked-up based on the key given. - * - * Note: If the object cannot be found a `console.warn` message is displayed. - * - * @method Phaser.Cache#getCanvas - * @param {string} key - The key of the asset to retrieve from the cache. - * @return {object} The canvas object or `null` if no item could be found matching the given key. - */ + * Gets a Canvas object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getCanvas + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {object} The canvas object or `null` if no item could be found matching the given key. + */ getCanvas: function (key) { - return this.getItem(key, Phaser.Cache.CANVAS, 'getCanvas', 'canvas'); - }, /** - * Gets a Image object from the cache. This returns a DOM Image object, not a Phaser.Image object. - * - * The object is looked-up based on the key given. - * - * Note: If the object cannot be found a `console.warn` message is displayed. - * - * Only the Image cache is searched, which covers images loaded via Loader.image, Sprite Sheets and Texture Atlases. - * - * If you need the image used by a bitmap font or similar then please use those respective 'get' methods. - * - * @method Phaser.Cache#getImage - * @param {string} [key] - The key of the asset to retrieve from the cache. If not given or null it will return a default image. If given but not found in the cache it will throw a warning and return the missing image. - * @param {boolean} [full=false] - If true the full image object will be returned, if false just the HTML Image object is returned. - * @return {Image} The Image object if found in the Cache, otherwise `null`. If `full` was true then a JavaScript object is returned. - */ + * Gets a Image object from the cache. This returns a DOM Image object, not a Phaser.Image object. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * Only the Image cache is searched, which covers images loaded via Loader.image, Sprite Sheets and Texture Atlases. + * + * If you need the image used by a bitmap font or similar then please use those respective 'get' methods. + * + * @method Phaser.Cache#getImage + * @param {string} [key] - The key of the asset to retrieve from the cache. If not given or null it will return a default image. If given but not found in the cache it will throw a warning and return the missing image. + * @param {boolean} [full=false] - If true the full image object will be returned, if false just the HTML Image object is returned. + * @return {Image} The Image object if found in the Cache, otherwise `null`. If `full` was true then a JavaScript object is returned. + */ getImage: function (key, full) { - if (key === undefined || key === null) { key = '__default'; @@ -1365,97 +1274,87 @@ Phaser.Cache.prototype = { { return img.data; } - }, /** - * Get a single texture frame by key. - * - * You'd only do this to get the default Frame created for a non-atlas / spritesheet image. - * - * @method Phaser.Cache#getTextureFrame - * @param {string} key - The key of the asset to retrieve from the cache. - * @return {Phaser.Frame} The frame data. - */ + * Get a single texture frame by key. + * + * You'd only do this to get the default Frame created for a non-atlas / spritesheet image. + * + * @method Phaser.Cache#getTextureFrame + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {Phaser.Frame} The frame data. + */ getTextureFrame: function (key) { - return this.getItem(key, Phaser.Cache.TEXTURE, 'getTextureFrame', 'frame'); - }, /** - * Gets a Phaser.Sound object from the cache. - * - * The object is looked-up based on the key given. - * - * Note: If the object cannot be found a `console.warn` message is displayed. - * - * @method Phaser.Cache#getSound - * @param {string} key - The key of the asset to retrieve from the cache. - * @return {Phaser.Sound} The sound object. - */ + * Gets a Phaser.Sound object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getSound + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {Phaser.Sound} The sound object. + */ getSound: function (key) { - return this.getItem(key, Phaser.Cache.SOUND, 'getSound'); - }, /** - * Gets a raw Sound data object from the cache. - * - * The object is looked-up based on the key given. - * - * Note: If the object cannot be found a `console.warn` message is displayed. - * - * @method Phaser.Cache#getSoundData - * @param {string} key - The key of the asset to retrieve from the cache. - * @return {object} The sound data. - */ + * Gets a raw Sound data object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getSoundData + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {object} The sound data. + */ getSoundData: function (key) { - return this.getItem(key, Phaser.Cache.SOUND, 'getSoundData', 'data'); - }, /** - * Gets a Text object from the cache. - * - * The object is looked-up based on the key given. - * - * Note: If the object cannot be found a `console.warn` message is displayed. - * - * @method Phaser.Cache#getText - * @param {string} key - The key of the asset to retrieve from the cache. - * @return {object} The text data. - */ + * Gets a Text object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getText + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {object} The text data. + */ getText: function (key) { - return this.getItem(key, Phaser.Cache.TEXT, 'getText', 'data'); - }, /** - * Gets a Physics Data object from the cache. - * - * The object is looked-up based on the key given. - * - * Note: If the object cannot be found a `console.warn` message is displayed. - * - * You can get either the entire data set, a single object or a single fixture of an object from it. - * - * @method Phaser.Cache#getPhysicsData - * @param {string} key - The key of the asset to retrieve from the cache. - * @param {string} [object=null] - If specified it will return just the physics object that is part of the given key, if null it will return them all. - * @param {string} fixtureKey - Fixture key of fixture inside an object. This key can be set per fixture with the Phaser Exporter. - * @return {object} The requested physics object data if found. - */ + * Gets a Physics Data object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * You can get either the entire data set, a single object or a single fixture of an object from it. + * + * @method Phaser.Cache#getPhysicsData + * @param {string} key - The key of the asset to retrieve from the cache. + * @param {string} [object=null] - If specified it will return just the physics object that is part of the given key, if null it will return them all. + * @param {string} fixtureKey - Fixture key of fixture inside an object. This key can be set per fixture with the Phaser Exporter. + * @return {object} The requested physics object data if found. + */ getPhysicsData: function (key, object, fixtureKey) { - var data = this.getItem(key, Phaser.Cache.PHYSICS, 'getPhysicsData', 'data'); if (data === null || object === undefined || object === null) @@ -1496,99 +1395,89 @@ Phaser.Cache.prototype = { } return null; - }, /** - * Gets a raw Tilemap data object from the cache. This will be in either CSV or JSON format. - * - * The object is looked-up based on the key given. - * - * Note: If the object cannot be found a `console.warn` message is displayed. - * - * @method Phaser.Cache#getTilemapData - * @param {string} key - The key of the asset to retrieve from the cache. - * @return {object} The raw tilemap data in CSV or JSON format. - */ + * Gets a raw Tilemap data object from the cache. This will be in either CSV or JSON format. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getTilemapData + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {object} The raw tilemap data in CSV or JSON format. + */ getTilemapData: function (key) { - return this.getItem(key, Phaser.Cache.TILEMAP, 'getTilemapData'); - }, /** - * Gets a binary object from the cache. - * - * The object is looked-up based on the key given. - * - * Note: If the object cannot be found a `console.warn` message is displayed. - * - * @method Phaser.Cache#getBinary - * @param {string} key - The key of the asset to retrieve from the cache. - * @return {object} The binary data object. - */ + * Gets a binary object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getBinary + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {object} The binary data object. + */ getBinary: function (key) { - return this.getItem(key, Phaser.Cache.BINARY, 'getBinary'); - }, /** - * Gets a BitmapData object from the cache. - * - * The object is looked-up based on the key given. - * - * Note: If the object cannot be found a `console.warn` message is displayed. - * - * @method Phaser.Cache#getBitmapData - * @param {string} key - The key of the asset to retrieve from the cache. - * @return {Phaser.BitmapData} The requested BitmapData object if found, or null if not. - */ + * Gets a BitmapData object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getBitmapData + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {Phaser.BitmapData} The requested BitmapData object if found, or null if not. + */ getBitmapData: function (key) { - return this.getItem(key, Phaser.Cache.BITMAPDATA, 'getBitmapData', 'data'); - }, /** - * Gets a Bitmap Font object from the cache. - * - * The object is looked-up based on the key given. - * - * Note: If the object cannot be found a `console.warn` message is displayed. - * - * @method Phaser.Cache#getBitmapFont - * @param {string} key - The key of the asset to retrieve from the cache. - * @return {Phaser.BitmapFont} The requested BitmapFont object if found, or null if not. - */ + * Gets a Bitmap Font object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getBitmapFont + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {Phaser.BitmapFont} The requested BitmapFont object if found, or null if not. + */ getBitmapFont: function (key) { - return this.getItem(key, Phaser.Cache.BITMAPFONT, 'getBitmapFont'); - }, /** - * Gets a JSON object from the cache. - * - * The object is looked-up based on the key given. - * - * Note: If the object cannot be found a `console.warn` message is displayed. - * - * You can either return the object by reference (the default), or return a clone - * of it by setting the `clone` argument to `true`. - * - * @method Phaser.Cache#getJSON - * @param {string} key - The key of the asset to retrieve from the cache. - * @param {boolean} [clone=false] - Return a clone of the original object (true) or a reference to it? (false) - * @return {object} The JSON object, or an Array if the key points to an Array property. If the property wasn't found, it returns null. - */ + * Gets a JSON object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * You can either return the object by reference (the default), or return a clone + * of it by setting the `clone` argument to `true`. + * + * @method Phaser.Cache#getJSON + * @param {string} key - The key of the asset to retrieve from the cache. + * @param {boolean} [clone=false] - Return a clone of the original object (true) or a reference to it? (false) + * @return {object} The JSON object, or an Array if the key points to an Array property. If the property wasn't found, it returns null. + */ getJSON: function (key, clone) { - var data = this.getItem(key, Phaser.Cache.JSON, 'getJSON', 'data'); if (data) @@ -1606,144 +1495,130 @@ Phaser.Cache.prototype = { { return null; } - }, /** - * Gets an XML object from the cache. - * - * The object is looked-up based on the key given. - * - * Note: If the object cannot be found a `console.warn` message is displayed. - * - * @method Phaser.Cache#getXML - * @param {string} key - The key of the asset to retrieve from the cache. - * @return {object} The XML object. - */ + * Gets an XML object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getXML + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {object} The XML object. + */ getXML: function (key) { - return this.getItem(key, Phaser.Cache.XML, 'getXML', 'data'); - }, /** - * Gets a Phaser.Video object from the cache. - * - * The object is looked-up based on the key given. - * - * Note: If the object cannot be found a `console.warn` message is displayed. - * - * @method Phaser.Cache#getVideo - * @param {string} key - The key of the asset to retrieve from the cache. - * @return {Phaser.Video} The video object. - */ + * Gets a Phaser.Video object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getVideo + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {Phaser.Video} The video object. + */ getVideo: function (key) { - return this.getItem(key, Phaser.Cache.VIDEO, 'getVideo'); - }, /** - * Gets a fragment shader object from the cache. - * - * The object is looked-up based on the key given. - * - * Note: If the object cannot be found a `console.warn` message is displayed. - * - * @method Phaser.Cache#getShader - * @param {string} key - The key of the asset to retrieve from the cache. - * @return {string} The shader object. - */ + * Gets a fragment shader object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getShader + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {string} The shader object. + */ getShader: function (key) { - return this.getItem(key, Phaser.Cache.SHADER, 'getShader', 'data'); - }, /** - * Gets a RenderTexture object from the cache. - * - * The object is looked-up based on the key given. - * - * Note: If the object cannot be found a `console.warn` message is displayed. - * - * @method Phaser.Cache#getRenderTexture - * @param {string} key - The key of the asset to retrieve from the cache. - * @return {Object} The object with Phaser.RenderTexture and Phaser.Frame. - */ + * Gets a RenderTexture object from the cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getRenderTexture + * @param {string} key - The key of the asset to retrieve from the cache. + * @return {Object} The object with Phaser.RenderTexture and Phaser.Frame. + */ getRenderTexture: function (key) { - return this.getItem(key, Phaser.Cache.RENDER_TEXTURE, 'getRenderTexture'); - }, /** - * Gets an item from the data cache. - * - * @method Phaser.Cache#getData - * @param {string} key - The key of the data item. - * @return {any} The data. - */ + * Gets an item from the data cache. + * + * @method Phaser.Cache#getData + * @param {string} key - The key of the data item. + * @return {any} The data. + */ getData: function (key) { - return this.getItem(key, Phaser.Cache.DATA, 'getData'); - }, - // ////////////////////////// - // Frame Related Methods // - // ////////////////////////// + /* + * ////////////////////////// + * Frame Related Methods // + * ////////////////////////// + */ /** - * Gets a PIXI.BaseTexture by key from the given Cache. - * - * @method Phaser.Cache#getBaseTexture - * @param {string} key - Asset key of the image for which you want the BaseTexture for. - * @param {integer} [cache=Phaser.Cache.IMAGE] - The cache to search for the item in. - * @return {PIXI.BaseTexture} The BaseTexture object. - */ + * Gets a PIXI.BaseTexture by key from the given Cache. + * + * @method Phaser.Cache#getBaseTexture + * @param {string} key - Asset key of the image for which you want the BaseTexture for. + * @param {integer} [cache=Phaser.Cache.IMAGE] - The cache to search for the item in. + * @return {PIXI.BaseTexture} The BaseTexture object. + */ getBaseTexture: function (key, cache) { - if (cache === undefined) { cache = Phaser.Cache.IMAGE; } return this.getItem(key, cache, 'getBaseTexture', 'base'); - }, /** - * Get a single frame by key. You'd only do this to get the default Frame created for a non-atlas/spritesheet image. - * - * @method Phaser.Cache#getFrame - * @param {string} key - Asset key of the frame data to retrieve from the Cache. - * @param {integer} [cache=Phaser.Cache.IMAGE] - The cache to search for the item in. - * @return {Phaser.Frame} The frame data. - */ + * Get a single frame by key. You'd only do this to get the default Frame created for a non-atlas/spritesheet image. + * + * @method Phaser.Cache#getFrame + * @param {string} key - Asset key of the frame data to retrieve from the Cache. + * @param {integer} [cache=Phaser.Cache.IMAGE] - The cache to search for the item in. + * @return {Phaser.Frame} The frame data. + */ getFrame: function (key, cache) { - if (cache === undefined) { cache = Phaser.Cache.IMAGE; } return this.getItem(key, cache, 'getFrame', 'frame'); - }, /** - * Get the total number of frames contained in the FrameData object specified by the given key. - * - * @method Phaser.Cache#getFrameCount - * @param {string} key - Asset key of the FrameData you want. - * @param {integer} [cache=Phaser.Cache.IMAGE] - The cache to search for the item in. - * @return {number} Then number of frames. 0 if the image is not found. - */ + * Get the total number of frames contained in the FrameData object specified by the given key. + * + * @method Phaser.Cache#getFrameCount + * @param {string} key - Asset key of the FrameData you want. + * @param {integer} [cache=Phaser.Cache.IMAGE] - The cache to search for the item in. + * @return {number} Then number of frames. 0 if the image is not found. + */ getFrameCount: function (key, cache) { - var data = this.getFrameData(key, cache); if (data) @@ -1754,79 +1629,71 @@ Phaser.Cache.prototype = { { return 0; } - }, /** - * Gets a Phaser.FrameData object from the Image Cache. - * - * The object is looked-up based on the key given. - * - * Note: If the object cannot be found a `console.warn` message is displayed. - * - * @method Phaser.Cache#getFrameData - * @param {string} key - Asset key of the frame data to retrieve from the Cache. - * @param {integer} [cache=Phaser.Cache.IMAGE] - The cache to search for the item in. - * @return {Phaser.FrameData} The frame data. - */ + * Gets a Phaser.FrameData object from the Image Cache. + * + * The object is looked-up based on the key given. + * + * Note: If the object cannot be found a `console.warn` message is displayed. + * + * @method Phaser.Cache#getFrameData + * @param {string} key - Asset key of the frame data to retrieve from the Cache. + * @param {integer} [cache=Phaser.Cache.IMAGE] - The cache to search for the item in. + * @return {Phaser.FrameData} The frame data. + */ getFrameData: function (key, cache) { - if (cache === undefined) { cache = Phaser.Cache.IMAGE; } return this.getItem(key, cache, 'getFrameData', 'frameData'); - }, /** - * Check if the FrameData for the given key exists in the Image Cache. - * - * @method Phaser.Cache#hasFrameData - * @param {string} key - Asset key of the frame data to retrieve from the Cache. - * @param {integer} [cache=Phaser.Cache.IMAGE] - The cache to search for the item in. - * @return {boolean} True if the given key has frameData in the cache, otherwise false. - */ + * Check if the FrameData for the given key exists in the Image Cache. + * + * @method Phaser.Cache#hasFrameData + * @param {string} key - Asset key of the frame data to retrieve from the Cache. + * @param {integer} [cache=Phaser.Cache.IMAGE] - The cache to search for the item in. + * @return {boolean} True if the given key has frameData in the cache, otherwise false. + */ hasFrameData: function (key, cache) { - if (cache === undefined) { cache = Phaser.Cache.IMAGE; } return (this.getItem(key, cache, '', 'frameData') !== null); - }, /** - * Replaces a set of frameData with a new Phaser.FrameData object. - * - * @method Phaser.Cache#updateFrameData - * @param {string} key - The unique key by which you will reference this object. - * @param {number} frameData - The new FrameData. - * @param {integer} [cache=Phaser.Cache.IMAGE] - The cache to search. One of the Cache consts such as `Phaser.Cache.IMAGE` or `Phaser.Cache.SOUND`. - */ + * Replaces a set of frameData with a new Phaser.FrameData object. + * + * @method Phaser.Cache#updateFrameData + * @param {string} key - The unique key by which you will reference this object. + * @param {number} frameData - The new FrameData. + * @param {integer} [cache=Phaser.Cache.IMAGE] - The cache to search. One of the Cache consts such as `Phaser.Cache.IMAGE` or `Phaser.Cache.SOUND`. + */ updateFrameData: function (key, frameData, cache) { - if (cache === undefined) { cache = Phaser.Cache.IMAGE; } if (this._cacheMap[cache][key]) { this._cacheMap[cache][key].frameData = frameData; } - }, /** - * Get a single frame out of a frameData set by key. - * - * @method Phaser.Cache#getFrameByIndex - * @param {string} key - Asset key of the frame data to retrieve from the Cache. - * @param {number} index - The index of the frame you want to get. - * @param {integer} [cache=Phaser.Cache.IMAGE] - The cache to search. One of the Cache consts such as `Phaser.Cache.IMAGE` or `Phaser.Cache.SOUND`. - * @return {Phaser.Frame} The frame object. - */ + * Get a single frame out of a frameData set by key. + * + * @method Phaser.Cache#getFrameByIndex + * @param {string} key - Asset key of the frame data to retrieve from the Cache. + * @param {number} index - The index of the frame you want to get. + * @param {integer} [cache=Phaser.Cache.IMAGE] - The cache to search. One of the Cache consts such as `Phaser.Cache.IMAGE` or `Phaser.Cache.SOUND`. + * @return {Phaser.Frame} The frame object. + */ getFrameByIndex: function (key, index, cache) { - var data = this.getFrameData(key, cache); if (data) @@ -1837,21 +1704,19 @@ Phaser.Cache.prototype = { { return null; } - }, /** - * Get a single frame out of a frameData set by key. - * - * @method Phaser.Cache#getFrameByName - * @param {string} key - Asset key of the frame data to retrieve from the Cache. - * @param {string} name - The name of the frame you want to get. - * @param {integer} [cache=Phaser.Cache.IMAGE] - The cache to search. One of the Cache consts such as `Phaser.Cache.IMAGE` or `Phaser.Cache.SOUND`. - * @return {Phaser.Frame} The frame object. - */ + * Get a single frame out of a frameData set by key. + * + * @method Phaser.Cache#getFrameByName + * @param {string} key - Asset key of the frame data to retrieve from the Cache. + * @param {string} name - The name of the frame you want to get. + * @param {integer} [cache=Phaser.Cache.IMAGE] - The cache to search. One of the Cache consts such as `Phaser.Cache.IMAGE` or `Phaser.Cache.SOUND`. + * @return {Phaser.Frame} The frame object. + */ getFrameByName: function (key, name, cache) { - var data = this.getFrameData(key, cache); if (data) @@ -1862,21 +1727,19 @@ Phaser.Cache.prototype = { { return null; } - }, /** - * Get a cached object by the URL. - * This only returns a value if you set Cache.autoResolveURL to `true` *before* starting the preload of any assets. - * Be aware that every call to this function makes a DOM src query, so use carefully and double-check for implications in your target browsers/devices. - * - * @method Phaser.Cache#getURL - * @param {string} url - The url for the object loaded to get from the cache. - * @return {object} The cached object. - */ + * Get a cached object by the URL. + * This only returns a value if you set Cache.autoResolveURL to `true` *before* starting the preload of any assets. + * Be aware that every call to this function makes a DOM src query, so use carefully and double-check for implications in your target browsers/devices. + * + * @method Phaser.Cache#getURL + * @param {string} url - The url for the object loaded to get from the cache. + * @return {object} The cached object. + */ getURL: function (url) { - var url = this._resolveURL(url); if (url) @@ -1888,19 +1751,17 @@ Phaser.Cache.prototype = { console.warn('Phaser.Cache.getUrl: Invalid url: "' + url + '" or Cache.autoResolveURL was false'); return null; } - }, /** - * Gets all keys used in the requested Cache. - * - * @method Phaser.Cache#getKeys - * @param {integer} [cache=Phaser.Cache.IMAGE] - The Cache you wish to get the keys from. Can be any of the Cache consts such as `Phaser.Cache.IMAGE`, `Phaser.Cache.SOUND` etc. - * @return {Array} The array of keys in the requested cache. - */ + * Gets all keys used in the requested Cache. + * + * @method Phaser.Cache#getKeys + * @param {integer} [cache=Phaser.Cache.IMAGE] - The Cache you wish to get the keys from. Can be any of the Cache consts such as `Phaser.Cache.IMAGE`, `Phaser.Cache.SOUND` etc. + * @return {Array} The array of keys in the requested cache. + */ getKeys: function (cache) { - if (cache === undefined) { cache = Phaser.Cache.IMAGE; } var out = []; @@ -1917,44 +1778,42 @@ Phaser.Cache.prototype = { } return out; - }, - // /////////////////// - // Remove Methods // - // /////////////////// + /* + * /////////////////// + * Remove Methods // + * /////////////////// + */ /** - * Removes a canvas from the cache. - * - * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere - * then it will persist in memory. - * - * @method Phaser.Cache#removeCanvas - * @param {string} key - Key of the asset you want to remove. - */ + * Removes a canvas from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeCanvas + * @param {string} key - Key of the asset you want to remove. + */ removeCanvas: function (key) { - delete this._cache.canvas[key]; - }, /** - * Removes an image from the cache. - * - * You can optionally elect to destroy it as well. This calls BaseTexture.destroy on it. - * - * Note that this only removes it from the Phaser Cache. If you still have references to the data elsewhere - * then it will persist in memory. - * - * @method Phaser.Cache#removeImage - * @param {string} key - Key of the asset you want to remove. - * @param {boolean} [destroyBaseTexture=true] - Should the BaseTexture behind this image also be destroyed? - */ + * Removes an image from the cache. + * + * You can optionally elect to destroy it as well. This calls BaseTexture.destroy on it. + * + * Note that this only removes it from the Phaser Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeImage + * @param {string} key - Key of the asset you want to remove. + * @param {boolean} [destroyBaseTexture=true] - Should the BaseTexture behind this image also be destroyed? + */ removeImage: function (key, destroyBaseTexture) { - if (destroyBaseTexture === undefined) { destroyBaseTexture = true; } var img = this.getImage(key, true); @@ -1965,274 +1824,240 @@ Phaser.Cache.prototype = { } delete this._cache.image[key]; - }, /** - * Removes a sound from the cache. - * - * If any `Phaser.Sound` objects use the audio file in the cache that you remove with this method, they will - * _automatically_ destroy themselves. If you wish to have full control over when Sounds are destroyed then - * you must finish your house-keeping and destroy them all yourself first, before calling this method. - * - * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere - * then it will persist in memory. - * - * @method Phaser.Cache#removeSound - * @param {string} key - Key of the asset you want to remove. - */ + * Removes a sound from the cache. + * + * If any `Phaser.Sound` objects use the audio file in the cache that you remove with this method, they will + * _automatically_ destroy themselves. If you wish to have full control over when Sounds are destroyed then + * you must finish your house-keeping and destroy them all yourself first, before calling this method. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeSound + * @param {string} key - Key of the asset you want to remove. + */ removeSound: function (key) { - delete this._cache.sound[key]; - }, /** - * Removes a text file from the cache. - * - * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere - * then it will persist in memory. - * - * @method Phaser.Cache#removeText - * @param {string} key - Key of the asset you want to remove. - */ + * Removes a text file from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeText + * @param {string} key - Key of the asset you want to remove. + */ removeText: function (key) { - delete this._cache.text[key]; - }, /** - * Removes a physics data file from the cache. - * - * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere - * then it will persist in memory. - * - * @method Phaser.Cache#removePhysics - * @param {string} key - Key of the asset you want to remove. - */ + * Removes a physics data file from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removePhysics + * @param {string} key - Key of the asset you want to remove. + */ removePhysics: function (key) { - delete this._cache.physics[key]; - }, /** - * Removes a tilemap from the cache. - * - * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere - * then it will persist in memory. - * - * @method Phaser.Cache#removeTilemap - * @param {string} key - Key of the asset you want to remove. - */ + * Removes a tilemap from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeTilemap + * @param {string} key - Key of the asset you want to remove. + */ removeTilemap: function (key) { - delete this._cache.tilemap[key]; - }, /** - * Removes a binary file from the cache. - * - * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere - * then it will persist in memory. - * - * @method Phaser.Cache#removeBinary - * @param {string} key - Key of the asset you want to remove. - */ + * Removes a binary file from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeBinary + * @param {string} key - Key of the asset you want to remove. + */ removeBinary: function (key) { - delete this._cache.binary[key]; - }, /** - * Removes a bitmap data from the cache. - * - * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere - * then it will persist in memory. - * - * @method Phaser.Cache#removeBitmapData - * @param {string} key - Key of the asset you want to remove. - */ + * Removes a bitmap data from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeBitmapData + * @param {string} key - Key of the asset you want to remove. + */ removeBitmapData: function (key) { - delete this._cache.bitmapData[key]; - }, /** - * Removes a bitmap font from the cache. - * - * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere - * then it will persist in memory. - * - * @method Phaser.Cache#removeBitmapFont - * @param {string} key - Key of the asset you want to remove. - */ + * Removes a bitmap font from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeBitmapFont + * @param {string} key - Key of the asset you want to remove. + */ removeBitmapFont: function (key) { - delete this._cache.bitmapFont[key]; - }, /** - * Removes a json object from the cache. - * - * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere - * then it will persist in memory. - * - * @method Phaser.Cache#removeJSON - * @param {string} key - Key of the asset you want to remove. - */ + * Removes a json object from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeJSON + * @param {string} key - Key of the asset you want to remove. + */ removeJSON: function (key) { - delete this._cache.json[key]; - }, /** - * Removes a xml object from the cache. - * - * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere - * then it will persist in memory. - * - * @method Phaser.Cache#removeXML - * @param {string} key - Key of the asset you want to remove. - */ + * Removes a xml object from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeXML + * @param {string} key - Key of the asset you want to remove. + */ removeXML: function (key) { - delete this._cache.xml[key]; - }, /** - * Removes a video from the cache. - * - * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere - * then it will persist in memory. - * - * @method Phaser.Cache#removeVideo - * @param {string} key - Key of the asset you want to remove. - */ + * Removes a video from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeVideo + * @param {string} key - Key of the asset you want to remove. + */ removeVideo: function (key) { - delete this._cache.video[key]; - }, /** - * Removes a shader from the cache. - * - * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere - * then it will persist in memory. - * - * @method Phaser.Cache#removeShader - * @param {string} key - Key of the asset you want to remove. - */ + * Removes a shader from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeShader + * @param {string} key - Key of the asset you want to remove. + */ removeShader: function (key) { - delete this._cache.shader[key]; - }, /** - * Removes a Render Texture from the cache. - * - * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere - * then it will persist in memory. - * - * @method Phaser.Cache#removeRenderTexture - * @param {string} key - Key of the asset you want to remove. - */ + * Removes a Render Texture from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeRenderTexture + * @param {string} key - Key of the asset you want to remove. + */ removeRenderTexture: function (key) { - delete this._cache.renderTexture[key]; - }, /** - * Removes a Sprite Sheet from the cache. - * - * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere - * then it will persist in memory. - * - * @method Phaser.Cache#removeSpriteSheet - * @param {string} key - Key of the asset you want to remove. - */ + * Removes a Sprite Sheet from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeSpriteSheet + * @param {string} key - Key of the asset you want to remove. + */ removeSpriteSheet: function (key) { - delete this._cache.spriteSheet[key]; - }, /** - * Removes a Texture Atlas from the cache. - * - * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere - * then it will persist in memory. - * - * @method Phaser.Cache#removeTextureAtlas - * @param {string} key - Key of the asset you want to remove. - */ + * Removes a Texture Atlas from the cache. + * + * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere + * then it will persist in memory. + * + * @method Phaser.Cache#removeTextureAtlas + * @param {string} key - Key of the asset you want to remove. + */ removeTextureAtlas: function (key) { - delete this._cache.image[key]; - }, removeData: function (key) { - delete this._cache.data[key]; - }, /** - * Empties out all of the GL Textures from Images stored in the cache. - * This is called automatically when the WebGL context is lost and then restored. - * - * @method Phaser.Cache#clearGLTextures - * @protected - */ + * Empties out all of the GL Textures from Images stored in the cache. + * This is called automatically when the WebGL context is lost and then restored. + * + * @method Phaser.Cache#clearGLTextures + * @protected + */ clearGLTextures: function () { - for (var key in this._cache.image) { this._cache.image[key].base._glTextures = []; } - }, /** - * Resolves a URL to its absolute form and stores it in Cache._urlMap as long as Cache.autoResolveURL is set to `true`. - * This is then looked-up by the Cache.getURL and Cache.checkURL calls. - * - * @method Phaser.Cache#_resolveURL - * @private - * @param {string} url - The URL to resolve. This is appended to Loader.baseURL. - * @param {object} [data] - The data associated with the URL to be stored to the URL Map. - * @return {string} The resolved URL. - */ + * Resolves a URL to its absolute form and stores it in Cache._urlMap as long as Cache.autoResolveURL is set to `true`. + * This is then looked-up by the Cache.getURL and Cache.checkURL calls. + * + * @method Phaser.Cache#_resolveURL + * @private + * @param {string} url - The URL to resolve. This is appended to Loader.baseURL. + * @param {object} [data] - The data associated with the URL to be stored to the URL Map. + * @return {string} The resolved URL. + */ _resolveURL: function (url, data) { - if (!this.autoResolveURL) { return null; @@ -2252,20 +2077,18 @@ Phaser.Cache.prototype = { } return this._urlTemp; - }, /** - * Clears the cache. Removes every local cache object reference. - * If an object in the cache has a `destroy` method it will be called; - * otherwise, `destroy` will be called on any of the object's `base`, `data`, - * `frameData`, or `texture` properties. - * - * @method Phaser.Cache#destroy - */ + * Clears the cache. Removes every local cache object reference. + * If an object in the cache has a `destroy` method it will be called; + * otherwise, `destroy` will be called on any of the object's `base`, `data`, + * `frameData`, or `texture` properties. + * + * @method Phaser.Cache#destroy + */ destroy: function () { - for (var i = 0; i < this._cacheMap.length; i++) { var cache = this._cacheMap[i]; @@ -2284,17 +2107,15 @@ Phaser.Cache.prototype = { this._urlMap = null; this._urlResolver = null; this._urlTemp = null; - }, /** - * @method Phaser.Cache#destroyItem - * @protected - * @param {object} item - */ + * @method Phaser.Cache#destroyItem + * @protected + * @param {object} item + */ destroyItem: function (item) { - if (item.destroy) { item.destroy(); @@ -2321,17 +2142,15 @@ Phaser.Cache.prototype = { item.texture.destroy(true); } } - }, /** - * Starts loading the DEFAULT and MISSING images. - * - * @private - */ + * Starts loading the DEFAULT and MISSING images. + * + * @private + */ _addImages: function () { - this._pendingCount = 0; this.addDefaultImage(); @@ -2356,64 +2175,55 @@ Phaser.Cache.prototype = { { this._ready(); } - }, /** - * Increments the pending count. - * - * @private - */ + * Increments the pending count. + * + * @private + */ _addPending: function () { - this._pendingCount += 1; - }, /** - * Decrements the pending count and checks if complete. - * - * @private - */ + * Decrements the pending count and checks if complete. + * + * @private + */ _removePending: function () { - this._pendingCount -= 1; this._checkReady(); - }, /** - * Calls {@link #_ready} if no pending items remain. - * - * @private - */ + * Calls {@link #_ready} if no pending items remain. + * + * @private + */ _checkReady: function () { - if (this.isReady) { this._ready(); } - }, /** - * Resets pending count and triggers {@link #onReady}. - * - * @private - */ + * Resets pending count and triggers {@link #onReady}. + * + * @private + */ _ready: function () { - this._pendingCount = 0; this.onReady.dispatch(this); - } }; @@ -2421,10 +2231,10 @@ Phaser.Cache.prototype = { Phaser.Cache.prototype.constructor = Phaser.Cache; /** -* The DEFAULT and MISSING textures have loaded (or the {@link #READY_TIMEOUT load timeout} was exceeded). -* -* @property {boolean} Phaser.Cache#isReady -*/ + * The DEFAULT and MISSING textures have loaded (or the {@link #READY_TIMEOUT load timeout} was exceeded). + * + * @property {boolean} Phaser.Cache#isReady + */ Object.defineProperty(Phaser.Cache.prototype, 'isReady', { get: function () { diff --git a/src/loader/Loader.js b/src/loader/Loader.js index f5c7a7d51..e14725abd 100644 --- a/src/loader/Loader.js +++ b/src/loader/Loader.js @@ -1,131 +1,130 @@ /* jshint wsh:true */ /** -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* The Loader handles loading all external content such as Images, Sounds, Texture Atlases and data files. -* -* The loader uses a combination of tag loading (eg. Image elements) and XHR and provides progress and completion callbacks. -* -* Parallel loading (see {@link #enableParallel}) is supported and enabled by default. -* Load-before behavior of parallel resources is controlled by synchronization points as discussed in {@link #withSyncPoint}. -* -* Texture Atlases can be created with tools such as [Texture Packer](https://www.codeandweb.com/texturepacker/phaser) and -* [Shoebox](http://renderhjs.net/shoebox/) -* -* @class Phaser.Loader -* @param {Phaser.Game} game - A reference to the currently running game. -*/ + * The Loader handles loading all external content such as Images, Sounds, Texture Atlases and data files. + * + * The loader uses a combination of tag loading (eg. Image elements) and XHR and provides progress and completion callbacks. + * + * Parallel loading (see {@link #enableParallel}) is supported and enabled by default. + * Load-before behavior of parallel resources is controlled by synchronization points as discussed in {@link #withSyncPoint}. + * + * Texture Atlases can be created with tools such as [Texture Packer](https://www.codeandweb.com/texturepacker/phaser) and + * [Shoebox](http://renderhjs.net/shoebox/) + * + * @class Phaser.Loader + * @param {Phaser.Game} game - A reference to the currently running game. + */ Phaser.Loader = function (game) { - /** - * Local reference to game. - * @property {Phaser.Game} game - * @protected - */ + * Local reference to game. + * @property {Phaser.Game} game + * @protected + */ this.game = game; /** - * Local reference to the Phaser.Cache. - * @property {Phaser.Cache} cache - * @protected - */ + * Local reference to the Phaser.Cache. + * @property {Phaser.Cache} cache + * @protected + */ this.cache = game.cache; /** - * If true all calls to Loader.reset will be ignored. Useful if you need to create a load queue before swapping to a preloader state. - * @property {boolean} resetLocked - * @default - */ + * If true all calls to Loader.reset will be ignored. Useful if you need to create a load queue before swapping to a preloader state. + * @property {boolean} resetLocked + * @default + */ this.resetLocked = false; /** - * True if the Loader is in the process of loading the queue. - * @property {boolean} isLoading - * @default - */ + * True if the Loader is in the process of loading the queue. + * @property {boolean} isLoading + * @default + */ this.isLoading = false; /** - * True if all assets in the queue have finished loading. - * @property {boolean} hasLoaded - * @default - */ + * True if all assets in the queue have finished loading. + * @property {boolean} hasLoaded + * @default + */ this.hasLoaded = false; /** - * You can optionally link a progress sprite with {@link Phaser.Loader#setPreloadSprite setPreloadSprite}. - * - * This property is an object containing: sprite, rect, direction, width and height - * - * @property {?object} preloadSprite - * @protected - */ + * You can optionally link a progress sprite with {@link Phaser.Loader#setPreloadSprite setPreloadSprite}. + * + * This property is an object containing: sprite, rect, direction, width and height + * + * @property {?object} preloadSprite + * @protected + */ this.preloadSprite = null; /** - * The crossOrigin value applied to loaded images. Very often this needs to be set to 'anonymous'. - * @property {boolean|string} crossOrigin - * @default - */ + * The crossOrigin value applied to loaded images. Very often this needs to be set to 'anonymous'. + * @property {boolean|string} crossOrigin + * @default + */ this.crossOrigin = false; /** - * If you want to append a URL before the path of any asset you can set this here. - * Useful if allowing the asset base url to be configured outside of the game code. - * The string _must_ end with a "/". - * - * @property {string} baseURL - */ + * If you want to append a URL before the path of any asset you can set this here. + * Useful if allowing the asset base url to be configured outside of the game code. + * The string _must_ end with a "/". + * + * @property {string} baseURL + */ this.baseURL = ''; /** - * The value of `path`, if set, is placed before any _relative_ file path given. For example: - * - * ```javascript - * load.path = "images/sprites/"; - * load.image("ball", "ball.png"); - * load.image("tree", "level1/oaktree.png"); - * load.image("boom", "http://server.com/explode.png"); - * ``` - * - * Would load the `ball` file from `images/sprites/ball.png` and the tree from - * `images/sprites/level1/oaktree.png` but the file `boom` would load from the URL - * given as it's an absolute URL. - * - * Please note that the path is added before the filename but *after* the baseURL (if set.) - * - * The string _must_ end with a "/". - * - * @property {string} path - */ + * The value of `path`, if set, is placed before any _relative_ file path given. For example: + * + * ```javascript + * load.path = "images/sprites/"; + * load.image("ball", "ball.png"); + * load.image("tree", "level1/oaktree.png"); + * load.image("boom", "http://server.com/explode.png"); + * ``` + * + * Would load the `ball` file from `images/sprites/ball.png` and the tree from + * `images/sprites/level1/oaktree.png` but the file `boom` would load from the URL + * given as it's an absolute URL. + * + * Please note that the path is added before the filename but *after* the baseURL (if set.) + * + * The string _must_ end with a "/". + * + * @property {string} path + */ this.path = ''; /** - * Used to map the application mime-types to to the Accept header in XHR requests. - * If you don't require these mappings, or they cause problems on your server, then - * remove them from the headers object and the XHR request will not try to use them. - * - * This object can also be used to set the `X-Requested-With` header to - * `XMLHttpRequest` (or any other value you need). To enable this do: - * - * ```javascript - * this.load.headers.requestedWith = 'XMLHttpRequest' - * ``` - * - * before adding anything to the Loader. The XHR loader will then call: - * - * ```javascript - * setRequestHeader('X-Requested-With', this.headers['requestedWith']) - * ``` - * - * @property {object} headers - * @default - */ + * Used to map the application mime-types to to the Accept header in XHR requests. + * If you don't require these mappings, or they cause problems on your server, then + * remove them from the headers object and the XHR request will not try to use them. + * + * This object can also be used to set the `X-Requested-With` header to + * `XMLHttpRequest` (or any other value you need). To enable this do: + * + * ```javascript + * this.load.headers.requestedWith = 'XMLHttpRequest' + * ``` + * + * before adding anything to the Loader. The XHR loader will then call: + * + * ```javascript + * setRequestHeader('X-Requested-With', this.headers['requestedWith']) + * ``` + * + * @property {object} headers + * @default + */ this.headers = { requestedWith: false, json: 'application/json', @@ -133,224 +132,222 @@ Phaser.Loader = function (game) }; /** - * This event is dispatched when the loading process starts: before the first file has been requested, - * but after all the initial packs have been loaded. - * - * @property {Phaser.Signal} onLoadStart - */ + * This event is dispatched when the loading process starts: before the first file has been requested, + * but after all the initial packs have been loaded. + * + * @property {Phaser.Signal} onLoadStart + */ this.onLoadStart = new Phaser.Signal(); /** - * This event is dispatched when the final file in the load queue has either loaded or failed, - * before {@link #onLoadComplete} and before the loader is {@link #reset}. - * - * @property {Phaser.Signal} onBeforeLoadComplete - */ + * This event is dispatched when the final file in the load queue has either loaded or failed, + * before {@link #onLoadComplete} and before the loader is {@link #reset}. + * + * @property {Phaser.Signal} onBeforeLoadComplete + */ this.onBeforeLoadComplete = new Phaser.Signal(); /** - * This event is dispatched when the final file in the load queue has either loaded or failed, - * after the loader is {@link #reset}. - * - * @property {Phaser.Signal} onLoadComplete - */ + * This event is dispatched when the final file in the load queue has either loaded or failed, + * after the loader is {@link #reset}. + * + * @property {Phaser.Signal} onLoadComplete + */ this.onLoadComplete = new Phaser.Signal(); /** - * This event is dispatched when an asset pack has either loaded or failed to load. - * - * This is called when the asset pack manifest file has loaded and successfully added its contents to the loader queue. - * - * Params: `(pack key, success?, total packs loaded, total packs)` - * - * @property {Phaser.Signal} onPackComplete - */ + * This event is dispatched when an asset pack has either loaded or failed to load. + * + * This is called when the asset pack manifest file has loaded and successfully added its contents to the loader queue. + * + * Params: `(pack key, success?, total packs loaded, total packs)` + * + * @property {Phaser.Signal} onPackComplete + */ this.onPackComplete = new Phaser.Signal(); /** - * This event is dispatched immediately before a file starts loading. - * It's possible the file may fail (eg. download error, invalid format) after this event is sent. - * - * Params: `(progress, file key, file url)` - * - * @property {Phaser.Signal} onFileStart - */ + * This event is dispatched immediately before a file starts loading. + * It's possible the file may fail (eg. download error, invalid format) after this event is sent. + * + * Params: `(progress, file key, file url)` + * + * @property {Phaser.Signal} onFileStart + */ this.onFileStart = new Phaser.Signal(); /** - * This event is dispatched when a file has either loaded or failed to load. - * - * Any function bound to this will receive the following parameters: - * - * progress, file key, success?, total loaded files, total files - * - * Where progress is a number between 1 and 100 (inclusive) representing the percentage of the load. - * - * @property {Phaser.Signal} onFileComplete - */ + * This event is dispatched when a file has either loaded or failed to load. + * + * Any function bound to this will receive the following parameters: + * + * progress, file key, success?, total loaded files, total files + * + * Where progress is a number between 1 and 100 (inclusive) representing the percentage of the load. + * + * @property {Phaser.Signal} onFileComplete + */ this.onFileComplete = new Phaser.Signal(); /** - * This event is dispatched when a file (or pack) errors as a result of the load request. - * - * For files it will be triggered before `onFileComplete`. For packs it will be triggered before `onPackComplete`. - * - * Params: `(file key, file)` - * - * @property {Phaser.Signal} onFileError - */ + * This event is dispatched when a file (or pack) errors as a result of the load request. + * + * For files it will be triggered before `onFileComplete`. For packs it will be triggered before `onPackComplete`. + * + * Params: `(file key, file)` + * + * @property {Phaser.Signal} onFileError + */ this.onFileError = new Phaser.Signal(); /** - * If true (the default) then parallel downloading will be enabled. - * - * To disable all parallel downloads this must be set to false prior to any resource being loaded. - * - * @property {boolean} enableParallel - */ + * If true (the default) then parallel downloading will be enabled. + * + * To disable all parallel downloads this must be set to false prior to any resource being loaded. + * + * @property {boolean} enableParallel + */ this.enableParallel = true; /** - * The number of concurrent / parallel resources to try and fetch at once. - * - * Many current browsers limit 6 requests per domain; this is slightly conservative. - * - * This should generally be left at the default, but can be set to a higher limit for specific use-cases. Just be careful when setting large values as different browsers could behave differently. - * - * @property {integer} maxParallelDownloads - */ + * The number of concurrent / parallel resources to try and fetch at once. + * + * Many current browsers limit 6 requests per domain; this is slightly conservative. + * + * This should generally be left at the default, but can be set to a higher limit for specific use-cases. Just be careful when setting large values as different browsers could behave differently. + * + * @property {integer} maxParallelDownloads + */ this.maxParallelDownloads = 4; /** - * A counter: if more than zero, files will be automatically added as a synchronization point. - * @property {integer} _withSyncPointDepth; - */ + * A counter: if more than zero, files will be automatically added as a synchronization point. + * @property {integer} _withSyncPointDepth; + */ this._withSyncPointDepth = 0; /** - * Contains all the information for asset files (including packs) to load. - * - * File/assets are only removed from the list after all loading completes. - * - * @property {file[]} _fileList - * @private - */ + * Contains all the information for asset files (including packs) to load. + * + * File/assets are only removed from the list after all loading completes. + * + * @property {file[]} _fileList + * @private + */ this._fileList = []; /** - * Inflight files (or packs) that are being fetched/processed. - * - * This means that if there are any files in the flight queue there should still be processing - * going on; it should only be empty before or after loading. - * - * The files in the queue may have additional properties added to them, - * including `requestObject` which is normally the associated XHR. - * - * @property {file[]} _flightQueue - * @private - */ + * Inflight files (or packs) that are being fetched/processed. + * + * This means that if there are any files in the flight queue there should still be processing + * going on; it should only be empty before or after loading. + * + * The files in the queue may have additional properties added to them, + * including `requestObject` which is normally the associated XHR. + * + * @property {file[]} _flightQueue + * @private + */ this._flightQueue = []; /** - * The offset into the fileList past all the complete (loaded or error) entries. - * - * @property {integer} _processingHead - * @private - */ + * The offset into the fileList past all the complete (loaded or error) entries. + * + * @property {integer} _processingHead + * @private + */ this._processingHead = 0; /** - * True when the first file (not pack) has loading started. - * This used to to control dispatching `onLoadStart` which happens after any initial packs are loaded. - * - * @property {boolean} _initialPacksLoaded - * @private - */ + * True when the first file (not pack) has loading started. + * This used to to control dispatching `onLoadStart` which happens after any initial packs are loaded. + * + * @property {boolean} _initialPacksLoaded + * @private + */ this._fileLoadStarted = false; /** - * Total packs seen - adjusted when a pack is added. - * @property {integer} _totalPackCount - * @private - */ + * Total packs seen - adjusted when a pack is added. + * @property {integer} _totalPackCount + * @private + */ this._totalPackCount = 0; /** - * Total files seen - adjusted when a file is added. - * @property {integer} _totalFileCount - * @private - */ + * Total files seen - adjusted when a file is added. + * @property {integer} _totalFileCount + * @private + */ this._totalFileCount = 0; /** - * Total packs loaded - adjusted just prior to `onPackComplete`. - * @property {integer} _loadedPackCount - * @private - */ + * Total packs loaded - adjusted just prior to `onPackComplete`. + * @property {integer} _loadedPackCount + * @private + */ this._loadedPackCount = 0; /** - * Total files loaded - adjusted just prior to `onFileComplete`. - * @property {integer} _loadedFileCount - * @private - */ + * Total files loaded - adjusted just prior to `onFileComplete`. + * @property {integer} _loadedFileCount + * @private + */ this._loadedFileCount = 0; - }; /** -* @constant -* @type {number} -*/ + * @constant + * @type {number} + */ Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY = 0; /** -* @constant -* @type {number} -*/ + * @constant + * @type {number} + */ Phaser.Loader.TEXTURE_ATLAS_JSON_HASH = 1; /** -* @constant -* @type {number} -*/ + * @constant + * @type {number} + */ Phaser.Loader.TEXTURE_ATLAS_XML_STARLING = 2; /** -* @constant -* @type {number} -*/ + * @constant + * @type {number} + */ Phaser.Loader.PHYSICS_LIME_CORONA_JSON = 3; /** -* @constant -* @type {number} -*/ + * @constant + * @type {number} + */ Phaser.Loader.PHYSICS_PHASER_JSON = 4; /** -* @constant -* @type {number} -*/ + * @constant + * @type {number} + */ Phaser.Loader.TEXTURE_ATLAS_JSON_PYXEL = 5; Phaser.Loader.prototype = { /** - * Set a Sprite to be a "preload" sprite by passing it to this method. - * - * A "preload" sprite will have its width or height crop adjusted based on the percentage of the loader in real-time. - * This allows you to easily make loading bars for games. - * - * The sprite will automatically be made visible when calling this. - * - * @method Phaser.Loader#setPreloadSprite - * @param {Phaser.Sprite|Phaser.Image} sprite - The sprite or image that will be cropped during the load. - * @param {number} [direction=0] - A value of zero means the sprite will be cropped horizontally, a value of 1 means its will be cropped vertically. - */ + * Set a Sprite to be a "preload" sprite by passing it to this method. + * + * A "preload" sprite will have its width or height crop adjusted based on the percentage of the loader in real-time. + * This allows you to easily make loading bars for games. + * + * The sprite will automatically be made visible when calling this. + * + * @method Phaser.Loader#setPreloadSprite + * @param {Phaser.Sprite|Phaser.Image} sprite - The sprite or image that will be cropped during the load. + * @param {number} [direction=0] - A value of zero means the sprite will be cropped horizontally, a value of 1 means its will be cropped vertically. + */ setPreloadSprite: function (sprite, direction) { - direction = direction || 0; this.preloadSprite = { sprite: sprite, direction: direction, width: sprite.width, height: sprite.height, rect: null }; @@ -369,58 +366,52 @@ Phaser.Loader.prototype = { sprite.crop(this.preloadSprite.rect); sprite.visible = true; - }, /** - * Called automatically by ScaleManager when the game resizes in RESIZE scalemode. - * - * This can be used to adjust the preloading sprite size, eg. - * - * @method Phaser.Loader#resize - * @protected - */ + * Called automatically by ScaleManager when the game resizes in RESIZE scalemode. + * + * This can be used to adjust the preloading sprite size, eg. + * + * @method Phaser.Loader#resize + * @protected + */ resize: function () { - if (this.preloadSprite && this.preloadSprite.height !== this.preloadSprite.sprite.height) { this.preloadSprite.rect.height = this.preloadSprite.sprite.height; } - }, /** - * Check whether a file/asset with a specific key is queued to be loaded. - * - * To access a loaded asset use Phaser.Cache, eg. {@link Phaser.Cache#checkImageKey} - * - * @method Phaser.Loader#checkKeyExists - * @param {string} type - The type asset you want to check. - * @param {string} key - Key of the asset you want to check. - * @return {boolean} Return true if exists, otherwise return false. - */ + * Check whether a file/asset with a specific key is queued to be loaded. + * + * To access a loaded asset use Phaser.Cache, eg. {@link Phaser.Cache#checkImageKey} + * + * @method Phaser.Loader#checkKeyExists + * @param {string} type - The type asset you want to check. + * @param {string} key - Key of the asset you want to check. + * @return {boolean} Return true if exists, otherwise return false. + */ checkKeyExists: function (type, key) { - return this.getAssetIndex(type, key) > -1; - }, /** - * Get the queue-index of the file/asset with a specific key. - * - * Only assets in the download file queue will be found. - * - * @method Phaser.Loader#getAssetIndex - * @param {string} type - The type asset you want to check. - * @param {string} key - Key of the asset you want to check. - * @return {number} The index of this key in the filelist, or -1 if not found. - * The index may change and should only be used immediately following this call - */ + * Get the queue-index of the file/asset with a specific key. + * + * Only assets in the download file queue will be found. + * + * @method Phaser.Loader#getAssetIndex + * @param {string} type - The type asset you want to check. + * @param {string} key - Key of the asset you want to check. + * @return {number} The index of this key in the filelist, or -1 if not found. + * The index may change and should only be used immediately following this call + */ getAssetIndex: function (type, key) { - var bestFound = -1; for (var i = 0; i < this._fileList.length; i++) @@ -440,23 +431,21 @@ Phaser.Loader.prototype = { } return bestFound; - }, /** - * Find a file/asset with a specific key. - * - * Only assets in the download file queue will be found. - * - * @method Phaser.Loader#getAsset - * @param {string} type - The type asset you want to check. - * @param {string} key - Key of the asset you want to check. - * @return {any} Returns an object if found that has 2 properties: `index` and `file`; otherwise a non-true value is returned. - * The index may change and should only be used immediately following this call. - */ + * Find a file/asset with a specific key. + * + * Only assets in the download file queue will be found. + * + * @method Phaser.Loader#getAsset + * @param {string} type - The type asset you want to check. + * @param {string} key - Key of the asset you want to check. + * @return {any} Returns an object if found that has 2 properties: `index` and `file`; otherwise a non-true value is returned. + * The index may change and should only be used immediately following this call. + */ getAsset: function (type, key) { - var fileIndex = this.getAssetIndex(type, key); if (fileIndex > -1) @@ -465,24 +454,22 @@ Phaser.Loader.prototype = { } return false; - }, /** - * Reset the loader and clear any queued assets. If `Loader.resetLocked` is true this operation will abort. - * - * This will abort any loading and clear any queued assets. - * - * Optionally you can clear any associated events. - * - * @method Phaser.Loader#reset - * @protected - * @param {boolean} [hard=false] - If true then the preload sprite and other artifacts may also be cleared. - * @param {boolean} [clearEvents=false] - If true then the all Loader signals will have removeAll called on them. - */ + * Reset the loader and clear any queued assets. If `Loader.resetLocked` is true this operation will abort. + * + * This will abort any loading and clear any queued assets. + * + * Optionally you can clear any associated events. + * + * @method Phaser.Loader#reset + * @protected + * @param {boolean} [hard=false] - If true then the preload sprite and other artifacts may also be cleared. + * @param {boolean} [clearEvents=false] - If true then the all Loader signals will have removeAll called on them. + */ reset: function (hard, clearEvents) { - if (clearEvents === undefined) { clearEvents = false; } if (this.resetLocked) @@ -516,25 +503,23 @@ Phaser.Loader.prototype = { this.onFileComplete.removeAll(); this.onFileError.removeAll(); } - }, /** - * Internal function that adds a new entry to the file list. Do not call directly. - * - * @method Phaser.Loader#addToFileList - * @protected - * @param {string} type - The type of resource to add to the list (image, audio, xml, etc). - * @param {string} key - The unique Cache ID key of this resource. - * @param {string} [url] - The URL the asset will be loaded from. - * @param {object} [properties=(none)] - Any additional properties needed to load the file. These are added directly to the added file object and overwrite any defaults. - * @param {boolean} [overwrite=false] - If true then this will overwrite a file asset of the same type/key. Otherwise it will only add a new asset. If overwrite is true, and the asset is already being loaded (or has been loaded), then it is appended instead. - * @param {string} [extension] - If no URL is given the Loader will sometimes auto-generate the URL based on the key, using this as the extension. - * @return {Phaser.Loader} This instance of the Phaser Loader. - */ + * Internal function that adds a new entry to the file list. Do not call directly. + * + * @method Phaser.Loader#addToFileList + * @protected + * @param {string} type - The type of resource to add to the list (image, audio, xml, etc). + * @param {string} key - The unique Cache ID key of this resource. + * @param {string} [url] - The URL the asset will be loaded from. + * @param {object} [properties=(none)] - Any additional properties needed to load the file. These are added directly to the added file object and overwrite any defaults. + * @param {boolean} [overwrite=false] - If true then this will overwrite a file asset of the same type/key. Otherwise it will only add a new asset. If overwrite is true, and the asset is already being loaded (or has been loaded), then it is appended instead. + * @param {string} [extension] - If no URL is given the Loader will sometimes auto-generate the URL based on the key, using this as the extension. + * @return {Phaser.Loader} This instance of the Phaser Loader. + */ addToFileList: function (type, key, url, properties, overwrite, extension) { - if (overwrite === undefined) { overwrite = false; } if (key === undefined || key === '') @@ -599,51 +584,47 @@ Phaser.Loader.prototype = { } return this; - }, /** - * Internal function that replaces an existing entry in the file list with a new one. Do not call directly. - * - * @method Phaser.Loader#replaceInFileList - * @protected - * @param {string} type - The type of resource to add to the list (image, audio, xml, etc). - * @param {string} key - The unique Cache ID key of this resource. - * @param {string} url - The URL the asset will be loaded from. - * @param {object} properties - Any additional properties needed to load the file. - */ + * Internal function that replaces an existing entry in the file list with a new one. Do not call directly. + * + * @method Phaser.Loader#replaceInFileList + * @protected + * @param {string} type - The type of resource to add to the list (image, audio, xml, etc). + * @param {string} key - The unique Cache ID key of this resource. + * @param {string} url - The URL the asset will be loaded from. + * @param {object} properties - Any additional properties needed to load the file. + */ replaceInFileList: function (type, key, url, properties) { - return this.addToFileList(type, key, url, properties, true); - }, /** - * Add a JSON resource pack ('packfile') to the Loader. - * - * A packfile is a JSON file that contains a list of assets to the be loaded. - * Please see the example 'loader/asset pack' in the Phaser Examples repository. - * - * Packs are always put before the first non-pack file that is not loaded / loading. - * - * This means that all packs added before any loading has started are added to the front - * of the file queue, in the order added. - * - * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. - * - * The URL of the packfile can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. - * - * @method Phaser.Loader#pack - * @param {string} key - Unique asset key of this resource pack. - * @param {string} [url] - URL of the Asset Pack JSON file. If you wish to pass a json object instead set this to null and pass the object as the data parameter. - * @param {object} [data] - The Asset Pack JSON data. Use this to pass in a json data object rather than loading it from a URL. TODO - * @param {object} [callbackContext=(loader)] - Some Loader operations, like Binary and Script require a context for their callbacks. Pass the context here. - * @return {Phaser.Loader} This Loader instance. - */ + * Add a JSON resource pack ('packfile') to the Loader. + * + * A packfile is a JSON file that contains a list of assets to the be loaded. + * Please see the example 'loader/asset pack' in the Phaser Examples repository. + * + * Packs are always put before the first non-pack file that is not loaded / loading. + * + * This means that all packs added before any loading has started are added to the front + * of the file queue, in the order added. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * The URL of the packfile can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * @method Phaser.Loader#pack + * @param {string} key - Unique asset key of this resource pack. + * @param {string} [url] - URL of the Asset Pack JSON file. If you wish to pass a json object instead set this to null and pass the object as the data parameter. + * @param {object} [data] - The Asset Pack JSON data. Use this to pass in a json data object rather than loading it from a URL. TODO + * @param {object} [callbackContext=(loader)] - Some Loader operations, like Binary and Script require a context for their callbacks. Pass the context here. + * @return {Phaser.Loader} This Loader instance. + */ pack: function (key, url, data, callbackContext) { - if (url === undefined) { url = null; } if (data === undefined) { data = null; } if (callbackContext === undefined) { callbackContext = null; } @@ -682,8 +663,10 @@ Phaser.Loader.prototype = { pack.loaded = true; } - // Add before first non-pack/no-loaded ~ last pack from start prior to loading - // (Read one past for splice-to-end) + /* + * Add before first non-pack/no-loaded ~ last pack from start prior to loading + * (Read one past for splice-to-end) + */ for (var i = 0; i < this._fileList.length + 1; i++) { var file = this._fileList[i]; @@ -697,61 +680,59 @@ Phaser.Loader.prototype = { } return this; - }, /** - * Adds an Image to the current load queue. - * - * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. - * - * Phaser can load all common image types: png, jpg, gif and any other format the browser can natively handle. - * - * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. - * - * Retrieve the image via `Cache.getImage(key)` - * - * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. - * - * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien" - * and no URL is given then the Loader will set the URL to be "alien.png". It will always add `.png` as the extension. - * If you do not desire this action then provide a URL. - * - * This method also supports passing in a texture object as the `url` argument. This allows you to load - * compressed textures into Phaser. You can also use `Loader.texture` to do this. - * - * Compressed Textures are a WebGL only feature, and require 3rd party tools to create. - * Available tools include Texture Packer, PVRTexTool, DirectX Texture Tool and Mali Texture Compression Tool. - * - * Supported texture compression formats are: PVRTC, S3TC and ETC1. - * Supported file formats are: PVR, DDS, KTX and PKM. - * - * The formats that support all 3 compression algorithms are PVR and KTX. - * PKM only supports ETC1, and DDS only S3TC for now. - * - * The texture path object looks like this: - * - * ```javascript - * load.image('factory', { - * etc1: 'assets/factory_etc1.pkm', - * s3tc: 'assets/factory_dxt1.pvr', - * pvrtc: 'assets/factory_pvrtc.pvr', - * truecolor: 'assets/factory.png' - * }); - * ``` - * - * The `truecolor` property points to a standard PNG file, that will be used if none of the - * compressed formats are supported by the browser / GPU. - * - * @method Phaser.Loader#image - * @param {string} key - Unique asset key of this image file. - * @param {string|object} [url] - URL of an image file. If undefined or `null` the url will be set to `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". Can also be a texture data object. - * @param {boolean} [overwrite=false] - If an unloaded file with a matching key already exists in the queue, this entry will overwrite it. - * @return {Phaser.Loader} This Loader instance. - */ + * Adds an Image to the current load queue. + * + * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. + * + * Phaser can load all common image types: png, jpg, gif and any other format the browser can natively handle. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the image via `Cache.getImage(key)` + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien" + * and no URL is given then the Loader will set the URL to be "alien.png". It will always add `.png` as the extension. + * If you do not desire this action then provide a URL. + * + * This method also supports passing in a texture object as the `url` argument. This allows you to load + * compressed textures into Phaser. You can also use `Loader.texture` to do this. + * + * Compressed Textures are a WebGL only feature, and require 3rd party tools to create. + * Available tools include Texture Packer, PVRTexTool, DirectX Texture Tool and Mali Texture Compression Tool. + * + * Supported texture compression formats are: PVRTC, S3TC and ETC1. + * Supported file formats are: PVR, DDS, KTX and PKM. + * + * The formats that support all 3 compression algorithms are PVR and KTX. + * PKM only supports ETC1, and DDS only S3TC for now. + * + * The texture path object looks like this: + * + * ```javascript + * load.image('factory', { + * etc1: 'assets/factory_etc1.pkm', + * s3tc: 'assets/factory_dxt1.pvr', + * pvrtc: 'assets/factory_pvrtc.pvr', + * truecolor: 'assets/factory.png' + * }); + * ``` + * + * The `truecolor` property points to a standard PNG file, that will be used if none of the + * compressed formats are supported by the browser / GPU. + * + * @method Phaser.Loader#image + * @param {string} key - Unique asset key of this image file. + * @param {string|object} [url] - URL of an image file. If undefined or `null` the url will be set to `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". Can also be a texture data object. + * @param {boolean} [overwrite=false] - If an unloaded file with a matching key already exists in the queue, this entry will overwrite it. + * @return {Phaser.Loader} This Loader instance. + */ image: function (key, url, overwrite) { - if (typeof url === 'object') { return this.texture(key, url, overwrite); @@ -760,98 +741,90 @@ Phaser.Loader.prototype = { { return this.addToFileList('image', key, url, undefined, overwrite, '.png'); } - }, /** - * Generate an image from a BitmapData object and add it to the current load queue. - * - * @method Phaser.Loader#imageFromBitmapData - * @param {string} key - Unique asset key for the generated image. - * @param {Phaser.BitmapData} bitmapData - * @param {boolean} [overwrite=false] - If an unloaded file with a matching key already exists in the queue, this entry will overwrite it. - * @return {Phaser.Loader} This Loader instance. - */ + * Generate an image from a BitmapData object and add it to the current load queue. + * + * @method Phaser.Loader#imageFromBitmapData + * @param {string} key - Unique asset key for the generated image. + * @param {Phaser.BitmapData} bitmapData + * @param {boolean} [overwrite=false] - If an unloaded file with a matching key already exists in the queue, this entry will overwrite it. + * @return {Phaser.Loader} This Loader instance. + */ imageFromBitmapData: function (key, bitmapData, overwrite) { - return this.image(key, bitmapData.canvas.toDataURL('image/png'), overwrite); - }, /** - * Generate a grid image and add it to the current load queue. - * - * @method Phaser.Loader#imageFromGrid - * @see Phaser.Create#grid - */ + * Generate a grid image and add it to the current load queue. + * + * @method Phaser.Loader#imageFromGrid + * @see Phaser.Create#grid + */ imageFromGrid: function (key, width, height, cellWidth, cellHeight, color) { - return this.imageFromBitmapData(key, this.game.create.grid(key, width, height, cellWidth, cellHeight, color, false)); - }, /** - * Generate a texture image and add it to the current load queue. - * - * @method Phaser.Loader#imageFromTexture - * @see Phaser.Create#texture - */ + * Generate a texture image and add it to the current load queue. + * + * @method Phaser.Loader#imageFromTexture + * @see Phaser.Create#texture + */ imageFromTexture: function (key, data, pixelWidth, pixelHeight, palette) { - return this.imageFromBitmapData(key, this.game.create.texture(key, data, pixelWidth, pixelHeight, palette, false)); - }, /** - * Adds a Compressed Texture Image to the current load queue. - * - * Compressed Textures are a WebGL only feature, and require 3rd party tools to create. - * Available tools include Texture Packer, PVRTexTool, DirectX Texture Tool and Mali Texture Compression Tool. - * - * Supported texture compression formats are: PVRTC, S3TC and ETC1. - * Supported file formats are: PVR, DDS, KTX and PKM. - * - * The formats that support all 3 compression algorithms are PVR and KTX. - * PKM only supports ETC1, and DDS only S3TC for now. - * - * The texture path object looks like this: - * - * ```javascript - * load.texture('factory', { - * etc1: 'assets/factory_etc1.pkm', - * s3tc: 'assets/factory_dxt1.pvr', - * pvrtc: 'assets/factory_pvrtc.pvr', - * truecolor: 'assets/factory.png' - * }); - * ``` - * - * The `truecolor` property points to a standard PNG file, that will be used if none of the - * compressed formats are supported by the browser / GPU. - * - * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. - * - * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. - * - * Retrieve the image via `Cache.getImage(key)` - * - * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. - * - * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien" - * and no URL is given then the Loader will set the URL to be "alien.pvr". It will always add `.pvr` as the extension. - * If you do not desire this action then provide a URL. - * - * @method Phaser.Loader#texture - * @param {string} key - Unique asset key of this image file. - * @param {object} object - The texture path data object. - * @param {boolean} [overwrite=false] - If an unloaded file with a matching key already exists in the queue, this entry will overwrite it. - * @return {Phaser.Loader} This Loader instance. - */ + * Adds a Compressed Texture Image to the current load queue. + * + * Compressed Textures are a WebGL only feature, and require 3rd party tools to create. + * Available tools include Texture Packer, PVRTexTool, DirectX Texture Tool and Mali Texture Compression Tool. + * + * Supported texture compression formats are: PVRTC, S3TC and ETC1. + * Supported file formats are: PVR, DDS, KTX and PKM. + * + * The formats that support all 3 compression algorithms are PVR and KTX. + * PKM only supports ETC1, and DDS only S3TC for now. + * + * The texture path object looks like this: + * + * ```javascript + * load.texture('factory', { + * etc1: 'assets/factory_etc1.pkm', + * s3tc: 'assets/factory_dxt1.pvr', + * pvrtc: 'assets/factory_pvrtc.pvr', + * truecolor: 'assets/factory.png' + * }); + * ``` + * + * The `truecolor` property points to a standard PNG file, that will be used if none of the + * compressed formats are supported by the browser / GPU. + * + * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the image via `Cache.getImage(key)` + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien" + * and no URL is given then the Loader will set the URL to be "alien.pvr". It will always add `.pvr` as the extension. + * If you do not desire this action then provide a URL. + * + * @method Phaser.Loader#texture + * @param {string} key - Unique asset key of this image file. + * @param {object} object - The texture path data object. + * @param {boolean} [overwrite=false] - If an unloaded file with a matching key already exists in the queue, this entry will overwrite it. + * @return {Phaser.Loader} This Loader instance. + */ texture: function (key, object, overwrite) { - if (this.game.renderType === Phaser.WEBGL) { var compression = this.game.renderer.extensions.compression; @@ -866,8 +839,10 @@ Phaser.Loader.prototype = { } } - // Check if we have a truecolor texture to fallback. - // Also catches calls to this function that are from a Canvas renderer + /* + * Check if we have a truecolor texture to fallback. + * Also catches calls to this function that are from a Canvas renderer + */ if (object.truecolor) { @@ -875,36 +850,34 @@ Phaser.Loader.prototype = { } return this; - }, /** - * Adds an array of images to the current load queue. - * - * It works by passing each element of the array to the Loader.image method. - * - * The files are **not** loaded immediately after calling this method. The files are added to the queue ready to be loaded when the loader starts. - * - * Phaser can load all common image types: png, jpg, gif and any other format the browser can natively handle. - * - * The keys must be unique Strings. They are used to add the files to the Phaser.Cache upon successful load. - * - * Retrieve the images via `Cache.getImage(key)` - * - * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. - * - * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien" - * and no URL is given then the Loader will set the URL to be "alien.png". It will always add `.png` as the extension. - * If you do not desire this action then provide a URL. - * - * @method Phaser.Loader#images - * @param {array} keys - An array of unique asset keys of the image files. - * @param {array} [urls] - Optional array of URLs. If undefined or `null` the url will be set to `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". If provided the URLs array length must match the keys array length. - * @return {Phaser.Loader} This Loader instance. + * Adds an array of images to the current load queue. + * + * It works by passing each element of the array to the Loader.image method. + * + * The files are **not** loaded immediately after calling this method. The files are added to the queue ready to be loaded when the loader starts. + * + * Phaser can load all common image types: png, jpg, gif and any other format the browser can natively handle. + * + * The keys must be unique Strings. They are used to add the files to the Phaser.Cache upon successful load. + * + * Retrieve the images via `Cache.getImage(key)` + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien" + * and no URL is given then the Loader will set the URL to be "alien.png". It will always add `.png` as the extension. + * If you do not desire this action then provide a URL. + * + * @method Phaser.Loader#images + * @param {array} keys - An array of unique asset keys of the image files. + * @param {array} [urls] - Optional array of URLs. If undefined or `null` the url will be set to `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". If provided the URLs array length must match the keys array length. + * @return {Phaser.Loader} This Loader instance. */ images: function (keys, urls) { - if (Array.isArray(urls)) { for (var i = 0; i < keys.length; i++) @@ -921,292 +894,276 @@ Phaser.Loader.prototype = { } return this; - }, /** - * Adds a Text file to the current load queue. - * - * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. - * - * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. - * - * Retrieve the file via `Cache.getText(key)` - * - * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. - * - * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien" - * and no URL is given then the Loader will set the URL to be "alien.txt". It will always add `.txt` as the extension. - * If you do not desire this action then provide a URL. - * - * @method Phaser.Loader#text - * @param {string} key - Unique asset key of the text file. - * @param {string} [url] - URL of the text file. If undefined or `null` the url will be set to `.txt`, i.e. if `key` was "alien" then the URL will be "alien.txt". - * @param {boolean} [overwrite=false] - If an unloaded file with a matching key already exists in the queue, this entry will overwrite it. - * @return {Phaser.Loader} This Loader instance. - */ + * Adds a Text file to the current load queue. + * + * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getText(key)` + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien" + * and no URL is given then the Loader will set the URL to be "alien.txt". It will always add `.txt` as the extension. + * If you do not desire this action then provide a URL. + * + * @method Phaser.Loader#text + * @param {string} key - Unique asset key of the text file. + * @param {string} [url] - URL of the text file. If undefined or `null` the url will be set to `.txt`, i.e. if `key` was "alien" then the URL will be "alien.txt". + * @param {boolean} [overwrite=false] - If an unloaded file with a matching key already exists in the queue, this entry will overwrite it. + * @return {Phaser.Loader} This Loader instance. + */ text: function (key, url, overwrite) { - return this.addToFileList('text', key, url, undefined, overwrite, '.txt'); - }, /** - * Adds a JSON file to the current load queue. - * - * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. - * - * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. - * - * Retrieve the file via `Cache.getJSON(key)`. JSON files are automatically parsed upon load. - * If you need to control when the JSON is parsed then use `Loader.text` instead and parse the text file as needed. - * - * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. - * - * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien" - * and no URL is given then the Loader will set the URL to be "alien.json". It will always add `.json` as the extension. - * If you do not desire this action then provide a URL. - * - * @method Phaser.Loader#json - * @param {string} key - Unique asset key of the json file. - * @param {string} [url] - URL of the JSON file. If undefined or `null` the url will be set to `.json`, i.e. if `key` was "alien" then the URL will be "alien.json". - * @param {boolean} [overwrite=false] - If an unloaded file with a matching key already exists in the queue, this entry will overwrite it. - * @return {Phaser.Loader} This Loader instance. - */ + * Adds a JSON file to the current load queue. + * + * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getJSON(key)`. JSON files are automatically parsed upon load. + * If you need to control when the JSON is parsed then use `Loader.text` instead and parse the text file as needed. + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien" + * and no URL is given then the Loader will set the URL to be "alien.json". It will always add `.json` as the extension. + * If you do not desire this action then provide a URL. + * + * @method Phaser.Loader#json + * @param {string} key - Unique asset key of the json file. + * @param {string} [url] - URL of the JSON file. If undefined or `null` the url will be set to `.json`, i.e. if `key` was "alien" then the URL will be "alien.json". + * @param {boolean} [overwrite=false] - If an unloaded file with a matching key already exists in the queue, this entry will overwrite it. + * @return {Phaser.Loader} This Loader instance. + */ json: function (key, url, overwrite) { - return this.addToFileList('json', key, url, undefined, overwrite, '.json'); - }, /** - * Adds a fragment shader file to the current load queue. - * - * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. - * - * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. - * - * Retrieve the file via `Cache.getShader(key)`. - * - * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. - * - * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "blur" - * and no URL is given then the Loader will set the URL to be "blur.frag". It will always add `.frag` as the extension. - * If you do not desire this action then provide a URL. - * - * @method Phaser.Loader#shader - * @param {string} key - Unique asset key of the fragment file. - * @param {string} [url] - URL of the fragment file. If undefined or `null` the url will be set to `.frag`, i.e. if `key` was "blur" then the URL will be "blur.frag". - * @param {boolean} [overwrite=false] - If an unloaded file with a matching key already exists in the queue, this entry will overwrite it. - * @return {Phaser.Loader} This Loader instance. - */ + * Adds a fragment shader file to the current load queue. + * + * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getShader(key)`. + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "blur" + * and no URL is given then the Loader will set the URL to be "blur.frag". It will always add `.frag` as the extension. + * If you do not desire this action then provide a URL. + * + * @method Phaser.Loader#shader + * @param {string} key - Unique asset key of the fragment file. + * @param {string} [url] - URL of the fragment file. If undefined or `null` the url will be set to `.frag`, i.e. if `key` was "blur" then the URL will be "blur.frag". + * @param {boolean} [overwrite=false] - If an unloaded file with a matching key already exists in the queue, this entry will overwrite it. + * @return {Phaser.Loader} This Loader instance. + */ shader: function (key, url, overwrite) { - return this.addToFileList('shader', key, url, undefined, overwrite, '.frag'); - }, /** - * Adds an XML file to the current load queue. - * - * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. - * - * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. - * - * Retrieve the file via `Cache.getXML(key)`. - * - * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. - * - * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien" - * and no URL is given then the Loader will set the URL to be "alien.xml". It will always add `.xml` as the extension. - * If you do not desire this action then provide a URL. - * - * @method Phaser.Loader#xml - * @param {string} key - Unique asset key of the xml file. - * @param {string} [url] - URL of the XML file. If undefined or `null` the url will be set to `.xml`, i.e. if `key` was "alien" then the URL will be "alien.xml". - * @param {boolean} [overwrite=false] - If an unloaded file with a matching key already exists in the queue, this entry will overwrite it. - * @return {Phaser.Loader} This Loader instance. - */ + * Adds an XML file to the current load queue. + * + * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getXML(key)`. + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien" + * and no URL is given then the Loader will set the URL to be "alien.xml". It will always add `.xml` as the extension. + * If you do not desire this action then provide a URL. + * + * @method Phaser.Loader#xml + * @param {string} key - Unique asset key of the xml file. + * @param {string} [url] - URL of the XML file. If undefined or `null` the url will be set to `.xml`, i.e. if `key` was "alien" then the URL will be "alien.xml". + * @param {boolean} [overwrite=false] - If an unloaded file with a matching key already exists in the queue, this entry will overwrite it. + * @return {Phaser.Loader} This Loader instance. + */ xml: function (key, url, overwrite) { - return this.addToFileList('xml', key, url, undefined, overwrite, '.xml'); - }, /** - * Adds a JavaScript file to the current load queue. - * - * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. - * - * The key must be a unique String. - * - * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. - * - * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien" - * and no URL is given then the Loader will set the URL to be "alien.js". It will always add `.js` as the extension. - * If you do not desire this action then provide a URL. - * - * Upon successful load the JavaScript is automatically turned into a script tag and executed, so be careful what you load! - * - * A callback, which will be invoked as the script tag has been created, can also be specified. - * The callback must return relevant `data`. - * - * @method Phaser.Loader#script - * @param {string} key - Unique asset key of the script file. - * @param {string} [url] - URL of the JavaScript file. If undefined or `null` the url will be set to `.js`, i.e. if `key` was "alien" then the URL will be "alien.js". - * @param {function} [callback=(none)] - Optional callback that will be called after the script tag has loaded, so you can perform additional processing. - * @param {object} [callbackContext=(loader)] - The context under which the callback will be applied. If not specified it will use the Phaser Loader as the context. - * @return {Phaser.Loader} This Loader instance. - */ + * Adds a JavaScript file to the current load queue. + * + * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. + * + * The key must be a unique String. + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien" + * and no URL is given then the Loader will set the URL to be "alien.js". It will always add `.js` as the extension. + * If you do not desire this action then provide a URL. + * + * Upon successful load the JavaScript is automatically turned into a script tag and executed, so be careful what you load! + * + * A callback, which will be invoked as the script tag has been created, can also be specified. + * The callback must return relevant `data`. + * + * @method Phaser.Loader#script + * @param {string} key - Unique asset key of the script file. + * @param {string} [url] - URL of the JavaScript file. If undefined or `null` the url will be set to `.js`, i.e. if `key` was "alien" then the URL will be "alien.js". + * @param {function} [callback=(none)] - Optional callback that will be called after the script tag has loaded, so you can perform additional processing. + * @param {object} [callbackContext=(loader)] - The context under which the callback will be applied. If not specified it will use the Phaser Loader as the context. + * @return {Phaser.Loader} This Loader instance. + */ script: function (key, url, callback, callbackContext) { - if (callback === undefined) { callback = false; } if (callback !== false && callbackContext === undefined) { callbackContext = this; } return this.addToFileList('script', key, url, { syncPoint: true, callback: callback, callbackContext: callbackContext }, false, '.js'); - }, /** - * Adds a binary file to the current load queue. - * - * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. - * - * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. - * - * Retrieve the file via `Cache.getBinary(key)`. - * - * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. - * - * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien" - * and no URL is given then the Loader will set the URL to be "alien.bin". It will always add `.bin` as the extension. - * If you do not desire this action then provide a URL. - * - * It will be loaded via xhr with a responseType of "arraybuffer". You can specify an optional callback to process the file after load. - * When the callback is called it will be passed 2 parameters: the key of the file and the file data. - * - * WARNING: If a callback is specified the data will be set to whatever it returns. Always return the data object, even if you didn't modify it. - * - * @method Phaser.Loader#binary - * @param {string} key - Unique asset key of the binary file. - * @param {string} [url] - URL of the binary file. If undefined or `null` the url will be set to `.bin`, i.e. if `key` was "alien" then the URL will be "alien.bin". - * @param {function} [callback=(none)] - Optional callback that will be passed the file after loading, so you can perform additional processing on it. - * @param {object} [callbackContext] - The context under which the callback will be applied. If not specified it will use the callback itself as the context. - * @return {Phaser.Loader} This Loader instance. - */ + * Adds a binary file to the current load queue. + * + * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getBinary(key)`. + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien" + * and no URL is given then the Loader will set the URL to be "alien.bin". It will always add `.bin` as the extension. + * If you do not desire this action then provide a URL. + * + * It will be loaded via xhr with a responseType of "arraybuffer". You can specify an optional callback to process the file after load. + * When the callback is called it will be passed 2 parameters: the key of the file and the file data. + * + * WARNING: If a callback is specified the data will be set to whatever it returns. Always return the data object, even if you didn't modify it. + * + * @method Phaser.Loader#binary + * @param {string} key - Unique asset key of the binary file. + * @param {string} [url] - URL of the binary file. If undefined or `null` the url will be set to `.bin`, i.e. if `key` was "alien" then the URL will be "alien.bin". + * @param {function} [callback=(none)] - Optional callback that will be passed the file after loading, so you can perform additional processing on it. + * @param {object} [callbackContext] - The context under which the callback will be applied. If not specified it will use the callback itself as the context. + * @return {Phaser.Loader} This Loader instance. + */ binary: function (key, url, callback, callbackContext) { - if (callback === undefined) { callback = false; } // Why is the default callback context the ..callback? if (callback !== false && callbackContext === undefined) { callbackContext = callback; } return this.addToFileList('binary', key, url, { callback: callback, callbackContext: callbackContext }, false, '.bin'); - }, /** - * Adds a Sprite Sheet to the current load queue. - * - * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. - * - * To clarify the terminology that Phaser uses: A Sprite Sheet is an image containing frames, usually of an animation, that are all equal - * dimensions and often in sequence. For example if the frame size is 32x32 then every frame in the sprite sheet will be that size. - * Sometimes (outside of Phaser) the term "sprite sheet" is used to refer to a texture atlas. - * A Texture Atlas works by packing together images as best it can, using whatever frame sizes it likes, often with cropping and trimming - * the frames in the process. Software such as Texture Packer, Flash CC or Shoebox all generate texture atlases, not sprite sheets. - * If you've got an atlas then use `Loader.atlas` instead. - * - * The key must be a unique String. It is used to add the image to the Phaser.Cache upon successful load. - * - * Retrieve the file via `Cache.getImage(key)`. Sprite sheets, being image based, live in the same Cache as all other Images. - * - * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. - * - * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien" - * and no URL is given then the Loader will set the URL to be "alien.png". It will always add `.png` as the extension. - * If you do not desire this action then provide a URL. - * - * An image with four frames, `margin = 1`, and `spacing = 2` looks like this: - * - * ``` - * ........ - * .# # . - * . . - * . . - * .# # . - * . . - * . . - * ........ - * - * . margin - * spacing - * # sprite frame - * ``` - * - * `spacing` must be on only the right and bottom edges of each frame, including the last row and column. - * - * The first sprite frame is found at (margin) px from the left of the image. - * The second sprite frame is found at (margin + frameWidth + spacing) px from the left of the image, and so on. - * - * @method Phaser.Loader#spritesheet - * @param {string} key - Unique asset key of the sheet file. - * @param {string} url - URL of the sprite sheet file. If undefined or `null` the url will be set to `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". - * @param {number} frameWidth - Width in pixels of a single frame in the sprite sheet. - * @param {number} frameHeight - Height in pixels of a single frame in the sprite sheet. - * @param {number} [frameMax=-1] - How many frames in this sprite sheet. If not specified it will divide the whole image into frames. - * @param {number} [margin=0] - The distance from the top-left of the image to the top-left of the first frame, if any. - * @param {number} [spacing=0] - The distance from the right edge of a frame to the left edge of the next frame on the same row, from the right edge of the last frame of a row to the margin, from the bottom edge of a frame to the top edge of the next frame on the same column, and from the bottom edge of the last frame of a column to the margin. - * @param {number} [skipFrames=0] - Skip a number of frames. Useful when there are multiple sprite sheets in one image. - * @return {Phaser.Loader} This Loader instance. - */ + * Adds a Sprite Sheet to the current load queue. + * + * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. + * + * To clarify the terminology that Phaser uses: A Sprite Sheet is an image containing frames, usually of an animation, that are all equal + * dimensions and often in sequence. For example if the frame size is 32x32 then every frame in the sprite sheet will be that size. + * Sometimes (outside of Phaser) the term "sprite sheet" is used to refer to a texture atlas. + * A Texture Atlas works by packing together images as best it can, using whatever frame sizes it likes, often with cropping and trimming + * the frames in the process. Software such as Texture Packer, Flash CC or Shoebox all generate texture atlases, not sprite sheets. + * If you've got an atlas then use `Loader.atlas` instead. + * + * The key must be a unique String. It is used to add the image to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getImage(key)`. Sprite sheets, being image based, live in the same Cache as all other Images. + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien" + * and no URL is given then the Loader will set the URL to be "alien.png". It will always add `.png` as the extension. + * If you do not desire this action then provide a URL. + * + * An image with four frames, `margin = 1`, and `spacing = 2` looks like this: + * + * ``` + * ........ + * .# # . + * . . + * . . + * .# # . + * . . + * . . + * ........ + * + * . margin + * spacing + * # sprite frame + * ``` + * + * `spacing` must be on only the right and bottom edges of each frame, including the last row and column. + * + * The first sprite frame is found at (margin) px from the left of the image. + * The second sprite frame is found at (margin + frameWidth + spacing) px from the left of the image, and so on. + * + * @method Phaser.Loader#spritesheet + * @param {string} key - Unique asset key of the sheet file. + * @param {string} url - URL of the sprite sheet file. If undefined or `null` the url will be set to `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". + * @param {number} frameWidth - Width in pixels of a single frame in the sprite sheet. + * @param {number} frameHeight - Height in pixels of a single frame in the sprite sheet. + * @param {number} [frameMax=-1] - How many frames in this sprite sheet. If not specified it will divide the whole image into frames. + * @param {number} [margin=0] - The distance from the top-left of the image to the top-left of the first frame, if any. + * @param {number} [spacing=0] - The distance from the right edge of a frame to the left edge of the next frame on the same row, from the right edge of the last frame of a row to the margin, from the bottom edge of a frame to the top edge of the next frame on the same column, and from the bottom edge of the last frame of a column to the margin. + * @param {number} [skipFrames=0] - Skip a number of frames. Useful when there are multiple sprite sheets in one image. + * @return {Phaser.Loader} This Loader instance. + */ spritesheet: function (key, url, frameWidth, frameHeight, frameMax, margin, spacing, skipFrames) { - if (frameMax === undefined) { frameMax = -1; } if (margin === undefined) { margin = 0; } if (spacing === undefined) { spacing = 0; } if (skipFrames === undefined) { skipFrames = 0; } return this.addToFileList('spritesheet', key, url, { frameWidth: frameWidth, frameHeight: frameHeight, frameMax: frameMax, margin: margin, spacing: spacing, skipFrames: skipFrames }, false, '.png'); - }, /** - * Adds an audio file to the current load queue. - * - * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. - * - * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. - * - * Retrieve the file via `Cache.getSound(key)`. - * - * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. - * - * Mobile warning: There are some mobile devices (certain iPad 2 and iPad Mini revisions) that cannot play 48000 Hz audio. - * When they try to play the audio becomes extremely distorted and buzzes, eventually crashing the sound system. - * The solution is to use a lower encoding rate such as 44100 Hz. - * - * @method Phaser.Loader#audio - * @param {string} key - Unique asset key of the audio file. - * @param {string|string[]|object[]} urls - Either a single string or an array of URIs or pairs of `{uri: .., type: ..}`. - * If an array is specified then the first URI (or URI + mime pair) that is device-compatible will be selected. - * For example: `"jump.mp3"`, `['jump.mp3', 'jump.ogg', 'jump.m4a']`, or `[{uri: "data:", type: 'opus'}, 'fallback.mp3']`. - * BLOB and DATA URIs can be used but only support automatic detection when used in the pair form; otherwise the format must be manually checked before adding the resource. - * @param {boolean} [autoDecode=true] - When using Web Audio the audio files can either be decoded at load time or run-time. - * Audio files can't be played until they are decoded and, if specified, this enables immediate decoding. Decoding is a non-blocking async process, however it consumes huge amounts of CPU time on mobiles especially. - * @return {Phaser.Loader} This Loader instance. - */ + * Adds an audio file to the current load queue. + * + * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getSound(key)`. + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * Mobile warning: There are some mobile devices (certain iPad 2 and iPad Mini revisions) that cannot play 48000 Hz audio. + * When they try to play the audio becomes extremely distorted and buzzes, eventually crashing the sound system. + * The solution is to use a lower encoding rate such as 44100 Hz. + * + * @method Phaser.Loader#audio + * @param {string} key - Unique asset key of the audio file. + * @param {string|string[]|object[]} urls - Either a single string or an array of URIs or pairs of `{uri: .., type: ..}`. + * If an array is specified then the first URI (or URI + mime pair) that is device-compatible will be selected. + * For example: `"jump.mp3"`, `['jump.mp3', 'jump.ogg', 'jump.m4a']`, or `[{uri: "data:", type: 'opus'}, 'fallback.mp3']`. + * BLOB and DATA URIs can be used but only support automatic detection when used in the pair form; otherwise the format must be manually checked before adding the resource. + * @param {boolean} [autoDecode=true] - When using Web Audio the audio files can either be decoded at load time or run-time. + * Audio files can't be played until they are decoded and, if specified, this enables immediate decoding. Decoding is a non-blocking async process, however it consumes huge amounts of CPU time on mobiles especially. + * @return {Phaser.Loader} This Loader instance. + */ audio: function (key, urls, autoDecode) { - if (this.game.sound.noAudio) { return this; @@ -1220,36 +1177,34 @@ Phaser.Loader.prototype = { } return this.addToFileList('audio', key, urls, { buffer: null, autoDecode: autoDecode }); - }, /** - * Adds an audio sprite file to the current load queue. - * - * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. - * - * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. - * - * Audio Sprites are a combination of audio files and a JSON configuration. - * - * The JSON follows the format of that created by https://github.com/tonistiigi/audiosprite - * - * Retrieve the file via `Cache.getSoundData(key)`. - * - * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. - * - * @method Phaser.Loader#audioSprite - * @param {string} key - Unique asset key of the audio file. - * @param {Array|string} urls - An array containing the URLs of the audio files, i.e.: [ 'audiosprite.mp3', 'audiosprite.ogg', 'audiosprite.m4a' ] or a single string containing just one URL. - * @param {string} [jsonURL=null] - The URL of the audiosprite configuration JSON object. If you wish to pass the data directly set this parameter to null. - * @param {string|object} [jsonData=null] - A JSON object or string containing the audiosprite configuration data. This is ignored if jsonURL is not null. - * @param {boolean} [autoDecode=true] - When using Web Audio the audio files can either be decoded at load time or run-time. - * Audio files can't be played until they are decoded and, if specified, this enables immediate decoding. Decoding is a non-blocking async process, however it consumes huge amounts of CPU time on mobiles especially. - * @return {Phaser.Loader} This Loader instance. - */ + * Adds an audio sprite file to the current load queue. + * + * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Audio Sprites are a combination of audio files and a JSON configuration. + * + * The JSON follows the format of that created by https://github.com/tonistiigi/audiosprite + * + * Retrieve the file via `Cache.getSoundData(key)`. + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * @method Phaser.Loader#audioSprite + * @param {string} key - Unique asset key of the audio file. + * @param {Array|string} urls - An array containing the URLs of the audio files, i.e.: [ 'audiosprite.mp3', 'audiosprite.ogg', 'audiosprite.m4a' ] or a single string containing just one URL. + * @param {string} [jsonURL=null] - The URL of the audiosprite configuration JSON object. If you wish to pass the data directly set this parameter to null. + * @param {string|object} [jsonData=null] - A JSON object or string containing the audiosprite configuration data. This is ignored if jsonURL is not null. + * @param {boolean} [autoDecode=true] - When using Web Audio the audio files can either be decoded at load time or run-time. + * Audio files can't be played until they are decoded and, if specified, this enables immediate decoding. Decoding is a non-blocking async process, however it consumes huge amounts of CPU time on mobiles especially. + * @return {Phaser.Loader} This Loader instance. + */ audioSprite: function (key, urls, jsonURL, jsonData, autoDecode) { - if (this.game.sound.noAudio) { return this; @@ -1280,60 +1235,56 @@ Phaser.Loader.prototype = { } return this; - }, /** - * A legacy alias for Loader.audioSprite. Please see that method for documentation. - * - * @method Phaser.Loader#audiosprite - * @param {string} key - Unique asset key of the audio file. - * @param {Array|string} urls - An array containing the URLs of the audio files, i.e.: [ 'audiosprite.mp3', 'audiosprite.ogg', 'audiosprite.m4a' ] or a single string containing just one URL. - * @param {string} [jsonURL=null] - The URL of the audiosprite configuration JSON object. If you wish to pass the data directly set this parameter to null. - * @param {string|object} [jsonData=null] - A JSON object or string containing the audiosprite configuration data. This is ignored if jsonURL is not null. - * @param {boolean} [autoDecode=true] - When using Web Audio the audio files can either be decoded at load time or run-time. - * Audio files can't be played until they are decoded and, if specified, this enables immediate decoding. Decoding is a non-blocking async process, however it consumes huge amounts of CPU time on mobiles especially. - * @return {Phaser.Loader} This Loader instance. - */ + * A legacy alias for Loader.audioSprite. Please see that method for documentation. + * + * @method Phaser.Loader#audiosprite + * @param {string} key - Unique asset key of the audio file. + * @param {Array|string} urls - An array containing the URLs of the audio files, i.e.: [ 'audiosprite.mp3', 'audiosprite.ogg', 'audiosprite.m4a' ] or a single string containing just one URL. + * @param {string} [jsonURL=null] - The URL of the audiosprite configuration JSON object. If you wish to pass the data directly set this parameter to null. + * @param {string|object} [jsonData=null] - A JSON object or string containing the audiosprite configuration data. This is ignored if jsonURL is not null. + * @param {boolean} [autoDecode=true] - When using Web Audio the audio files can either be decoded at load time or run-time. + * Audio files can't be played until they are decoded and, if specified, this enables immediate decoding. Decoding is a non-blocking async process, however it consumes huge amounts of CPU time on mobiles especially. + * @return {Phaser.Loader} This Loader instance. + */ audiosprite: function (key, urls, jsonURL, jsonData, autoDecode) { - return this.audioSprite(key, urls, jsonURL, jsonData, autoDecode); - }, /** - * Adds a video file to the current load queue. - * - * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. - * - * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. - * - * Retrieve the file via `Cache.getVideo(key)`. - * - * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. - * - * You don't need to preload a video in order to play it in your game. See `Video.createVideoFromURL` for details. - * - * @method Phaser.Loader#video - * @param {string} key - Unique asset key of the video file. - * @param {string|string[]|object[]} urls - Either a single string or an array of URIs or pairs of `{uri: .., type: ..}`. - * If an array is specified then the first URI (or URI + mime pair) that is device-compatible will be selected. - * For example: `"boom.mp4"`, `['boom.mp4', 'boom.ogg', 'boom.webm']`, or `[{uri: "data:", type: 'opus'}, 'fallback.mp4']`. - * BLOB and DATA URIs can be used but only support automatic detection when used in the pair form; otherwise the format must be manually checked before adding the resource. - * @param {string} [loadEvent='canplaythrough'] - This sets the Video source event to listen for before the load is considered complete. - * 'canplaythrough' implies the video has downloaded enough, and bandwidth is high enough that it can be played to completion. - * 'canplay' implies the video has downloaded enough to start playing, but not necessarily to finish. - * 'loadeddata' just makes sure that the video meta data and first frame have downloaded. Phaser uses this value automatically if the - * browser is detected as being Firefox and no `loadEvent` is given, otherwise it defaults to `canplaythrough`. - * @param {boolean} [asBlob=false] - Video files can either be loaded via the creation of a video element which has its src property set. - * Or they can be loaded via xhr, stored as binary data in memory and then converted to a Blob. This isn't supported in IE9 or Android 2. - * If you need to have the same video playing at different times across multiple Sprites then you need to load it as a Blob. - * @return {Phaser.Loader} This Loader instance. - */ + * Adds a video file to the current load queue. + * + * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getVideo(key)`. + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * You don't need to preload a video in order to play it in your game. See `Video.createVideoFromURL` for details. + * + * @method Phaser.Loader#video + * @param {string} key - Unique asset key of the video file. + * @param {string|string[]|object[]} urls - Either a single string or an array of URIs or pairs of `{uri: .., type: ..}`. + * If an array is specified then the first URI (or URI + mime pair) that is device-compatible will be selected. + * For example: `"boom.mp4"`, `['boom.mp4', 'boom.ogg', 'boom.webm']`, or `[{uri: "data:", type: 'opus'}, 'fallback.mp4']`. + * BLOB and DATA URIs can be used but only support automatic detection when used in the pair form; otherwise the format must be manually checked before adding the resource. + * @param {string} [loadEvent='canplaythrough'] - This sets the Video source event to listen for before the load is considered complete. + * 'canplaythrough' implies the video has downloaded enough, and bandwidth is high enough that it can be played to completion. + * 'canplay' implies the video has downloaded enough to start playing, but not necessarily to finish. + * 'loadeddata' just makes sure that the video meta data and first frame have downloaded. Phaser uses this value automatically if the + * browser is detected as being Firefox and no `loadEvent` is given, otherwise it defaults to `canplaythrough`. + * @param {boolean} [asBlob=false] - Video files can either be loaded via the creation of a video element which has its src property set. + * Or they can be loaded via xhr, stored as binary data in memory and then converted to a Blob. This isn't supported in IE9 or Android 2. + * If you need to have the same video playing at different times across multiple Sprites then you need to load it as a Blob. + * @return {Phaser.Loader} This Loader instance. + */ video: function (key, urls, loadEvent, asBlob) { - if (loadEvent === undefined) { if (this.game.device.firefox) @@ -1354,45 +1305,43 @@ Phaser.Loader.prototype = { } return this.addToFileList('video', key, urls, { buffer: null, asBlob: asBlob, loadEvent: loadEvent }); - }, /** - * Adds a Tile Map data file to the current load queue. - * - * Phaser can load data in two different formats: CSV and Tiled JSON. - * - * Tiled is a free software package, specifically for creating tilemaps, and is available from http://www.mapeditor.org - * - * You can choose to either load the data externally, by providing a URL to a json file. - * Or you can pass in a JSON object or String via the `data` parameter. - * If you pass a String the data is automatically run through `JSON.parse` and then immediately added to the Phaser.Cache. - * - * If a URL is provided the file is **not** loaded immediately after calling this method, but is added to the load queue. - * - * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. - * - * Retrieve the file via `Cache.getTilemapData(key)`. JSON files are automatically parsed upon load. - * If you need to control when the JSON is parsed then use `Loader.text` instead and parse the text file as needed. - * - * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. - * - * If the URL isn't specified and no data is given then the Loader will take the key and create a filename from that. - * For example if the key is "level1" and no URL or data is given then the Loader will set the URL to be "level1.json". - * If you set the format to be Tilemap.CSV it will set the URL to be "level1.csv" instead. - * - * If you do not desire this action then provide a URL or data object. - * - * @method Phaser.Loader#tilemap - * @param {string} key - Unique asset key of the tilemap data. - * @param {string} [url] - URL of the tile map file. If undefined or `null` and no data is given the url will be set to `.json`, i.e. if `key` was "level1" then the URL will be "level1.json". - * @param {object|string} [data] - An optional JSON data object. If given then the url is ignored and this JSON object is used for map data instead. - * @param {number} [format=Phaser.Tilemap.CSV] - The format of the map data. Either Phaser.Tilemap.CSV or Phaser.Tilemap.TILED_JSON. - * @return {Phaser.Loader} This Loader instance. - */ + * Adds a Tile Map data file to the current load queue. + * + * Phaser can load data in two different formats: CSV and Tiled JSON. + * + * Tiled is a free software package, specifically for creating tilemaps, and is available from http://www.mapeditor.org + * + * You can choose to either load the data externally, by providing a URL to a json file. + * Or you can pass in a JSON object or String via the `data` parameter. + * If you pass a String the data is automatically run through `JSON.parse` and then immediately added to the Phaser.Cache. + * + * If a URL is provided the file is **not** loaded immediately after calling this method, but is added to the load queue. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getTilemapData(key)`. JSON files are automatically parsed upon load. + * If you need to control when the JSON is parsed then use `Loader.text` instead and parse the text file as needed. + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the URL isn't specified and no data is given then the Loader will take the key and create a filename from that. + * For example if the key is "level1" and no URL or data is given then the Loader will set the URL to be "level1.json". + * If you set the format to be Tilemap.CSV it will set the URL to be "level1.csv" instead. + * + * If you do not desire this action then provide a URL or data object. + * + * @method Phaser.Loader#tilemap + * @param {string} key - Unique asset key of the tilemap data. + * @param {string} [url] - URL of the tile map file. If undefined or `null` and no data is given the url will be set to `.json`, i.e. if `key` was "level1" then the URL will be "level1.json". + * @param {object|string} [data] - An optional JSON data object. If given then the url is ignored and this JSON object is used for map data instead. + * @param {number} [format=Phaser.Tilemap.CSV] - The format of the map data. Either Phaser.Tilemap.CSV or Phaser.Tilemap.TILED_JSON. + * @return {Phaser.Loader} This Loader instance. + */ tilemap: function (key, url, data, format) { - if (url === undefined) { url = null; } if (data === undefined) { data = null; } if (format === undefined) { format = Phaser.Tilemap.CSV; } @@ -1437,79 +1386,73 @@ Phaser.Loader.prototype = { } return this; - }, /** - * Adds a CSV Map data file to the current load queue. - * - * @method Phaser.Loader#tilemapCSV - * @param {string} key - Unique asset key of the tilemap data. - * @param {string} [url] - URL of the tile map file. If undefined or `null` and no data is given the url will be set to `.csv`, i.e. if `key` was "level1" then the URL will be "level1.csv". - * @param {string} [data] - A CSV data string. If given then the url is ignored and this is used for map data instead. - * @return {Phaser.Loader} This Loader instance. - * - * @see Phaser.Loader#tilemap - */ + * Adds a CSV Map data file to the current load queue. + * + * @method Phaser.Loader#tilemapCSV + * @param {string} key - Unique asset key of the tilemap data. + * @param {string} [url] - URL of the tile map file. If undefined or `null` and no data is given the url will be set to `.csv`, i.e. if `key` was "level1" then the URL will be "level1.csv". + * @param {string} [data] - A CSV data string. If given then the url is ignored and this is used for map data instead. + * @return {Phaser.Loader} This Loader instance. + * + * @see Phaser.Loader#tilemap + */ tilemapCSV: function (key, url, data) { - return this.tilemap(key, url, data, Phaser.Tilemap.CSV); - }, /** - * Adds a Tiled JSON Map data file to the current load queue. - * - * @method Phaser.Loader#tilemapTiledJSON - * @param {string} key - Unique asset key of the tilemap data. - * @param {string} [url] - URL of the tile map file. If undefined or `null` and no data is given the url will be set to `.json`, i.e. if `key` was "level1" then the URL will be "level1.json". - * @param {object|string} [data] - A JSON data object or string. If given then the url is ignored and this is used for map data instead. - * @return {Phaser.Loader} This Loader instance. - * - * @see Phaser.Loader#tilemap - */ + * Adds a Tiled JSON Map data file to the current load queue. + * + * @method Phaser.Loader#tilemapTiledJSON + * @param {string} key - Unique asset key of the tilemap data. + * @param {string} [url] - URL of the tile map file. If undefined or `null` and no data is given the url will be set to `.json`, i.e. if `key` was "level1" then the URL will be "level1.json". + * @param {object|string} [data] - A JSON data object or string. If given then the url is ignored and this is used for map data instead. + * @return {Phaser.Loader} This Loader instance. + * + * @see Phaser.Loader#tilemap + */ tilemapTiledJSON: function (key, url, data) { - return this.tilemap(key, url, data, Phaser.Tilemap.TILED_JSON); - }, /** - * Adds a physics data file to the current load queue. - * - * The data must be in `Lime + Corona` JSON format. [Physics Editor](https://www.codeandweb.com) by code'n'web exports in this format natively. - * - * You can choose to either load the data externally, by providing a URL to a json file. - * Or you can pass in a JSON object or String via the `data` parameter. - * If you pass a String the data is automatically run through `JSON.parse` and then immediately added to the Phaser.Cache. - * - * If a URL is provided the file is **not** loaded immediately after calling this method, but is added to the load queue. - * - * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. - * - * Retrieve the file via `Cache.getJSON(key)`. JSON files are automatically parsed upon load. - * If you need to control when the JSON is parsed then use `Loader.text` instead and parse the text file as needed. - * - * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. - * - * If the URL isn't specified and no data is given then the Loader will take the key and create a filename from that. - * For example if the key is "alien" and no URL or data is given then the Loader will set the URL to be "alien.json". - * It will always use `.json` as the extension. - * - * If you do not desire this action then provide a URL or data object. - * - * @method Phaser.Loader#physics - * @param {string} key - Unique asset key of the physics json data. - * @param {string} [url] - URL of the physics data file. If undefined or `null` and no data is given the url will be set to `.json`, i.e. if `key` was "alien" then the URL will be "alien.json". - * @param {object|string} [data] - An optional JSON data object. If given then the url is ignored and this JSON object is used for physics data instead. - * @param {string} [format=Phaser.Physics.LIME_CORONA_JSON] - The format of the physics data. - * @return {Phaser.Loader} This Loader instance. - */ + * Adds a physics data file to the current load queue. + * + * The data must be in `Lime + Corona` JSON format. [Physics Editor](https://www.codeandweb.com) by code'n'web exports in this format natively. + * + * You can choose to either load the data externally, by providing a URL to a json file. + * Or you can pass in a JSON object or String via the `data` parameter. + * If you pass a String the data is automatically run through `JSON.parse` and then immediately added to the Phaser.Cache. + * + * If a URL is provided the file is **not** loaded immediately after calling this method, but is added to the load queue. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getJSON(key)`. JSON files are automatically parsed upon load. + * If you need to control when the JSON is parsed then use `Loader.text` instead and parse the text file as needed. + * + * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the URL isn't specified and no data is given then the Loader will take the key and create a filename from that. + * For example if the key is "alien" and no URL or data is given then the Loader will set the URL to be "alien.json". + * It will always use `.json` as the extension. + * + * If you do not desire this action then provide a URL or data object. + * + * @method Phaser.Loader#physics + * @param {string} key - Unique asset key of the physics json data. + * @param {string} [url] - URL of the physics data file. If undefined or `null` and no data is given the url will be set to `.json`, i.e. if `key` was "alien" then the URL will be "alien.json". + * @param {object|string} [data] - An optional JSON data object. If given then the url is ignored and this JSON object is used for physics data instead. + * @param {string} [format=Phaser.Physics.LIME_CORONA_JSON] - The format of the physics data. + * @return {Phaser.Loader} This Loader instance. + */ physics: function (key, url, data, format) { - if (url === undefined) { url = null; } if (data === undefined) { data = null; } if (format === undefined) { format = Phaser.Physics.LIME_CORONA_JSON; } @@ -1535,50 +1478,48 @@ Phaser.Loader.prototype = { } return this; - }, /** - * Adds Bitmap Font files to the current load queue. - * - * To create the Bitmap Font files you can use: - * - * BMFont (Windows, free): http://www.angelcode.com/products/bmfont/ - * Glyph Designer (OS X, commercial): http://www.71squared.com/en/glyphdesigner - * Littera (Web-based, free): http://kvazars.com/littera/ - * - * You can choose to either load the data externally, by providing a URL to an xml file. - * Or you can pass in an XML object or String via the `xmlData` parameter. - * If you pass a String the data is automatically run through `Loader.parseXML` and then immediately added to the Phaser.Cache. - * - * If URLs are provided the files are **not** loaded immediately after calling this method, but are added to the load queue. - * - * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. - * - * Retrieve the file via `Cache.getBitmapFont(key)`. XML files are automatically parsed upon load. - * If you need to control when the XML is parsed then use `Loader.text` instead and parse the XML file as needed. - * - * The URLs can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. - * - * If the textureURL isn't specified then the Loader will take the key and create a filename from that. - * For example if the key is "megaFont" and textureURL is null then the Loader will set the URL to be "megaFont.png". - * The same is true for the atlasURL. If atlasURL isn't specified and no atlasData has been provided then the Loader will - * set the atlasURL to be the key. For example if the key is "megaFont" the atlasURL will be set to "megaFont.xml". - * - * If you do not desire this action then provide URLs and / or a data object. - * - * @method Phaser.Loader#bitmapFont - * @param {string} key - Unique asset key of the bitmap font. - * @param {string} textureURL - URL of the Bitmap Font texture file. If undefined or `null` the url will be set to `.png`, i.e. if `key` was "megaFont" then the URL will be "megaFont.png". - * @param {string} atlasURL - URL of the Bitmap Font atlas file (xml/json). If undefined or `null` AND `atlasData` is null, the url will be set to `.xml`, i.e. if `key` was "megaFont" then the URL will be "megaFont.xml". - * @param {object} atlasData - An optional Bitmap Font atlas in string form (stringified xml/json). - * @param {number} [xSpacing=0] - If you'd like to add additional horizontal spacing between the characters then set the pixel value here. - * @param {number} [ySpacing=0] - If you'd like to add additional vertical spacing between the lines then set the pixel value here. - * @return {Phaser.Loader} This Loader instance. - */ + * Adds Bitmap Font files to the current load queue. + * + * To create the Bitmap Font files you can use: + * + * BMFont (Windows, free): http://www.angelcode.com/products/bmfont/ + * Glyph Designer (OS X, commercial): http://www.71squared.com/en/glyphdesigner + * Littera (Web-based, free): http://kvazars.com/littera/ + * + * You can choose to either load the data externally, by providing a URL to an xml file. + * Or you can pass in an XML object or String via the `xmlData` parameter. + * If you pass a String the data is automatically run through `Loader.parseXML` and then immediately added to the Phaser.Cache. + * + * If URLs are provided the files are **not** loaded immediately after calling this method, but are added to the load queue. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getBitmapFont(key)`. XML files are automatically parsed upon load. + * If you need to control when the XML is parsed then use `Loader.text` instead and parse the XML file as needed. + * + * The URLs can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the textureURL isn't specified then the Loader will take the key and create a filename from that. + * For example if the key is "megaFont" and textureURL is null then the Loader will set the URL to be "megaFont.png". + * The same is true for the atlasURL. If atlasURL isn't specified and no atlasData has been provided then the Loader will + * set the atlasURL to be the key. For example if the key is "megaFont" the atlasURL will be set to "megaFont.xml". + * + * If you do not desire this action then provide URLs and / or a data object. + * + * @method Phaser.Loader#bitmapFont + * @param {string} key - Unique asset key of the bitmap font. + * @param {string} textureURL - URL of the Bitmap Font texture file. If undefined or `null` the url will be set to `.png`, i.e. if `key` was "megaFont" then the URL will be "megaFont.png". + * @param {string} atlasURL - URL of the Bitmap Font atlas file (xml/json). If undefined or `null` AND `atlasData` is null, the url will be set to `.xml`, i.e. if `key` was "megaFont" then the URL will be "megaFont.xml". + * @param {object} atlasData - An optional Bitmap Font atlas in string form (stringified xml/json). + * @param {number} [xSpacing=0] - If you'd like to add additional horizontal spacing between the characters then set the pixel value here. + * @param {number} [ySpacing=0] - If you'd like to add additional vertical spacing between the lines then set the pixel value here. + * @return {Phaser.Loader} This Loader instance. + */ bitmapFont: function (key, textureURL, atlasURL, atlasData, xSpacing, ySpacing) { - if (textureURL === undefined || textureURL === null) { textureURL = key + '.png'; @@ -1629,146 +1570,140 @@ Phaser.Loader.prototype = { } return this; - }, /** - * Adds a Texture Atlas file to the current load queue. - * - * Unlike `Loader.atlasJSONHash` this call expects the atlas data to be in a JSON Array format. - * - * To create the Texture Atlas you can use tools such as: - * - * [Texture Packer](https://www.codeandweb.com/texturepacker/phaser) - * [Shoebox](http://renderhjs.net/shoebox/) - * - * If using Texture Packer we recommend you enable "Trim sprite names". - * If your atlas software has an option to "rotate" the resulting frames, you must disable it. - * - * You can choose to either load the data externally, by providing a URL to a json file. - * Or you can pass in a JSON object or String via the `atlasData` parameter. - * If you pass a String the data is automatically run through `JSON.parse` and then immediately added to the Phaser.Cache. - * - * If URLs are provided the files are **not** loaded immediately after calling this method, but are added to the load queue. - * - * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. - * - * Retrieve the file via `Cache.getImage(key)`. JSON files are automatically parsed upon load. - * If you need to control when the JSON is parsed then use `Loader.text` instead and parse the JSON file as needed. - * - * The URLs can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. - * - * If the textureURL isn't specified then the Loader will take the key and create a filename from that. - * For example if the key is "player" and textureURL is null then the Loader will set the URL to be "player.png". - * The same is true for the atlasURL. If atlasURL isn't specified and no atlasData has been provided then the Loader will - * set the atlasURL to be the key. For example if the key is "player" the atlasURL will be set to "player.json". - * - * If you do not desire this action then provide URLs and / or a data object. - * - * @method Phaser.Loader#atlasJSONArray - * @param {string} key - Unique asset key of the texture atlas file. - * @param {string} [textureURL] - URL of the texture atlas image file. If undefined or `null` the url will be set to `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". - * @param {string} [atlasURL] - URL of the texture atlas data file. If undefined or `null` and no atlasData is given, the url will be set to `.json`, i.e. if `key` was "alien" then the URL will be "alien.json". - * @param {object} [atlasData] - A JSON data object. You don't need this if the data is being loaded from a URL. - * @return {Phaser.Loader} This Loader instance. - */ + * Adds a Texture Atlas file to the current load queue. + * + * Unlike `Loader.atlasJSONHash` this call expects the atlas data to be in a JSON Array format. + * + * To create the Texture Atlas you can use tools such as: + * + * [Texture Packer](https://www.codeandweb.com/texturepacker/phaser) + * [Shoebox](http://renderhjs.net/shoebox/) + * + * If using Texture Packer we recommend you enable "Trim sprite names". + * If your atlas software has an option to "rotate" the resulting frames, you must disable it. + * + * You can choose to either load the data externally, by providing a URL to a json file. + * Or you can pass in a JSON object or String via the `atlasData` parameter. + * If you pass a String the data is automatically run through `JSON.parse` and then immediately added to the Phaser.Cache. + * + * If URLs are provided the files are **not** loaded immediately after calling this method, but are added to the load queue. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getImage(key)`. JSON files are automatically parsed upon load. + * If you need to control when the JSON is parsed then use `Loader.text` instead and parse the JSON file as needed. + * + * The URLs can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the textureURL isn't specified then the Loader will take the key and create a filename from that. + * For example if the key is "player" and textureURL is null then the Loader will set the URL to be "player.png". + * The same is true for the atlasURL. If atlasURL isn't specified and no atlasData has been provided then the Loader will + * set the atlasURL to be the key. For example if the key is "player" the atlasURL will be set to "player.json". + * + * If you do not desire this action then provide URLs and / or a data object. + * + * @method Phaser.Loader#atlasJSONArray + * @param {string} key - Unique asset key of the texture atlas file. + * @param {string} [textureURL] - URL of the texture atlas image file. If undefined or `null` the url will be set to `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". + * @param {string} [atlasURL] - URL of the texture atlas data file. If undefined or `null` and no atlasData is given, the url will be set to `.json`, i.e. if `key` was "alien" then the URL will be "alien.json". + * @param {object} [atlasData] - A JSON data object. You don't need this if the data is being loaded from a URL. + * @return {Phaser.Loader} This Loader instance. + */ atlasJSONArray: function (key, textureURL, atlasURL, atlasData) { - return this.atlas(key, textureURL, atlasURL, atlasData, Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY); - }, /** - * Adds a Texture Atlas file to the current load queue. - * - * Unlike `Loader.atlas` this call expects the atlas data to be in a JSON Hash format. - * - * To create the Texture Atlas you can use tools such as: - * - * [Texture Packer](https://www.codeandweb.com/texturepacker/phaser) - * [Shoebox](http://renderhjs.net/shoebox/) - * - * If using Texture Packer we recommend you enable "Trim sprite names". - * If your atlas software has an option to "rotate" the resulting frames, you must disable it. - * - * You can choose to either load the data externally, by providing a URL to a json file. - * Or you can pass in a JSON object or String via the `atlasData` parameter. - * If you pass a String the data is automatically run through `JSON.parse` and then immediately added to the Phaser.Cache. - * - * If URLs are provided the files are **not** loaded immediately after calling this method, but are added to the load queue. - * - * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. - * - * Retrieve the file via `Cache.getImage(key)`. JSON files are automatically parsed upon load. - * If you need to control when the JSON is parsed then use `Loader.text` instead and parse the JSON file as needed. - * - * The URLs can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. - * - * If the textureURL isn't specified then the Loader will take the key and create a filename from that. - * For example if the key is "player" and textureURL is null then the Loader will set the URL to be "player.png". - * The same is true for the atlasURL. If atlasURL isn't specified and no atlasData has been provided then the Loader will - * set the atlasURL to be the key. For example if the key is "player" the atlasURL will be set to "player.json". - * - * If you do not desire this action then provide URLs and / or a data object. - * - * @method Phaser.Loader#atlasJSONHash - * @param {string} key - Unique asset key of the texture atlas file. - * @param {string} [textureURL] - URL of the texture atlas image file. If undefined or `null` the url will be set to `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". - * @param {string} [atlasURL] - URL of the texture atlas data file. If undefined or `null` and no atlasData is given, the url will be set to `.json`, i.e. if `key` was "alien" then the URL will be "alien.json". - * @param {object} [atlasData] - A JSON data object. You don't need this if the data is being loaded from a URL. - * @return {Phaser.Loader} This Loader instance. - */ + * Adds a Texture Atlas file to the current load queue. + * + * Unlike `Loader.atlas` this call expects the atlas data to be in a JSON Hash format. + * + * To create the Texture Atlas you can use tools such as: + * + * [Texture Packer](https://www.codeandweb.com/texturepacker/phaser) + * [Shoebox](http://renderhjs.net/shoebox/) + * + * If using Texture Packer we recommend you enable "Trim sprite names". + * If your atlas software has an option to "rotate" the resulting frames, you must disable it. + * + * You can choose to either load the data externally, by providing a URL to a json file. + * Or you can pass in a JSON object or String via the `atlasData` parameter. + * If you pass a String the data is automatically run through `JSON.parse` and then immediately added to the Phaser.Cache. + * + * If URLs are provided the files are **not** loaded immediately after calling this method, but are added to the load queue. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getImage(key)`. JSON files are automatically parsed upon load. + * If you need to control when the JSON is parsed then use `Loader.text` instead and parse the JSON file as needed. + * + * The URLs can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the textureURL isn't specified then the Loader will take the key and create a filename from that. + * For example if the key is "player" and textureURL is null then the Loader will set the URL to be "player.png". + * The same is true for the atlasURL. If atlasURL isn't specified and no atlasData has been provided then the Loader will + * set the atlasURL to be the key. For example if the key is "player" the atlasURL will be set to "player.json". + * + * If you do not desire this action then provide URLs and / or a data object. + * + * @method Phaser.Loader#atlasJSONHash + * @param {string} key - Unique asset key of the texture atlas file. + * @param {string} [textureURL] - URL of the texture atlas image file. If undefined or `null` the url will be set to `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". + * @param {string} [atlasURL] - URL of the texture atlas data file. If undefined or `null` and no atlasData is given, the url will be set to `.json`, i.e. if `key` was "alien" then the URL will be "alien.json". + * @param {object} [atlasData] - A JSON data object. You don't need this if the data is being loaded from a URL. + * @return {Phaser.Loader} This Loader instance. + */ atlasJSONHash: function (key, textureURL, atlasURL, atlasData) { - return this.atlas(key, textureURL, atlasURL, atlasData, Phaser.Loader.TEXTURE_ATLAS_JSON_HASH); - }, /** - * Adds a Texture Atlas file to the current load queue. - * - * This call expects the atlas data to be in the Starling XML data format. - * - * To create the Texture Atlas you can use tools such as: - * - * [Texture Packer](https://www.codeandweb.com/texturepacker/phaser) - * [Shoebox](http://renderhjs.net/shoebox/) - * - * If using Texture Packer we recommend you enable "Trim sprite names". - * If your atlas software has an option to "rotate" the resulting frames, you must disable it. - * - * You can choose to either load the data externally, by providing a URL to an xml file. - * Or you can pass in an XML object or String via the `atlasData` parameter. - * If you pass a String the data is automatically run through `Loader.parseXML` and then immediately added to the Phaser.Cache. - * - * If URLs are provided the files are **not** loaded immediately after calling this method, but are added to the load queue. - * - * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. - * - * Retrieve the file via `Cache.getImage(key)`. XML files are automatically parsed upon load. - * If you need to control when the XML is parsed then use `Loader.text` instead and parse the XML file as needed. - * - * The URLs can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. - * - * If the textureURL isn't specified then the Loader will take the key and create a filename from that. - * For example if the key is "player" and textureURL is null then the Loader will set the URL to be "player.png". - * The same is true for the atlasURL. If atlasURL isn't specified and no atlasData has been provided then the Loader will - * set the atlasURL to be the key. For example if the key is "player" the atlasURL will be set to "player.xml". - * - * If you do not desire this action then provide URLs and / or a data object. - * - * @method Phaser.Loader#atlasXML - * @param {string} key - Unique asset key of the texture atlas file. - * @param {string} [textureURL] - URL of the texture atlas image file. If undefined or `null` the url will be set to `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". - * @param {string} [atlasURL] - URL of the texture atlas data file. If undefined or `null` and no atlasData is given, the url will be set to `.json`, i.e. if `key` was "alien" then the URL will be "alien.xml". - * @param {object} [atlasData] - An XML data object. You don't need this if the data is being loaded from a URL. - * @return {Phaser.Loader} This Loader instance. - */ + * Adds a Texture Atlas file to the current load queue. + * + * This call expects the atlas data to be in the Starling XML data format. + * + * To create the Texture Atlas you can use tools such as: + * + * [Texture Packer](https://www.codeandweb.com/texturepacker/phaser) + * [Shoebox](http://renderhjs.net/shoebox/) + * + * If using Texture Packer we recommend you enable "Trim sprite names". + * If your atlas software has an option to "rotate" the resulting frames, you must disable it. + * + * You can choose to either load the data externally, by providing a URL to an xml file. + * Or you can pass in an XML object or String via the `atlasData` parameter. + * If you pass a String the data is automatically run through `Loader.parseXML` and then immediately added to the Phaser.Cache. + * + * If URLs are provided the files are **not** loaded immediately after calling this method, but are added to the load queue. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getImage(key)`. XML files are automatically parsed upon load. + * If you need to control when the XML is parsed then use `Loader.text` instead and parse the XML file as needed. + * + * The URLs can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the textureURL isn't specified then the Loader will take the key and create a filename from that. + * For example if the key is "player" and textureURL is null then the Loader will set the URL to be "player.png". + * The same is true for the atlasURL. If atlasURL isn't specified and no atlasData has been provided then the Loader will + * set the atlasURL to be the key. For example if the key is "player" the atlasURL will be set to "player.xml". + * + * If you do not desire this action then provide URLs and / or a data object. + * + * @method Phaser.Loader#atlasXML + * @param {string} key - Unique asset key of the texture atlas file. + * @param {string} [textureURL] - URL of the texture atlas image file. If undefined or `null` the url will be set to `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". + * @param {string} [atlasURL] - URL of the texture atlas data file. If undefined or `null` and no atlasData is given, the url will be set to `.json`, i.e. if `key` was "alien" then the URL will be "alien.xml". + * @param {object} [atlasData] - An XML data object. You don't need this if the data is being loaded from a URL. + * @return {Phaser.Loader} This Loader instance. + */ atlasXML: function (key, textureURL, atlasURL, atlasData) { - if (atlasURL === undefined) { atlasURL = null; } if (atlasData === undefined) { atlasData = null; } @@ -1778,51 +1713,49 @@ Phaser.Loader.prototype = { } return this.atlas(key, textureURL, atlasURL, atlasData, Phaser.Loader.TEXTURE_ATLAS_XML_STARLING); - }, /** - * Adds a Texture Atlas file to the current load queue. - * - * To create the Texture Atlas you can use tools such as: - * - * [Texture Packer](https://www.codeandweb.com/texturepacker/phaser) - * [Shoebox](http://renderhjs.net/shoebox/) - * - * If using Texture Packer we recommend you enable "Trim sprite names". - * If your atlas software has an option to "rotate" the resulting frames, you must disable it. - * - * You can choose to either load the data externally, by providing a URL to a json file. - * Or you can pass in a JSON object or String via the `atlasData` parameter. - * If you pass a String the data is automatically run through `JSON.parse` and then immediately added to the Phaser.Cache. - * - * If URLs are provided the files are **not** loaded immediately after calling this method, but are added to the load queue. - * - * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. - * - * Retrieve the file via `Cache.getImage(key)`. JSON files are automatically parsed upon load. - * If you need to control when the JSON is parsed then use `Loader.text` instead and parse the JSON file as needed. - * - * The URLs can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. - * - * If the textureURL isn't specified then the Loader will take the key and create a filename from that. - * For example if the key is "player" and textureURL is null then the Loader will set the URL to be "player.png". - * The same is true for the atlasURL. If atlasURL isn't specified and no atlasData has been provided then the Loader will - * set the atlasURL to be the key. For example if the key is "player" the atlasURL will be set to "player.json". - * - * If you do not desire this action then provide URLs and / or a data object. - * - * @method Phaser.Loader#atlas - * @param {string} key - Unique asset key of the texture atlas file. - * @param {string} [textureURL] - URL of the texture atlas image file. If undefined or `null` the url will be set to `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". - * @param {string} [atlasURL] - URL of the texture atlas data file. If undefined or `null` and no atlasData is given, the url will be set to `.json`, i.e. if `key` was "alien" then the URL will be "alien.json". - * @param {object} [atlasData] - A JSON or XML data object. You don't need this if the data is being loaded from a URL. - * @param {number} [format] - The format of the data. Can be Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY (the default), Phaser.Loader.TEXTURE_ATLAS_JSON_HASH or Phaser.Loader.TEXTURE_ATLAS_XML_STARLING. - * @return {Phaser.Loader} This Loader instance. - */ + * Adds a Texture Atlas file to the current load queue. + * + * To create the Texture Atlas you can use tools such as: + * + * [Texture Packer](https://www.codeandweb.com/texturepacker/phaser) + * [Shoebox](http://renderhjs.net/shoebox/) + * + * If using Texture Packer we recommend you enable "Trim sprite names". + * If your atlas software has an option to "rotate" the resulting frames, you must disable it. + * + * You can choose to either load the data externally, by providing a URL to a json file. + * Or you can pass in a JSON object or String via the `atlasData` parameter. + * If you pass a String the data is automatically run through `JSON.parse` and then immediately added to the Phaser.Cache. + * + * If URLs are provided the files are **not** loaded immediately after calling this method, but are added to the load queue. + * + * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load. + * + * Retrieve the file via `Cache.getImage(key)`. JSON files are automatically parsed upon load. + * If you need to control when the JSON is parsed then use `Loader.text` instead and parse the JSON file as needed. + * + * The URLs can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it. + * + * If the textureURL isn't specified then the Loader will take the key and create a filename from that. + * For example if the key is "player" and textureURL is null then the Loader will set the URL to be "player.png". + * The same is true for the atlasURL. If atlasURL isn't specified and no atlasData has been provided then the Loader will + * set the atlasURL to be the key. For example if the key is "player" the atlasURL will be set to "player.json". + * + * If you do not desire this action then provide URLs and / or a data object. + * + * @method Phaser.Loader#atlas + * @param {string} key - Unique asset key of the texture atlas file. + * @param {string} [textureURL] - URL of the texture atlas image file. If undefined or `null` the url will be set to `.png`, i.e. if `key` was "alien" then the URL will be "alien.png". + * @param {string} [atlasURL] - URL of the texture atlas data file. If undefined or `null` and no atlasData is given, the url will be set to `.json`, i.e. if `key` was "alien" then the URL will be "alien.json". + * @param {object} [atlasData] - A JSON or XML data object. You don't need this if the data is being loaded from a URL. + * @param {number} [format] - The format of the data. Can be Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY (the default), Phaser.Loader.TEXTURE_ATLAS_JSON_HASH or Phaser.Loader.TEXTURE_ATLAS_XML_STARLING. + * @return {Phaser.Loader} This Loader instance. + */ atlas: function (key, textureURL, atlasURL, atlasData, format) { - if (textureURL === undefined || textureURL === null) { textureURL = key + '.png'; @@ -1881,29 +1814,26 @@ Phaser.Loader.prototype = { } this.addToFileList('textureatlas', key, textureURL, { atlasURL: null, atlasData: atlasData, format: format }); - } return this; - }, /** - * Add a synchronization point to the assets / files added within the supplied callback. - * - * A synchronization point denotes that an asset _must_ be completely loaded before - * subsequent assets can be loaded. An asset marked as a sync-point does not need to wait - * for previous assets to load (unless they are sync-points). Resources, such as packs, may still - * be downloaded around sync-points, as long as they do not finalize loading. - * - * @method Phaser.Loader#withSyncPoint - * @param {function} callback - The callback is invoked and is supplied with a single argument: the loader. - * @param {object} [callbackContext=(loader)] - Context for the callback. - * @return {Phaser.Loader} This Loader instance. - */ + * Add a synchronization point to the assets / files added within the supplied callback. + * + * A synchronization point denotes that an asset _must_ be completely loaded before + * subsequent assets can be loaded. An asset marked as a sync-point does not need to wait + * for previous assets to load (unless they are sync-points). Resources, such as packs, may still + * be downloaded around sync-points, as long as they do not finalize loading. + * + * @method Phaser.Loader#withSyncPoint + * @param {function} callback - The callback is invoked and is supplied with a single argument: the loader. + * @param {object} [callbackContext=(loader)] - Context for the callback. + * @return {Phaser.Loader} This Loader instance. + */ withSyncPoint: function (callback, callbackContext) { - this._withSyncPointDepth++; try @@ -1919,19 +1849,18 @@ Phaser.Loader.prototype = { }, /** - * Add a synchronization point to a specific file/asset in the load queue. - * - * This has no effect on already loaded assets. - * - * @method Phaser.Loader#addSyncPoint - * @param {string} type - The type of resource to turn into a sync point (image, audio, xml, etc). - * @param {string} key - Key of the file you want to turn into a sync point. - * @return {Phaser.Loader} This Loader instance. - * @see {@link Phaser.Loader#withSyncPoint withSyncPoint} - */ + * Add a synchronization point to a specific file/asset in the load queue. + * + * This has no effect on already loaded assets. + * + * @method Phaser.Loader#addSyncPoint + * @param {string} type - The type of resource to turn into a sync point (image, audio, xml, etc). + * @param {string} key - Key of the file you want to turn into a sync point. + * @return {Phaser.Loader} This Loader instance. + * @see {@link Phaser.Loader#withSyncPoint withSyncPoint} + */ addSyncPoint: function (type, key) { - var asset = this.getAsset(type, key); if (asset) @@ -1943,18 +1872,17 @@ Phaser.Loader.prototype = { }, /** - * Remove a file/asset from the loading queue. - * - * A file that is loaded or has started loading cannot be removed. - * - * @method Phaser.Loader#removeFile - * @protected - * @param {string} type - The type of resource to add to the list (image, audio, xml, etc). - * @param {string} key - Key of the file you want to remove. - */ + * Remove a file/asset from the loading queue. + * + * A file that is loaded or has started loading cannot be removed. + * + * @method Phaser.Loader#removeFile + * @protected + * @param {string} type - The type of resource to add to the list (image, audio, xml, etc). + * @param {string} key - Key of the file you want to remove. + */ removeFile: function (type, key) { - var asset = this.getAsset(type, key); if (asset) @@ -1964,31 +1892,27 @@ Phaser.Loader.prototype = { this._fileList.splice(asset.index, 1); } } - }, /** - * Remove all file loading requests - this is _insufficient_ to stop current loading. Use `reset` instead. - * - * @method Phaser.Loader#removeAll - * @protected - */ + * Remove all file loading requests - this is _insufficient_ to stop current loading. Use `reset` instead. + * + * @method Phaser.Loader#removeAll + * @protected + */ removeAll: function () { - this._fileList.length = 0; this._flightQueue.length = 0; - }, /** - * Start loading the assets. Normally you don't need to call this yourself as the StateManager will do so. - * - * @method Phaser.Loader#start - */ + * Start loading the assets. Normally you don't need to call this yourself as the StateManager will do so. + * + * @method Phaser.Loader#start + */ start: function () { - if (this.isLoading) { return; @@ -2000,25 +1924,23 @@ Phaser.Loader.prototype = { this.updateProgress(); this.processLoadQueue(); - }, /** - * Process the next item(s) in the file/asset queue. - * - * Process the queue and start loading enough items to fill up the inflight queue. - * - * If a sync-file is encountered then subsequent asset processing is delayed until it completes. - * The exception to this rule is that packfiles can be downloaded (but not processed) even if - * there appear other sync files (ie. packs) - this enables multiple packfiles to be fetched in parallel. - * such as during the start phaser. - * - * @method Phaser.Loader#processLoadQueue - * @private - */ + * Process the next item(s) in the file/asset queue. + * + * Process the queue and start loading enough items to fill up the inflight queue. + * + * If a sync-file is encountered then subsequent asset processing is delayed until it completes. + * The exception to this rule is that packfiles can be downloaded (but not processed) even if + * there appear other sync files (ie. packs) - this enables multiple packfiles to be fetched in parallel. + * such as during the start phaser. + * + * @method Phaser.Loader#processLoadQueue + * @private + */ processLoadQueue: function () { - if (!this.isLoading) { console.warn('Phaser.Loader - active loading canceled / reset'); @@ -2056,7 +1978,6 @@ Phaser.Loader.prototype = { this._loadedPackCount++; this.onPackComplete.dispatch(file.key, !file.error, this._loadedPackCount, this._totalPackCount); } - } } @@ -2092,8 +2013,10 @@ Phaser.Loader.prototype = { // -> not loaded/failed, not loading if (file.type === 'packfile' && !file.data) { - // Fetches the pack data: the pack is processed above as it reaches queue-start. - // (Packs do not trigger onLoadStart or onFileStart.) + /* + * Fetches the pack data: the pack is processed above as it reaches queue-start. + * (Packs do not trigger onLoadStart or onFileStart.) + */ this._flightQueue.push(file); file.loading = true; @@ -2120,8 +2043,10 @@ Phaser.Loader.prototype = { syncblock = true; } - // Stop looking if queue full - or if syncblocked and there are no more packs. - // (As only packs can be loaded around a syncblock) + /* + * Stop looking if queue full - or if syncblocked and there are no more packs. + * (As only packs can be loaded around a syncblock) + */ if (this._flightQueue.length >= inflightLimit || (syncblock && this._loadedPackCount === this._totalPackCount)) { @@ -2131,16 +2056,20 @@ Phaser.Loader.prototype = { this.updateProgress(); - // True when all items in the queue have been advanced over - // (There should be no inflight items as they are complete - loaded/error.) + /* + * True when all items in the queue have been advanced over + * (There should be no inflight items as they are complete - loaded/error.) + */ if (this._processingHead >= this._fileList.length) { this.finishedLoading(); } else if (!this._flightQueue.length) { - // Flight queue is empty but file list is not done being processed. - // This indicates a critical internal error with no known recovery. + /* + * Flight queue is empty but file list is not done being processed. + * This indicates a critical internal error with no known recovery. + */ console.warn('Phaser.Loader - aborting: processing queue empty, loading may have stalled'); var _this = this; @@ -2150,19 +2079,17 @@ Phaser.Loader.prototype = { _this.finishedLoading(true); }, 2000); } - }, /** - * The loading is all finished. - * - * @method Phaser.Loader#finishedLoading - * @private - * @param {boolean} [abnormal=true] - True if the loading finished abnormally. - */ + * The loading is all finished. + * + * @method Phaser.Loader#finishedLoading + * @private + * @param {boolean} [abnormal=true] - True if the loading finished abnormally. + */ finishedLoading: function (abnormal) { - // Destroy could have occurred while loading if (this.hasLoaded || !this.game.state) { @@ -2184,21 +2111,19 @@ Phaser.Loader.prototype = { this.reset(); this.onLoadComplete.dispatch(); this.game.state.loadComplete(); - }, /** - * Informs the loader that the given file resource has been fetched and processed; - * or such a request has failed. - * - * @method Phaser.Loader#asyncComplete - * @private - * @param {object} file - * @param {string} [error=''] - The error message, if any. No message implies no error. - */ + * Informs the loader that the given file resource has been fetched and processed; + * or such a request has failed. + * + * @method Phaser.Loader#asyncComplete + * @private + * @param {object} file + * @param {string} [error=''] - The error message, if any. No message implies no error. + */ asyncComplete: function (file, errorMessage) { - if (errorMessage === undefined) { errorMessage = ''; } file.loaded = true; @@ -2212,19 +2137,17 @@ Phaser.Loader.prototype = { } this.processLoadQueue(); - }, /** - * Process pack data. This will usually modify the file list. - * - * @method Phaser.Loader#processPack - * @private - * @param {object} pack - */ + * Process pack data. This will usually modify the file list. + * + * @method Phaser.Loader#processPack + * @private + * @param {object} pack + */ processPack: function (pack) { - var packData = pack.data[pack.key]; if (!packData) @@ -2312,23 +2235,21 @@ Phaser.Loader.prototype = { break; } } - }, /** - * Transforms the asset URL. - * - * The default implementation prepends the baseURL if the url doesn't begin with http or // - * - * @method Phaser.Loader#transformUrl - * @protected - * @param {string} url - The url to transform. - * @param {object} file - The file object being transformed. - * @return {string} The transformed url. In rare cases where the url isn't specified it will return false instead. - */ + * Transforms the asset URL. + * + * The default implementation prepends the baseURL if the url doesn't begin with http or // + * + * @method Phaser.Loader#transformUrl + * @protected + * @param {string} url - The url to transform. + * @param {object} file - The file object being transformed. + * @return {string} The transformed url. In rare cases where the url isn't specified it will return false instead. + */ transformUrl: function (url, file) { - if (!url) { return false; @@ -2342,21 +2263,19 @@ Phaser.Loader.prototype = { { return this.baseURL + file.path + url; } - }, /** - * Start fetching a resource. - * - * All code paths, async or otherwise, from this function must return to `asyncComplete`. - * - * @method Phaser.Loader#loadFile - * @private - * @param {object} file - */ + * Start fetching a resource. + * + * All code paths, async or otherwise, from this function must return to `asyncComplete`. + * + * @method Phaser.Loader#loadFile + * @private + * @param {object} file + */ loadFile: function (file) { - // Image or Data? switch (file.type) { @@ -2461,13 +2380,12 @@ Phaser.Loader.prototype = { this.xhrLoad(file, this.transformUrl(file.url, file), 'arraybuffer', this.fileComplete); break; } - }, /** - * Continue async loading through an Image tag. - * @private - */ + * Continue async loading through an Image tag. + * @private + */ loadImageTag: function (file) { var _this = this; @@ -2502,25 +2420,25 @@ Phaser.Loader.prototype = { file.data.src = this.transformUrl(file.url, file); - // Image is immediately-available/cached - // Special Firefox magic, exclude from cached reload - // More info here: https://github.com/photonstorm/phaser/issues/2534 + /* + * Image is immediately-available/cached + * Special Firefox magic, exclude from cached reload + * More info here: https://github.com/photonstorm/phaser/issues/2534 + */ if (!this.game.device.firefox && file.data.complete && file.data.width && file.data.height) { file.data.onload = null; file.data.onerror = null; this.fileComplete(file); } - }, /** - * Continue async loading through a Video tag. - * @private - */ + * Continue async loading through a Video tag. + * @private + */ loadVideoTag: function (file) { - var _this = this; file.data = document.createElement('video'); @@ -2531,12 +2449,10 @@ Phaser.Loader.prototype = { var videoLoadEvent = function () { - file.data.removeEventListener(file.loadEvent, videoLoadEvent, false); file.data.onerror = null; file.data.canplay = true; Phaser.GAMES[_this.game.id].load.fileComplete(file); - }; file.data.onerror = function () @@ -2551,16 +2467,14 @@ Phaser.Loader.prototype = { file.data.src = this.transformUrl(file.url, file); file.data.load(); - }, /** - * Continue async loading through an Audio tag. - * @private - */ + * Continue async loading through an Audio tag. + * @private + */ loadAudioTag: function (file) { - var _this = this; if (this.game.sound.touchLocked) @@ -2597,25 +2511,23 @@ Phaser.Loader.prototype = { file.data.addEventListener('canplaythrough', playThroughEvent, false); file.data.load(); } - }, /** - * Starts the xhr loader. - * - * This is designed specifically to use with asset file processing. - * - * @method Phaser.Loader#xhrLoad - * @private - * @param {object} file - The file/pack to load. - * @param {string} url - The URL of the file. - * @param {string} type - The xhr responseType. - * @param {function} onload - The function to call on success. Invoked in `this` context and supplied with `(file, xhr)` arguments. - * @param {function} [onerror=fileError] The function to call on error. Invoked in `this` context and supplied with `(file, xhr)` arguments. - */ + * Starts the xhr loader. + * + * This is designed specifically to use with asset file processing. + * + * @method Phaser.Loader#xhrLoad + * @private + * @param {object} file - The file/pack to load. + * @param {string} url - The URL of the file. + * @param {string} type - The xhr responseType. + * @param {function} onload - The function to call on success. Invoked in `this` context and supplied with `(file, xhr)` arguments. + * @param {function} [onerror=fileError] The function to call on error. Invoked in `this` context and supplied with `(file, xhr)` arguments. + */ xhrLoad: function (file, url, type, onload, onerror) { - var xhr = new XMLHttpRequest(); xhr.open('GET', url, true); xhr.responseType = type; @@ -2636,7 +2548,6 @@ Phaser.Loader.prototype = { xhr.onload = function () { - try { if (xhr.readyState === 4 && xhr.status >= 400 && xhr.status <= 599) @@ -2650,9 +2561,10 @@ Phaser.Loader.prototype = { } catch (e) { - - // If this was the last file in the queue and an error is thrown in the create method - // then it's caught here, so be sure we don't carry on processing it + /* + * If this was the last file in the queue and an error is thrown in the create method + * then it's caught here, so be sure we don't carry on processing it + */ if (!_this.hasLoaded) { @@ -2668,16 +2580,12 @@ Phaser.Loader.prototype = { xhr.onerror = function () { - try { - return onerror.call(_this, file, xhr); - } catch (e) { - if (!_this.hasLoaded) { _this.asyncComplete(file, e.message || 'Exception'); @@ -2687,7 +2595,6 @@ Phaser.Loader.prototype = { { console.error(e); } - } }; @@ -2695,22 +2602,20 @@ Phaser.Loader.prototype = { file.requestUrl = url; xhr.send(); - }, /** - * Give a bunch of URLs, return the first URL that has an extension this device thinks it can play. - * - * It is assumed that the device can play "blob:" or "data:" URIs - There is no mime-type checking on data URIs. - * - * @method Phaser.Loader#getVideoURL - * @private - * @param {object[]|string[]} urls - See {@link #video} for format. - * @return {string} The URL to try and fetch; or null. - */ + * Give a bunch of URLs, return the first URL that has an extension this device thinks it can play. + * + * It is assumed that the device can play "blob:" or "data:" URIs - There is no mime-type checking on data URIs. + * + * @method Phaser.Loader#getVideoURL + * @private + * @param {object[]|string[]} urls - See {@link #video} for format. + * @return {string} The URL to try and fetch; or null. + */ getVideoURL: function (urls) { - for (var i = 0; i < urls.length; i++) { var url = urls[i]; @@ -2751,22 +2656,20 @@ Phaser.Loader.prototype = { } return null; - }, /** - * Give a bunch of URLs, return the first URL that has an extension this device thinks it can play. - * - * It is assumed that the device can play "blob:" or "data:" URIs - There is no mime-type checking on data URIs. - * - * @method Phaser.Loader#getAudioURL - * @private - * @param {object[]|string[]} urls - See {@link #audio} for format. - * @return {string} The URL to try and fetch; or null. - */ + * Give a bunch of URLs, return the first URL that has an extension this device thinks it can play. + * + * It is assumed that the device can play "blob:" or "data:" URIs - There is no mime-type checking on data URIs. + * + * @method Phaser.Loader#getAudioURL + * @private + * @param {object[]|string[]} urls - See {@link #audio} for format. + * @return {string} The URL to try and fetch; or null. + */ getAudioURL: function (urls) { - if (this.game.sound.noAudio) { return null; @@ -2812,21 +2715,19 @@ Phaser.Loader.prototype = { } return null; - }, /** - * Error occurred when loading a file. - * - * @method Phaser.Loader#fileError - * @private - * @param {object} file - * @param {?XMLHttpRequest} xhr - XHR request, unspecified if loaded via other means (eg. tags) - * @param {string} reason - */ + * Error occurred when loading a file. + * + * @method Phaser.Loader#fileError + * @private + * @param {object} file + * @param {?XMLHttpRequest} xhr - XHR request, unspecified if loaded via other means (eg. tags) + * @param {string} reason + */ fileError: function (file, xhr, reason) { - var url = file.requestUrl || this.transformUrl(file.url, file); var message = 'error loading asset from URL ' + url; @@ -2841,20 +2742,18 @@ Phaser.Loader.prototype = { } this.asyncComplete(file, message); - }, /** - * Called when a file has been downloaded and needs to be processed further. - * - * @method Phaser.Loader#fileComplete - * @private - * @param {object} file - File loaded - * @param {?XMLHttpRequest} xhr - XHR request, unspecified if loaded via other means (eg. tags) - */ + * Called when a file has been downloaded and needs to be processed further. + * + * @method Phaser.Loader#fileComplete + * @private + * @param {object} file - File loaded + * @param {?XMLHttpRequest} xhr - XHR request, unspecified if loaded via other means (eg. tags) + */ fileComplete: function (file, xhr) { - var loadNext = true; switch (file.type) @@ -3033,20 +2932,18 @@ Phaser.Loader.prototype = { { this.asyncComplete(file); } - }, /** - * Successfully loaded a JSON file - only used for certain types. - * - * @method Phaser.Loader#jsonLoadComplete - * @private - * @param {object} file - File associated with this request - * @param {XMLHttpRequest} xhr - */ + * Successfully loaded a JSON file - only used for certain types. + * + * @method Phaser.Loader#jsonLoadComplete + * @private + * @param {object} file - File associated with this request + * @param {XMLHttpRequest} xhr + */ jsonLoadComplete: function (file, xhr) { - var data = JSON.parse(xhr.responseText); if (file.type === 'tilemap') @@ -3070,35 +2967,32 @@ Phaser.Loader.prototype = { }, /** - * Successfully loaded a CSV file - only used for certain types. - * - * @method Phaser.Loader#csvLoadComplete - * @private - * @param {object} file - File associated with this request - * @param {XMLHttpRequest} xhr - */ + * Successfully loaded a CSV file - only used for certain types. + * + * @method Phaser.Loader#csvLoadComplete + * @private + * @param {object} file - File associated with this request + * @param {XMLHttpRequest} xhr + */ csvLoadComplete: function (file, xhr) { - var data = xhr.responseText; this.cache.addTilemap(file.key, file.url, data, file.format); this.asyncComplete(file); - }, /** - * Successfully loaded an XML file - only used for certain types. - * - * @method Phaser.Loader#xmlLoadComplete - * @private - * @param {object} file - File associated with this request - * @param {XMLHttpRequest} xhr - */ + * Successfully loaded an XML file - only used for certain types. + * + * @method Phaser.Loader#xmlLoadComplete + * @private + * @param {object} file - File associated with this request + * @param {XMLHttpRequest} xhr + */ xmlLoadComplete: function (file, xhr) { - // Always try parsing the content as XML, regardless of actually response type var data = xhr.responseText; var xml = this.parseXml(data); @@ -3125,20 +3019,18 @@ Phaser.Loader.prototype = { } this.asyncComplete(file); - }, /** - * Parses string data as XML. - * - * @method Phaser.Loader#parseXml - * @private - * @param {string} data - The XML text to parse - * @return {?XMLDocument} Returns the xml document, or null if such could not parsed to a valid document. - */ + * Parses string data as XML. + * + * @method Phaser.Loader#parseXml + * @private + * @param {string} data - The XML text to parse + * @return {?XMLDocument} Returns the xml document, or null if such could not parsed to a valid document. + */ parseXml: function (data) { - var xml; try @@ -3170,18 +3062,16 @@ Phaser.Loader.prototype = { { return xml; } - }, /** - * Update the loading sprite progress. - * - * @method Phaser.Loader#updateProgress - * @private - */ + * Update the loading sprite progress. + * + * @method Phaser.Loader#updateProgress + * @private + */ updateProgress: function () { - if (this.preloadSprite) { if (this.preloadSprite.direction === 0) @@ -3203,76 +3093,67 @@ Phaser.Loader.prototype = { this.preloadSprite = null; } } - }, /** - * Returns the number of files that have already been loaded, even if they errored. - * - * @method Phaser.Loader#totalLoadedFiles - * @protected - * @return {number} The number of files that have already been loaded (even if they errored) - */ + * Returns the number of files that have already been loaded, even if they errored. + * + * @method Phaser.Loader#totalLoadedFiles + * @protected + * @return {number} The number of files that have already been loaded (even if they errored) + */ totalLoadedFiles: function () { - return this._loadedFileCount; - }, /** - * Returns the number of files still waiting to be processed in the load queue. This value decreases as each file in the queue is loaded. - * - * @method Phaser.Loader#totalQueuedFiles - * @protected - * @return {number} The number of files that still remain in the load queue. - */ + * Returns the number of files still waiting to be processed in the load queue. This value decreases as each file in the queue is loaded. + * + * @method Phaser.Loader#totalQueuedFiles + * @protected + * @return {number} The number of files that still remain in the load queue. + */ totalQueuedFiles: function () { - return this._totalFileCount - this._loadedFileCount; - }, /** - * Returns the number of asset packs that have already been loaded, even if they errored. - * - * @method Phaser.Loader#totalLoadedPacks - * @protected - * @return {number} The number of asset packs that have already been loaded (even if they errored) - */ + * Returns the number of asset packs that have already been loaded, even if they errored. + * + * @method Phaser.Loader#totalLoadedPacks + * @protected + * @return {number} The number of asset packs that have already been loaded (even if they errored) + */ totalLoadedPacks: function () { - return this._totalPackCount; - }, /** - * Returns the number of asset packs still waiting to be processed in the load queue. This value decreases as each pack in the queue is loaded. - * - * @method Phaser.Loader#totalQueuedPacks - * @protected - * @return {number} The number of asset packs that still remain in the load queue. - */ + * Returns the number of asset packs still waiting to be processed in the load queue. This value decreases as each pack in the queue is loaded. + * + * @method Phaser.Loader#totalQueuedPacks + * @protected + * @return {number} The number of asset packs that still remain in the load queue. + */ totalQueuedPacks: function () { - return this._totalPackCount - this._loadedPackCount; - } }; /** -* The non-rounded load progress value (from 0.0 to 100.0). -* -* A general indicator of the progress. -* It is possible for the progress to decrease, after `onLoadStart`, if more files are dynamically added. -* -* @name Phaser.Loader#progressFloat -* @property {number} -*/ + * The non-rounded load progress value (from 0.0 to 100.0). + * + * A general indicator of the progress. + * It is possible for the progress to decrease, after `onLoadStart`, if more files are dynamically added. + * + * @name Phaser.Loader#progressFloat + * @property {number} + */ Object.defineProperty(Phaser.Loader.prototype, 'progressFloat', { get: function () @@ -3284,11 +3165,11 @@ Object.defineProperty(Phaser.Loader.prototype, 'progressFloat', { }); /** -* The rounded load progress percentage value (from 0 to 100). See {@link Phaser.Loader#progressFloat}. -* -* @name Phaser.Loader#progress -* @property {integer} -*/ + * The rounded load progress percentage value (from 0 to 100). See {@link Phaser.Loader#progressFloat}. + * + * @name Phaser.Loader#progress + * @property {integer} + */ Object.defineProperty(Phaser.Loader.prototype, 'progress', { get: function () diff --git a/src/loader/LoaderParser.js b/src/loader/LoaderParser.js index 768a91ec9..4a708ca19 100644 --- a/src/loader/LoaderParser.js +++ b/src/loader/LoaderParser.js @@ -1,50 +1,47 @@ /** -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* Phaser.LoaderParser parses data objects from Phaser.Loader that need more preparation before they can be inserted into the Cache. -* -* @class Phaser.LoaderParser -*/ + * Phaser.LoaderParser parses data objects from Phaser.Loader that need more preparation before they can be inserted into the Cache. + * + * @class Phaser.LoaderParser + */ Phaser.LoaderParser = { /** - * Alias for xmlBitmapFont, for backwards compatibility. - * - * @method Phaser.LoaderParser.bitmapFont - * @param {object} xml - XML data you want to parse. - * @param {PIXI.BaseTexture} baseTexture - The BaseTexture this font uses. - * @param {number} [xSpacing=0] - Additional horizontal spacing between the characters. - * @param {number} [ySpacing=0] - Additional vertical spacing between the characters. - * @param {Phaser.Frame} [frame] - Optional Frame, if this font is embedded in a texture atlas. - * @param {number} [resolution=1] - Optional game resolution to apply to the kerning data. - * @return {object} The parsed Bitmap Font data. - */ + * Alias for xmlBitmapFont, for backwards compatibility. + * + * @method Phaser.LoaderParser.bitmapFont + * @param {object} xml - XML data you want to parse. + * @param {PIXI.BaseTexture} baseTexture - The BaseTexture this font uses. + * @param {number} [xSpacing=0] - Additional horizontal spacing between the characters. + * @param {number} [ySpacing=0] - Additional vertical spacing between the characters. + * @param {Phaser.Frame} [frame] - Optional Frame, if this font is embedded in a texture atlas. + * @param {number} [resolution=1] - Optional game resolution to apply to the kerning data. + * @return {object} The parsed Bitmap Font data. + */ bitmapFont: function (xml, baseTexture, xSpacing, ySpacing, frame, resolution) { - return this.xmlBitmapFont(xml, baseTexture, xSpacing, ySpacing, frame, resolution); - }, /** - * Parse a Bitmap Font from an XML file. - * - * @method Phaser.LoaderParser.xmlBitmapFont - * @param {object} xml - XML data you want to parse. - * @param {PIXI.BaseTexture} baseTexture - The BaseTexture this font uses. - * @param {number} [xSpacing=0] - Additional horizontal spacing between the characters. - * @param {number} [ySpacing=0] - Additional vertical spacing between the characters. - * @param {Phaser.Frame} [frame] - Optional Frame, if this font is embedded in a texture atlas. - * @param {number} [resolution=1] - Optional game resolution to apply to the kerning data. - * @return {object} The parsed Bitmap Font data. - */ + * Parse a Bitmap Font from an XML file. + * + * @method Phaser.LoaderParser.xmlBitmapFont + * @param {object} xml - XML data you want to parse. + * @param {PIXI.BaseTexture} baseTexture - The BaseTexture this font uses. + * @param {number} [xSpacing=0] - Additional horizontal spacing between the characters. + * @param {number} [ySpacing=0] - Additional vertical spacing between the characters. + * @param {Phaser.Frame} [frame] - Optional Frame, if this font is embedded in a texture atlas. + * @param {number} [resolution=1] - Optional game resolution to apply to the kerning data. + * @return {object} The parsed Bitmap Font data. + */ xmlBitmapFont: function (xml, baseTexture, xSpacing, ySpacing, frame, resolution) { - if (resolution == null) { resolution = 1; @@ -122,24 +119,22 @@ Phaser.LoaderParser = { } return this.finalizeBitmapFont(baseTexture, data); - }, /** - * Parse a Bitmap Font from a JSON file. - * - * @method Phaser.LoaderParser.jsonBitmapFont - * @param {object} json - JSON data you want to parse. - * @param {PIXI.BaseTexture} baseTexture - The BaseTexture this font uses. - * @param {number} [xSpacing=0] - Additional horizontal spacing between the characters. - * @param {number} [ySpacing=0] - Additional vertical spacing between the characters. - * @param {Phaser.Frame} [frame] - Optional Frame, if this font is embedded in a texture atlas. - * @param {number} [resolution=1] - Optional game resolution to apply to the kerning data. - * @return {object} The parsed Bitmap Font data. - */ + * Parse a Bitmap Font from a JSON file. + * + * @method Phaser.LoaderParser.jsonBitmapFont + * @param {object} json - JSON data you want to parse. + * @param {PIXI.BaseTexture} baseTexture - The BaseTexture this font uses. + * @param {number} [xSpacing=0] - Additional horizontal spacing between the characters. + * @param {number} [ySpacing=0] - Additional vertical spacing between the characters. + * @param {Phaser.Frame} [frame] - Optional Frame, if this font is embedded in a texture atlas. + * @param {number} [resolution=1] - Optional game resolution to apply to the kerning data. + * @return {object} The parsed Bitmap Font data. + */ jsonBitmapFont: function (json, baseTexture, xSpacing, ySpacing, frame, resolution) { - if (resolution == null) { resolution = 1; @@ -159,7 +154,6 @@ Phaser.LoaderParser = { function parseChar (letter) { - var charCode = parseInt(letter._id, 10); var char = data.chars[charCode] = { @@ -219,64 +213,60 @@ Phaser.LoaderParser = { } return this.finalizeBitmapFont(baseTexture, data); - }, /** - * Finalize Bitmap Font parsing. - * - * @method Phaser.LoaderParser.finalizeBitmapFont - * @private - * @param {PIXI.BaseTexture} baseTexture - The BaseTexture this font uses. - * @param {object} bitmapFontData - Pre-parsed bitmap font data. - * @return {object} The parsed Bitmap Font data. - */ + * Finalize Bitmap Font parsing. + * + * @method Phaser.LoaderParser.finalizeBitmapFont + * @private + * @param {PIXI.BaseTexture} baseTexture - The BaseTexture this font uses. + * @param {object} bitmapFontData - Pre-parsed bitmap font data. + * @return {object} The parsed Bitmap Font data. + */ finalizeBitmapFont: function (baseTexture, bitmapFontData) { - Object.keys(bitmapFontData.chars).forEach( function addTexture (charCode) { - var letter = bitmapFontData.chars[charCode]; letter.texture = new PIXI.Texture(baseTexture, new Phaser.Rectangle(letter.x, letter.y, letter.width, letter.height)); - } ); return bitmapFontData; - }, /** - * Extract PVR header from loaded binary - * - * @method Phaser.LoaderParser.pvr - * @param {ArrayBuffer} arrayBuffer - * @return {object} The parsed PVR file including texture data. - */ + * Extract PVR header from loaded binary + * + * @method Phaser.LoaderParser.pvr + * @param {ArrayBuffer} arrayBuffer + * @return {object} The parsed PVR file including texture data. + */ pvr: function (arrayBuffer) { - - // Reference: http://cdn.imgtec.com/sdk-documentation/PVR+File+Format.Specification.pdf - // PVR 3 header structure - // --------------------------------------- - // address: 0, size: 4 bytes version - // address: 4, size: 4 bytes flags - // address: 8, size: 8 bytes pixel format - // address: 16, size: 4 bytes color space - // address: 20, size: 4 bytes channel type - // address: 24, size: 4 bytes height - // address: 28, size: 4 bytes width - // address: 32, size: 4 bytes depth - // address: 36, size: 4 bytes number of surfaces - // address: 40, size: 4 bytes number of faces - // address: 44, size: 4 bytes number of mipmaps - // address: 48, size: 4 bytes meta data size - // --------------------------------------- + /* + * Reference: http://cdn.imgtec.com/sdk-documentation/PVR+File+Format.Specification.pdf + * PVR 3 header structure + * --------------------------------------- + * address: 0, size: 4 bytes version + * address: 4, size: 4 bytes flags + * address: 8, size: 8 bytes pixel format + * address: 16, size: 4 bytes color space + * address: 20, size: 4 bytes channel type + * address: 24, size: 4 bytes height + * address: 28, size: 4 bytes width + * address: 32, size: 4 bytes depth + * address: 36, size: 4 bytes number of surfaces + * address: 40, size: 4 bytes number of faces + * address: 44, size: 4 bytes number of mipmaps + * address: 48, size: 4 bytes meta data size + * --------------------------------------- + */ var uintArray = new Uint32Array(arrayBuffer.slice(0, 52)), byteArray = new Uint8Array(arrayBuffer), pvrHeader = null, @@ -355,51 +345,51 @@ Phaser.LoaderParser = { } return pvrHeader; - }, /** - * Extract DDS header from loaded binary - * - * @method Phaser.LoaderParser.dds - * @param {ArrayBuffer} arrayBuffer - * @return {object} The parsed DDS file including texture data. - */ + * Extract DDS header from loaded binary + * + * @method Phaser.LoaderParser.dds + * @param {ArrayBuffer} arrayBuffer + * @return {object} The parsed DDS file including texture data. + */ dds: function (arrayBuffer) { - - // Reference at: https://msdn.microsoft.com/en-us/library/windows/desktop/bb943982(v=vs.85).aspx - // DDS header structure - // --------------------------------------- - // address: 0, size: 4 bytes Identifier 'DDS ' - // address: 4, size: 4 bytes size - // address: 8, size: 4 bytes flags - // address: 12, size: 4 bytes height - // address: 16, size: 4 bytes width - // address: 20, size: 4 bytes pitch or linear size - // address: 24, size: 4 bytes depth - // address: 28, size: 4 bytes mipmap count - // address: 32, size: 44 bytes reserved space 1 - // address: 76, size: 4 pixel format size - // address: 80, size: 4 pixel format flag - // address: 84, size: 4 pixel format four CC - // address: 88, size: 4 pixel format bit count - // address: 92, size: 4 pixel format R bit mask - // address: 96, size: 4 pixel format G bit mask - // address: 100, size: 4 pixel format B bit mask - // address: 104, size: 4 pixel format A bit mask - // address: 108, size: 4 caps 1 - // address: 112, size: 4 caps 2 - // address: 116, size: 4 caps 3 - // address: 120, size: 4 caps 4 - // address: 124, size: 4 reserved 2 - // -- DXT10 extension - // address: 130, size: 4 DXGI Format - // address: 134, size: 4 resource dimension - // address: 138, size: 4 misc flag - // address: 142, size: 4 array size - // address: 146, size: 4 misc flag 2 - // --------------------------------------- + /* + * Reference at: https://msdn.microsoft.com/en-us/library/windows/desktop/bb943982(v=vs.85).aspx + * DDS header structure + * --------------------------------------- + * address: 0, size: 4 bytes Identifier 'DDS ' + * address: 4, size: 4 bytes size + * address: 8, size: 4 bytes flags + * address: 12, size: 4 bytes height + * address: 16, size: 4 bytes width + * address: 20, size: 4 bytes pitch or linear size + * address: 24, size: 4 bytes depth + * address: 28, size: 4 bytes mipmap count + * address: 32, size: 44 bytes reserved space 1 + * address: 76, size: 4 pixel format size + * address: 80, size: 4 pixel format flag + * address: 84, size: 4 pixel format four CC + * address: 88, size: 4 pixel format bit count + * address: 92, size: 4 pixel format R bit mask + * address: 96, size: 4 pixel format G bit mask + * address: 100, size: 4 pixel format B bit mask + * address: 104, size: 4 pixel format A bit mask + * address: 108, size: 4 caps 1 + * address: 112, size: 4 caps 2 + * address: 116, size: 4 caps 3 + * address: 120, size: 4 caps 4 + * address: 124, size: 4 reserved 2 + * -- DXT10 extension + * address: 130, size: 4 DXGI Format + * address: 134, size: 4 resource dimension + * address: 138, size: 4 misc flag + * address: 142, size: 4 array size + * address: 146, size: 4 misc flag 2 + * --------------------------------------- + */ var byteArray = new Uint8Array(arrayBuffer), uintArray = new Uint32Array(arrayBuffer), ddsHeader = null; @@ -463,41 +453,41 @@ Phaser.LoaderParser = { } return ddsHeader; - }, /** - * Extract KTX header from loaded binary - * - * @method Phaser.LoaderParser.ktx - * @param {ArrayBuffer} arrayBuffer - * @return {object} The parsed KTX file including texture data. - */ + * Extract KTX header from loaded binary + * + * @method Phaser.LoaderParser.ktx + * @param {ArrayBuffer} arrayBuffer + * @return {object} The parsed KTX file including texture data. + */ ktx: function (arrayBuffer) { - - // Reference: https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/ - // KTX header structure - // --------------------------------------- - // address: 0, size 12 bytes: Identifier '«KTX 11»\r\n\x1A\n' - // address: 12, size 4 bytes: endianness - // address: 16, size 4 bytes: GL type - // address: 20, size 4 bytes: GL type size - // address: 24, size 4 bytes: GL format - // address: 28, size 4 bytes: GL internal format - // address: 32, size 4 bytes: GL base internal format - // address: 36, size 4 bytes: pixel width - // address: 40, size 4 bytes: pixel height - // address: 44, size 4 bytes: pixel depth - // address: 48, size 4 bytes: number of array elements - // address: 52, size 4 bytes: number of faces - // address: 56, size 4 bytes: number of mipmap levels - // address: 60, size 4 bytes: bytes of key value data - // address: 64, size 4 bytes: key and value bytes size - // address: X, size 1 byte : key and value - // address: X, size 1 byte : value padding - // address: X, size 4 byte : image size - // --------------------------------------- + /* + * Reference: https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/ + * KTX header structure + * --------------------------------------- + * address: 0, size 12 bytes: Identifier '«KTX 11»\r\n\x1A\n' + * address: 12, size 4 bytes: endianness + * address: 16, size 4 bytes: GL type + * address: 20, size 4 bytes: GL type size + * address: 24, size 4 bytes: GL format + * address: 28, size 4 bytes: GL internal format + * address: 32, size 4 bytes: GL base internal format + * address: 36, size 4 bytes: pixel width + * address: 40, size 4 bytes: pixel height + * address: 44, size 4 bytes: pixel depth + * address: 48, size 4 bytes: number of array elements + * address: 52, size 4 bytes: number of faces + * address: 56, size 4 bytes: number of mipmap levels + * address: 60, size 4 bytes: bytes of key value data + * address: 64, size 4 bytes: key and value bytes size + * address: X, size 1 byte : key and value + * address: X, size 1 byte : value padding + * address: X, size 4 byte : image size + * --------------------------------------- + */ var byteArray = new Uint8Array(arrayBuffer), uintArray = new Uint32Array(arrayBuffer), ktxHeader = null, @@ -568,30 +558,30 @@ Phaser.LoaderParser = { } return ktxHeader; - }, /** - * Extract PKM header from loaded binary - * - * @method Phaser.LoaderParser.pkm - * @param {ArrayBuffer} arrayBuffer - * @return {object} The parsed PKM file including texture data. - */ + * Extract PKM header from loaded binary + * + * @method Phaser.LoaderParser.pkm + * @param {ArrayBuffer} arrayBuffer + * @return {object} The parsed PKM file including texture data. + */ pkm: function (arrayBuffer) { - - // PKM header structure - // --------------------------------------- - // address: 0, size 4 bytes: for 'PKM ' - // address: 4, size 2 bytes: for version - // address: 6, size 2 bytes: for type - // address: 8, size 2 bytes: for extended width - // address: 10, size 2 bytes: for extended height - // address: 12, size 2 bytes: for original width - // address: 14, size 2 bytes: for original height - // address: 16, texture data - // --------------------------------------- + /* + * PKM header structure + * --------------------------------------- + * address: 0, size 4 bytes: for 'PKM ' + * address: 4, size 2 bytes: for version + * address: 6, size 2 bytes: for type + * address: 8, size 2 bytes: for extended width + * address: 10, size 2 bytes: for extended height + * address: 12, size 2 bytes: for original width + * address: 14, size 2 bytes: for original height + * address: 16, texture data + * --------------------------------------- + */ var byteArray = new Uint8Array(arrayBuffer), pkmHeader = null; @@ -600,7 +590,6 @@ Phaser.LoaderParser = { byteArray[2] === 0x4D && byteArray[3] === 0x20) { - pkmHeader = { complete: true, fileFormat: 'PKM', @@ -615,7 +604,6 @@ Phaser.LoaderParser = { } return pkmHeader; - } }; diff --git a/src/math/Math.js b/src/math/Math.js index 82cdd0e78..c10d70251 100644 --- a/src/math/Math.js +++ b/src/math/Math.js @@ -1,26 +1,26 @@ /** -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* A collection of useful mathematical functions. -* -* These are normally accessed through `game.math`. -* -* @class Phaser.Math -* @static -* @see {@link Phaser.Utils} -* @see {@link Phaser.ArrayUtils} -*/ + * A collection of useful mathematical functions. + * + * These are normally accessed through `game.math`. + * + * @class Phaser.Math + * @static + * @see {@link Phaser.Utils} + * @see {@link Phaser.ArrayUtils} + */ Phaser.Math = { /** - * Twice PI. - * @property {number} Phaser.Math#PI2 - * @default ~6.283 - */ + * Twice PI. + * @property {number} Phaser.Math#PI2 + * @default ~6.283 + */ PI2: Math.PI * 2, /** @@ -31,56 +31,51 @@ Phaser.Math = { HALF_PI: Math.PI * 0.5, /** - * Degrees to Radians factor. - * @property {number} Phaser.Math#DEG_TO_RAD - */ + * Degrees to Radians factor. + * @property {number} Phaser.Math#DEG_TO_RAD + */ DEG_TO_RAD: Math.PI / 180, /** - * Degrees to Radians factor. - * @property {number} Phaser.Math#RAD_TO_DEG - */ + * Degrees to Radians factor. + * @property {number} Phaser.Math#RAD_TO_DEG + */ RAD_TO_DEG: 180 / Math.PI, /** - * Convert degrees to radians. - * - * @method Phaser.Math#degToRad - * @param {number} degrees - Angle in degrees. - * @return {number} Angle in radians. - */ + * Convert degrees to radians. + * + * @method Phaser.Math#degToRad + * @param {number} degrees - Angle in degrees. + * @return {number} Angle in radians. + */ degToRad: function (degrees) { - return degrees * Phaser.Math.DEG_TO_RAD; - }, /** - * Convert radians to degrees. - * - * @method Phaser.Math#radToDeg - * @param {number} radians - Angle in radians. - * @return {number} Angle in degrees - */ + * Convert radians to degrees. + * + * @method Phaser.Math#radToDeg + * @param {number} radians - Angle in radians. + * @return {number} Angle in degrees + */ radToDeg: function (radians) { - return radians * Phaser.Math.RAD_TO_DEG; - }, /** - * Given a number, this function returns the closest number that is a power of two. - * This function is from the Starling Framework. - * - * @method Phaser.Math#getNextPowerOfTwo - * @param {number} value - The value to get the closest power of two from. - * @return {number} The closest number that is a power of two. - */ + * Given a number, this function returns the closest number that is a power of two. + * This function is from the Starling Framework. + * + * @method Phaser.Math#getNextPowerOfTwo + * @param {number} value - The value to get the closest power of two from. + * @return {number} The closest number that is a power of two. + */ getNextPowerOfTwo: function (value) { - if (value > 0 && (value & (value - 1)) === 0) { // http://goo.gl/D9kPj @@ -97,36 +92,32 @@ Phaser.Math = { return result; } - }, /** - * Checks if the given dimensions make a power of two texture. - * - * @method Phaser.Math#isPowerOfTwo - * @param {number} width - The width to check. - * @param {number} height - The height to check. - * @return {boolean} True if the width and height are a power of two. - */ + * Checks if the given dimensions make a power of two texture. + * + * @method Phaser.Math#isPowerOfTwo + * @param {number} width - The width to check. + * @param {number} height - The height to check. + * @return {boolean} True if the width and height are a power of two. + */ isPowerOfTwo: function (width, height) { - return (width > 0 && (width & (width - 1)) === 0 && height > 0 && (height & (height - 1)) === 0); - }, /** - * Returns a random float in the range `[min, max)`. If these parameters are not in order than they will be put in order. - * Default is 0 for `min` and 1 for `max`. - * - * @method Phaser.Math#random - * @param {number} min - The minimum value. Must be a Number. - * @param {number} max - The maximum value. Must be a Number. - * @return {number} A floating point number between min (inclusive) and max (exclusive). - */ + * Returns a random float in the range `[min, max)`. If these parameters are not in order than they will be put in order. + * Default is 0 for `min` and 1 for `max`. + * + * @method Phaser.Math#random + * @param {number} min - The minimum value. Must be a Number. + * @param {number} max - The maximum value. Must be a Number. + * @return {number} A floating point number between min (inclusive) and max (exclusive). + */ random: function (min, max) { - if (min === undefined) { min = 0; } if (max === undefined) { max = 1; } @@ -143,21 +134,19 @@ Phaser.Math = { } return (Math.random() * (max - min) + min); - }, /** - * Returns a random integer in the range `[min, max]`. If these parameters are not in order than they will be put in order. - * Default is 0 for `min` and 1 for `max`. - * - * @method Phaser.Math#between - * @param {number} min - The minimum value. Must be a Number. - * @param {number} max - The maximum value. Must be a Number. - * @return {number} An integer between min (inclusive) and max (inclusive). - */ + * Returns a random integer in the range `[min, max]`. If these parameters are not in order than they will be put in order. + * Default is 0 for `min` and 1 for `max`. + * + * @method Phaser.Math#between + * @param {number} min - The minimum value. Must be a Number. + * @param {number} max - The maximum value. Must be a Number. + * @return {number} An integer between min (inclusive) and max (inclusive). + */ between: function (min, max) { - if (min === undefined) { min = 0; } if (max === undefined) { max = 1; } @@ -177,107 +166,95 @@ Phaser.Math = { max = Math.floor(max); return Math.floor(Math.random() * (max - min + 1)) + min; - }, /** - * Two number are fuzzyEqual if their difference is less than epsilon. - * - * @method Phaser.Math#fuzzyEqual - * @param {number} a - The first number to compare. - * @param {number} b - The second number to compare. - * @param {number} [epsilon=0.0001] - The epsilon (a small value used in the calculation) - * @return {boolean} True if |a-b|b+epsilon - */ + * `a` is fuzzyGreaterThan `b` if it is more than b - epsilon. + * + * @method Phaser.Math#fuzzyGreaterThan + * @param {number} a - The first number to compare. + * @param {number} b - The second number to compare. + * @param {number} [epsilon=0.0001] - The epsilon (a small value used in the calculation) + * @return {boolean} True if a>b+epsilon + */ fuzzyGreaterThan: function (a, b, epsilon) { - if (epsilon === undefined) { epsilon = 0.0001; } return a > b - epsilon; - }, /** - * Applies a fuzzy ceil to the given value. - * - * @method Phaser.Math#fuzzyCeil - * @param {number} val - The value to ceil. - * @param {number} [epsilon=0.0001] - The epsilon (a small value used in the calculation) - * @return {number} ceiling(val-epsilon) - */ + * Applies a fuzzy ceil to the given value. + * + * @method Phaser.Math#fuzzyCeil + * @param {number} val - The value to ceil. + * @param {number} [epsilon=0.0001] - The epsilon (a small value used in the calculation) + * @return {number} ceiling(val-epsilon) + */ fuzzyCeil: function (val, epsilon) { - if (epsilon === undefined) { epsilon = 0.0001; } return Math.ceil(val - epsilon); - }, /** - * Applies a fuzzy floor to the given value. - * - * @method Phaser.Math#fuzzyFloor - * @param {number} val - The value to floor. - * @param {number} [epsilon=0.0001] - The epsilon (a small value used in the calculation) - * @return {number} floor(val+epsilon) - */ + * Applies a fuzzy floor to the given value. + * + * @method Phaser.Math#fuzzyFloor + * @param {number} val - The value to floor. + * @param {number} [epsilon=0.0001] - The epsilon (a small value used in the calculation) + * @return {number} floor(val+epsilon) + */ fuzzyFloor: function (val, epsilon) { - if (epsilon === undefined) { epsilon = 0.0001; } return Math.floor(val + epsilon); - }, /** - * Averages all values passed to the function and returns the result. - * - * @method Phaser.Math#average - * @params {...number} The numbers to average - * @return {number} The average of all given values. - */ + * Averages all values passed to the function and returns the result. + * + * @method Phaser.Math#average + * @params {...number} The numbers to average + * @return {number} The average of all given values. + */ average: function () { - var sum = 0; var len = arguments.length; @@ -287,35 +264,31 @@ Phaser.Math = { } return sum / len; - }, /** - * @method Phaser.Math#shear - * @param {number} n - * @return {number} n mod 1 - */ + * @method Phaser.Math#shear + * @param {number} n + * @return {number} n mod 1 + */ shear: function (n) { - return n % 1; - }, /** - * Snap a value to nearest grid slice, using rounding. - * - * Example: if you have an interval gap of 5 and a position of 12... you will snap to 10 whereas 14 will snap to 15. - * - * @method Phaser.Math#snapTo - * @param {number} input - The value to snap. - * @param {number} gap - The interval gap of the grid. - * @param {number} [start=0] - Optional starting offset for gap. - * @return {number} The snapped value. - */ + * Snap a value to nearest grid slice, using rounding. + * + * Example: if you have an interval gap of 5 and a position of 12... you will snap to 10 whereas 14 will snap to 15. + * + * @method Phaser.Math#snapTo + * @param {number} input - The value to snap. + * @param {number} gap - The interval gap of the grid. + * @param {number} [start=0] - Optional starting offset for gap. + * @return {number} The snapped value. + */ snapTo: function (input, gap, start) { - if (start === undefined) { start = 0; } if (gap === 0) @@ -327,24 +300,22 @@ Phaser.Math = { input = gap * Math.round(input / gap); return start + input; - }, /** - * Snap a value to nearest grid slice, using floor. - * - * Example: if you have an interval gap of 5 and a position of 12... you will snap to 10. - * As will 14 snap to 10... but 16 will snap to 15. - * - * @method Phaser.Math#snapToFloor - * @param {number} input - The value to snap. - * @param {number} gap - The interval gap of the grid. - * @param {number} [start=0] - Optional starting offset for gap. - * @return {number} The snapped value. - */ + * Snap a value to nearest grid slice, using floor. + * + * Example: if you have an interval gap of 5 and a position of 12... you will snap to 10. + * As will 14 snap to 10... but 16 will snap to 15. + * + * @method Phaser.Math#snapToFloor + * @param {number} input - The value to snap. + * @param {number} gap - The interval gap of the grid. + * @param {number} [start=0] - Optional starting offset for gap. + * @return {number} The snapped value. + */ snapToFloor: function (input, gap, start) { - if (start === undefined) { start = 0; } if (gap === 0) @@ -356,24 +327,22 @@ Phaser.Math = { input = gap * Math.floor(input / gap); return start + input; - }, /** - * Snap a value to nearest grid slice, using ceil. - * - * Example: if you have an interval gap of 5 and a position of 12... you will snap to 15. - * As will 14 will snap to 15... but 16 will snap to 20. - * - * @method Phaser.Math#snapToCeil - * @param {number} input - The value to snap. - * @param {number} gap - The interval gap of the grid. - * @param {number} [start=0] - Optional starting offset for gap. - * @return {number} The snapped value. - */ + * Snap a value to nearest grid slice, using ceil. + * + * Example: if you have an interval gap of 5 and a position of 12... you will snap to 15. + * As will 14 will snap to 15... but 16 will snap to 20. + * + * @method Phaser.Math#snapToCeil + * @param {number} input - The value to snap. + * @param {number} gap - The interval gap of the grid. + * @param {number} [start=0] - Optional starting offset for gap. + * @return {number} The snapped value. + */ snapToCeil: function (input, gap, start) { - if (start === undefined) { start = 0; } if (gap === 0) @@ -385,133 +354,123 @@ Phaser.Math = { input = gap * Math.ceil(input / gap); return start + input; - }, /** - * Round to some place comparative to a `base`, default is 10 for decimal place. - * The `place` is represented by the power applied to `base` to get that place. - * - * e.g. 2000/7 ~= 285.714285714285714285714 ~= (bin)100011101.1011011011011011 - * - * roundTo(2000/7,3) === 0 - * roundTo(2000/7,2) == 300 - * roundTo(2000/7,1) == 290 - * roundTo(2000/7,0) == 286 - * roundTo(2000/7,-1) == 285.7 - * roundTo(2000/7,-2) == 285.71 - * roundTo(2000/7,-3) == 285.714 - * roundTo(2000/7,-4) == 285.7143 - * roundTo(2000/7,-5) == 285.71429 - * - * roundTo(2000/7,3,2) == 288 -- 100100000 - * roundTo(2000/7,2,2) == 284 -- 100011100 - * roundTo(2000/7,1,2) == 286 -- 100011110 - * roundTo(2000/7,0,2) == 286 -- 100011110 - * roundTo(2000/7,-1,2) == 285.5 -- 100011101.1 - * roundTo(2000/7,-2,2) == 285.75 -- 100011101.11 - * roundTo(2000/7,-3,2) == 285.75 -- 100011101.11 - * roundTo(2000/7,-4,2) == 285.6875 -- 100011101.1011 - * roundTo(2000/7,-5,2) == 285.71875 -- 100011101.10111 - * - * Note what occurs when we round to the 3rd space (8ths place), 100100000, this is to be assumed - * because we are rounding 100011.1011011011011011 which rounds up. - * - * @method Phaser.Math#roundTo - * @param {number} value - The value to round. - * @param {number} [place=0] - The place to round to. - * @param {number} [base=10] - The base to round in. Default is 10 for decimal. - * @return {number} The rounded value. - */ + * Round to some place comparative to a `base`, default is 10 for decimal place. + * The `place` is represented by the power applied to `base` to get that place. + * + * e.g. 2000/7 ~= 285.714285714285714285714 ~= (bin)100011101.1011011011011011 + * + * roundTo(2000/7,3) === 0 + * roundTo(2000/7,2) == 300 + * roundTo(2000/7,1) == 290 + * roundTo(2000/7,0) == 286 + * roundTo(2000/7,-1) == 285.7 + * roundTo(2000/7,-2) == 285.71 + * roundTo(2000/7,-3) == 285.714 + * roundTo(2000/7,-4) == 285.7143 + * roundTo(2000/7,-5) == 285.71429 + * + * roundTo(2000/7,3,2) == 288 -- 100100000 + * roundTo(2000/7,2,2) == 284 -- 100011100 + * roundTo(2000/7,1,2) == 286 -- 100011110 + * roundTo(2000/7,0,2) == 286 -- 100011110 + * roundTo(2000/7,-1,2) == 285.5 -- 100011101.1 + * roundTo(2000/7,-2,2) == 285.75 -- 100011101.11 + * roundTo(2000/7,-3,2) == 285.75 -- 100011101.11 + * roundTo(2000/7,-4,2) == 285.6875 -- 100011101.1011 + * roundTo(2000/7,-5,2) == 285.71875 -- 100011101.10111 + * + * Note what occurs when we round to the 3rd space (8ths place), 100100000, this is to be assumed + * because we are rounding 100011.1011011011011011 which rounds up. + * + * @method Phaser.Math#roundTo + * @param {number} value - The value to round. + * @param {number} [place=0] - The place to round to. + * @param {number} [base=10] - The base to round in. Default is 10 for decimal. + * @return {number} The rounded value. + */ roundTo: function (value, place, base) { - if (place === undefined) { place = 0; } if (base === undefined) { base = 10; } var p = Math.pow(base, -place); return Math.round(value * p) / p; - }, /** - * Floors to some place comparative to a `base`, default is 10 for decimal place. - * The `place` is represented by the power applied to `base` to get that place. - * - * @method Phaser.Math#floorTo - * @param {number} value - The value to round. - * @param {number} [place=0] - The place to round to. - * @param {number} [base=10] - The base to round in. Default is 10 for decimal. - * @return {number} The rounded value. - */ + * Floors to some place comparative to a `base`, default is 10 for decimal place. + * The `place` is represented by the power applied to `base` to get that place. + * + * @method Phaser.Math#floorTo + * @param {number} value - The value to round. + * @param {number} [place=0] - The place to round to. + * @param {number} [base=10] - The base to round in. Default is 10 for decimal. + * @return {number} The rounded value. + */ floorTo: function (value, place, base) { - if (place === undefined) { place = 0; } if (base === undefined) { base = 10; } var p = Math.pow(base, -place); return Math.floor(value * p) / p; - }, /** - * Ceils to some place comparative to a `base`, default is 10 for decimal place. - * The `place` is represented by the power applied to `base` to get that place. - * - * @method Phaser.Math#ceilTo - * @param {number} value - The value to round. - * @param {number} [place=0] - The place to round to. - * @param {number} [base=10] - The base to round in. Default is 10 for decimal. - * @return {number} The rounded value. - */ + * Ceils to some place comparative to a `base`, default is 10 for decimal place. + * The `place` is represented by the power applied to `base` to get that place. + * + * @method Phaser.Math#ceilTo + * @param {number} value - The value to round. + * @param {number} [place=0] - The place to round to. + * @param {number} [base=10] - The base to round in. Default is 10 for decimal. + * @return {number} The rounded value. + */ ceilTo: function (value, place, base) { - if (place === undefined) { place = 0; } if (base === undefined) { base = 10; } var p = Math.pow(base, -place); return Math.ceil(value * p) / p; - }, /** - * Truncates a number, removing any fractional part. - * Same as round-towards-zero. - * - * @method Phaser.Math#trunc - * @param {number} value - The value to truncate. - * @return {number} The truncated value. - */ + * Truncates a number, removing any fractional part. + * Same as round-towards-zero. + * + * @method Phaser.Math#trunc + * @param {number} value - The value to truncate. + * @return {number} The truncated value. + */ trunc: function (value) { - if (!isFinite(value)) { return value; } return (value - value % 1) || (value < 0 ? -0 : value === 0 ? value : 0); - }, /** - * Rotates currentAngle towards targetAngle, taking the shortest rotation distance. - * The lerp argument is the amount to rotate by in this call. - * - * @method Phaser.Math#rotateToAngle - * @param {number} currentAngle - The current angle, in radians. - * @param {number} targetAngle - The target angle to rotate to, in radians. - * @param {number} [lerp=0.05] - The lerp value to add to the current angle. - * @return {number} The adjusted angle. - */ + * Rotates currentAngle towards targetAngle, taking the shortest rotation distance. + * The lerp argument is the amount to rotate by in this call. + * + * @method Phaser.Math#rotateToAngle + * @param {number} currentAngle - The current angle, in radians. + * @param {number} targetAngle - The target angle to rotate to, in radians. + * @param {number} [lerp=0.05] - The lerp value to add to the current angle. + * @return {number} The adjusted angle. + */ rotateToAngle: function (currentAngle, targetAngle, lerp) { - if (lerp === undefined) { lerp = 0.05; } if (currentAngle === targetAngle) @@ -548,27 +507,25 @@ Phaser.Math = { } return currentAngle; - }, /** - * Gets the shortest angle between `angle1` and `angle2`. - * Both angles must be in the range -180 to 180, which is the same clamped - * range that `sprite.angle` uses, so you can pass in two sprite angles to - * this method, and get the shortest angle back between the two of them. - * - * The angle returned will be in the same range. If the returned angle is - * greater than 0 then it's a counter-clockwise rotation, if < 0 then it's - * a clockwise rotation. - * - * @method Phaser.Math#getShortestAngle - * @param {number} angle1 - The first angle. In the range -180 to 180. - * @param {number} angle2 - The second angle. In the range -180 to 180. - * @return {number} The shortest angle, in degrees. If greater than zero it's a counter-clockwise rotation. - */ + * Gets the shortest angle between `angle1` and `angle2`. + * Both angles must be in the range -180 to 180, which is the same clamped + * range that `sprite.angle` uses, so you can pass in two sprite angles to + * this method, and get the shortest angle back between the two of them. + * + * The angle returned will be in the same range. If the returned angle is + * greater than 0 then it's a counter-clockwise rotation, if < 0 then it's + * a clockwise rotation. + * + * @method Phaser.Math#getShortestAngle + * @param {number} angle1 - The first angle. In the range -180 to 180. + * @param {number} angle2 - The second angle. In the range -180 to 180. + * @return {number} The shortest angle, in degrees. If greater than zero it's a counter-clockwise rotation. + */ getShortestAngle: function (angle1, angle2) { - var difference = angle2 - angle1; if (difference === 0) @@ -579,148 +536,130 @@ Phaser.Math = { var times = Math.floor((difference - (-180)) / 360); return difference - (times * 360); - }, /** - * Find the angle of a segment from (x1, y1) -> (x2, y2). - * - * @method Phaser.Math#angleBetween - * @param {number} x1 - The x coordinate of the first value. - * @param {number} y1 - The y coordinate of the first value. - * @param {number} x2 - The x coordinate of the second value. - * @param {number} y2 - The y coordinate of the second value. - * @return {number} The angle, in radians. - */ + * Find the angle of a segment from (x1, y1) -> (x2, y2). + * + * @method Phaser.Math#angleBetween + * @param {number} x1 - The x coordinate of the first value. + * @param {number} y1 - The y coordinate of the first value. + * @param {number} x2 - The x coordinate of the second value. + * @param {number} y2 - The y coordinate of the second value. + * @return {number} The angle, in radians. + */ angleBetween: function (x1, y1, x2, y2) { - return Math.atan2(y2 - y1, x2 - x1); - }, /** - * Find the angle of a segment from (x1, y1) -> (x2, y2). - * - * The difference between this method and Math.angleBetween is that this assumes the y coordinate travels - * down the screen. - * - * @method Phaser.Math#angleBetweenY - * @param {number} x1 - The x coordinate of the first value. - * @param {number} y1 - The y coordinate of the first value. - * @param {number} x2 - The x coordinate of the second value. - * @param {number} y2 - The y coordinate of the second value. - * @return {number} The angle, in radians. - */ + * Find the angle of a segment from (x1, y1) -> (x2, y2). + * + * The difference between this method and Math.angleBetween is that this assumes the y coordinate travels + * down the screen. + * + * @method Phaser.Math#angleBetweenY + * @param {number} x1 - The x coordinate of the first value. + * @param {number} y1 - The y coordinate of the first value. + * @param {number} x2 - The x coordinate of the second value. + * @param {number} y2 - The y coordinate of the second value. + * @return {number} The angle, in radians. + */ angleBetweenY: function (x1, y1, x2, y2) { - return Math.atan2(x2 - x1, y2 - y1); - }, /** - * Find the angle of a segment from (point1.x, point1.y) -> (point2.x, point2.y). - * - * @method Phaser.Math#angleBetweenPoints - * @param {Phaser.Point} point1 - The first point. - * @param {Phaser.Point} point2 - The second point. - * @return {number} The angle between the two points, in radians. - */ + * Find the angle of a segment from (point1.x, point1.y) -> (point2.x, point2.y). + * + * @method Phaser.Math#angleBetweenPoints + * @param {Phaser.Point} point1 - The first point. + * @param {Phaser.Point} point2 - The second point. + * @return {number} The angle between the two points, in radians. + */ angleBetweenPoints: function (point1, point2) { - return Math.atan2(point2.y - point1.y, point2.x - point1.x); - }, /** - * Find the angle of a segment from (point1.x, point1.y) -> (point2.x, point2.y). - * @method Phaser.Math#angleBetweenPointsY - * @param {Phaser.Point} point1 - * @param {Phaser.Point} point2 - * @return {number} The angle, in radians. - */ + * Find the angle of a segment from (point1.x, point1.y) -> (point2.x, point2.y). + * @method Phaser.Math#angleBetweenPointsY + * @param {Phaser.Point} point1 + * @param {Phaser.Point} point2 + * @return {number} The angle, in radians. + */ angleBetweenPointsY: function (point1, point2) { - return Math.atan2(point2.x - point1.x, point2.y - point1.y); - }, /** - * Reverses an angle. - * @method Phaser.Math#reverseAngle - * @param {number} angleRad - The angle to reverse, in radians. - * @return {number} The reverse angle, in radians. - */ + * Reverses an angle. + * @method Phaser.Math#reverseAngle + * @param {number} angleRad - The angle to reverse, in radians. + * @return {number} The reverse angle, in radians. + */ reverseAngle: function (angleRad) { - return this.normalizeAngle(angleRad + Math.PI, true); - }, /** - * Normalizes an angle to the [0,2pi) range. - * @method Phaser.Math#normalizeAngle - * @param {number} angleRad - The angle to normalize, in radians. - * @return {number} The angle, fit within the [0,2pi] range, in radians. - */ + * Normalizes an angle to the [0,2pi) range. + * @method Phaser.Math#normalizeAngle + * @param {number} angleRad - The angle to normalize, in radians. + * @return {number} The angle, fit within the [0,2pi] range, in radians. + */ normalizeAngle: function (angleRad) { - angleRad = angleRad % (2 * Math.PI); return angleRad >= 0 ? angleRad : angleRad + 2 * Math.PI; - }, /** - * Adds the given amount to the value, but never lets the value go over the specified maximum. - * - * @method Phaser.Math#maxAdd - * @param {number} value - The value to add the amount to. - * @param {number} amount - The amount to add to the value. - * @param {number} max - The maximum the value is allowed to be. - * @return {number} The new value. - */ + * Adds the given amount to the value, but never lets the value go over the specified maximum. + * + * @method Phaser.Math#maxAdd + * @param {number} value - The value to add the amount to. + * @param {number} amount - The amount to add to the value. + * @param {number} max - The maximum the value is allowed to be. + * @return {number} The new value. + */ maxAdd: function (value, amount, max) { - return Math.min(value + amount, max); - }, /** - * Subtracts the given amount from the value, but never lets the value go below the specified minimum. - * - * @method Phaser.Math#minSub - * @param {number} value - The base value. - * @param {number} amount - The amount to subtract from the base value. - * @param {number} min - The minimum the value is allowed to be. - * @return {number} The new value. - */ + * Subtracts the given amount from the value, but never lets the value go below the specified minimum. + * + * @method Phaser.Math#minSub + * @param {number} value - The base value. + * @param {number} amount - The amount to subtract from the base value. + * @param {number} min - The minimum the value is allowed to be. + * @return {number} The new value. + */ minSub: function (value, amount, min) { - return Math.max(value - amount, min); - }, /** - * Ensures that the value always stays between min and max, by wrapping the value around. - * - * If `max` is not larger than `min` the result is 0. - * - * @method Phaser.Math#wrap - * @param {number} value - The value to wrap. - * @param {number} min - The minimum the value is allowed to be. - * @param {number} max - The maximum the value is allowed to be, should be larger than `min`. - * @return {number} The wrapped value. - */ + * Ensures that the value always stays between min and max, by wrapping the value around. + * + * If `max` is not larger than `min` the result is 0. + * + * @method Phaser.Math#wrap + * @param {number} value - The value to wrap. + * @param {number} min - The minimum the value is allowed to be. + * @param {number} max - The maximum the value is allowed to be, should be larger than `min`. + * @return {number} The wrapped value. + */ wrap: function (value, min, max) { - var range = max - min; if (range <= 0) @@ -736,23 +675,21 @@ Phaser.Math = { } return result + min; - }, /** - * Adds value to amount and ensures that the result always stays between 0 and max, by wrapping the value around. - * - * Values _must_ be positive integers, and are passed through Math.abs. See {@link Phaser.Math#wrap} for an alternative. - * - * @method Phaser.Math#wrapValue - * @param {number} value - The value to add the amount to. - * @param {number} amount - The amount to add to the value. - * @param {number} max - The maximum the value is allowed to be. - * @return {number} The wrapped value. - */ + * Adds value to amount and ensures that the result always stays between 0 and max, by wrapping the value around. + * + * Values _must_ be positive integers, and are passed through Math.abs. See {@link Phaser.Math#wrap} for an alternative. + * + * @method Phaser.Math#wrapValue + * @param {number} value - The value to add the amount to. + * @param {number} amount - The amount to add to the value. + * @param {number} max - The maximum the value is allowed to be. + * @return {number} The wrapped value. + */ wrapValue: function (value, amount, max) { - var diff; value = Math.abs(value); amount = Math.abs(amount); @@ -760,51 +697,45 @@ Phaser.Math = { diff = (value + amount) % max; return diff; - }, /** - * Returns true if the number given is odd. - * - * @method Phaser.Math#isOdd - * @param {integer} n - The number to check. - * @return {boolean} True if the given number is odd. False if the given number is even. - */ + * Returns true if the number given is odd. + * + * @method Phaser.Math#isOdd + * @param {integer} n - The number to check. + * @return {boolean} True if the given number is odd. False if the given number is even. + */ isOdd: function (n) { - // Does not work with extremely large values return !!(n & 1); - }, /** - * Returns true if the number given is even. - * - * @method Phaser.Math#isEven - * @param {integer} n - The number to check. - * @return {boolean} True if the given number is even. False if the given number is odd. - */ + * Returns true if the number given is even. + * + * @method Phaser.Math#isEven + * @param {integer} n - The number to check. + * @return {boolean} True if the given number is even. False if the given number is odd. + */ isEven: function (n) { - // Does not work with extremely large values return !(n & 1); - }, /** - * Variation of Math.min that can be passed either an array of numbers or the numbers as parameters. - * - * Prefer the standard `Math.min` function when appropriate. - * - * @method Phaser.Math#min - * @return {number} The lowest value from those given. - * @see {@link http://jsperf.com/math-s-min-max-vs-homemade} - */ + * Variation of Math.min that can be passed either an array of numbers or the numbers as parameters. + * + * Prefer the standard `Math.min` function when appropriate. + * + * @method Phaser.Math#min + * @return {number} The lowest value from those given. + * @see {@link http://jsperf.com/math-s-min-max-vs-homemade} + */ min: function () { - if (arguments.length === 1 && typeof arguments[0] === 'object') { var data = arguments[0]; @@ -823,21 +754,19 @@ Phaser.Math = { } return data[min]; - }, /** - * Variation of Math.max that can be passed either an array of numbers or the numbers as parameters. - * - * Prefer the standard `Math.max` function when appropriate. - * - * @method Phaser.Math#max - * @return {number} The largest value from those given. - * @see {@link http://jsperf.com/math-s-min-max-vs-homemade} - */ + * Variation of Math.max that can be passed either an array of numbers or the numbers as parameters. + * + * Prefer the standard `Math.max` function when appropriate. + * + * @method Phaser.Math#max + * @return {number} The largest value from those given. + * @see {@link http://jsperf.com/math-s-min-max-vs-homemade} + */ max: function () { - if (arguments.length === 1 && typeof arguments[0] === 'object') { var data = arguments[0]; @@ -856,19 +785,17 @@ Phaser.Math = { } return data[max]; - }, /** - * Variation of Math.min that can be passed a property and either an array of objects or the objects as parameters. - * It will find the lowest matching property value from the given objects. - * - * @method Phaser.Math#minProperty - * @return {number} The lowest value from those given. - */ + * Variation of Math.min that can be passed a property and either an array of objects or the objects as parameters. + * It will find the lowest matching property value from the given objects. + * + * @method Phaser.Math#minProperty + * @return {number} The lowest value from those given. + */ minProperty: function (property) { - if (arguments.length === 2 && typeof arguments[1] === 'object') { var data = arguments[1]; @@ -887,19 +814,17 @@ Phaser.Math = { } return data[min][property]; - }, /** - * Variation of Math.max that can be passed a property and either an array of objects or the objects as parameters. - * It will find the largest matching property value from the given objects. - * - * @method Phaser.Math#maxProperty - * @return {number} The largest value from those given. - */ + * Variation of Math.max that can be passed a property and either an array of objects or the objects as parameters. + * It will find the largest matching property value from the given objects. + * + * @method Phaser.Math#maxProperty + * @return {number} The largest value from those given. + */ maxProperty: function (property) { - if (arguments.length === 2 && typeof arguments[1] === 'object') { var data = arguments[1]; @@ -918,35 +843,31 @@ Phaser.Math = { } return data[max][property]; - }, /** - * Keeps an angle value between -180 and +180; or -PI and PI if radians. - * - * @method Phaser.Math#wrapAngle - * @param {number} angle - The angle value to wrap - * @param {boolean} [radians=false] - Set to `true` if the angle is given in radians, otherwise degrees is expected. - * @return {number} The new angle value; will be the same as the input angle if it was within bounds. - */ + * Keeps an angle value between -180 and +180; or -PI and PI if radians. + * + * @method Phaser.Math#wrapAngle + * @param {number} angle - The angle value to wrap + * @param {boolean} [radians=false] - Set to `true` if the angle is given in radians, otherwise degrees is expected. + * @return {number} The new angle value; will be the same as the input angle if it was within bounds. + */ wrapAngle: function (angle, radians) { - return radians ? this.wrap(angle, -Math.PI, Math.PI) : this.wrap(angle, -180, 180); - }, /** - * A Linear Interpolation Method, mostly used by Phaser.Tween. - * - * @method Phaser.Math#linearInterpolation - * @param {Array} v - The input array of values to interpolate between. - * @param {number} k - The amount of interpolation, between 0 (start) and 1 (end). - * @return {number} The interpolated value - */ + * A Linear Interpolation Method, mostly used by Phaser.Tween. + * + * @method Phaser.Math#linearInterpolation + * @param {Array} v - The input array of values to interpolate between. + * @param {number} k - The amount of interpolation, between 0 (start) and 1 (end). + * @return {number} The interpolated value + */ linearInterpolation: function (v, k) { - var m = v.length - 1; var f = m * k; var i = Math.floor(f); @@ -962,20 +883,18 @@ Phaser.Math = { } return this.linear(v[i], v[i + 1 > m ? m : i + 1], f - i); - }, /** - * A Bezier Interpolation Method, mostly used by Phaser.Tween. - * - * @method Phaser.Math#bezierInterpolation - * @param {Array} v - The input array of values to interpolate between. - * @param {number} k - The percentage of interpolation, between 0 and 1. - * @return {number} The interpolated value - */ + * A Bezier Interpolation Method, mostly used by Phaser.Tween. + * + * @method Phaser.Math#bezierInterpolation + * @param {Array} v - The input array of values to interpolate between. + * @param {number} k - The percentage of interpolation, between 0 and 1. + * @return {number} The interpolated value + */ bezierInterpolation: function (v, k) { - var b = 0; var n = v.length - 1; @@ -985,20 +904,18 @@ Phaser.Math = { } return b; - }, /** - * A Catmull Rom Interpolation Method, mostly used by Phaser.Tween. - * - * @method Phaser.Math#catmullRomInterpolation - * @param {Array} v - The input array of values to interpolate between. - * @param {number} k - The percentage of interpolation, between 0 and 1. - * @return {number} The interpolated value - */ + * A Catmull Rom Interpolation Method, mostly used by Phaser.Tween. + * + * @method Phaser.Math#catmullRomInterpolation + * @param {Array} v - The input array of values to interpolate between. + * @param {number} k - The percentage of interpolation, between 0 and 1. + * @return {number} The interpolated value + */ catmullRomInterpolation: function (v, k) { - var m = v.length - 1; var f = m * k; var i = Math.floor(f); @@ -1026,47 +943,41 @@ Phaser.Math = { return this.catmullRom(v[i ? i - 1 : 0], v[i], v[m < i + 1 ? m : i + 1], v[m < i + 2 ? m : i + 2], f - i); } - }, /** - * Calculates a linear (interpolation) value over t. - * - * @method Phaser.Math#linear - * @param {number} p0 - * @param {number} p1 - * @param {number} t - A value between 0 and 1. - * @return {number} - */ + * Calculates a linear (interpolation) value over t. + * + * @method Phaser.Math#linear + * @param {number} p0 + * @param {number} p1 + * @param {number} t - A value between 0 and 1. + * @return {number} + */ linear: function (p0, p1, t) { - return (p1 - p0) * t + p0; - }, /** - * @method Phaser.Math#bernstein - * @protected - * @param {number} n - * @param {number} i - * @return {number} - */ + * @method Phaser.Math#bernstein + * @protected + * @param {number} n + * @param {number} i + * @return {number} + */ bernstein: function (n, i) { - return this.factorial(n) / this.factorial(i) / this.factorial(n - i); - }, /** - * @method Phaser.Math#factorial - * @param {number} value - the number you want to evaluate - * @return {number} - */ + * @method Phaser.Math#factorial + * @param {number} value - the number you want to evaluate + * @return {number} + */ factorial: function (value) { - if (value === 0) { return 1; @@ -1080,79 +991,71 @@ Phaser.Math = { } return res; - }, /** - * Calculates a catmum rom value. - * - * @method Phaser.Math#catmullRom - * @protected - * @param {number} p0 - * @param {number} p1 - * @param {number} p2 - * @param {number} p3 - * @param {number} t - * @return {number} - */ + * Calculates a catmum rom value. + * + * @method Phaser.Math#catmullRom + * @protected + * @param {number} p0 + * @param {number} p1 + * @param {number} p2 + * @param {number} p3 + * @param {number} t + * @return {number} + */ catmullRom: function (p0, p1, p2, p3, t) { - var v0 = (p2 - p0) * 0.5, v1 = (p3 - p1) * 0.5, t2 = t * t, t3 = t * t2; return (2 * p1 - 2 * p2 + v0 + v1) * t3 + (-3 * p1 + 3 * p2 - 2 * v0 - v1) * t2 + v0 * t + p1; - }, /** - * The absolute difference between two values. - * - * @method Phaser.Math#difference - * @param {number} a - The first value to check. - * @param {number} b - The second value to check. - * @return {number} The absolute difference between the two values. - */ + * The absolute difference between two values. + * + * @method Phaser.Math#difference + * @param {number} a - The first value to check. + * @param {number} b - The second value to check. + * @return {number} The absolute difference between the two values. + */ difference: function (a, b) { - return Math.abs(a - b); - }, /** - * Round to the next whole number _away_ from zero. - * - * @method Phaser.Math#roundAwayFromZero - * @param {number} value - Any number. - * @return {integer} The rounded value of that number. - */ + * Round to the next whole number _away_ from zero. + * + * @method Phaser.Math#roundAwayFromZero + * @param {number} value - Any number. + * @return {integer} The rounded value of that number. + */ roundAwayFromZero: function (value) { - // "Opposite" of truncate. return (value > 0) ? Math.ceil(value) : Math.floor(value); - }, /** - * Generate a sine and cosine table simultaneously and extremely quickly. - * The parameters allow you to specify the length, amplitude and frequency of the wave. - * This generator is fast enough to be used in real-time. - * Code based on research by Franky of scene.at - * - * @method Phaser.Math#sinCosGenerator - * @param {number} length - The length of the wave - * @param {number} sinAmplitude - The amplitude to apply to the sine table (default 1.0) if you need values between say -+ 125 then give 125 as the value - * @param {number} cosAmplitude - The amplitude to apply to the cosine table (default 1.0) if you need values between say -+ 125 then give 125 as the value - * @param {number} frequency - The frequency of the sine and cosine table data - * @return {{sin:number[], cos:number[]}} Returns the table data. - */ + * Generate a sine and cosine table simultaneously and extremely quickly. + * The parameters allow you to specify the length, amplitude and frequency of the wave. + * This generator is fast enough to be used in real-time. + * Code based on research by Franky of scene.at + * + * @method Phaser.Math#sinCosGenerator + * @param {number} length - The length of the wave + * @param {number} sinAmplitude - The amplitude to apply to the sine table (default 1.0) if you need values between say -+ 125 then give 125 as the value + * @param {number} cosAmplitude - The amplitude to apply to the cosine table (default 1.0) if you need values between say -+ 125 then give 125 as the value + * @param {number} frequency - The frequency of the sine and cosine table data + * @return {{sin:number[], cos:number[]}} Returns the table data. + */ sinCosGenerator: function (length, sinAmplitude, cosAmplitude, frequency) { - if (sinAmplitude === undefined) { sinAmplitude = 1.0; } if (cosAmplitude === undefined) { cosAmplitude = 1.0; } if (frequency === undefined) { frequency = 1.0; } @@ -1166,107 +1069,95 @@ Phaser.Math = { for (var c = 0; c < length; c++) { - cos -= sin * frq; sin += cos * frq; cosTable[c] = cos; sinTable[c] = sin; - } return { sin: sinTable, cos: cosTable, length: length }; - }, /** - * Returns the length of the hypotenuse connecting two segments of given lengths. - * - * @method Phaser.Math#hypot - * @param {number} a - * @param {number} b - * @return {number} The length of the hypotenuse connecting the given lengths. - */ + * Returns the length of the hypotenuse connecting two segments of given lengths. + * + * @method Phaser.Math#hypot + * @param {number} a + * @param {number} b + * @return {number} The length of the hypotenuse connecting the given lengths. + */ hypot: function (a, b) { - return Math.sqrt(a * a + b * b); - }, /** - * Returns the euclidian distance between the two given set of coordinates. - * - * @method Phaser.Math#distance - * @param {number} x1 - * @param {number} y1 - * @param {number} x2 - * @param {number} y2 - * @return {number} The distance between the two sets of coordinates. - */ + * Returns the euclidian distance between the two given set of coordinates. + * + * @method Phaser.Math#distance + * @param {number} x1 + * @param {number} y1 + * @param {number} x2 + * @param {number} y2 + * @return {number} The distance between the two sets of coordinates. + */ distance: function (x1, y1, x2, y2) { - var dx = x1 - x2; var dy = y1 - y2; return Math.sqrt(dx * dx + dy * dy); - }, /** - * Returns the euclidean distance squared between the two given set of - * coordinates (cuts out a square root operation before returning). - * - * @method Phaser.Math#distanceSq - * @param {number} x1 - * @param {number} y1 - * @param {number} x2 - * @param {number} y2 - * @return {number} The distance squared between the two sets of coordinates. - */ + * Returns the euclidean distance squared between the two given set of + * coordinates (cuts out a square root operation before returning). + * + * @method Phaser.Math#distanceSq + * @param {number} x1 + * @param {number} y1 + * @param {number} x2 + * @param {number} y2 + * @return {number} The distance squared between the two sets of coordinates. + */ distanceSq: function (x1, y1, x2, y2) { - var dx = x1 - x2; var dy = y1 - y2; return dx * dx + dy * dy; - }, /** - * Returns the distance between the two given set of coordinates at the power given. - * - * @method Phaser.Math#distancePow - * @param {number} x1 - * @param {number} y1 - * @param {number} x2 - * @param {number} y2 - * @param {number} [pow=2] - * @return {number} The distance between the two sets of coordinates. - */ + * Returns the distance between the two given set of coordinates at the power given. + * + * @method Phaser.Math#distancePow + * @param {number} x1 + * @param {number} y1 + * @param {number} x2 + * @param {number} y2 + * @param {number} [pow=2] + * @return {number} The distance between the two sets of coordinates. + */ distancePow: function (x1, y1, x2, y2, pow) { - if (pow === undefined) { pow = 2; } return Math.sqrt(Math.pow(x2 - x1, pow) + Math.pow(y2 - y1, pow)); - }, /** - * Force a value within the boundaries by clamping it to the range `min`, `max`. - * - * @method Phaser.Math#clamp - * @param {float} v - The value to be clamped. - * @param {float} min - The minimum bounds. - * @param {float} max - The maximum bounds. - * @return {number} The clamped value. - */ + * Force a value within the boundaries by clamping it to the range `min`, `max`. + * + * @method Phaser.Math#clamp + * @param {float} v - The value to be clamped. + * @param {float} min - The minimum bounds. + * @param {float} max - The maximum bounds. + * @return {number} The clamped value. + */ clamp: function (v, min, max) { - if (v < min) { return min; @@ -1279,126 +1170,112 @@ Phaser.Math = { { return v; } - }, /** - * Clamp `x` to the range `[a, Infinity)`. - * Roughly the same as `Math.max(x, a)`, except for NaN handling. - * - * @method Phaser.Math#clampBottom - * @param {number} x - * @param {number} a - * @return {number} - */ + * Clamp `x` to the range `[a, Infinity)`. + * Roughly the same as `Math.max(x, a)`, except for NaN handling. + * + * @method Phaser.Math#clampBottom + * @param {number} x + * @param {number} a + * @return {number} + */ clampBottom: function (x, a) { - return x < a ? a : x; - }, /** - * Checks if two values are within the given tolerance of each other. - * - * @method Phaser.Math#within - * @param {number} a - The first number to check - * @param {number} b - The second number to check - * @param {number} tolerance - The tolerance. Anything equal to or less than this is considered within the range. - * @return {boolean} True if a is <= tolerance of b. - * @see {@link Phaser.Math.fuzzyEqual} - */ + * Checks if two values are within the given tolerance of each other. + * + * @method Phaser.Math#within + * @param {number} a - The first number to check + * @param {number} b - The second number to check + * @param {number} tolerance - The tolerance. Anything equal to or less than this is considered within the range. + * @return {boolean} True if a is <= tolerance of b. + * @see {@link Phaser.Math.fuzzyEqual} + */ within: function (a, b, tolerance) { - return (Math.abs(a - b) <= tolerance); - }, /** - * Linear mapping from range to range - * - * @method Phaser.Math#mapLinear - * @param {number} x - The value to map - * @param {number} a1 - First endpoint of the range - * @param {number} a2 - Final endpoint of the range - * @param {number} b1 - First endpoint of the range - * @param {number} b2 - Final endpoint of the range - * @return {number} - */ + * Linear mapping from range to range + * + * @method Phaser.Math#mapLinear + * @param {number} x - The value to map + * @param {number} a1 - First endpoint of the range + * @param {number} a2 - Final endpoint of the range + * @param {number} b1 - First endpoint of the range + * @param {number} b2 - Final endpoint of the range + * @return {number} + */ mapLinear: function (x, a1, a2, b1, b2) { - return b1 + (x - a1) * (b2 - b1) / (a2 - a1); - }, /** - * Smoothstep function as detailed at http://en.wikipedia.org/wiki/Smoothstep - * - * @method Phaser.Math#smoothstep - * @param {float} x - The input value. - * @param {float} min - The left edge. Should be smaller than the right edge. - * @param {float} max - The right edge. - * @return {float} A value between 0 and 1. - */ + * Smoothstep function as detailed at http://en.wikipedia.org/wiki/Smoothstep + * + * @method Phaser.Math#smoothstep + * @param {float} x - The input value. + * @param {float} min - The left edge. Should be smaller than the right edge. + * @param {float} max - The right edge. + * @return {float} A value between 0 and 1. + */ smoothstep: function (x, min, max) { - // Scale, bias and saturate x to 0..1 range x = Math.max(0, Math.min(1, (x - min) / (max - min))); // Evaluate polynomial return x * x * (3 - 2 * x); - }, /** - * Smootherstep function as detailed at http://en.wikipedia.org/wiki/Smoothstep - * - * @method Phaser.Math#smootherstep - * @param {float} x - The input value. - * @param {float} min - The left edge. Should be smaller than the right edge. - * @param {float} max - The right edge. - * @return {float} A value between 0 and 1. - */ + * Smootherstep function as detailed at http://en.wikipedia.org/wiki/Smoothstep + * + * @method Phaser.Math#smootherstep + * @param {float} x - The input value. + * @param {float} min - The left edge. Should be smaller than the right edge. + * @param {float} max - The right edge. + * @return {float} A value between 0 and 1. + */ smootherstep: function (x, min, max) { - x = Math.max(0, Math.min(1, (x - min) / (max - min))); return x * x * x * (x * (x * 6 - 15) + 10); - }, /** - * A value representing the sign of the value: -1 for negative, +1 for positive, 0 if value is 0. - * - * This works differently from `Math.sign` for values of NaN and -0, etc. - * - * @method Phaser.Math#sign - * @param {number} x - * @return {integer} An integer in {-1, 0, 1} - */ + * A value representing the sign of the value: -1 for negative, +1 for positive, 0 if value is 0. + * + * This works differently from `Math.sign` for values of NaN and -0, etc. + * + * @method Phaser.Math#sign + * @param {number} x + * @return {integer} An integer in {-1, 0, 1} + */ sign: function (x) { - return (x < 0) ? -1 : ((x > 0) ? 1 : 0); - }, /** - * Work out what percentage value `a` is of value `b` using the given base. - * - * @method Phaser.Math#percent - * @param {number} a - The value to work out the percentage for. - * @param {number} b - The value you wish to get the percentage of. - * @param {number} [base=0] - The base value. - * @return {number} The percentage a is of b, between 0 and 1. - */ + * Work out what percentage value `a` is of value `b` using the given base. + * + * @method Phaser.Math#percent + * @param {number} a - The value to work out the percentage for. + * @param {number} b - The value you wish to get the percentage of. + * @param {number} [base=0] - The base value. + * @return {number} The percentage a is of b, between 0 and 1. + */ percent: function (a, b, base) { - if (base === undefined) { base = 0; } if (a > b || base > b) @@ -1413,7 +1290,6 @@ Phaser.Math = { { return (a - base) / b; } - } }; diff --git a/src/math/QuadTree.js b/src/math/QuadTree.js index b2b54583c..6f3c50b7c 100644 --- a/src/math/QuadTree.js +++ b/src/math/QuadTree.js @@ -6,82 +6,79 @@ */ /** -* A QuadTree implementation. The original code was a conversion of the Java code posted to GameDevTuts. -* However I've tweaked it massively to add node indexing, removed lots of temp. var creation and significantly increased performance as a result. -* Original version at https://github.com/timohausmann/quadtree-js/ -* -* @class Phaser.QuadTree -* @constructor -* @param {number} x - The top left coordinate of the quadtree. -* @param {number} y - The top left coordinate of the quadtree. -* @param {number} width - The width of the quadtree in pixels. -* @param {number} height - The height of the quadtree in pixels. -* @param {number} [maxObjects=10] - The maximum number of objects per node. -* @param {number} [maxLevels=4] - The maximum number of levels to iterate to. -* @param {number} [level=0] - Which level is this? -*/ + * A QuadTree implementation. The original code was a conversion of the Java code posted to GameDevTuts. + * However I've tweaked it massively to add node indexing, removed lots of temp. var creation and significantly increased performance as a result. + * Original version at https://github.com/timohausmann/quadtree-js/ + * + * @class Phaser.QuadTree + * @constructor + * @param {number} x - The top left coordinate of the quadtree. + * @param {number} y - The top left coordinate of the quadtree. + * @param {number} width - The width of the quadtree in pixels. + * @param {number} height - The height of the quadtree in pixels. + * @param {number} [maxObjects=10] - The maximum number of objects per node. + * @param {number} [maxLevels=4] - The maximum number of levels to iterate to. + * @param {number} [level=0] - Which level is this? + */ Phaser.QuadTree = function (x, y, width, height, maxObjects, maxLevels, level) { - /** - * @property {number} maxObjects - The maximum number of objects per node. - * @default - */ + * @property {number} maxObjects - The maximum number of objects per node. + * @default + */ this.maxObjects = 10; /** - * @property {number} maxLevels - The maximum number of levels to break down to. - * @default - */ + * @property {number} maxLevels - The maximum number of levels to break down to. + * @default + */ this.maxLevels = 4; /** - * @property {number} level - The current level. - */ + * @property {number} level - The current level. + */ this.level = 0; /** - * @property {object} bounds - Object that contains the quadtree bounds. - */ + * @property {object} bounds - Object that contains the quadtree bounds. + */ this.bounds = {}; /** - * @property {array} objects - Array of quadtree children. - */ + * @property {array} objects - Array of quadtree children. + */ this.objects = []; /** - * @property {array} nodes - Array of associated child nodes. - */ + * @property {array} nodes - Array of associated child nodes. + */ this.nodes = []; /** - * @property {array} _empty - Internal empty array. - * @private - */ + * @property {array} _empty - Internal empty array. + * @private + */ this._empty = []; this.reset(x, y, width, height, maxObjects, maxLevels, level); - }; Phaser.QuadTree.prototype = { /** - * Resets the QuadTree. - * - * @method Phaser.QuadTree#reset - * @param {number} x - The top left coordinate of the quadtree. - * @param {number} y - The top left coordinate of the quadtree. - * @param {number} width - The width of the quadtree in pixels. - * @param {number} height - The height of the quadtree in pixels. - * @param {number} [maxObjects=10] - The maximum number of objects per node. - * @param {number} [maxLevels=4] - The maximum number of levels to iterate to. - * @param {number} [level=0] - Which level is this? - */ + * Resets the QuadTree. + * + * @method Phaser.QuadTree#reset + * @param {number} x - The top left coordinate of the quadtree. + * @param {number} y - The top left coordinate of the quadtree. + * @param {number} width - The width of the quadtree in pixels. + * @param {number} height - The height of the quadtree in pixels. + * @param {number} [maxObjects=10] - The maximum number of objects per node. + * @param {number} [maxLevels=4] - The maximum number of levels to iterate to. + * @param {number} [level=0] - Which level is this? + */ reset: function (x, y, width, height, maxObjects, maxLevels, level) { - this.maxObjects = maxObjects || 10; this.maxLevels = maxLevels || 4; this.level = level || 0; @@ -99,46 +96,40 @@ Phaser.QuadTree.prototype = { this.objects.length = 0; this.nodes.length = 0; - }, /** - * Populates this quadtree with the children of the given Group. In order to be added the child must exist and have a body property. - * - * @method Phaser.QuadTree#populate - * @param {Phaser.Group} group - The Group to add to the quadtree. - */ + * Populates this quadtree with the children of the given Group. In order to be added the child must exist and have a body property. + * + * @method Phaser.QuadTree#populate + * @param {Phaser.Group} group - The Group to add to the quadtree. + */ populate: function (group) { - group.forEach(this.populateHandler, this, true); - }, /** - * Handler for the populate method. - * - * @method Phaser.QuadTree#populateHandler - * @param {Phaser.Sprite|object} sprite - The Sprite to check. - */ + * Handler for the populate method. + * + * @method Phaser.QuadTree#populateHandler + * @param {Phaser.Sprite|object} sprite - The Sprite to check. + */ populateHandler: function (sprite) { - if (sprite.body && sprite.exists) { this.insert(sprite.body); } - }, /** - * Split the node into 4 subnodes - * - * @method Phaser.QuadTree#split - */ + * Split the node into 4 subnodes + * + * @method Phaser.QuadTree#split + */ split: function () { - // top right node this.nodes[0] = new Phaser.QuadTree(this.bounds.right, this.bounds.y, this.bounds.subWidth, this.bounds.subHeight, this.maxObjects, this.maxLevels, (this.level + 1)); @@ -150,18 +141,16 @@ Phaser.QuadTree.prototype = { // bottom right node this.nodes[3] = new Phaser.QuadTree(this.bounds.right, this.bounds.bottom, this.bounds.subWidth, this.bounds.subHeight, this.maxObjects, this.maxLevels, (this.level + 1)); - }, /** - * Insert the object into the node. If the node exceeds the capacity, it will split and add all objects to their corresponding subnodes. - * - * @method Phaser.QuadTree#insert - * @param {Phaser.Physics.Arcade.Body|object} body - The Body object to insert into the quadtree. Can be any object so long as it exposes x, y, right and bottom properties. - */ + * Insert the object into the node. If the node exceeds the capacity, it will split and add all objects to their corresponding subnodes. + * + * @method Phaser.QuadTree#insert + * @param {Phaser.Physics.Arcade.Body|object} body - The Body object to insert into the quadtree. Can be any object so long as it exposes x, y, right and bottom properties. + */ insert: function (body) { - var i = 0; var index; @@ -203,19 +192,17 @@ Phaser.QuadTree.prototype = { } } } - }, /** - * Determine which node the object belongs to. - * - * @method Phaser.QuadTree#getIndex - * @param {Phaser.Rectangle|object} rect - The bounds in which to check. - * @return {number} index - Index of the subnode (0-3), or -1 if rect cannot completely fit within a subnode and is part of the parent node. - */ + * Determine which node the object belongs to. + * + * @method Phaser.QuadTree#getIndex + * @param {Phaser.Rectangle|object} rect - The bounds in which to check. + * @return {number} index - Index of the subnode (0-3), or -1 if rect cannot completely fit within a subnode and is part of the parent node. + */ getIndex: function (rect) { - // default is that rect doesn't fit, i.e. it straddles the internal quadrants var index = -1; @@ -248,19 +235,17 @@ Phaser.QuadTree.prototype = { } return index; - }, /** - * Return all objects that could collide with the given Sprite or Rectangle. - * - * @method Phaser.QuadTree#retrieve - * @param {Phaser.Sprite|Phaser.Rectangle} source - The source object to check the QuadTree against. Either a Sprite or Rectangle. - * @return {array} - Array with all detected objects. - */ + * Return all objects that could collide with the given Sprite or Rectangle. + * + * @method Phaser.QuadTree#retrieve + * @param {Phaser.Sprite|Phaser.Rectangle} source - The source object to check the QuadTree against. Either a Sprite or Rectangle. + * @return {array} - Array with all detected objects. + */ retrieve: function (source) { - if (source instanceof Phaser.Rectangle) { var returnObjects = this.objects; @@ -297,16 +282,14 @@ Phaser.QuadTree.prototype = { } return returnObjects; - }, /** - * Clear the quadtree. - * @method Phaser.QuadTree#clear - */ + * Clear the quadtree. + * @method Phaser.QuadTree#clear + */ clear: function () { - this.objects.length = 0; var i = this.nodes.length; @@ -325,37 +308,37 @@ Phaser.QuadTree.prototype = { Phaser.QuadTree.prototype.constructor = Phaser.QuadTree; /** -* Javascript QuadTree -* @version 1.0 -* -* @version 1.3, March 11th 2014 -* @author Richard Davey -* The original code was a conversion of the Java code posted to GameDevTuts. However I've tweaked -* it massively to add node indexing, removed lots of temp. var creation and significantly -* increased performance as a result. -* -* Original version at https://github.com/timohausmann/quadtree-js/ -*/ + * Javascript QuadTree + * @version 1.0 + * + * @version 1.3, March 11th 2014 + * @author Richard Davey + * The original code was a conversion of the Java code posted to GameDevTuts. However I've tweaked + * it massively to add node indexing, removed lots of temp. var creation and significantly + * increased performance as a result. + * + * Original version at https://github.com/timohausmann/quadtree-js/ + */ /** -* @copyright © 2012 Timo Hausmann -* -* Permission is hereby granted, free of charge, to any person obtaining -* a copy of this software and associated documentation files (the -* "Software"), to deal in the Software without restriction, including -* without limitation the rights to use, copy, modify, merge, publish, -* distribute, sublicense, and/or sell copies of the Software, and to -* permit persons to whom the Software is furnished to do so, subject to -* the following conditions: -* -* The above copyright notice and this permission notice shall be -* included in all copies or substantial portions of the Software. -* -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -*/ + * @copyright © 2012 Timo Hausmann + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ diff --git a/src/math/RandomDataGenerator.js b/src/math/RandomDataGenerator.js index 3f8b6a384..1fb68b73a 100644 --- a/src/math/RandomDataGenerator.js +++ b/src/math/RandomDataGenerator.js @@ -1,52 +1,51 @@ /* jshint noempty: false */ /** -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* An extremely useful repeatable random data generator. -* -* Based on Nonsense by Josh Faul https://github.com/jocafa/Nonsense. -* -* The random number genererator is based on the Alea PRNG, but is modified. -* - https://github.com/coverslide/node-alea -* - https://github.com/nquinlan/better-random-numbers-for-javascript-mirror -* - http://baagoe.org/en/wiki/Better_random_numbers_for_javascript (original, perm. 404) -* -* @class Phaser.RandomDataGenerator -* @constructor -* @param {any[]|string} [seeds] - An array of values to use as the seed, or a generator state (from {#state}). -*/ + * An extremely useful repeatable random data generator. + * + * Based on Nonsense by Josh Faul https://github.com/jocafa/Nonsense. + * + * The random number genererator is based on the Alea PRNG, but is modified. + * - https://github.com/coverslide/node-alea + * - https://github.com/nquinlan/better-random-numbers-for-javascript-mirror + * - http://baagoe.org/en/wiki/Better_random_numbers_for_javascript (original, perm. 404) + * + * @class Phaser.RandomDataGenerator + * @constructor + * @param {any[]|string} [seeds] - An array of values to use as the seed, or a generator state (from {#state}). + */ Phaser.RandomDataGenerator = function (seeds) { - if (seeds === undefined) { seeds = []; } /** - * @property {number} c - Internal var. - * @private - */ + * @property {number} c - Internal var. + * @private + */ this.c = 1; /** - * @property {number} s0 - Internal var. - * @private - */ + * @property {number} s0 - Internal var. + * @private + */ this.s0 = 0; /** - * @property {number} s1 - Internal var. - * @private - */ + * @property {number} s1 - Internal var. + * @private + */ this.s1 = 0; /** - * @property {number} s2 - Internal var. - * @private - */ + * @property {number} s2 - Internal var. + * @private + */ this.s2 = 0; if (typeof seeds === 'string') @@ -57,21 +56,19 @@ Phaser.RandomDataGenerator = function (seeds) { this.sow(seeds); } - }; Phaser.RandomDataGenerator.prototype = { /** - * Private random helper. - * - * @method Phaser.RandomDataGenerator#rnd - * @private - * @return {number} - */ + * Private random helper. + * + * @method Phaser.RandomDataGenerator#rnd + * @private + * @return {number} + */ rnd: function () { - var t = 2091639 * this.s0 + this.c * 2.3283064365386963e-10; // 2^-32 this.c = t | 0; @@ -83,16 +80,15 @@ Phaser.RandomDataGenerator.prototype = { }, /** - * Reset the seed of the random data generator. - * - * _Note_: the seed array is only processed up to the first `undefined` (or `null`) value, should such be present. - * - * @method Phaser.RandomDataGenerator#sow - * @param {any[]} seeds - The array of seeds: the `toString()` of each value is used. - */ + * Reset the seed of the random data generator. + * + * _Note_: the seed array is only processed up to the first `undefined` (or `null`) value, should such be present. + * + * @method Phaser.RandomDataGenerator#sow + * @param {any[]} seeds - The array of seeds: the `toString()` of each value is used. + */ sow: function (seeds) { - // Always reset to default seed this.s0 = this.hash(' '); this.s1 = this.hash(this.s0); @@ -116,20 +112,18 @@ Phaser.RandomDataGenerator.prototype = { this.s2 -= this.hash(seed); this.s2 += ~~(this.s2 < 0); } - }, /** - * Internal method that creates a seed hash. - * - * @method Phaser.RandomDataGenerator#hash - * @private - * @param {any} data - * @return {number} hashed value. - */ + * Internal method that creates a seed hash. + * + * @method Phaser.RandomDataGenerator#hash + * @private + * @param {any} data + * @return {number} hashed value. + */ hash: function (data) { - var h, i, n; n = 0xefc8249d; data = data.toString(); @@ -147,116 +141,100 @@ Phaser.RandomDataGenerator.prototype = { } return (n >>> 0) * 2.3283064365386963e-10;// 2^-32 - }, /** - * Returns a random integer between 0 and 2^32. - * - * @method Phaser.RandomDataGenerator#integer - * @return {number} A random integer between 0 and 2^32. - */ + * Returns a random integer between 0 and 2^32. + * + * @method Phaser.RandomDataGenerator#integer + * @return {number} A random integer between 0 and 2^32. + */ integer: function () { - return this.rnd.apply(this) * 0x100000000;// 2^32 - }, /** - * Returns a random real number between 0 and 1. - * - * @method Phaser.RandomDataGenerator#frac - * @return {number} A random real number between 0 and 1. - */ + * Returns a random real number between 0 and 1. + * + * @method Phaser.RandomDataGenerator#frac + * @return {number} A random real number between 0 and 1. + */ frac: function () { - return this.rnd.apply(this) + (this.rnd.apply(this) * 0x200000 | 0) * 1.1102230246251565e-16; // 2^-53 - }, /** - * Returns a random real number between 0 and 2^32. - * - * @method Phaser.RandomDataGenerator#real - * @return {number} A random real number between 0 and 2^32. - */ + * Returns a random real number between 0 and 2^32. + * + * @method Phaser.RandomDataGenerator#real + * @return {number} A random real number between 0 and 2^32. + */ real: function () { - return this.integer() + this.frac(); - }, /** - * Returns a random integer between and including min and max. - * - * @method Phaser.RandomDataGenerator#integerInRange - * @param {number} min - The minimum value in the range. - * @param {number} max - The maximum value in the range. - * @return {number} A random number between min and max. - */ + * Returns a random integer between and including min and max. + * + * @method Phaser.RandomDataGenerator#integerInRange + * @param {number} min - The minimum value in the range. + * @param {number} max - The maximum value in the range. + * @return {number} A random number between min and max. + */ integerInRange: function (min, max) { - return Math.floor(this.realInRange(0, max - min + 1) + min); - }, /** - * Returns a random integer between and including min and max. - * This method is an alias for RandomDataGenerator.integerInRange. - * - * @method Phaser.RandomDataGenerator#between - * @param {number} min - The minimum value in the range. - * @param {number} max - The maximum value in the range. - * @return {number} A random number between min and max. - */ + * Returns a random integer between and including min and max. + * This method is an alias for RandomDataGenerator.integerInRange. + * + * @method Phaser.RandomDataGenerator#between + * @param {number} min - The minimum value in the range. + * @param {number} max - The maximum value in the range. + * @return {number} A random number between min and max. + */ between: function (min, max) { - return this.integerInRange(min, max); - }, /** - * Returns a random real number between min and max. - * - * @method Phaser.RandomDataGenerator#realInRange - * @param {number} min - The minimum value in the range. - * @param {number} max - The maximum value in the range. - * @return {number} A random number between min and max. - */ + * Returns a random real number between min and max. + * + * @method Phaser.RandomDataGenerator#realInRange + * @param {number} min - The minimum value in the range. + * @param {number} max - The maximum value in the range. + * @return {number} A random number between min and max. + */ realInRange: function (min, max) { - return this.frac() * (max - min) + min; - }, /** - * Returns a random real number between -1 and 1. - * - * @method Phaser.RandomDataGenerator#normal - * @return {number} A random real number between -1 and 1. - */ + * Returns a random real number between -1 and 1. + * + * @method Phaser.RandomDataGenerator#normal + * @return {number} A random real number between -1 and 1. + */ normal: function () { - return 1 - 2 * this.frac(); - }, /** - * Returns a valid RFC4122 version4 ID hex string from https://gist.github.com/1308368 - * - * @method Phaser.RandomDataGenerator#uuid - * @return {string} A valid RFC4122 version4 ID hex string - */ + * Returns a valid RFC4122 version4 ID hex string from https://gist.github.com/1308368 + * + * @method Phaser.RandomDataGenerator#uuid + * @return {string} A valid RFC4122 version4 ID hex string + */ uuid: function () { - var a = ''; var b = ''; @@ -264,98 +242,86 @@ Phaser.RandomDataGenerator.prototype = { {} // eslint-disable-line no-empty return b; - }, /** - * Returns a random member of `array`. - * - * @method Phaser.RandomDataGenerator#pick - * @param {Array} ary - An Array to pick a random member of. - * @return {any} A random member of the array. - */ + * Returns a random member of `array`. + * + * @method Phaser.RandomDataGenerator#pick + * @param {Array} ary - An Array to pick a random member of. + * @return {any} A random member of the array. + */ pick: function (ary) { - return ary[this.integerInRange(0, ary.length - 1)]; - }, /** - * Returns a sign to be used with multiplication operator. - * - * @method Phaser.RandomDataGenerator#sign - * @return {number} -1 or +1. - */ + * Returns a sign to be used with multiplication operator. + * + * @method Phaser.RandomDataGenerator#sign + * @return {number} -1 or +1. + */ sign: function () { - return this.pick([ -1, 1 ]); - }, /** - * Returns a random member of `array`, favoring the earlier entries. - * - * @method Phaser.RandomDataGenerator#weightedPick - * @param {Array} ary - An Array to pick a random member of. - * @return {any} A random member of the array. - */ + * Returns a random member of `array`, favoring the earlier entries. + * + * @method Phaser.RandomDataGenerator#weightedPick + * @param {Array} ary - An Array to pick a random member of. + * @return {any} A random member of the array. + */ weightedPick: function (ary) { - return ary[~~(Math.pow(this.frac(), 2) * (ary.length - 1) + 0.5)]; - }, /** - * Returns a random timestamp between min and max, or between the beginning of 2000 and the end of 2020 if min and max aren't specified. - * - * @method Phaser.RandomDataGenerator#timestamp - * @param {number} min - The minimum value in the range. - * @param {number} max - The maximum value in the range. - * @return {number} A random timestamp between min and max. - */ + * Returns a random timestamp between min and max, or between the beginning of 2000 and the end of 2020 if min and max aren't specified. + * + * @method Phaser.RandomDataGenerator#timestamp + * @param {number} min - The minimum value in the range. + * @param {number} max - The maximum value in the range. + * @return {number} A random timestamp between min and max. + */ timestamp: function (min, max) { - return this.realInRange(min || 946684800000, max || 1577862000000); - }, /** - * Returns a random angle between -180 and 180. - * - * @method Phaser.RandomDataGenerator#angle - * @return {number} A random number between -180 and 180. - */ + * Returns a random angle between -180 and 180. + * + * @method Phaser.RandomDataGenerator#angle + * @return {number} A random number between -180 and 180. + */ angle: function () { - return this.integerInRange(-180, 180); - }, /** - * Gets or Sets the state of the generator. This allows you to retain the values - * that the generator is using between games, i.e. in a game save file. - * - * To seed this generator with a previously saved state you can pass it as the - * `seed` value in your game config, or call this method directly after Phaser has booted. - * - * Call this method with no parameters to return the current state. - * - * If providing a state it should match the same format that this method - * returns, which is a string with a header `!rnd` followed by the `c`, - * `s0`, `s1` and `s2` values respectively, each comma-delimited. - * - * @method Phaser.RandomDataGenerator#state - * @param {string} [state] - Generator state to be set. - * @return {string} The current state of the generator. - */ + * Gets or Sets the state of the generator. This allows you to retain the values + * that the generator is using between games, i.e. in a game save file. + * + * To seed this generator with a previously saved state you can pass it as the + * `seed` value in your game config, or call this method directly after Phaser has booted. + * + * Call this method with no parameters to return the current state. + * + * If providing a state it should match the same format that this method + * returns, which is a string with a header `!rnd` followed by the `c`, + * `s0`, `s1` and `s2` values respectively, each comma-delimited. + * + * @method Phaser.RandomDataGenerator#state + * @param {string} [state] - Generator state to be set. + * @return {string} The current state of the generator. + */ state: function (state) { - if (typeof state === 'string' && state.match(/^!rnd/)) { state = state.split(','); @@ -367,7 +333,6 @@ Phaser.RandomDataGenerator.prototype = { } return [ '!rnd', this.c, this.s0, this.s1, this.s2 ].join(','); - } }; diff --git a/src/net/Net.js b/src/net/Net.js index 9cb775767..09ac5f423 100644 --- a/src/net/Net.js +++ b/src/net/Net.js @@ -1,74 +1,69 @@ /** -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* Phaser.Net handles browser URL related tasks such as checking host names, domain names and query string manipulation. -* -* @class Phaser.Net -* @constructor -* @param {Phaser.Game} game - A reference to the currently running game. -*/ + * Phaser.Net handles browser URL related tasks such as checking host names, domain names and query string manipulation. + * + * @class Phaser.Net + * @constructor + * @param {Phaser.Game} game - A reference to the currently running game. + */ Phaser.Net = function (game) { - this.game = game; - }; Phaser.Net.prototype = { /** - * Returns the hostname given by the browser. - * - * @method Phaser.Net#getHostName - * @return {string} - */ + * Returns the hostname given by the browser. + * + * @method Phaser.Net#getHostName + * @return {string} + */ getHostName: function () { - if (window.location && window.location.hostname) { return window.location.hostname; } return null; - }, /** - * Compares the given domain name against the hostname of the browser containing the game. - * If the domain name is found it returns true. - * You can specify a part of a domain, for example 'google' would match 'google.com', 'google.co.uk', etc. - * Do not include 'http://' at the start. - * - * @method Phaser.Net#checkDomainName - * @param {string} domain - * @return {boolean} true if the given domain fragment can be found in the window.location.hostname - */ + * Compares the given domain name against the hostname of the browser containing the game. + * If the domain name is found it returns true. + * You can specify a part of a domain, for example 'google' would match 'google.com', 'google.co.uk', etc. + * Do not include 'http://' at the start. + * + * @method Phaser.Net#checkDomainName + * @param {string} domain + * @return {boolean} true if the given domain fragment can be found in the window.location.hostname + */ checkDomainName: function (domain) { return window.location.hostname.indexOf(domain) !== -1; }, /** - * Updates a value on the Query String and returns it in full. - * If the value doesn't already exist it is set. - * If the value exists it is replaced with the new value given. If you don't provide a new value it is removed from the query string. - * Optionally you can redirect to the new url, or just return it as a string. - * - * @method Phaser.Net#updateQueryString - * @param {string} key - The querystring key to update. - * @param {string} value - The new value to be set. If it already exists it will be replaced. - * @param {boolean} redirect - If true the browser will issue a redirect to the url with the new querystring. - * @param {string} url - The URL to modify. If none is given it uses window.location.href. - * @return {string} If redirect is false then the modified url and query string is returned. - */ + * Updates a value on the Query String and returns it in full. + * If the value doesn't already exist it is set. + * If the value exists it is replaced with the new value given. If you don't provide a new value it is removed from the query string. + * Optionally you can redirect to the new url, or just return it as a string. + * + * @method Phaser.Net#updateQueryString + * @param {string} key - The querystring key to update. + * @param {string} value - The new value to be set. If it already exists it will be replaced. + * @param {boolean} redirect - If true the browser will issue a redirect to the url with the new querystring. + * @param {string} url - The URL to modify. If none is given it uses window.location.href. + * @return {string} If redirect is false then the modified url and query string is returned. + */ updateQueryString: function (key, value, redirect, url) { - if (redirect === undefined) { redirect = false; } if (url === undefined || url === '') { url = window.location.href; } @@ -99,7 +94,6 @@ Phaser.Net.prototype = { } output = url; - } else { @@ -114,20 +108,18 @@ Phaser.Net.prototype = { { return output; } - }, /** - * Returns the Query String as an object. - * If you specify a parameter it will return just the value of that parameter, should it exist. - * - * @method Phaser.Net#getQueryString - * @param {string} [parameter=''] - If specified this will return just the value for that key. - * @return {string|object} An object containing the key value pairs found in the query string or just the value if a parameter was given. - */ + * Returns the Query String as an object. + * If you specify a parameter it will return just the value of that parameter, should it exist. + * + * @method Phaser.Net#getQueryString + * @param {string} [parameter=''] - If specified this will return just the value for that key. + * @return {string|object} An object containing the key value pairs found in the query string or just the value if a parameter was given. + */ getQueryString: function (parameter) { - if (parameter === undefined) { parameter = ''; } var output = {}; @@ -151,17 +143,16 @@ Phaser.Net.prototype = { } return output; - }, /** - * Takes a Uniform Resource Identifier (URI) component (previously created by encodeURIComponent or by a similar routine) and - * decodes it, replacing \ with spaces in the return. Used internally by the Net classes. - * - * @method Phaser.Net#decodeURI - * @param {string} value - The URI component to be decoded. - * @return {string} The decoded value. - */ + * Takes a Uniform Resource Identifier (URI) component (previously created by encodeURIComponent or by a similar routine) and + * decodes it, replacing \ with spaces in the return. Used internally by the Net classes. + * + * @method Phaser.Net#decodeURI + * @param {string} value - The URI component to be decoded. + * @return {string} The decoded value. + */ decodeURI: function (value) { return decodeURIComponent(value.replace(/\+/g, ' ')); diff --git a/src/particles/Particles.js b/src/particles/Particles.js index fc83fdba9..6c756db3c 100644 --- a/src/particles/Particles.js +++ b/src/particles/Particles.js @@ -1,45 +1,43 @@ /** -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* Phaser.Particles tracks any Emitters attached to it. -* -* @class Phaser.Particles -* @constructor -* @param {Phaser.Game} game - A reference to the currently running game. -*/ + * Phaser.Particles tracks any Emitters attached to it. + * + * @class Phaser.Particles + * @constructor + * @param {Phaser.Game} game - A reference to the currently running game. + */ Phaser.Particles = function (game) { - /** - * @property {Phaser.Game} game - A reference to the currently running Game. - */ + * @property {Phaser.Game} game - A reference to the currently running Game. + */ this.game = game; /** - * @property {object} emitters - Internal emitters store. - */ + * @property {object} emitters - Internal emitters store. + */ this.emitters = {}; /** - * @property {number} ID - - * @default - */ + * @property {number} ID - + * @default + */ this.ID = 0; - }; Phaser.Particles.prototype = { /** - * Adds a new Particle Emitter to the Particle Manager. - * @method Phaser.Particles#add - * @param {Phaser.Emitter} emitter - The emitter to be added to the particle manager. - * @return {Phaser.Emitter} The emitter that was added. - */ + * Adds a new Particle Emitter to the Particle Manager. + * @method Phaser.Particles#add + * @param {Phaser.Emitter} emitter - The emitter to be added to the particle manager. + * @return {Phaser.Emitter} The emitter that was added. + */ add: function (emitter) { this.emitters[emitter.id] = emitter; @@ -47,10 +45,10 @@ Phaser.Particles.prototype = { }, /** - * Removes an existing Particle Emitter from the Particle Manager. - * @method Phaser.Particles#remove - * @param {Phaser.Emitter} emitter - The emitter to remove. - */ + * Removes an existing Particle Emitter from the Particle Manager. + * @method Phaser.Particles#remove + * @param {Phaser.Emitter} emitter - The emitter to remove. + */ remove: function (emitter) { delete this.emitters[emitter.id]; diff --git a/src/particles/arcade/ArcadeParticles.js b/src/particles/arcade/ArcadeParticles.js index 876327d92..3b8aa708f 100644 --- a/src/particles/arcade/ArcadeParticles.js +++ b/src/particles/arcade/ArcadeParticles.js @@ -1,12 +1,12 @@ /** -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* Arcade Particles is a Particle System integrated with Arcade Physics. -* -* @class Phaser.Particles.Arcade -*/ + * Arcade Particles is a Particle System integrated with Arcade Physics. + * + * @class Phaser.Particles.Arcade + */ Phaser.Particles.Arcade = {}; diff --git a/src/particles/arcade/Emitter.js b/src/particles/arcade/Emitter.js index dd7fcc8d6..54f7de64f 100644 --- a/src/particles/arcade/Emitter.js +++ b/src/particles/arcade/Emitter.js @@ -1,60 +1,59 @@ /** -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* Emitter is a lightweight particle emitter that uses Arcade Physics. -* It can be used for one-time explosions or for continuous effects like rain and fire. -* All it really does is launch Particle objects out at set intervals, and fixes their positions and velocities accordingly. -* -* @class Phaser.Particles.Arcade.Emitter -* @constructor -* @extends Phaser.Group -* @param {Phaser.Game} game - Current game instance. -* @param {number} [x=0] - The x coordinate within the Emitter that the particles are emitted from. -* @param {number} [y=0] - The y coordinate within the Emitter that the particles are emitted from. -* @param {number} [maxParticles=50] - The total number of particles in this emitter. -*/ + * Emitter is a lightweight particle emitter that uses Arcade Physics. + * It can be used for one-time explosions or for continuous effects like rain and fire. + * All it really does is launch Particle objects out at set intervals, and fixes their positions and velocities accordingly. + * + * @class Phaser.Particles.Arcade.Emitter + * @constructor + * @extends Phaser.Group + * @param {Phaser.Game} game - Current game instance. + * @param {number} [x=0] - The x coordinate within the Emitter that the particles are emitted from. + * @param {number} [y=0] - The y coordinate within the Emitter that the particles are emitted from. + * @param {number} [maxParticles=50] - The total number of particles in this emitter. + */ Phaser.Particles.Arcade.Emitter = function (game, x, y, maxParticles) { - /** - * @property {number} maxParticles - The total number of particles in this emitter. - * @default - */ + * @property {number} maxParticles - The total number of particles in this emitter. + * @default + */ this.maxParticles = maxParticles || 50; Phaser.Group.call(this, game); /** - * @property {number} _id - Internal ID for this emitter -- only used by the Particle System in most cases - * @private - */ + * @property {number} _id - Internal ID for this emitter -- only used by the Particle System in most cases + * @private + */ this._id = this.game.particles.ID++; /** - * @property {string} name - A handy string name for this emitter. Can be set to anything. - */ + * @property {string} name - A handy string name for this emitter. Can be set to anything. + */ this.name = 'emitter' + this.id; /** - * @property {number} type - Internal Phaser Type value. - * @protected - */ + * @property {number} type - Internal Phaser Type value. + * @protected + */ this.type = Phaser.EMITTER; /** - * @property {number} physicsType - The const physics body type of this object. - * @readonly - */ + * @property {number} physicsType - The const physics body type of this object. + * @readonly + */ this.physicsType = Phaser.GROUP; /** - * @property {Phaser.Rectangle} area - The {@link #setSize size} of the emitter's emit area. The **actual** emit area is a rectangle of this size centered on (emitX, emitY): `{x: this.left, y: this.top, width: this.area.width, height: this.area.height}`. Particles are generated at a random position within this area. - * @default - */ + * @property {Phaser.Rectangle} area - The {@link #setSize size} of the emitter's emit area. The **actual** emit area is a rectangle of this size centered on (emitX, emitY): `{x: this.left, y: this.top, width: this.area.width, height: this.area.height}`. Particles are generated at a random position within this area. + * @default + */ this.area = new Phaser.Rectangle(x, y, 1, 1); /** @@ -82,160 +81,160 @@ Phaser.Particles.Arcade.Emitter = function (game, x, y, maxParticles) this.maxSpeed = 100; /** - * @property {Phaser.Point} minParticleSpeed - The minimum possible velocity of a particle. - * @default - */ + * @property {Phaser.Point} minParticleSpeed - The minimum possible velocity of a particle. + * @default + */ this.minParticleSpeed = new Phaser.Point(-100, -100); /** - * @property {Phaser.Point} maxParticleSpeed - The maximum possible velocity of a particle. - * @default - */ + * @property {Phaser.Point} maxParticleSpeed - The maximum possible velocity of a particle. + * @default + */ this.maxParticleSpeed = new Phaser.Point(100, 100); /** - * @property {number} minParticleScale - The minimum possible scale of a particle. This is applied to the X and Y axis. If you need to control each axis see minParticleScaleX. - * @default - */ + * @property {number} minParticleScale - The minimum possible scale of a particle. This is applied to the X and Y axis. If you need to control each axis see minParticleScaleX. + * @default + */ this.minParticleScale = 1; /** - * @property {number} maxParticleScale - The maximum possible scale of a particle. This is applied to the X and Y axis. If you need to control each axis see maxParticleScaleX. - * @default - */ + * @property {number} maxParticleScale - The maximum possible scale of a particle. This is applied to the X and Y axis. If you need to control each axis see maxParticleScaleX. + * @default + */ this.maxParticleScale = 1; /** - * @property {array} scaleData - An array of the calculated scale easing data applied to particles with scaleRates > 0. - */ + * @property {array} scaleData - An array of the calculated scale easing data applied to particles with scaleRates > 0. + */ this.scaleData = null; /** - * @property {number} minRotation - The minimum possible angular velocity of a particle. - * @default - */ + * @property {number} minRotation - The minimum possible angular velocity of a particle. + * @default + */ this.minRotation = -360; /** - * @property {number} maxRotation - The maximum possible angular velocity of a particle. - * @default - */ + * @property {number} maxRotation - The maximum possible angular velocity of a particle. + * @default + */ this.maxRotation = 360; /** - * @property {number} minParticleAlpha - The minimum possible alpha value of a particle. - * @default - */ + * @property {number} minParticleAlpha - The minimum possible alpha value of a particle. + * @default + */ this.minParticleAlpha = 1; /** - * @property {number} maxParticleAlpha - The maximum possible alpha value of a particle. - * @default - */ + * @property {number} maxParticleAlpha - The maximum possible alpha value of a particle. + * @default + */ this.maxParticleAlpha = 1; /** - * @property {array} alphaData - An array of the calculated alpha easing data applied to particles with alphaRates > 0. - */ + * @property {array} alphaData - An array of the calculated alpha easing data applied to particles with alphaRates > 0. + */ this.alphaData = null; /** - * @property {function} particleClass - For emitting your own particle class types. They must extend Phaser.Particle. - * @default - */ + * @property {function} particleClass - For emitting your own particle class types. They must extend Phaser.Particle. + * @default + */ this.particleClass = Phaser.Particle; /** - * @property {Phaser.Point} particleDrag - The X and Y drag component of particles launched from the emitter. - */ + * @property {Phaser.Point} particleDrag - The X and Y drag component of particles launched from the emitter. + */ this.particleDrag = new Phaser.Point(); /** - * @property {number} angularDrag - The angular drag component of particles launched from the emitter if they are rotating. - * @default - */ + * @property {number} angularDrag - The angular drag component of particles launched from the emitter if they are rotating. + * @default + */ this.angularDrag = 0; /** - * @property {number} frequency - How often a particle is emitted in ms (if emitter is started with Explode === false). - * @default - */ + * @property {number} frequency - How often a particle is emitted in ms (if emitter is started with Explode === false). + * @default + */ this.frequency = 100; /** - * @property {number} lifespan - How long each particle lives once it is emitted in ms. Default is 2 seconds. Set lifespan to 'zero' for particles to live forever. - * @default - */ + * @property {number} lifespan - How long each particle lives once it is emitted in ms. Default is 2 seconds. Set lifespan to 'zero' for particles to live forever. + * @default + */ this.lifespan = 2000; /** - * @property {Phaser.Point} bounce - How much each particle should bounce on each axis. 1 = full bounce, 0 = no bounce. - */ + * @property {Phaser.Point} bounce - How much each particle should bounce on each axis. 1 = full bounce, 0 = no bounce. + */ this.bounce = new Phaser.Point(); /** - * @property {boolean} on - Determines whether the emitter is currently emitting particles. It is totally safe to directly toggle this. - * @default - */ + * @property {boolean} on - Determines whether the emitter is currently emitting particles. It is totally safe to directly toggle this. + * @default + */ this.on = false; /** - * @property {Phaser.Point} particleAnchor - When a particle is created its anchor will be set to match this Point object (defaults to x/y: 0.5 to aid in rotation) - * @default - */ + * @property {Phaser.Point} particleAnchor - When a particle is created its anchor will be set to match this Point object (defaults to x/y: 0.5 to aid in rotation) + * @default + */ this.particleAnchor = new Phaser.Point(0.5, 0.5); /** - * @property {number} blendMode - The blendMode as set on the particle when emitted from the Emitter. Defaults to NORMAL. Needs browser capable of supporting canvas blend-modes (most not available in WebGL) - * @default - */ + * @property {number} blendMode - The blendMode as set on the particle when emitted from the Emitter. Defaults to NORMAL. Needs browser capable of supporting canvas blend-modes (most not available in WebGL) + * @default + */ this.blendMode = Phaser.blendModes.NORMAL; /** - * The point the particles are emitted from. - * Emitter.x and Emitter.y control the containers location, which updates all current particles - * Emitter.emitX and Emitter.emitY control the emission location relative to the x/y position. - * @property {number} emitX - */ + * The point the particles are emitted from. + * Emitter.x and Emitter.y control the containers location, which updates all current particles + * Emitter.emitX and Emitter.emitY control the emission location relative to the x/y position. + * @property {number} emitX + */ this.emitX = x; /** - * The point the particles are emitted from. - * Emitter.x and Emitter.y control the containers location, which updates all current particles - * Emitter.emitX and Emitter.emitY control the emission location relative to the x/y position. - * @property {number} emitY - */ + * The point the particles are emitted from. + * Emitter.x and Emitter.y control the containers location, which updates all current particles + * Emitter.emitX and Emitter.emitY control the emission location relative to the x/y position. + * @property {number} emitY + */ this.emitY = y; /** - * @property {boolean} autoScale - When a new Particle is emitted this controls if it will automatically scale in size. Use Emitter.setScale to configure. - */ + * @property {boolean} autoScale - When a new Particle is emitted this controls if it will automatically scale in size. Use Emitter.setScale to configure. + */ this.autoScale = false; /** - * @property {boolean} autoAlpha - When a new Particle is emitted this controls if it will automatically change alpha. Use Emitter.setAlpha to configure. - */ + * @property {boolean} autoAlpha - When a new Particle is emitted this controls if it will automatically change alpha. Use Emitter.setAlpha to configure. + */ this.autoAlpha = false; /** - * @property {boolean} particleBringToTop - If this is `true` then when the Particle is emitted it will be bought to the top of the Emitters display list. - * @default - */ + * @property {boolean} particleBringToTop - If this is `true` then when the Particle is emitted it will be bought to the top of the Emitters display list. + * @default + */ this.particleBringToTop = false; /** - * @property {boolean} particleSendToBack - If this is `true` then when the Particle is emitted it will be sent to the back of the Emitters display list. - * @default - */ + * @property {boolean} particleSendToBack - If this is `true` then when the Particle is emitted it will be sent to the back of the Emitters display list. + * @default + */ this.particleSendToBack = false; /** - * @property {object} counts - Records emitter activity. - * @property {number} counts.emitted - How many particles were emitted during the last update. - * @property {number} counts.failed - How many particles could not be emitted during the last update (because no particles were available). - * @property {number} counts.totalEmitted - How many particles have been emitted. - * @property {number} counts.totalFailed - How many particles could not be emitted when they were due (because no particles were available). - */ + * @property {object} counts - Records emitter activity. + * @property {number} counts.emitted - How many particles were emitted during the last update. + * @property {number} counts.failed - How many particles could not be emitted during the last update (because no particles were available). + * @property {number} counts.totalEmitted - How many particles have been emitted. + * @property {number} counts.totalFailed - How many particles could not be emitted when they were due (because no particles were available). + */ this.counts = { emitted: 0, failed: 0, @@ -244,78 +243,76 @@ Phaser.Particles.Arcade.Emitter = function (game, x, y, maxParticles) }; /** - * @property {Phaser.Point} _gravity - Internal gravity value. - * @private - */ + * @property {Phaser.Point} _gravity - Internal gravity value. + * @private + */ this._gravity = new Phaser.Point(0, 100); /** - * @property {Phaser.Point} _minParticleScale - Internal particle scale var. - * @private - */ + * @property {Phaser.Point} _minParticleScale - Internal particle scale var. + * @private + */ this._minParticleScale = new Phaser.Point(1, 1); /** - * @property {Phaser.Point} _maxParticleScale - Internal particle scale var. - * @private - */ + * @property {Phaser.Point} _maxParticleScale - Internal particle scale var. + * @private + */ this._maxParticleScale = new Phaser.Point(1, 1); /** - * @property {number} _total - Internal helper for deciding how many particles to launch (via {@link #start}). - * @private - */ + * @property {number} _total - Internal helper for deciding how many particles to launch (via {@link #start}). + * @private + */ this._total = 0; /** - * @property {number} _timer - Internal helper for deciding when to launch particles or kill them. - * @private - */ + * @property {number} _timer - Internal helper for deciding when to launch particles or kill them. + * @private + */ this._timer = 0; /** - * @property {number} _counter - Internal counter for figuring out how many particles to launch. - * @private - */ + * @property {number} _counter - Internal counter for figuring out how many particles to launch. + * @private + */ this._counter = 0; /** - * @property {number} _flowQuantity - Internal counter for figuring out how many particles to launch per flow update. - * @private - */ + * @property {number} _flowQuantity - Internal counter for figuring out how many particles to launch per flow update. + * @private + */ this._flowQuantity = 0; /** - * @property {number} _flowTotal - Internal counter for figuring out how many particles to launch in total (via {@link #flow}). - * @private - */ + * @property {number} _flowTotal - Internal counter for figuring out how many particles to launch in total (via {@link #flow}). + * @private + */ this._flowTotal = 0; /** - * @property {boolean} _explode - Internal helper for the style of particle emission (all at once, or one at a time). - * @private - */ + * @property {boolean} _explode - Internal helper for the style of particle emission (all at once, or one at a time). + * @private + */ this._explode = true; /** - * @property {any} _frames - Internal helper for the particle frame. - * @private - */ + * @property {any} _frames - Internal helper for the particle frame. + * @private + */ this._frames = null; - }; Phaser.Particles.Arcade.Emitter.prototype = Object.create(Phaser.Group.prototype); Phaser.Particles.Arcade.Emitter.prototype.constructor = Phaser.Particles.Arcade.Emitter; /** -* Called automatically by the game loop, decides when to launch particles and when to "die". -* -* @method Phaser.Particles.Arcade.Emitter#update -*/ + * Called automatically by the game loop, decides when to launch particles and when to "die". + * + * @method Phaser.Particles.Arcade.Emitter#update + */ Phaser.Particles.Arcade.Emitter.prototype.update = function () { - this.counts.emitted = 0; this.counts.failed = 0; @@ -362,7 +359,6 @@ Phaser.Particles.Arcade.Emitter.prototype.update = function () this.on = false; } } - } var i = this.children.length; @@ -374,25 +370,23 @@ Phaser.Particles.Arcade.Emitter.prototype.update = function () this.children[i].update(); } } - }; /** -* This function generates a new set of particles for use by this emitter. -* The particles are stored internally waiting to be emitted via Emitter.start. -* -* @method Phaser.Particles.Arcade.Emitter#makeParticles -* @param {array|string} keys - A string or an array of strings that the particle sprites will use as their texture. If an array one is picked at random. -* @param {array|number} [frames=0] - A frame number, or array of frames that the sprite will use. If an array one is picked at random. -* @param {number} [quantity] - The number of particles to generate. If not given it will use the value of Emitter.maxParticles. If the value is greater than Emitter.maxParticles it will use Emitter.maxParticles as the quantity. -* @param {boolean} [collide=false] - If you want the particles to be able to collide with other Arcade Physics bodies then set this to true. -* @param {boolean} [collideWorldBounds=false] - A particle can be set to collide against the World bounds automatically and rebound back into the World if this is set to true. Otherwise it will leave the World. -* @param {object} [particleArguments=null] - Custom arguments to pass to your particle class -* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. -*/ + * This function generates a new set of particles for use by this emitter. + * The particles are stored internally waiting to be emitted via Emitter.start. + * + * @method Phaser.Particles.Arcade.Emitter#makeParticles + * @param {array|string} keys - A string or an array of strings that the particle sprites will use as their texture. If an array one is picked at random. + * @param {array|number} [frames=0] - A frame number, or array of frames that the sprite will use. If an array one is picked at random. + * @param {number} [quantity] - The number of particles to generate. If not given it will use the value of Emitter.maxParticles. If the value is greater than Emitter.maxParticles it will use Emitter.maxParticles as the quantity. + * @param {boolean} [collide=false] - If you want the particles to be able to collide with other Arcade Physics bodies then set this to true. + * @param {boolean} [collideWorldBounds=false] - A particle can be set to collide against the World bounds automatically and rebound back into the World if this is set to true. Otherwise it will leave the World. + * @param {object} [particleArguments=null] - Custom arguments to pass to your particle class + * @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. + */ Phaser.Particles.Arcade.Emitter.prototype.makeParticles = function (keys, frames, quantity, collide, collideWorldBounds, particleArguments) { - if (frames === undefined) { frames = 0; } if (quantity === undefined) { quantity = this.maxParticles; } if (collide === undefined) { collide = false; } @@ -440,53 +434,47 @@ Phaser.Particles.Arcade.Emitter.prototype.makeParticles = function (keys, frames } return this; - }; /** -* Call this function to turn off all the particles and the emitter. -* -* @method Phaser.Particles.Arcade.Emitter#kill -* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. -*/ + * Call this function to turn off all the particles and the emitter. + * + * @method Phaser.Particles.Arcade.Emitter#kill + * @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. + */ Phaser.Particles.Arcade.Emitter.prototype.kill = function () { - this.on = false; this.alive = false; this.exists = false; return this; - }; /** -* Handy for bringing game objects "back to life". Just sets alive and exists back to true. -* -* @method Phaser.Particles.Arcade.Emitter#revive -* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. -*/ + * Handy for bringing game objects "back to life". Just sets alive and exists back to true. + * + * @method Phaser.Particles.Arcade.Emitter#revive + * @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. + */ Phaser.Particles.Arcade.Emitter.prototype.revive = function () { - this.alive = true; this.exists = true; return this; - }; /** -* Call this function to emit the given quantity of particles at all once (an explosion) -* -* @method Phaser.Particles.Arcade.Emitter#explode -* @param {number} [lifespan=0] - How long each particle lives once emitted in ms. 0 = forever. -* @param {number} [quantity=this.maxParticles] - How many particles to launch. -* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. -*/ + * Call this function to emit the given quantity of particles at all once (an explosion) + * + * @method Phaser.Particles.Arcade.Emitter#explode + * @param {number} [lifespan=0] - How long each particle lives once emitted in ms. 0 = forever. + * @param {number} [quantity=this.maxParticles] - How many particles to launch. + * @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. + */ Phaser.Particles.Arcade.Emitter.prototype.explode = function (lifespan, quantity) { - if (quantity === undefined) { quantity = this.maxParticles; @@ -497,30 +485,28 @@ Phaser.Particles.Arcade.Emitter.prototype.explode = function (lifespan, quantity this.start(true, lifespan, 0, quantity, false); return this; - }; /** -* Call this function to start emitting a flow of particles. -* `quantity` particles are released every interval of `frequency` ms until `total` particles have been released (or forever). -* If you set the total to be 20 and quantity to be 5 then flow will emit 4 times in total (4 × 5 = 20 total) and then turn {@link #on off}. -* If you set the total to be -1 then no quantity cap is used and it will keep emitting (as long as there are inactive particles available). -* -* {@link #output}, {@link #lifespanOutput}, and {@link #remainder} describe the particle flow rate. -* During a stable flow, the number of active particles approaches {@link #lifespanOutput} and the number of inactive particles approaches {@link #remainder}. -* If {@link #remainder} is less than 0, there will likely be no particles available for a portion of the flow (see {@link #count}). -* -* @method Phaser.Particles.Arcade.Emitter#flow -* @param {number} [lifespan=0] - How long each particle lives once emitted in ms. 0 = forever. -* @param {number} [frequency=250] - The interval between each release of particles, given in ms. Values between 0 and 16.66 will behave the same (60 releases per second). -* @param {number} [quantity=1] - How many particles to launch at each interval. Not larger than {@link #maxParticles}. -* @param {number} [total=-1] - Turn {@link #on off} after launching this many particles in total. If -1 it will carry on indefinitely. -* @param {boolean} [immediate=true] - Should the flow start immediately (true) or wait until the first frequency event? (false) -* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. -*/ + * Call this function to start emitting a flow of particles. + * `quantity` particles are released every interval of `frequency` ms until `total` particles have been released (or forever). + * If you set the total to be 20 and quantity to be 5 then flow will emit 4 times in total (4 × 5 = 20 total) and then turn {@link #on off}. + * If you set the total to be -1 then no quantity cap is used and it will keep emitting (as long as there are inactive particles available). + * + * {@link #output}, {@link #lifespanOutput}, and {@link #remainder} describe the particle flow rate. + * During a stable flow, the number of active particles approaches {@link #lifespanOutput} and the number of inactive particles approaches {@link #remainder}. + * If {@link #remainder} is less than 0, there will likely be no particles available for a portion of the flow (see {@link #count}). + * + * @method Phaser.Particles.Arcade.Emitter#flow + * @param {number} [lifespan=0] - How long each particle lives once emitted in ms. 0 = forever. + * @param {number} [frequency=250] - The interval between each release of particles, given in ms. Values between 0 and 16.66 will behave the same (60 releases per second). + * @param {number} [quantity=1] - How many particles to launch at each interval. Not larger than {@link #maxParticles}. + * @param {number} [total=-1] - Turn {@link #on off} after launching this many particles in total. If -1 it will carry on indefinitely. + * @param {boolean} [immediate=true] - Should the flow start immediately (true) or wait until the first frequency event? (false) + * @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. + */ Phaser.Particles.Arcade.Emitter.prototype.flow = function (lifespan, frequency, quantity, total, immediate) { - if (frequency === undefined || frequency === null) { frequency = 250; } if (quantity === undefined || quantity === 0) { quantity = 1; } if (total === undefined) { total = -1; } @@ -549,41 +535,39 @@ Phaser.Particles.Arcade.Emitter.prototype.flow = function (lifespan, frequency, } return this; - }; /** -* Start emitting particles. -* -* {@link #explode} and {@link #flow} are simpler methods. -* -* There are two patterns, based on the `explode` argument: -* -* ##### explode=true -* -* start(true, lifespan=0, null, total) -* -* When `explode` is true or `forceQuantity` is true, `start` emits `total` particles immediately. You should pass a nonzero `total`. -* -* ##### explode=false -* -* start(false, lifespan=0, frequency=250, total=0) -* -* When `explode` is false and `forceQuantity` is false, `start` emits 1 particle every interval of `frequency` ms. If `total` is not zero, the emitter turns itself off after `total` particles have been released. If `total` is zero, the emitter keeps emitting particles as long as they are available. To emit more than 1 particle per flow interval, use {@link #flow} instead. -* -* `forceQuantity` seems equivalent to `explode` and can probably be avoided. -* -* @method Phaser.Particles.Arcade.Emitter#start -* @param {boolean} [explode=true] - Whether the particles should all burst out at once (true) or at the frequency given (false). -* @param {number} [lifespan=0] - How long each particle lives once emitted in ms. 0 = forever. -* @param {number} [frequency=250] - The interval between each release of 1 particle, when `explode` is false. Value given in ms. Ignored if `explode` is set to true. -* @param {number} [total=0] - Turn {@link #on off} after launching this many particles in total. -* @param {number} [forceQuantity=false] - Equivalent to `explodes`. -* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. -*/ + * Start emitting particles. + * + * {@link #explode} and {@link #flow} are simpler methods. + * + * There are two patterns, based on the `explode` argument: + * + * ##### explode=true + * + * start(true, lifespan=0, null, total) + * + * When `explode` is true or `forceQuantity` is true, `start` emits `total` particles immediately. You should pass a nonzero `total`. + * + * ##### explode=false + * + * start(false, lifespan=0, frequency=250, total=0) + * + * When `explode` is false and `forceQuantity` is false, `start` emits 1 particle every interval of `frequency` ms. If `total` is not zero, the emitter turns itself off after `total` particles have been released. If `total` is zero, the emitter keeps emitting particles as long as they are available. To emit more than 1 particle per flow interval, use {@link #flow} instead. + * + * `forceQuantity` seems equivalent to `explode` and can probably be avoided. + * + * @method Phaser.Particles.Arcade.Emitter#start + * @param {boolean} [explode=true] - Whether the particles should all burst out at once (true) or at the frequency given (false). + * @param {number} [lifespan=0] - How long each particle lives once emitted in ms. 0 = forever. + * @param {number} [frequency=250] - The interval between each release of 1 particle, when `explode` is false. Value given in ms. Ignored if `explode` is set to true. + * @param {number} [total=0] - Turn {@link #on off} after launching this many particles in total. + * @param {number} [forceQuantity=false] - Equivalent to `explodes`. + * @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. + */ Phaser.Particles.Arcade.Emitter.prototype.start = function (explode, lifespan, frequency, total, forceQuantity) { - if (explode === undefined) { explode = true; } if (lifespan === undefined) { lifespan = 0; } if (frequency === undefined || frequency === null) { frequency = 250; } @@ -618,28 +602,26 @@ Phaser.Particles.Arcade.Emitter.prototype.start = function (explode, lifespan, f } return this; - }; /** -* This function is used internally to emit the next particle in the queue. -* -* However it can also be called externally to emit a particle. -* -* When called externally you can use the arguments to override any defaults the Emitter has set. -* -* The newly emitted particle is available in {@link Phaser.Particles.Arcade.Emitter#cursor}. -* -* @method Phaser.Particles.Arcade.Emitter#emitParticle -* @param {number} [x] - The x coordinate to emit the particle from. If `null` or `undefined` it will use `Emitter.emitX` or if the Emitter has a width > 1 a random value between `Emitter.left` and `Emitter.right`. -* @param {number} [y] - The y coordinate to emit the particle from. If `null` or `undefined` it will use `Emitter.emitY` or if the Emitter has a height > 1 a random value between `Emitter.top` and `Emitter.bottom`. -* @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - This is the image or texture used by the Particle during rendering. It can be a string which is a reference to the Cache Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. -* @param {string|number} [frame] - If this Particle is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. -* @return {boolean} True if a particle was emitted, otherwise false. -*/ + * This function is used internally to emit the next particle in the queue. + * + * However it can also be called externally to emit a particle. + * + * When called externally you can use the arguments to override any defaults the Emitter has set. + * + * The newly emitted particle is available in {@link Phaser.Particles.Arcade.Emitter#cursor}. + * + * @method Phaser.Particles.Arcade.Emitter#emitParticle + * @param {number} [x] - The x coordinate to emit the particle from. If `null` or `undefined` it will use `Emitter.emitX` or if the Emitter has a width > 1 a random value between `Emitter.left` and `Emitter.right`. + * @param {number} [y] - The y coordinate to emit the particle from. If `null` or `undefined` it will use `Emitter.emitY` or if the Emitter has a height > 1 a random value between `Emitter.top` and `Emitter.bottom`. + * @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - This is the image or texture used by the Particle during rendering. It can be a string which is a reference to the Cache Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. + * @param {string|number} [frame] - If this Particle is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. + * @return {boolean} True if a particle was emitted, otherwise false. + */ Phaser.Particles.Arcade.Emitter.prototype.emitParticle = function (x, y, key, frame) { - if (x === undefined) { x = null; } if (y === undefined) { y = null; } @@ -692,19 +674,17 @@ Phaser.Particles.Arcade.Emitter.prototype.emitParticle = function (x, y, key, fr this.resetParticle(particle, emitX, emitY); return true; - }; /** -* Helper for {@link #emitParticle}. Gets the next available particle. -* -* @private -* @return {?Phaser.Particle} The first particle with exists=false, or null -*/ + * Helper for {@link #emitParticle}. Gets the next available particle. + * + * @private + * @return {?Phaser.Particle} The first particle with exists=false, or null + */ Phaser.Particles.Arcade.Emitter.prototype.getNextParticle = function () { - var i = this.length; while (i--) @@ -718,7 +698,6 @@ Phaser.Particles.Arcade.Emitter.prototype.getNextParticle = function () } return null; - }; /** @@ -731,7 +710,6 @@ Phaser.Particles.Arcade.Emitter.prototype.getNextParticle = function () */ Phaser.Particles.Arcade.Emitter.prototype.resetParticle = function (particle, x, y) { - var rnd = this.game.rnd; particle.reset(x, y); @@ -802,51 +780,45 @@ Phaser.Particles.Arcade.Emitter.prototype.resetParticle = function (particle, x, body.angularDrag = this.angularDrag; particle.onEmit(); - }; /** -* Destroys this Emitter, all associated child Particles and then removes itself from the Particle Manager. -* -* @method Phaser.Particles.Arcade.Emitter#destroy -*/ + * Destroys this Emitter, all associated child Particles and then removes itself from the Particle Manager. + * + * @method Phaser.Particles.Arcade.Emitter#destroy + */ Phaser.Particles.Arcade.Emitter.prototype.destroy = function () { - this.game.particles.remove(this); Phaser.Group.prototype.destroy.call(this, true, false); - }; /** -* A more compact way of setting the width and height of the emitter. -* -* @method Phaser.Particles.Arcade.Emitter#setSize -* @param {number} width - The desired width of the emitter (particles are spawned randomly within these dimensions). -* @param {number} height - The desired height of the emitter. -* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. -*/ + * A more compact way of setting the width and height of the emitter. + * + * @method Phaser.Particles.Arcade.Emitter#setSize + * @param {number} width - The desired width of the emitter (particles are spawned randomly within these dimensions). + * @param {number} height - The desired height of the emitter. + * @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. + */ Phaser.Particles.Arcade.Emitter.prototype.setSize = function (width, height) { - this.area.width = width; this.area.height = height; return this; - }; /** -* A more compact way of setting the X velocity range of the emitter. -* @method Phaser.Particles.Arcade.Emitter#setXSpeed -* @param {number} [min=0] - The minimum value for this range. -* @param {number} [max=0] - The maximum value for this range. -* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. -*/ + * A more compact way of setting the X velocity range of the emitter. + * @method Phaser.Particles.Arcade.Emitter#setXSpeed + * @param {number} [min=0] - The minimum value for this range. + * @param {number} [max=0] - The maximum value for this range. + * @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. + */ Phaser.Particles.Arcade.Emitter.prototype.setXSpeed = function (min, max) { - min = min || 0; max = max || 0; @@ -854,19 +826,17 @@ Phaser.Particles.Arcade.Emitter.prototype.setXSpeed = function (min, max) this.maxParticleSpeed.x = max; return this; - }; /** -* A more compact way of setting the Y velocity range of the emitter. -* @method Phaser.Particles.Arcade.Emitter#setYSpeed -* @param {number} [min=0] - The minimum value for this range. -* @param {number} [max=0] - The maximum value for this range. -* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. -*/ + * A more compact way of setting the Y velocity range of the emitter. + * @method Phaser.Particles.Arcade.Emitter#setYSpeed + * @param {number} [min=0] - The minimum value for this range. + * @param {number} [max=0] - The maximum value for this range. + * @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. + */ Phaser.Particles.Arcade.Emitter.prototype.setYSpeed = function (min, max) { - min = min || 0; max = max || 0; @@ -874,20 +844,18 @@ Phaser.Particles.Arcade.Emitter.prototype.setYSpeed = function (min, max) this.maxParticleSpeed.y = max; return this; - }; /** -* A more compact way of setting the angular velocity constraints of the particles. -* -* @method Phaser.Particles.Arcade.Emitter#setRotation -* @param {number} [min=0] - The minimum value for this range. -* @param {number} [max=0] - The maximum value for this range. -* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. -*/ + * A more compact way of setting the angular velocity constraints of the particles. + * + * @method Phaser.Particles.Arcade.Emitter#setRotation + * @param {number} [min=0] - The minimum value for this range. + * @param {number} [max=0] - The maximum value for this range. + * @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. + */ Phaser.Particles.Arcade.Emitter.prototype.setRotation = function (min, max) { - min = min || 0; max = max || 0; @@ -895,25 +863,23 @@ Phaser.Particles.Arcade.Emitter.prototype.setRotation = function (min, max) this.maxRotation = max; return this; - }; /** -* A more compact way of setting the alpha constraints of the particles. -* The rate parameter, if set to a value above zero, lets you set the speed at which the Particle change in alpha from min to max. -* If rate is zero, which is the default, the particle won't change alpha - instead it will pick a random alpha between min and max on emit. -* -* @method Phaser.Particles.Arcade.Emitter#setAlpha -* @param {number} [min=1] - The minimum value for this range. -* @param {number} [max=1] - The maximum value for this range. -* @param {number} [rate=0] - The rate (in ms) at which the particles will change in alpha from min to max, or set to zero to pick a random alpha between the two. -* @param {function} [ease=Phaser.Easing.Linear.None] - If you've set a rate > 0 this is the easing formula applied between the min and max values. -* @param {boolean} [yoyo=false] - If you've set a rate > 0 you can set if the ease will yoyo or not (i.e. ease back to its original values) -* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. -*/ + * A more compact way of setting the alpha constraints of the particles. + * The rate parameter, if set to a value above zero, lets you set the speed at which the Particle change in alpha from min to max. + * If rate is zero, which is the default, the particle won't change alpha - instead it will pick a random alpha between min and max on emit. + * + * @method Phaser.Particles.Arcade.Emitter#setAlpha + * @param {number} [min=1] - The minimum value for this range. + * @param {number} [max=1] - The maximum value for this range. + * @param {number} [rate=0] - The rate (in ms) at which the particles will change in alpha from min to max, or set to zero to pick a random alpha between the two. + * @param {function} [ease=Phaser.Easing.Linear.None] - If you've set a rate > 0 this is the easing formula applied between the min and max values. + * @param {boolean} [yoyo=false] - If you've set a rate > 0 you can set if the ease will yoyo or not (i.e. ease back to its original values) + * @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. + */ Phaser.Particles.Arcade.Emitter.prototype.setAlpha = function (min, max, rate, ease, yoyo) { - if (min === undefined) { min = 1; } if (max === undefined) { max = 1; } if (rate === undefined) { rate = 0; } @@ -938,27 +904,25 @@ Phaser.Particles.Arcade.Emitter.prototype.setAlpha = function (min, max, rate, e } return this; - }; /** -* A more compact way of setting the scale constraints of the particles. -* The rate parameter, if set to a value above zero, lets you set the speed and ease which the Particle uses to change in scale from min to max across both axis. -* If rate is zero, which is the default, the particle won't change scale during update, instead it will pick a random scale between min and max on emit. -* -* @method Phaser.Particles.Arcade.Emitter#setScale -* @param {number} [minX=1] - The minimum value of Particle.scale.x. -* @param {number} [maxX=1] - The maximum value of Particle.scale.x. -* @param {number} [minY=1] - The minimum value of Particle.scale.y. -* @param {number} [maxY=1] - The maximum value of Particle.scale.y. -* @param {number} [rate=0] - The rate (in ms) at which the particles will change in scale from min to max, or set to zero to pick a random size between the two. -* @param {function} [ease=Phaser.Easing.Linear.None] - If you've set a rate > 0 this is the easing formula applied between the min and max values. -* @param {boolean} [yoyo=false] - If you've set a rate > 0 you can set if the ease will yoyo or not (i.e. ease back to its original values) -* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. -*/ + * A more compact way of setting the scale constraints of the particles. + * The rate parameter, if set to a value above zero, lets you set the speed and ease which the Particle uses to change in scale from min to max across both axis. + * If rate is zero, which is the default, the particle won't change scale during update, instead it will pick a random scale between min and max on emit. + * + * @method Phaser.Particles.Arcade.Emitter#setScale + * @param {number} [minX=1] - The minimum value of Particle.scale.x. + * @param {number} [maxX=1] - The maximum value of Particle.scale.x. + * @param {number} [minY=1] - The minimum value of Particle.scale.y. + * @param {number} [maxY=1] - The maximum value of Particle.scale.y. + * @param {number} [rate=0] - The rate (in ms) at which the particles will change in scale from min to max, or set to zero to pick a random size between the two. + * @param {function} [ease=Phaser.Easing.Linear.None] - If you've set a rate > 0 this is the easing formula applied between the min and max values. + * @param {boolean} [yoyo=false] - If you've set a rate > 0 you can set if the ease will yoyo or not (i.e. ease back to its original values) + * @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. + */ Phaser.Particles.Arcade.Emitter.prototype.setScale = function (minX, maxX, minY, maxY, rate, ease, yoyo) { - if (minX === undefined) { minX = 1; } if (maxX === undefined) { maxX = 1; } if (minY === undefined) { minY = 1; } @@ -990,7 +954,6 @@ Phaser.Particles.Arcade.Emitter.prototype.setScale = function (minX, maxX, minY, } return this; - }; /** @@ -1009,7 +972,6 @@ Phaser.Particles.Arcade.Emitter.prototype.setScale = function (minX, maxX, minY, */ Phaser.Particles.Arcade.Emitter.prototype.setAngle = function (minAngle, maxAngle, minSpeed, maxSpeed) { - this.minAngle = minAngle; this.maxAngle = maxAngle; @@ -1017,20 +979,18 @@ Phaser.Particles.Arcade.Emitter.prototype.setAngle = function (minAngle, maxAngl if (maxSpeed != null) { this.maxSpeed = maxSpeed; } return this; - }; /** -* Change the emitter's center to match the center of any object with a `center` property, such as an Arcade Body. -* If the object doesn't have a `center` property it will be set to the object's anchor-adjusted world position (`object.world`). -* -* @method Phaser.Particles.Arcade.Emitter#at -* @param {object|Phaser.Sprite|Phaser.Image|Phaser.TileSprite|Phaser.Text|PIXI.DisplayObject} object - The object that you wish to match the center with. -* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. -*/ + * Change the emitter's center to match the center of any object with a `center` property, such as an Arcade Body. + * If the object doesn't have a `center` property it will be set to the object's anchor-adjusted world position (`object.world`). + * + * @method Phaser.Particles.Arcade.Emitter#at + * @param {object|Phaser.Sprite|Phaser.Image|Phaser.TileSprite|Phaser.Text|PIXI.DisplayObject} object - The object that you wish to match the center with. + * @return {Phaser.Particles.Arcade.Emitter} This Emitter instance. + */ Phaser.Particles.Arcade.Emitter.prototype.at = function (object) { - if (object.center) { this.emitX = object.center.x; @@ -1043,7 +1003,6 @@ Phaser.Particles.Arcade.Emitter.prototype.at = function (object) } return this; - }; /** @@ -1073,9 +1032,9 @@ Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, 'gravity', { /** -* @name Phaser.Particles.Arcade.Emitter#id -* @property {number} id - Gets the internal ID that represents this emitter. -*/ + * @name Phaser.Particles.Arcade.Emitter#id + * @property {number} id - Gets the internal ID that represents this emitter. + */ Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, 'id', { get: function () { @@ -1084,9 +1043,9 @@ Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, 'id', { }); /** -* @name Phaser.Particles.Arcade.Emitter#width -* @property {number} width - Gets or sets the width of the Emitter. This is the region in which a particle can be emitted. -*/ + * @name Phaser.Particles.Arcade.Emitter#width + * @property {number} width - Gets or sets the width of the Emitter. This is the region in which a particle can be emitted. + */ Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, 'width', { get: function () @@ -1102,9 +1061,9 @@ Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, 'width', { }); /** -* @name Phaser.Particles.Arcade.Emitter#height -* @property {number} height - Gets or sets the height of the Emitter. This is the region in which a particle can be emitted. -*/ + * @name Phaser.Particles.Arcade.Emitter#height + * @property {number} height - Gets or sets the height of the Emitter. This is the region in which a particle can be emitted. + */ Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, 'height', { get: function () @@ -1120,9 +1079,9 @@ Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, 'height', { }); /** -* @name Phaser.Particles.Arcade.Emitter#x -* @property {number} x - Gets or sets the x position of the Emitter. -*/ + * @name Phaser.Particles.Arcade.Emitter#x + * @property {number} x - Gets or sets the x position of the Emitter. + */ Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, 'x', { get: function () @@ -1138,9 +1097,9 @@ Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, 'x', { }); /** -* @name Phaser.Particles.Arcade.Emitter#y -* @property {number} y - Gets or sets the y position of the Emitter. -*/ + * @name Phaser.Particles.Arcade.Emitter#y + * @property {number} y - Gets or sets the y position of the Emitter. + */ Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, 'y', { get: function () @@ -1156,10 +1115,10 @@ Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, 'y', { }); /** -* @name Phaser.Particles.Arcade.Emitter#left -* @property {number} left - Gets the left position of the Emitter. -* @readonly -*/ + * @name Phaser.Particles.Arcade.Emitter#left + * @property {number} left - Gets the left position of the Emitter. + * @readonly + */ Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, 'left', { get: function () @@ -1170,10 +1129,10 @@ Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, 'left', { }); /** -* @name Phaser.Particles.Arcade.Emitter#right -* @property {number} right - Gets the right position of the Emitter. -* @readonly -*/ + * @name Phaser.Particles.Arcade.Emitter#right + * @property {number} right - Gets the right position of the Emitter. + * @readonly + */ Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, 'right', { get: function () @@ -1184,10 +1143,10 @@ Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, 'right', { }); /** -* @name Phaser.Particles.Arcade.Emitter#top -* @property {number} top - Gets the top position of the Emitter. -* @readonly -*/ + * @name Phaser.Particles.Arcade.Emitter#top + * @property {number} top - Gets the top position of the Emitter. + * @readonly + */ Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, 'top', { get: function () @@ -1198,10 +1157,10 @@ Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, 'top', { }); /** -* @name Phaser.Particles.Arcade.Emitter#bottom -* @property {number} bottom - Gets the bottom position of the Emitter. -* @readonly -*/ + * @name Phaser.Particles.Arcade.Emitter#bottom + * @property {number} bottom - Gets the bottom position of the Emitter. + * @readonly + */ Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, 'bottom', { get: function () @@ -1254,30 +1213,30 @@ Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, 'remainder', { }); /** -* The last particle released, if any. -* -* You should treat this as read-only (and also avoid {@link #next} and {@link #previous}) once the emitter is started. Phaser uses it internally to track particles. -* -* @name Phaser.Particles.Arcade.Emitter#cursor -* @property {?DisplayObject} cursor -* @readonly -*/ + * The last particle released, if any. + * + * You should treat this as read-only (and also avoid {@link #next} and {@link #previous}) once the emitter is started. Phaser uses it internally to track particles. + * + * @name Phaser.Particles.Arcade.Emitter#cursor + * @property {?DisplayObject} cursor + * @readonly + */ // Inherited from Phaser.Group#cursor /** -* Advances the cursor to the next particle. -* -* @method Phaser.Particles.Arcade.Emitter#next -* @protected -* @return {any} The child the cursor now points to. -*/ + * Advances the cursor to the next particle. + * + * @method Phaser.Particles.Arcade.Emitter#next + * @protected + * @return {any} The child the cursor now points to. + */ // Inherited from Phaser.Group#next /** -* Moves the group cursor to the previous particle. -* -* @method Phaser.Particles.Arcade.Emitter#previous -* @protected -* @return {any} The child the cursor now points to. -*/ + * Moves the group cursor to the previous particle. + * + * @method Phaser.Particles.Arcade.Emitter#previous + * @protected + * @return {any} The child the cursor now points to. + */ // Inherited from Phaser.Group#previous diff --git a/src/physics/Physics.js b/src/physics/Physics.js index dd2f63d76..0a12fc46f 100644 --- a/src/physics/Physics.js +++ b/src/physics/Physics.js @@ -1,118 +1,115 @@ /** -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* The Physics Manager is responsible for looking after all of the running physics systems. -* Phaser supports 4 physics systems: Arcade Physics, P2, Ninja Physics and Box2D via a commercial plugin. -* -* Game Objects (such as Sprites) can only belong to 1 physics system, but you can have multiple systems active in a single game. -* -* For example you could have P2 managing a polygon-built terrain landscape that an vehicle drives over, while it could be firing bullets that use the -* faster (due to being much simpler) Arcade Physics system. -* -* @class Phaser.Physics -* @constructor -* @param {Phaser.Game} game - A reference to the currently running game. -* @param {object} [physicsConfig=null] - A physics configuration object to pass to the Physics world on creation. -*/ + * The Physics Manager is responsible for looking after all of the running physics systems. + * Phaser supports 4 physics systems: Arcade Physics, P2, Ninja Physics and Box2D via a commercial plugin. + * + * Game Objects (such as Sprites) can only belong to 1 physics system, but you can have multiple systems active in a single game. + * + * For example you could have P2 managing a polygon-built terrain landscape that an vehicle drives over, while it could be firing bullets that use the + * faster (due to being much simpler) Arcade Physics system. + * + * @class Phaser.Physics + * @constructor + * @param {Phaser.Game} game - A reference to the currently running game. + * @param {object} [physicsConfig=null] - A physics configuration object to pass to the Physics world on creation. + */ Phaser.Physics = function (game, config) { - config = config || {}; /** - * @property {Phaser.Game} game - Local reference to game. - */ + * @property {Phaser.Game} game - Local reference to game. + */ this.game = game; /** - * @property {object} config - The physics configuration object as passed to the game on creation. - */ + * @property {object} config - The physics configuration object as passed to the game on creation. + */ this.config = config; /** - * @property {Phaser.Physics.Arcade} arcade - The Arcade Physics system. - */ + * @property {Phaser.Physics.Arcade} arcade - The Arcade Physics system. + */ this.arcade = null; /** - * @property {Phaser.Physics.P2} p2 - The P2.JS Physics system. - */ + * @property {Phaser.Physics.P2} p2 - The P2.JS Physics system. + */ this.p2 = null; /** - * @property {Phaser.Physics.Ninja} ninja - The N+ Ninja Physics system. - */ + * @property {Phaser.Physics.Ninja} ninja - The N+ Ninja Physics system. + */ this.ninja = null; /** - * @property {Phaser.Physics.Box2D} box2d - The Box2D Physics system. - */ + * @property {Phaser.Physics.Box2D} box2d - The Box2D Physics system. + */ this.box2d = null; /** - * @property {Phaser.Physics.Chipmunk} chipmunk - The Chipmunk Physics system (to be done). - */ + * @property {Phaser.Physics.Chipmunk} chipmunk - The Chipmunk Physics system (to be done). + */ this.chipmunk = null; /** - * @property {Phaser.Physics.Matter} matter - The MatterJS Physics system (coming soon). - */ + * @property {Phaser.Physics.Matter} matter - The MatterJS Physics system (coming soon). + */ this.matter = null; this.parseConfig(); - }; /** -* @const -* @type {number} -*/ + * @const + * @type {number} + */ Phaser.Physics.ARCADE = 0; /** -* @const -* @type {number} -*/ + * @const + * @type {number} + */ Phaser.Physics.P2JS = 1; /** -* @const -* @type {number} -*/ + * @const + * @type {number} + */ Phaser.Physics.NINJA = 2; /** -* @const -* @type {number} -*/ + * @const + * @type {number} + */ Phaser.Physics.BOX2D = 3; /** -* @const -* @type {number} -*/ + * @const + * @type {number} + */ Phaser.Physics.CHIPMUNK = 4; /** -* @const -* @type {number} -*/ + * @const + * @type {number} + */ Phaser.Physics.MATTERJS = 5; Phaser.Physics.prototype = { /** - * Parses the Physics Configuration object passed to the Game constructor and starts any physics systems specified within. - * - * @method Phaser.Physics#parseConfig - */ + * Parses the Physics Configuration object passed to the Game constructor and starts any physics systems specified within. + * + * @method Phaser.Physics#parseConfig + */ parseConfig: function () { - if ((!this.config.hasOwnProperty('arcade') || this.config.arcade === true) && Phaser.Physics.hasOwnProperty('Arcade')) { // If Arcade isn't specified, we create it automatically if we can @@ -138,32 +135,30 @@ Phaser.Physics.prototype = { { this.matter = new Phaser.Physics.Matter(this.game, this.config); } - }, /** - * This will create an instance of the requested physics simulation. - * Phaser.Physics.Arcade is running by default, but all others need activating directly. - * - * You can start the following physics systems: - * - * Phaser.Physics.P2JS - A full-body advanced physics system by Stefan Hedman. - * Phaser.Physics.NINJA - A port of Metanet Softwares N+ physics system. - * Phaser.Physics.BOX2D - A commercial Phaser Plugin (see http://phaser.io) - * - * Both Ninja Physics and Box2D require their respective plugins to be loaded before you can start them. - * They are not bundled into the core Phaser library. - * - * If the physics world has already been created (i.e. in another state in your game) then - * calling startSystem will reset the physics world, not re-create it. If you need to start them again from their constructors - * then set Phaser.Physics.p2 (or whichever system you want to recreate) to `null` before calling `startSystem`. - * - * @method Phaser.Physics#startSystem - * @param {number} system - The physics system to start: Phaser.Physics.ARCADE, Phaser.Physics.P2JS, Phaser.Physics.NINJA or Phaser.Physics.BOX2D. - */ + * This will create an instance of the requested physics simulation. + * Phaser.Physics.Arcade is running by default, but all others need activating directly. + * + * You can start the following physics systems: + * + * Phaser.Physics.P2JS - A full-body advanced physics system by Stefan Hedman. + * Phaser.Physics.NINJA - A port of Metanet Softwares N+ physics system. + * Phaser.Physics.BOX2D - A commercial Phaser Plugin (see http://phaser.io) + * + * Both Ninja Physics and Box2D require their respective plugins to be loaded before you can start them. + * They are not bundled into the core Phaser library. + * + * If the physics world has already been created (i.e. in another state in your game) then + * calling startSystem will reset the physics world, not re-create it. If you need to start them again from their constructors + * then set Phaser.Physics.p2 (or whichever system you want to recreate) to `null` before calling `startSystem`. + * + * @method Phaser.Physics#startSystem + * @param {number} system - The physics system to start: Phaser.Physics.ARCADE, Phaser.Physics.P2JS, Phaser.Physics.NINJA or Phaser.Physics.BOX2D. + */ startSystem: function (system) { - if (system === Phaser.Physics.ARCADE) { this.arcade = new Phaser.Physics.Arcade(this.game); @@ -205,32 +200,30 @@ Phaser.Physics.prototype = { this.matter.reset(); } } - }, /** - * This will create a default physics body on the given game object or array of objects. - * A game object can only have 1 physics body active at any one time, and it can't be changed until the object is destroyed. - * It can be for any of the physics systems that have been started: - * - * Phaser.Physics.Arcade - A light weight AABB based collision system with basic separation. - * Phaser.Physics.P2JS - A full-body advanced physics system supporting multiple object shapes, polygon loading, contact materials, springs and constraints. - * Phaser.Physics.NINJA - A port of Metanet Softwares N+ physics system. Advanced AABB and Circle vs. Tile collision. - * Phaser.Physics.BOX2D - A port of https://code.google.com/p/box2d-html5 - * Phaser.Physics.MATTER - A full-body and light-weight advanced physics system (still in development) - * Phaser.Physics.CHIPMUNK is still in development. - * - * If you require more control over what type of body is created, for example to create a Ninja Physics Circle instead of the default AABB, then see the - * individual physics systems `enable` methods instead of using this generic one. - * - * @method Phaser.Physics#enable - * @param {object|array} object - The game object to create the physics body on. Can also be an array of objects, a body will be created on every object in the array. - * @param {number} [system=Phaser.Physics.ARCADE] - The physics system that will be used to create the body. Defaults to Arcade Physics. - * @param {boolean} [debug=false] - Enable the debug drawing for this body. Defaults to false. - */ + * This will create a default physics body on the given game object or array of objects. + * A game object can only have 1 physics body active at any one time, and it can't be changed until the object is destroyed. + * It can be for any of the physics systems that have been started: + * + * Phaser.Physics.Arcade - A light weight AABB based collision system with basic separation. + * Phaser.Physics.P2JS - A full-body advanced physics system supporting multiple object shapes, polygon loading, contact materials, springs and constraints. + * Phaser.Physics.NINJA - A port of Metanet Softwares N+ physics system. Advanced AABB and Circle vs. Tile collision. + * Phaser.Physics.BOX2D - A port of https://code.google.com/p/box2d-html5 + * Phaser.Physics.MATTER - A full-body and light-weight advanced physics system (still in development) + * Phaser.Physics.CHIPMUNK is still in development. + * + * If you require more control over what type of body is created, for example to create a Ninja Physics Circle instead of the default AABB, then see the + * individual physics systems `enable` methods instead of using this generic one. + * + * @method Phaser.Physics#enable + * @param {object|array} object - The game object to create the physics body on. Can also be an array of objects, a body will be created on every object in the array. + * @param {number} [system=Phaser.Physics.ARCADE] - The physics system that will be used to create the body. Defaults to Arcade Physics. + * @param {boolean} [debug=false] - Enable the debug drawing for this body. Defaults to false. + */ enable: function (object, system, debug) { - if (system === undefined) { system = Phaser.Physics.ARCADE; } if (debug === undefined) { debug = false; } @@ -258,18 +251,16 @@ Phaser.Physics.prototype = { { console.warn(object.key + ' is attempting to enable a physics body using an unknown physics system.'); } - }, /** - * preUpdate checks. - * - * @method Phaser.Physics#preUpdate - * @protected - */ + * preUpdate checks. + * + * @method Phaser.Physics#preUpdate + * @protected + */ preUpdate: function () { - // ArcadePhysics / Ninja don't have a core to preUpdate if (this.p2) @@ -286,18 +277,16 @@ Phaser.Physics.prototype = { { this.matter.preUpdate(); } - }, /** - * Updates all running physics systems. - * - * @method Phaser.Physics#update - * @protected - */ + * Updates all running physics systems. + * + * @method Phaser.Physics#update + * @protected + */ update: function () { - // ArcadePhysics / Ninja don't have a core to update if (this.p2) @@ -314,18 +303,16 @@ Phaser.Physics.prototype = { { this.matter.update(); } - }, /** - * Updates the physics bounds to match the world dimensions. - * - * @method Phaser.Physics#setBoundsToWorld - * @protected - */ + * Updates the physics bounds to match the world dimensions. + * + * @method Phaser.Physics#setBoundsToWorld + * @protected + */ setBoundsToWorld: function () { - if (this.arcade) { this.arcade.setBoundsToWorld(); @@ -350,18 +337,16 @@ Phaser.Physics.prototype = { { this.matter.setBoundsToWorld(); } - }, /** - * Clears down all active physics systems. This doesn't destroy them, it just clears them of objects and is called when the State changes. - * - * @method Phaser.Physics#clear - * @protected - */ + * Clears down all active physics systems. This doesn't destroy them, it just clears them of objects and is called when the State changes. + * + * @method Phaser.Physics#clear + * @protected + */ clear: function () { - if (this.p2) { this.p2.clear(); @@ -376,18 +361,16 @@ Phaser.Physics.prototype = { { this.matter.clear(); } - }, /** - * Resets the active physics system. Called automatically on a Phaser.State swap. - * - * @method Phaser.Physics#reset - * @protected - */ + * Resets the active physics system. Called automatically on a Phaser.State swap. + * + * @method Phaser.Physics#reset + * @protected + */ reset: function () { - if (this.p2) { this.p2.reset(); @@ -402,17 +385,15 @@ Phaser.Physics.prototype = { { this.matter.reset(); } - }, /** - * Destroys all active physics systems. Usually only called on a Game Shutdown, not on a State swap. - * - * @method Phaser.Physics#destroy - */ + * Destroys all active physics systems. Usually only called on a Game Shutdown, not on a State swap. + * + * @method Phaser.Physics#destroy + */ destroy: function () { - if (this.p2) { this.p2.destroy(); @@ -433,7 +414,6 @@ Phaser.Physics.prototype = { this.p2 = null; this.box2d = null; this.matter = null; - } }; diff --git a/src/physics/arcade/Body.js b/src/physics/arcade/Body.js index 318a1b18f..aeb557bb2 100644 --- a/src/physics/arcade/Body.js +++ b/src/physics/arcade/Body.js @@ -1,119 +1,118 @@ /** -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* The Physics Body is linked to a single Sprite. All physics operations should be performed against the body rather than -* the Sprite itself. For example you can set the velocity, acceleration, bounce values etc all on the Body. -* -* @class Phaser.Physics.Arcade.Body -* @constructor -* @param {Phaser.Sprite} sprite - The Sprite object this physics body belongs to. -*/ + * The Physics Body is linked to a single Sprite. All physics operations should be performed against the body rather than + * the Sprite itself. For example you can set the velocity, acceleration, bounce values etc all on the Body. + * + * @class Phaser.Physics.Arcade.Body + * @constructor + * @param {Phaser.Sprite} sprite - The Sprite object this physics body belongs to. + */ Phaser.Physics.Arcade.Body = function (sprite) { - /** - * @property {Phaser.Sprite} sprite - Reference to the parent Sprite. - */ + * @property {Phaser.Sprite} sprite - Reference to the parent Sprite. + */ this.sprite = sprite; /** - * @property {Phaser.Game} game - Local reference to game. - */ + * @property {Phaser.Game} game - Local reference to game. + */ this.game = sprite.game; /** - * @property {number} type - The type of physics system this body belongs to. - */ + * @property {number} type - The type of physics system this body belongs to. + */ this.type = Phaser.Physics.ARCADE; /** - * @property {boolean} enable - A disabled body won't be checked for any form of collision or overlap or have its pre/post updates run. - * @default - */ + * @property {boolean} enable - A disabled body won't be checked for any form of collision or overlap or have its pre/post updates run. + * @default + */ this.enable = true; /** - * If `true` this Body is using circular collision detection. If `false` it is using rectangular. - * Use `Body.setCircle` to control the collision shape this Body uses. - * @property {boolean} isCircle - * @default - * @readOnly - */ + * If `true` this Body is using circular collision detection. If `false` it is using rectangular. + * Use `Body.setCircle` to control the collision shape this Body uses. + * @property {boolean} isCircle + * @default + * @readOnly + */ this.isCircle = false; /** - * The radius of the circular collision shape this Body is using if Body.setCircle has been enabled, relative to the Sprite's _texture_. - * If you wish to change the radius then call {@link #setCircle} again with the new value. - * If you wish to stop the Body using a circle then call {@link #setCircle} with a radius of zero (or undefined). - * The actual radius of the Body (at any Sprite scale) is equal to {@link #halfWidth} and the diameter is equal to {@link #width}. - * @property {number} radius - * @default - * @readOnly - */ + * The radius of the circular collision shape this Body is using if Body.setCircle has been enabled, relative to the Sprite's _texture_. + * If you wish to change the radius then call {@link #setCircle} again with the new value. + * If you wish to stop the Body using a circle then call {@link #setCircle} with a radius of zero (or undefined). + * The actual radius of the Body (at any Sprite scale) is equal to {@link #halfWidth} and the diameter is equal to {@link #width}. + * @property {number} radius + * @default + * @readOnly + */ this.radius = 0; /** - * @property {Phaser.Point} offset - The offset of the Physics Body from the Sprite's texture. - */ + * @property {Phaser.Point} offset - The offset of the Physics Body from the Sprite's texture. + */ this.offset = new Phaser.Point(); /** - * @property {Phaser.Point} position - The position of the physics body, equivalent to ({@link #left}, {@link #top}). - * @readonly - */ + * @property {Phaser.Point} position - The position of the physics body, equivalent to ({@link #left}, {@link #top}). + * @readonly + */ this.position = new Phaser.Point(sprite.x, sprite.y); /** - * @property {Phaser.Point} prev - The previous position of the physics body. - * @readonly - */ + * @property {Phaser.Point} prev - The previous position of the physics body. + * @readonly + */ this.prev = new Phaser.Point(this.position.x, this.position.y); /** - * @property {boolean} allowRotation - Allow this Body to be rotated? (via angularVelocity, etc) - * @default - */ + * @property {boolean} allowRotation - Allow this Body to be rotated? (via angularVelocity, etc) + * @default + */ this.allowRotation = true; /** - * The Body's rotation in degrees, as calculated by its angularVelocity and angularAcceleration. Please understand that the collision Body - * itself never rotates, it is always axis-aligned. However these values are passed up to the parent Sprite and updates its rotation. - * @property {number} rotation - */ + * The Body's rotation in degrees, as calculated by its angularVelocity and angularAcceleration. Please understand that the collision Body + * itself never rotates, it is always axis-aligned. However these values are passed up to the parent Sprite and updates its rotation. + * @property {number} rotation + */ this.rotation = sprite.angle; /** - * @property {number} preRotation - The previous rotation of the physics body, in degrees. - * @readonly - */ + * @property {number} preRotation - The previous rotation of the physics body, in degrees. + * @readonly + */ this.preRotation = sprite.angle; /** - * @property {number} width - The calculated width of the physics body. - * @readonly - */ + * @property {number} width - The calculated width of the physics body. + * @readonly + */ this.width = sprite.width; /** - * @property {number} height - The calculated height of the physics body. - * @readonly - */ + * @property {number} height - The calculated height of the physics body. + * @readonly + */ this.height = sprite.height; /** - * @property {number} sourceWidth - The un-scaled original size. - * @readonly - */ + * @property {number} sourceWidth - The un-scaled original size. + * @readonly + */ this.sourceWidth = sprite.width; /** - * @property {number} sourceHeight - The un-scaled original size. - * @readonly - */ + * @property {number} sourceHeight - The un-scaled original size. + * @readonly + */ this.sourceHeight = sprite.height; if (sprite.texture) @@ -123,42 +122,42 @@ Phaser.Physics.Arcade.Body = function (sprite) } /** - * @property {number} halfWidth - The calculated width / 2 of the physics body. - * @readonly - */ + * @property {number} halfWidth - The calculated width / 2 of the physics body. + * @readonly + */ this.halfWidth = Math.abs(sprite.width / 2); /** - * @property {number} halfHeight - The calculated height / 2 of the physics body. - * @readonly - */ + * @property {number} halfHeight - The calculated height / 2 of the physics body. + * @readonly + */ this.halfHeight = Math.abs(sprite.height / 2); /** - * @property {Phaser.Point} center - The center coordinate of the Physics Body. - * @readonly - */ + * @property {Phaser.Point} center - The center coordinate of the Physics Body. + * @readonly + */ this.center = new Phaser.Point(sprite.x + this.halfWidth, sprite.y + this.halfHeight); /** - * @property {Phaser.Point} velocity - The velocity, or rate of change the Body's position. Measured in pixels per second. - */ + * @property {Phaser.Point} velocity - The velocity, or rate of change the Body's position. Measured in pixels per second. + */ this.velocity = new Phaser.Point(); /** - * @property {Phaser.Point} newVelocity - The distanced traveled during the last update, equal to `velocity * physicsElapsed`. Calculated during the Body.preUpdate and applied to its position. - * @readonly - */ + * @property {Phaser.Point} newVelocity - The distanced traveled during the last update, equal to `velocity * physicsElapsed`. Calculated during the Body.preUpdate and applied to its position. + * @readonly + */ this.newVelocity = new Phaser.Point(); /** - * @property {Phaser.Point} deltaMax - The Sprite position is updated based on the delta x/y values. You can set a cap on those (both +-) using deltaMax. - */ + * @property {Phaser.Point} deltaMax - The Sprite position is updated based on the delta x/y values. You can set a cap on those (both +-) using deltaMax. + */ this.deltaMax = new Phaser.Point(); /** - * @property {Phaser.Point} acceleration - The acceleration is the rate of change of the velocity. Measured in pixels per second squared. - */ + * @property {Phaser.Point} acceleration - The acceleration is the rate of change of the velocity. Measured in pixels per second squared. + */ this.acceleration = new Phaser.Point(); /** @@ -168,365 +167,363 @@ Phaser.Physics.Arcade.Body = function (sprite) this.allowDrag = true; /** - * @property {Phaser.Point} drag - The drag applied to the motion of the Body (when {@link #allowDrag} is enabled). Measured in pixels per second squared. - */ + * @property {Phaser.Point} drag - The drag applied to the motion of the Body (when {@link #allowDrag} is enabled). Measured in pixels per second squared. + */ this.drag = new Phaser.Point(); /** - * @property {boolean} allowGravity - Allow this Body to be influenced by gravity? Either world or local. - * @default - */ + * @property {boolean} allowGravity - Allow this Body to be influenced by gravity? Either world or local. + * @default + */ this.allowGravity = true; /** - * @property {Phaser.Point} gravity - This Body's local gravity, **added** to any world gravity, unless Body.allowGravity is set to false. - */ + * @property {Phaser.Point} gravity - This Body's local gravity, **added** to any world gravity, unless Body.allowGravity is set to false. + */ this.gravity = new Phaser.Point(); /** - * @property {Phaser.Point} bounce - The elasticity of the Body when colliding. bounce.x/y = 1 means full rebound, bounce.x/y = 0.5 means 50% rebound velocity. - */ + * @property {Phaser.Point} bounce - The elasticity of the Body when colliding. bounce.x/y = 1 means full rebound, bounce.x/y = 0.5 means 50% rebound velocity. + */ this.bounce = new Phaser.Point(); /** - * The elasticity of the Body when colliding with the World bounds. - * By default this property is `null`, in which case `Body.bounce` is used instead. Set this property - * to a Phaser.Point object in order to enable a World bounds specific bounce value. - * @property {Phaser.Point} worldBounce - */ + * The elasticity of the Body when colliding with the World bounds. + * By default this property is `null`, in which case `Body.bounce` is used instead. Set this property + * to a Phaser.Point object in order to enable a World bounds specific bounce value. + * @property {Phaser.Point} worldBounce + */ this.worldBounce = null; /** - * A Signal that is dispatched when this Body collides with the world bounds. - * Due to the potentially high volume of signals this could create it is disabled by default. - * To use this feature set this property to a Phaser.Signal: `sprite.body.onWorldBounds = new Phaser.Signal()` - * and it will be called when a collision happens, passing five arguments: - * `onWorldBounds(sprite, up, down, left, right)` - * where the Sprite is a reference to the Sprite that owns this Body, and the other arguments are booleans - * indicating on which side of the world the Body collided. - * @property {Phaser.Signal} onWorldBounds - */ + * A Signal that is dispatched when this Body collides with the world bounds. + * Due to the potentially high volume of signals this could create it is disabled by default. + * To use this feature set this property to a Phaser.Signal: `sprite.body.onWorldBounds = new Phaser.Signal()` + * and it will be called when a collision happens, passing five arguments: + * `onWorldBounds(sprite, up, down, left, right)` + * where the Sprite is a reference to the Sprite that owns this Body, and the other arguments are booleans + * indicating on which side of the world the Body collided. + * @property {Phaser.Signal} onWorldBounds + */ this.onWorldBounds = null; /** - * A Signal that is dispatched when this Body collides with another Body. - * - * You still need to call `game.physics.arcade.collide` in your `update` method in order - * for this signal to be dispatched. - * - * Usually you'd pass a callback to the `collide` method, but this signal provides for - * a different level of notification. - * - * Due to the potentially high volume of signals this could create it is disabled by default. - * - * To use this feature set this property to a Phaser.Signal: `sprite.body.onCollide = new Phaser.Signal()` - * and it will be called when a collision happens, passing two arguments: the sprites which collided. - * The first sprite in the argument is always the owner of this Body. - * - * If two Bodies with this Signal set collide, both will dispatch the Signal. - * @property {Phaser.Signal} onCollide - */ + * A Signal that is dispatched when this Body collides with another Body. + * + * You still need to call `game.physics.arcade.collide` in your `update` method in order + * for this signal to be dispatched. + * + * Usually you'd pass a callback to the `collide` method, but this signal provides for + * a different level of notification. + * + * Due to the potentially high volume of signals this could create it is disabled by default. + * + * To use this feature set this property to a Phaser.Signal: `sprite.body.onCollide = new Phaser.Signal()` + * and it will be called when a collision happens, passing two arguments: the sprites which collided. + * The first sprite in the argument is always the owner of this Body. + * + * If two Bodies with this Signal set collide, both will dispatch the Signal. + * @property {Phaser.Signal} onCollide + */ this.onCollide = null; /** - * A Signal that is dispatched when this Body overlaps with another Body. - * - * You still need to call `game.physics.arcade.overlap` in your `update` method in order - * for this signal to be dispatched. - * - * Usually you'd pass a callback to the `overlap` method, but this signal provides for - * a different level of notification. - * - * Due to the potentially high volume of signals this could create it is disabled by default. - * - * To use this feature set this property to a Phaser.Signal: `sprite.body.onOverlap = new Phaser.Signal()` - * and it will be called when a collision happens, passing two arguments: the sprites which collided. - * The first sprite in the argument is always the owner of this Body. - * - * If two Bodies with this Signal set collide, both will dispatch the Signal. - * @property {Phaser.Signal} onOverlap - */ + * A Signal that is dispatched when this Body overlaps with another Body. + * + * You still need to call `game.physics.arcade.overlap` in your `update` method in order + * for this signal to be dispatched. + * + * Usually you'd pass a callback to the `overlap` method, but this signal provides for + * a different level of notification. + * + * Due to the potentially high volume of signals this could create it is disabled by default. + * + * To use this feature set this property to a Phaser.Signal: `sprite.body.onOverlap = new Phaser.Signal()` + * and it will be called when a collision happens, passing two arguments: the sprites which collided. + * The first sprite in the argument is always the owner of this Body. + * + * If two Bodies with this Signal set collide, both will dispatch the Signal. + * @property {Phaser.Signal} onOverlap + */ this.onOverlap = null; /** - * @property {Phaser.Point} maxVelocity - The maximum velocity (in pixels per second squared) that the Body can reach. - * @default - */ + * @property {Phaser.Point} maxVelocity - The maximum velocity (in pixels per second squared) that the Body can reach. + * @default + */ this.maxVelocity = new Phaser.Point(10000, 10000); /** - * @property {Phaser.Point} friction - If this Body is {@link #immovable} and moving, and another Body is 'riding' this one, this is the amount of motion the riding Body receives on each axis. - */ + * @property {Phaser.Point} friction - If this Body is {@link #immovable} and moving, and another Body is 'riding' this one, this is the amount of motion the riding Body receives on each axis. + */ this.friction = new Phaser.Point(1, 0); /** - * @property {number} angularVelocity - The angular velocity is the rate of change of the Body's rotation. It is measured in degrees per second. - * @default - */ + * @property {number} angularVelocity - The angular velocity is the rate of change of the Body's rotation. It is measured in degrees per second. + * @default + */ this.angularVelocity = 0; /** - * @property {number} angularAcceleration - The angular acceleration is the rate of change of the angular velocity. Measured in degrees per second squared. - * @default - */ + * @property {number} angularAcceleration - The angular acceleration is the rate of change of the angular velocity. Measured in degrees per second squared. + * @default + */ this.angularAcceleration = 0; /** - * @property {number} angularDrag - The drag applied during the rotation of the Body. Measured in degrees per second squared. - * @default - */ + * @property {number} angularDrag - The drag applied during the rotation of the Body. Measured in degrees per second squared. + * @default + */ this.angularDrag = 0; /** - * @property {number} maxAngular - The maximum angular velocity in degrees per second that the Body can reach. - * @default - */ + * @property {number} maxAngular - The maximum angular velocity in degrees per second that the Body can reach. + * @default + */ this.maxAngular = 1000; /** - * @property {number} mass - The mass of the Body. When two bodies collide their mass is used in the calculation to determine the exchange of velocity. - * @default - */ + * @property {number} mass - The mass of the Body. When two bodies collide their mass is used in the calculation to determine the exchange of velocity. + * @default + */ this.mass = 1; /** - * @property {number} angle - The angle of the Body's **velocity** in radians. - * @readonly - */ + * @property {number} angle - The angle of the Body's **velocity** in radians. + * @readonly + */ this.angle = 0; /** - * @property {number} speed - The speed of the Body in pixels per second, equal to the magnitude of the velocity. - * @readonly - */ + * @property {number} speed - The speed of the Body in pixels per second, equal to the magnitude of the velocity. + * @readonly + */ this.speed = 0; /** - * @property {number} facing - A const reference to the direction the Body is traveling or facing: Phaser.NONE, Phaser.LEFT, Phaser.RIGHT, Phaser.UP, or Phaser.DOWN. If the Body is moving on both axes, UP and DOWN take precedence. - * @default - */ + * @property {number} facing - A const reference to the direction the Body is traveling or facing: Phaser.NONE, Phaser.LEFT, Phaser.RIGHT, Phaser.UP, or Phaser.DOWN. If the Body is moving on both axes, UP and DOWN take precedence. + * @default + */ this.facing = Phaser.NONE; /** - * @property {boolean} immovable - An immovable Body will not receive any impacts from other bodies. **Two** immovable Bodies can't separate or exchange momentum and will pass through each other. - * @default - */ + * @property {boolean} immovable - An immovable Body will not receive any impacts from other bodies. **Two** immovable Bodies can't separate or exchange momentum and will pass through each other. + * @default + */ this.immovable = false; /** - * Whether the physics system should update the Body's position and rotation based on its velocity, acceleration, drag, and gravity. - * - * If you have a Body that is being moved around the world via a tween or a Group motion, but its local x/y position never - * actually changes, then you should set Body.moves = false. Otherwise it will most likely fly off the screen. - * If you want the physics system to move the body around, then set moves to true. - * - * A Body with moves = false can still be moved slightly (but not accelerated) during collision separation unless you set {@link #immovable} as well. - * - * @property {boolean} moves - Set to true to allow the Physics system to move this Body, otherwise false to move it manually. - * @default - */ + * Whether the physics system should update the Body's position and rotation based on its velocity, acceleration, drag, and gravity. + * + * If you have a Body that is being moved around the world via a tween or a Group motion, but its local x/y position never + * actually changes, then you should set Body.moves = false. Otherwise it will most likely fly off the screen. + * If you want the physics system to move the body around, then set moves to true. + * + * A Body with moves = false can still be moved slightly (but not accelerated) during collision separation unless you set {@link #immovable} as well. + * + * @property {boolean} moves - Set to true to allow the Physics system to move this Body, otherwise false to move it manually. + * @default + */ this.moves = true; /** - * This flag allows you to disable the custom x separation that takes place by Physics.Arcade.separate. - * Used in combination with your own collision processHandler you can create whatever type of collision response you need. - * @property {boolean} customSeparateX - Use a custom separation system or the built-in one? - * @default - */ + * This flag allows you to disable the custom x separation that takes place by Physics.Arcade.separate. + * Used in combination with your own collision processHandler you can create whatever type of collision response you need. + * @property {boolean} customSeparateX - Use a custom separation system or the built-in one? + * @default + */ this.customSeparateX = false; /** - * This flag allows you to disable the custom y separation that takes place by Physics.Arcade.separate. - * Used in combination with your own collision processHandler you can create whatever type of collision response you need. - * @property {boolean} customSeparateY - Use a custom separation system or the built-in one? - * @default - */ + * This flag allows you to disable the custom y separation that takes place by Physics.Arcade.separate. + * Used in combination with your own collision processHandler you can create whatever type of collision response you need. + * @property {boolean} customSeparateY - Use a custom separation system or the built-in one? + * @default + */ this.customSeparateY = false; /** - * When this body collides with another, the amount of overlap is stored here. - * @property {number} overlapX - The amount of horizontal overlap during the collision. - */ + * When this body collides with another, the amount of overlap is stored here. + * @property {number} overlapX - The amount of horizontal overlap during the collision. + */ this.overlapX = 0; /** - * When this body collides with another, the amount of overlap is stored here. - * @property {number} overlapY - The amount of vertical overlap during the collision. - */ + * When this body collides with another, the amount of overlap is stored here. + * @property {number} overlapY - The amount of vertical overlap during the collision. + */ this.overlapY = 0; /** - * If `Body.isCircle` is true, and this body collides with another circular body, the amount of overlap is stored here. - * @property {number} overlapR - The amount of overlap during the collision. - */ + * If `Body.isCircle` is true, and this body collides with another circular body, the amount of overlap is stored here. + * @property {number} overlapR - The amount of overlap during the collision. + */ this.overlapR = 0; /** - * If a body is overlapping with another body, but neither of them are moving (maybe they spawned on-top of each other?) this is set to true. - * @property {boolean} embedded - Body embed value. - */ + * If a body is overlapping with another body, but neither of them are moving (maybe they spawned on-top of each other?) this is set to true. + * @property {boolean} embedded - Body embed value. + */ this.embedded = false; /** - * A Body can be set to collide against the World bounds automatically and rebound back into the World if this is set to true. Otherwise it will leave the World. - * @property {boolean} collideWorldBounds - Should the Body collide with the World bounds? - */ + * A Body can be set to collide against the World bounds automatically and rebound back into the World if this is set to true. Otherwise it will leave the World. + * @property {boolean} collideWorldBounds - Should the Body collide with the World bounds? + */ this.collideWorldBounds = false; /** - * Set the checkCollision properties to control which directions collision is processed for this Body. - * For example checkCollision.up = false means it won't collide when the collision happened while moving up. - * If you need to disable a Body entirely, use `body.enable = false`, this will also disable motion. - * If you need to disable just collision and/or overlap checks, but retain motion, set `checkCollision.none = true`. - * @property {object} checkCollision - An object containing allowed collision (none, up, down, left, right). - */ + * Set the checkCollision properties to control which directions collision is processed for this Body. + * For example checkCollision.up = false means it won't collide when the collision happened while moving up. + * If you need to disable a Body entirely, use `body.enable = false`, this will also disable motion. + * If you need to disable just collision and/or overlap checks, but retain motion, set `checkCollision.none = true`. + * @property {object} checkCollision - An object containing allowed collision (none, up, down, left, right). + */ this.checkCollision = { none: false, up: true, down: true, left: true, right: true }; /** - * This object is populated with boolean values when the Body collides with another. - * touching.up = true means the collision happened to the top of this Body for example. - * @property {object} touching - An object containing touching results (none, up, down, left, right). - */ + * This object is populated with boolean values when the Body collides with another. + * touching.up = true means the collision happened to the top of this Body for example. + * @property {object} touching - An object containing touching results (none, up, down, left, right). + */ this.touching = { none: true, up: false, down: false, left: false, right: false }; /** - * This object is populated with previous touching values from the bodies previous collision. - * @property {object} wasTouching - An object containing previous touching results (none, up, down, left, right). - */ + * This object is populated with previous touching values from the bodies previous collision. + * @property {object} wasTouching - An object containing previous touching results (none, up, down, left, right). + */ this.wasTouching = { none: true, up: false, down: false, left: false, right: false }; /** - * This object is populated with boolean values when the Body collides with the World bounds or a Tile. - * For example if blocked.up is true then the Body cannot move up. - * @property {object} blocked - An object containing on which faces this Body is blocked from moving, if any (none, up, down, left, right). - */ + * This object is populated with boolean values when the Body collides with the World bounds or a Tile. + * For example if blocked.up is true then the Body cannot move up. + * @property {object} blocked - An object containing on which faces this Body is blocked from moving, if any (none, up, down, left, right). + */ this.blocked = { none: true, up: false, down: false, left: false, right: false }; /** - * If this is an especially small or fast moving object then it can sometimes skip over tilemap collisions if it moves through a tile in a step. - * Set this padding value to add extra padding to its bounds. tilePadding.x applied to its width, y to its height. - * @property {Phaser.Point} tilePadding - Extra padding to be added to this sprite's dimensions when checking for tile collision. - */ + * If this is an especially small or fast moving object then it can sometimes skip over tilemap collisions if it moves through a tile in a step. + * Set this padding value to add extra padding to its bounds. tilePadding.x applied to its width, y to its height. + * @property {Phaser.Point} tilePadding - Extra padding to be added to this sprite's dimensions when checking for tile collision. + */ this.tilePadding = new Phaser.Point(); /** - * @property {boolean} dirty - If this Body in a preUpdate (true) or postUpdate (false) state? - */ + * @property {boolean} dirty - If this Body in a preUpdate (true) or postUpdate (false) state? + */ this.dirty = false; /** - * @property {boolean} skipQuadTree - If true and you collide this Sprite against a Group, it will disable the collision check from using a QuadTree. - */ + * @property {boolean} skipQuadTree - If true and you collide this Sprite against a Group, it will disable the collision check from using a QuadTree. + */ this.skipQuadTree = false; /** - * If true the Body will check itself against the Sprite.getBounds() dimensions and adjust its width and height accordingly. - * If false it will compare its dimensions against the Sprite scale instead, and adjust its width height if the scale has changed. - * Typically you would need to enable syncBounds if your sprite is the child of a responsive display object such as a FlexLayer, - * or in any situation where the Sprite scale doesn't change, but its parents scale is effecting the dimensions regardless. - * @property {boolean} syncBounds - * @default - */ + * If true the Body will check itself against the Sprite.getBounds() dimensions and adjust its width and height accordingly. + * If false it will compare its dimensions against the Sprite scale instead, and adjust its width height if the scale has changed. + * Typically you would need to enable syncBounds if your sprite is the child of a responsive display object such as a FlexLayer, + * or in any situation where the Sprite scale doesn't change, but its parents scale is effecting the dimensions regardless. + * @property {boolean} syncBounds + * @default + */ this.syncBounds = false; /** - * @property {boolean} isMoving - Set by the `moveTo` and `moveFrom` methods. - */ + * @property {boolean} isMoving - Set by the `moveTo` and `moveFrom` methods. + */ this.isMoving = false; /** - * @property {boolean} stopVelocityOnCollide - Set by the `moveTo` and `moveFrom` methods. - */ + * @property {boolean} stopVelocityOnCollide - Set by the `moveTo` and `moveFrom` methods. + */ this.stopVelocityOnCollide = true; /** - * @property {integer} moveTimer - Internal time used by the `moveTo` and `moveFrom` methods. - * @private - */ + * @property {integer} moveTimer - Internal time used by the `moveTo` and `moveFrom` methods. + * @private + */ this.moveTimer = 0; /** - * @property {integer} moveDistance - Internal distance value, used by the `moveTo` and `moveFrom` methods. - * @private - */ + * @property {integer} moveDistance - Internal distance value, used by the `moveTo` and `moveFrom` methods. + * @private + */ this.moveDistance = 0; /** - * @property {integer} moveDuration - Internal duration value, used by the `moveTo` and `moveFrom` methods. - * @private - */ + * @property {integer} moveDuration - Internal duration value, used by the `moveTo` and `moveFrom` methods. + * @private + */ this.moveDuration = 0; /** - * @property {Phaser.Line} moveTarget - Set by the `moveTo` method, and updated each frame. - * @private - */ + * @property {Phaser.Line} moveTarget - Set by the `moveTo` method, and updated each frame. + * @private + */ this.moveTarget = null; /** - * @property {Phaser.Point} moveEnd - Set by the `moveTo` method, and updated each frame. - * @private - */ + * @property {Phaser.Point} moveEnd - Set by the `moveTo` method, and updated each frame. + * @private + */ this.moveEnd = null; /** - * @property {Phaser.Signal} onMoveComplete - Listen for the completion of `moveTo` or `moveFrom` events. - */ + * @property {Phaser.Signal} onMoveComplete - Listen for the completion of `moveTo` or `moveFrom` events. + */ this.onMoveComplete = new Phaser.Signal(); /** - * @property {function} movementCallback - Optional callback. If set, invoked during the running of `moveTo` or `moveFrom` events. - */ + * @property {function} movementCallback - Optional callback. If set, invoked during the running of `moveTo` or `moveFrom` events. + */ this.movementCallback = null; /** - * @property {object} movementCallbackContext - Context in which to call the movementCallback. - */ + * @property {object} movementCallbackContext - Context in which to call the movementCallback. + */ this.movementCallbackContext = null; /** - * @property {boolean} _reset - Internal cache var. - * @private - */ + * @property {boolean} _reset - Internal cache var. + * @private + */ this._reset = true; /** - * @property {number} _sx - Internal cache var. - * @private - */ + * @property {number} _sx - Internal cache var. + * @private + */ this._sx = sprite.scale.x; /** - * @property {number} _sy - Internal cache var. - * @private - */ + * @property {number} _sy - Internal cache var. + * @private + */ this._sy = sprite.scale.y; /** - * @property {number} _dx - Internal cache var. - * @private - */ + * @property {number} _dx - Internal cache var. + * @private + */ this._dx = 0; /** - * @property {number} _dy - Internal cache var. - * @private - */ + * @property {number} _dy - Internal cache var. + * @private + */ this._dy = 0; - }; Phaser.Physics.Arcade.Body.prototype = { /** - * Internal method. - * - * @method Phaser.Physics.Arcade.Body#updateBounds - * @protected - */ + * Internal method. + * + * @method Phaser.Physics.Arcade.Body#updateBounds + * @protected + */ updateBounds: function () { - if (this.syncBounds) { var b = this.sprite.getBounds(); @@ -560,31 +557,27 @@ Phaser.Physics.Arcade.Body.prototype = { this.halfHeight = Math.floor(this.height / 2); this.updateCenter(); } - }, /** - * Update the Body's center from its position. - * - * @method Phaser.Physics.Arcade.Body#updateCenter - * @protected - */ + * Update the Body's center from its position. + * + * @method Phaser.Physics.Arcade.Body#updateCenter + * @protected + */ updateCenter: function () { - this.center.setTo(this.position.x + this.halfWidth, this.position.y + this.halfHeight); - }, /** - * Internal method. - * - * @method Phaser.Physics.Arcade.Body#preUpdate - * @protected - */ + * Internal method. + * + * @method Phaser.Physics.Arcade.Body#preUpdate + * @protected + */ preUpdate: function () { - if (!this.enable || this.game.physics.arcade.isPaused) { return; @@ -654,8 +647,10 @@ Phaser.Physics.Arcade.Body.prototype = { this.speed = Math.sqrt(this.velocity.x * this.velocity.x + this.velocity.y * this.velocity.y); - // Now the State update will throw collision checks at the Body - // And finally we'll integrate the new position back to the Sprite in postUpdate + /* + * Now the State update will throw collision checks at the Body + * And finally we'll integrate the new position back to the Sprite in postUpdate + */ if (this.collideWorldBounds) { @@ -670,18 +665,16 @@ Phaser.Physics.Arcade.Body.prototype = { this._dy = this.deltaY(); this._reset = false; - }, /** - * Internal method. - * - * @method Phaser.Physics.Arcade.Body#updateMovement - * @protected - */ + * Internal method. + * + * @method Phaser.Physics.Arcade.Body#updateMovement + * @protected + */ updateMovement: function () { - var percent = 0; var collided = (this.overlapX !== 0 || this.overlapY !== 0); @@ -712,22 +705,20 @@ Phaser.Physics.Arcade.Body.prototype = { } return true; - }, /** - * If this Body is moving as a result of a call to `moveTo` or `moveFrom` (i.e. it - * has Body.isMoving true), then calling this method will stop the movement before - * either the duration or distance counters expire. - * - * The `onMoveComplete` signal is dispatched. - * - * @method Phaser.Physics.Arcade.Body#stopMovement - * @param {boolean} [stopVelocity] - Should the Body.velocity be set to zero? - */ + * If this Body is moving as a result of a call to `moveTo` or `moveFrom` (i.e. it + * has Body.isMoving true), then calling this method will stop the movement before + * either the duration or distance counters expire. + * + * The `onMoveComplete` signal is dispatched. + * + * @method Phaser.Physics.Arcade.Body#stopMovement + * @param {boolean} [stopVelocity] - Should the Body.velocity be set to zero? + */ stopMovement: function (stopVelocity) { - if (this.isMoving) { this.isMoving = false; @@ -737,22 +728,22 @@ Phaser.Physics.Arcade.Body.prototype = { this.velocity.set(0); } - // Send the Sprite this Body belongs to - // and a boolean indicating if it stopped because of a collision or not + /* + * Send the Sprite this Body belongs to + * and a boolean indicating if it stopped because of a collision or not + */ this.onMoveComplete.dispatch(this.sprite, (this.overlapX !== 0 || this.overlapY !== 0)); } - }, /** - * Internal method. - * - * @method Phaser.Physics.Arcade.Body#postUpdate - * @protected - */ + * Internal method. + * + * @method Phaser.Physics.Arcade.Body#postUpdate + * @protected + */ postUpdate: function () { - // Only allow postUpdate to be called once per frame if (!this.enable || !this.dirty) { @@ -828,19 +819,17 @@ Phaser.Physics.Arcade.Body.prototype = { this.prev.x = this.position.x; this.prev.y = this.position.y; - }, /** - * Internal method. - * - * @method Phaser.Physics.Arcade.Body#checkWorldBounds - * @protected - * @return {boolean} True if the Body collided with the world bounds, otherwise false. - */ + * Internal method. + * + * @method Phaser.Physics.Arcade.Body#checkWorldBounds + * @protected + * @return {boolean} True if the Body collided with the world bounds, otherwise false. + */ checkWorldBounds: function () { - var pos = this.position; var bounds = this.game.physics.arcade.bounds; var check = this.game.physics.arcade.checkCollision; @@ -879,42 +868,40 @@ Phaser.Physics.Arcade.Body.prototype = { } return !this.blocked.none; - }, /** - * Note: This method is experimental, and may be changed or removed in a future release. - * - * This method moves the Body in the given direction, for the duration specified. - * It works by setting the velocity on the Body, and an internal timer, and then - * monitoring the duration each frame. When the duration is up the movement is - * stopped and the `Body.onMoveComplete` signal is dispatched. - * - * Movement also stops if the Body collides or overlaps with any other Body. - * - * You can control if the velocity should be reset to zero on collision, by using - * the property `Body.stopVelocityOnCollide`. - * - * Stop the movement at any time by calling `Body.stopMovement`. - * - * You can optionally set a speed in pixels per second. If not specified it - * will use the current `Body.speed` value. If this is zero, the function will return false. - * - * Please note that due to browser timings you should allow for a variance in - * when the duration will actually expire. Depending on system it may be as much as - * +- 50ms. Also this method doesn't take into consideration any other forces acting - * on the Body, such as Gravity, drag or maxVelocity, all of which may impact the - * movement. - * - * @method Phaser.Physics.Arcade.Body#moveFrom - * @param {integer} duration - The duration of the movement, in ms. - * @param {integer} [speed] - The speed of the movement, in pixels per second. If not provided `Body.speed` is used. - * @param {integer} [direction] - The angle of movement. If not provided `Body.angle` is used. - * @return {boolean} True if the movement successfully started, otherwise false. - */ + * Note: This method is experimental, and may be changed or removed in a future release. + * + * This method moves the Body in the given direction, for the duration specified. + * It works by setting the velocity on the Body, and an internal timer, and then + * monitoring the duration each frame. When the duration is up the movement is + * stopped and the `Body.onMoveComplete` signal is dispatched. + * + * Movement also stops if the Body collides or overlaps with any other Body. + * + * You can control if the velocity should be reset to zero on collision, by using + * the property `Body.stopVelocityOnCollide`. + * + * Stop the movement at any time by calling `Body.stopMovement`. + * + * You can optionally set a speed in pixels per second. If not specified it + * will use the current `Body.speed` value. If this is zero, the function will return false. + * + * Please note that due to browser timings you should allow for a variance in + * when the duration will actually expire. Depending on system it may be as much as + * +- 50ms. Also this method doesn't take into consideration any other forces acting + * on the Body, such as Gravity, drag or maxVelocity, all of which may impact the + * movement. + * + * @method Phaser.Physics.Arcade.Body#moveFrom + * @param {integer} duration - The duration of the movement, in ms. + * @param {integer} [speed] - The speed of the movement, in pixels per second. If not provided `Body.speed` is used. + * @param {integer} [direction] - The angle of movement. If not provided `Body.angle` is used. + * @return {boolean} True if the movement successfully started, otherwise false. + */ moveFrom: function (duration, speed, direction) { - if (speed === undefined) { speed = this.speed; } if (speed === 0) @@ -954,41 +941,39 @@ Phaser.Physics.Arcade.Body.prototype = { this.isMoving = true; return true; - }, /** - * Note: This method is experimental, and may be changed or removed in a future release. - * - * This method moves the Body in the given direction, for the duration specified. - * It works by setting the velocity on the Body, and an internal distance counter. - * The distance is monitored each frame. When the distance equals the distance - * specified in this call, the movement is stopped, and the `Body.onMoveComplete` - * signal is dispatched. - * - * Movement also stops if the Body collides or overlaps with any other Body. - * - * You can control if the velocity should be reset to zero on collision, by using - * the property `Body.stopVelocityOnCollide`. - * - * Stop the movement at any time by calling `Body.stopMovement`. - * - * Please note that due to browser timings you should allow for a variance in - * when the distance will actually expire. - * - * Note: This method doesn't take into consideration any other forces acting - * on the Body, such as Gravity, drag or maxVelocity, all of which may impact the - * movement. - * - * @method Phaser.Physics.Arcade.Body#moveTo - * @param {integer} duration - The duration of the movement, in ms. - * @param {integer} distance - The distance, in pixels, the Body will move. - * @param {integer} [direction] - The angle of movement. If not provided `Body.angle` is used. - * @return {boolean} True if the movement successfully started, otherwise false. - */ + * Note: This method is experimental, and may be changed or removed in a future release. + * + * This method moves the Body in the given direction, for the duration specified. + * It works by setting the velocity on the Body, and an internal distance counter. + * The distance is monitored each frame. When the distance equals the distance + * specified in this call, the movement is stopped, and the `Body.onMoveComplete` + * signal is dispatched. + * + * Movement also stops if the Body collides or overlaps with any other Body. + * + * You can control if the velocity should be reset to zero on collision, by using + * the property `Body.stopVelocityOnCollide`. + * + * Stop the movement at any time by calling `Body.stopMovement`. + * + * Please note that due to browser timings you should allow for a variance in + * when the distance will actually expire. + * + * Note: This method doesn't take into consideration any other forces acting + * on the Body, such as Gravity, drag or maxVelocity, all of which may impact the + * movement. + * + * @method Phaser.Physics.Arcade.Body#moveTo + * @param {integer} duration - The duration of the movement, in ms. + * @param {integer} distance - The distance, in pixels, the Body will move. + * @param {integer} [direction] - The angle of movement. If not provided `Body.angle` is used. + * @return {boolean} True if the movement successfully started, otherwise false. + */ moveTo: function (duration, distance, direction) { - var speed = distance / (duration / 1000); if (speed === 0) @@ -1042,52 +1027,50 @@ Phaser.Physics.Arcade.Body.prototype = { this.isMoving = true; return true; - }, /** - * You can modify the size of the physics Body to be any dimension you need. - * This allows you to make it smaller, or larger, than the parent Sprite. You - * can also control the x and y offset of the Body. - * - * The width, height, and offset arguments are relative to the Sprite - * _texture_ and are scaled with the Sprite's {@link Phaser.Sprite#scale} - * (but **not** the scale of any ancestors or the {@link Phaser.Camera#scale - * Camera scale}). - * - * For example: If you have a Sprite with a texture that is 80x100 in size, - * and you want the physics body to be 32x32 pixels in the middle of the - * texture, you would do: - * - * `setSize(32 / Math.abs(this.scale.x), 32 / Math.abs(this.scale.y), 24, - * 34)` - * - * Where the first two parameters are the new Body size (32x32 pixels) - * relative to the Sprite's scale. 24 is the horizontal offset of the Body - * from the top-left of the Sprites texture, and 34 is the vertical offset. - * - * If you've scaled a Sprite by altering its `width`, `height`, or `scale` - * and you want to position the Body relative to the Sprite's dimensions - * (which will differ from its texture's dimensions), you should divide these - * arguments by the Sprite's current scale: - * - * `setSize(32 / sprite.scale.x, 32 / sprite.scale.y)` - * - * Calling `setSize` on a Body that has already had `setCircle` will reset - * all of the Circle properties, making this Body rectangular again. - * @method Phaser.Physics.Arcade.Body#setSize - * @param {number} width - The width of the Body, relative to the Sprite's - * texture. - * @param {number} height - The height of the Body, relative to the Sprite's - * texture. - * @param {number} [offsetX] - The X offset of the Body from the left of the - * Sprite's texture. - * @param {number} [offsetY] - The Y offset of the Body from the top of the - * Sprite's texture. - */ + * You can modify the size of the physics Body to be any dimension you need. + * This allows you to make it smaller, or larger, than the parent Sprite. You + * can also control the x and y offset of the Body. + * + * The width, height, and offset arguments are relative to the Sprite + * _texture_ and are scaled with the Sprite's {@link Phaser.Sprite#scale} + * (but **not** the scale of any ancestors or the {@link Phaser.Camera#scale + * Camera scale}). + * + * For example: If you have a Sprite with a texture that is 80x100 in size, + * and you want the physics body to be 32x32 pixels in the middle of the + * texture, you would do: + * + * `setSize(32 / Math.abs(this.scale.x), 32 / Math.abs(this.scale.y), 24, + * 34)` + * + * Where the first two parameters are the new Body size (32x32 pixels) + * relative to the Sprite's scale. 24 is the horizontal offset of the Body + * from the top-left of the Sprites texture, and 34 is the vertical offset. + * + * If you've scaled a Sprite by altering its `width`, `height`, or `scale` + * and you want to position the Body relative to the Sprite's dimensions + * (which will differ from its texture's dimensions), you should divide these + * arguments by the Sprite's current scale: + * + * `setSize(32 / sprite.scale.x, 32 / sprite.scale.y)` + * + * Calling `setSize` on a Body that has already had `setCircle` will reset + * all of the Circle properties, making this Body rectangular again. + * @method Phaser.Physics.Arcade.Body#setSize + * @param {number} width - The width of the Body, relative to the Sprite's + * texture. + * @param {number} height - The height of the Body, relative to the Sprite's + * texture. + * @param {number} [offsetX] - The X offset of the Body from the left of the + * Sprite's texture. + * @param {number} [offsetY] - The Y offset of the Body from the top of the + * Sprite's texture. + */ setSize: function (width, height, offsetX, offsetY) { - if (offsetX === undefined) { offsetX = this.offset.x; } if (offsetY === undefined) { offsetY = this.offset.y; } @@ -1103,28 +1086,26 @@ Phaser.Physics.Arcade.Body.prototype = { this.isCircle = false; this.radius = 0; - }, /** - * Sets this Body as using a circle, of the given radius, for all collision detection instead of a rectangle. - * The radius is given in pixels (relative to the Sprite's _texture_) and is the distance from the center of the circle to the edge. - * - * You can also control the x and y offset, which is the position of the Body relative to the top-left of the Sprite's texture. - * - * To change a Body back to being rectangular again call `Body.setSize`. - * - * Note: Circular collision only happens with other Arcade Physics bodies, it does not - * work against tile maps, where rectangular collision is the only method supported. - * - * @method Phaser.Physics.Arcade.Body#setCircle - * @param {number} [radius] - The radius of the Body in pixels. Pass a value of zero / undefined, to stop the Body using a circle for collision. - * @param {number} [offsetX] - The X offset of the Body from the left of the Sprite's texture. - * @param {number} [offsetY] - The Y offset of the Body from the top of the Sprite's texture. - */ + * Sets this Body as using a circle, of the given radius, for all collision detection instead of a rectangle. + * The radius is given in pixels (relative to the Sprite's _texture_) and is the distance from the center of the circle to the edge. + * + * You can also control the x and y offset, which is the position of the Body relative to the top-left of the Sprite's texture. + * + * To change a Body back to being rectangular again call `Body.setSize`. + * + * Note: Circular collision only happens with other Arcade Physics bodies, it does not + * work against tile maps, where rectangular collision is the only method supported. + * + * @method Phaser.Physics.Arcade.Body#setCircle + * @param {number} [radius] - The radius of the Body in pixels. Pass a value of zero / undefined, to stop the Body using a circle for collision. + * @param {number} [offsetX] - The X offset of the Body from the left of the Sprite's texture. + * @param {number} [offsetY] - The Y offset of the Body from the top of the Sprite's texture. + */ setCircle: function (radius, offsetX, offsetY) { - if (offsetX === undefined) { offsetX = this.offset.x; } if (offsetY === undefined) { offsetY = this.offset.y; } @@ -1150,19 +1131,17 @@ Phaser.Physics.Arcade.Body.prototype = { { this.isCircle = false; } - }, /** - * Resets all Body values (velocity, acceleration, rotation, etc) - * - * @method Phaser.Physics.Arcade.Body#reset - * @param {number} x - The new x position of the Body. - * @param {number} y - The new y position of the Body. - */ + * Resets all Body values (velocity, acceleration, rotation, etc) + * + * @method Phaser.Physics.Arcade.Body#reset + * @param {number} x - The new x position of the Body. + * @param {number} y - The new y position of the Body. + */ reset: function (x, y) { - this.stop(); this.position.x = (x - (this.sprite.anchor.x * this.sprite.width)) + this.sprite.scale.x * this.offset.x; @@ -1180,7 +1159,6 @@ Phaser.Physics.Arcade.Body.prototype = { this.updateBounds(); this.updateCenter(); - }, /** @@ -1190,166 +1168,143 @@ Phaser.Physics.Arcade.Body.prototype = { */ stop: function () { - this.velocity.set(0); this.acceleration.set(0); this.speed = 0; this.angularVelocity = 0; this.angularAcceleration = 0; - }, /** - * Returns the bounds of this physics body. - * - * Only used internally by the World collision methods. - * - * @method Phaser.Physics.Arcade.Body#getBounds - * @param {object} obj - The object in which to set the bounds values. - * @return {object} The object that was given to this method. - */ + * Returns the bounds of this physics body. + * + * Only used internally by the World collision methods. + * + * @method Phaser.Physics.Arcade.Body#getBounds + * @param {object} obj - The object in which to set the bounds values. + * @return {object} The object that was given to this method. + */ getBounds: function (obj) { - obj.x = this.x; obj.y = this.y; obj.right = this.right; obj.bottom = this.bottom; return obj; - }, /** - * Tests if a world point lies within this Body. - * - * @method Phaser.Physics.Arcade.Body#hitTest - * @param {number} x - The world x coordinate to test. - * @param {number} y - The world y coordinate to test. - * @return {boolean} True if the given coordinates are inside this Body, otherwise false. - */ + * Tests if a world point lies within this Body. + * + * @method Phaser.Physics.Arcade.Body#hitTest + * @param {number} x - The world x coordinate to test. + * @param {number} y - The world y coordinate to test. + * @return {boolean} True if the given coordinates are inside this Body, otherwise false. + */ hitTest: function (x, y) { - return (this.isCircle) ? Phaser.Circle.contains(this, x, y) : Phaser.Rectangle.contains(this, x, y); - }, /** - * Returns true if the bottom of this Body is in contact with either the world bounds or a tile. - * - * @method Phaser.Physics.Arcade.Body#onFloor - * @return {boolean} True if in contact with either the world bounds or a tile. - */ + * Returns true if the bottom of this Body is in contact with either the world bounds or a tile. + * + * @method Phaser.Physics.Arcade.Body#onFloor + * @return {boolean} True if in contact with either the world bounds or a tile. + */ onFloor: function () { - return this.blocked.down; - }, /** - * Returns true if the top of this Body is in contact with either the world bounds or a tile. - * - * @method Phaser.Physics.Arcade.Body#onCeiling - * @return {boolean} True if in contact with either the world bounds or a tile. - */ + * Returns true if the top of this Body is in contact with either the world bounds or a tile. + * + * @method Phaser.Physics.Arcade.Body#onCeiling + * @return {boolean} True if in contact with either the world bounds or a tile. + */ onCeiling: function () { - return this.blocked.up; - }, /** - * Returns true if either side of this Body is in contact with either the world bounds or a tile. - * - * @method Phaser.Physics.Arcade.Body#onWall - * @return {boolean} True if in contact with either the world bounds or a tile. - */ + * Returns true if either side of this Body is in contact with either the world bounds or a tile. + * + * @method Phaser.Physics.Arcade.Body#onWall + * @return {boolean} True if in contact with either the world bounds or a tile. + */ onWall: function () { - return (this.blocked.left || this.blocked.right); - }, /** - * Returns the absolute delta x value. - * - * @method Phaser.Physics.Arcade.Body#deltaAbsX - * @return {number} The absolute delta value. - */ + * Returns the absolute delta x value. + * + * @method Phaser.Physics.Arcade.Body#deltaAbsX + * @return {number} The absolute delta value. + */ deltaAbsX: function () { - return (this.deltaX() > 0 ? this.deltaX() : -this.deltaX()); - }, /** - * Returns the absolute delta y value. - * - * @method Phaser.Physics.Arcade.Body#deltaAbsY - * @return {number} The absolute delta value. - */ + * Returns the absolute delta y value. + * + * @method Phaser.Physics.Arcade.Body#deltaAbsY + * @return {number} The absolute delta value. + */ deltaAbsY: function () { - return (this.deltaY() > 0 ? this.deltaY() : -this.deltaY()); - }, /** - * Returns the delta x value. The difference between Body.x now and in the previous step. - * - * @method Phaser.Physics.Arcade.Body#deltaX - * @return {number} The delta value. Positive if the motion was to the right, negative if to the left. - */ + * Returns the delta x value. The difference between Body.x now and in the previous step. + * + * @method Phaser.Physics.Arcade.Body#deltaX + * @return {number} The delta value. Positive if the motion was to the right, negative if to the left. + */ deltaX: function () { - return this.position.x - this.prev.x; - }, /** - * Returns the delta y value. The difference between Body.y now and in the previous step. - * - * @method Phaser.Physics.Arcade.Body#deltaY - * @return {number} The delta value. Positive if the motion was downwards, negative if upwards. - */ + * Returns the delta y value. The difference between Body.y now and in the previous step. + * + * @method Phaser.Physics.Arcade.Body#deltaY + * @return {number} The delta value. Positive if the motion was downwards, negative if upwards. + */ deltaY: function () { - return this.position.y - this.prev.y; - }, /** - * Returns the delta z value. The difference between Body.rotation now and in the previous step. - * - * @method Phaser.Physics.Arcade.Body#deltaZ - * @return {number} The delta value. Positive if the motion was clockwise, negative if anti-clockwise. - */ + * Returns the delta z value. The difference between Body.rotation now and in the previous step. + * + * @method Phaser.Physics.Arcade.Body#deltaZ + * @return {number} The delta value. Positive if the motion was clockwise, negative if anti-clockwise. + */ deltaZ: function () { - return this.rotation - this.preRotation; - }, /** - * Destroys this Body. - * - * First it calls Group.removeFromHash if the Game Object this Body belongs to is part of a Group. - * Then it nulls the Game Objects body reference, and nulls this Body.sprite reference. - * - * @method Phaser.Physics.Arcade.Body#destroy - */ + * Destroys this Body. + * + * First it calls Group.removeFromHash if the Game Object this Body belongs to is part of a Group. + * Then it nulls the Game Objects body reference, and nulls this Body.sprite reference. + * + * @method Phaser.Physics.Arcade.Body#destroy + */ destroy: function () { - if (this.sprite.parent && this.sprite.parent instanceof Phaser.Group) { this.sprite.parent.removeFromHash(this.sprite); @@ -1357,129 +1312,112 @@ Phaser.Physics.Arcade.Body.prototype = { this.sprite.body = null; this.sprite = null; - } }; /** -* @name Phaser.Physics.Arcade.Body#left -* @property {number} left - The x position of the Body. The same as `Body.x`. -*/ + * @name Phaser.Physics.Arcade.Body#left + * @property {number} left - The x position of the Body. The same as `Body.x`. + */ Object.defineProperty(Phaser.Physics.Arcade.Body.prototype, 'left', { get: function () { - return this.position.x; - } }); /** -* @name Phaser.Physics.Arcade.Body#right -* @property {number} right - The right value of this Body (same as Body.x + Body.width) -* @readonly -*/ + * @name Phaser.Physics.Arcade.Body#right + * @property {number} right - The right value of this Body (same as Body.x + Body.width) + * @readonly + */ Object.defineProperty(Phaser.Physics.Arcade.Body.prototype, 'right', { get: function () { - return this.position.x + this.width; - } }); /** -* @name Phaser.Physics.Arcade.Body#top -* @property {number} top - The y position of the Body. The same as `Body.y`. -*/ + * @name Phaser.Physics.Arcade.Body#top + * @property {number} top - The y position of the Body. The same as `Body.y`. + */ Object.defineProperty(Phaser.Physics.Arcade.Body.prototype, 'top', { get: function () { - return this.position.y; - } }); /** -* @name Phaser.Physics.Arcade.Body#bottom -* @property {number} bottom - The bottom value of this Body (same as Body.y + Body.height) -* @readonly -*/ + * @name Phaser.Physics.Arcade.Body#bottom + * @property {number} bottom - The bottom value of this Body (same as Body.y + Body.height) + * @readonly + */ Object.defineProperty(Phaser.Physics.Arcade.Body.prototype, 'bottom', { get: function () { - return this.position.y + this.height; - } }); /** -* @name Phaser.Physics.Arcade.Body#x -* @property {number} x - The x position. -*/ + * @name Phaser.Physics.Arcade.Body#x + * @property {number} x - The x position. + */ Object.defineProperty(Phaser.Physics.Arcade.Body.prototype, 'x', { get: function () { - return this.position.x; - }, set: function (value) { - this.position.x = value; } }); /** -* @name Phaser.Physics.Arcade.Body#y -* @property {number} y - The y position. -*/ + * @name Phaser.Physics.Arcade.Body#y + * @property {number} y - The y position. + */ Object.defineProperty(Phaser.Physics.Arcade.Body.prototype, 'y', { get: function () { - return this.position.y; - }, set: function (value) { - this.position.y = value; - } }); /** -* Render Sprite Body. -* -* @method Phaser.Physics.Arcade.Body#render -* @param {object} context - The context to render to. -* @param {Phaser.Physics.Arcade.Body} body - The Body to render the info of. -* @param {string} [color='rgba(0,255,0,0.4)'] - color of the debug info to be rendered. (format is css color string). -* @param {boolean} [filled=true] - Render the objected as a filled (default, true) or a stroked (false) -* @param {number} [lineWidth=1] - The width of the stroke when unfilled. -*/ + * Render Sprite Body. + * + * @method Phaser.Physics.Arcade.Body#render + * @param {object} context - The context to render to. + * @param {Phaser.Physics.Arcade.Body} body - The Body to render the info of. + * @param {string} [color='rgba(0,255,0,0.4)'] - color of the debug info to be rendered. (format is css color string). + * @param {boolean} [filled=true] - Render the objected as a filled (default, true) or a stroked (false) + * @param {number} [lineWidth=1] - The width of the stroke when unfilled. + */ Phaser.Physics.Arcade.Body.render = function (context, body, color, filled, lineWidth) { - if (filled === undefined) { filled = true; } color = color || 'rgba(0,255,0,0.4)'; @@ -1511,28 +1449,25 @@ Phaser.Physics.Arcade.Body.render = function (context, body, color, filled, line { context.strokeRect(body.position.x - body.game.camera.x, body.position.y - body.game.camera.y, body.width, body.height); } - }; /** -* Render Sprite Body Physics Data as text. -* -* @method Phaser.Physics.Arcade.Body#renderBodyInfo -* @param {Phaser.Physics.Arcade.Body} body - The Body to render the info of. -* @param {number} x - X position of the debug info to be rendered. -* @param {number} y - Y position of the debug info to be rendered. -* @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). -*/ + * Render Sprite Body Physics Data as text. + * + * @method Phaser.Physics.Arcade.Body#renderBodyInfo + * @param {Phaser.Physics.Arcade.Body} body - The Body to render the info of. + * @param {number} x - X position of the debug info to be rendered. + * @param {number} y - Y position of the debug info to be rendered. + * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). + */ Phaser.Physics.Arcade.Body.renderBodyInfo = function (debug, body) { - debug.line('x: ' + body.x.toFixed(2), 'y: ' + body.y.toFixed(2), 'width: ' + body.width, 'height: ' + body.height); debug.line('velocity x: ' + body.velocity.x.toFixed(2), 'y: ' + body.velocity.y.toFixed(2), 'deltaX: ' + body._dx.toFixed(2), 'deltaY: ' + body._dy.toFixed(2)); debug.line('acceleration x: ' + body.acceleration.x.toFixed(2), 'y: ' + body.acceleration.y.toFixed(2), 'speed: ' + body.speed.toFixed(2), 'angle: ' + body.angle.toFixed(2)); debug.line('gravity x: ' + body.gravity.x, 'y: ' + body.gravity.y, 'bounce x: ' + body.bounce.x.toFixed(2), 'y: ' + body.bounce.y.toFixed(2)); debug.line('touching left: ' + body.touching.left, 'right: ' + body.touching.right, 'up: ' + body.touching.up, 'down: ' + body.touching.down); debug.line('blocked left: ' + body.blocked.left, 'right: ' + body.blocked.right, 'up: ' + body.blocked.up, 'down: ' + body.blocked.down); - }; Phaser.Physics.Arcade.Body.prototype.constructor = Phaser.Physics.Arcade.Body; diff --git a/src/physics/arcade/TilemapCollision.js b/src/physics/arcade/TilemapCollision.js index 09c34eeb7..fb6b24b96 100644 --- a/src/physics/arcade/TilemapCollision.js +++ b/src/physics/arcade/TilemapCollision.js @@ -1,41 +1,40 @@ /** -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* The Arcade Physics Tile map collision methods. -* -* These are mixed into {@link Phaser.Physics.Arcade}. -* -* @class Phaser.Physics.Arcade.TilemapCollision -* @constructor -*/ + * The Arcade Physics Tile map collision methods. + * + * These are mixed into {@link Phaser.Physics.Arcade}. + * + * @class Phaser.Physics.Arcade.TilemapCollision + * @constructor + */ Phaser.Physics.Arcade.TilemapCollision = function () {}; Phaser.Physics.Arcade.TilemapCollision.prototype = { /** - * @property {number} TILE_BIAS - A value added to the delta values during collision with tiles. The best value probably depends on your tile size. Increase it if sprites are tunneling; decrease it if sprites are flipping across tile edges. - */ + * @property {number} TILE_BIAS - A value added to the delta values during collision with tiles. The best value probably depends on your tile size. Increase it if sprites are tunneling; decrease it if sprites are flipping across tile edges. + */ TILE_BIAS: 16, /** - * An internal function. Use Phaser.Physics.Arcade.collide instead. - * - * @method Phaser.Physics.Arcade#collideSpriteVsTilemapLayer - * @private - * @param {Phaser.Sprite} sprite - The sprite to check. - * @param {Phaser.TilemapLayer} tilemapLayer - The layer to check. - * @param {function} collideCallback - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them. - * @param {function} processCallback - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them. - * @param {object} callbackContext - The context in which to run the callbacks. - * @param {boolean} overlapOnly - Just run an overlap or a full collision. - */ + * An internal function. Use Phaser.Physics.Arcade.collide instead. + * + * @method Phaser.Physics.Arcade#collideSpriteVsTilemapLayer + * @private + * @param {Phaser.Sprite} sprite - The sprite to check. + * @param {Phaser.TilemapLayer} tilemapLayer - The layer to check. + * @param {function} collideCallback - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them. + * @param {function} processCallback - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them. + * @param {object} callbackContext - The context in which to run the callbacks. + * @param {boolean} overlapOnly - Just run an overlap or a full collision. + */ collideSpriteVsTilemapLayer: function (sprite, tilemapLayer, collideCallback, processCallback, callbackContext, overlapOnly) { - if (!sprite.body) { return; @@ -81,24 +80,22 @@ Phaser.Physics.Arcade.TilemapCollision.prototype = { } } } - }, /** - * An internal function. Use Phaser.Physics.Arcade.collide instead. - * - * @private - * @method Phaser.Physics.Arcade#collideGroupVsTilemapLayer - * @param {Phaser.Group} group - The Group to check. - * @param {Phaser.TilemapLayer} tilemapLayer - The layer to check. - * @param {function} collideCallback - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them. - * @param {function} processCallback - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them. - * @param {object} callbackContext - The context in which to run the callbacks. - * @param {boolean} overlapOnly - Just run an overlap or a full collision. - */ + * An internal function. Use Phaser.Physics.Arcade.collide instead. + * + * @private + * @method Phaser.Physics.Arcade#collideGroupVsTilemapLayer + * @param {Phaser.Group} group - The Group to check. + * @param {Phaser.TilemapLayer} tilemapLayer - The layer to check. + * @param {function} collideCallback - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them. + * @param {function} processCallback - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them. + * @param {object} callbackContext - The context in which to run the callbacks. + * @param {boolean} overlapOnly - Just run an overlap or a full collision. + */ collideGroupVsTilemapLayer: function (group, tilemapLayer, collideCallback, processCallback, callbackContext, overlapOnly) { - if (group.length === 0) { return; @@ -111,22 +108,20 @@ Phaser.Physics.Arcade.TilemapCollision.prototype = { this.collideSpriteVsTilemapLayer(group.children[i], tilemapLayer, collideCallback, processCallback, callbackContext, overlapOnly); } } - }, /** - * The core separation function to separate a physics body and a tile. - * - * @private - * @method Phaser.Physics.Arcade#separateTile - * @param {Phaser.Physics.Arcade.Body} body - The Body object to separate. - * @param {Phaser.Tile} tile - The tile to collide against. - * @param {Phaser.TilemapLayer} tilemapLayer - The tilemapLayer to collide against. - * @return {boolean} Returns true if the body was separated, otherwise false. - */ + * The core separation function to separate a physics body and a tile. + * + * @private + * @method Phaser.Physics.Arcade#separateTile + * @param {Phaser.Physics.Arcade.Body} body - The Body object to separate. + * @param {Phaser.Tile} tile - The tile to collide against. + * @param {Phaser.TilemapLayer} tilemapLayer - The tilemapLayer to collide against. + * @return {boolean} Returns true if the body was separated, otherwise false. + */ separateTile: function (i, body, tile, tilemapLayer, overlapOnly) { - if (!body.enable) { return false; @@ -229,22 +224,20 @@ Phaser.Physics.Arcade.TilemapCollision.prototype = { } return (ox !== 0 || oy !== 0); - }, /** - * Check the body against the given tile on the X axis. - * - * @private - * @method Phaser.Physics.Arcade#tileCheckX - * @param {Phaser.Physics.Arcade.Body} body - The Body object to separate. - * @param {Phaser.Tile} tile - The tile to check. - * @param {Phaser.TilemapLayer} tilemapLayer - The tilemapLayer to collide against. - * @return {number} The amount of separation that occurred. - */ + * Check the body against the given tile on the X axis. + * + * @private + * @method Phaser.Physics.Arcade#tileCheckX + * @param {Phaser.Physics.Arcade.Body} body - The Body object to separate. + * @param {Phaser.Tile} tile - The tile to check. + * @param {Phaser.TilemapLayer} tilemapLayer - The tilemapLayer to collide against. + * @return {number} The amount of separation that occurred. + */ tileCheckX: function (body, tile, tilemapLayer) { - var ox = 0; var tilemapLayerOffsetX = tilemapLayer.getTileOffsetX(); @@ -288,22 +281,20 @@ Phaser.Physics.Arcade.TilemapCollision.prototype = { } return ox; - }, /** - * Check the body against the given tile on the Y axis. - * - * @private - * @method Phaser.Physics.Arcade#tileCheckY - * @param {Phaser.Physics.Arcade.Body} body - The Body object to separate. - * @param {Phaser.Tile} tile - The tile to check. - * @param {Phaser.TilemapLayer} tilemapLayer - The tilemapLayer to collide against. - * @return {number} The amount of separation that occurred. - */ + * Check the body against the given tile on the Y axis. + * + * @private + * @method Phaser.Physics.Arcade#tileCheckY + * @param {Phaser.Physics.Arcade.Body} body - The Body object to separate. + * @param {Phaser.Tile} tile - The tile to check. + * @param {Phaser.TilemapLayer} tilemapLayer - The tilemapLayer to collide against. + * @return {number} The amount of separation that occurred. + */ tileCheckY: function (body, tile, tilemapLayer) { - var oy = 0; var tilemapLayerOffsetY = tilemapLayer.getTileOffsetY(); @@ -347,20 +338,18 @@ Phaser.Physics.Arcade.TilemapCollision.prototype = { } return oy; - }, /** - * Internal function to process the separation of a physics body from a tile. - * - * @private - * @method Phaser.Physics.Arcade#processTileSeparationX - * @param {Phaser.Physics.Arcade.Body} body - The Body object to separate. - * @param {number} x - The x separation amount. - */ + * Internal function to process the separation of a physics body from a tile. + * + * @private + * @method Phaser.Physics.Arcade#processTileSeparationX + * @param {Phaser.Physics.Arcade.Body} body - The Body object to separate. + * @param {number} x - The x separation amount. + */ processTileSeparationX: function (body, x) { - if (x < 0) { body.blocked.left = true; @@ -382,20 +371,18 @@ Phaser.Physics.Arcade.TilemapCollision.prototype = { { body.velocity.x = -body.velocity.x * body.bounce.x; } - }, /** - * Internal function to process the separation of a physics body from a tile. - * - * @private - * @method Phaser.Physics.Arcade#processTileSeparationY - * @param {Phaser.Physics.Arcade.Body} body - The Body object to separate. - * @param {number} y - The y separation amount. - */ + * Internal function to process the separation of a physics body from a tile. + * + * @private + * @method Phaser.Physics.Arcade#processTileSeparationY + * @param {Phaser.Physics.Arcade.Body} body - The Body object to separate. + * @param {number} y - The y separation amount. + */ processTileSeparationY: function (body, y) { - if (y < 0) { body.blocked.up = true; @@ -417,7 +404,6 @@ Phaser.Physics.Arcade.TilemapCollision.prototype = { { body.velocity.y = -body.velocity.y * body.bounce.y; } - } }; diff --git a/src/physics/arcade/World.js b/src/physics/arcade/World.js index dea5a6432..90bf4c1fc 100644 --- a/src/physics/arcade/World.js +++ b/src/physics/arcade/World.js @@ -1,177 +1,170 @@ /** -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* The Arcade Physics world. Contains Arcade Physics related collision, overlap and motion methods. -* -* @class Phaser.Physics.Arcade -* @constructor -* @param {Phaser.Game} game - reference to the current game instance. -*/ + * The Arcade Physics world. Contains Arcade Physics related collision, overlap and motion methods. + * + * @class Phaser.Physics.Arcade + * @constructor + * @param {Phaser.Game} game - reference to the current game instance. + */ Phaser.Physics.Arcade = function (game) { - /** - * @property {Phaser.Game} game - Local reference to game. - */ + * @property {Phaser.Game} game - Local reference to game. + */ this.game = game; /** - * @property {Phaser.Point} gravity - The World gravity setting. Defaults to x: 0, y: 0, or no gravity. - */ + * @property {Phaser.Point} gravity - The World gravity setting. Defaults to x: 0, y: 0, or no gravity. + */ this.gravity = new Phaser.Point(); /** - * @property {Phaser.Rectangle} bounds - The bounds inside of which the physics world exists. Defaults to match the world bounds. - */ + * @property {Phaser.Rectangle} bounds - The bounds inside of which the physics world exists. Defaults to match the world bounds. + */ this.bounds = new Phaser.Rectangle(0, 0, game.world.width, game.world.height); /** - * Which edges of the World bounds Bodies can collide against when `collideWorldBounds` is `true`. - * For example checkCollision.down = false means Bodies cannot collide with the World.bounds.bottom. - * @property {object} checkCollision - An object containing allowed collision flags (up, down, left, right). - */ + * Which edges of the World bounds Bodies can collide against when `collideWorldBounds` is `true`. + * For example checkCollision.down = false means Bodies cannot collide with the World.bounds.bottom. + * @property {object} checkCollision - An object containing allowed collision flags (up, down, left, right). + */ this.checkCollision = { up: true, down: true, left: true, right: true }; /** - * @property {number} maxObjects - Used by the QuadTree to set the maximum number of objects per quad. - */ + * @property {number} maxObjects - Used by the QuadTree to set the maximum number of objects per quad. + */ this.maxObjects = 10; /** - * @property {number} maxLevels - Used by the QuadTree to set the maximum number of iteration levels. - */ + * @property {number} maxLevels - Used by the QuadTree to set the maximum number of iteration levels. + */ this.maxLevels = 4; /** - * @property {number} OVERLAP_BIAS - A value added to the delta values during collision checks. Increase it to prevent sprite tunneling. - * @default - */ + * @property {number} OVERLAP_BIAS - A value added to the delta values during collision checks. Increase it to prevent sprite tunneling. + * @default + */ this.OVERLAP_BIAS = 4; /** - * @property {boolean} forceX - If true World.separate will always separate on the X axis before Y. Otherwise it will check gravity totals first. - */ + * @property {boolean} forceX - If true World.separate will always separate on the X axis before Y. Otherwise it will check gravity totals first. + */ this.forceX = false; /** - * @property {number} sortDirection - Used when colliding a Sprite vs. a Group, or a Group vs. a Group, this defines the direction the sort is based on. Default is Phaser.Physics.Arcade.LEFT_RIGHT. - * @default - */ + * @property {number} sortDirection - Used when colliding a Sprite vs. a Group, or a Group vs. a Group, this defines the direction the sort is based on. Default is Phaser.Physics.Arcade.LEFT_RIGHT. + * @default + */ this.sortDirection = Phaser.Physics.Arcade.LEFT_RIGHT; /** - * @property {boolean} skipQuadTree - If true the QuadTree will not be used for any collision. QuadTrees are great if objects are well spread out in your game, otherwise they are a performance hit. If you enable this you can disable on a per body basis via `Body.skipQuadTree`. - */ + * @property {boolean} skipQuadTree - If true the QuadTree will not be used for any collision. QuadTrees are great if objects are well spread out in your game, otherwise they are a performance hit. If you enable this you can disable on a per body basis via `Body.skipQuadTree`. + */ this.skipQuadTree = true; /** - * @property {boolean} isPaused - If `true` the `Body.preUpdate` method will be skipped, halting all motion for all bodies. Note that other methods such as `collide` will still work, so be careful not to call them on paused bodies. - */ + * @property {boolean} isPaused - If `true` the `Body.preUpdate` method will be skipped, halting all motion for all bodies. Note that other methods such as `collide` will still work, so be careful not to call them on paused bodies. + */ this.isPaused = false; /** - * @property {Phaser.QuadTree} quadTree - The world QuadTree. - */ + * @property {Phaser.QuadTree} quadTree - The world QuadTree. + */ this.quadTree = new Phaser.QuadTree(this.game.world.bounds.x, this.game.world.bounds.y, this.game.world.bounds.width, this.game.world.bounds.height, this.maxObjects, this.maxLevels); /** - * @property {number} _total - Internal cache var. - * @private - */ + * @property {number} _total - Internal cache var. + * @private + */ this._total = 0; // By default we want the bounds the same size as the world bounds this.setBoundsToWorld(); - }; Phaser.Physics.Arcade.prototype.constructor = Phaser.Physics.Arcade; /** -* A constant used for the sortDirection value. -* Use this if you don't wish to perform any pre-collision sorting at all, or will manually sort your Groups. -* @constant -* @type {number} -*/ + * A constant used for the sortDirection value. + * Use this if you don't wish to perform any pre-collision sorting at all, or will manually sort your Groups. + * @constant + * @type {number} + */ Phaser.Physics.Arcade.SORT_NONE = 0; /** -* A constant used for the sortDirection value. -* Use this if your game world is wide but short and scrolls from the left to the right (i.e. Mario) -* @constant -* @type {number} -*/ + * A constant used for the sortDirection value. + * Use this if your game world is wide but short and scrolls from the left to the right (i.e. Mario) + * @constant + * @type {number} + */ Phaser.Physics.Arcade.LEFT_RIGHT = 1; /** -* A constant used for the sortDirection value. -* Use this if your game world is wide but short and scrolls from the right to the left (i.e. Mario backwards) -* @constant -* @type {number} -*/ + * A constant used for the sortDirection value. + * Use this if your game world is wide but short and scrolls from the right to the left (i.e. Mario backwards) + * @constant + * @type {number} + */ Phaser.Physics.Arcade.RIGHT_LEFT = 2; /** -* A constant used for the sortDirection value. -* Use this if your game world is narrow but tall and scrolls from the top to the bottom (i.e. Dig Dug) -* @constant -* @type {number} -*/ + * A constant used for the sortDirection value. + * Use this if your game world is narrow but tall and scrolls from the top to the bottom (i.e. Dig Dug) + * @constant + * @type {number} + */ Phaser.Physics.Arcade.TOP_BOTTOM = 3; /** -* A constant used for the sortDirection value. -* Use this if your game world is narrow but tall and scrolls from the bottom to the top (i.e. Commando or a vertically scrolling shoot-em-up) -* @constant -* @type {number} -*/ + * A constant used for the sortDirection value. + * Use this if your game world is narrow but tall and scrolls from the bottom to the top (i.e. Commando or a vertically scrolling shoot-em-up) + * @constant + * @type {number} + */ Phaser.Physics.Arcade.BOTTOM_TOP = 4; Phaser.Physics.Arcade.prototype = { /** - * Updates the size of this physics world. - * - * @method Phaser.Physics.Arcade#setBounds - * @param {number} x - Top left most corner of the world. - * @param {number} y - Top left most corner of the world. - * @param {number} width - New width of the world. Can never be smaller than the Game.width. - * @param {number} height - New height of the world. Can never be smaller than the Game.height. - */ + * Updates the size of this physics world. + * + * @method Phaser.Physics.Arcade#setBounds + * @param {number} x - Top left most corner of the world. + * @param {number} y - Top left most corner of the world. + * @param {number} width - New width of the world. Can never be smaller than the Game.width. + * @param {number} height - New height of the world. Can never be smaller than the Game.height. + */ setBounds: function (x, y, width, height) { - this.bounds.setTo(x, y, width, height); - }, /** - * Updates the size of this physics world to match the size of the game world. - * - * @method Phaser.Physics.Arcade#setBoundsToWorld - */ + * Updates the size of this physics world to match the size of the game world. + * + * @method Phaser.Physics.Arcade#setBoundsToWorld + */ setBoundsToWorld: function () { - this.bounds.copyFrom(this.game.world.bounds); - }, /** - * This will create an Arcade Physics body on the given game object or array of game objects. - * A game object can only have 1 physics body active at any one time, and it can't be changed until the object is destroyed. - * - * @method Phaser.Physics.Arcade#enable - * @param {object|array|Phaser.Group} object - The game object to create the physics body on. Can also be an array or Group of objects, a body will be created on every child that has a `body` property. - * @param {boolean} [children=true] - Should a body be created on all children of this object? If true it will recurse down the display list as far as it can go. - */ + * This will create an Arcade Physics body on the given game object or array of game objects. + * A game object can only have 1 physics body active at any one time, and it can't be changed until the object is destroyed. + * + * @method Phaser.Physics.Arcade#enable + * @param {object|array|Phaser.Group} object - The game object to create the physics body on. Can also be an array or Group of objects, a body will be created on every child that has a `body` property. + * @param {boolean} [children=true] - Should a body be created on all children of this object? If true it will recurse down the display list as far as it can go. + */ enable: function (object, children) { - if (children === undefined) { children = true; } var i = 1; @@ -213,22 +206,20 @@ Phaser.Physics.Arcade.prototype = { this.enable(object.children, true); } } - }, /** - * Creates an Arcade Physics body on the given game object. - * - * A game object can only have 1 physics body active at any one time, and it can't be changed until the body is nulled. - * - * When you add an Arcade Physics body to an object it will automatically add the object into its parent Groups hash array. - * - * @method Phaser.Physics.Arcade#enableBody - * @param {object} object - The game object to create the physics body on. A body will only be created if this object has a null `body` property. - */ + * Creates an Arcade Physics body on the given game object. + * + * A game object can only have 1 physics body active at any one time, and it can't be changed until the body is nulled. + * + * When you add an Arcade Physics body to an object it will automatically add the object into its parent Groups hash array. + * + * @method Phaser.Physics.Arcade#enableBody + * @param {object} object - The game object to create the physics body on. A body will only be created if this object has a null `body` property. + */ enableBody: function (object) { - if (object.hasOwnProperty('body') && object.body === null) { object.body = new Phaser.Physics.Arcade.Body(object); @@ -238,18 +229,16 @@ Phaser.Physics.Arcade.prototype = { object.parent.addToHash(object); } } - }, /** - * Called automatically by a Physics body, it updates all motion related values on the Body unless `World.isPaused` is `true`. - * - * @method Phaser.Physics.Arcade#updateMotion - * @param {Phaser.Physics.Arcade.Body} The Body object to be updated. - */ + * Called automatically by a Physics body, it updates all motion related values on the Body unless `World.isPaused` is `true`. + * + * @method Phaser.Physics.Arcade#updateMotion + * @param {Phaser.Physics.Arcade.Body} The Body object to be updated. + */ updateMotion: function (body) { - if (body.allowRotation) { var velocityDelta = this.computeVelocity(0, body, body.angularVelocity, body.angularAcceleration, body.angularDrag, body.maxAngular) - body.angularVelocity; @@ -259,25 +248,23 @@ Phaser.Physics.Arcade.prototype = { body.velocity.x = this.computeVelocity(1, body, body.velocity.x, body.acceleration.x, body.drag.x, body.maxVelocity.x); body.velocity.y = this.computeVelocity(2, body, body.velocity.y, body.acceleration.y, body.drag.y, body.maxVelocity.y); - }, /** - * A tween-like function that takes a starting velocity and some other factors and returns an altered velocity. - * Based on a function in Flixel by @ADAMATOMIC - * - * @method Phaser.Physics.Arcade#computeVelocity - * @param {number} axis - 0 for nothing, 1 for horizontal, 2 for vertical. - * @param {Phaser.Physics.Arcade.Body} body - The Body object to be updated. - * @param {number} velocity - Any component of velocity (e.g. 20). - * @param {number} acceleration - Rate at which the velocity is changing. - * @param {number} drag - Really kind of a deceleration, this is how much the velocity changes if Acceleration is not set. - * @param {number} [max=10000] - An absolute value cap for the velocity. - * @return {number} The altered Velocity value. - */ + * A tween-like function that takes a starting velocity and some other factors and returns an altered velocity. + * Based on a function in Flixel by @ADAMATOMIC + * + * @method Phaser.Physics.Arcade#computeVelocity + * @param {number} axis - 0 for nothing, 1 for horizontal, 2 for vertical. + * @param {Phaser.Physics.Arcade.Body} body - The Body object to be updated. + * @param {number} velocity - Any component of velocity (e.g. 20). + * @param {number} acceleration - Rate at which the velocity is changing. + * @param {number} drag - Really kind of a deceleration, this is how much the velocity changes if Acceleration is not set. + * @param {number} [max=10000] - An absolute value cap for the velocity. + * @return {number} The altered Velocity value. + */ computeVelocity: function (axis, body, velocity, acceleration, drag, max) { - if (max === undefined) { max = 10000; } if (axis === 1 && body.allowGravity) @@ -321,39 +308,37 @@ Phaser.Physics.Arcade.prototype = { } return velocity; - }, /** - * Checks for overlaps between two game objects. The objects can be Sprites, Groups or Emitters. - * - * Unlike {@link #collide} the objects are NOT automatically separated or have any physics applied, they merely test for overlap results. - * - * You can perform Sprite vs. Sprite, Sprite vs. Group and Group vs. Group overlap checks. - * Both the first and second parameter can be arrays of objects, of differing types. - * If two arrays are passed, the contents of the first parameter will be tested against all contents of the 2nd parameter. - * - * **This function is not recursive**, and will not test against children of objects passed (i.e. Groups within Groups). - * - * ##### Tilemaps - * - * Any overlapping tiles, including blank/null tiles, will give a positive result. Tiles marked via {@link Phaser.Tilemap#setCollision} (and similar methods) have no special status, and callbacks added via {@link Phaser.Tilemap#setTileIndexCallback} or {@link Phaser.Tilemap#setTileLocationCallback} are not invoked. So calling this method without any callbacks isn't very useful. - * - * If you're interested only in whether an object overlaps a certain tile or class of tiles, filter the tiles with `processCallback` and then use the result returned by this method. Blank/null tiles can be excluded by their {@link Phaser.Tile#index index} (-1). - * - * If you want to take action on certain overlaps, examine the tiles in `collideCallback` and then handle as you like. - * - * @method Phaser.Physics.Arcade#overlap - * @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter|array} object1 - The first object or array of objects to check. Can be Phaser.Sprite, Phaser.Group or Phaser.Particles.Emitter. - * @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter|array} object2 - The second object or array of objects to check. Can be Phaser.Sprite, Phaser.Group or Phaser.Particles.Emitter. - * @param {function} [overlapCallback=null] - An optional callback function that is called if the objects overlap. The two objects will be passed to this function in the same order in which you specified them, unless you are checking Group vs. Sprite, in which case Sprite will always be the first parameter. - * @param {function} [processCallback=null] - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then `overlapCallback` will only be called if this callback returns `true`. - * @param {object} [callbackContext] - The context in which to run the callbacks. - * @return {boolean} True if an overlap occurred otherwise false. - */ + * Checks for overlaps between two game objects. The objects can be Sprites, Groups or Emitters. + * + * Unlike {@link #collide} the objects are NOT automatically separated or have any physics applied, they merely test for overlap results. + * + * You can perform Sprite vs. Sprite, Sprite vs. Group and Group vs. Group overlap checks. + * Both the first and second parameter can be arrays of objects, of differing types. + * If two arrays are passed, the contents of the first parameter will be tested against all contents of the 2nd parameter. + * + * **This function is not recursive**, and will not test against children of objects passed (i.e. Groups within Groups). + * + * ##### Tilemaps + * + * Any overlapping tiles, including blank/null tiles, will give a positive result. Tiles marked via {@link Phaser.Tilemap#setCollision} (and similar methods) have no special status, and callbacks added via {@link Phaser.Tilemap#setTileIndexCallback} or {@link Phaser.Tilemap#setTileLocationCallback} are not invoked. So calling this method without any callbacks isn't very useful. + * + * If you're interested only in whether an object overlaps a certain tile or class of tiles, filter the tiles with `processCallback` and then use the result returned by this method. Blank/null tiles can be excluded by their {@link Phaser.Tile#index index} (-1). + * + * If you want to take action on certain overlaps, examine the tiles in `collideCallback` and then handle as you like. + * + * @method Phaser.Physics.Arcade#overlap + * @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter|array} object1 - The first object or array of objects to check. Can be Phaser.Sprite, Phaser.Group or Phaser.Particles.Emitter. + * @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter|array} object2 - The second object or array of objects to check. Can be Phaser.Sprite, Phaser.Group or Phaser.Particles.Emitter. + * @param {function} [overlapCallback=null] - An optional callback function that is called if the objects overlap. The two objects will be passed to this function in the same order in which you specified them, unless you are checking Group vs. Sprite, in which case Sprite will always be the first parameter. + * @param {function} [processCallback=null] - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then `overlapCallback` will only be called if this callback returns `true`. + * @param {object} [callbackContext] - The context in which to run the callbacks. + * @return {boolean} True if an overlap occurred otherwise false. + */ overlap: function (object1, object2, overlapCallback, processCallback, callbackContext) { - overlapCallback = overlapCallback || null; processCallback = processCallback || null; callbackContext = callbackContext || overlapCallback; @@ -363,61 +348,59 @@ Phaser.Physics.Arcade.prototype = { this.collideObjects(object1, object2, overlapCallback, processCallback, callbackContext, true); return (this._total > 0); - }, /** - * Checks for collision between two game objects and separates them if colliding ({@link https://gist.github.com/samme/cbb81dd19f564dcfe2232761e575063d details}). If you don't require separation then use {@link #overlap} instead. - * - * You can perform Sprite vs. Sprite, Sprite vs. Group, Group vs. Group, Sprite vs. Tilemap Layer or Group vs. Tilemap Layer collisions. - * Both the `object1` and `object2` can be arrays of objects, of differing types. - * - * If two Groups or arrays are passed, each member of one will be tested against each member of the other. - * - * If one Group **only** is passed (as `object1`), each member of the Group will be collided against the other members. - * - * If either object is `null` the collision test will fail. - * - * Bodies with `enable = false` and Sprites with `exists = false` are skipped (ignored). - * - * An optional processCallback can be provided. If given this function will be called when two sprites are found to be colliding. It is called before any separation takes place, giving you the chance to perform additional checks. If the function returns true then the collision and separation is carried out. If it returns false it is skipped. - * - * The collideCallback is an optional function that is only called if two sprites collide. If a processCallback has been set then it needs to return true for collideCallback to be called. - * - * **This function is not recursive**, and will not test against children of objects passed (i.e. Groups or Tilemaps within other Groups). - * - * ##### Examples - * - * ```javascript - * collide(group); - * collide(group, undefined); // equivalent - * - * collide(sprite1, sprite2); - * - * collide(sprite, group); - * - * collide(group1, group2); - * - * collide([sprite1, sprite2], [sprite3, sprite4]); // 1 vs. 3, 1 vs. 4, 2 vs. 3, 2 vs. 4 - * ``` - * - * ##### Tilemaps - * - * Tiles marked via {@link Phaser.Tilemap#setCollision} (and similar methods) are "solid". If a Sprite collides with one of these tiles, the two are separated by moving the Sprite outside the tile's edges. Enable {@link Phaser.TilemapLayer#debug} to see the colliding edges of the Tilemap. - * - * Tiles with a callback attached via {@link Phaser.Tilemap#setTileIndexCallback} or {@link Phaser.Tilemap#setTileLocationCallback} invoke the callback if a Sprite collides with them. If a tile has a callback attached via both methods, only the location callback is invoked. The colliding Sprite is separated from the tile only if the callback returns `true`. - * - * @method Phaser.Physics.Arcade#collide - * @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter|Phaser.TilemapLayer|array} object1 - The first object or array of objects to check. Can be Phaser.Sprite, Phaser.Group, Phaser.Particles.Emitter, or Phaser.TilemapLayer. - * @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter|Phaser.TilemapLayer|array} object2 - The second object or array of objects to check. Can be Phaser.Sprite, Phaser.Group, Phaser.Particles.Emitter or Phaser.TilemapLayer. - * @param {function} [collideCallback=null] - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them, unless you are colliding Group vs. Sprite, in which case Sprite will always be the first parameter. - * @param {function} [processCallback=null] - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them, unless you are colliding Group vs. Sprite, in which case Sprite will always be the first parameter. - * @param {object} [callbackContext] - The context in which to run the callbacks. - * @return {boolean} True if a collision occurred otherwise false. - */ + * Checks for collision between two game objects and separates them if colliding ({@link https://gist.github.com/samme/cbb81dd19f564dcfe2232761e575063d details}). If you don't require separation then use {@link #overlap} instead. + * + * You can perform Sprite vs. Sprite, Sprite vs. Group, Group vs. Group, Sprite vs. Tilemap Layer or Group vs. Tilemap Layer collisions. + * Both the `object1` and `object2` can be arrays of objects, of differing types. + * + * If two Groups or arrays are passed, each member of one will be tested against each member of the other. + * + * If one Group **only** is passed (as `object1`), each member of the Group will be collided against the other members. + * + * If either object is `null` the collision test will fail. + * + * Bodies with `enable = false` and Sprites with `exists = false` are skipped (ignored). + * + * An optional processCallback can be provided. If given this function will be called when two sprites are found to be colliding. It is called before any separation takes place, giving you the chance to perform additional checks. If the function returns true then the collision and separation is carried out. If it returns false it is skipped. + * + * The collideCallback is an optional function that is only called if two sprites collide. If a processCallback has been set then it needs to return true for collideCallback to be called. + * + * **This function is not recursive**, and will not test against children of objects passed (i.e. Groups or Tilemaps within other Groups). + * + * ##### Examples + * + * ```javascript + * collide(group); + * collide(group, undefined); // equivalent + * + * collide(sprite1, sprite2); + * + * collide(sprite, group); + * + * collide(group1, group2); + * + * collide([sprite1, sprite2], [sprite3, sprite4]); // 1 vs. 3, 1 vs. 4, 2 vs. 3, 2 vs. 4 + * ``` + * + * ##### Tilemaps + * + * Tiles marked via {@link Phaser.Tilemap#setCollision} (and similar methods) are "solid". If a Sprite collides with one of these tiles, the two are separated by moving the Sprite outside the tile's edges. Enable {@link Phaser.TilemapLayer#debug} to see the colliding edges of the Tilemap. + * + * Tiles with a callback attached via {@link Phaser.Tilemap#setTileIndexCallback} or {@link Phaser.Tilemap#setTileLocationCallback} invoke the callback if a Sprite collides with them. If a tile has a callback attached via both methods, only the location callback is invoked. The colliding Sprite is separated from the tile only if the callback returns `true`. + * + * @method Phaser.Physics.Arcade#collide + * @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter|Phaser.TilemapLayer|array} object1 - The first object or array of objects to check. Can be Phaser.Sprite, Phaser.Group, Phaser.Particles.Emitter, or Phaser.TilemapLayer. + * @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter|Phaser.TilemapLayer|array} object2 - The second object or array of objects to check. Can be Phaser.Sprite, Phaser.Group, Phaser.Particles.Emitter or Phaser.TilemapLayer. + * @param {function} [collideCallback=null] - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them, unless you are colliding Group vs. Sprite, in which case Sprite will always be the first parameter. + * @param {function} [processCallback=null] - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them, unless you are colliding Group vs. Sprite, in which case Sprite will always be the first parameter. + * @param {object} [callbackContext] - The context in which to run the callbacks. + * @return {boolean} True if a collision occurred otherwise false. + */ collide: function (object1, object2, collideCallback, processCallback, callbackContext) { - collideCallback = collideCallback || null; processCallback = processCallback || null; callbackContext = callbackContext || collideCallback; @@ -427,7 +410,6 @@ Phaser.Physics.Arcade.prototype = { this.collideObjects(object1, object2, collideCallback, processCallback, callbackContext, false); return (this._total > 0); - }, /** @@ -442,14 +424,12 @@ Phaser.Physics.Arcade.prototype = { */ sortLeftRight: function (a, b) { - if (!a.body || !b.body) { return 0; } return a.body.x - b.body.x; - }, /** @@ -464,14 +444,12 @@ Phaser.Physics.Arcade.prototype = { */ sortRightLeft: function (a, b) { - if (!a.body || !b.body) { return 0; } return b.body.x - a.body.x; - }, /** @@ -486,14 +464,12 @@ Phaser.Physics.Arcade.prototype = { */ sortTopBottom: function (a, b) { - if (!a.body || !b.body) { return 0; } return a.body.y - b.body.y; - }, /** @@ -508,14 +484,12 @@ Phaser.Physics.Arcade.prototype = { */ sortBottomTop: function (a, b) { - if (!a.body || !b.body) { return 0; } return b.body.y - a.body.y; - }, /** @@ -533,7 +507,6 @@ Phaser.Physics.Arcade.prototype = { */ sort: function (group, sortDirection) { - if (group.physicsSortDirection !== null) { sortDirection = group.physicsSortDirection; @@ -561,18 +534,16 @@ Phaser.Physics.Arcade.prototype = { // Game world is say 800x2000 and you start at 2000 group.hash.sort(this.sortBottomTop); } - }, /** - * Internal collision handler. Extracts objects for {@link #collideHandler}. - * - * @method Phaser.Physics.Arcade#collideObjects - * @private - */ + * Internal collision handler. Extracts objects for {@link #collideHandler}. + * + * @method Phaser.Physics.Arcade#collideObjects + * @private + */ collideObjects: function (object1, object2, collideCallback, processCallback, callbackContext, overlapOnly) { - if (!Array.isArray(object1) && Array.isArray(object2)) { for (var i = 0; i < object2.length; i++) @@ -609,24 +580,22 @@ Phaser.Physics.Arcade.prototype = { { this.collideHandler(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly); } - }, /** - * Internal collision handler. Matches arguments to other handlers. - * - * @method Phaser.Physics.Arcade#collideHandler - * @private - * @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter|Phaser.TilemapLayer} object1 - The first object to check. Can be an instance of Phaser.Sprite, Phaser.Group, Phaser.Particles.Emitter, or Phaser.TilemapLayer. - * @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter|Phaser.TilemapLayer} object2 - The second object to check. Can be an instance of Phaser.Sprite, Phaser.Group, Phaser.Particles.Emitter or Phaser.TilemapLayer. Can also be an array of objects to check. - * @param {function} collideCallback - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them. - * @param {function} processCallback - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them. - * @param {object} callbackContext - The context in which to run the callbacks. - * @param {boolean} overlapOnly - Just run an overlap or a full collision. - */ + * Internal collision handler. Matches arguments to other handlers. + * + * @method Phaser.Physics.Arcade#collideHandler + * @private + * @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter|Phaser.TilemapLayer} object1 - The first object to check. Can be an instance of Phaser.Sprite, Phaser.Group, Phaser.Particles.Emitter, or Phaser.TilemapLayer. + * @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter|Phaser.TilemapLayer} object2 - The second object to check. Can be an instance of Phaser.Sprite, Phaser.Group, Phaser.Particles.Emitter or Phaser.TilemapLayer. Can also be an array of objects to check. + * @param {function} collideCallback - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them. + * @param {function} processCallback - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them. + * @param {object} callbackContext - The context in which to run the callbacks. + * @param {boolean} overlapOnly - Just run an overlap or a full collision. + */ collideHandler: function (object1, object2, collideCallback, processCallback, callbackContext, overlapOnly) { - // Only collide valid objects if (object2 === undefined && object1.physicsType === Phaser.GROUP) { @@ -701,25 +670,23 @@ Phaser.Physics.Arcade.prototype = { this.collideGroupVsTilemapLayer(object2, object1, collideCallback, processCallback, callbackContext, overlapOnly); } } - }, /** - * An internal function. Use Phaser.Physics.Arcade.collide instead. - * - * @method Phaser.Physics.Arcade#collideSpriteVsSprite - * @private - * @param {Phaser.Sprite} sprite1 - The first sprite to check. - * @param {Phaser.Sprite} sprite2 - The second sprite to check. - * @param {function} collideCallback - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them. - * @param {function} processCallback - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them. - * @param {object} callbackContext - The context in which to run the callbacks. - * @param {boolean} overlapOnly - Just run an overlap or a full collision. - * @return {boolean} True if there was a collision, otherwise false. - */ + * An internal function. Use Phaser.Physics.Arcade.collide instead. + * + * @method Phaser.Physics.Arcade#collideSpriteVsSprite + * @private + * @param {Phaser.Sprite} sprite1 - The first sprite to check. + * @param {Phaser.Sprite} sprite2 - The second sprite to check. + * @param {function} collideCallback - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them. + * @param {function} processCallback - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them. + * @param {object} callbackContext - The context in which to run the callbacks. + * @param {boolean} overlapOnly - Just run an overlap or a full collision. + * @return {boolean} True if there was a collision, otherwise false. + */ collideSpriteVsSprite: function (sprite1, sprite2, collideCallback, processCallback, callbackContext, overlapOnly) { - if (!sprite1.body || !sprite2.body) { return false; @@ -736,24 +703,22 @@ Phaser.Physics.Arcade.prototype = { } return true; - }, /** - * An internal function. Use Phaser.Physics.Arcade.collide instead. - * - * @method Phaser.Physics.Arcade#collideSpriteVsGroup - * @private - * @param {Phaser.Sprite} sprite - The sprite to check. - * @param {Phaser.Group} group - The Group to check. - * @param {function} collideCallback - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them. - * @param {function} processCallback - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them. - * @param {object} callbackContext - The context in which to run the callbacks. - * @param {boolean} overlapOnly - Just run an overlap or a full collision. - */ + * An internal function. Use Phaser.Physics.Arcade.collide instead. + * + * @method Phaser.Physics.Arcade#collideSpriteVsGroup + * @private + * @param {Phaser.Sprite} sprite - The sprite to check. + * @param {Phaser.Group} group - The Group to check. + * @param {function} collideCallback - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them. + * @param {function} processCallback - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them. + * @param {object} callbackContext - The context in which to run the callbacks. + * @param {boolean} overlapOnly - Just run an overlap or a full collision. + */ collideSpriteVsGroup: function (sprite, group, collideCallback, processCallback, callbackContext, overlapOnly) { - if (group.length === 0 || !sprite.body) { return; @@ -850,24 +815,22 @@ Phaser.Physics.Arcade.prototype = { } } } - }, /** - * An internal function. Use Phaser.Physics.Arcade.collide instead. - * - * @method Phaser.Physics.Arcade#collideGroupVsSelf - * @private - * @param {Phaser.Group} group - The Group to check. - * @param {function} collideCallback - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them. - * @param {function} processCallback - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them. - * @param {object} callbackContext - The context in which to run the callbacks. - * @param {boolean} overlapOnly - Just run an overlap or a full collision. - * @return {boolean} True if there was a collision, otherwise false. - */ + * An internal function. Use Phaser.Physics.Arcade.collide instead. + * + * @method Phaser.Physics.Arcade#collideGroupVsSelf + * @private + * @param {Phaser.Group} group - The Group to check. + * @param {function} collideCallback - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them. + * @param {function} processCallback - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them. + * @param {object} callbackContext - The context in which to run the callbacks. + * @param {boolean} overlapOnly - Just run an overlap or a full collision. + * @return {boolean} True if there was a collision, otherwise false. + */ collideGroupVsSelf: function (group, collideCallback, processCallback, callbackContext, overlapOnly) { - if (group.length === 0) { return; @@ -950,24 +913,22 @@ Phaser.Physics.Arcade.prototype = { this.collideSpriteVsSprite(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly); } } - }, /** - * An internal function. Use Phaser.Physics.Arcade.collide instead. - * - * @method Phaser.Physics.Arcade#collideGroupVsGroup - * @private - * @param {Phaser.Group} group1 - The first Group to check. - * @param {Phaser.Group} group2 - The second Group to check. - * @param {function} collideCallback - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them. - * @param {function} processCallback - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them. - * @param {object} callbackContext - The context in which to run the callbacks. - * @param {boolean} overlapOnly - Just run an overlap or a full collision. - */ + * An internal function. Use Phaser.Physics.Arcade.collide instead. + * + * @method Phaser.Physics.Arcade#collideGroupVsGroup + * @private + * @param {Phaser.Group} group1 - The first Group to check. + * @param {Phaser.Group} group2 - The second Group to check. + * @param {function} collideCallback - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them. + * @param {function} processCallback - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them. + * @param {object} callbackContext - The context in which to run the callbacks. + * @param {boolean} overlapOnly - Just run an overlap or a full collision. + */ collideGroupVsGroup: function (group1, group2, collideCallback, processCallback, callbackContext, overlapOnly) { - if (group1.length === 0 || group2.length === 0) { return; @@ -987,24 +948,22 @@ Phaser.Physics.Arcade.prototype = { } } } - }, /** - * The core separation function to separate two physics bodies. - * - * @private - * @method Phaser.Physics.Arcade#separate - * @param {Phaser.Physics.Arcade.Body} body1 - The first Body object to separate. - * @param {Phaser.Physics.Arcade.Body} body2 - The second Body object to separate. - * @param {function} [processCallback=null] - A callback function that lets you perform additional checks against the two objects if they overlap. If this function is set then the sprites will only be collided if it returns true. - * @param {object} [callbackContext] - The context in which to run the process callback. - * @param {boolean} overlapOnly - Just run an overlap or a full collision. - * @return {boolean} Returns true if the bodies collided, otherwise false. - */ + * The core separation function to separate two physics bodies. + * + * @private + * @method Phaser.Physics.Arcade#separate + * @param {Phaser.Physics.Arcade.Body} body1 - The first Body object to separate. + * @param {Phaser.Physics.Arcade.Body} body2 - The second Body object to separate. + * @param {function} [processCallback=null] - A callback function that lets you perform additional checks against the two objects if they overlap. If this function is set then the sprites will only be collided if it returns true. + * @param {object} [callbackContext] - The context in which to run the process callback. + * @param {boolean} overlapOnly - Just run an overlap or a full collision. + * @return {boolean} Returns true if the bodies collided, otherwise false. + */ separate: function (body1, body2, processCallback, callbackContext, overlapOnly) { - if ( !body1.enable || !body2.enable || @@ -1027,8 +986,10 @@ Phaser.Physics.Arcade.prototype = { return this.separateCircle(body1, body2, overlapOnly); } - // We define the behavior of bodies in a collision circle and rectangle - // If a collision occurs in the corner points of the rectangle, the body behave like circles + /* + * We define the behavior of bodies in a collision circle and rectangle + * If a collision occurs in the corner points of the rectangle, the body behave like circles + */ // Either body1 or body2 is a circle if (body1.isCircle !== body2.isCircle) @@ -1110,20 +1071,18 @@ Phaser.Physics.Arcade.prototype = { } return result; - }, /** - * Check for intersection against two bodies. - * - * @method Phaser.Physics.Arcade#intersects - * @param {Phaser.Physics.Arcade.Body} body1 - The first Body object to check. - * @param {Phaser.Physics.Arcade.Body} body2 - The second Body object to check. - * @return {boolean} True if they intersect, otherwise false. - */ + * Check for intersection against two bodies. + * + * @method Phaser.Physics.Arcade#intersects + * @param {Phaser.Physics.Arcade.Body} body1 - The first Body object to check. + * @param {Phaser.Physics.Arcade.Body} body2 - The second Body object to check. + * @return {boolean} True if they intersect, otherwise false. + */ intersects: function (body1, body2) { - if (body1 === body2) { return false; @@ -1173,20 +1132,18 @@ Phaser.Physics.Arcade.prototype = { return true; } - }, /** - * Checks to see if a circular Body intersects with a Rectangular Body. - * - * @method Phaser.Physics.Arcade#circleBodyIntersects - * @param {Phaser.Physics.Arcade.Body} circle - The Body with `isCircle` set. - * @param {Phaser.Physics.Arcade.Body} body - The Body with `isCircle` not set (i.e. uses Rectangle shape) - * @return {boolean} Returns true if the bodies intersect, otherwise false. - */ + * Checks to see if a circular Body intersects with a Rectangular Body. + * + * @method Phaser.Physics.Arcade#circleBodyIntersects + * @param {Phaser.Physics.Arcade.Body} circle - The Body with `isCircle` set. + * @param {Phaser.Physics.Arcade.Body} body - The Body with `isCircle` not set (i.e. uses Rectangle shape) + * @return {boolean} Returns true if the bodies intersect, otherwise false. + */ circleBodyIntersects: function (circle, body) { - var x = Phaser.Math.clamp(circle.center.x, body.left, body.right); var y = Phaser.Math.clamp(circle.center.y, body.top, body.bottom); @@ -1194,22 +1151,20 @@ Phaser.Physics.Arcade.prototype = { var dy = (circle.center.y - y) * (circle.center.y - y); return (dx + dy) <= (circle.halfWidth * circle.halfWidth); - }, /** - * The core separation function to separate two circular physics bodies. - * - * @method Phaser.Physics.Arcade#separateCircle - * @private - * @param {Phaser.Physics.Arcade.Body} body1 - The first Body to separate. Must have `Body.isCircle` true and a positive `radius`. - * @param {Phaser.Physics.Arcade.Body} body2 - The second Body to separate. Must have `Body.isCircle` true and a positive `radius`. - * @param {boolean} overlapOnly - If true the bodies will only have their overlap data set, no separation or exchange of velocity will take place. - * @return {boolean} Returns true if the bodies were separated or overlap, otherwise false. - */ + * The core separation function to separate two circular physics bodies. + * + * @method Phaser.Physics.Arcade#separateCircle + * @private + * @param {Phaser.Physics.Arcade.Body} body1 - The first Body to separate. Must have `Body.isCircle` true and a positive `radius`. + * @param {Phaser.Physics.Arcade.Body} body2 - The second Body to separate. Must have `Body.isCircle` true and a positive `radius`. + * @param {boolean} overlapOnly - If true the bodies will only have their overlap data set, no separation or exchange of velocity will take place. + * @return {boolean} Returns true if the bodies were separated or overlap, otherwise false. + */ separateCircle: function (body1, body2, overlapOnly) { - // Set the bounding box overlap values this.getOverlapX(body1, body2); this.getOverlapY(body1, body2); @@ -1286,8 +1241,10 @@ Phaser.Physics.Arcade.prototype = { return (overlap !== 0); } - // Transform the velocity vector to the coordinate system oriented along the direction of impact. - // This is done to eliminate the vertical component of the velocity + /* + * Transform the velocity vector to the coordinate system oriented along the direction of impact. + * This is done to eliminate the vertical component of the velocity + */ var v1 = { x: body1.velocity.x * Math.cos(angleCollision) + body1.velocity.y * Math.sin(angleCollision), y: -body1.velocity.x * Math.sin(angleCollision) + body1.velocity.y * Math.cos(angleCollision) @@ -1315,9 +1272,11 @@ Phaser.Physics.Arcade.prototype = { body2.velocity.y = (v2.y * Math.cos(angleCollision) + tempVel2 * Math.sin(angleCollision)) * body2.bounce.y; } - // When the collision angle is almost perpendicular to the total initial velocity vector - // (collision on a tangent) vector direction can be determined incorrectly. - // This code fixes the problem + /* + * When the collision angle is almost perpendicular to the total initial velocity vector + * (collision on a tangent) vector direction can be determined incorrectly. + * This code fixes the problem + */ if (Math.abs(angleCollision) < Math.PI / 2) { @@ -1381,22 +1340,20 @@ Phaser.Physics.Arcade.prototype = { } return true; - }, /** - * Calculates the horizontal overlap between two Bodies and sets their properties accordingly, including: - * `touching.left`, `touching.right` and `overlapX`. - * - * @method Phaser.Physics.Arcade#getOverlapX - * @param {Phaser.Physics.Arcade.Body} body1 - The first Body to separate. - * @param {Phaser.Physics.Arcade.Body} body2 - The second Body to separate. - * @param {boolean} overlapOnly - Is this an overlap only check, or part of separation? - * @return {float} Returns the amount of horizontal overlap between the two bodies. - */ + * Calculates the horizontal overlap between two Bodies and sets their properties accordingly, including: + * `touching.left`, `touching.right` and `overlapX`. + * + * @method Phaser.Physics.Arcade#getOverlapX + * @param {Phaser.Physics.Arcade.Body} body1 - The first Body to separate. + * @param {Phaser.Physics.Arcade.Body} body2 - The second Body to separate. + * @param {boolean} overlapOnly - Is this an overlap only check, or part of separation? + * @return {float} Returns the amount of horizontal overlap between the two bodies. + */ getOverlapX: function (body1, body2, overlapOnly) { - var overlap = 0; var maxOverlap = body1.deltaAbsX() + body2.deltaAbsX() + this.OVERLAP_BIAS; @@ -1446,22 +1403,20 @@ Phaser.Physics.Arcade.prototype = { body2.overlapX = overlap; return overlap; - }, /** - * Calculates the vertical overlap between two Bodies and sets their properties accordingly, including: - * `touching.up`, `touching.down` and `overlapY`. - * - * @method Phaser.Physics.Arcade#getOverlapY - * @param {Phaser.Physics.Arcade.Body} body1 - The first Body to separate. - * @param {Phaser.Physics.Arcade.Body} body2 - The second Body to separate. - * @param {boolean} overlapOnly - Is this an overlap only check, or part of separation? - * @return {float} Returns the amount of vertical overlap between the two bodies. - */ + * Calculates the vertical overlap between two Bodies and sets their properties accordingly, including: + * `touching.up`, `touching.down` and `overlapY`. + * + * @method Phaser.Physics.Arcade#getOverlapY + * @param {Phaser.Physics.Arcade.Body} body1 - The first Body to separate. + * @param {Phaser.Physics.Arcade.Body} body2 - The second Body to separate. + * @param {boolean} overlapOnly - Is this an overlap only check, or part of separation? + * @return {float} Returns the amount of vertical overlap between the two bodies. + */ getOverlapY: function (body1, body2, overlapOnly) { - var overlap = 0; var maxOverlap = body1.deltaAbsY() + body2.deltaAbsY() + this.OVERLAP_BIAS; @@ -1511,22 +1466,20 @@ Phaser.Physics.Arcade.prototype = { body2.overlapY = overlap; return overlap; - }, /** - * The core separation function to separate two physics bodies on the x axis. - * - * @method Phaser.Physics.Arcade#separateX - * @private - * @param {Phaser.Physics.Arcade.Body} body1 - The first Body to separate. - * @param {Phaser.Physics.Arcade.Body} body2 - The second Body to separate. - * @param {boolean} overlapOnly - If true the bodies will only have their overlap data set, no separation or exchange of velocity will take place. - * @return {boolean} Returns true if the bodies were separated or overlap, otherwise false. - */ + * The core separation function to separate two physics bodies on the x axis. + * + * @method Phaser.Physics.Arcade#separateX + * @private + * @param {Phaser.Physics.Arcade.Body} body1 - The first Body to separate. + * @param {Phaser.Physics.Arcade.Body} body2 - The second Body to separate. + * @param {boolean} overlapOnly - If true the bodies will only have their overlap data set, no separation or exchange of velocity will take place. + * @return {boolean} Returns true if the bodies were separated or overlap, otherwise false. + */ separateX: function (body1, body2, overlapOnly) { - var overlap = this.getOverlapX(body1, body2, overlapOnly); // Can't separate two immovable bodies, or a body with its own custom separation logic @@ -1582,22 +1535,20 @@ Phaser.Physics.Arcade.prototype = { // If we got this far then there WAS overlap, and separation is complete, so return true return true; - }, /** - * The core separation function to separate two physics bodies on the y axis. - * - * @private - * @method Phaser.Physics.Arcade#separateY - * @param {Phaser.Physics.Arcade.Body} body1 - The first Body to separate. - * @param {Phaser.Physics.Arcade.Body} body2 - The second Body to separate. - * @param {boolean} overlapOnly - If true the bodies will only have their overlap data set, no separation or exchange of velocity will take place. - * @return {boolean} Returns true if the bodies were separated or overlap, otherwise false. - */ + * The core separation function to separate two physics bodies on the y axis. + * + * @private + * @method Phaser.Physics.Arcade#separateY + * @param {Phaser.Physics.Arcade.Body} body1 - The first Body to separate. + * @param {Phaser.Physics.Arcade.Body} body2 - The second Body to separate. + * @param {boolean} overlapOnly - If true the bodies will only have their overlap data set, no separation or exchange of velocity will take place. + * @return {boolean} Returns true if the bodies were separated or overlap, otherwise false. + */ separateY: function (body1, body2, overlapOnly) { - var overlap = this.getOverlapY(body1, body2, overlapOnly); // Can't separate two immovable bodies, or a body with its own custom separation logic @@ -1653,50 +1604,46 @@ Phaser.Physics.Arcade.prototype = { // If we got this far then there WAS overlap, and separation is complete, so return true return true; - }, /** - * Given a Group and a Pointer this will check to see which Group children overlap with the Pointer coordinates. - * Each child will be sent to the given callback for further processing. - * Note that the children are not checked for depth order, but simply if they overlap the Pointer or not. - * - * @method Phaser.Physics.Arcade#getObjectsUnderPointer - * @param {Phaser.Pointer} pointer - The Pointer to check. - * @param {Phaser.Group} group - The Group to check. - * @param {function} [callback] - A callback function that is called if the object overlaps with the Pointer. The callback will be sent two parameters: the Pointer and the Object that overlapped with it. - * @param {object} [callbackContext] - The context in which to run the callback. - * @return {PIXI.DisplayObject[]} An array of the Sprites from the Group that overlapped the Pointer coordinates. - */ + * Given a Group and a Pointer this will check to see which Group children overlap with the Pointer coordinates. + * Each child will be sent to the given callback for further processing. + * Note that the children are not checked for depth order, but simply if they overlap the Pointer or not. + * + * @method Phaser.Physics.Arcade#getObjectsUnderPointer + * @param {Phaser.Pointer} pointer - The Pointer to check. + * @param {Phaser.Group} group - The Group to check. + * @param {function} [callback] - A callback function that is called if the object overlaps with the Pointer. The callback will be sent two parameters: the Pointer and the Object that overlapped with it. + * @param {object} [callbackContext] - The context in which to run the callback. + * @return {PIXI.DisplayObject[]} An array of the Sprites from the Group that overlapped the Pointer coordinates. + */ getObjectsUnderPointer: function (pointer, group, callback, callbackContext) { - if (group.length === 0 || !pointer.exists) { return; } return this.getObjectsAtLocation(pointer.x, pointer.y, group, callback, callbackContext, pointer); - }, /** - * Given a Group and a location this will check to see which Group children overlap with the coordinates. - * Each child will be sent to the given callback for further processing. - * Note that the children are not checked for depth order, but simply if they overlap the coordinate or not. - * - * @method Phaser.Physics.Arcade#getObjectsAtLocation - * @param {number} x - The x coordinate to check. - * @param {number} y - The y coordinate to check. - * @param {Phaser.Group} group - The Group to check. - * @param {function} [callback] - A callback function that is called if the object overlaps the coordinates. The callback will be sent two parameters: the callbackArg and the Object that overlapped the location. - * @param {object} [callbackContext] - The context in which to run the callback. - * @param {object} [callbackArg] - An argument to pass to the callback. - * @return {PIXI.DisplayObject[]} An array of the Sprites from the Group that overlapped the coordinates. - */ + * Given a Group and a location this will check to see which Group children overlap with the coordinates. + * Each child will be sent to the given callback for further processing. + * Note that the children are not checked for depth order, but simply if they overlap the coordinate or not. + * + * @method Phaser.Physics.Arcade#getObjectsAtLocation + * @param {number} x - The x coordinate to check. + * @param {number} y - The y coordinate to check. + * @param {Phaser.Group} group - The Group to check. + * @param {function} [callback] - A callback function that is called if the object overlaps the coordinates. The callback will be sent two parameters: the callbackArg and the Object that overlapped the location. + * @param {object} [callbackContext] - The context in which to run the callback. + * @param {object} [callbackArg] - An argument to pass to the callback. + * @return {PIXI.DisplayObject[]} An array of the Sprites from the Group that overlapped the coordinates. + */ getObjectsAtLocation: function (x, y, group, callback, callbackContext, callbackArg) { - this.quadTree.clear(); this.quadTree.reset(this.game.world.bounds.x, this.game.world.bounds.y, this.game.world.bounds.width, this.game.world.bounds.height, this.maxObjects, this.maxLevels); @@ -1722,27 +1669,25 @@ Phaser.Physics.Arcade.prototype = { } return output; - }, /** - * Move the given display object towards the destination object at a steady velocity. - * If you specify a maxTime then it will adjust the speed (overwriting what you set) so it arrives at the destination in that number of seconds. - * Timings are approximate due to the way browser timers work. Allow for a variance of +- 50ms. - * Note: The display object does not continuously track the target. If the target changes location during transit the display object will not modify its course. - * Note: The display object doesn't stop moving once it reaches the destination coordinates. - * Note: Doesn't take into account acceleration, maxVelocity or drag (if you've set drag or acceleration too high this object may not move at all) - * - * @method Phaser.Physics.Arcade#moveToObject - * @param {any} displayObject - The display object to move. - * @param {any} destination - The display object to move towards. Can be any object but must have visible x/y properties. - * @param {number} [speed=60] - The speed it will move, in pixels per second (default is 60 pixels/sec) - * @param {number} [maxTime=0] - Time given in milliseconds (1000 = 1 sec). If set the speed is adjusted so the object will arrive at destination in the given number of ms. - * @return {number} The angle (in radians) that the object should be visually set to in order to match its new velocity. - */ + * Move the given display object towards the destination object at a steady velocity. + * If you specify a maxTime then it will adjust the speed (overwriting what you set) so it arrives at the destination in that number of seconds. + * Timings are approximate due to the way browser timers work. Allow for a variance of +- 50ms. + * Note: The display object does not continuously track the target. If the target changes location during transit the display object will not modify its course. + * Note: The display object doesn't stop moving once it reaches the destination coordinates. + * Note: Doesn't take into account acceleration, maxVelocity or drag (if you've set drag or acceleration too high this object may not move at all) + * + * @method Phaser.Physics.Arcade#moveToObject + * @param {any} displayObject - The display object to move. + * @param {any} destination - The display object to move towards. Can be any object but must have visible x/y properties. + * @param {number} [speed=60] - The speed it will move, in pixels per second (default is 60 pixels/sec) + * @param {number} [maxTime=0] - Time given in milliseconds (1000 = 1 sec). If set the speed is adjusted so the object will arrive at destination in the given number of ms. + * @return {number} The angle (in radians) that the object should be visually set to in order to match its new velocity. + */ moveToObject: function (displayObject, destination, speed, maxTime) { - if (speed === undefined) { speed = 60; } if (maxTime === undefined) { maxTime = 0; } @@ -1757,26 +1702,24 @@ Phaser.Physics.Arcade.prototype = { displayObject.body.velocity.setToPolar(angle, speed); return angle; - }, /** - * Move the given display object towards the pointer at a steady velocity. If no pointer is given it will use Phaser.Input.activePointer. - * If you specify a maxTime then it will adjust the speed (over-writing what you set) so it arrives at the destination in that number of seconds. - * Timings are approximate due to the way browser timers work. Allow for a variance of +- 50ms. - * Note: The display object does not continuously track the target. If the target changes location during transit the display object will not modify its course. - * Note: The display object doesn't stop moving once it reaches the destination coordinates. - * - * @method Phaser.Physics.Arcade#moveToPointer - * @param {any} displayObject - The display object to move. - * @param {number} [speed=60] - The speed it will move, in pixels per second (default is 60 pixels/sec) - * @param {Phaser.Pointer} [pointer] - The pointer to move towards. Defaults to Phaser.Input.activePointer. - * @param {number} [maxTime=0] - Time given in milliseconds (1000 = 1 sec). If set the speed is adjusted so the object will arrive at destination in the given number of ms. - * @return {number} The angle (in radians) that the object should be visually set to in order to match its new velocity. - */ + * Move the given display object towards the pointer at a steady velocity. If no pointer is given it will use Phaser.Input.activePointer. + * If you specify a maxTime then it will adjust the speed (over-writing what you set) so it arrives at the destination in that number of seconds. + * Timings are approximate due to the way browser timers work. Allow for a variance of +- 50ms. + * Note: The display object does not continuously track the target. If the target changes location during transit the display object will not modify its course. + * Note: The display object doesn't stop moving once it reaches the destination coordinates. + * + * @method Phaser.Physics.Arcade#moveToPointer + * @param {any} displayObject - The display object to move. + * @param {number} [speed=60] - The speed it will move, in pixels per second (default is 60 pixels/sec) + * @param {Phaser.Pointer} [pointer] - The pointer to move towards. Defaults to Phaser.Input.activePointer. + * @param {number} [maxTime=0] - Time given in milliseconds (1000 = 1 sec). If set the speed is adjusted so the object will arrive at destination in the given number of ms. + * @return {number} The angle (in radians) that the object should be visually set to in order to match its new velocity. + */ moveToPointer: function (displayObject, speed, pointer, maxTime) { - if (speed === undefined) { speed = 60; } pointer = pointer || this.game.input.activePointer; if (maxTime === undefined) { maxTime = 0; } @@ -1792,28 +1735,26 @@ Phaser.Physics.Arcade.prototype = { displayObject.body.velocity.setToPolar(angle, speed); return angle; - }, /** - * Move the given display object towards the x/y coordinates at a steady velocity. - * If you specify a maxTime then it will adjust the speed (over-writing what you set) so it arrives at the destination in that number of seconds. - * Timings are approximate due to the way browser timers work. Allow for a variance of +- 50ms. - * Note: The display object does not continuously track the target. If the target changes location during transit the display object will not modify its course. - * Note: The display object doesn't stop moving once it reaches the destination coordinates. - * Note: Doesn't take into account acceleration, maxVelocity or drag (if you've set drag or acceleration too high this object may not move at all) - * - * @method Phaser.Physics.Arcade#moveToXY - * @param {any} displayObject - The display object to move. - * @param {number} x - The x coordinate to move towards. - * @param {number} y - The y coordinate to move towards. - * @param {number} [speed=60] - The speed it will move, in pixels per second (default is 60 pixels/sec) - * @param {number} [maxTime=0] - Time given in milliseconds (1000 = 1 sec). If set the speed is adjusted so the object will arrive at destination in the given number of ms. - * @return {number} The angle (in radians) that the object should be visually set to in order to match its new velocity. - */ + * Move the given display object towards the x/y coordinates at a steady velocity. + * If you specify a maxTime then it will adjust the speed (over-writing what you set) so it arrives at the destination in that number of seconds. + * Timings are approximate due to the way browser timers work. Allow for a variance of +- 50ms. + * Note: The display object does not continuously track the target. If the target changes location during transit the display object will not modify its course. + * Note: The display object doesn't stop moving once it reaches the destination coordinates. + * Note: Doesn't take into account acceleration, maxVelocity or drag (if you've set drag or acceleration too high this object may not move at all) + * + * @method Phaser.Physics.Arcade#moveToXY + * @param {any} displayObject - The display object to move. + * @param {number} x - The x coordinate to move towards. + * @param {number} y - The y coordinate to move towards. + * @param {number} [speed=60] - The speed it will move, in pixels per second (default is 60 pixels/sec) + * @param {number} [maxTime=0] - Time given in milliseconds (1000 = 1 sec). If set the speed is adjusted so the object will arrive at destination in the given number of ms. + * @return {number} The angle (in radians) that the object should be visually set to in order to match its new velocity. + */ moveToXY: function (displayObject, x, y, speed, maxTime) { - if (speed === undefined) { speed = 60; } if (maxTime === undefined) { maxTime = 0; } @@ -1828,86 +1769,78 @@ Phaser.Physics.Arcade.prototype = { displayObject.body.velocity.setToPolar(angle, speed); return angle; - }, /** - * Given the angle (in degrees) and speed calculate the velocity and return it as a Point object, or set it to the given point object. - * One way to use this is: velocityFromAngle(angle, 200, sprite.velocity) which will set the values directly to the sprites velocity and not create a new Point object. - * - * @method Phaser.Physics.Arcade#velocityFromAngle - * @param {number} angle - The angle in degrees calculated in clockwise positive direction (down = 90 degrees positive, right = 0 degrees positive, up = 90 degrees negative) - * @param {number} [speed=60] - The speed it will move, in pixels per second sq. - * @param {Phaser.Point|object} [point] - The Point object in which the x and y properties will be set to the calculated velocity. - * @return {Phaser.Point} - A Point where point.x contains the velocity x value and point.y contains the velocity y value. - */ + * Given the angle (in degrees) and speed calculate the velocity and return it as a Point object, or set it to the given point object. + * One way to use this is: velocityFromAngle(angle, 200, sprite.velocity) which will set the values directly to the sprites velocity and not create a new Point object. + * + * @method Phaser.Physics.Arcade#velocityFromAngle + * @param {number} angle - The angle in degrees calculated in clockwise positive direction (down = 90 degrees positive, right = 0 degrees positive, up = 90 degrees negative) + * @param {number} [speed=60] - The speed it will move, in pixels per second sq. + * @param {Phaser.Point|object} [point] - The Point object in which the x and y properties will be set to the calculated velocity. + * @return {Phaser.Point} - A Point where point.x contains the velocity x value and point.y contains the velocity y value. + */ velocityFromAngle: function (angle, speed, point) { - if (speed === undefined) { speed = 60; } point = point || new Phaser.Point(); return point.setToPolar(angle, speed, true); - }, /** - * Given the rotation (in radians) and speed calculate the velocity and return it as a Point object, or set it to the given point object. - * One way to use this is: velocityFromRotation(rotation, 200, sprite.velocity) which will set the values directly to the sprites velocity and not create a new Point object. - * - * @method Phaser.Physics.Arcade#velocityFromRotation - * @param {number} rotation - The angle in radians. - * @param {number} [speed=60] - The speed it will move, in pixels per second sq. - * @param {Phaser.Point|object} [point] - The Point object in which the x and y properties will be set to the calculated velocity. - * @return {Phaser.Point} - A Point where point.x contains the velocity x value and point.y contains the velocity y value. - */ + * Given the rotation (in radians) and speed calculate the velocity and return it as a Point object, or set it to the given point object. + * One way to use this is: velocityFromRotation(rotation, 200, sprite.velocity) which will set the values directly to the sprites velocity and not create a new Point object. + * + * @method Phaser.Physics.Arcade#velocityFromRotation + * @param {number} rotation - The angle in radians. + * @param {number} [speed=60] - The speed it will move, in pixels per second sq. + * @param {Phaser.Point|object} [point] - The Point object in which the x and y properties will be set to the calculated velocity. + * @return {Phaser.Point} - A Point where point.x contains the velocity x value and point.y contains the velocity y value. + */ velocityFromRotation: function (rotation, speed, point) { - if (speed === undefined) { speed = 60; } point = point || new Phaser.Point(); return point.setToPolar(rotation, speed); - }, /** - * Given the rotation (in radians) and speed calculate the acceleration and return it as a Point object, or set it to the given point object. - * One way to use this is: accelerationFromRotation(rotation, 200, sprite.acceleration) which will set the values directly to the sprites acceleration and not create a new Point object. - * - * @method Phaser.Physics.Arcade#accelerationFromRotation - * @param {number} rotation - The angle in radians. - * @param {number} [speed=60] - The speed it will move, in pixels per second sq. - * @param {Phaser.Point|object} [point] - The Point object in which the x and y properties will be set to the calculated acceleration. - * @return {Phaser.Point} - A Point where point.x contains the acceleration x value and point.y contains the acceleration y value. - */ + * Given the rotation (in radians) and speed calculate the acceleration and return it as a Point object, or set it to the given point object. + * One way to use this is: accelerationFromRotation(rotation, 200, sprite.acceleration) which will set the values directly to the sprites acceleration and not create a new Point object. + * + * @method Phaser.Physics.Arcade#accelerationFromRotation + * @param {number} rotation - The angle in radians. + * @param {number} [speed=60] - The speed it will move, in pixels per second sq. + * @param {Phaser.Point|object} [point] - The Point object in which the x and y properties will be set to the calculated acceleration. + * @return {Phaser.Point} - A Point where point.x contains the acceleration x value and point.y contains the acceleration y value. + */ accelerationFromRotation: function (rotation, speed, point) { - if (speed === undefined) { speed = 60; } point = point || new Phaser.Point(); return point.setToPolar(rotation, speed); - }, /** - * Sets the acceleration.x/y property on the display object so it will move towards the target at the given speed (in pixels per second sq.) - * You must give a maximum speed value, beyond which the display object won't go any faster. - * Note: The display object does not continuously track the target. If the target changes location during transit the display object will not modify its course. - * Note: The display object doesn't stop moving once it reaches the destination coordinates. - * - * @method Phaser.Physics.Arcade#accelerateToObject - * @param {any} displayObject - The display object to move. - * @param {any} destination - The display object to move towards. Can be any object but must have visible x/y properties. - * @param {number} [speed=60] - The speed it will accelerate in pixels per second. - * @param {number} [xSpeedMax=500] - The maximum x velocity the display object can reach. - * @param {number} [ySpeedMax=500] - The maximum y velocity the display object can reach. - * @return {number} The angle (in radians) that the object should be visually set to in order to match its new trajectory. - */ + * Sets the acceleration.x/y property on the display object so it will move towards the target at the given speed (in pixels per second sq.) + * You must give a maximum speed value, beyond which the display object won't go any faster. + * Note: The display object does not continuously track the target. If the target changes location during transit the display object will not modify its course. + * Note: The display object doesn't stop moving once it reaches the destination coordinates. + * + * @method Phaser.Physics.Arcade#accelerateToObject + * @param {any} displayObject - The display object to move. + * @param {any} destination - The display object to move towards. Can be any object but must have visible x/y properties. + * @param {number} [speed=60] - The speed it will accelerate in pixels per second. + * @param {number} [xSpeedMax=500] - The maximum x velocity the display object can reach. + * @param {number} [ySpeedMax=500] - The maximum y velocity the display object can reach. + * @return {number} The angle (in radians) that the object should be visually set to in order to match its new trajectory. + */ accelerateToObject: function (displayObject, destination, speed, xSpeedMax, ySpeedMax) { - if (speed === undefined) { speed = 60; } if (xSpeedMax === undefined) { xSpeedMax = 1000; } if (ySpeedMax === undefined) { ySpeedMax = 1000; } @@ -1918,26 +1851,24 @@ Phaser.Physics.Arcade.prototype = { displayObject.body.maxVelocity.setTo(xSpeedMax, ySpeedMax); return angle; - }, /** - * Sets the acceleration.x/y property on the display object so it will move towards the target at the given speed (in pixels per second sq.) - * You must give a maximum speed value, beyond which the display object won't go any faster. - * Note: The display object does not continuously track the target. If the target changes location during transit the display object will not modify its course. - * Note: The display object doesn't stop moving once it reaches the destination coordinates. - * - * @method Phaser.Physics.Arcade#accelerateToPointer - * @param {any} displayObject - The display object to move. - * @param {Phaser.Pointer} [pointer] - The pointer to move towards. Defaults to Phaser.Input.activePointer. - * @param {number} [speed=60] - The speed it will accelerate in pixels per second. - * @param {number} [xSpeedMax=500] - The maximum x velocity the display object can reach. - * @param {number} [ySpeedMax=500] - The maximum y velocity the display object can reach. - * @return {number} The angle (in radians) that the object should be visually set to in order to match its new trajectory. - */ + * Sets the acceleration.x/y property on the display object so it will move towards the target at the given speed (in pixels per second sq.) + * You must give a maximum speed value, beyond which the display object won't go any faster. + * Note: The display object does not continuously track the target. If the target changes location during transit the display object will not modify its course. + * Note: The display object doesn't stop moving once it reaches the destination coordinates. + * + * @method Phaser.Physics.Arcade#accelerateToPointer + * @param {any} displayObject - The display object to move. + * @param {Phaser.Pointer} [pointer] - The pointer to move towards. Defaults to Phaser.Input.activePointer. + * @param {number} [speed=60] - The speed it will accelerate in pixels per second. + * @param {number} [xSpeedMax=500] - The maximum x velocity the display object can reach. + * @param {number} [ySpeedMax=500] - The maximum y velocity the display object can reach. + * @return {number} The angle (in radians) that the object should be visually set to in order to match its new trajectory. + */ accelerateToPointer: function (displayObject, pointer, speed, xSpeedMax, ySpeedMax) { - if (speed === undefined) { speed = 60; } if (pointer === undefined) { pointer = this.game.input.activePointer; } if (xSpeedMax === undefined) { xSpeedMax = 1000; } @@ -1949,27 +1880,25 @@ Phaser.Physics.Arcade.prototype = { displayObject.body.maxVelocity.setTo(xSpeedMax, ySpeedMax); return angle; - }, /** - * Sets the acceleration.x/y property on the display object so it will move towards the x/y coordinates at the given speed (in pixels per second sq.) - * You must give a maximum speed value, beyond which the display object won't go any faster. - * Note: The display object does not continuously track the target. If the target changes location during transit the display object will not modify its course. - * Note: The display object doesn't stop moving once it reaches the destination coordinates. - * - * @method Phaser.Physics.Arcade#accelerateToXY - * @param {any} displayObject - The display object to move. - * @param {number} x - The x coordinate to accelerate towards. - * @param {number} y - The y coordinate to accelerate towards. - * @param {number} [speed=60] - The speed it will accelerate in pixels per second. - * @param {number} [xSpeedMax=500] - The maximum x velocity the display object can reach. - * @param {number} [ySpeedMax=500] - The maximum y velocity the display object can reach. - * @return {number} The angle (in radians) that the object should be visually set to in order to match its new trajectory. - */ + * Sets the acceleration.x/y property on the display object so it will move towards the x/y coordinates at the given speed (in pixels per second sq.) + * You must give a maximum speed value, beyond which the display object won't go any faster. + * Note: The display object does not continuously track the target. If the target changes location during transit the display object will not modify its course. + * Note: The display object doesn't stop moving once it reaches the destination coordinates. + * + * @method Phaser.Physics.Arcade#accelerateToXY + * @param {any} displayObject - The display object to move. + * @param {number} x - The x coordinate to accelerate towards. + * @param {number} y - The y coordinate to accelerate towards. + * @param {number} [speed=60] - The speed it will accelerate in pixels per second. + * @param {number} [xSpeedMax=500] - The maximum x velocity the display object can reach. + * @param {number} [ySpeedMax=500] - The maximum y velocity the display object can reach. + * @return {number} The angle (in radians) that the object should be visually set to in order to match its new trajectory. + */ accelerateToXY: function (displayObject, x, y, speed, xSpeedMax, ySpeedMax) { - if (speed === undefined) { speed = 60; } if (xSpeedMax === undefined) { xSpeedMax = 1000; } if (ySpeedMax === undefined) { ySpeedMax = 1000; } @@ -1980,32 +1909,30 @@ Phaser.Physics.Arcade.prototype = { displayObject.body.maxVelocity.setTo(xSpeedMax, ySpeedMax); return angle; - }, /** - * Find the distance between two display objects (like Sprites). - * - * The optional `world` argument allows you to return the result based on the Game Objects `world` property, - * instead of its `x` and `y` values. This is useful of the object has been nested inside an offset Group, - * or parent Game Object. - * - * If you have nested objects and need to calculate the distance between their centers in World coordinates, - * set their anchors to (0.5, 0.5) and use the `world` argument. - * - * If objects aren't nested or they share a parent's offset, you can calculate the distance between their - * centers with the `useCenter` argument, regardless of their anchor values. - * - * @method Phaser.Physics.Arcade#distanceBetween - * @param {any} source - The Display Object to test from. - * @param {any} target - The Display Object to test to. - * @param {boolean} [world=false] - Calculate the distance using World coordinates (true), or Object coordinates (false, the default). If `useCenter` is true, this value is ignored. - * @param {boolean} [useCenter=false] - Calculate the distance using the {@link Phaser.Sprite#centerX} and {@link Phaser.Sprite#centerY} coordinates. If true, this value overrides the `world` argument. - * @return {number} The distance between the source and target objects. - */ + * Find the distance between two display objects (like Sprites). + * + * The optional `world` argument allows you to return the result based on the Game Objects `world` property, + * instead of its `x` and `y` values. This is useful of the object has been nested inside an offset Group, + * or parent Game Object. + * + * If you have nested objects and need to calculate the distance between their centers in World coordinates, + * set their anchors to (0.5, 0.5) and use the `world` argument. + * + * If objects aren't nested or they share a parent's offset, you can calculate the distance between their + * centers with the `useCenter` argument, regardless of their anchor values. + * + * @method Phaser.Physics.Arcade#distanceBetween + * @param {any} source - The Display Object to test from. + * @param {any} target - The Display Object to test to. + * @param {boolean} [world=false] - Calculate the distance using World coordinates (true), or Object coordinates (false, the default). If `useCenter` is true, this value is ignored. + * @param {boolean} [useCenter=false] - Calculate the distance using the {@link Phaser.Sprite#centerX} and {@link Phaser.Sprite#centerY} coordinates. If true, this value overrides the `world` argument. + * @return {number} The distance between the source and target objects. + */ distanceBetween: function (source, target, world, useCenter) { - if (world === undefined) { world = false; } var dx; @@ -2028,55 +1955,51 @@ Phaser.Physics.Arcade.prototype = { } return Math.sqrt(dx * dx + dy * dy); - }, /** - * Find the distance between a display object (like a Sprite) and the given x/y coordinates. - * The calculation is made from the display objects x/y coordinate. This may be the top-left if its anchor hasn't been changed. - * If you need to calculate from the center of a display object instead use {@link #distanceBetween} with the `useCenter` argument. - * - * The optional `world` argument allows you to return the result based on the Game Objects `world` property, - * instead of its `x` and `y` values. This is useful of the object has been nested inside an offset Group, - * or parent Game Object. - * - * @method Phaser.Physics.Arcade#distanceToXY - * @param {any} displayObject - The Display Object to test from. - * @param {number} x - The x coordinate to move towards. - * @param {number} y - The y coordinate to move towards. - * @param {boolean} [world=false] - Calculate the distance using World coordinates (true), or Object coordinates (false, the default) - * @return {number} The distance between the object and the x/y coordinates. - */ + * Find the distance between a display object (like a Sprite) and the given x/y coordinates. + * The calculation is made from the display objects x/y coordinate. This may be the top-left if its anchor hasn't been changed. + * If you need to calculate from the center of a display object instead use {@link #distanceBetween} with the `useCenter` argument. + * + * The optional `world` argument allows you to return the result based on the Game Objects `world` property, + * instead of its `x` and `y` values. This is useful of the object has been nested inside an offset Group, + * or parent Game Object. + * + * @method Phaser.Physics.Arcade#distanceToXY + * @param {any} displayObject - The Display Object to test from. + * @param {number} x - The x coordinate to move towards. + * @param {number} y - The y coordinate to move towards. + * @param {boolean} [world=false] - Calculate the distance using World coordinates (true), or Object coordinates (false, the default) + * @return {number} The distance between the object and the x/y coordinates. + */ distanceToXY: function (displayObject, x, y, world) { - if (world === undefined) { world = false; } var dx = (world) ? displayObject.world.x - x : displayObject.x - x; var dy = (world) ? displayObject.world.y - y : displayObject.y - y; return Math.sqrt(dx * dx + dy * dy); - }, /** - * Find the distance between a display object (like a Sprite) and a Pointer. If no Pointer is given the Input.activePointer is used. - * The calculation is made from the display objects x/y coordinate. This may be the top-left if its anchor hasn't been changed. - * If you need to calculate from the center of a display object instead use {@link #distanceBetween} with the `useCenter` argument. - * - * The optional `world` argument allows you to return the result based on the Game Objects `world` property, - * instead of its `x` and `y` values. This is useful of the object has been nested inside an offset Group, - * or parent Game Object. - * - * @method Phaser.Physics.Arcade#distanceToPointer - * @param {any} displayObject - The Display Object to test from. - * @param {Phaser.Pointer} [pointer] - The Phaser.Pointer to test to. If none is given then Input.activePointer is used. - * @param {boolean} [world=false] - Calculate the distance using World coordinates (true), or Object coordinates (false, the default) - * @return {number} The distance between the object and the Pointer. - */ + * Find the distance between a display object (like a Sprite) and a Pointer. If no Pointer is given the Input.activePointer is used. + * The calculation is made from the display objects x/y coordinate. This may be the top-left if its anchor hasn't been changed. + * If you need to calculate from the center of a display object instead use {@link #distanceBetween} with the `useCenter` argument. + * + * The optional `world` argument allows you to return the result based on the Game Objects `world` property, + * instead of its `x` and `y` values. This is useful of the object has been nested inside an offset Group, + * or parent Game Object. + * + * @method Phaser.Physics.Arcade#distanceToPointer + * @param {any} displayObject - The Display Object to test from. + * @param {Phaser.Pointer} [pointer] - The Phaser.Pointer to test to. If none is given then Input.activePointer is used. + * @param {boolean} [world=false] - Calculate the distance using World coordinates (true), or Object coordinates (false, the default) + * @return {number} The distance between the object and the Pointer. + */ distanceToPointer: function (displayObject, pointer, world) { - if (pointer === undefined) { pointer = this.game.input.activePointer; } if (world === undefined) { world = false; } @@ -2084,20 +2007,19 @@ Phaser.Physics.Arcade.prototype = { var dy = (world) ? displayObject.world.y - pointer.worldY : displayObject.y - pointer.worldY; return Math.sqrt(dx * dx + dy * dy); - }, /** - * From a set of points or display objects, find the one closest to a source point or object. - * - * @method Phaser.Physics.Arcade#closest - * @param {any} source - The {@link Phaser.Point Point} or Display Object distances will be measured from. - * @param {any[]} targets - The {@link Phaser.Point Points} or Display Objects whose distances to the source will be compared. - * @param {boolean} [world=false] - Calculate the distance using World coordinates (true), or Object coordinates (false, the default). If `useCenter` is true, this value is ignored. - * @param {boolean} [useCenter=false] - Calculate the distance using the {@link Phaser.Sprite#centerX} and {@link Phaser.Sprite#centerY} coordinates. If true, this value overrides the `world` argument. - * @return {any} - The first target closest to the origin. - */ + * From a set of points or display objects, find the one closest to a source point or object. + * + * @method Phaser.Physics.Arcade#closest + * @param {any} source - The {@link Phaser.Point Point} or Display Object distances will be measured from. + * @param {any[]} targets - The {@link Phaser.Point Points} or Display Objects whose distances to the source will be compared. + * @param {boolean} [world=false] - Calculate the distance using World coordinates (true), or Object coordinates (false, the default). If `useCenter` is true, this value is ignored. + * @param {boolean} [useCenter=false] - Calculate the distance using the {@link Phaser.Sprite#centerX} and {@link Phaser.Sprite#centerY} coordinates. If true, this value overrides the `world` argument. + * @return {any} - The first target closest to the origin. + */ closest: function (source, targets, world, useCenter) { var min = Infinity; @@ -2119,15 +2041,15 @@ Phaser.Physics.Arcade.prototype = { }, /** - * From a set of points or display objects, find the one farthest from a source point or object. - * - * @method Phaser.Physics.Arcade#farthest - * @param {any} source - The {@link Phaser.Point Point} or Display Object distances will be measured from. - * @param {any[]} targets - The {@link Phaser.Point Points} or Display Objects whose distances to the source will be compared. - * @param {boolean} [world=false] - Calculate the distance using World coordinates (true), or Object coordinates (false, the default). If `useCenter` is true, this value is ignored. - * @param {boolean} [useCenter=false] - Calculate the distance using the {@link Phaser.Sprite#centerX} and {@link Phaser.Sprite#centerY} coordinates. If true, this value overrides the `world` argument. - * @return {any} - The target closest to the origin. - */ + * From a set of points or display objects, find the one farthest from a source point or object. + * + * @method Phaser.Physics.Arcade#farthest + * @param {any} source - The {@link Phaser.Point Point} or Display Object distances will be measured from. + * @param {any[]} targets - The {@link Phaser.Point Points} or Display Objects whose distances to the source will be compared. + * @param {boolean} [world=false] - Calculate the distance using World coordinates (true), or Object coordinates (false, the default). If `useCenter` is true, this value is ignored. + * @param {boolean} [useCenter=false] - Calculate the distance using the {@link Phaser.Sprite#centerX} and {@link Phaser.Sprite#centerY} coordinates. If true, this value overrides the `world` argument. + * @return {any} - The target closest to the origin. + */ farthest: function (source, targets, world, useCenter) { var max = -1; @@ -2149,21 +2071,20 @@ Phaser.Physics.Arcade.prototype = { }, /** - * Find the angle in radians between two display objects (like Sprites). - * - * The optional `world` argument allows you to return the result based on the Game Objects `world` property, - * instead of its `x` and `y` values. This is useful of the object has been nested inside an offset Group, - * or parent Game Object. - * - * @method Phaser.Physics.Arcade#angleBetween - * @param {any} source - The Display Object to test from. - * @param {any} target - The Display Object to test to. - * @param {boolean} [world=false] - Calculate the angle using World coordinates (true), or Object coordinates (false, the default) - * @return {number} The angle in radians between the source and target display objects. - */ + * Find the angle in radians between two display objects (like Sprites). + * + * The optional `world` argument allows you to return the result based on the Game Objects `world` property, + * instead of its `x` and `y` values. This is useful of the object has been nested inside an offset Group, + * or parent Game Object. + * + * @method Phaser.Physics.Arcade#angleBetween + * @param {any} source - The Display Object to test from. + * @param {any} target - The Display Object to test to. + * @param {boolean} [world=false] - Calculate the angle using World coordinates (true), or Object coordinates (false, the default) + * @return {number} The angle in radians between the source and target display objects. + */ angleBetween: function (source, target, world) { - if (world === undefined) { world = false; } if (world) @@ -2174,44 +2095,40 @@ Phaser.Physics.Arcade.prototype = { { return Phaser.Point.angle(target, source); } - }, /** - * Find the angle in radians between centers of two display objects (like Sprites). - * - * @method Phaser.Physics.Arcade#angleBetweenCenters - * @param {any} source - The Display Object to test from. - * @param {any} target - The Display Object to test to. - * @return {number} The angle in radians between the source and target display objects. - */ + * Find the angle in radians between centers of two display objects (like Sprites). + * + * @method Phaser.Physics.Arcade#angleBetweenCenters + * @param {any} source - The Display Object to test from. + * @param {any} target - The Display Object to test to. + * @return {number} The angle in radians between the source and target display objects. + */ angleBetweenCenters: function (source, target) { - var dx = target.centerX - source.centerX; var dy = target.centerY - source.centerY; return Math.atan2(dy, dx); - }, /** - * Find the angle in radians between a display object (like a Sprite) and the given x/y coordinate. - * - * The optional `world` argument allows you to return the result based on the Game Objects `world` property, - * instead of its `x` and `y` values. This is useful of the object has been nested inside an offset Group, - * or parent Game Object. - * - * @method Phaser.Physics.Arcade#angleToXY - * @param {any} displayObject - The Display Object to test from. - * @param {number} x - The x coordinate to get the angle to. - * @param {number} y - The y coordinate to get the angle to. - * @param {boolean} [world=false] - Calculate the angle using World coordinates (true), or Object coordinates (false, the default) - * @return {number} The angle in radians between displayObject.x/y to Pointer.x/y - */ + * Find the angle in radians between a display object (like a Sprite) and the given x/y coordinate. + * + * The optional `world` argument allows you to return the result based on the Game Objects `world` property, + * instead of its `x` and `y` values. This is useful of the object has been nested inside an offset Group, + * or parent Game Object. + * + * @method Phaser.Physics.Arcade#angleToXY + * @param {any} displayObject - The Display Object to test from. + * @param {number} x - The x coordinate to get the angle to. + * @param {number} y - The y coordinate to get the angle to. + * @param {boolean} [world=false] - Calculate the angle using World coordinates (true), or Object coordinates (false, the default) + * @return {number} The angle in radians between displayObject.x/y to Pointer.x/y + */ angleToXY: function (displayObject, x, y, world) { - if (world === undefined) { world = false; } if (world) @@ -2222,25 +2139,23 @@ Phaser.Physics.Arcade.prototype = { { return Math.atan2(y - displayObject.y, x - displayObject.x); } - }, /** - * Find the angle in radians between a display object (like a Sprite) and a Pointer, taking their x/y and center into account. - * - * The optional `world` argument allows you to return the result based on the Game Objects `world` property, - * instead of its `x` and `y` values. This is useful of the object has been nested inside an offset Group, - * or parent Game Object. - * - * @method Phaser.Physics.Arcade#angleToPointer - * @param {any} displayObject - The Display Object to test from. - * @param {Phaser.Pointer} [pointer] - The Phaser.Pointer to test to. If none is given then Input.activePointer is used. - * @param {boolean} [world=false] - Calculate the angle using World coordinates (true), or Object coordinates (false, the default) - * @return {number} The angle in radians between displayObject.x/y to Pointer.x/y - */ + * Find the angle in radians between a display object (like a Sprite) and a Pointer, taking their x/y and center into account. + * + * The optional `world` argument allows you to return the result based on the Game Objects `world` property, + * instead of its `x` and `y` values. This is useful of the object has been nested inside an offset Group, + * or parent Game Object. + * + * @method Phaser.Physics.Arcade#angleToPointer + * @param {any} displayObject - The Display Object to test from. + * @param {Phaser.Pointer} [pointer] - The Phaser.Pointer to test to. If none is given then Input.activePointer is used. + * @param {boolean} [world=false] - Calculate the angle using World coordinates (true), or Object coordinates (false, the default) + * @return {number} The angle in radians between displayObject.x/y to Pointer.x/y + */ angleToPointer: function (displayObject, pointer, world) { - if (pointer === undefined) { pointer = this.game.input.activePointer; } if (world === undefined) { world = false; } @@ -2252,23 +2167,20 @@ Phaser.Physics.Arcade.prototype = { { return Math.atan2(pointer.worldY - displayObject.y, pointer.worldX - displayObject.x); } - }, /** - * Find the angle in radians between a display object (like a Sprite) and a Pointer, - * taking their x/y and center into account relative to the world. - * - * @method Phaser.Physics.Arcade#worldAngleToPointer - * @param {any} displayObject - The DisplayObjerct to test from. - * @param {Phaser.Pointer} [pointer] - The Phaser.Pointer to test to. If none is given then Input.activePointer is used. - * @return {number} The angle in radians between displayObject.world.x/y to Pointer.worldX / worldY - */ + * Find the angle in radians between a display object (like a Sprite) and a Pointer, + * taking their x/y and center into account relative to the world. + * + * @method Phaser.Physics.Arcade#worldAngleToPointer + * @param {any} displayObject - The DisplayObjerct to test from. + * @param {Phaser.Pointer} [pointer] - The Phaser.Pointer to test to. If none is given then Input.activePointer is used. + * @return {number} The angle in radians between displayObject.world.x/y to Pointer.worldX / worldY + */ worldAngleToPointer: function (displayObject, pointer) { - return this.angleToPointer(displayObject, pointer, true); - } }; diff --git a/src/pixi/display/DisplayObject.js b/src/pixi/display/DisplayObject.js index b8d15ff04..ebd0bceab 100644 --- a/src/pixi/display/DisplayObject.js +++ b/src/pixi/display/DisplayObject.js @@ -1,93 +1,92 @@ /** -* @author Mat Groves http://matgroves.com @Doormat23 -* @author Richard Davey -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Mat Groves http://matgroves.com @Doormat23 + * @author Richard Davey + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* The base class for all objects that are rendered. Contains properties for position, scaling, -* rotation, masks and cache handling. -* -* This is an abstract class and should not be used on its own, rather it should be extended. -* -* It is used internally by the likes of PIXI.Sprite. -* -* @class PIXI.DisplayObject -* @constructor -*/ + * The base class for all objects that are rendered. Contains properties for position, scaling, + * rotation, masks and cache handling. + * + * This is an abstract class and should not be used on its own, rather it should be extended. + * + * It is used internally by the likes of PIXI.Sprite. + * + * @class PIXI.DisplayObject + * @constructor + */ PIXI.DisplayObject = function () { - /** - * The coordinates, in pixels, of this DisplayObject, relative to its parent container. - * - * The value of this property does not reflect any positioning happening further up the display list. - * To obtain that value please see the `worldPosition` property. - * - * @property {PIXI.Point} position - * @default - */ + * The coordinates, in pixels, of this DisplayObject, relative to its parent container. + * + * The value of this property does not reflect any positioning happening further up the display list. + * To obtain that value please see the `worldPosition` property. + * + * @property {PIXI.Point} position + * @default + */ this.position = new PIXI.Point(0, 0); /** - * The scale of this DisplayObject. A scale of 1:1 represents the DisplayObject - * at its default size. A value of 0.5 would scale this DisplayObject by half, and so on. - * - * The value of this property does not reflect any scaling happening further up the display list. - * To obtain that value please see the `worldScale` property. - * - * @property {PIXI.Point} scale - * @default - */ + * The scale of this DisplayObject. A scale of 1:1 represents the DisplayObject + * at its default size. A value of 0.5 would scale this DisplayObject by half, and so on. + * + * The value of this property does not reflect any scaling happening further up the display list. + * To obtain that value please see the `worldScale` property. + * + * @property {PIXI.Point} scale + * @default + */ this.scale = new PIXI.Point(1, 1); /** - * The pivot point of this DisplayObject that it rotates around. The values are expressed - * in pixel values. - * @property {PIXI.Point} pivot - * @default - */ + * The pivot point of this DisplayObject that it rotates around. The values are expressed + * in pixel values. + * @property {PIXI.Point} pivot + * @default + */ this.pivot = new PIXI.Point(0, 0); /** - * The rotation of this DisplayObject. The value is given, and expressed, in radians, and is based on - * a right-handed orientation. - * - * The value of this property does not reflect any rotation happening further up the display list. - * To obtain that value please see the `worldRotation` property. - * - * @property {number} rotation - * @default - */ + * The rotation of this DisplayObject. The value is given, and expressed, in radians, and is based on + * a right-handed orientation. + * + * The value of this property does not reflect any rotation happening further up the display list. + * To obtain that value please see the `worldRotation` property. + * + * @property {number} rotation + * @default + */ this.rotation = 0; /** - * The alpha value of this DisplayObject. A value of 1 is fully opaque. A value of 0 is transparent. - * Please note that an object with an alpha value of 0 is skipped during the render pass. - * - * The value of this property does not reflect any alpha values set further up the display list. - * To obtain that value please see the `worldAlpha` property. - * - * @property {number} alpha - * @default - */ + * The alpha value of this DisplayObject. A value of 1 is fully opaque. A value of 0 is transparent. + * Please note that an object with an alpha value of 0 is skipped during the render pass. + * + * The value of this property does not reflect any alpha values set further up the display list. + * To obtain that value please see the `worldAlpha` property. + * + * @property {number} alpha + * @default + */ this.alpha = 1; /** - * The visibility of this DisplayObject. A value of `false` makes the object invisible. - * A value of `true` makes it visible. - * - * An object with a visible value of `false` is skipped during the render pass. - * Equally a DisplayObject with visible `false` will not render any of its children. - * - * The value of this property does not reflect any visible values set further up the display list. - * To obtain that value please see the {@link #worldVisible} property. - * - * Objects that are not {@link #worldVisible} do not update their {@link #worldPosition}. - * - * @property {boolean} visible - * @default - */ + * The visibility of this DisplayObject. A value of `false` makes the object invisible. + * A value of `true` makes it visible. + * + * An object with a visible value of `false` is skipped during the render pass. + * Equally a DisplayObject with visible `false` will not render any of its children. + * + * The value of this property does not reflect any visible values set further up the display list. + * To obtain that value please see the {@link #worldVisible} property. + * + * Objects that are not {@link #worldVisible} do not update their {@link #worldPosition}. + * + * @property {boolean} visible + * @default + */ this.visible = true; /** @@ -100,153 +99,152 @@ PIXI.DisplayObject = function () this.hitArea = null; /** - * Should this DisplayObject be rendered by the renderer? An object with a renderable value of - * `false` is skipped during the render pass. - * - * @property {boolean} renderable - * @default - */ + * Should this DisplayObject be rendered by the renderer? An object with a renderable value of + * `false` is skipped during the render pass. + * + * @property {boolean} renderable + * @default + */ this.renderable = false; /** - * The parent DisplayObjectContainer that this DisplayObject is a child of. - * All DisplayObjects must belong to a parent in order to be rendered. - * The root parent is the Stage object. This property is set automatically when the - * DisplayObject is added to, or removed from, a DisplayObjectContainer. - * - * @property {PIXI.DisplayObjectContainer} parent - * @default - * @readOnly - */ + * The parent DisplayObjectContainer that this DisplayObject is a child of. + * All DisplayObjects must belong to a parent in order to be rendered. + * The root parent is the Stage object. This property is set automatically when the + * DisplayObject is added to, or removed from, a DisplayObjectContainer. + * + * @property {PIXI.DisplayObjectContainer} parent + * @default + * @readOnly + */ this.parent = null; /** - * The multiplied alpha value of this DisplayObject. A value of 1 is fully opaque. A value of 0 is transparent. - * This value is the calculated total, based on the alpha values of all parents of this DisplayObjects - * in the display list. - * - * To obtain, and set, the local alpha value, see the `alpha` property. - * - * Note: This property is only updated at the end of the `updateTransform` call, once per render. Until - * that happens this property will contain values based on the previous frame. Be mindful of this if - * accessing this property outside of the normal game flow, i.e. from an asynchronous event callback. - * - * @property {number} worldAlpha - * @readOnly - */ + * The multiplied alpha value of this DisplayObject. A value of 1 is fully opaque. A value of 0 is transparent. + * This value is the calculated total, based on the alpha values of all parents of this DisplayObjects + * in the display list. + * + * To obtain, and set, the local alpha value, see the `alpha` property. + * + * Note: This property is only updated at the end of the `updateTransform` call, once per render. Until + * that happens this property will contain values based on the previous frame. Be mindful of this if + * accessing this property outside of the normal game flow, i.e. from an asynchronous event callback. + * + * @property {number} worldAlpha + * @readOnly + */ this.worldAlpha = 1; /** - * The current transform of this DisplayObject. - * - * This property contains the calculated total, based on the transforms of all parents of this - * DisplayObject in the display list. - * - * Note: This property is only updated at the end of the `updateTransform` call, once per render. Until - * that happens this property will contain values based on the previous frame. Be mindful of this if - * accessing this property outside of the normal game flow, i.e. from an asynchronous event callback. - * - * @property {Phaser.Matrix} worldTransform - * @readOnly - */ + * The current transform of this DisplayObject. + * + * This property contains the calculated total, based on the transforms of all parents of this + * DisplayObject in the display list. + * + * Note: This property is only updated at the end of the `updateTransform` call, once per render. Until + * that happens this property will contain values based on the previous frame. Be mindful of this if + * accessing this property outside of the normal game flow, i.e. from an asynchronous event callback. + * + * @property {Phaser.Matrix} worldTransform + * @readOnly + */ this.worldTransform = new Phaser.Matrix(); /** - * The coordinates, in pixels, of this DisplayObject within the world. - * - * This property contains the calculated total, based on the positions of all parents of this - * DisplayObject in the display list. - * - * Note: This property is only updated at the end of the `updateTransform` call, once per render. Until - * that happens this property will contain values based on the previous frame. Be mindful of this if - * accessing this property outside of the normal game flow, i.e. from an asynchronous event callback. - * - * @property {PIXI.Point} worldPosition - * @readOnly - */ + * The coordinates, in pixels, of this DisplayObject within the world. + * + * This property contains the calculated total, based on the positions of all parents of this + * DisplayObject in the display list. + * + * Note: This property is only updated at the end of the `updateTransform` call, once per render. Until + * that happens this property will contain values based on the previous frame. Be mindful of this if + * accessing this property outside of the normal game flow, i.e. from an asynchronous event callback. + * + * @property {PIXI.Point} worldPosition + * @readOnly + */ this.worldPosition = new PIXI.Point(0, 0); /** - * The global scale of this DisplayObject. - * - * This property contains the calculated total, based on the scales of all parents of this - * DisplayObject in the display list. - * - * Note: This property is only updated at the end of the `updateTransform` call, once per render. Until - * that happens this property will contain values based on the previous frame. Be mindful of this if - * accessing this property outside of the normal game flow, i.e. from an asynchronous event callback. - * - * @property {PIXI.Point} worldScale - * @readOnly - */ + * The global scale of this DisplayObject. + * + * This property contains the calculated total, based on the scales of all parents of this + * DisplayObject in the display list. + * + * Note: This property is only updated at the end of the `updateTransform` call, once per render. Until + * that happens this property will contain values based on the previous frame. Be mindful of this if + * accessing this property outside of the normal game flow, i.e. from an asynchronous event callback. + * + * @property {PIXI.Point} worldScale + * @readOnly + */ this.worldScale = new PIXI.Point(1, 1); /** - * The rotation, in radians, of this DisplayObject. - * - * This property contains the calculated total, based on the rotations of all parents of this - * DisplayObject in the display list. - * - * Note: This property is only updated at the end of the `updateTransform` call, once per render. Until - * that happens this property will contain values based on the previous frame. Be mindful of this if - * accessing this property outside of the normal game flow, i.e. from an asynchronous event callback. - * - * @property {number} worldRotation - * @readOnly - */ + * The rotation, in radians, of this DisplayObject. + * + * This property contains the calculated total, based on the rotations of all parents of this + * DisplayObject in the display list. + * + * Note: This property is only updated at the end of the `updateTransform` call, once per render. Until + * that happens this property will contain values based on the previous frame. Be mindful of this if + * accessing this property outside of the normal game flow, i.e. from an asynchronous event callback. + * + * @property {number} worldRotation + * @readOnly + */ this.worldRotation = 0; /** - * The rectangular area used by filters when rendering a shader for this DisplayObject. - * - * @property {PIXI.Rectangle} filterArea - * @type Rectangle - * @default - */ + * The rectangular area used by filters when rendering a shader for this DisplayObject. + * + * @property {PIXI.Rectangle} filterArea + * @type Rectangle + * @default + */ this.filterArea = null; /** - * @property {number} _sr - Cached rotation value. - * @private - */ + * @property {number} _sr - Cached rotation value. + * @private + */ this._sr = 0; /** - * @property {number} _cr - Cached rotation value. - * @private - */ + * @property {number} _cr - Cached rotation value. + * @private + */ this._cr = 1; /** - * @property {PIXI.Rectangle} _bounds - The cached bounds of this object. - * @private - */ + * @property {PIXI.Rectangle} _bounds - The cached bounds of this object. + * @private + */ this._bounds = new PIXI.Rectangle(0, 0, 0, 0); /** - * @property {PIXI.Rectangle} _currentBounds - The most recently calculated bounds of this object. - * @private - */ + * @property {PIXI.Rectangle} _currentBounds - The most recently calculated bounds of this object. + * @private + */ this._currentBounds = null; /** - * @property {PIXI.Rectangle} _mask - The cached mask of this object. - * @private - */ + * @property {PIXI.Rectangle} _mask - The cached mask of this object. + * @private + */ this._mask = null; /** - * @property {boolean} _cacheAsBitmap - Internal cache as bitmap flag. - * @private - */ + * @property {boolean} _cacheAsBitmap - Internal cache as bitmap flag. + * @private + */ this._cacheAsBitmap = false; /** - * @property {boolean} _cacheIsDirty - Internal dirty cache flag. - * @private - */ + * @property {boolean} _cacheIsDirty - Internal dirty cache flag. + * @private + */ this._cacheIsDirty = false; - }; PIXI.DisplayObject.prototype = { @@ -254,17 +252,16 @@ PIXI.DisplayObject.prototype = { constructor: PIXI.DisplayObject, /** - * Destroy this DisplayObject. - * - * Removes any cached sprites, sets renderable flag to false, and nulls filters, bounds and mask. - * - * Also iteratively calls `destroy` on any children. - * - * @method PIXI.DisplayObject#destroy - */ + * Destroy this DisplayObject. + * + * Removes any cached sprites, sets renderable flag to false, and nulls filters, bounds and mask. + * + * Also iteratively calls `destroy` on any children. + * + * @method PIXI.DisplayObject#destroy + */ destroy: function () { - if (this.children) { var i = this.children.length; @@ -289,31 +286,29 @@ PIXI.DisplayObject.prototype = { this._destroyCachedSprite(); this._destroyTintedTexture(); - }, /** - * Updates the transform matrix this DisplayObject uses for rendering. - * - * If the object has no parent, and no parent parameter is provided, it will default to - * Phaser.Game.World as the parent transform to use. If that is unavailable the transform fails to take place. - * - * The `parent` parameter has priority over the actual parent. Use it as a parent override. - * Setting it does **not** change the actual parent of this DisplayObject. - * - * Calling this method updates the `worldTransform`, `worldAlpha`, `worldPosition`, `worldScale` - * and `worldRotation` properties. - * - * If a `transformCallback` has been specified, it is called at the end of this method, and is passed - * the new, updated, worldTransform property, along with the parent transform used. - * - * @method PIXI.DisplayObject#updateTransform - * @param {PIXI.DisplayObjectContainer} [parent] - Optional parent to calculate this DisplayObjects transform from. - * @return {PIXI.DisplayObject} - A reference to this DisplayObject. - */ + * Updates the transform matrix this DisplayObject uses for rendering. + * + * If the object has no parent, and no parent parameter is provided, it will default to + * Phaser.Game.World as the parent transform to use. If that is unavailable the transform fails to take place. + * + * The `parent` parameter has priority over the actual parent. Use it as a parent override. + * Setting it does **not** change the actual parent of this DisplayObject. + * + * Calling this method updates the `worldTransform`, `worldAlpha`, `worldPosition`, `worldScale` + * and `worldRotation` properties. + * + * If a `transformCallback` has been specified, it is called at the end of this method, and is passed + * the new, updated, worldTransform property, along with the parent transform used. + * + * @method PIXI.DisplayObject#updateTransform + * @param {PIXI.DisplayObjectContainer} [parent] - Optional parent to calculate this DisplayObjects transform from. + * @return {PIXI.DisplayObject} - A reference to this DisplayObject. + */ updateTransform: function (parent) { - if (!parent && !this.parent && !this.game) { return this; @@ -433,35 +428,33 @@ PIXI.DisplayObject.prototype = { } return this; - }, /** - * To be overridden by classes that require it. - * - * @method PIXI.DisplayObject#preUpdate - */ + * To be overridden by classes that require it. + * + * @method PIXI.DisplayObject#preUpdate + */ preUpdate: function () { }, /** - * Generates a RenderTexture based on this DisplayObject, which can they be used to texture other Sprites. - * This can be useful if your DisplayObject is static, or complicated, and needs to be reused multiple times. - * - * Please note that no garbage collection takes place on old textures. It is up to you to destroy old textures, - * and references to them, so they don't linger in memory. - * - * @method PIXI.DisplayObject#generateTexture - * @param {number} [resolution=1] - The resolution of the texture being generated. - * @param {number} [scaleMode=PIXI.scaleModes.DEFAULT] - See {{#crossLink "PIXI/scaleModes:property"}}PIXI.scaleModes{{/crossLink}} for possible values. - * @param {PIXI.CanvasRenderer|PIXI.WebGLRenderer} renderer - The renderer used to generate the texture. - * @return {Phaser.RenderTexture} - A RenderTexture containing an image of this DisplayObject at the time it was invoked. - */ + * Generates a RenderTexture based on this DisplayObject, which can they be used to texture other Sprites. + * This can be useful if your DisplayObject is static, or complicated, and needs to be reused multiple times. + * + * Please note that no garbage collection takes place on old textures. It is up to you to destroy old textures, + * and references to them, so they don't linger in memory. + * + * @method PIXI.DisplayObject#generateTexture + * @param {number} [resolution=1] - The resolution of the texture being generated. + * @param {number} [scaleMode=PIXI.scaleModes.DEFAULT] - See {{#crossLink "PIXI/scaleModes:property"}}PIXI.scaleModes{{/crossLink}} for possible values. + * @param {PIXI.CanvasRenderer|PIXI.WebGLRenderer} renderer - The renderer used to generate the texture. + * @return {Phaser.RenderTexture} - A RenderTexture containing an image of this DisplayObject at the time it was invoked. + */ generateTexture: function (resolution, scaleMode, renderer) { - var bounds = this.getLocalBounds(); var renderTexture = new Phaser.RenderTexture(this.game, bounds.width | 0, bounds.height | 0, renderer, scaleMode, resolution); @@ -472,51 +465,45 @@ PIXI.DisplayObject.prototype = { renderTexture.render(this, PIXI.DisplayObject._tempMatrix); return renderTexture; - }, /** - * If this DisplayObject has a cached Sprite, this method generates and updates it. - * - * @method PIXI.DisplayObject#updateCache - * @return {PIXI.DisplayObject} - A reference to this DisplayObject. - */ + * If this DisplayObject has a cached Sprite, this method generates and updates it. + * + * @method PIXI.DisplayObject#updateCache + * @return {PIXI.DisplayObject} - A reference to this DisplayObject. + */ updateCache: function () { - this._generateCachedSprite(); return this; - }, /** - * Calculates the global position of this DisplayObject, based on the position given. - * - * @method PIXI.DisplayObject#toGlobal - * @param {PIXI.Point} position - The global position to calculate from. - * @return {PIXI.Point} - A point object representing the position of this DisplayObject based on the global position given. - */ + * Calculates the global position of this DisplayObject, based on the position given. + * + * @method PIXI.DisplayObject#toGlobal + * @param {PIXI.Point} position - The global position to calculate from. + * @return {PIXI.Point} - A point object representing the position of this DisplayObject based on the global position given. + */ toGlobal: function (position) { - this.updateTransform(); return this.worldTransform.apply(position); - }, /** - * Calculates the local position of this DisplayObject, relative to another point. - * - * @method PIXI.DisplayObject#toLocal - * @param {PIXI.Point} position - The world origin to calculate from. - * @param {PIXI.DisplayObject} [from] - An optional DisplayObject to calculate the global position from. - * @return {PIXI.Point} - A point object representing the position of this DisplayObject based on the global position given. - */ + * Calculates the local position of this DisplayObject, relative to another point. + * + * @method PIXI.DisplayObject#toLocal + * @param {PIXI.Point} position - The world origin to calculate from. + * @param {PIXI.DisplayObject} [from] - An optional DisplayObject to calculate the global position from. + * @return {PIXI.Point} - A point object representing the position of this DisplayObject based on the global position given. + */ toLocal: function (position, from) { - if (from) { position = from.toGlobal(position); @@ -525,19 +512,17 @@ PIXI.DisplayObject.prototype = { this.updateTransform(); return this.worldTransform.applyInverse(position); - }, /** - * Internal method. - * - * @method PIXI.DisplayObject#_renderCachedSprite - * @private - * @param {Object} renderSession - The render session - */ + * Internal method. + * + * @method PIXI.DisplayObject#_renderCachedSprite + * @private + * @param {Object} renderSession - The render session + */ _renderCachedSprite: function (renderSession) { - this._cachedSprite.worldAlpha = this.worldAlpha; if (renderSession.gl) @@ -548,18 +533,16 @@ PIXI.DisplayObject.prototype = { { PIXI.Sprite.prototype._renderCanvas.call(this._cachedSprite, renderSession); } - }, /** - * Internal method. - * - * @method PIXI.DisplayObject#_generateCachedSprite - * @private - */ + * Internal method. + * + * @method PIXI.DisplayObject#_generateCachedSprite + * @private + */ _generateCachedSprite: function () { - this._cacheAsBitmap = false; var bounds = this.getLocalBounds(); @@ -601,18 +584,16 @@ PIXI.DisplayObject.prototype = { this._filters = tempFilters; this._cacheAsBitmap = true; - }, /** - * Destroys a cached Sprite. - * - * @method PIXI.DisplayObject#_destroyCachedSprite - * @private - */ + * Destroys a cached Sprite. + * + * @method PIXI.DisplayObject#_destroyCachedSprite + * @private + */ _destroyCachedSprite: function () { - if (!this._cachedSprite) { return; @@ -621,7 +602,6 @@ PIXI.DisplayObject.prototype = { this._cachedSprite.texture.destroy(true); this._cachedSprite = null; - }, _destroyTintedTexture: function () @@ -644,63 +624,54 @@ PIXI.DisplayObject.prototype.displayObjectUpdateTransform = PIXI.DisplayObject.p Object.defineProperties(PIXI.DisplayObject.prototype, { /** - * The horizontal position of the DisplayObject, in pixels, relative to its parent. - * If you need the world position of the DisplayObject, use `DisplayObject.worldPosition` instead. - * @name PIXI.DisplayObject#x - * @property {number} x - The horizontal position of the DisplayObject, in pixels, relative to its parent. - */ + * The horizontal position of the DisplayObject, in pixels, relative to its parent. + * If you need the world position of the DisplayObject, use `DisplayObject.worldPosition` instead. + * @name PIXI.DisplayObject#x + * @property {number} x - The horizontal position of the DisplayObject, in pixels, relative to its parent. + */ x: { get: function () { - return this.position.x; - }, set: function (value) { - this.position.x = value; - } }, /** - * The vertical position of the DisplayObject, in pixels, relative to its parent. - * If you need the world position of the DisplayObject, use `DisplayObject.worldPosition` instead. - * @name PIXI.DisplayObject#y - * @property {number} y - The vertical position of the DisplayObject, in pixels, relative to its parent. - */ + * The vertical position of the DisplayObject, in pixels, relative to its parent. + * If you need the world position of the DisplayObject, use `DisplayObject.worldPosition` instead. + * @name PIXI.DisplayObject#y + * @property {number} y - The vertical position of the DisplayObject, in pixels, relative to its parent. + */ y: { get: function () { - return this.position.y; - }, set: function (value) { - this.position.y = value; - } }, /** - * Indicates if this DisplayObject is visible, based on it, and all of its parents, `visible` property values. - * @name PIXI.DisplayObject#worldVisible - * @property {boolean} worldVisible - Indicates if this DisplayObject is visible, based on it, and all of its parents, `visible` property values. - */ + * Indicates if this DisplayObject is visible, based on it, and all of its parents, `visible` property values. + * @name PIXI.DisplayObject#worldVisible + * @property {boolean} worldVisible - Indicates if this DisplayObject is visible, based on it, and all of its parents, `visible` property values. + */ worldVisible: { get: function () { - if (!this.visible) { return false; @@ -725,37 +696,32 @@ Object.defineProperties(PIXI.DisplayObject.prototype, { item = item.parent; } while (item); - } return true; } - } }, /** - * Sets a mask for this DisplayObject. A mask is an instance of a Graphics object. - * When applied it limits the visible area of this DisplayObject to the shape of the mask. - * Under a Canvas renderer it uses shape clipping. Under a WebGL renderer it uses a Stencil Buffer. - * To remove a mask, set this property to `null`. - * - * @name PIXI.DisplayObject#mask - * @property {Phaser.Graphics} mask - The mask applied to this DisplayObject. Set to `null` to remove an existing mask. - */ + * Sets a mask for this DisplayObject. A mask is an instance of a Graphics object. + * When applied it limits the visible area of this DisplayObject to the shape of the mask. + * Under a Canvas renderer it uses shape clipping. Under a WebGL renderer it uses a Stencil Buffer. + * To remove a mask, set this property to `null`. + * + * @name PIXI.DisplayObject#mask + * @property {Phaser.Graphics} mask - The mask applied to this DisplayObject. Set to `null` to remove an existing mask. + */ mask: { get: function () { - return this._mask; - }, set: function (value) { - if (this._mask) { this._mask.isMask = false; @@ -767,36 +733,32 @@ Object.defineProperties(PIXI.DisplayObject.prototype, { { this._mask.isMask = true; } - } }, /** - * Sets the filters for this DisplayObject. This is a WebGL only feature, and is ignored by the Canvas - * Renderer. A filter is a shader applied to this DisplayObject. You can modify the placement of the filter - * using `DisplayObject.filterArea`. - * - * To remove filters, set this property to `null`. - * - * Note: You cannot have a filter set, and a MULTIPLY Blend Mode active, at the same time. Setting a - * filter will reset this DisplayObjects blend mode to NORMAL. - * - * @name PIXI.DisplayObject#filters - * @property {Array} filters - An Array of Phaser.Filter objects, or objects that extend them. - */ + * Sets the filters for this DisplayObject. This is a WebGL only feature, and is ignored by the Canvas + * Renderer. A filter is a shader applied to this DisplayObject. You can modify the placement of the filter + * using `DisplayObject.filterArea`. + * + * To remove filters, set this property to `null`. + * + * Note: You cannot have a filter set, and a MULTIPLY Blend Mode active, at the same time. Setting a + * filter will reset this DisplayObjects blend mode to NORMAL. + * + * @name PIXI.DisplayObject#filters + * @property {Array} filters - An Array of Phaser.Filter objects, or objects that extend them. + */ filters: { get: function () { - return this._filters; - }, set: function (value) { - if (Array.isArray(value)) { // Put all the passes in one place. @@ -822,40 +784,36 @@ Object.defineProperties(PIXI.DisplayObject.prototype, { { this.blendMode = PIXI.blendModes.NORMAL; } - } }, /** - * Sets if this DisplayObject should be cached as a bitmap. - * - * When invoked it will take a snapshot of the DisplayObject, as it is at that moment, and store it - * in a RenderTexture. This is then used whenever this DisplayObject is rendered. It can provide a - * performance benefit for complex, but static, DisplayObjects. I.e. those with lots of children. - * - * Transparent areas adjoining the edges may be removed ({@link https://github.com/photonstorm/phaser-ce/issues/283 #283}). - * - * Cached Bitmaps do not track their parents. If you update a property of this DisplayObject, it will not - * re-generate the cached bitmap automatically. To do that you need to call `DisplayObject.updateCache`. - * - * To remove a cached bitmap, set this property to `null`. - * - * @name PIXI.DisplayObject#cacheAsBitmap - * @property {boolean} cacheAsBitmap - Cache this DisplayObject as a Bitmap. Set to `null` to remove an existing cached bitmap. - */ + * Sets if this DisplayObject should be cached as a bitmap. + * + * When invoked it will take a snapshot of the DisplayObject, as it is at that moment, and store it + * in a RenderTexture. This is then used whenever this DisplayObject is rendered. It can provide a + * performance benefit for complex, but static, DisplayObjects. I.e. those with lots of children. + * + * Transparent areas adjoining the edges may be removed ({@link https://github.com/photonstorm/phaser-ce/issues/283 #283}). + * + * Cached Bitmaps do not track their parents. If you update a property of this DisplayObject, it will not + * re-generate the cached bitmap automatically. To do that you need to call `DisplayObject.updateCache`. + * + * To remove a cached bitmap, set this property to `null`. + * + * @name PIXI.DisplayObject#cacheAsBitmap + * @property {boolean} cacheAsBitmap - Cache this DisplayObject as a Bitmap. Set to `null` to remove an existing cached bitmap. + */ cacheAsBitmap: { get: function () { - return this._cacheAsBitmap; - }, set: function (value) { - if (this._cacheAsBitmap === value) { return; @@ -871,7 +829,6 @@ Object.defineProperties(PIXI.DisplayObject.prototype, { } this._cacheAsBitmap = value; - } } diff --git a/src/pixi/display/DisplayObjectContainer.js b/src/pixi/display/DisplayObjectContainer.js index 71024d0ce..35027790e 100644 --- a/src/pixi/display/DisplayObjectContainer.js +++ b/src/pixi/display/DisplayObjectContainer.js @@ -12,7 +12,6 @@ */ PIXI.DisplayObjectContainer = function () { - PIXI.DisplayObject.call(this); /** @@ -25,16 +24,15 @@ PIXI.DisplayObjectContainer = function () this.children = []; /** - * If `ignoreChildInput` is `false` it will allow this objects _children_ to be considered as valid for Input events. - * - * If this property is `true` then the children will _not_ be considered as valid for Input events. - * - * Note that this property isn't recursive: only immediate children are influenced, it doesn't scan further down. - * @property {boolean} ignoreChildInput - * @default - */ + * If `ignoreChildInput` is `false` it will allow this objects _children_ to be considered as valid for Input events. + * + * If this property is `true` then the children will _not_ be considered as valid for Input events. + * + * Note that this property isn't recursive: only immediate children are influenced, it doesn't scan further down. + * @property {boolean} ignoreChildInput + * @default + */ this.ignoreChildInput = false; - }; PIXI.DisplayObjectContainer.prototype = Object.create(PIXI.DisplayObject.prototype); @@ -49,9 +47,7 @@ PIXI.DisplayObjectContainer.prototype.constructor = PIXI.DisplayObjectContainer; */ PIXI.DisplayObjectContainer.prototype.addChild = function (child) { - return this.addChildAt(child, this.children.length); - }; /** @@ -64,7 +60,6 @@ PIXI.DisplayObjectContainer.prototype.addChild = function (child) */ PIXI.DisplayObjectContainer.prototype.addChildAt = function (child, index) { - if (index >= 0 && index <= this.children.length) { if (child.parent) @@ -82,7 +77,6 @@ PIXI.DisplayObjectContainer.prototype.addChildAt = function (child, index) { throw new Error(child + 'addChildAt: The index ' + index + ' supplied is out of bounds ' + this.children.length); } - }; /** @@ -94,7 +88,6 @@ PIXI.DisplayObjectContainer.prototype.addChildAt = function (child, index) */ PIXI.DisplayObjectContainer.prototype.swapChildren = function (child, child2) { - if (child === child2) { return; @@ -110,7 +103,6 @@ PIXI.DisplayObjectContainer.prototype.swapChildren = function (child, child2) this.children[index1] = child2; this.children[index2] = child; - }; /** @@ -122,7 +114,6 @@ PIXI.DisplayObjectContainer.prototype.swapChildren = function (child, child2) */ PIXI.DisplayObjectContainer.prototype.getChildIndex = function (child) { - var index = this.children.indexOf(child); if (index === -1) @@ -131,7 +122,6 @@ PIXI.DisplayObjectContainer.prototype.getChildIndex = function (child) } return index; - }; /** @@ -143,7 +133,6 @@ PIXI.DisplayObjectContainer.prototype.getChildIndex = function (child) */ PIXI.DisplayObjectContainer.prototype.setChildIndex = function (child, index) { - if (index < 0 || index >= this.children.length) { throw new Error('The supplied index is out of bounds'); @@ -153,7 +142,6 @@ PIXI.DisplayObjectContainer.prototype.setChildIndex = function (child, index) this.children.splice(currentIndex, 1); // remove from old position this.children.splice(index, 0, child); // add at new position - }; /** @@ -165,14 +153,12 @@ PIXI.DisplayObjectContainer.prototype.setChildIndex = function (child, index) */ PIXI.DisplayObjectContainer.prototype.getChildAt = function (index) { - if (index < 0 || index >= this.children.length) { throw new Error('getChildAt: Supplied index ' + index + ' does not exist in the child list, or the supplied DisplayObject must be a child of the caller'); } return this.children[index]; - }; /** @@ -184,7 +170,6 @@ PIXI.DisplayObjectContainer.prototype.getChildAt = function (index) */ PIXI.DisplayObjectContainer.prototype.removeChild = function (child) { - var index = this.children.indexOf(child); if (index === -1) @@ -193,7 +178,6 @@ PIXI.DisplayObjectContainer.prototype.removeChild = function (child) } return this.removeChildAt(index); - }; /** @@ -205,7 +189,6 @@ PIXI.DisplayObjectContainer.prototype.removeChild = function (child) */ PIXI.DisplayObjectContainer.prototype.removeChildAt = function (index) { - var child = this.getChildAt(index); if (child) @@ -216,43 +199,37 @@ PIXI.DisplayObjectContainer.prototype.removeChildAt = function (index) } return child; - }; PIXI.DisplayObjectContainer.prototype.bringChildToTop = function (child) { - if (child.parent !== this) { return; } return this.setChildIndex(child, this.children.length - 1); - }; PIXI.DisplayObjectContainer.prototype.sendChildToBack = function (child) { - if (child.parent !== this) { return; } return this.setChildIndex(child, 0); - }; /** -* Removes all children from this container that are within the begin and end indexes. -* -* @method PIXI.DisplayObjectContainer#removeChildren -* @param beginIndex {Number} The beginning position. Default value is 0. -* @param endIndex {Number} The ending position. Default value is size of the container. -*/ + * Removes all children from this container that are within the begin and end indexes. + * + * @method PIXI.DisplayObjectContainer#removeChildren + * @param beginIndex {Number} The beginning position. Default value is 0. + * @param endIndex {Number} The ending position. Default value is size of the container. + */ PIXI.DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) { - if (beginIndex === undefined) { beginIndex = 0; } if (endIndex === undefined) { endIndex = this.children.length; } @@ -278,7 +255,6 @@ PIXI.DisplayObjectContainer.prototype.removeChildren = function (beginIndex, end { throw new Error('removeChildren: Range Error, numeric values are outside the acceptable range'); } - }; /* @@ -289,7 +265,6 @@ PIXI.DisplayObjectContainer.prototype.removeChildren = function (beginIndex, end */ PIXI.DisplayObjectContainer.prototype.updateTransform = function () { - if (!this.visible) { return; @@ -306,7 +281,6 @@ PIXI.DisplayObjectContainer.prototype.updateTransform = function () { this.children[i].updateTransform(); } - }; // performance increase to avoid using call.. (10x faster) @@ -321,7 +295,6 @@ PIXI.DisplayObjectContainer.prototype.displayObjectContainerUpdateTransform = PI */ PIXI.DisplayObjectContainer.prototype.getBounds = function (targetCoordinateSpace) { - var isTargetCoordinateSpaceDisplayObject = (targetCoordinateSpace && targetCoordinateSpace instanceof PIXI.DisplayObject); var isTargetCoordinateSpaceThisOrParent = true; @@ -467,7 +440,6 @@ PIXI.DisplayObjectContainer.prototype.getBounds = function (targetCoordinateSpac } return bounds; - }; /** @@ -478,21 +450,18 @@ PIXI.DisplayObjectContainer.prototype.getBounds = function (targetCoordinateSpac */ PIXI.DisplayObjectContainer.prototype.getLocalBounds = function () { - return this.getBounds(this); - }; /** -* Determines whether the specified display object is a child of the DisplayObjectContainer instance or the instance itself. -* -* @method PIXI.DisplayObjectContainer#contains -* @param {DisplayObject} child -* @returns {boolean} -*/ + * Determines whether the specified display object is a child of the DisplayObjectContainer instance or the instance itself. + * + * @method PIXI.DisplayObjectContainer#contains + * @param {DisplayObject} child + * @returns {boolean} + */ PIXI.DisplayObjectContainer.prototype.contains = function (child) { - if (!child) { return false; @@ -508,15 +477,14 @@ PIXI.DisplayObjectContainer.prototype.contains = function (child) }; /** -* Renders the object using the WebGL renderer -* -* @method PIXI.DisplayObjectContainer#_renderWebGL -* @param renderSession {RenderSession} -* @private -*/ + * Renders the object using the WebGL renderer + * + * @method PIXI.DisplayObjectContainer#_renderWebGL + * @param renderSession {RenderSession} + * @private + */ PIXI.DisplayObjectContainer.prototype._renderWebGL = function (renderSession) { - if (!this.visible || this.alpha <= 0) { return; @@ -567,19 +535,17 @@ PIXI.DisplayObjectContainer.prototype._renderWebGL = function (renderSession) this.children[i]._renderWebGL(renderSession); } } - }; /** -* Renders the object using the Canvas renderer -* -* @method PIXI.DisplayObjectContainer#_renderCanvas -* @param renderSession {RenderSession} -* @private -*/ + * Renders the object using the Canvas renderer + * + * @method PIXI.DisplayObjectContainer#_renderCanvas + * @param renderSession {RenderSession} + * @private + */ PIXI.DisplayObjectContainer.prototype._renderCanvas = function (renderSession) { - if (this.visible === false || this.alpha === 0) { return; @@ -605,7 +571,6 @@ PIXI.DisplayObjectContainer.prototype._renderCanvas = function (renderSession) { renderSession.maskManager.popMask(renderSession); } - }; /** @@ -623,7 +588,6 @@ Object.defineProperty(PIXI.DisplayObjectContainer.prototype, 'width', { set: function (value) { - var width = this.getLocalBounds().width; if (width !== 0) @@ -654,7 +618,6 @@ Object.defineProperty(PIXI.DisplayObjectContainer.prototype, 'height', { set: function (value) { - var height = this.getLocalBounds().height; if (height !== 0) diff --git a/src/pixi/display/Sprite.js b/src/pixi/display/Sprite.js index 9033c2ee9..7e1801258 100644 --- a/src/pixi/display/Sprite.js +++ b/src/pixi/display/Sprite.js @@ -12,7 +12,6 @@ */ PIXI.Sprite = function (texture) { - PIXI.DisplayObjectContainer.call(this); /** @@ -104,12 +103,12 @@ PIXI.Sprite = function (texture) this.shader = null; /** - * Controls if this Sprite is processed by the core Phaser game loops and Group loops (except {@link Phaser.Group#update}). - * - * @property exists - * @type Boolean - * @default true - */ + * Controls if this Sprite is processed by the core Phaser game loops and Group loops (except {@link Phaser.Group#update}). + * + * @property exists + * @type Boolean + * @default true + */ this.exists = true; if (this.texture.baseTexture.hasLoaded) @@ -118,7 +117,6 @@ PIXI.Sprite = function (texture) } this.renderable = true; - }; /** @@ -211,19 +209,19 @@ PIXI.Sprite.prototype.onTextureUpdate = function () }; /** -* Returns the bounds of the Sprite as a rectangle. -* The bounds calculation takes the worldTransform into account. -* -* The worldTransform was calculated during the last render pass and is not updated when you call this method. -* If this Sprite was just created and has never been rendered, you can call `updateTransform` on the Sprite itself. -* If any of the Sprite's ancestors have been positioned, scaled, or rotated since the last render pass, -* those changes have not yet have been applied to this Sprite's worldTransform. Call `updateTransform` -* on the root-most (highest) ancestor that was changed. -* -* @method PIXI.Sprite#getBounds -* @param matrix {Matrix} the transformation matrix of the sprite -* @return {Rectangle} the framing rectangle -*/ + * Returns the bounds of the Sprite as a rectangle. + * The bounds calculation takes the worldTransform into account. + * + * The worldTransform was calculated during the last render pass and is not updated when you call this method. + * If this Sprite was just created and has never been rendered, you can call `updateTransform` on the Sprite itself. + * If any of the Sprite's ancestors have been positioned, scaled, or rotated since the last render pass, + * those changes have not yet have been applied to this Sprite's worldTransform. Call `updateTransform` + * on the root-most (highest) ancestor that was changed. + * + * @method PIXI.Sprite#getBounds + * @param matrix {Matrix} the transformation matrix of the sprite + * @return {Rectangle} the framing rectangle + */ PIXI.Sprite.prototype.getBounds = function (matrix) { var width = this.texture.frame.width; @@ -269,8 +267,10 @@ PIXI.Sprite.prototype.getBounds = function (matrix) h1 = -temp; } - // this means there is no rotation going on right? RIGHT? - // if thats the case then we can avoid checking the bound values! yay + /* + * this means there is no rotation going on right? RIGHT? + * if thats the case then we can avoid checking the bound values! yay + */ minX = a * w1 + tx; maxX = a * w0 + tx; minY = d * h1 + ty; @@ -333,7 +333,6 @@ PIXI.Sprite.prototype.getBounds = function (matrix) */ PIXI.Sprite.prototype.getLocalBounds = function () { - var matrixCache = this.worldTransform; this.worldTransform = Phaser.identityMatrix; @@ -353,17 +352,16 @@ PIXI.Sprite.prototype.getLocalBounds = function () } return bounds; - }; /** -* Renders the object using the WebGL renderer -* -* @method PIXI.Sprite#_renderWebGL -* @param renderSession {RenderSession} -* @param {Matrix} [matrix] - Optional matrix. If provided the Display Object will be rendered using this matrix, otherwise it will use its worldTransform. -* @private -*/ + * Renders the object using the WebGL renderer + * + * @method PIXI.Sprite#_renderWebGL + * @param renderSession {RenderSession} + * @param {Matrix} [matrix] - Optional matrix. If provided the Display Object will be rendered using this matrix, otherwise it will use its worldTransform. + * @private + */ PIXI.Sprite.prototype._renderWebGL = function (renderSession, matrix) { // if the sprite is not visible or the alpha is 0 then no need to render this element @@ -422,18 +420,17 @@ PIXI.Sprite.prototype._renderWebGL = function (renderSession, matrix) { this.children[i]._renderWebGL(renderSession, wt); } - } }; /** -* Renders the object using the Canvas renderer -* -* @method PIXI.Sprite#_renderCanvas -* @param renderSession {RenderSession} -* @param {Matrix} [matrix] - Optional matrix. If provided the Display Object will be rendered using this matrix, otherwise it will use its worldTransform. -* @private -*/ + * Renders the object using the Canvas renderer + * + * @method PIXI.Sprite#_renderCanvas + * @param renderSession {RenderSession} + * @param {Matrix} [matrix] - Optional matrix. If provided the Display Object will be rendered using this matrix, otherwise it will use its worldTransform. + * @private + */ PIXI.Sprite.prototype._renderCanvas = function (renderSession, matrix) { // If the sprite is not visible or the alpha is 0 then no need to render this element @@ -511,8 +508,10 @@ PIXI.Sprite.prototype._renderCanvas = function (renderSession, matrix) tx = wt.c * ch + tx; ty = wt.d * ch + ty; - // Rotate matrix by 90 degrees - // We use precalculated values for sine and cosine of rad(90) + /* + * Rotate matrix by 90 degrees + * We use precalculated values for sine and cosine of rad(90) + */ wt.a = a * 6.123233995736766e-17 + -c; wt.b = b * 6.123233995736766e-17 + -d; wt.c = a + c * 6.123233995736766e-17; @@ -575,5 +574,4 @@ PIXI.Sprite.prototype._renderCanvas = function (renderSession, matrix) { renderSession.maskManager.popMask(renderSession); } - }; diff --git a/src/pixi/renderers/canvas/CanvasGraphics.js b/src/pixi/renderers/canvas/CanvasGraphics.js index 1ba0904ca..5cf6a7e63 100644 --- a/src/pixi/renderers/canvas/CanvasGraphics.js +++ b/src/pixi/renderers/canvas/CanvasGraphics.js @@ -196,7 +196,6 @@ PIXI.CanvasGraphics.renderGraphics = function (graphics, context) } } } - }; /** @@ -226,7 +225,6 @@ PIXI.CanvasGraphics.renderGraphicsMask = function (graphics, context) if (data.type === Phaser.POLYGON) { - var points = shape.points; context.moveTo(points[0], points[1]); @@ -241,7 +239,6 @@ PIXI.CanvasGraphics.renderGraphicsMask = function (graphics, context) { context.closePath(); } - } else if (data.type === Phaser.RECTANGLE) { @@ -256,7 +253,6 @@ PIXI.CanvasGraphics.renderGraphicsMask = function (graphics, context) } else if (data.type === Phaser.ELLIPSE) { - // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas var w = shape.width * 2; @@ -282,7 +278,6 @@ PIXI.CanvasGraphics.renderGraphicsMask = function (graphics, context) } else if (data.type === Phaser.ROUNDEDRECTANGLE) { - var rx = shape.x; var ry = shape.y; var width = shape.width; @@ -326,7 +321,5 @@ PIXI.CanvasGraphics.updateGraphicsTint = function (graphics) data._fillTint = (((fillColor >> 16 & 0xFF) / 255 * tintR * 255 << 16) + ((fillColor >> 8 & 0xFF) / 255 * tintG * 255 << 8) + (fillColor & 0xFF) / 255 * tintB * 255); data._lineTint = (((lineColor >> 16 & 0xFF) / 255 * tintR * 255 << 16) + ((lineColor >> 8 & 0xFF) / 255 * tintG * 255 << 8) + (lineColor & 0xFF) / 255 * tintB * 255); - } - }; diff --git a/src/pixi/renderers/canvas/CanvasRenderer.js b/src/pixi/renderers/canvas/CanvasRenderer.js index 82838a004..c05faa759 100644 --- a/src/pixi/renderers/canvas/CanvasRenderer.js +++ b/src/pixi/renderers/canvas/CanvasRenderer.js @@ -12,10 +12,9 @@ */ PIXI.CanvasRenderer = function (game, config) { - /** - * @property {Phaser.Game} game - A reference to the Phaser Game instance. - */ + * @property {Phaser.Game} game - A reference to the Phaser Game instance. + */ this.game = game; if (!PIXI.defaultRenderer) @@ -149,7 +148,6 @@ PIXI.CanvasRenderer = function (game, config) this.mapBlendModes(); this.resize(this.width, this.height); - }; // constructor @@ -163,7 +161,6 @@ PIXI.CanvasRenderer.prototype.constructor = PIXI.CanvasRenderer; */ PIXI.CanvasRenderer.prototype.render = function (root) { - this.context.setTransform(1, 0, 0, 1, 0, 0); this.context.globalAlpha = 1; @@ -194,15 +191,16 @@ PIXI.CanvasRenderer.prototype.render = function (root) } this.renderDisplayObject(root); - }; PIXI.CanvasRenderer.prototype.setTexturePriority = function () { - // Does nothing on Canvas, but here to allow you to simply set - // `game.renderer.setTexturePriority()` without having to worry about - // running in WebGL or not. + /* + * Does nothing on Canvas, but here to allow you to simply set + * `game.renderer.setTexturePriority()` without having to worry about + * running in WebGL or not. + */ }; @@ -214,7 +212,6 @@ PIXI.CanvasRenderer.prototype.setTexturePriority = function () */ PIXI.CanvasRenderer.prototype.destroy = function (removeView) { - if (removeView === undefined) { removeView = true; } if (removeView && this.view.parent) @@ -226,7 +223,6 @@ PIXI.CanvasRenderer.prototype.destroy = function (removeView) this.context = null; this.maskManager = null; this.renderSession = null; - }; /** @@ -238,7 +234,6 @@ PIXI.CanvasRenderer.prototype.destroy = function (removeView) */ PIXI.CanvasRenderer.prototype.resize = function (width, height) { - this.width = width * this.resolution; this.height = height * this.resolution; @@ -255,7 +250,6 @@ PIXI.CanvasRenderer.prototype.resize = function (width, height) { this.context[this.renderSession.smoothProperty] = (this.renderSession.scaleMode === PIXI.scaleModes.LINEAR); } - }; /** @@ -269,11 +263,9 @@ PIXI.CanvasRenderer.prototype.resize = function (width, height) */ PIXI.CanvasRenderer.prototype.renderDisplayObject = function (displayObject, context, matrix) { - this.renderSession.context = context || this.context; this.renderSession.resolution = this.resolution; displayObject._renderCanvas(this.renderSession, matrix); - }; /** @@ -284,7 +276,6 @@ PIXI.CanvasRenderer.prototype.renderDisplayObject = function (displayObject, con */ PIXI.CanvasRenderer.prototype.mapBlendModes = function () { - if (!PIXI.blendModesCanvas) { var b = []; @@ -311,5 +302,4 @@ PIXI.CanvasRenderer.prototype.mapBlendModes = function () PIXI.blendModesCanvas = b; } - }; diff --git a/src/pixi/renderers/canvas/utils/CanvasMaskManager.js b/src/pixi/renderers/canvas/utils/CanvasMaskManager.js index ef2abdb30..6e2db61ba 100644 --- a/src/pixi/renderers/canvas/utils/CanvasMaskManager.js +++ b/src/pixi/renderers/canvas/utils/CanvasMaskManager.js @@ -23,7 +23,6 @@ PIXI.CanvasMaskManager.prototype.constructor = PIXI.CanvasMaskManager; */ PIXI.CanvasMaskManager.prototype.pushMask = function (maskData, renderSession) { - var context = renderSession.context; context.save(); diff --git a/src/pixi/renderers/canvas/utils/CanvasTinter.js b/src/pixi/renderers/canvas/utils/CanvasTinter.js index 175c7ba58..a94bc1535 100644 --- a/src/pixi/renderers/canvas/utils/CanvasTinter.js +++ b/src/pixi/renderers/canvas/utils/CanvasTinter.js @@ -67,7 +67,6 @@ PIXI.CanvasTinter.tintWithMultiply = function (texture, color, canvas) context.globalCompositeOperation = 'destination-atop'; context.drawImage(texture.baseTexture.source, crop.x, crop.y, w, h, 0, 0, w, h); - }; /** diff --git a/src/pixi/renderers/webgl/WebGLRenderer.js b/src/pixi/renderers/webgl/WebGLRenderer.js index e708410b8..a02e30c99 100644 --- a/src/pixi/renderers/webgl/WebGLRenderer.js +++ b/src/pixi/renderers/webgl/WebGLRenderer.js @@ -18,10 +18,9 @@ PIXI._enableMultiTextureToggle = false; */ PIXI.WebGLRenderer = function (game, config) { - /** - * @property {Phaser.Game} game - A reference to the Phaser Game instance. - */ + * @property {Phaser.Game} game - A reference to the Phaser Game instance. + */ this.game = game; if (!PIXI.defaultRenderer) @@ -219,15 +218,14 @@ PIXI.WebGLRenderer = function (game, config) // map some webGL blend modes.. this.mapBlendModes(); - }; // constructor PIXI.WebGLRenderer.prototype.constructor = PIXI.WebGLRenderer; /** -* @method PIXI.WebGLRenderer#initContext -*/ + * @method PIXI.WebGLRenderer#initContext + */ PIXI.WebGLRenderer.prototype.initContext = function () { var gl = this.view.getContext('webgl', this._contextOptions) || this.view.getContext('experimental-webgl', this._contextOptions); @@ -280,31 +278,30 @@ PIXI.WebGLRenderer.prototype.initContext = function () }; /** -* If Multi Texture support has been enabled, then calling this method will enable batching on the given -* textures. The texture collection is an array of keys, that map to Phaser.Cache image entries. -* -* The number of textures that can be batched is dependent on hardware. If you provide more textures -* than can be batched by the GPU, then only those at the start of the array will be used. Generally -* you shouldn't provide more than 16 textures to this method. You can check the hardware limit via the -* `maxTextures` property. -* -* You can also check the property `currentBatchedTextures` at any time, to see which textures are currently -* being batched. -* -* To stop all textures from being batched, call this method again with an empty array. -* -* To change the textures being batched, call this method with a new array of image keys. The old ones -* will all be purged out and no-longer batched, and the new ones enabled. -* -* Note: Throws a warning if you haven't enabled Multiple Texture batching support in the Phaser Game config. -* -* @method PIXI.WebGLRenderer#setTexturePriority -* @param textureNameCollection {Array} An Array of Texture Cache keys to use for multi-texture batching. -* @return {Array} An array containing the texture keys that were enabled for batching. -*/ + * If Multi Texture support has been enabled, then calling this method will enable batching on the given + * textures. The texture collection is an array of keys, that map to Phaser.Cache image entries. + * + * The number of textures that can be batched is dependent on hardware. If you provide more textures + * than can be batched by the GPU, then only those at the start of the array will be used. Generally + * you shouldn't provide more than 16 textures to this method. You can check the hardware limit via the + * `maxTextures` property. + * + * You can also check the property `currentBatchedTextures` at any time, to see which textures are currently + * being batched. + * + * To stop all textures from being batched, call this method again with an empty array. + * + * To change the textures being batched, call this method with a new array of image keys. The old ones + * will all be purged out and no-longer batched, and the new ones enabled. + * + * Note: Throws a warning if you haven't enabled Multiple Texture batching support in the Phaser Game config. + * + * @method PIXI.WebGLRenderer#setTexturePriority + * @param textureNameCollection {Array} An Array of Texture Cache keys to use for multi-texture batching. + * @return {Array} An array containing the texture keys that were enabled for batching. + */ PIXI.WebGLRenderer.prototype.setTexturePriority = function (textureNameCollection) { - if (!PIXI._enableMultiTextureToggle) { console.warn('setTexturePriority error: Multi Texture support hasn\'t been enabled in the Phaser Game Config.'); @@ -326,9 +323,11 @@ PIXI.WebGLRenderer.prototype.setTexturePriority = function (textureNameCollectio var imageCache = this.game.cache._cache.image; var imageName = null; - // Clear out all previously batched textures and reset their flags. - // If the array has been modified, then the developer will have to - // deal with that in their own way. + /* + * Clear out all previously batched textures and reset their flags. + * If the array has been modified, then the developer will have to + * deal with that in their own way. + */ for (var i = 0; i < this.currentBatchedTextures.length; i++) { imageName = this.currentBatchedTextures[i]; @@ -374,7 +373,6 @@ PIXI.WebGLRenderer.prototype.setTexturePriority = function (textureNameCollectio this.renderSession.maxTextureAvailableSpace = maxTextureAvailableSpace; return this.currentBatchedTextures; - }; /** @@ -595,7 +593,6 @@ PIXI.WebGLRenderer.prototype.updateTexture = function (texture) // return texture._glTextures[gl.id]; return true; - }; /** diff --git a/src/pixi/renderers/webgl/shaders/ComplexPrimitiveShader.js b/src/pixi/renderers/webgl/shaders/ComplexPrimitiveShader.js index be1bb97df..860c5f0ca 100644 --- a/src/pixi/renderers/webgl/shaders/ComplexPrimitiveShader.js +++ b/src/pixi/renderers/webgl/shaders/ComplexPrimitiveShader.js @@ -3,10 +3,10 @@ */ /** -* @class PIXI.ComplexPrimitiveShader -* @constructor -* @param gl {WebGLContext} the current WebGL drawing context -*/ + * @class PIXI.ComplexPrimitiveShader + * @constructor + * @param gl {WebGLContext} the current WebGL drawing context + */ PIXI.ComplexPrimitiveShader = function (gl) { /** @@ -78,10 +78,10 @@ PIXI.ComplexPrimitiveShader = function (gl) PIXI.ComplexPrimitiveShader.prototype.constructor = PIXI.ComplexPrimitiveShader; /** -* Initialises the shader. -* -* @method PIXI.ComplexPrimitiveShader#init -*/ + * Initialises the shader. + * + * @method PIXI.ComplexPrimitiveShader#init + */ PIXI.ComplexPrimitiveShader.prototype.init = function () { var gl = this.gl; @@ -110,10 +110,10 @@ PIXI.ComplexPrimitiveShader.prototype.init = function () }; /** -* Destroys the shader. -* -* @method PIXI.ComplexPrimitiveShader#destroy -*/ + * Destroys the shader. + * + * @method PIXI.ComplexPrimitiveShader#destroy + */ PIXI.ComplexPrimitiveShader.prototype.destroy = function () { this.gl.deleteProgram(this.program); diff --git a/src/pixi/renderers/webgl/shaders/PixiFastShader.js b/src/pixi/renderers/webgl/shaders/PixiFastShader.js index 84c0440d8..da10f7b83 100644 --- a/src/pixi/renderers/webgl/shaders/PixiFastShader.js +++ b/src/pixi/renderers/webgl/shaders/PixiFastShader.js @@ -55,12 +55,16 @@ PIXI.PixiFastShader = function (gl) 'varying float vTextureIndex;', 'uniform sampler2D uSamplerArray[' + this.MAX_TEXTURES + '];', - // Blue color means that you are trying to bound - // a texture out of the limits of the hardware. + /* + * Blue color means that you are trying to bound + * a texture out of the limits of the hardware. + */ 'const vec4 BLUE = vec4(1.0, 0.0, 1.0, 1.0);', - // If you get a red color means you are out of memory - // or in some way corrupted the vertex buffer. + /* + * If you get a red color means you are out of memory + * or in some way corrupted the vertex buffer. + */ 'const vec4 RED = vec4(1.0, 0.0, 0.0, 1.0);', 'void main(void) {', dynamicIfs, @@ -143,7 +147,6 @@ PIXI.PixiFastShader.prototype.constructor = PIXI.PixiFastShader; */ PIXI.PixiFastShader.prototype.init = function () { - var gl = this.gl; var program = PIXI.compileProgram(gl, this.vertexSrc, this.fragmentSrc); @@ -192,10 +195,12 @@ PIXI.PixiFastShader.prototype.init = function () // Begin worst hack eva // - // WHY??? ONLY on my chrome pixel the line above returns -1 when using filters? - // maybe its somthing to do with the current state of the gl context. - // Im convinced this is a bug in the chrome browser as there is NO reason why this should be returning -1 especially as it only manifests on my chrome pixel - // If theres any webGL people that know why could happen please help :) + /* + * WHY??? ONLY on my chrome pixel the line above returns -1 when using filters? + * maybe its somthing to do with the current state of the gl context. + * Im convinced this is a bug in the chrome browser as there is NO reason why this should be returning -1 especially as it only manifests on my chrome pixel + * If theres any webGL people that know why could happen please help :) + */ if (this.colorAttribute === -1) { this.colorAttribute = 2; diff --git a/src/pixi/renderers/webgl/shaders/PixiShader.js b/src/pixi/renderers/webgl/shaders/PixiShader.js index a51828ddf..7d04d9c8e 100644 --- a/src/pixi/renderers/webgl/shaders/PixiShader.js +++ b/src/pixi/renderers/webgl/shaders/PixiShader.js @@ -4,10 +4,10 @@ */ /** -* @class PIXI.PixiShader -* @constructor -* @param gl {WebGLContext} the current WebGL drawing context -*/ + * @class PIXI.PixiShader + * @constructor + * @param gl {WebGLContext} the current WebGL drawing context + */ PIXI.PixiShader = function (gl) { /** @@ -92,12 +92,16 @@ PIXI.PixiShader.prototype.initMultitexShader = function () 'varying float vTextureIndex;', 'uniform sampler2D uSamplerArray[' + this.MAX_TEXTURES + '];', - // Blue color means that you are trying to bound - // a texture out of the limits of the hardware. + /* + * Blue color means that you are trying to bound + * a texture out of the limits of the hardware. + */ 'const vec4 BLUE = vec4(1.0, 0.0, 1.0, 1.0);', - // If you get a red color means you are out of memory - // or in some way corrupted the vertex buffer. + /* + * If you get a red color means you are out of memory + * or in some way corrupted the vertex buffer. + */ 'const vec4 RED = vec4(1.0, 0.0, 0.0, 1.0);', 'void main(void) {', dynamicIfs, @@ -110,8 +114,10 @@ PIXI.PixiShader.prototype.initMultitexShader = function () gl.useProgram(program); - // get and store the uniforms for the shader - // this.uSampler = gl.getUniformLocation(program, 'uSampler'); + /* + * get and store the uniforms for the shader + * this.uSampler = gl.getUniformLocation(program, 'uSampler'); + */ this.uSamplerArray = gl.getUniformLocation(program, 'uSamplerArray[0]'); this.projectionVector = gl.getUniformLocation(program, 'projectionVector'); this.offsetVector = gl.getUniformLocation(program, 'offsetVector'); @@ -141,10 +147,12 @@ PIXI.PixiShader.prototype.initMultitexShader = function () // Begin worst hack eva // - // WHY??? ONLY on my chrome pixel the line above returns -1 when using filters? - // maybe its something to do with the current state of the gl context. - // I'm convinced this is a bug in the chrome browser as there is NO reason why this should be returning -1 especially as it only manifests on my chrome pixel - // If theres any webGL people that know why could happen please help :) + /* + * WHY??? ONLY on my chrome pixel the line above returns -1 when using filters? + * maybe its something to do with the current state of the gl context. + * I'm convinced this is a bug in the chrome browser as there is NO reason why this should be returning -1 especially as it only manifests on my chrome pixel + * If theres any webGL people that know why could happen please help :) + */ if(this.colorAttribute === -1) { this.colorAttribute = 2; @@ -168,7 +176,6 @@ PIXI.PixiShader.prototype.initMultitexShader = function () PIXI.PixiShader.prototype.initDefaultShader = function () { - if (this.fragmentSrc === null) { this.fragmentSrc = [ @@ -204,10 +211,12 @@ PIXI.PixiShader.prototype.initDefaultShader = function () // Begin worst hack eva // - // WHY??? ONLY on my chrome pixel the line above returns -1 when using filters? - // maybe its something to do with the current state of the gl context. - // I'm convinced this is a bug in the chrome browser as there is NO reason why this should be returning -1 especially as it only manifests on my chrome pixel - // If theres any webGL people that know why could happen please help :) + /* + * WHY??? ONLY on my chrome pixel the line above returns -1 when using filters? + * maybe its something to do with the current state of the gl context. + * I'm convinced this is a bug in the chrome browser as there is NO reason why this should be returning -1 especially as it only manifests on my chrome pixel + * If theres any webGL people that know why could happen please help :) + */ if(this.colorAttribute === -1) { this.colorAttribute = 2; @@ -230,10 +239,10 @@ PIXI.PixiShader.prototype.initDefaultShader = function () }; /** -* Initialises the shader. -* -* @method PIXI.PixiShader#init -*/ + * Initialises the shader. + * + * @method PIXI.PixiShader#init + */ PIXI.PixiShader.prototype.init = function (usingFilter) { if (PIXI._enableMultiTextureToggle && !usingFilter) @@ -247,13 +256,13 @@ PIXI.PixiShader.prototype.init = function (usingFilter) }; /** -* Initialises the shader uniform values. -* -* Uniforms are specified in the GLSL_ES Specification: http://www.khronos.org/registry/webgl/specs/latest/1.0/ -* http://www.khronos.org/registry/gles/specs/2.0/GLSL_ES_Specification_1.0.17.pdf -* -* @method PIXI.PixiShader#initUniforms -*/ + * Initialises the shader uniform values. + * + * Uniforms are specified in the GLSL_ES Specification: http://www.khronos.org/registry/webgl/specs/latest/1.0/ + * http://www.khronos.org/registry/gles/specs/2.0/GLSL_ES_Specification_1.0.17.pdf + * + * @method PIXI.PixiShader#initUniforms + */ PIXI.PixiShader.prototype.initUniforms = function () { this.textureCount = 1; @@ -317,14 +326,13 @@ PIXI.PixiShader.prototype.initUniforms = function () } } } - }; /** -* Initialises a Sampler2D uniform (which may only be available later on after initUniforms once the texture has loaded) -* -* @method PIXI.PixiShader#initSampler2D -*/ + * Initialises a Sampler2D uniform (which may only be available later on after initUniforms once the texture has loaded) + * + * @method PIXI.PixiShader#initSampler2D + */ PIXI.PixiShader.prototype.initSampler2D = function (uniform) { if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded) @@ -343,15 +351,19 @@ PIXI.PixiShader.prototype.initSampler2D = function (uniform) { var data = uniform.textureData; - // GLTexture = mag linear, min linear_mipmap_linear, wrap repeat + gl.generateMipmap(gl.TEXTURE_2D); - // GLTextureLinear = mag/min linear, wrap clamp - // GLTextureNearestRepeat = mag/min NEAREST, wrap repeat - // GLTextureNearest = mag/min nearest, wrap clamp - // AudioTexture = whatever + luminance + width 512, height 2, border 0 - // KeyTexture = whatever + luminance + width 256, height 2, border 0 + /* + * GLTexture = mag linear, min linear_mipmap_linear, wrap repeat + gl.generateMipmap(gl.TEXTURE_2D); + * GLTextureLinear = mag/min linear, wrap clamp + * GLTextureNearestRepeat = mag/min NEAREST, wrap repeat + * GLTextureNearest = mag/min nearest, wrap clamp + * AudioTexture = whatever + luminance + width 512, height 2, border 0 + * KeyTexture = whatever + luminance + width 256, height 2, border 0 + */ - // magFilter can be: gl.LINEAR, gl.LINEAR_MIPMAP_LINEAR or gl.NEAREST - // wrapS/T can be: gl.CLAMP_TO_EDGE or gl.REPEAT + /* + * magFilter can be: gl.LINEAR, gl.LINEAR_MIPMAP_LINEAR or gl.NEAREST + * wrapS/T can be: gl.CLAMP_TO_EDGE or gl.REPEAT + */ var magFilter = (data.magFilter) ? data.magFilter : gl.LINEAR; var minFilter = (data.minFilter) ? data.minFilter : gl.LINEAR; @@ -393,14 +405,13 @@ PIXI.PixiShader.prototype.initSampler2D = function (uniform) uniform._init = true; this.textureCount++; - }; /** -* Updates the shader uniform values. -* -* @method PIXI.PixiShader#syncUniforms -*/ + * Updates the shader uniform values. + * + * @method PIXI.PixiShader#syncUniforms + */ PIXI.PixiShader.prototype.syncUniforms = function () { this.textureCount = 1; @@ -460,14 +471,13 @@ PIXI.PixiShader.prototype.syncUniforms = function () } } } - }; /** -* Destroys the shader. -* -* @method PIXI.PixiShader#destroy -*/ + * Destroys the shader. + * + * @method PIXI.PixiShader#destroy + */ PIXI.PixiShader.prototype.destroy = function () { this.gl.deleteProgram(this.program); @@ -478,11 +488,11 @@ PIXI.PixiShader.prototype.destroy = function () }; /** -* The Default Vertex shader source. -* -* @property defaultVertexSrc -* @type String -*/ + * The Default Vertex shader source. + * + * @property defaultVertexSrc + * @type String + */ PIXI.PixiShader.defaultVertexSrc = [ '// PixiShader Vertex Shader', '// With multi-texture rendering', diff --git a/src/pixi/renderers/webgl/shaders/PrimitiveShader.js b/src/pixi/renderers/webgl/shaders/PrimitiveShader.js index c7f5eeb33..280d4d468 100644 --- a/src/pixi/renderers/webgl/shaders/PrimitiveShader.js +++ b/src/pixi/renderers/webgl/shaders/PrimitiveShader.js @@ -3,10 +3,10 @@ */ /** -* @class PIXI.PrimitiveShader -* @constructor -* @param gl {WebGLContext} the current WebGL drawing context -*/ + * @class PIXI.PrimitiveShader + * @constructor + * @param gl {WebGLContext} the current WebGL drawing context + */ PIXI.PrimitiveShader = function (gl) { /** @@ -73,10 +73,10 @@ PIXI.PrimitiveShader = function (gl) PIXI.PrimitiveShader.prototype.constructor = PIXI.PrimitiveShader; /** -* Initialises the shader. -* -* @method PIXI.PrimitiveShader#init -*/ + * Initialises the shader. + * + * @method PIXI.PrimitiveShader#init + */ PIXI.PrimitiveShader.prototype.init = function () { var gl = this.gl; @@ -103,10 +103,10 @@ PIXI.PrimitiveShader.prototype.init = function () }; /** -* Destroys the shader. -* -* @method PIXI.PrimitiveShader#destroy -*/ + * Destroys the shader. + * + * @method PIXI.PrimitiveShader#destroy + */ PIXI.PrimitiveShader.prototype.destroy = function () { this.gl.deleteProgram(this.program); diff --git a/src/pixi/renderers/webgl/shaders/StripShader.js b/src/pixi/renderers/webgl/shaders/StripShader.js index 41bce32ca..2d65df4ff 100644 --- a/src/pixi/renderers/webgl/shaders/StripShader.js +++ b/src/pixi/renderers/webgl/shaders/StripShader.js @@ -3,10 +3,10 @@ */ /** -* @class PIXI.StripShader -* @constructor -* @param gl {WebGLContext} the current WebGL drawing context -*/ + * @class PIXI.StripShader + * @constructor + * @param gl {WebGLContext} the current WebGL drawing context + */ PIXI.StripShader = function (gl) { /** @@ -58,12 +58,16 @@ PIXI.StripShader = function (gl) 'uniform float alpha;', 'uniform sampler2D uSamplerArray[' + this.MAX_TEXTURES + '];', - // Blue color means that you are trying to bound - // a texture out of the limits of the hardware. + /* + * Blue color means that you are trying to bound + * a texture out of the limits of the hardware. + */ 'const vec4 BLUE = vec4(1.0, 0.0, 1.0, 1.0);', - // If you get a red color means you are out of memory - // or in some way corrupted the vertex buffer. + /* + * If you get a red color means you are out of memory + * or in some way corrupted the vertex buffer. + */ 'const vec4 RED = vec4(1.0, 0.0, 0.0, 1.0);', 'void main(void) {', dynamicIfs, @@ -108,8 +112,10 @@ PIXI.StripShader = function (gl) 'uniform vec2 projectionVector;', 'uniform vec2 offsetVector;', - // 'uniform float alpha;', - // 'uniform vec3 tint;', + /* + * 'uniform float alpha;', + * 'uniform vec3 tint;', + */ 'varying vec2 vTextureCoord;', 'varying float vTextureIndex;', @@ -132,10 +138,10 @@ PIXI.StripShader = function (gl) PIXI.StripShader.prototype.constructor = PIXI.StripShader; /** -* Initialises the shader. -* -* @method PIXI.StripShader#init -*/ + * Initialises the shader. + * + * @method PIXI.StripShader#init + */ PIXI.StripShader.prototype.init = function () { var gl = this.gl; @@ -187,10 +193,10 @@ PIXI.StripShader.prototype.init = function () }; /** -* Destroys the shader. -* -* @method PIXI.StripShader#destroy -*/ + * Destroys the shader. + * + * @method PIXI.StripShader#destroy + */ PIXI.StripShader.prototype.destroy = function () { this.gl.deleteProgram(this.program); diff --git a/src/pixi/renderers/webgl/utils/FilterTexture.js b/src/pixi/renderers/webgl/utils/FilterTexture.js index be3044e86..53eebb868 100644 --- a/src/pixi/renderers/webgl/utils/FilterTexture.js +++ b/src/pixi/renderers/webgl/utils/FilterTexture.js @@ -56,13 +56,13 @@ function _CreateFramebuffer (gl, width, height, scaleMode, textureUnit) } /** -* @class PIXI.FilterTexture -* @constructor -* @param gl {WebGLContext} the current WebGL drawing context -* @param width {Number} the horizontal range of the filter -* @param height {Number} the vertical range of the filter -* @param scaleMode {Number} See {{#crossLink "PIXI/scaleModes:property"}}PIXI.scaleModes{{/crossLink}} for possible values -*/ + * @class PIXI.FilterTexture + * @constructor + * @param gl {WebGLContext} the current WebGL drawing context + * @param width {Number} the horizontal range of the filter + * @param height {Number} the vertical range of the filter + * @param scaleMode {Number} See {{#crossLink "PIXI/scaleModes:property"}}PIXI.scaleModes{{/crossLink}} for possible values + */ PIXI.FilterTexture = function (gl, width, height, scaleMode, textureUnit) { textureUnit = typeof textureUnit === 'number' ? textureUnit : 0; @@ -94,10 +94,10 @@ PIXI.FilterTexture = function (gl, width, height, scaleMode, textureUnit) PIXI.FilterTexture.prototype.constructor = PIXI.FilterTexture; /** -* Clears the filter texture. -* -* @method PIXI.FilterTexture#clear -*/ + * Clears the filter texture. + * + * @method PIXI.FilterTexture#clear + */ PIXI.FilterTexture.prototype.clear = function () { var gl = this.gl; @@ -130,10 +130,10 @@ PIXI.FilterTexture.prototype.resize = function (width, height) }; /** -* Destroys the filter texture. -* -* @method PIXI.FilterTexture#destroy -*/ + * Destroys the filter texture. + * + * @method PIXI.FilterTexture#destroy + */ PIXI.FilterTexture.prototype.destroy = function () { var gl = this.gl; diff --git a/src/pixi/renderers/webgl/utils/WebGLBlendModeManager.js b/src/pixi/renderers/webgl/utils/WebGLBlendModeManager.js index e8386924d..e56d520c8 100644 --- a/src/pixi/renderers/webgl/utils/WebGLBlendModeManager.js +++ b/src/pixi/renderers/webgl/utils/WebGLBlendModeManager.js @@ -3,10 +3,10 @@ */ /** -* @class PIXI.WebGLBlendModeManager -* @constructor -* @param gl {WebGLContext} the current WebGL drawing context -*/ + * @class PIXI.WebGLBlendModeManager + * @constructor + * @param gl {WebGLContext} the current WebGL drawing context + */ PIXI.WebGLBlendModeManager = function () { /** @@ -30,11 +30,11 @@ PIXI.WebGLBlendModeManager.prototype.setContext = function (gl) }; /** -* Sets-up the given blendMode from WebGL's point of view. -* -* @method PIXI.WebGLBlendModeManager#setBlendMode -* @param blendMode {Number} the blendMode, should be a Pixi const, such as PIXI.BlendModes.ADD -*/ + * Sets-up the given blendMode from WebGL's point of view. + * + * @method PIXI.WebGLBlendModeManager#setBlendMode + * @param blendMode {Number} the blendMode, should be a Pixi const, such as PIXI.BlendModes.ADD + */ PIXI.WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) { if(this.currentBlendMode === blendMode) { return false; } @@ -52,10 +52,10 @@ PIXI.WebGLBlendModeManager.prototype.setBlendMode = function (blendMode) }; /** -* Destroys this object. -* -* @method PIXI.WebGLBlendModeManager#destroy -*/ + * Destroys this object. + * + * @method PIXI.WebGLBlendModeManager#destroy + */ PIXI.WebGLBlendModeManager.prototype.destroy = function () { this.gl = null; diff --git a/src/pixi/renderers/webgl/utils/WebGLFastSpriteBatch.js b/src/pixi/renderers/webgl/utils/WebGLFastSpriteBatch.js index fbab45e8d..7c776970f 100644 --- a/src/pixi/renderers/webgl/utils/WebGLFastSpriteBatch.js +++ b/src/pixi/renderers/webgl/utils/WebGLFastSpriteBatch.js @@ -9,12 +9,11 @@ */ /** -* @class PIXI.WebGLFastSpriteBatch -* @constructor -*/ + * @class PIXI.WebGLFastSpriteBatch + * @constructor + */ PIXI.WebGLFastSpriteBatch = function (gl) { - /** * @property vertSize * @type Number @@ -232,7 +231,6 @@ PIXI.WebGLFastSpriteBatch.prototype.renderSprite = function (sprite) gl.bindTexture(gl.TEXTURE_2D, baseTexture._glTextures[gl.id]); PIXI.WebGLRenderer.textureArray[textureIndex] = baseTexture; if(!sprite.texture._uvs) { return; } - } // sprite = children[i]; @@ -343,7 +341,6 @@ PIXI.WebGLFastSpriteBatch.prototype.renderSprite = function (sprite) vertices[index++] = textureIndex; - // xy vertices[index++] = w1; vertices[index++] = h0; @@ -418,7 +415,6 @@ PIXI.WebGLFastSpriteBatch.prototype.flush = function () // increment the draw count this.renderSession.drawCount++; - }; @@ -461,5 +457,4 @@ PIXI.WebGLFastSpriteBatch.prototype.start = function () gl.vertexAttribPointer(this.shader.aTextureCoord, 2, gl.FLOAT, false, stride, 7 * 4); gl.vertexAttribPointer(this.shader.colorAttribute, 1, gl.FLOAT, false, stride, 9 * 4); gl.vertexAttribPointer(this.shader.aTextureIndex, 1, gl.FLOAT, false, stride, 10 * 4); - }; diff --git a/src/pixi/renderers/webgl/utils/WebGLFilterManager.js b/src/pixi/renderers/webgl/utils/WebGLFilterManager.js index 971c7362f..1c407aa3b 100644 --- a/src/pixi/renderers/webgl/utils/WebGLFilterManager.js +++ b/src/pixi/renderers/webgl/utils/WebGLFilterManager.js @@ -3,9 +3,9 @@ */ /** -* @class PIXI.WebGLFilterManager -* @constructor -*/ + * @class PIXI.WebGLFilterManager + * @constructor + */ PIXI.WebGLFilterManager = function () { /** @@ -30,11 +30,11 @@ PIXI.WebGLFilterManager = function () PIXI.WebGLFilterManager.prototype.constructor = PIXI.WebGLFilterManager; /** -* Initialises the context and the properties. -* -* @method PIXI.WebGLFilterManager#setContext -* @param gl {WebGLContext} the current WebGL drawing context -*/ + * Initialises the context and the properties. + * + * @method PIXI.WebGLFilterManager#setContext + * @param gl {WebGLContext} the current WebGL drawing context + */ PIXI.WebGLFilterManager.prototype.setContext = function (gl) { this.gl = gl; @@ -44,10 +44,10 @@ PIXI.WebGLFilterManager.prototype.setContext = function (gl) }; /** -* @method PIXI.WebGLFilterManager#begin -* @param renderSession {RenderSession} -* @param buffer {ArrayBuffer} -*/ + * @method PIXI.WebGLFilterManager#begin + * @param renderSession {RenderSession} + * @param buffer {ArrayBuffer} + */ PIXI.WebGLFilterManager.prototype.begin = function (renderSession, buffer) { this.renderSession = renderSession; @@ -60,11 +60,11 @@ PIXI.WebGLFilterManager.prototype.begin = function (renderSession, buffer) }; /** -* Applies the filter and adds it to the current filter stack. -* -* @method PIXI.WebGLFilterManager#pushFilter -* @param filterBlock {Object} the filter that will be pushed to the current filter stack -*/ + * Applies the filter and adds it to the current filter stack. + * + * @method PIXI.WebGLFilterManager#pushFilter + * @param filterBlock {Object} the filter that will be pushed to the current filter stack + */ PIXI.WebGLFilterManager.prototype.pushFilter = function (filterBlock) { var gl = this.gl; @@ -82,8 +82,10 @@ PIXI.WebGLFilterManager.prototype.pushFilter = function (filterBlock) // <<< modify by nextht - // filter program - // OPTIMISATION - the first filter is free if its a simple color change? + /* + * filter program + * OPTIMISATION - the first filter is free if its a simple color change? + */ this.filterStack.push(filterBlock); var filter = filterBlock.filterPasses[0]; @@ -129,25 +131,26 @@ PIXI.WebGLFilterManager.prototype.pushFilter = function (filterBlock) offset.x = -filterArea.x; offset.y = -filterArea.y; - // update projection - // now restore the regular shader.. - // this.renderSession.shaderManager.setShader(this.defaultShader); - // gl.uniform2f(this.defaultShader.projectionVector, filterArea.width/2, -filterArea.height/2); - // gl.uniform2f(this.defaultShader.offsetVector, -filterArea.x, -filterArea.y); + /* + * update projection + * now restore the regular shader.. + * this.renderSession.shaderManager.setShader(this.defaultShader); + * gl.uniform2f(this.defaultShader.projectionVector, filterArea.width/2, -filterArea.height/2); + * gl.uniform2f(this.defaultShader.offsetVector, -filterArea.x, -filterArea.y); + */ gl.colorMask(true, true, true, true); gl.clearColor(0,0,0, 0); gl.clear(gl.COLOR_BUFFER_BIT); filterBlock._glFilterTexture = texture; - }; /** -* Removes the last filter from the filter stack and doesn't return it. -* -* @method PIXI.WebGLFilterManager#popFilter -*/ + * Removes the last filter from the filter stack and doesn't return it. + * + * @method PIXI.WebGLFilterManager#popFilter + */ PIXI.WebGLFilterManager.prototype.popFilter = function () { var gl = this.gl; @@ -208,8 +211,10 @@ PIXI.WebGLFilterManager.prototype.popFilter = function () gl.activeTexture(gl.TEXTURE0); gl.bindTexture(gl.TEXTURE_2D, inputTexture.texture); - // draw texture.. - // filterPass.applyFilterPass(filterArea.width, filterArea.height); + /* + * draw texture.. + * filterPass.applyFilterPass(filterArea.width, filterArea.height); + */ this.applyFilterPass(filterPass, filterArea, filterArea.width, filterArea.height); // swap the textures.. @@ -268,8 +273,10 @@ PIXI.WebGLFilterManager.prototype.popFilter = function () var x = filterArea.x - offsetX; var y = filterArea.y - offsetY; - // update the buffers.. - // make sure to flip the y! + /* + * update the buffers.. + * make sure to flip the y! + */ gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); this.vertexArray[0] = x; @@ -300,8 +307,10 @@ PIXI.WebGLFilterManager.prototype.popFilter = function () // bind the buffer gl.bindFramebuffer(gl.FRAMEBUFFER, buffer); - // set the blend mode! - // gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA) + /* + * set the blend mode! + * gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA) + */ // set texture gl.activeTexture(gl.TEXTURE0); @@ -328,10 +337,12 @@ PIXI.WebGLFilterManager.prototype.popFilter = function () // apply! this.applyFilterPass(filter, filterArea, sizeX, sizeY); - // now restore the regular shader.. should happen automatically now.. - // this.renderSession.shaderManager.setShader(this.defaultShader); - // gl.uniform2f(this.defaultShader.projectionVector, sizeX/2, -sizeY/2); - // gl.uniform2f(this.defaultShader.offsetVector, -offsetX, -offsetY); + /* + * now restore the regular shader.. should happen automatically now.. + * this.renderSession.shaderManager.setShader(this.defaultShader); + * gl.uniform2f(this.defaultShader.projectionVector, sizeX/2, -sizeY/2); + * gl.uniform2f(this.defaultShader.offsetVector, -offsetX, -offsetY); + */ // return the texture to the pool this.texturePool.push(texture); @@ -340,14 +351,14 @@ PIXI.WebGLFilterManager.prototype.popFilter = function () /** -* Applies the filter to the specified area. -* -* @method PIXI.WebGLFilterManager#applyFilterPass -* @param filter {Phaser.Filter} the filter that needs to be applied -* @param filterArea {Texture} TODO - might need an update -* @param width {Number} the horizontal range of the filter -* @param height {Number} the vertical range of the filter -*/ + * Applies the filter to the specified area. + * + * @method PIXI.WebGLFilterManager#applyFilterPass + * @param filter {Phaser.Filter} the filter that needs to be applied + * @param filterArea {Texture} TODO - might need an update + * @param width {Number} the horizontal range of the filter + * @param height {Number} the vertical range of the filter + */ PIXI.WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea, width, height) { // use program @@ -401,10 +412,10 @@ PIXI.WebGLFilterManager.prototype.applyFilterPass = function (filter, filterArea }; /** -* Initialises the shader buffers. -* -* @method PIXI.WebGLFilterManager#initShaderBuffers -*/ + * Initialises the shader buffers. + * + * @method PIXI.WebGLFilterManager#initShaderBuffers + */ PIXI.WebGLFilterManager.prototype.initShaderBuffers = function () { var gl = this.gl; @@ -415,8 +426,10 @@ PIXI.WebGLFilterManager.prototype.initShaderBuffers = function () this.colorBuffer = gl.createBuffer(); this.indexBuffer = gl.createBuffer(); - // bind and upload the vertexs.. - // keep a reference to the vertexFloatData.. + /* + * bind and upload the vertexs.. + * keep a reference to the vertexFloatData.. + */ this.vertexArray = new Float32Array([ 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, @@ -445,14 +458,13 @@ PIXI.WebGLFilterManager.prototype.initShaderBuffers = function () // bind and upload the index gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer); gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array([ 0, 1, 2, 1, 3, 2 ]), gl.STATIC_DRAW); - }; /** -* Destroys the filter and removes it from the filter stack. -* -* @method PIXI.WebGLFilterManager#destroy -*/ + * Destroys the filter and removes it from the filter stack. + * + * @method PIXI.WebGLFilterManager#destroy + */ PIXI.WebGLFilterManager.prototype.destroy = function () { var gl = this.gl; diff --git a/src/pixi/renderers/webgl/utils/WebGLGraphics.js b/src/pixi/renderers/webgl/utils/WebGLGraphics.js index 54c96e8f3..a5da6dcd7 100644 --- a/src/pixi/renderers/webgl/utils/WebGLGraphics.js +++ b/src/pixi/renderers/webgl/utils/WebGLGraphics.js @@ -138,9 +138,11 @@ PIXI.WebGLGraphics.updateGraphics = function (graphics, gl) var webGLData; - // loop through the graphics datas and construct each one.. - // if the object is a complex fill then the new stencil buffer technique will be used - // other wise graphics objects will be pushed into a batch.. + /* + * loop through the graphics datas and construct each one.. + * if the object is a complex fill then the new stencil buffer technique will be used + * other wise graphics objects will be pushed into a batch.. + */ for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) { var data = graphics.graphicsData[i]; @@ -177,7 +179,6 @@ PIXI.WebGLGraphics.updateGraphics = function (graphics, gl) webGLData = PIXI.WebGLGraphics.switchMode(webGL, 1); PIXI.WebGLGraphics.buildComplexPoly(data, webGLData); } - } else { @@ -191,7 +192,6 @@ PIXI.WebGLGraphics.updateGraphics = function (graphics, gl) { webGLData = PIXI.WebGLGraphics.switchMode(webGL, 0); PIXI.WebGLGraphics.buildLine(data, webGLData); - } } else @@ -268,9 +268,11 @@ PIXI.WebGLGraphics.switchMode = function (webGL, type) */ PIXI.WebGLGraphics.buildRectangle = function (graphicsData, webGLData) { - // --- // - // need to convert points to a nice regular data - // + /* + * --- // + * need to convert points to a nice regular data + * + */ var rectData = graphicsData.shape; var x = rectData.x; var y = rectData.y; @@ -415,7 +417,6 @@ PIXI.WebGLGraphics.buildRoundedRectangle = function (graphicsData, webGLData) PIXI.WebGLGraphics.quadraticBezierCurve = function (fromX, fromY, cpX, cpY, toX, toY) { - var xa, ya, xb, @@ -666,7 +667,6 @@ PIXI.WebGLGraphics.buildLine = function (graphicsData, webGLData) if(Math.abs(denom) < 0.1) { - denom += 10.1; verts.push(p2x - perpx , p2y - perpy, r, g, b, alpha); @@ -708,7 +708,6 @@ PIXI.WebGLGraphics.buildLine = function (graphicsData, webGLData) } else { - verts.push(px , py); verts.push(r, g, b, alpha); @@ -770,8 +769,8 @@ PIXI.WebGLGraphics.buildComplexPoly = function (graphicsData, webGLData) webGLData.color = Phaser.Color.hexToRGBArray(graphicsData.fillColor); /* - calclate the bounds.. - */ + * calclate the bounds.. + */ var minX = Infinity; var maxX = -Infinity; @@ -807,7 +806,6 @@ PIXI.WebGLGraphics.buildComplexPoly = function (graphicsData, webGLData) { indices.push(i); } - }; /** diff --git a/src/pixi/renderers/webgl/utils/WebGLMaskManager.js b/src/pixi/renderers/webgl/utils/WebGLMaskManager.js index e88da18fa..069b859af 100644 --- a/src/pixi/renderers/webgl/utils/WebGLMaskManager.js +++ b/src/pixi/renderers/webgl/utils/WebGLMaskManager.js @@ -3,10 +3,10 @@ */ /** -* @class PIXI.WebGLMaskManager -* @constructor -* @private -*/ + * @class PIXI.WebGLMaskManager + * @constructor + * @private + */ PIXI.WebGLMaskManager = function () { }; @@ -14,23 +14,23 @@ PIXI.WebGLMaskManager = function () PIXI.WebGLMaskManager.prototype.constructor = PIXI.WebGLMaskManager; /** -* Sets the drawing context to the one given in parameter. -* -* @method PIXI.WebGLMaskManager#setContext -* @param gl {WebGLContext} the current WebGL drawing context -*/ + * Sets the drawing context to the one given in parameter. + * + * @method PIXI.WebGLMaskManager#setContext + * @param gl {WebGLContext} the current WebGL drawing context + */ PIXI.WebGLMaskManager.prototype.setContext = function (gl) { this.gl = gl; }; /** -* Applies the Mask and adds it to the current filter stack. -* -* @method PIXI.WebGLMaskManager#pushMask -* @param maskData {Array} -* @param renderSession {Object} -*/ + * Applies the Mask and adds it to the current filter stack. + * + * @method PIXI.WebGLMaskManager#pushMask + * @param maskData {Array} + * @param renderSession {Object} + */ PIXI.WebGLMaskManager.prototype.pushMask = function (maskData, renderSession) { var gl = renderSession.gl; @@ -49,12 +49,12 @@ PIXI.WebGLMaskManager.prototype.pushMask = function (maskData, renderSession) }; /** -* Removes the last filter from the filter stack and doesn't return it. -* -* @method PIXI.WebGLMaskManager#popMask -* @param maskData {Array} -* @param renderSession {Object} an object containing all the useful parameters -*/ + * Removes the last filter from the filter stack and doesn't return it. + * + * @method PIXI.WebGLMaskManager#popMask + * @param maskData {Array} + * @param renderSession {Object} an object containing all the useful parameters + */ PIXI.WebGLMaskManager.prototype.popMask = function (maskData, renderSession) { var gl = this.gl; @@ -65,14 +65,13 @@ PIXI.WebGLMaskManager.prototype.popMask = function (maskData, renderSession) } renderSession.stencilManager.popStencil(maskData, maskData._webGL[gl.id].data[0], renderSession); - }; /** -* Destroys the mask stack. -* -* @method PIXI.WebGLMaskManager#destroy -*/ + * Destroys the mask stack. + * + * @method PIXI.WebGLMaskManager#destroy + */ PIXI.WebGLMaskManager.prototype.destroy = function () { this.gl = null; diff --git a/src/pixi/renderers/webgl/utils/WebGLShaderManager.js b/src/pixi/renderers/webgl/utils/WebGLShaderManager.js index b07f324e9..59038e305 100644 --- a/src/pixi/renderers/webgl/utils/WebGLShaderManager.js +++ b/src/pixi/renderers/webgl/utils/WebGLShaderManager.js @@ -3,10 +3,10 @@ */ /** -* @class PIXI.WebGLShaderManager -* @constructor -* @private -*/ + * @class PIXI.WebGLShaderManager + * @constructor + * @private + */ PIXI.WebGLShaderManager = function () { /** @@ -37,17 +37,16 @@ PIXI.WebGLShaderManager = function () * @type Array */ this.stack = []; - }; PIXI.WebGLShaderManager.prototype.constructor = PIXI.WebGLShaderManager; /** -* Initialises the context and the properties. -* -* @method PIXI.WebGLShaderManager#setContext -* @param gl {WebGLContext} the current WebGL drawing context -*/ + * Initialises the context and the properties. + * + * @method PIXI.WebGLShaderManager#setContext + * @param gl {WebGLContext} the current WebGL drawing context + */ PIXI.WebGLShaderManager.prototype.setContext = function (gl) { this.gl = gl; @@ -74,11 +73,11 @@ PIXI.WebGLShaderManager.prototype.setContext = function (gl) }; /** -* Takes the attributes given in parameters. -* -* @method PIXI.WebGLShaderManager#setAttribs -* @param attribs {Array} attribs -*/ + * Takes the attributes given in parameters. + * + * @method PIXI.WebGLShaderManager#setAttribs + * @param attribs {Array} attribs + */ PIXI.WebGLShaderManager.prototype.setAttribs = function (attribs) { // reset temp state @@ -117,11 +116,11 @@ PIXI.WebGLShaderManager.prototype.setAttribs = function (attribs) }; /** -* Sets the current shader. -* -* @method PIXI.WebGLShaderManager#setShader -* @param shader {Any} -*/ + * Sets the current shader. + * + * @method PIXI.WebGLShaderManager#setShader + * @param shader {Any} + */ PIXI.WebGLShaderManager.prototype.setShader = function (shader) { if(this._currentId === shader._UID) { return false; } @@ -137,10 +136,10 @@ PIXI.WebGLShaderManager.prototype.setShader = function (shader) }; /** -* Destroys this object. -* -* @method PIXI.WebGLShaderManager#destroy -*/ + * Destroys this object. + * + * @method PIXI.WebGLShaderManager#destroy + */ PIXI.WebGLShaderManager.prototype.destroy = function () { this.attribState = null; diff --git a/src/pixi/renderers/webgl/utils/WebGLShaderUtils.js b/src/pixi/renderers/webgl/utils/WebGLShaderUtils.js index 4f21820a4..ba8fbc13d 100644 --- a/src/pixi/renderers/webgl/utils/WebGLShaderUtils.js +++ b/src/pixi/renderers/webgl/utils/WebGLShaderUtils.js @@ -3,47 +3,47 @@ */ /** -* @method PIXI.initDefaultShaders -* @static -* @private -*/ + * @method PIXI.initDefaultShaders + * @static + * @private + */ PIXI.initDefaultShaders = function () { }; /** -* @method PIXI.CompileVertexShader -* @static -* @param gl {WebGLContext} the current WebGL drawing context -* @param shaderSrc {Array} -* @return {Any} -*/ + * @method PIXI.CompileVertexShader + * @static + * @param gl {WebGLContext} the current WebGL drawing context + * @param shaderSrc {Array} + * @return {Any} + */ PIXI.CompileVertexShader = function (gl, shaderSrc) { return PIXI._CompileShader(gl, shaderSrc, gl.VERTEX_SHADER); }; /** -* @method PIXI.CompileFragmentShader -* @static -* @param gl {WebGLContext} the current WebGL drawing context -* @param shaderSrc {Array} -* @return {Any} -*/ + * @method PIXI.CompileFragmentShader + * @static + * @param gl {WebGLContext} the current WebGL drawing context + * @param shaderSrc {Array} + * @return {Any} + */ PIXI.CompileFragmentShader = function (gl, shaderSrc) { return PIXI._CompileShader(gl, shaderSrc, gl.FRAGMENT_SHADER); }; /** -* @method PIXI._CompileShader -* @static -* @private -* @param gl {WebGLContext} the current WebGL drawing context -* @param shaderSrc {Array} -* @param shaderType {Number} -* @return {Any} -*/ + * @method PIXI._CompileShader + * @static + * @private + * @param gl {WebGLContext} the current WebGL drawing context + * @param shaderSrc {Array} + * @param shaderType {Number} + * @return {Any} + */ PIXI._CompileShader = function (gl, shaderSrc, shaderType) { var src = shaderSrc; @@ -67,13 +67,13 @@ PIXI._CompileShader = function (gl, shaderSrc, shaderType) }; /** -* @method PIXI.compileProgram -* @static -* @param gl {WebGLContext} the current WebGL drawing context -* @param vertexSrc {Array} -* @param fragmentSrc {Array} -* @return {Any} -*/ + * @method PIXI.compileProgram + * @static + * @param gl {WebGLContext} the current WebGL drawing context + * @param vertexSrc {Array} + * @param fragmentSrc {Array} + * @return {Any} + */ PIXI.compileProgram = function (gl, vertexSrc, fragmentSrc) { var fragmentShader = PIXI.CompileFragmentShader(gl, fragmentSrc); diff --git a/src/pixi/renderers/webgl/utils/WebGLSpriteBatch.js b/src/pixi/renderers/webgl/utils/WebGLSpriteBatch.js index ae3579f0e..1956f922c 100644 --- a/src/pixi/renderers/webgl/utils/WebGLSpriteBatch.js +++ b/src/pixi/renderers/webgl/utils/WebGLSpriteBatch.js @@ -17,10 +17,9 @@ */ PIXI.WebGLSpriteBatch = function (game) { - /** - * @property {Phaser.Game} game - A reference to the currently running game. - */ + * @property {Phaser.Game} game - A reference to the currently running game. + */ this.game = game; /** @@ -36,15 +35,19 @@ PIXI.WebGLSpriteBatch = function (game) */ this.size = 2000; // Math.pow(2, 16) / this.vertSize; - // the total number of bytes in our batch - // Including texture index: - // position + uv + color + textureIndex - // vec2 + vec2 + (char * 4) + float + /* + * the total number of bytes in our batch + * Including texture index: + * position + uv + color + textureIndex + * vec2 + vec2 + (char * 4) + float + */ this.vertexSize = (4 * 2) + (4 * 2) + (4) + (4); var numVerts = this.vertexSize * this.size * 4; - // this.size * 4 * 4 * this.vertSize; - // the total number of indices in our batch + /* + * this.size * 4 * 4 * this.vertSize; + * the total number of indices in our batch + */ var numIndices = this.size * 6; /** @@ -338,8 +341,10 @@ PIXI.WebGLSpriteBatch.prototype.render = function (sprite, matrix) tx = wt.c * ch + tx; ty = wt.d * ch + ty; - // Rotate matrix by 90 degrees - // We use precalculated values for sine and cosine of rad(90) + /* + * Rotate matrix by 90 degrees + * We use precalculated values for sine and cosine of rad(90) + */ a = a0 * 6.123233995736766e-17 + -c0; b = b0 * 6.123233995736766e-17 + -d0; c = a0 + c0 * 6.123233995736766e-17; @@ -463,11 +468,15 @@ PIXI.WebGLSpriteBatch.prototype.renderTilingSprite = function (sprite) var w = texture.baseTexture.width; var h = texture.baseTexture.height; - // var w = sprite._frame.sourceSizeW; - // var h = sprite._frame.sourceSizeH; + /* + * var w = sprite._frame.sourceSizeW; + * var h = sprite._frame.sourceSizeH; + */ - // w = 16; - // h = 16; + /* + * w = 16; + * h = 16; + */ sprite.tilePosition.x %= w * sprite.tileScaleOffset.x; sprite.tilePosition.y %= h * sprite.tileScaleOffset.y; @@ -649,7 +658,6 @@ PIXI.WebGLSpriteBatch.prototype.flush = function () for (var i = 0, j = this.currentBatchSize; i < j; i++) { - sprite = this.sprites[i]; if (sprite.tilingTexture) @@ -716,8 +724,10 @@ PIXI.WebGLSpriteBatch.prototype.flush = function () shader.syncUniforms(); } - // both these only need to be set if they are changing.. - // set the projection + /* + * both these only need to be set if they are changing.. + * set the projection + */ var projection = this.renderSession.projection; gl.uniform2f(shader.projectionVector, projection.x, projection.y); diff --git a/src/pixi/renderers/webgl/utils/WebGLStencilManager.js b/src/pixi/renderers/webgl/utils/WebGLStencilManager.js index 7069550c6..d73e92817 100644 --- a/src/pixi/renderers/webgl/utils/WebGLStencilManager.js +++ b/src/pixi/renderers/webgl/utils/WebGLStencilManager.js @@ -3,10 +3,10 @@ */ /** -* @class PIXI.WebGLStencilManager -* @constructor -* @private -*/ + * @class PIXI.WebGLStencilManager + * @constructor + * @private + */ PIXI.WebGLStencilManager = function () { this.stencilStack = []; @@ -15,24 +15,24 @@ PIXI.WebGLStencilManager = function () }; /** -* Sets the drawing context to the one given in parameter. -* -* @method PIXI.WebGLStencilManager#setContext -* @param gl {WebGLContext} the current WebGL drawing context -*/ + * Sets the drawing context to the one given in parameter. + * + * @method PIXI.WebGLStencilManager#setContext + * @param gl {WebGLContext} the current WebGL drawing context + */ PIXI.WebGLStencilManager.prototype.setContext = function (gl) { this.gl = gl; }; /** -* Applies the Mask and adds it to the current filter stack. -* -* @method PIXI.WebGLStencilManager#pushMask -* @param graphics {Graphics} -* @param webGLData {Array} -* @param renderSession {Object} -*/ + * Applies the Mask and adds it to the current filter stack. + * + * @method PIXI.WebGLStencilManager#pushMask + * @param graphics {Graphics} + * @param webGLData {Array} + * @param renderSession {Object} + */ PIXI.WebGLStencilManager.prototype.pushStencil = function (graphics, webGLData, renderSession) { var gl = this.gl; @@ -160,8 +160,10 @@ PIXI.WebGLStencilManager.prototype.bindGraphics = function (graphics, webGLData, gl.vertexAttribPointer(shader.aVertexPosition, 2, gl.FLOAT, false, 4 * 2, 0); - // now do the rest.. - // set the index buffer! + /* + * now do the rest.. + * set the index buffer! + */ gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, webGLData.indexBuffer); } else @@ -207,11 +209,9 @@ PIXI.WebGLStencilManager.prototype.popStencil = function (graphics, webGLData, r { // the stack is empty! gl.disable(gl.STENCIL_TEST); - } else { - var level = this.count; this.bindGraphics(graphics, webGLData, renderSession); @@ -250,7 +250,6 @@ PIXI.WebGLStencilManager.prototype.popStencil = function (graphics, webGLData, r { gl.stencilFunc(gl.EQUAL,level, 0xFF); } - } else { @@ -280,16 +279,14 @@ PIXI.WebGLStencilManager.prototype.popStencil = function (graphics, webGLData, r gl.colorMask(true, true, true, true); gl.stencilOp(gl.KEEP,gl.KEEP,gl.KEEP); - - } }; /** -* Destroys the mask stack. -* -* @method PIXI.WebGLStencilManager#destroy -*/ + * Destroys the mask stack. + * + * @method PIXI.WebGLStencilManager#destroy + */ PIXI.WebGLStencilManager.prototype.destroy = function () { this.stencilStack = null; diff --git a/src/pixi/textures/BaseTexture.js b/src/pixi/textures/BaseTexture.js index 4b9da9932..62e34d08a 100644 --- a/src/pixi/textures/BaseTexture.js +++ b/src/pixi/textures/BaseTexture.js @@ -136,7 +136,6 @@ PIXI.BaseTexture = function (source, scaleMode, resolution) * @private */ this._powerOf2 = false; - }; PIXI.BaseTexture.prototype.constructor = PIXI.BaseTexture; @@ -208,7 +207,6 @@ PIXI.BaseTexture.prototype.unloadFromGPU = function () { gl.deleteTexture(glTexture); } - } this._glTextures.length = 0; diff --git a/src/pixi/textures/Texture.js b/src/pixi/textures/Texture.js index 18b3b87f0..d008a2e70 100644 --- a/src/pixi/textures/Texture.js +++ b/src/pixi/textures/Texture.js @@ -148,7 +148,6 @@ PIXI.Texture = function (baseTexture, frame, crop, trim) if (this.noFrame) { frame = new PIXI.Rectangle(0, 0, baseTexture.width, baseTexture.height); } this.setFrame(frame); } - }; PIXI.Texture.prototype.constructor = PIXI.Texture; @@ -225,7 +224,6 @@ PIXI.Texture.prototype.setFrame = function (frame) } if (this.valid) { this._updateUvs(); } - }; /** @@ -263,7 +261,6 @@ PIXI.Texture.prototype._updateUvs = function () */ PIXI.Texture.prototype._updateUvsInverted = function () { - if (!this._uvs) { this._uvs = new PIXI.TextureUvs(); } var frame = this.crop; @@ -281,7 +278,6 @@ PIXI.Texture.prototype._updateUvsInverted = function () this._uvs.x3 = frame.x / tw; this._uvs.y3 = (frame.y + frame.width) / th; - }; /** diff --git a/src/polyfills.js b/src/polyfills.js index a2c715349..339f1b1ff 100644 --- a/src/polyfills.js +++ b/src/polyfills.js @@ -1,7 +1,7 @@ /** -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ if (typeof AudioBufferSourceNode !== 'undefined') { @@ -25,20 +25,17 @@ if (!Math.trunc) } /** -* A polyfill for Function.prototype.bind -*/ + * A polyfill for Function.prototype.bind + */ if (!Function.prototype.bind) { - /* jshint freeze: false */ Function.prototype.bind = (function () { - var slice = Array.prototype.slice; return function (thisArg) { - var target = this, boundArgs = slice.call(arguments, 1); @@ -73,8 +70,8 @@ if (!Function.prototype.bind) } /** -* A polyfill for Array.isArray -*/ + * A polyfill for Array.isArray + */ if (!Array.isArray) { Array.isArray = function (arg) @@ -84,9 +81,9 @@ if (!Array.isArray) } /** -* A polyfill for Array.forEach -* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach -*/ + * A polyfill for Array.forEach + * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach + */ if (!Array.prototype.forEach) { Array.prototype.forEach = function (fun /* , thisArg */) @@ -119,10 +116,10 @@ if (!Array.prototype.forEach) } /** -* Low-budget Float32Array knock-off, suitable for use with P2.js in IE9 -* Source: http://www.html5gamedevs.com/topic/5988-phaser-12-ie9/ -* Cameron Foale (http://www.kibibu.com) -*/ + * Low-budget Float32Array knock-off, suitable for use with P2.js in IE9 + * Source: http://www.html5gamedevs.com/topic/5988-phaser-12-ie9/ + * Cameron Foale (http://www.kibibu.com) + */ if (typeof window.Uint32Array !== 'function' && typeof window.Uint32Array !== 'object') { var CheapArray = function (type) @@ -133,7 +130,6 @@ if (typeof window.Uint32Array !== 'function' && typeof window.Uint32Array !== 'o window[type] = function (arg) { - if (typeof(arg) === 'number') { Array.call(this, arg); diff --git a/src/sound/AudioSprite.js b/src/sound/AudioSprite.js index 8e72ab069..44d509869 100644 --- a/src/sound/AudioSprite.js +++ b/src/sound/AudioSprite.js @@ -16,11 +16,10 @@ */ Phaser.AudioSprite = function (game, key) { - /** - * A reference to the currently running Game. - * @property {Phaser.Game} game - */ + * A reference to the currently running Game. + * @property {Phaser.Game} game + */ this.game = game; /** @@ -70,7 +69,6 @@ Phaser.AudioSprite = function (game, key) this.play(this.autoplayKey); this.autoplay = this.sounds[this.autoplayKey]; } - }; Phaser.AudioSprite.prototype = { @@ -85,11 +83,9 @@ Phaser.AudioSprite.prototype = { */ play: function (marker, volume) { - if (volume === undefined) { volume = 1; } return this.sounds[marker].play(marker, null, volume); - }, /** @@ -100,7 +96,6 @@ Phaser.AudioSprite.prototype = { */ stop: function (marker) { - if (!marker) { for (var key in this.sounds) @@ -112,7 +107,6 @@ Phaser.AudioSprite.prototype = { { this.sounds[marker].stop(); } - }, /** @@ -124,9 +118,7 @@ Phaser.AudioSprite.prototype = { */ get: function (marker) { - return this.sounds[marker]; - } }; diff --git a/src/sound/Sound.js b/src/sound/Sound.js index 8769f5548..86b984b1d 100644 --- a/src/sound/Sound.js +++ b/src/sound/Sound.js @@ -1,216 +1,215 @@ /** -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* The Sound class constructor. -* -* @class Phaser.Sound -* @constructor -* @param {Phaser.Game} game - Reference to the current game instance. -* @param {string} key - Asset key for the sound. -* @param {number} [volume=1] - Default value for the volume, between 0 and 1. -* @param {boolean} [loop=false] - Whether or not the sound will loop. -*/ + * The Sound class constructor. + * + * @class Phaser.Sound + * @constructor + * @param {Phaser.Game} game - Reference to the current game instance. + * @param {string} key - Asset key for the sound. + * @param {number} [volume=1] - Default value for the volume, between 0 and 1. + * @param {boolean} [loop=false] - Whether or not the sound will loop. + */ Phaser.Sound = function (game, key, volume, loop, connect) { - if (volume === undefined) { volume = 1; } if (loop === undefined) { loop = false; } if (connect === undefined) { connect = game.sound.connectToMaster; } /** - * A reference to the currently running Game. - * @property {Phaser.Game} game - */ + * A reference to the currently running Game. + * @property {Phaser.Game} game + */ this.game = game; /** - * @property {string} name - Name of the sound. - */ + * @property {string} name - Name of the sound. + */ this.name = key; /** - * @property {string} key - Asset key for the sound. - */ + * @property {string} key - Asset key for the sound. + */ this.key = key; /** - * @property {boolean} loop - Whether or not the sound or current sound marker will loop. - */ + * @property {boolean} loop - Whether or not the sound or current sound marker will loop. + */ this.loop = loop; /** - * @property {object} markers - The sound markers. - */ + * @property {object} markers - The sound markers. + */ this.markers = {}; /** - * @property {AudioContext} context - Reference to the AudioContext instance. - */ + * @property {AudioContext} context - Reference to the AudioContext instance. + */ this.context = null; /** - * @property {boolean} autoplay - Whether the sound should start automatically. - */ + * @property {boolean} autoplay - Whether the sound should start automatically. + */ this.autoplay = false; /** - * @property {number} totalDuration - The total duration of the sound in seconds. - */ + * @property {number} totalDuration - The total duration of the sound in seconds. + */ this.totalDuration = 0; /** - * @property {number} startTime - The time the sound starts playing, in game-time coordinates (ms). - * @default - */ + * @property {number} startTime - The time the sound starts playing, in game-time coordinates (ms). + * @default + */ this.startTime = 0; /** - * @property {number} currentTime - The current time of sound playback in ms. - */ + * @property {number} currentTime - The current time of sound playback in ms. + */ this.currentTime = 0; /** - * @property {number} duration - The duration of the current sound marker in seconds. - */ + * @property {number} duration - The duration of the current sound marker in seconds. + */ this.duration = 0; /** - * @property {number} durationMS - The duration of the current sound marker in ms. - */ + * @property {number} durationMS - The duration of the current sound marker in ms. + */ this.durationMS = 0; /** - * @property {number} position - The position of the current sound marker in seconds. - */ + * @property {number} position - The position of the current sound marker in seconds. + */ this.position = 0; /** - * @property {number} stopTime - The time the sound stopped in ms. - */ + * @property {number} stopTime - The time the sound stopped in ms. + */ this.stopTime = 0; /** - * @property {boolean} paused - Whether the sound is paused. - * @default - */ + * @property {boolean} paused - Whether the sound is paused. + * @default + */ this.paused = false; /** - * @property {number} pausedPosition - The position the sound had reached when it was paused in ms. - */ + * @property {number} pausedPosition - The position the sound had reached when it was paused in ms. + */ this.pausedPosition = 0; /** - * @property {number} pausedTime - The game time (ms) at which the sound was paused. - */ + * @property {number} pausedTime - The game time (ms) at which the sound was paused. + */ this.pausedTime = 0; /** - * @property {boolean} isPlaying - Whether the sound is currently playing. - * @default - */ + * @property {boolean} isPlaying - Whether the sound is currently playing. + * @default + */ this.isPlaying = false; /** - * @property {string} currentMarker - The string ID of the currently playing marker, if any. - * @default - */ + * @property {string} currentMarker - The string ID of the currently playing marker, if any. + * @default + */ this.currentMarker = ''; /** - * @property {Phaser.Tween} fadeTween - The tween that fades the audio, set via Sound.fadeIn and Sound.fadeOut. - */ + * @property {Phaser.Tween} fadeTween - The tween that fades the audio, set via Sound.fadeIn and Sound.fadeOut. + */ this.fadeTween = null; /** - * @property {boolean} pendingPlayback - Playback is pending (delayed) because the audio isn't decoded or is touch-locked. - * @readonly - */ + * @property {boolean} pendingPlayback - Playback is pending (delayed) because the audio isn't decoded or is touch-locked. + * @readonly + */ this.pendingPlayback = false; /** - * @property {boolean} override - When playing this sound, always start from the beginning. - * @default - */ + * @property {boolean} override - When playing this sound, always start from the beginning. + * @default + */ this.override = false; /** - * @property {boolean} allowMultiple - This will allow you to have multiple instances of this Sound playing at once. This is only useful when running under Web Audio, and we recommend you implement a local pooling system to not flood the sound channels. - * @default - */ + * @property {boolean} allowMultiple - This will allow you to have multiple instances of this Sound playing at once. This is only useful when running under Web Audio, and we recommend you implement a local pooling system to not flood the sound channels. + * @default + */ this.allowMultiple = false; /** - * @property {boolean} playOnce - Marks the Sound for deletion from SoundManager after playing once. Useful for playing several identical sounds overlapping without flooding the sound channel - * @default - */ + * @property {boolean} playOnce - Marks the Sound for deletion from SoundManager after playing once. Useful for playing several identical sounds overlapping without flooding the sound channel + * @default + */ this.playOnce = false; /** - * @property {boolean} usingWebAudio - Whether this sound is being played with Web Audio. - * @readonly - */ + * @property {boolean} usingWebAudio - Whether this sound is being played with Web Audio. + * @readonly + */ this.usingWebAudio = this.game.sound.usingWebAudio; /** - * @property {boolean} usingAudioTag - Whether this sound is being played via the Audio tag. - * @readonly - */ + * @property {boolean} usingAudioTag - Whether this sound is being played via the Audio tag. + * @readonly + */ this.usingAudioTag = this.game.sound.usingAudioTag; /** - * @property {object} externalNode - If defined this Sound won't connect to the SoundManager master gain node, but will instead connect to externalNode. - */ + * @property {object} externalNode - If defined this Sound won't connect to the SoundManager master gain node, but will instead connect to externalNode. + */ this.externalNode = null; /** - * @property {object} masterGainNode - The master gain node in a Web Audio system. - */ + * @property {object} masterGainNode - The master gain node in a Web Audio system. + */ this.masterGainNode = null; /** - * @property {object} gainNode - The gain node in a Web Audio system. - */ + * @property {object} gainNode - The gain node in a Web Audio system. + */ this.gainNode = null; /** - * @property {AudioBufferSourceNode|HTMLAudioElement} _sound - The audio source. - * @private - */ + * @property {AudioBufferSourceNode|HTMLAudioElement} _sound - The audio source. + * @private + */ this._sound = null; /** - * @property {object} _globalVolume - Internal var for keeping track of global volume when using AudioTag - * @private - */ + * @property {object} _globalVolume - Internal var for keeping track of global volume when using AudioTag + * @private + */ this._globalVolume = 1; /** - * @property {boolean} _markedToDelete - When audio stops, disconnect Web Audio nodes. - * @private - */ + * @property {boolean} _markedToDelete - When audio stops, disconnect Web Audio nodes. + * @private + */ this._markedToDelete = false; /** - * @property {boolean} _pendingStart - play() was called but waiting for playback. Audio Tag only, and not used for sound markers. Cleared in update() once playback starts. - * @private - */ + * @property {boolean} _pendingStart - play() was called but waiting for playback. Audio Tag only, and not used for sound markers. Cleared in update() once playback starts. + * @private + */ this._pendingStart = false; /** - * @property {boolean} _removeFromSoundManager - When audio stops, remove it from the Sound Manager and destroy it. - * @private - */ + * @property {boolean} _removeFromSoundManager - When audio stops, remove it from the Sound Manager and destroy it. + * @private + */ this._removeFromSoundManager = false; /** - * @property {number} _sourceId - For debugging Web Audio sources. - * @private - */ + * @property {number} _sourceId - For debugging Web Audio sources. + * @private + */ this._sourceId = 0; if (this.usingWebAudio) @@ -253,151 +252,147 @@ Phaser.Sound = function (game, key, volume, loop, connect) } /** - * @property {Phaser.Signal} onDecoded - The onDecoded event is dispatched when the sound has finished decoding (typically for mp3 files). It passes one argument, this sound. - */ + * @property {Phaser.Signal} onDecoded - The onDecoded event is dispatched when the sound has finished decoding (typically for mp3 files). It passes one argument, this sound. + */ this.onDecoded = new Phaser.Signal(); /** - * @property {Phaser.Signal} onPlay - The onPlay event is dispatched each time this sound is played (but not looped). It passes one argument, this sound. - */ + * @property {Phaser.Signal} onPlay - The onPlay event is dispatched each time this sound is played (but not looped). It passes one argument, this sound. + */ this.onPlay = new Phaser.Signal(); /** - * @property {Phaser.Signal} onPause - The onPause event is dispatched when this sound is paused. It passes one argument, this sound. - */ + * @property {Phaser.Signal} onPause - The onPause event is dispatched when this sound is paused. It passes one argument, this sound. + */ this.onPause = new Phaser.Signal(); /** - * @property {Phaser.Signal} onResume - The onResume event is dispatched when this sound is resumed from a paused state. It passes one argument, this sound. - */ + * @property {Phaser.Signal} onResume - The onResume event is dispatched when this sound is resumed from a paused state. It passes one argument, this sound. + */ this.onResume = new Phaser.Signal(); /** - * @property {Phaser.Signal} onLoop - The onLoop event is dispatched when this sound loops during playback. It passes one argument, this sound. - */ + * @property {Phaser.Signal} onLoop - The onLoop event is dispatched when this sound loops during playback. It passes one argument, this sound. + */ this.onLoop = new Phaser.Signal(); /** - * @property {Phaser.Signal} onStop - The onStop event is dispatched when this sound stops playback or when a non-looping marker completes. It passes two arguments: this sound and any {@link #currentMarker marker} that was playing. - */ + * @property {Phaser.Signal} onStop - The onStop event is dispatched when this sound stops playback or when a non-looping marker completes. It passes two arguments: this sound and any {@link #currentMarker marker} that was playing. + */ this.onStop = new Phaser.Signal(); /** - * @property {Phaser.Signal} onMute - The onMute event is dispatched when this sound is muted. It passes one argument, this sound. - */ + * @property {Phaser.Signal} onMute - The onMute event is dispatched when this sound is muted. It passes one argument, this sound. + */ this.onMute = new Phaser.Signal(); /** - * @property {Phaser.Signal} onMarkerComplete - The onMarkerComplete event is dispatched when a marker within this sound completes playback. It passes two arguments: the {@link #currentMarker} and this sound. - */ + * @property {Phaser.Signal} onMarkerComplete - The onMarkerComplete event is dispatched when a marker within this sound completes playback. It passes two arguments: the {@link #currentMarker} and this sound. + */ this.onMarkerComplete = new Phaser.Signal(); /** - * @property {Phaser.Signal} onFadeComplete - The onFadeComplete event is dispatched when this sound finishes fading either in or out. It passes two arguments: this sound and its current {@link #volume}. - */ + * @property {Phaser.Signal} onFadeComplete - The onFadeComplete event is dispatched when this sound finishes fading either in or out. It passes two arguments: this sound and its current {@link #volume}. + */ this.onFadeComplete = new Phaser.Signal(); /** - * @property {number} _volume - The global audio volume. A value between 0 (silence) and 1 (full volume). - * @private - */ + * @property {number} _volume - The global audio volume. A value between 0 (silence) and 1 (full volume). + * @private + */ this._volume = volume; /** - * @property {any} _buffer - Decoded data buffer / Audio tag. - * @private - */ + * @property {any} _buffer - Decoded data buffer / Audio tag. + * @private + */ this._buffer = null; /** - * @property {boolean} _muted - Boolean indicating whether the sound is muted or not. - * @private - */ + * @property {boolean} _muted - Boolean indicating whether the sound is muted or not. + * @private + */ this._muted = false; /** - * @property {number} _tempMarker - Internal marker var. - * @private - */ + * @property {number} _tempMarker - Internal marker var. + * @private + */ this._tempMarker = 0; /** - * @property {number} _tempPosition - Internal marker var. - * @private - */ + * @property {number} _tempPosition - Internal marker var. + * @private + */ this._tempPosition = 0; /** - * @property {number} _tempVolume - Internal marker var. - * @private - */ + * @property {number} _tempVolume - Internal marker var. + * @private + */ this._tempVolume = 0; /** - * @property {number} _tempPause - Internal marker var. - * @private - */ + * @property {number} _tempPause - Internal marker var. + * @private + */ this._tempPause = 0; /** - * @property {number} _muteVolume - Internal cache var. - * @private - */ + * @property {number} _muteVolume - Internal cache var. + * @private + */ this._muteVolume = 0; /** - * @property {boolean} _tempLoop - Internal cache var. - * @private - */ + * @property {boolean} _tempLoop - Internal cache var. + * @private + */ this._tempLoop = 0; /** - * @property {boolean} _paused - Was this sound paused via code or a game event? - * @private - */ + * @property {boolean} _paused - Was this sound paused via code or a game event? + * @private + */ this._paused = false; /** - * @property {boolean} _onDecodedEventDispatched - Was the onDecoded event dispatched? - * @private - */ + * @property {boolean} _onDecodedEventDispatched - Was the onDecoded event dispatched? + * @private + */ this._onDecodedEventDispatched = false; - }; Phaser.Sound.prototype = { /** - * Called automatically when this sound is unlocked. - * @method Phaser.Sound#soundHasUnlocked - * @param {string} key - The Phaser.Cache key of the sound file to check for decoding. - * @protected - */ + * Called automatically when this sound is unlocked. + * @method Phaser.Sound#soundHasUnlocked + * @param {string} key - The Phaser.Cache key of the sound file to check for decoding. + * @protected + */ soundHasUnlocked: function (key) { - if (key === this.key) { this._sound = this.game.cache.getSoundData(this.key); this.totalDuration = this._sound.duration; } - }, /** - * Adds a marker into the current Sound. A marker is represented by a unique key and a start time and duration. - * This allows you to bundle multiple sounds together into a single audio file and use markers to jump between them for playback. - * - * @method Phaser.Sound#addMarker - * @param {string} name - A unique name for this marker, i.e. 'explosion', 'gunshot', etc. - * @param {number} start - The start point of this marker in the audio file, given in seconds. 2.5 = 2500ms, 0.5 = 500ms, etc. - * @param {number} [duration=1] - The duration of the marker in seconds. 2.5 = 2500ms, 0.5 = 500ms, etc. - * @param {number} [volume=1] - The volume the sound will play back at, between 0 (silent) and 1 (full volume). - * @param {boolean} [loop=false] - Sets if the sound will loop or not. - */ + * Adds a marker into the current Sound. A marker is represented by a unique key and a start time and duration. + * This allows you to bundle multiple sounds together into a single audio file and use markers to jump between them for playback. + * + * @method Phaser.Sound#addMarker + * @param {string} name - A unique name for this marker, i.e. 'explosion', 'gunshot', etc. + * @param {number} start - The start point of this marker in the audio file, given in seconds. 2.5 = 2500ms, 0.5 = 500ms, etc. + * @param {number} [duration=1] - The duration of the marker in seconds. 2.5 = 2500ms, 0.5 = 500ms, etc. + * @param {number} [volume=1] - The volume the sound will play back at, between 0 (silent) and 1 (full volume). + * @param {boolean} [loop=false] - Sets if the sound will loop or not. + */ addMarker: function (name, start, duration, volume, loop) { - if (duration === undefined || duration === null) { duration = 1; } if (volume === undefined || volume === null) { volume = 1; } if (loop === undefined) { loop = false; } @@ -411,28 +406,25 @@ Phaser.Sound.prototype = { durationMS: duration * 1000, loop: loop }; - }, /** - * Removes a marker from the sound. - * @method Phaser.Sound#removeMarker - * @param {string} name - The key of the marker to remove. - */ + * Removes a marker from the sound. + * @method Phaser.Sound#removeMarker + * @param {string} name - The key of the marker to remove. + */ removeMarker: function (name) { - delete this.markers[name]; - }, /** - * Called automatically by the AudioContext when the sound stops playing. - * Doesn't get called if the sound is set to loop or is a section of an Audio Sprite. - * - * @method Phaser.Sound#onEndedHandler - * @protected - */ + * Called automatically by the AudioContext when the sound stops playing. + * Doesn't get called if the sound is set to loop or is a section of an Audio Sprite. + * + * @method Phaser.Sound#onEndedHandler + * @protected + */ onEndedHandler: function () { this._removeOnEndedHandler(); @@ -474,13 +466,12 @@ Phaser.Sound.prototype = { }, /** - * Called automatically by Phaser.SoundManager. - * @method Phaser.Sound#update - * @protected - */ + * Called automatically by Phaser.SoundManager. + * @method Phaser.Sound#update + * @protected + */ update: function () { - if (!this.game.cache.checkSoundKey(this.key)) { this.destroy(); @@ -588,26 +579,23 @@ Phaser.Sound.prototype = { */ loopFull: function (volume) { - return this.play(null, 0, volume, true); - }, /** - * Play this sound, or a marked section of it. - * - * @method Phaser.Sound#play - * @param {string} [marker=''] - If you want to play a marker then give the key here, otherwise leave blank to play the full sound. - * @param {number} [position=0] - The starting position to play the sound from - this is ignored if you provide a marker. - * @param {number} [volume=1] - Volume of the sound you want to play. If none is given it will use the volume given to the Sound when it was created (which defaults to 1 if none was specified). - * @param {boolean} [loop=false] - Loop when finished playing? If not using a marker / audio sprite the looping will be done via the WebAudio loop property, otherwise it's time based. - * @param {boolean} [forceRestart=true] - If the sound is already playing you can set forceRestart to restart it from the beginning. - * @param {boolean} [onPlay=true] - Dispatch the `onPlay` signal. - * @return {Phaser.Sound} This sound instance. - */ + * Play this sound, or a marked section of it. + * + * @method Phaser.Sound#play + * @param {string} [marker=''] - If you want to play a marker then give the key here, otherwise leave blank to play the full sound. + * @param {number} [position=0] - The starting position to play the sound from - this is ignored if you provide a marker. + * @param {number} [volume=1] - Volume of the sound you want to play. If none is given it will use the volume given to the Sound when it was created (which defaults to 1 if none was specified). + * @param {boolean} [loop=false] - Loop when finished playing? If not using a marker / audio sprite the looping will be done via the WebAudio loop property, otherwise it's time based. + * @param {boolean} [forceRestart=true] - If the sound is already playing you can set forceRestart to restart it from the beginning. + * @param {boolean} [onPlay=true] - Dispatch the `onPlay` signal. + * @return {Phaser.Sound} This sound instance. + */ play: function (marker, position, volume, loop, forceRestart, onPlay) { - if (marker === undefined || marker === false || marker === null) { marker = ''; } if (forceRestart === undefined) { forceRestart = true; } if (onPlay === undefined) { onPlay = true; } @@ -635,8 +623,10 @@ Phaser.Sound.prototype = { if (marker === '' && Object.keys(this.markers).length > 0) { - // If they didn't specify a marker but this is an audio sprite, - // we should never play the entire thing + /* + * If they didn't specify a marker but this is an audio sprite, + * we should never play the entire thing + */ return this; } @@ -812,38 +802,34 @@ Phaser.Sound.prototype = { } return this; - }, /** - * Restart the sound, or a marked section of it. - * - * @method Phaser.Sound#restart - * @param {string} [marker=''] - If you want to play a marker then give the key here, otherwise leave blank to play the full sound. - * @param {number} [position=0] - The starting position to play the sound from - this is ignored if you provide a marker. - * @param {number} [volume=1] - Volume of the sound you want to play. - * @param {boolean} [loop=false] - Loop when it finished playing? - */ + * Restart the sound, or a marked section of it. + * + * @method Phaser.Sound#restart + * @param {string} [marker=''] - If you want to play a marker then give the key here, otherwise leave blank to play the full sound. + * @param {number} [position=0] - The starting position to play the sound from - this is ignored if you provide a marker. + * @param {number} [volume=1] - Volume of the sound you want to play. + * @param {boolean} [loop=false] - Loop when it finished playing? + */ restart: function (marker, position, volume, loop) { - marker = marker || ''; position = position || 0; volume = volume || 1; if (loop === undefined) { loop = false; } this.play(marker, position, volume, loop, true); - }, /** - * Pauses the sound. - * - * @method Phaser.Sound#pause - */ + * Pauses the sound. + * + * @method Phaser.Sound#pause + */ pause: function () { - if (this.isPlaying) { this.paused = true; @@ -853,17 +839,15 @@ Phaser.Sound.prototype = { this.onPause.dispatch(this); this.stop(); } - }, /** - * Resumes the sound. - * - * @method Phaser.Sound#resume - */ + * Resumes the sound. + * + * @method Phaser.Sound#resume + */ resume: function () { - if (this.paused) { if (this.usingWebAudio) @@ -908,23 +892,20 @@ Phaser.Sound.prototype = { this.startTime += (this.game.time.time - this.pausedTime); this.onResume.dispatch(this); } - }, /** - * Stop playing this sound. - * - * @method Phaser.Sound#stop - */ + * Stop playing this sound. + * + * @method Phaser.Sound#stop + */ stop: function () { - if (this.isPlaying && this._sound) { if (this.usingWebAudio) { this._stopSourceAndDisconnect(); - } else if (this.usingAudioTag) { @@ -954,24 +935,22 @@ Phaser.Sound.prototype = { this.onStop.dispatch(this, prevMarker); } - }, /** - * Starts this sound playing (or restarts it if already doing so) and sets the volume to zero. - * Then increases the volume from 0 to 1 over the duration specified. - * - * At the end of the fade Sound.onFadeComplete is dispatched with this Sound object as the first parameter, - * and the final volume (1) as the second parameter. - * - * @method Phaser.Sound#fadeIn - * @param {number} [duration=1000] - The time in milliseconds over which the Sound should fade in. - * @param {boolean} [loop=false] - Should the Sound be set to loop? Note that this doesn't cause the fade to repeat. - * @param {string} [marker=(current marker)] - The marker to start at; defaults to the current (last played) marker. To start playing from the beginning specify specify a marker of `''`. - */ + * Starts this sound playing (or restarts it if already doing so) and sets the volume to zero. + * Then increases the volume from 0 to 1 over the duration specified. + * + * At the end of the fade Sound.onFadeComplete is dispatched with this Sound object as the first parameter, + * and the final volume (1) as the second parameter. + * + * @method Phaser.Sound#fadeIn + * @param {number} [duration=1000] - The time in milliseconds over which the Sound should fade in. + * @param {boolean} [loop=false] - Should the Sound be set to loop? Note that this doesn't cause the fade to repeat. + * @param {string} [marker=(current marker)] - The marker to start at; defaults to the current (last played) marker. To start playing from the beginning specify specify a marker of `''`. + */ fadeIn: function (duration, loop, marker) { - if (loop === undefined) { loop = false; } if (marker === undefined) { marker = this.currentMarker; } @@ -983,36 +962,32 @@ Phaser.Sound.prototype = { this.play(marker, 0, 0, loop); this.fadeTo(duration, 1); - }, /** - * Decreases the volume of this Sound from its current value to 0 over the duration specified. - * At the end of the fade Sound.onFadeComplete is dispatched with this Sound object as the first parameter, - * and the final volume (0) as the second parameter. - * - * @method Phaser.Sound#fadeOut - * @param {number} [duration=1000] - The time in milliseconds over which the Sound should fade out. - */ + * Decreases the volume of this Sound from its current value to 0 over the duration specified. + * At the end of the fade Sound.onFadeComplete is dispatched with this Sound object as the first parameter, + * and the final volume (0) as the second parameter. + * + * @method Phaser.Sound#fadeOut + * @param {number} [duration=1000] - The time in milliseconds over which the Sound should fade out. + */ fadeOut: function (duration) { - this.fadeTo(duration, 0); - }, /** - * Fades the volume of this Sound from its current value to the given volume over the duration specified. - * At the end of the fade Sound.onFadeComplete is dispatched with this Sound object as the first parameter, - * and the final volume (volume) as the second parameter. - * - * @method Phaser.Sound#fadeTo - * @param {number} [duration=1000] - The time in milliseconds during which the Sound should fade out. - * @param {number} [volume] - The volume which the Sound should fade to. This is a value between 0 and 1. - */ + * Fades the volume of this Sound from its current value to the given volume over the duration specified. + * At the end of the fade Sound.onFadeComplete is dispatched with this Sound object as the first parameter, + * and the final volume (volume) as the second parameter. + * + * @method Phaser.Sound#fadeTo + * @param {number} [duration=1000] - The time in milliseconds during which the Sound should fade out. + * @param {number} [volume] - The volume which the Sound should fade to. This is a value between 0 and 1. + */ fadeTo: function (duration, volume) { - if (!this.isPlaying || this.paused || volume === this.volume) { return; @@ -1029,41 +1004,37 @@ Phaser.Sound.prototype = { this.fadeTween = this.game.add.tween(this).to({ volume: volume }, duration, Phaser.Easing.Linear.None, true); this.fadeTween.onComplete.add(this.fadeComplete, this); - }, /** - * Internal handler for Sound.fadeIn, Sound.fadeOut and Sound.fadeTo. - * - * @method Phaser.Sound#fadeComplete - * @private - */ + * Internal handler for Sound.fadeIn, Sound.fadeOut and Sound.fadeTo. + * + * @method Phaser.Sound#fadeComplete + * @private + */ fadeComplete: function () { - this.onFadeComplete.dispatch(this, this.volume); if (this.volume === 0) { this.stop(); } - }, /** - * Called automatically by SoundManager.volume. - * - * Sets the volume of AudioTag Sounds as a percentage of the Global Volume. - * - * You should not normally call this directly. - * - * @method Phaser.Sound#updateGlobalVolume - * @protected - * @param {float} globalVolume - The global SoundManager volume. - */ + * Called automatically by SoundManager.volume. + * + * Sets the volume of AudioTag Sounds as a percentage of the Global Volume. + * + * You should not normally call this directly. + * + * @method Phaser.Sound#updateGlobalVolume + * @protected + * @param {float} globalVolume - The global SoundManager volume. + */ updateGlobalVolume: function (globalVolume) { - // this._volume is the % of the global volume this sound should be played at if (this.usingAudioTag && this._sound) @@ -1071,18 +1042,16 @@ Phaser.Sound.prototype = { this._globalVolume = globalVolume; this._sound.volume = this._globalVolume * this._volume; } - }, /** - * Destroys this sound and all associated events and removes it from the SoundManager. - * - * @method Phaser.Sound#destroy - * @param {boolean} [remove=true] - If true this Sound is automatically removed from the SoundManager. - */ + * Destroys this sound and all associated events and removes it from the SoundManager. + * + * @method Phaser.Sound#destroy + * @param {boolean} [remove=true] - If true this Sound is automatically removed from the SoundManager. + */ destroy: function (remove) { - if (remove === undefined) { remove = true; } this._markedToDelete = true; @@ -1113,25 +1082,20 @@ Phaser.Sound.prototype = { _createSourceAndConnect: function () { - this._sound = this.context.createBufferSource(); this._sound.connect(this.externalNode || this.gainNode); this._buffer = this.game.cache.getSoundData(this.key); this._sound.buffer = this._buffer; this._sourceId++; - }, _disconnectSource: function () { - this._sound.disconnect(this.externalNode || this.gainNode); - }, _startSource: function (when, offset, duration) { - // Avoids passing an undefined `duration` (#588, #635). if (duration === undefined) @@ -1142,12 +1106,10 @@ Phaser.Sound.prototype = { { this._sound.start(when || 0, offset || 0, duration); } - }, _stopSourceAndDisconnect: function () { - // Firefox calls onended() after _sound.stop(). Chrome and Safari do not. (#530) this._removeOnEndedHandler(); @@ -1163,21 +1125,16 @@ Phaser.Sound.prototype = { this._disconnectSource(); this._sound = null; - }, _addOnEndedHandler: function () { - this._sound.onended = this.onEndedHandler.bind(this); - }, _removeOnEndedHandler: function () { - this._sound.onended = null; - } }; @@ -1185,10 +1142,10 @@ Phaser.Sound.prototype = { Phaser.Sound.prototype.constructor = Phaser.Sound; /** -* @name Phaser.Sound#isDecoding -* @property {boolean} isDecoding - Returns true if the sound file is still decoding. -* @readonly -*/ + * @name Phaser.Sound#isDecoding + * @property {boolean} isDecoding - Returns true if the sound file is still decoding. + * @readonly + */ Object.defineProperty(Phaser.Sound.prototype, 'isDecoding', { get: function () @@ -1199,10 +1156,10 @@ Object.defineProperty(Phaser.Sound.prototype, 'isDecoding', { }); /** -* @name Phaser.Sound#isDecoded -* @property {boolean} isDecoded - Returns true if the sound file has decoded. -* @readonly -*/ + * @name Phaser.Sound#isDecoded + * @property {boolean} isDecoded - Returns true if the sound file has decoded. + * @readonly + */ Object.defineProperty(Phaser.Sound.prototype, 'isDecoded', { get: function () @@ -1213,21 +1170,18 @@ Object.defineProperty(Phaser.Sound.prototype, 'isDecoded', { }); /** -* @name Phaser.Sound#mute -* @property {boolean} mute - Gets or sets the muted state of this sound. -*/ + * @name Phaser.Sound#mute + * @property {boolean} mute - Gets or sets the muted state of this sound. + */ Object.defineProperty(Phaser.Sound.prototype, 'mute', { get: function () { - return (this._muted || this.game.sound.mute); - }, set: function (value) { - value = value || false; if (value === this._muted) @@ -1264,15 +1218,14 @@ Object.defineProperty(Phaser.Sound.prototype, 'mute', { } this.onMute.dispatch(this); - } }); /** -* @name Phaser.Sound#volume -* @property {number} volume - Gets or sets the volume of this sound, a value between 0 and 1. The value given is clamped to the range 0 to 1. -*/ + * @name Phaser.Sound#volume + * @property {number} volume - Gets or sets the volume of this sound, a value between 0 and 1. The value given is clamped to the range 0 to 1. + */ Object.defineProperty(Phaser.Sound.prototype, 'volume', { get: function () @@ -1282,7 +1235,6 @@ Object.defineProperty(Phaser.Sound.prototype, 'volume', { set: function (value) { - // Causes an Index size error if you don't clamp the value if (this.usingAudioTag) { diff --git a/src/sound/SoundManager.js b/src/sound/SoundManager.js index 283f27391..1843ba60f 100644 --- a/src/sound/SoundManager.js +++ b/src/sound/SoundManager.js @@ -1,57 +1,56 @@ /** -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* The Sound Manager is responsible for playing back audio via either the Legacy HTML Audio tag or via Web Audio if the browser supports it. -* Note: On Firefox 25+ on Linux if you have media.gstreamer disabled in about:config then it cannot play back mp3 or m4a files. -* The audio file type and the encoding of those files are extremely important. Not all browsers can play all audio formats. -* There is a good guide to what's supported here: http://hpr.dogphilosophy.net/test/ -* -* If you are reloading a Phaser Game on a page that never properly refreshes (such as in an AngularJS project) then you will quickly run out -* of AudioContext nodes. If this is the case create a global var called {@link PhaserGlobal} on the window object before creating the game. The active -* AudioContext will then be saved to `window.PhaserGlobal.audioContext` when the Phaser game is destroyed, and re-used when it starts again. -* -* Mobile warning: There are some mobile devices (certain iPad 2 and iPad Mini revisions) that cannot play 48000 Hz audio. -* When they try to play the audio becomes extremely distorted and buzzes, eventually crashing the sound system. -* The solution is to use a lower encoding rate such as 44100 Hz. Sometimes the audio context will -* be created with a sampleRate of 48000. If this happens and audio distorts you should re-create the context. -* -* @class Phaser.SoundManager -* @constructor -* @param {Phaser.Game} game - Reference to the current game instance. -*/ + * The Sound Manager is responsible for playing back audio via either the Legacy HTML Audio tag or via Web Audio if the browser supports it. + * Note: On Firefox 25+ on Linux if you have media.gstreamer disabled in about:config then it cannot play back mp3 or m4a files. + * The audio file type and the encoding of those files are extremely important. Not all browsers can play all audio formats. + * There is a good guide to what's supported here: http://hpr.dogphilosophy.net/test/ + * + * If you are reloading a Phaser Game on a page that never properly refreshes (such as in an AngularJS project) then you will quickly run out + * of AudioContext nodes. If this is the case create a global var called {@link PhaserGlobal} on the window object before creating the game. The active + * AudioContext will then be saved to `window.PhaserGlobal.audioContext` when the Phaser game is destroyed, and re-used when it starts again. + * + * Mobile warning: There are some mobile devices (certain iPad 2 and iPad Mini revisions) that cannot play 48000 Hz audio. + * When they try to play the audio becomes extremely distorted and buzzes, eventually crashing the sound system. + * The solution is to use a lower encoding rate such as 44100 Hz. Sometimes the audio context will + * be created with a sampleRate of 48000. If this happens and audio distorts you should re-create the context. + * + * @class Phaser.SoundManager + * @constructor + * @param {Phaser.Game} game - Reference to the current game instance. + */ Phaser.SoundManager = function (game) { - /** - * @property {Phaser.Game} game - Local reference to game. - */ + * @property {Phaser.Game} game - Local reference to game. + */ this.game = game; /** - * @property {Phaser.Signal} onSoundDecode - The event dispatched when a sound decodes (typically only for mp3 files) - */ + * @property {Phaser.Signal} onSoundDecode - The event dispatched when a sound decodes (typically only for mp3 files) + */ this.onSoundDecode = new Phaser.Signal(); /** - * This signal is dispatched whenever the global volume changes. The new volume is passed as the only parameter to your callback. - * @property {Phaser.Signal} onVolumeChange - */ + * This signal is dispatched whenever the global volume changes. The new volume is passed as the only parameter to your callback. + * @property {Phaser.Signal} onVolumeChange + */ this.onVolumeChange = new Phaser.Signal(); /** - * This signal is dispatched when the SoundManager is globally muted, either directly via game code or as a result of the game pausing. - * @property {Phaser.Signal} onMute - */ + * This signal is dispatched when the SoundManager is globally muted, either directly via game code or as a result of the game pausing. + * @property {Phaser.Signal} onMute + */ this.onMute = new Phaser.Signal(); /** - * This signal is dispatched when the SoundManager is globally un-muted, either directly via game code or as a result of the game resuming from a pause. - * @property {Phaser.Signal} onUnMute - */ + * This signal is dispatched when the SoundManager is globally un-muted, either directly via game code or as a result of the game resuming from a pause. + * @property {Phaser.Signal} onUnMute + */ this.onUnMute = new Phaser.Signal(); /** @@ -62,9 +61,9 @@ Phaser.SoundManager = function (game) this.onTouchUnlock = new Phaser.Signal(); /** - * @property {AudioContext} context - The AudioContext being used for playback. - * @default - */ + * @property {AudioContext} context - The AudioContext being used for playback. + * @default + */ this.context = null; /** @@ -78,127 +77,125 @@ Phaser.SoundManager = function (game) this.baseLatency = null; /** - * @property {boolean} usingWebAudio - True the SoundManager and device are both using Web Audio. - * @readonly - */ + * @property {boolean} usingWebAudio - True the SoundManager and device are both using Web Audio. + * @readonly + */ this.usingWebAudio = false; /** - * @property {boolean} usingAudioTag - True the SoundManager and device are both using the Audio tag instead of Web Audio. - * @readonly - */ + * @property {boolean} usingAudioTag - True the SoundManager and device are both using the Audio tag instead of Web Audio. + * @readonly + */ this.usingAudioTag = false; /** - * @property {boolean} noAudio - True if audio been disabled via the PhaserGlobal (useful if you need to use a 3rd party audio library) or the device doesn't support any audio. - * @default - */ + * @property {boolean} noAudio - True if audio been disabled via the PhaserGlobal (useful if you need to use a 3rd party audio library) or the device doesn't support any audio. + * @default + */ this.noAudio = false; /** - * @property {boolean} connectToMaster - Used in conjunction with Sound.externalNode this allows you to stop a Sound node being connected to the SoundManager master gain node. - * @default - */ + * @property {boolean} connectToMaster - Used in conjunction with Sound.externalNode this allows you to stop a Sound node being connected to the SoundManager master gain node. + * @default + */ this.connectToMaster = true; /** - * @property {boolean} touchLocked - true if the audio system is currently locked awaiting a touch event. - * @default - */ + * @property {boolean} touchLocked - true if the audio system is currently locked awaiting a touch event. + * @default + */ this.touchLocked = false; /** - * @property {number} channels - The number of audio channels to use in playback. - * @default - */ + * @property {number} channels - The number of audio channels to use in playback. + * @default + */ this.channels = 32; /** - * Set to true to have all sound muted when the Phaser game pauses (such as on loss of focus), - * or set to false to keep audio playing, regardless of the game pause state. You may need to - * do this should you wish to control audio muting via external DOM buttons or similar. - * @property {boolean} muteOnPause - * @default - */ + * Set to true to have all sound muted when the Phaser game pauses (such as on loss of focus), + * or set to false to keep audio playing, regardless of the game pause state. You may need to + * do this should you wish to control audio muting via external DOM buttons or similar. + * @property {boolean} muteOnPause + * @default + */ this.muteOnPause = true; /** - * @property {boolean} _codeMuted - Internal mute tracking var. - * @private - * @default - */ + * @property {boolean} _codeMuted - Internal mute tracking var. + * @private + * @default + */ this._codeMuted = false; /** - * @property {boolean} _muted - Internal mute tracking var. - * @private - * @default - */ + * @property {boolean} _muted - Internal mute tracking var. + * @private + * @default + */ this._muted = false; /** - * @property {AudioContext} _unlockSource - Internal unlock tracking var. - * @private - * @default - */ + * @property {AudioContext} _unlockSource - Internal unlock tracking var. + * @private + * @default + */ this._unlockSource = null; /** - * @property {number} _volume - The global audio volume. A value between 0 (silence) and 1 (full volume). - * @private - * @default - */ + * @property {number} _volume - The global audio volume. A value between 0 (silence) and 1 (full volume). + * @private + * @default + */ this._volume = 1; /** - * @property {array} _sounds - An array containing all the sounds - * @private - */ + * @property {array} _sounds - An array containing all the sounds + * @private + */ this._sounds = []; /** - * @property {Phaser.ArraySet} _watchList - An array set containing all the sounds being monitored for decoding status. - * @private - */ + * @property {Phaser.ArraySet} _watchList - An array set containing all the sounds being monitored for decoding status. + * @private + */ this._watchList = new Phaser.ArraySet(); /** - * @property {boolean} _watching - Is the SoundManager monitoring the watchList? - * @private - */ + * @property {boolean} _watching - Is the SoundManager monitoring the watchList? + * @private + */ this._watching = false; /** - * @property {function} _watchCallback - The callback to invoke once the watchlist is clear. - * @private - */ + * @property {function} _watchCallback - The callback to invoke once the watchlist is clear. + * @private + */ this._watchCallback = null; /** - * @property {object} _watchContext - The context in which to call the watchlist callback. - * @private - */ + * @property {object} _watchContext - The context in which to call the watchlist callback. + * @private + */ this._watchContext = null; /** - * @property {function} _resumeWebAudioOnClick - Bound 'click' handler. Added in boot(), if necessary. - * @private - */ + * @property {function} _resumeWebAudioOnClick - Bound 'click' handler. Added in boot(), if necessary. + * @private + */ this._resumeWebAudioOnClick = this._resumeWebAudioOnClick.bind(this); - }; Phaser.SoundManager.prototype = { /** - * Initialises the sound manager. - * @method Phaser.SoundManager#boot - * @protected - */ + * Initialises the sound manager. + * @method Phaser.SoundManager#boot + * @protected + */ boot: function () { - var device = this.game.device; var PhaserGlobal = window.PhaserGlobal; @@ -283,8 +280,10 @@ Phaser.SoundManager.prototype = { this.masterGain.gain.value = 1; this.masterGain.connect(this.context.destination); - // A suspended context is actually normal (momentarily) in Firefox. - // In that case the input handler will do nothing, which is fine. + /* + * A suspended context is actually normal (momentarily) in Firefox. + * In that case the input handler will do nothing, which is fine. + */ if (this.context.state === 'suspended') { this.game.canvas.addEventListener('click', this._resumeWebAudioOnClick); @@ -304,18 +303,16 @@ Phaser.SoundManager.prototype = { { console.log('A "GainNode.gain.value setter smoothing is deprecated" notice in Chrome is normal. '); } - }, /** - * Sets the Input Manager touch callback to be SoundManager.unlock. - * Required for iOS audio device unlocking. Mostly just used internally. - * - * @method Phaser.SoundManager#setTouchLock - */ + * Sets the Input Manager touch callback to be SoundManager.unlock. + * Required for iOS audio device unlocking. Mostly just used internally. + * + * @method Phaser.SoundManager#setTouchLock + */ setTouchLock: function () { - if (this.noAudio || (window.PhaserGlobal && window.PhaserGlobal.disableAudio === true)) { return; @@ -324,50 +321,44 @@ Phaser.SoundManager.prototype = { this.game.input.addTouchLockCallback(this.unlock, this, true); this.touchLocked = true; - }, /** - * Turns off {@link #touchLocked} and dispatches {@link #onTouchUnlock}. - * - * @method Phaser.SoundManager#setTouchUnlock - * @private - */ + * Turns off {@link #touchLocked} and dispatches {@link #onTouchUnlock}. + * + * @method Phaser.SoundManager#setTouchUnlock + * @private + */ setTouchUnlock: function () { - this.touchLocked = false; this._unlockSource = null; this.onTouchUnlock.dispatch(); - }, /** - * Try to resume a suspended WebAudio context. - * - * If the context isn't suspended, or if WebAudio isn't in use, nothing is done. - * - * @return {?Promise} - A Promise, if resume was called. See {@link https://developer.mozilla.org/en-US/docs/Web/API/BaseAudioContext/resume}. - */ + * Try to resume a suspended WebAudio context. + * + * If the context isn't suspended, or if WebAudio isn't in use, nothing is done. + * + * @return {?Promise} - A Promise, if resume was called. See {@link https://developer.mozilla.org/en-US/docs/Web/API/BaseAudioContext/resume}. + */ resumeWebAudio: function () { - if (this.usingWebAudio && this.context.state === 'suspended') { return this.context.resume(); } - }, /** - * Enables the audio, usually after the first touch. - * - * @method Phaser.SoundManager#unlock - * @return {boolean} True if the callback should be removed, otherwise false. - */ + * Enables the audio, usually after the first touch. + * + * @method Phaser.SoundManager#unlock + * @return {boolean} True if the callback should be removed, otherwise false. + */ unlock: function () { - if (this.noAudio || !this.touchLocked || this._unlockSource !== null) { return true; @@ -380,8 +371,10 @@ Phaser.SoundManager.prototype = { } else if (this.usingWebAudio) { - // Create empty buffer and play it - // The onended handler will set touchLocked to false + /* + * Create empty buffer and play it + * The onended handler will set touchLocked to false + */ var buffer = this.context.createBuffer(1, 1, 22050); this._unlockSource = this.context.createBufferSource(); @@ -411,17 +404,15 @@ Phaser.SoundManager.prototype = { // We can remove the event because we've done what we needed (started the unlock sound playing) return true; - }, /** - * Stops all the sounds in the game. - * - * @method Phaser.SoundManager#stopAll - */ + * Stops all the sounds in the game. + * + * @method Phaser.SoundManager#stopAll + */ stopAll: function () { - if (this.noAudio) { return; @@ -434,17 +425,15 @@ Phaser.SoundManager.prototype = { this._sounds[i].stop(); } } - }, /** - * Pauses all the sounds in the game. - * - * @method Phaser.SoundManager#pauseAll - */ + * Pauses all the sounds in the game. + * + * @method Phaser.SoundManager#pauseAll + */ pauseAll: function () { - if (this.noAudio) { return; @@ -457,17 +446,15 @@ Phaser.SoundManager.prototype = { this._sounds[i].pause(); } } - }, /** - * Resumes every sound in the game. - * - * @method Phaser.SoundManager#resumeAll - */ + * Resumes every sound in the game. + * + * @method Phaser.SoundManager#resumeAll + */ resumeAll: function () { - if (this.noAudio) { return; @@ -480,19 +467,17 @@ Phaser.SoundManager.prototype = { this._sounds[i].resume(); } } - }, /** - * Decode a sound by its asset key. - * - * @method Phaser.SoundManager#decode - * @param {string} key - Assets key of the sound to be decoded. - * @param {Phaser.Sound} [sound] - Its buffer will be set to decoded data. - */ + * Decode a sound by its asset key. + * + * @method Phaser.SoundManager#decode + * @param {string} key - Assets key of the sound to be decoded. + * @param {Phaser.Sound} [sound] - Its buffer will be set to decoded data. + */ decode: function (key, sound) { - sound = sound || null; var soundData = this.game.cache.getSoundData(key); @@ -509,7 +494,6 @@ Phaser.SoundManager.prototype = { { this.context.decodeAudioData(soundData, function (buffer) { - if (buffer) { _this.game.cache.decodedSound(key, buffer); @@ -520,7 +504,6 @@ Phaser.SoundManager.prototype = { catch (e) {} // eslint-disable-line no-empty } } - }, /** @@ -536,7 +519,6 @@ Phaser.SoundManager.prototype = { */ setDecodedCallback: function (files, callback, callbackContext) { - if (typeof files === 'string') { files = [ files ]; @@ -571,18 +553,16 @@ Phaser.SoundManager.prototype = { this._watchCallback = callback; this._watchContext = callbackContext; } - }, /** - * Updates every sound in the game, checks for audio unlock on mobile and monitors the decoding watch list. - * - * @method Phaser.SoundManager#update - * @protected - */ + * Updates every sound in the game, checks for audio unlock on mobile and monitors the decoding watch list. + * + * @method Phaser.SoundManager#update + * @protected + */ update: function () { - if (this.noAudio) { return; @@ -613,22 +593,20 @@ Phaser.SoundManager.prototype = { this._watchCallback.call(this._watchContext); } } - }, /** - * Adds a new Sound into the SoundManager. - * - * @method Phaser.SoundManager#add - * @param {string} key - Asset key for the sound. - * @param {number} [volume=1] - Default value for the volume. - * @param {boolean} [loop=false] - Whether or not the sound will loop. - * @param {boolean} [connect=true] - Controls if the created Sound object will connect to the master gainNode of the SoundManager when running under WebAudio. - * @return {Phaser.Sound} The new sound instance. - */ + * Adds a new Sound into the SoundManager. + * + * @method Phaser.SoundManager#add + * @param {string} key - Asset key for the sound. + * @param {number} [volume=1] - Default value for the volume. + * @param {boolean} [loop=false] - Whether or not the sound will loop. + * @param {boolean} [connect=true] - Controls if the created Sound object will connect to the master gainNode of the SoundManager when running under WebAudio. + * @return {Phaser.Sound} The new sound instance. + */ add: function (key, volume, loop, connect) { - if (volume === undefined) { volume = 1; } if (loop === undefined) { loop = false; } if (connect === undefined) { connect = this.connectToMaster; } @@ -638,7 +616,6 @@ Phaser.SoundManager.prototype = { this._sounds.push(sound); return sound; - }, /** @@ -650,23 +627,20 @@ Phaser.SoundManager.prototype = { */ addSprite: function (key) { - var audioSprite = new Phaser.AudioSprite(this.game, key); return audioSprite; - }, /** - * Removes a Sound from the SoundManager. The removed Sound is destroyed before removal. - * - * @method Phaser.SoundManager#remove - * @param {Phaser.Sound} sound - The sound object to remove. - * @return {boolean} True if the sound was removed successfully, otherwise false. - */ + * Removes a Sound from the SoundManager. The removed Sound is destroyed before removal. + * + * @method Phaser.SoundManager#remove + * @param {Phaser.Sound} sound - The sound object to remove. + * @return {boolean} True if the sound was removed successfully, otherwise false. + */ remove: function (sound) { - var i = this._sounds.length; while (i--) @@ -680,18 +654,16 @@ Phaser.SoundManager.prototype = { } return false; - }, /** - * Removes all Sounds from the SoundManager. - * The removed Sounds are destroyed before removal. - * - * @method Phaser.SoundManager#removeAll - */ + * Removes all Sounds from the SoundManager. + * The removed Sounds are destroyed before removal. + * + * @method Phaser.SoundManager#removeAll + */ removeAll: function () { - this.stopAll(); for (var i = 0; i < this._sounds.length; i++) @@ -703,20 +675,18 @@ Phaser.SoundManager.prototype = { } this._sounds.length = 0; - }, /** - * Removes all Sounds from the SoundManager that have an asset key matching the given value. - * The removed Sounds are destroyed before removal. - * - * @method Phaser.SoundManager#removeByKey - * @param {string} key - The key to match when removing sound objects. - * @return {number} The number of matching sound objects that were removed. - */ + * Removes all Sounds from the SoundManager that have an asset key matching the given value. + * The removed Sounds are destroyed before removal. + * + * @method Phaser.SoundManager#removeByKey + * @param {string} key - The key to match when removing sound objects. + * @return {number} The number of matching sound objects that were removed. + */ removeByKey: function (key) { - var i = this._sounds.length; var removed = 0; @@ -731,21 +701,19 @@ Phaser.SoundManager.prototype = { } return removed; - }, /** - * Adds a new Sound into the SoundManager and starts it playing. - * - * @method Phaser.SoundManager#play - * @param {string} key - Asset key for the sound. - * @param {number} [volume=1] - Default value for the volume. - * @param {boolean} [loop=false] - Whether or not the sound will loop. - * @return {Phaser.Sound} The new sound instance. - */ + * Adds a new Sound into the SoundManager and starts it playing. + * + * @method Phaser.SoundManager#play + * @param {string} key - Asset key for the sound. + * @param {number} [volume=1] - Default value for the volume. + * @param {boolean} [loop=false] - Whether or not the sound will loop. + * @return {Phaser.Sound} The new sound instance. + */ play: function (key, volume, loop) { - if (this.noAudio) { return; @@ -756,18 +724,16 @@ Phaser.SoundManager.prototype = { sound.play(); return sound; - }, /** - * Internal mute handler called automatically by the SoundManager.mute setter. - * - * @method Phaser.SoundManager#setMute - * @private - */ + * Internal mute handler called automatically by the SoundManager.mute setter. + * + * @method Phaser.SoundManager#setMute + * @private + */ setMute: function () { - if (this._muted) { return; @@ -791,18 +757,16 @@ Phaser.SoundManager.prototype = { } this.onMute.dispatch(); - }, /** - * Internal mute handler called automatically by the SoundManager.mute setter. - * - * @method Phaser.SoundManager#unsetMute - * @private - */ + * Internal mute handler called automatically by the SoundManager.mute setter. + * + * @method Phaser.SoundManager#unsetMute + * @private + */ unsetMute: function () { - if (!this._muted || this._codeMuted) { return; @@ -825,17 +789,15 @@ Phaser.SoundManager.prototype = { } this.onUnMute.dispatch(); - }, /** - * Stops all the sounds in the game, then destroys them and finally clears up any callbacks. - * - * @method Phaser.SoundManager#destroy - */ + * Stops all the sounds in the game, then destroys them and finally clears up any callbacks. + * + * @method Phaser.SoundManager#destroy + */ destroy: function () { - this.removeAll(); this.onSoundDecode.dispose(); @@ -855,7 +817,6 @@ Phaser.SoundManager.prototype = { this.context.close(); } } - }, _resumeWebAudioOnClick: function () @@ -870,21 +831,18 @@ Phaser.SoundManager.prototype = { Phaser.SoundManager.prototype.constructor = Phaser.SoundManager; /** -* @name Phaser.SoundManager#mute -* @property {boolean} mute - Gets or sets the muted state of the SoundManager. This effects all sounds in the game. -*/ + * @name Phaser.SoundManager#mute + * @property {boolean} mute - Gets or sets the muted state of the SoundManager. This effects all sounds in the game. + */ Object.defineProperty(Phaser.SoundManager.prototype, 'mute', { get: function () { - return this._muted; - }, set: function (value) { - value = value || false; if (value) @@ -912,21 +870,18 @@ Object.defineProperty(Phaser.SoundManager.prototype, 'mute', { }); /** -* @name Phaser.SoundManager#volume -* @property {number} volume - Gets or sets the global volume of the SoundManager, a value between 0 and 1. The value given is clamped to the range 0 to 1. -*/ + * @name Phaser.SoundManager#volume + * @property {number} volume - Gets or sets the global volume of the SoundManager, a value between 0 and 1. The value given is clamped to the range 0 to 1. + */ Object.defineProperty(Phaser.SoundManager.prototype, 'volume', { get: function () { - return this._volume; - }, set: function (value) { - if (value < 0) { value = 0; @@ -958,7 +913,6 @@ Object.defineProperty(Phaser.SoundManager.prototype, 'volume', { this.onVolumeChange.dispatch(value); } - } }); diff --git a/src/stubs/Color.js b/src/stubs/Color.js index 0093bfe62..b2fc249ee 100644 --- a/src/stubs/Color.js +++ b/src/stubs/Color.js @@ -1,32 +1,31 @@ /** -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* The Phaser.Color stub. This stub only includes the bare minimum functions that Phaser needs. -* -* @class Phaser.Color -*/ + * The Phaser.Color stub. This stub only includes the bare minimum functions that Phaser needs. + * + * @class Phaser.Color + */ Phaser.Color = { /** - * Converts a value - a "hex" string, a "CSS 'web' string", or a number - into red, green, blue, and alpha components. - * - * The value can be a string (see `hexToColor` and `webToColor` for the supported formats) or a packed integer (see `getRGB`). - * - * An alpha channel is _not_ supported when specifying a hex string. - * - * @method Phaser.Color.valueToColor - * @static - * @param {string|number} value - The color expressed as a recognized string format or a packed integer. - * @param {object} [out] - The object to use for the output. If not provided a new object will be created. - * @return {object} The (`out`) object with the red, green, blue, and alpha values set as the r/g/b/a properties. - */ + * Converts a value - a "hex" string, a "CSS 'web' string", or a number - into red, green, blue, and alpha components. + * + * The value can be a string (see `hexToColor` and `webToColor` for the supported formats) or a packed integer (see `getRGB`). + * + * An alpha channel is _not_ supported when specifying a hex string. + * + * @method Phaser.Color.valueToColor + * @static + * @param {string|number} value - The color expressed as a recognized string format or a packed integer. + * @param {object} [out] - The object to use for the output. If not provided a new object will be created. + * @return {object} The (`out`) object with the red, green, blue, and alpha values set as the r/g/b/a properties. + */ valueToColor: function (value, out) { - if (typeof value === 'string') { if (value.indexOf('rgb') === 0) @@ -42,8 +41,10 @@ Phaser.Color = { } else if (typeof value === 'number') { - // `getRGB` does not take optional object to modify; - // alpha is also adjusted to match `createColor`. + /* + * `getRGB` does not take optional object to modify; + * alpha is also adjusted to match `createColor`. + */ var tempColor = Phaser.Color.getRGB(value); out.r = tempColor.r; out.g = tempColor.g; @@ -55,22 +56,20 @@ Phaser.Color = { { return out; } - }, /** - * Return the component parts of a color as an Object with the properties alpha, red, green, blue. - * - * Alpha will only be set if it exist in the given color (0xAARRGGBB) - * - * @method Phaser.Color.getRGB - * @static - * @param {number} color - Color in RGB (0xRRGGBB) or ARGB format (0xAARRGGBB). - * @returns {object} An Object with properties: alpha, red, green, blue (also r, g, b and a). Alpha will only be present if a color value > 16777215 was given. - */ + * Return the component parts of a color as an Object with the properties alpha, red, green, blue. + * + * Alpha will only be set if it exist in the given color (0xAARRGGBB) + * + * @method Phaser.Color.getRGB + * @static + * @param {number} color - Color in RGB (0xRRGGBB) or ARGB format (0xAARRGGBB). + * @returns {object} An Object with properties: alpha, red, green, blue (also r, g, b and a). Alpha will only be present if a color value > 16777215 was given. + */ getRGB: function (color) { - if (color > 16777215) { // The color value has an alpha component @@ -98,23 +97,21 @@ Phaser.Color = { b: color & 0xFF }; } - }, /** - * Converts a CSS 'web' string into a Phaser Color object. - * - * The web string can be in the format `'rgb(r,g,b)'` or `'rgba(r,g,b,a)'` where r/g/b are in the range [0..255] and a is in the range [0..1]. - * - * @method Phaser.Color.webToColor - * @static - * @param {string} web - The color string in CSS 'web' format. - * @param {object} [out] - An object into which 4 properties will be created: r, g, b and a. If not provided a new object will be created. - * @return {object} An object with the red, green, blue and alpha values set in the r, g, b and a properties. - */ + * Converts a CSS 'web' string into a Phaser Color object. + * + * The web string can be in the format `'rgb(r,g,b)'` or `'rgba(r,g,b,a)'` where r/g/b are in the range [0..255] and a is in the range [0..1]. + * + * @method Phaser.Color.webToColor + * @static + * @param {string} web - The color string in CSS 'web' format. + * @param {object} [out] - An object into which 4 properties will be created: r, g, b and a. If not provided a new object will be created. + * @return {object} An object with the red, green, blue and alpha values set in the r, g, b and a properties. + */ webToColor: function (web, out) { - var result = (/^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d+(?:\.\d+)?))?\s*\)$/).exec(web); if (result) @@ -127,25 +124,23 @@ Phaser.Color = { } return out; - }, /** - * Converts a hex string into a Phaser Color object. - * - * The hex string can supplied as `'#0033ff'` or the short-hand format of `'#03f'`; it can begin with an optional "#" or "0x", or be unprefixed. - * - * An alpha channel is _not_ supported. - * - * @method Phaser.Color.hexToColor - * @static - * @param {string} hex - The color string in a hex format. - * @param {object} [out] - An object into which 3 properties will be created or set: r, g and b. If not provided a new object will be created. - * @return {object} An object with the red, green and blue values set in the r, g and b properties. - */ + * Converts a hex string into a Phaser Color object. + * + * The hex string can supplied as `'#0033ff'` or the short-hand format of `'#03f'`; it can begin with an optional "#" or "0x", or be unprefixed. + * + * An alpha channel is _not_ supported. + * + * @method Phaser.Color.hexToColor + * @static + * @param {string} hex - The color string in a hex format. + * @param {object} [out] - An object into which 3 properties will be created or set: r, g and b. If not provided a new object will be created. + * @return {object} An object with the red, green and blue values set in the r, g and b properties. + */ hexToColor: function (hex, out) { - // Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF") hex = hex.replace(/^(?:#|0x)?([a-f\d])([a-f\d])([a-f\d])$/i, function (m, r, g, b) { @@ -166,61 +161,54 @@ Phaser.Color = { } return out; - }, /** - * Takes a color object and updates the rgba property. - * - * @method Phaser.Color.updateColor - * @static - * @param {object} out - The color object to update. - * @returns {number} A native color value integer (format: 0xAARRGGBB). - */ + * Takes a color object and updates the rgba property. + * + * @method Phaser.Color.updateColor + * @static + * @param {object} out - The color object to update. + * @returns {number} A native color value integer (format: 0xAARRGGBB). + */ updateColor: function (out) { - out.rgba = 'rgba(' + out.r.toString() + ',' + out.g.toString() + ',' + out.b.toString() + ',' + out.a.toString() + ')'; out.color = Phaser.Color.getColor(out.r, out.g, out.b); out.color32 = Phaser.Color.getColor32(out.a, out.r, out.g, out.b); return out; - }, /** - * Given an alpha and 3 color values this will return an integer representation of it. - * - * @method Phaser.Color.getColor32 - * @static - * @param {number} a - The alpha color component, in the range 0 - 255. - * @param {number} r - The red color component, in the range 0 - 255. - * @param {number} g - The green color component, in the range 0 - 255. - * @param {number} b - The blue color component, in the range 0 - 255. - * @returns {number} A native color value integer (format: 0xAARRGGBB). - */ + * Given an alpha and 3 color values this will return an integer representation of it. + * + * @method Phaser.Color.getColor32 + * @static + * @param {number} a - The alpha color component, in the range 0 - 255. + * @param {number} r - The red color component, in the range 0 - 255. + * @param {number} g - The green color component, in the range 0 - 255. + * @param {number} b - The blue color component, in the range 0 - 255. + * @returns {number} A native color value integer (format: 0xAARRGGBB). + */ getColor32: function (a, r, g, b) { - return a << 24 | r << 16 | g << 8 | b; - }, /** - * Given 3 color values this will return an integer representation of it. - * - * @method Phaser.Color.getColor - * @static - * @param {number} r - The red color component, in the range 0 - 255. - * @param {number} g - The green color component, in the range 0 - 255. - * @param {number} b - The blue color component, in the range 0 - 255. - * @returns {number} A native color value integer (format: 0xRRGGBB). - */ + * Given 3 color values this will return an integer representation of it. + * + * @method Phaser.Color.getColor + * @static + * @param {number} r - The red color component, in the range 0 - 255. + * @param {number} g - The green color component, in the range 0 - 255. + * @param {number} b - The blue color component, in the range 0 - 255. + * @returns {number} A native color value integer (format: 0xRRGGBB). + */ getColor: function (r, g, b) { - return r << 16 | g << 8 | b; - } }; diff --git a/src/stubs/Create.js b/src/stubs/Create.js index 259a8152f..c65c4dc55 100644 --- a/src/stubs/Create.js +++ b/src/stubs/Create.js @@ -1,7 +1,7 @@ /** -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ Phaser.Create = function () {}; diff --git a/src/stubs/DOM.js b/src/stubs/DOM.js index 51779c10b..cd7c77469 100644 --- a/src/stubs/DOM.js +++ b/src/stubs/DOM.js @@ -1,35 +1,34 @@ /** -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* DOM utility class. -* -* Provides a useful Window and Element functions as well as cross-browser compatibility buffer. -* -* Some code originally derived from {@link https://github.com/ryanve/verge verge}. -* Some parts were inspired by the research of Ryan Van Etten, released under MIT License 2013. -* -* @class Phaser.DOM -* @static -*/ + * DOM utility class. + * + * Provides a useful Window and Element functions as well as cross-browser compatibility buffer. + * + * Some code originally derived from {@link https://github.com/ryanve/verge verge}. + * Some parts were inspired by the research of Ryan Van Etten, released under MIT License 2013. + * + * @class Phaser.DOM + * @static + */ Phaser.DOM = { /** - * Get the [absolute] position of the element relative to the Document. - * - * The value may vary slightly as the page is scrolled due to rounding errors. - * - * @method Phaser.DOM.getOffset - * @param {DOMElement} element - The targeted element that we want to retrieve the offset. - * @param {Phaser.Point} [point] - The point we want to take the x/y values of the offset. - * @return {Phaser.Point} - A point objet with the offsetX and Y as its properties. - */ + * Get the [absolute] position of the element relative to the Document. + * + * The value may vary slightly as the page is scrolled due to rounding errors. + * + * @method Phaser.DOM.getOffset + * @param {DOMElement} element - The targeted element that we want to retrieve the offset. + * @param {Phaser.Point} [point] - The point we want to take the x/y values of the offset. + * @return {Phaser.Point} - A point objet with the offsetX and Y as its properties. + */ getOffset: function (element, point) { - point = point || new Phaser.Point(); var box = element.getBoundingClientRect(); @@ -43,14 +42,12 @@ Phaser.DOM = { point.y = box.top + scrollTop - clientTop; return point; - } }; Phaser.Device.whenReady(function () { - // All target browsers should support page[XY]Offset. var scrollX = window && ('pageXOffset' in window) ? function () { return window.pageXOffset; } : @@ -61,23 +58,22 @@ Phaser.Device.whenReady(function () function () { return document.documentElement.scrollTop; }; /** - * A cross-browser window.scrollX. - * - * @name Phaser.DOM.scrollX - * @property {number} scrollX - * @readonly - * @protected - */ + * A cross-browser window.scrollX. + * + * @name Phaser.DOM.scrollX + * @property {number} scrollX + * @readonly + * @protected + */ Object.defineProperty(Phaser.DOM, 'scrollX', {get: scrollX}); /** - * A cross-browser window.scrollY. - * - * @name Phaser.DOM.scrollY - * @property {number} scrollY - * @readonly - * @protected - */ + * A cross-browser window.scrollY. + * + * @name Phaser.DOM.scrollY + * @property {number} scrollY + * @readonly + * @protected + */ Object.defineProperty(Phaser.DOM, 'scrollY', {get: scrollY}); - }, null, true); diff --git a/src/stubs/Debug.js b/src/stubs/Debug.js index 71d013d05..9232280c8 100644 --- a/src/stubs/Debug.js +++ b/src/stubs/Debug.js @@ -1,17 +1,17 @@ /** -* @author Steven Rogers -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Steven Rogers + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* This is a stub for the Phaser Debug Class. -* It allows you to exclude the default Debug from your build, without making Game crash. -*/ + * This is a stub for the Phaser Debug Class. + * It allows you to exclude the default Debug from your build, without making Game crash. + */ /** -* No-operation for Phaser Debug stub. -*/ + * No-operation for Phaser Debug stub. + */ var debugNoop = function () {}; Phaser.Utils.Debug = debugNoop; diff --git a/src/stubs/Net.js b/src/stubs/Net.js index 2e2237216..6d5ff89db 100644 --- a/src/stubs/Net.js +++ b/src/stubs/Net.js @@ -1,17 +1,17 @@ /** -* @author Steven Rogers -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Steven Rogers + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* This is a stub for the Phaser Net Class. -* It allows you to exclude the default Net from your build, without making Game crash. -*/ + * This is a stub for the Phaser Net Class. + * It allows you to exclude the default Net from your build, without making Game crash. + */ /** -* No-operation for Phaser Net stub. -*/ + * No-operation for Phaser Net stub. + */ var netNoop = function () {}; Phaser.Net = netNoop; diff --git a/src/stubs/ScaleManager.js b/src/stubs/ScaleManager.js index 0630d8fe7..a33661004 100644 --- a/src/stubs/ScaleManager.js +++ b/src/stubs/ScaleManager.js @@ -1,24 +1,22 @@ /** -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* This is a stub for the Phaser ScaleManager. -* It allows you to exclude the default Scale Manager from your build, without making Game crash. -*/ + * This is a stub for the Phaser ScaleManager. + * It allows you to exclude the default Scale Manager from your build, without making Game crash. + */ Phaser.ScaleManager = function () { - /** - * The bounds of the scaled game. The x/y will match the offset of the canvas element and the width/height the scaled width and height. - * @property {Phaser.Rectangle} bounds - * @readonly - */ + * The bounds of the scaled game. The x/y will match the offset of the canvas element and the width/height the scaled width and height. + * @property {Phaser.Rectangle} bounds + * @readonly + */ this.bounds = new Phaser.Rectangle(); - }; Phaser.ScaleManager.prototype.boot = function () {}; diff --git a/src/stubs/SoundManager.js b/src/stubs/SoundManager.js index 7c5820656..ae5c9c9f2 100644 --- a/src/stubs/SoundManager.js +++ b/src/stubs/SoundManager.js @@ -1,13 +1,13 @@ /** -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* This is a stub for the Phaser SoundManager. -* It allows you to exclude the default Sound Manager from your build, without making Game crash. -*/ + * This is a stub for the Phaser SoundManager. + * It allows you to exclude the default Sound Manager from your build, without making Game crash. + */ Phaser.SoundManager = function () { diff --git a/src/stubs/TweenManager.js b/src/stubs/TweenManager.js index 36e6163f0..d27613a73 100644 --- a/src/stubs/TweenManager.js +++ b/src/stubs/TweenManager.js @@ -1,13 +1,13 @@ /** -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* This is a stub for the Phaser TweenManager. -* It allows you to exclude the default Tween Manager from your build, without making Game crash. -*/ + * This is a stub for the Phaser TweenManager. + * It allows you to exclude the default Tween Manager from your build, without making Game crash. + */ Phaser.TweenManager = function () {}; diff --git a/src/tilemap/ImageCollection.js b/src/tilemap/ImageCollection.js index 31f0659e3..ad178ba66 100644 --- a/src/tilemap/ImageCollection.js +++ b/src/tilemap/ImageCollection.js @@ -1,95 +1,94 @@ /** -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* An Image Collection is a special tileset containing mulitple images, with no slicing into each image. -* -* Image Collections are normally created automatically when Tiled data is loaded. -* -* @class Phaser.ImageCollection -* @constructor -* @param {string} name - The name of the image collection in the map data. -* @param {integer} firstgid - The first image index this image collection contains. -* @param {integer} [width=32] - Width of widest image (in pixels). -* @param {integer} [height=32] - Height of tallest image (in pixels). -* @param {integer} [margin=0] - The margin around all images in the collection (in pixels). -* @param {integer} [spacing=0] - The spacing between each image in the collection (in pixels). -* @param {object} [properties={}] - Custom Image Collection properties. -*/ + * An Image Collection is a special tileset containing mulitple images, with no slicing into each image. + * + * Image Collections are normally created automatically when Tiled data is loaded. + * + * @class Phaser.ImageCollection + * @constructor + * @param {string} name - The name of the image collection in the map data. + * @param {integer} firstgid - The first image index this image collection contains. + * @param {integer} [width=32] - Width of widest image (in pixels). + * @param {integer} [height=32] - Height of tallest image (in pixels). + * @param {integer} [margin=0] - The margin around all images in the collection (in pixels). + * @param {integer} [spacing=0] - The spacing between each image in the collection (in pixels). + * @param {object} [properties={}] - Custom Image Collection properties. + */ Phaser.ImageCollection = function (name, firstgid, width, height, margin, spacing, properties) { - if (width === undefined || width <= 0) { width = 32; } if (height === undefined || height <= 0) { height = 32; } if (margin === undefined) { margin = 0; } if (spacing === undefined) { spacing = 0; } /** - * The name of the Image Collection. - * @property {string} name - */ + * The name of the Image Collection. + * @property {string} name + */ this.name = name; /** - * The Tiled firstgid value. - * This is the starting index of the first image index this Image Collection contains. - * @property {integer} firstgid - */ + * The Tiled firstgid value. + * This is the starting index of the first image index this Image Collection contains. + * @property {integer} firstgid + */ this.firstgid = firstgid | 0; /** - * The width of the widest image (in pixels). - * @property {integer} imageWidth - * @readonly - */ + * The width of the widest image (in pixels). + * @property {integer} imageWidth + * @readonly + */ this.imageWidth = width | 0; /** - * The height of the tallest image (in pixels). - * @property {integer} imageHeight - * @readonly - */ + * The height of the tallest image (in pixels). + * @property {integer} imageHeight + * @readonly + */ this.imageHeight = height | 0; /** - * The margin around the images in the collection (in pixels). - * Use `setSpacing` to change. - * @property {integer} imageMarge - * @readonly - */ + * The margin around the images in the collection (in pixels). + * Use `setSpacing` to change. + * @property {integer} imageMarge + * @readonly + */ // Modified internally this.imageMargin = margin | 0; /** - * The spacing between each image in the collection (in pixels). - * Use `setSpacing` to change. - * @property {integer} imageSpacing - * @readonly - */ + * The spacing between each image in the collection (in pixels). + * Use `setSpacing` to change. + * @property {integer} imageSpacing + * @readonly + */ this.imageSpacing = spacing | 0; /** - * Image Collection-specific properties that are typically defined in the Tiled editor. - * @property {object} properties - */ + * Image Collection-specific properties that are typically defined in the Tiled editor. + * @property {object} properties + */ this.properties = properties || {}; /** - * The cached images that are a part of this collection. - * @property {array} images - * @readonly - */ + * The cached images that are a part of this collection. + * @property {array} images + * @readonly + */ // Modified internally this.images = []; /** - * The total number of images in the image collection. - * @property {integer} total - * @readonly - */ + * The total number of images in the image collection. + * @property {integer} total + * @readonly + */ // Modified internally this.total = 0; }; @@ -97,35 +96,31 @@ Phaser.ImageCollection = function (name, firstgid, width, height, margin, spacin Phaser.ImageCollection.prototype = { /** - * Returns true if and only if this image collection contains the given image index. - * - * @method Phaser.ImageCollection#containsImageIndex - * @param {integer} imageIndex - The image index to search for. - * @return {boolean} True if this Image Collection contains the given index. - */ + * Returns true if and only if this image collection contains the given image index. + * + * @method Phaser.ImageCollection#containsImageIndex + * @param {integer} imageIndex - The image index to search for. + * @return {boolean} True if this Image Collection contains the given index. + */ containsImageIndex: function (imageIndex) { - return ( imageIndex >= this.firstgid && imageIndex < (this.firstgid + this.total) ); - }, /** - * Add an image to this Image Collection. - * - * @method Phaser.ImageCollection#addImage - * @param {integer} gid - The gid of the image in the Image Collection. - * @param {string} image - The the key of the image in the Image Collection and in the cache. - */ + * Add an image to this Image Collection. + * + * @method Phaser.ImageCollection#addImage + * @param {integer} gid - The gid of the image in the Image Collection. + * @param {string} image - The the key of the image in the Image Collection and in the cache. + */ addImage: function (gid, image) { - this.images.push({ gid: gid, image: image }); this.total++; - } }; diff --git a/src/tilemap/Tile.js b/src/tilemap/Tile.js index 80f25fddc..c6402fce0 100644 --- a/src/tilemap/Tile.js +++ b/src/tilemap/Tile.js @@ -1,192 +1,187 @@ /** -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* A Tile is a representation of a single tile within the Tilemap. -* -* @class Phaser.Tile -* @constructor -* @param {object} layer - The layer in the Tilemap data that this tile belongs to. -* @param {number} index - The index of this tile type in the core map data. -* @param {number} x - The x coordinate of this tile. -* @param {number} y - The y coordinate of this tile. -* @param {number} width - Width of the tile. -* @param {number} height - Height of the tile. -*/ + * A Tile is a representation of a single tile within the Tilemap. + * + * @class Phaser.Tile + * @constructor + * @param {object} layer - The layer in the Tilemap data that this tile belongs to. + * @param {number} index - The index of this tile type in the core map data. + * @param {number} x - The x coordinate of this tile. + * @param {number} y - The y coordinate of this tile. + * @param {number} width - Width of the tile. + * @param {number} height - Height of the tile. + */ Phaser.Tile = function (layer, index, x, y, width, height) { - /** - * @property {object} layer - The layer in the Tilemap data that this tile belongs to. - */ + * @property {object} layer - The layer in the Tilemap data that this tile belongs to. + */ this.layer = layer; /** - * @property {number} index - The index of this tile within the map data corresponding to the tileset, or -1 if this represents a blank/null tile. - */ + * @property {number} index - The index of this tile within the map data corresponding to the tileset, or -1 if this represents a blank/null tile. + */ this.index = index; /** - * @property {number} x - The x map coordinate of this tile. - */ + * @property {number} x - The x map coordinate of this tile. + */ this.x = x; /** - * @property {number} y - The y map coordinate of this tile. - */ + * @property {number} y - The y map coordinate of this tile. + */ this.y = y; /** - * @property {number} rotation - The rotation angle of this tile. - */ + * @property {number} rotation - The rotation angle of this tile. + */ this.rotation = 0; /** - * @property {boolean} flipped - Whether this tile is flipped (mirrored) or not. - */ + * @property {boolean} flipped - Whether this tile is flipped (mirrored) or not. + */ this.flipped = false; /** - * @property {number} x - The x map coordinate of this tile. - */ + * @property {number} x - The x map coordinate of this tile. + */ this.worldX = x * width; /** - * @property {number} y - The y map coordinate of this tile. - */ + * @property {number} y - The y map coordinate of this tile. + */ this.worldY = y * height; /** - * @property {number} width - The width of the tile in pixels. - */ + * @property {number} width - The width of the tile in pixels. + */ this.width = width; /** - * @property {number} height - The height of the tile in pixels. - */ + * @property {number} height - The height of the tile in pixels. + */ this.height = height; /** - * @property {number} width - The width of the tile in pixels. - */ + * @property {number} width - The width of the tile in pixels. + */ this.centerX = Math.abs(width / 2); /** - * @property {number} height - The height of the tile in pixels. - */ + * @property {number} height - The height of the tile in pixels. + */ this.centerY = Math.abs(height / 2); /** - * @property {number} alpha - The alpha value at which this tile is drawn to the canvas. - */ + * @property {number} alpha - The alpha value at which this tile is drawn to the canvas. + */ this.alpha = 1; /** - * @property {object} properties - Tile specific properties. - */ + * @property {object} properties - Tile specific properties. + */ this.properties = {}; /** - * @property {boolean} scanned - Has this tile been walked / turned into a poly? - */ + * @property {boolean} scanned - Has this tile been walked / turned into a poly? + */ this.scanned = false; /** - * @property {boolean} faceTop - Is the top of this tile an interesting edge? - */ + * @property {boolean} faceTop - Is the top of this tile an interesting edge? + */ this.faceTop = false; /** - * @property {boolean} faceBottom - Is the bottom of this tile an interesting edge? - */ + * @property {boolean} faceBottom - Is the bottom of this tile an interesting edge? + */ this.faceBottom = false; /** - * @property {boolean} faceLeft - Is the left of this tile an interesting edge? - */ + * @property {boolean} faceLeft - Is the left of this tile an interesting edge? + */ this.faceLeft = false; /** - * @property {boolean} faceRight - Is the right of this tile an interesting edge? - */ + * @property {boolean} faceRight - Is the right of this tile an interesting edge? + */ this.faceRight = false; /** - * @property {boolean} collideLeft - Indicating collide with any object on the left. - * @default - */ + * @property {boolean} collideLeft - Indicating collide with any object on the left. + * @default + */ this.collideLeft = false; /** - * @property {boolean} collideRight - Indicating collide with any object on the right. - * @default - */ + * @property {boolean} collideRight - Indicating collide with any object on the right. + * @default + */ this.collideRight = false; /** - * @property {boolean} collideUp - Indicating collide with any object on the top. - * @default - */ + * @property {boolean} collideUp - Indicating collide with any object on the top. + * @default + */ this.collideUp = false; /** - * @property {boolean} collideDown - Indicating collide with any object on the bottom. - * @default - */ + * @property {boolean} collideDown - Indicating collide with any object on the bottom. + * @default + */ this.collideDown = false; /** - * @property {function} collisionCallback - Tile collision callback. - * @default - */ + * @property {function} collisionCallback - Tile collision callback. + * @default + */ this.collisionCallback = null; /** - * @property {object} collisionCallbackContext - The context in which the collision callback will be called. - * @default - */ + * @property {object} collisionCallbackContext - The context in which the collision callback will be called. + * @default + */ this.collisionCallbackContext = this; /** - * @property {boolean} debug - * @default - */ + * @property {boolean} debug + * @default + */ this.debug = false; - }; Phaser.Tile.prototype = { /** - * Check if the given x and y world coordinates are within this Tile. - * - * @method Phaser.Tile#containsPoint - * @param {number} x - The x coordinate to test. - * @param {number} y - The y coordinate to test. - * @return {boolean} True if the coordinates are within this Tile, otherwise false. - */ + * Check if the given x and y world coordinates are within this Tile. + * + * @method Phaser.Tile#containsPoint + * @param {number} x - The x coordinate to test. + * @param {number} y - The y coordinate to test. + * @return {boolean} True if the coordinates are within this Tile, otherwise false. + */ containsPoint: function (x, y) { - return !(x < this.worldX || y < this.worldY || x > this.right || y > this.bottom); - }, /** - * Check for intersection with this tile. - * - * @method Phaser.Tile#intersects - * @param {number} x - The x axis in pixels. - * @param {number} y - The y axis in pixels. - * @param {number} right - The right point. - * @param {number} bottom - The bottom point. - */ + * Check for intersection with this tile. + * + * @method Phaser.Tile#intersects + * @param {number} x - The x axis in pixels. + * @param {number} y - The y axis in pixels. + * @param {number} right - The right point. + * @param {number} bottom - The bottom point. + */ intersects: function (x, y, right, bottom) { - if (right <= this.worldX) { return false; @@ -208,51 +203,45 @@ Phaser.Tile.prototype = { } return true; - }, /** - * Set a callback to be called when this tile is hit by an object. - * The callback must true true for collision processing to take place. - * - * @method Phaser.Tile#setCollisionCallback - * @param {function} callback - Callback function. - * @param {object} context - Callback will be called within this context. - */ + * Set a callback to be called when this tile is hit by an object. + * The callback must true true for collision processing to take place. + * + * @method Phaser.Tile#setCollisionCallback + * @param {function} callback - Callback function. + * @param {object} context - Callback will be called within this context. + */ setCollisionCallback: function (callback, context) { - this.collisionCallback = callback; this.collisionCallbackContext = context; - }, /** - * Clean up memory. - * - * @method Phaser.Tile#destroy - */ + * Clean up memory. + * + * @method Phaser.Tile#destroy + */ destroy: function () { - this.collisionCallback = null; this.collisionCallbackContext = null; this.properties = null; - }, /** - * Sets the collision flags for each side of this tile and updates the interesting faces list. - * - * @method Phaser.Tile#setCollision - * @param {boolean} left - Indicating collide with any object on the left. - * @param {boolean} right - Indicating collide with any object on the right. - * @param {boolean} up - Indicating collide with any object on the top. - * @param {boolean} down - Indicating collide with any object on the bottom. - */ + * Sets the collision flags for each side of this tile and updates the interesting faces list. + * + * @method Phaser.Tile#setCollision + * @param {boolean} left - Indicating collide with any object on the left. + * @param {boolean} right - Indicating collide with any object on the right. + * @param {boolean} up - Indicating collide with any object on the top. + * @param {boolean} down - Indicating collide with any object on the bottom. + */ setCollision: function (left, right, up, down) { - this.collideLeft = left; this.collideRight = right; this.collideUp = up; @@ -262,17 +251,15 @@ Phaser.Tile.prototype = { this.faceRight = right; this.faceTop = up; this.faceBottom = down; - }, /** - * Reset collision status flags. - * - * @method Phaser.Tile#resetCollision - */ + * Reset collision status flags. + * + * @method Phaser.Tile#resetCollision + */ resetCollision: function () { - this.collideLeft = false; this.collideRight = false; this.collideUp = false; @@ -282,20 +269,18 @@ Phaser.Tile.prototype = { this.faceBottom = false; this.faceLeft = false; this.faceRight = false; - }, /** - * Is this tile interesting? - * - * @method Phaser.Tile#isInteresting - * @param {boolean} collides - If true will check any collides value. - * @param {boolean} faces - If true will check any face value. - * @return {boolean} True if the Tile is interesting, otherwise false. - */ + * Is this tile interesting? + * + * @method Phaser.Tile#isInteresting + * @param {boolean} collides - If true will check any collides value. + * @param {boolean} faces - If true will check any face value. + * @return {boolean} True if the Tile is interesting, otherwise false. + */ isInteresting: function (collides, faces) { - if (collides && faces) { // Does this tile have any collide flags OR interesting face? @@ -313,18 +298,16 @@ Phaser.Tile.prototype = { } return false; - }, /** - * Copies the tile data and properties from the given tile to this tile. - * - * @method Phaser.Tile#copy - * @param {Phaser.Tile} tile - The tile to copy from. - */ + * Copies the tile data and properties from the given tile to this tile. + * + * @method Phaser.Tile#copy + * @param {Phaser.Tile} tile - The tile to copy from. + */ copy: function (tile) { - this.index = tile.index; this.alpha = tile.alpha; this.properties = tile.properties; @@ -336,7 +319,6 @@ Phaser.Tile.prototype = { this.collisionCallback = tile.collisionCallback; this.collisionCallbackContext = tile.collisionCallbackContext; - } }; @@ -344,10 +326,10 @@ Phaser.Tile.prototype = { Phaser.Tile.prototype.constructor = Phaser.Tile; /** -* @name Phaser.Tile#collides -* @property {boolean} collides - True if this tile can collide on any of its faces. -* @readonly -*/ + * @name Phaser.Tile#collides + * @property {boolean} collides - True if this tile can collide on any of its faces. + * @readonly + */ Object.defineProperty(Phaser.Tile.prototype, 'collides', { get: function () @@ -358,10 +340,10 @@ Object.defineProperty(Phaser.Tile.prototype, 'collides', { }); /** -* @name Phaser.Tile#canCollide -* @property {boolean} canCollide - True if this tile can collide on any of its faces or has a collision callback set. -* @readonly -*/ + * @name Phaser.Tile#canCollide + * @property {boolean} canCollide - True if this tile can collide on any of its faces or has a collision callback set. + * @readonly + */ Object.defineProperty(Phaser.Tile.prototype, 'canCollide', { get: function () @@ -372,10 +354,10 @@ Object.defineProperty(Phaser.Tile.prototype, 'canCollide', { }); /** -* @name Phaser.Tile#left -* @property {number} left - The x value in pixels. -* @readonly -*/ + * @name Phaser.Tile#left + * @property {number} left - The x value in pixels. + * @readonly + */ Object.defineProperty(Phaser.Tile.prototype, 'left', { get: function () @@ -386,10 +368,10 @@ Object.defineProperty(Phaser.Tile.prototype, 'left', { }); /** -* @name Phaser.Tile#right -* @property {number} right - The sum of the x and width properties. -* @readonly -*/ + * @name Phaser.Tile#right + * @property {number} right - The sum of the x and width properties. + * @readonly + */ Object.defineProperty(Phaser.Tile.prototype, 'right', { get: function () @@ -400,10 +382,10 @@ Object.defineProperty(Phaser.Tile.prototype, 'right', { }); /** -* @name Phaser.Tile#top -* @property {number} top - The y value. -* @readonly -*/ + * @name Phaser.Tile#top + * @property {number} top - The y value. + * @readonly + */ Object.defineProperty(Phaser.Tile.prototype, 'top', { get: function () @@ -414,10 +396,10 @@ Object.defineProperty(Phaser.Tile.prototype, 'top', { }); /** -* @name Phaser.Tile#bottom -* @property {number} bottom - The sum of the y and height properties. -* @readonly -*/ + * @name Phaser.Tile#bottom + * @property {number} bottom - The sum of the y and height properties. + * @readonly + */ Object.defineProperty(Phaser.Tile.prototype, 'bottom', { get: function () diff --git a/src/tilemap/Tilemap.js b/src/tilemap/Tilemap.js index 5eb7e955c..cae34ff02 100644 --- a/src/tilemap/Tilemap.js +++ b/src/tilemap/Tilemap.js @@ -1,41 +1,40 @@ /** -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* Creates a new Phaser.Tilemap object. The map can either be populated with data from a Tiled JSON file or from a CSV file. -* -* Tiled is a free software package specifically for creating tile maps, and is available from http://www.mapeditor.org -* -* To do this pass the Cache key as the first parameter. When using Tiled data you need only provide the key. -* When using CSV data you must provide the key and the tileWidth and tileHeight parameters. -* If creating a blank tilemap to be populated later, you can either specify no parameters at all and then use `Tilemap.create` or pass the map and tile dimensions here. -* Note that all Tilemaps use a base tile size to calculate dimensions from, but that a TilemapLayer may have its own unique tile size that overrides it. -* A Tile map is rendered to the display using a TilemapLayer. It is not added to the display list directly itself. -* A map may have multiple layers. You can perform operations on the map data such as copying, pasting, filling and shuffling the tiles around. -* -* @class Phaser.Tilemap -* @constructor -* @param {Phaser.Game} game - Game reference to the currently running game. -* @param {string} [key] - The key of the tilemap data as stored in the Cache. If you're creating a blank map either leave this parameter out or pass `null`. -* @param {number} [tileWidth=32] - The pixel width of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data. -* @param {number} [tileHeight=32] - The pixel height of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data. -* @param {number} [width=10] - The width of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this. -* @param {number} [height=10] - The height of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this. -*/ + * Creates a new Phaser.Tilemap object. The map can either be populated with data from a Tiled JSON file or from a CSV file. + * + * Tiled is a free software package specifically for creating tile maps, and is available from http://www.mapeditor.org + * + * To do this pass the Cache key as the first parameter. When using Tiled data you need only provide the key. + * When using CSV data you must provide the key and the tileWidth and tileHeight parameters. + * If creating a blank tilemap to be populated later, you can either specify no parameters at all and then use `Tilemap.create` or pass the map and tile dimensions here. + * Note that all Tilemaps use a base tile size to calculate dimensions from, but that a TilemapLayer may have its own unique tile size that overrides it. + * A Tile map is rendered to the display using a TilemapLayer. It is not added to the display list directly itself. + * A map may have multiple layers. You can perform operations on the map data such as copying, pasting, filling and shuffling the tiles around. + * + * @class Phaser.Tilemap + * @constructor + * @param {Phaser.Game} game - Game reference to the currently running game. + * @param {string} [key] - The key of the tilemap data as stored in the Cache. If you're creating a blank map either leave this parameter out or pass `null`. + * @param {number} [tileWidth=32] - The pixel width of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data. + * @param {number} [tileHeight=32] - The pixel height of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data. + * @param {number} [width=10] - The width of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this. + * @param {number} [height=10] - The height of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this. + */ Phaser.Tilemap = function (game, key, tileWidth, tileHeight, width, height) { - /** - * @property {Phaser.Game} game - A reference to the currently running Game. - */ + * @property {Phaser.Game} game - A reference to the currently running Game. + */ this.game = game; /** - * @property {string} key - The key of this map data in the Phaser.Cache. - */ + * @property {string} key - The key of this map data in the Phaser.Cache. + */ this.key = key; var data = Phaser.TilemapParser.parse(this.game, key, tileWidth, tileHeight, width, height); @@ -46,183 +45,181 @@ Phaser.Tilemap = function (game, key, tileWidth, tileHeight, width, height) } /** - * @property {number} width - The width of the map (in tiles). - */ + * @property {number} width - The width of the map (in tiles). + */ this.width = data.width; /** - * @property {number} height - The height of the map (in tiles). - */ + * @property {number} height - The height of the map (in tiles). + */ this.height = data.height; /** - * @property {number} tileWidth - The base width of the tiles in the map (in pixels). - */ + * @property {number} tileWidth - The base width of the tiles in the map (in pixels). + */ this.tileWidth = data.tileWidth; /** - * @property {number} tileHeight - The base height of the tiles in the map (in pixels). - */ + * @property {number} tileHeight - The base height of the tiles in the map (in pixels). + */ this.tileHeight = data.tileHeight; /** - * @property {string} orientation - The orientation of the map data (as specified in Tiled), usually 'orthogonal'. - */ + * @property {string} orientation - The orientation of the map data (as specified in Tiled), usually 'orthogonal'. + */ this.orientation = data.orientation; /** - * @property {number} format - The format of the map data, either Phaser.Tilemap.CSV or Phaser.Tilemap.TILED_JSON. - */ + * @property {number} format - The format of the map data, either Phaser.Tilemap.CSV or Phaser.Tilemap.TILED_JSON. + */ this.format = data.format; /** - * @property {number} version - The version of the map data (as specified in Tiled, usually 1). - */ + * @property {number} version - The version of the map data (as specified in Tiled, usually 1). + */ this.version = data.version; /** - * @property {object} properties - Map specific properties as specified in Tiled. - */ + * @property {object} properties - Map specific properties as specified in Tiled. + */ this.properties = data.properties; /** - * @property {number} widthInPixels - The width of the map in pixels based on width * tileWidth. - */ + * @property {number} widthInPixels - The width of the map in pixels based on width * tileWidth. + */ this.widthInPixels = data.widthInPixels; /** - * @property {number} heightInPixels - The height of the map in pixels based on height * tileHeight. - */ + * @property {number} heightInPixels - The height of the map in pixels based on height * tileHeight. + */ this.heightInPixels = data.heightInPixels; /** - * @property {array} layers - An array of Tilemap layer data. - */ + * @property {array} layers - An array of Tilemap layer data. + */ this.layers = data.layers; /** - * @property {array} tilesets - An array of Tilesets. - */ + * @property {array} tilesets - An array of Tilesets. + */ this.tilesets = data.tilesets; /** - * @property {array} imagecollections - An array of Image Collections. - */ + * @property {array} imagecollections - An array of Image Collections. + */ this.imagecollections = data.imagecollections; /** - * @property {array} tiles - The super array of Tiles. - */ + * @property {array} tiles - The super array of Tiles. + */ this.tiles = data.tiles; /** - * @property {array} objects - An array of Tiled Object Layers. - */ + * @property {array} objects - An array of Tiled Object Layers. + */ this.objects = data.objects; /** - * @property {array} collideIndexes - An array of tile indexes that collide. - */ + * @property {array} collideIndexes - An array of tile indexes that collide. + */ this.collideIndexes = []; /** - * @property {array} collision - An array of collision data (polylines, etc). - */ + * @property {array} collision - An array of collision data (polylines, etc). + */ this.collision = data.collision; /** - * @property {array} images - An array of Tiled Image Layers. - */ + * @property {array} images - An array of Tiled Image Layers. + */ this.images = data.images; /** - * @property {boolean} enableDebug - If set then console.log is used to dump out useful layer creation debug data. - */ + * @property {boolean} enableDebug - If set then console.log is used to dump out useful layer creation debug data. + */ this.enableDebug = false; /** - * @property {number} currentLayer - The current layer. - */ + * @property {number} currentLayer - The current layer. + */ this.currentLayer = 0; /** - * @property {array} debugMap - Map data used for debug values only. - */ + * @property {array} debugMap - Map data used for debug values only. + */ this.debugMap = []; /** - * @property {array} _results - Internal var. - * @private - */ + * @property {array} _results - Internal var. + * @private + */ this._results = []; /** - * @property {number} _tempA - Internal var. - * @private - */ + * @property {number} _tempA - Internal var. + * @private + */ this._tempA = 0; /** - * @property {number} _tempB - Internal var. - * @private - */ + * @property {number} _tempB - Internal var. + * @private + */ this._tempB = 0; - }; /** -* @constant -* @type {number} -*/ + * @constant + * @type {number} + */ Phaser.Tilemap.CSV = 0; /** -* @constant -* @type {number} -*/ + * @constant + * @type {number} + */ Phaser.Tilemap.TILED_JSON = 1; /** -* @constant -* @type {number} -*/ + * @constant + * @type {number} + */ Phaser.Tilemap.NORTH = 0; /** -* @constant -* @type {number} -*/ + * @constant + * @type {number} + */ Phaser.Tilemap.EAST = 1; /** -* @constant -* @type {number} -*/ + * @constant + * @type {number} + */ Phaser.Tilemap.SOUTH = 2; /** -* @constant -* @type {number} -*/ + * @constant + * @type {number} + */ Phaser.Tilemap.WEST = 3; Phaser.Tilemap.prototype = { /** - * Creates an empty map of the given dimensions and one blank layer. If layers already exist they are erased. - * - * @method Phaser.Tilemap#create - * @param {string} name - The name of the default layer of the map. - * @param {number} width - The width of the map in tiles. - * @param {number} height - The height of the map in tiles. - * @param {number} tileWidth - The width of the tiles the map uses for calculations. - * @param {number} tileHeight - The height of the tiles the map uses for calculations. - * @param {Phaser.Group} [group] - Optional Group to add the layer to. If not specified it will be added to the World group. - * @return {Phaser.TilemapLayer} The TilemapLayer object. This is an extension of Phaser.Image and can be moved around the display list accordingly. - */ + * Creates an empty map of the given dimensions and one blank layer. If layers already exist they are erased. + * + * @method Phaser.Tilemap#create + * @param {string} name - The name of the default layer of the map. + * @param {number} width - The width of the map in tiles. + * @param {number} height - The height of the map in tiles. + * @param {number} tileWidth - The width of the tiles the map uses for calculations. + * @param {number} tileHeight - The height of the tiles the map uses for calculations. + * @param {Phaser.Group} [group] - Optional Group to add the layer to. If not specified it will be added to the World group. + * @return {Phaser.TilemapLayer} The TilemapLayer object. This is an extension of Phaser.Image and can be moved around the display list accordingly. + */ create: function (name, width, height, tileWidth, tileHeight, group) { - if (group === undefined) { group = this.game.world; } this.width = width; @@ -233,45 +230,41 @@ Phaser.Tilemap.prototype = { this.layers.length = 0; return this.createBlankLayer(name, width, height, tileWidth, tileHeight, group); - }, /** - * Sets the base tile size for the map. - * - * @method Phaser.Tilemap#setTileSize - * @param {number} tileWidth - The width of the tiles the map uses for calculations. - * @param {number} tileHeight - The height of the tiles the map uses for calculations. - */ + * Sets the base tile size for the map. + * + * @method Phaser.Tilemap#setTileSize + * @param {number} tileWidth - The width of the tiles the map uses for calculations. + * @param {number} tileHeight - The height of the tiles the map uses for calculations. + */ setTileSize: function (tileWidth, tileHeight) { - this.tileWidth = tileWidth; this.tileHeight = tileHeight; this.widthInPixels = this.width * tileWidth; this.heightInPixels = this.height * tileHeight; - }, /** - * Adds an image to the map to be used as a tileset. A single map may use multiple tilesets. - * Note that the tileset name can be found in the JSON file exported from Tiled, or in the Tiled editor. - * - * @method Phaser.Tilemap#addTilesetImage - * @param {string} tileset - The name of the tileset as specified in the map data. - * @param {string|Phaser.BitmapData} [key] - The key of the Phaser.Cache image used for this tileset. - * If `undefined` or `null` it will look for an image with a key matching the tileset parameter. - * You can also pass in a BitmapData which can be used instead of an Image. - * @param {number} [tileWidth=32] - The width of the tiles in the Tileset Image. If not given it will default to the map.tileWidth value, if that isn't set then 32. - * @param {number} [tileHeight=32] - The height of the tiles in the Tileset Image. If not given it will default to the map.tileHeight value, if that isn't set then 32. - * @param {number} [tileMargin=0] - The width of the tiles in the Tileset Image. - * @param {number} [tileSpacing=0] - The height of the tiles in the Tileset Image. - * @param {number} [gid=0] - If adding multiple tilesets to a blank/dynamic map, specify the starting GID the set will use here. - * @return {Phaser.Tileset} Returns the Tileset object that was created or updated, or null if it failed. - */ + * Adds an image to the map to be used as a tileset. A single map may use multiple tilesets. + * Note that the tileset name can be found in the JSON file exported from Tiled, or in the Tiled editor. + * + * @method Phaser.Tilemap#addTilesetImage + * @param {string} tileset - The name of the tileset as specified in the map data. + * @param {string|Phaser.BitmapData} [key] - The key of the Phaser.Cache image used for this tileset. + * If `undefined` or `null` it will look for an image with a key matching the tileset parameter. + * You can also pass in a BitmapData which can be used instead of an Image. + * @param {number} [tileWidth=32] - The width of the tiles in the Tileset Image. If not given it will default to the map.tileWidth value, if that isn't set then 32. + * @param {number} [tileHeight=32] - The height of the tiles in the Tileset Image. If not given it will default to the map.tileHeight value, if that isn't set then 32. + * @param {number} [tileMargin=0] - The width of the tiles in the Tileset Image. + * @param {number} [tileSpacing=0] - The height of the tiles in the Tileset Image. + * @param {number} [gid=0] - If adding multiple tilesets to a blank/dynamic map, specify the starting GID the set will use here. + * @return {Phaser.Tileset} Returns the Tileset object that was created or updated, or null if it failed. + */ addTilesetImage: function (tileset, key, tileWidth, tileHeight, tileMargin, tileSpacing, gid) { - if (tileset === undefined) { return null; } if (tileWidth === undefined) { tileWidth = this.tileWidth; } if (tileHeight === undefined) { tileHeight = this.tileHeight; } @@ -373,38 +366,35 @@ Phaser.Tilemap.prototype = { } return newSet; - } - }, /** - * Creates a Sprite for every {@link http://doc.mapeditor.org/reference/tmx-map-format/#object object} matching the `gid` argument. You can optionally specify the group that the Sprite will be created in. If none is - * given it will be created in the World. All properties from the map data objectgroup are copied across to the Sprite, so you can use this as an easy way to - * configure Sprite properties from within the map editor. For example giving an object a property of `alpha: 0.5` in the map editor will duplicate that when the - * Sprite is created. You could also give it a value like: `body.velocity.x: 100` to set it moving automatically. - * - * The `gid` argument is matched against: - * - * 1. For a tile object, the tile identifier (`gid`); or - * 2. The object's unique ID (`id`); or - * 3. The object's `name` (a string) - * - * @method Phaser.Tilemap#createFromObjects - * @param {string} name - The name of the Object Group to create Sprites from. - * @param {number|string} gid - The object's tile reference (gid), unique ID (id) or name. - * @param {string} key - The Game.cache key of the image that this Sprite will use. - * @param {number|string} [frame] - If the Sprite image contains multiple frames you can specify which one to use here. - * @param {boolean} [exists=true] - The default exists state of the Sprite. - * @param {boolean} [autoCull=false] - The default autoCull state of the Sprite. Sprites that are autoCulled are culled from the camera if out of its range. - * @param {Phaser.Group} [group=Phaser.World] - Group to add the Sprite to. If not specified it will be added to the World group. - * @param {object} [CustomClass=Phaser.Sprite] - If you wish to create your own class, rather than Phaser.Sprite, pass the class here. Your class must extend Phaser.Sprite and have the same constructor parameters. - * @param {boolean} [adjustY=true] - By default the Tiled map editor uses a bottom-left coordinate system. Phaser uses top-left. So most objects will appear too low down. This parameter moves them up by their height. - * @param {boolean} [adjustSize=true] - By default the width and height of the objects are transferred to the sprite. This parameter controls that behavior. - */ + * Creates a Sprite for every {@link http://doc.mapeditor.org/reference/tmx-map-format/#object object} matching the `gid` argument. You can optionally specify the group that the Sprite will be created in. If none is + * given it will be created in the World. All properties from the map data objectgroup are copied across to the Sprite, so you can use this as an easy way to + * configure Sprite properties from within the map editor. For example giving an object a property of `alpha: 0.5` in the map editor will duplicate that when the + * Sprite is created. You could also give it a value like: `body.velocity.x: 100` to set it moving automatically. + * + * The `gid` argument is matched against: + * + * 1. For a tile object, the tile identifier (`gid`); or + * 2. The object's unique ID (`id`); or + * 3. The object's `name` (a string) + * + * @method Phaser.Tilemap#createFromObjects + * @param {string} name - The name of the Object Group to create Sprites from. + * @param {number|string} gid - The object's tile reference (gid), unique ID (id) or name. + * @param {string} key - The Game.cache key of the image that this Sprite will use. + * @param {number|string} [frame] - If the Sprite image contains multiple frames you can specify which one to use here. + * @param {boolean} [exists=true] - The default exists state of the Sprite. + * @param {boolean} [autoCull=false] - The default autoCull state of the Sprite. Sprites that are autoCulled are culled from the camera if out of its range. + * @param {Phaser.Group} [group=Phaser.World] - Group to add the Sprite to. If not specified it will be added to the World group. + * @param {object} [CustomClass=Phaser.Sprite] - If you wish to create your own class, rather than Phaser.Sprite, pass the class here. Your class must extend Phaser.Sprite and have the same constructor parameters. + * @param {boolean} [adjustY=true] - By default the Tiled map editor uses a bottom-left coordinate system. Phaser uses top-left. So most objects will appear too low down. This parameter moves them up by their height. + * @param {boolean} [adjustSize=true] - By default the width and height of the objects are transferred to the sprite. This parameter controls that behavior. + */ createFromObjects: function (name, gid, key, frame, exists, autoCull, group, CustomClass, adjustY, adjustSize) { - if (exists === undefined) { exists = true; } if (autoCull === undefined) { autoCull = false; } if (group === undefined) { group = this.game.world; } @@ -477,27 +467,25 @@ Phaser.Tilemap.prototype = { } } } - }, /** - * Creates a Sprite for every object matching the given tile indexes in the map data. - * You can specify the group that the Sprite will be created in. If none is given it will be created in the World. - * You can optional specify if the tile will be replaced with another after the Sprite is created. This is useful if you want to lay down special - * tiles in a level that are converted to Sprites, but want to replace the tile itself with a floor tile or similar once converted. - * - * @method Phaser.Tilemap#createFromTiles - * @param {integer|Array} tiles - The tile index, or array of indexes, to create Sprites from. - * @param {integer|Array} replacements - The tile index, or array of indexes, to change a converted tile to. Set to -1 to remove the tile. Set to `null` to make no change (leave the tile as is). - * @param {string} key - The Game.cache key of the image that this Sprite will use. - * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. - * @param {Phaser.Group} [group=Phaser.World] - Group to add the Sprite to. If not specified it will be added to the World group. - * @param {object} [properties] - An object that contains the default properties for your newly created Sprite. This object will be iterated and any matching Sprite property will be set. - * @return {integer} The number of Sprites that were created. - */ + * Creates a Sprite for every object matching the given tile indexes in the map data. + * You can specify the group that the Sprite will be created in. If none is given it will be created in the World. + * You can optional specify if the tile will be replaced with another after the Sprite is created. This is useful if you want to lay down special + * tiles in a level that are converted to Sprites, but want to replace the tile itself with a floor tile or similar once converted. + * + * @method Phaser.Tilemap#createFromTiles + * @param {integer|Array} tiles - The tile index, or array of indexes, to create Sprites from. + * @param {integer|Array} replacements - The tile index, or array of indexes, to change a converted tile to. Set to -1 to remove the tile. Set to `null` to make no change (leave the tile as is). + * @param {string} key - The Game.cache key of the image that this Sprite will use. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. + * @param {Phaser.Group} [group=Phaser.World] - Group to add the Sprite to. If not specified it will be added to the World group. + * @param {object} [properties] - An object that contains the default properties for your newly created Sprite. This object will be iterated and any matching Sprite property will be set. + * @return {integer} The number of Sprites that were created. + */ createFromTiles: function (tiles, replacements, key, layer, group, properties) { - if (typeof tiles === 'number') { tiles = [ tiles ]; } if (replacements === undefined || replacements === null) @@ -551,7 +539,6 @@ Phaser.Tilemap.prototype = { group.add(sprite); total++; } - } if (replacements.length === 1) @@ -572,25 +559,23 @@ Phaser.Tilemap.prototype = { } return total; - }, /** - * Creates a new TilemapLayer object. By default TilemapLayers are fixed to the camera. - * The `layer` parameter is important. If you've created your map in Tiled then you can get this by looking in Tiled and looking at the Layer name. - * Or you can open the JSON file it exports and look at the layers[].name value. Either way it must match. - * If you wish to create a blank layer to put your own tiles on then see Tilemap.createBlankLayer. - * - * @method Phaser.Tilemap#createLayer - * @param {number|string} layer - The layer array index value, or if a string is given the layer name, within the map data that this TilemapLayer represents. - * @param {number} [width] - The rendered width of the layer, should never be wider than Game.width. If not given it will be set to Game.width. - * @param {number} [height] - The rendered height of the layer, should never be wider than Game.height. If not given it will be set to Game.height. - * @param {Phaser.Group} [group] - Optional Group to add the object to. If not specified it will be added to the World group. - * @return {Phaser.TilemapLayer} The TilemapLayer object. This is an extension of Phaser.Sprite and can be moved around the display list accordingly. - */ + * Creates a new TilemapLayer object. By default TilemapLayers are fixed to the camera. + * The `layer` parameter is important. If you've created your map in Tiled then you can get this by looking in Tiled and looking at the Layer name. + * Or you can open the JSON file it exports and look at the layers[].name value. Either way it must match. + * If you wish to create a blank layer to put your own tiles on then see Tilemap.createBlankLayer. + * + * @method Phaser.Tilemap#createLayer + * @param {number|string} layer - The layer array index value, or if a string is given the layer name, within the map data that this TilemapLayer represents. + * @param {number} [width] - The rendered width of the layer, should never be wider than Game.width. If not given it will be set to Game.width. + * @param {number} [height] - The rendered height of the layer, should never be wider than Game.height. If not given it will be set to Game.height. + * @param {Phaser.Group} [group] - Optional Group to add the object to. If not specified it will be added to the World group. + * @return {Phaser.TilemapLayer} The TilemapLayer object. This is an extension of Phaser.Sprite and can be moved around the display list accordingly. + */ createLayer: function (layer, width, height, group) { - // Add Buffer support for the left of the canvas if (width === undefined) { width = this.game.width; } @@ -647,25 +632,23 @@ Phaser.Tilemap.prototype = { } return rootLayer; - }, /** - * Creates a new and empty layer on this Tilemap. By default TilemapLayers are fixed to the camera. - * - * @method Phaser.Tilemap#createBlankLayer - * @param {string} name - The name of this layer. Must be unique within the map. - * @param {number} width - The width of the layer in tiles. - * @param {number} height - The height of the layer in tiles. - * @param {number} tileWidth - The width of the tiles the layer uses for calculations. - * @param {number} tileHeight - The height of the tiles the layer uses for calculations. - * @param {Phaser.Group} [group] - Optional Group to add the layer to. If not specified it will be added to the World group. - * @return {Phaser.TilemapLayer} The TilemapLayer object. This is an extension of Phaser.Image and can be moved around the display list accordingly. - */ + * Creates a new and empty layer on this Tilemap. By default TilemapLayers are fixed to the camera. + * + * @method Phaser.Tilemap#createBlankLayer + * @param {string} name - The name of this layer. Must be unique within the map. + * @param {number} width - The width of the layer in tiles. + * @param {number} height - The height of the layer in tiles. + * @param {number} tileWidth - The width of the tiles the layer uses for calculations. + * @param {number} tileHeight - The height of the tiles the layer uses for calculations. + * @param {Phaser.Group} [group] - Optional Group to add the layer to. If not specified it will be added to the World group. + * @return {Phaser.TilemapLayer} The TilemapLayer object. This is an extension of Phaser.Image and can be moved around the display list accordingly. + */ createBlankLayer: function (name, width, height, tileWidth, tileHeight, group) { - if (group === undefined) { group = this.game.world; } if (this.getLayerIndex(name) !== null) @@ -731,21 +714,19 @@ Phaser.Tilemap.prototype = { output.name = name; return group.add(output); - }, /** - * Gets the layer index based on the layers name. - * - * @method Phaser.Tilemap#getIndex - * @protected - * @param {array} location - The local array to search. - * @param {string} name - The name of the array element to get. - * @return {number} The index of the element in the array, or null if not found. - */ + * Gets the layer index based on the layers name. + * + * @method Phaser.Tilemap#getIndex + * @protected + * @param {array} location - The local array to search. + * @param {string} name - The name of the array element to get. + * @return {number} The index of the element in the array, or null if not found. + */ getIndex: function (location, name) { - for (var i = 0; i < location.length; i++) { if (location[i].name === name) @@ -755,67 +736,59 @@ Phaser.Tilemap.prototype = { } return null; - }, /** - * Gets the layer index based on its name. - * - * @method Phaser.Tilemap#getLayerIndex - * @param {string} name - The name of the layer to get. - * @return {number} The index of the layer in this tilemap, or null if not found. - */ + * Gets the layer index based on its name. + * + * @method Phaser.Tilemap#getLayerIndex + * @param {string} name - The name of the layer to get. + * @return {number} The index of the layer in this tilemap, or null if not found. + */ getLayerIndex: function (name) { - return this.getIndex(this.layers, name); - }, /** - * Gets the tileset index based on its name. - * - * @method Phaser.Tilemap#getTilesetIndex - * @param {string} name - The name of the tileset to get. - * @return {number} The index of the tileset in this tilemap, or null if not found. - */ + * Gets the tileset index based on its name. + * + * @method Phaser.Tilemap#getTilesetIndex + * @param {string} name - The name of the tileset to get. + * @return {number} The index of the tileset in this tilemap, or null if not found. + */ getTilesetIndex: function (name) { - return this.getIndex(this.tilesets, name); - }, /** - * Gets the image index based on its name. - * - * @method Phaser.Tilemap#getImageIndex - * @param {string} name - The name of the image to get. - * @return {number} The index of the image in this tilemap, or null if not found. - */ + * Gets the image index based on its name. + * + * @method Phaser.Tilemap#getImageIndex + * @param {string} name - The name of the image to get. + * @return {number} The index of the image in this tilemap, or null if not found. + */ getImageIndex: function (name) { - return this.getIndex(this.images, name); - }, /** - * Sets a global collision callback for the given tile index within the layer. This will affect all tiles on this layer that have the same index. - * If a callback is already set for the tile index it will be replaced. Set the callback to null to remove it. - * If you want to set a callback for a tile at a specific location on the map then see setTileLocationCallback. - * - * Return `true` from the callback to continue separating the tile and colliding object, or `false` to cancel the collision for the current tile (see {@link Phaser.Physics.Arcade#separateTile}). - * - * @method Phaser.Tilemap#setTileIndexCallback - * @param {number|array} indexes - Either a single tile index, or an array of tile indexes to have a collision callback set for. - * @param {function} callback - The callback that will be invoked when the tile is collided with (via {@link Phaser.Physics.Arcade#collide}). - * @param {object} callbackContext - The context under which the callback is called. - * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to this.currentLayer. - */ + * Sets a global collision callback for the given tile index within the layer. This will affect all tiles on this layer that have the same index. + * If a callback is already set for the tile index it will be replaced. Set the callback to null to remove it. + * If you want to set a callback for a tile at a specific location on the map then see setTileLocationCallback. + * + * Return `true` from the callback to continue separating the tile and colliding object, or `false` to cancel the collision for the current tile (see {@link Phaser.Physics.Arcade#separateTile}). + * + * @method Phaser.Tilemap#setTileIndexCallback + * @param {number|array} indexes - Either a single tile index, or an array of tile indexes to have a collision callback set for. + * @param {function} callback - The callback that will be invoked when the tile is collided with (via {@link Phaser.Physics.Arcade#collide}). + * @param {object} callbackContext - The context under which the callback is called. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to this.currentLayer. + */ setTileIndexCallback: function (indexes, callback, callbackContext, layer) { - layer = this.getLayer(layer); if (typeof indexes === 'number') @@ -826,8 +799,10 @@ Phaser.Tilemap.prototype = { } else { - // This may seem a bit wasteful, because it will cause empty array elements to be created, but the look-up cost is much - // less than having to iterate through the callbacks array hunting down tile indexes each frame, so I'll take the small memory hit. + /* + * This may seem a bit wasteful, because it will cause empty array elements to be created, but the look-up cost is much + * less than having to iterate through the callbacks array hunting down tile indexes each frame, so I'll take the small memory hit. + */ this.layers[layer].callbacks[indexes] = { callback: callback, callbackContext: callbackContext }; } } @@ -845,28 +820,26 @@ Phaser.Tilemap.prototype = { } } } - }, /** - * Sets a global collision callback for the given map location within the layer. This will affect all tiles on this layer found in the given area. - * If a callback is already set for the tile index it will be replaced. Set the callback to null to remove it. - * If you want to set a callback for a tile at a specific location on the map then see setTileLocationCallback. - * - * Return `true` from the callback to continue separating the tile and colliding object, or `false` to cancel the collision for the current tile (see {@link Phaser.Physics.Arcade#separateTile}). - * - * @method Phaser.Tilemap#setTileLocationCallback - * @param {number} x - X position of the top left of the area to copy (given in tiles, not pixels) - * @param {number} y - Y position of the top left of the area to copy (given in tiles, not pixels) - * @param {number} width - The width of the area to copy (given in tiles, not pixels) - * @param {number} height - The height of the area to copy (given in tiles, not pixels) - * @param {function} callback - The callback that will be invoked when the tile is collided with (via {@link Phaser.Physics.Arcade#collide}). - * @param {object} callbackContext - The context under which the callback is called. - * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to this.currentLayer. - */ + * Sets a global collision callback for the given map location within the layer. This will affect all tiles on this layer found in the given area. + * If a callback is already set for the tile index it will be replaced. Set the callback to null to remove it. + * If you want to set a callback for a tile at a specific location on the map then see setTileLocationCallback. + * + * Return `true` from the callback to continue separating the tile and colliding object, or `false` to cancel the collision for the current tile (see {@link Phaser.Physics.Arcade#separateTile}). + * + * @method Phaser.Tilemap#setTileLocationCallback + * @param {number} x - X position of the top left of the area to copy (given in tiles, not pixels) + * @param {number} y - Y position of the top left of the area to copy (given in tiles, not pixels) + * @param {number} width - The width of the area to copy (given in tiles, not pixels) + * @param {number} height - The height of the area to copy (given in tiles, not pixels) + * @param {function} callback - The callback that will be invoked when the tile is collided with (via {@link Phaser.Physics.Arcade#collide}). + * @param {object} callbackContext - The context under which the callback is called. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to this.currentLayer. + */ setTileLocationCallback: function (x, y, width, height, callback, callbackContext, layer) { - layer = this.getLayer(layer); this.copy(x, y, width, height, layer); @@ -880,26 +853,24 @@ Phaser.Tilemap.prototype = { { this._results[i].setCollisionCallback(callback, callbackContext); } - }, /** - * Sets collision on the given tile or tiles. You can pass in either a single numeric index or an array of indexes: [2, 3, 15, 20]. - * The `collides` parameter controls if collision will be enabled (true) or disabled (false). - * - * Collision-enabled tiles can be collided against Sprites using {@link Phaser.Physics.Arcade#collide}. - * - * You can verify the collision faces by enabling {@link Phaser.TilemapLayer#debug}. - * - * @method Phaser.Tilemap#setCollision - * @param {number|array} indexes - Either a single tile index, or an array of tile IDs to be checked for collision. - * @param {boolean} [collides=true] - If true it will enable collision. If false it will clear collision. - * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to this.currentLayer. - * @param {boolean} [recalculate=true] - Recalculates the tile faces after the update. - */ + * Sets collision on the given tile or tiles. You can pass in either a single numeric index or an array of indexes: [2, 3, 15, 20]. + * The `collides` parameter controls if collision will be enabled (true) or disabled (false). + * + * Collision-enabled tiles can be collided against Sprites using {@link Phaser.Physics.Arcade#collide}. + * + * You can verify the collision faces by enabling {@link Phaser.TilemapLayer#debug}. + * + * @method Phaser.Tilemap#setCollision + * @param {number|array} indexes - Either a single tile index, or an array of tile IDs to be checked for collision. + * @param {boolean} [collides=true] - If true it will enable collision. If false it will clear collision. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to this.currentLayer. + * @param {boolean} [recalculate=true] - Recalculates the tile faces after the update. + */ setCollision: function (indexes, collides, layer, recalculate) { - if (collides === undefined) { collides = true; } if (recalculate === undefined) { recalculate = true; } @@ -923,24 +894,22 @@ Phaser.Tilemap.prototype = { this.calculateFaces(layer); } } - }, /** - * Sets collision on a range of tiles where the tile IDs increment sequentially. - * Calling this with a start value of 10 and a stop value of 14 would set collision for tiles 10, 11, 12, 13 and 14. - * The `collides` parameter controls if collision will be enabled (true) or disabled (false). - * - * @method Phaser.Tilemap#setCollisionBetween - * @param {number} start - The first index of the tile to be set for collision. - * @param {number} stop - The last index of the tile to be set for collision. - * @param {boolean} [collides=true] - If true it will enable collision. If false it will clear collision. - * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to this.currentLayer. - * @param {boolean} [recalculate=true] - Recalculates the tile faces after the update. - */ + * Sets collision on a range of tiles where the tile IDs increment sequentially. + * Calling this with a start value of 10 and a stop value of 14 would set collision for tiles 10, 11, 12, 13 and 14. + * The `collides` parameter controls if collision will be enabled (true) or disabled (false). + * + * @method Phaser.Tilemap#setCollisionBetween + * @param {number} start - The first index of the tile to be set for collision. + * @param {number} stop - The last index of the tile to be set for collision. + * @param {boolean} [collides=true] - If true it will enable collision. If false it will clear collision. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to this.currentLayer. + * @param {boolean} [recalculate=true] - Recalculates the tile faces after the update. + */ setCollisionBetween: function (start, stop, collides, layer, recalculate) { - if (collides === undefined) { collides = true; } if (recalculate === undefined) { recalculate = true; } @@ -961,22 +930,20 @@ Phaser.Tilemap.prototype = { // Now re-calculate interesting faces this.calculateFaces(layer); } - }, /** - * Sets collision on all tiles in the given layer, except for the IDs of those in the given array. - * The `collides` parameter controls if collision will be enabled (true) or disabled (false). - * - * @method Phaser.Tilemap#setCollisionByExclusion - * @param {array} indexes - An array of the tile IDs to not be counted for collision. - * @param {boolean} [collides=true] - If true it will enable collision. If false it will clear collision. - * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to this.currentLayer. - * @param {boolean} [recalculate=true] - Recalculates the tile faces after the update. - */ + * Sets collision on all tiles in the given layer, except for the IDs of those in the given array. + * The `collides` parameter controls if collision will be enabled (true) or disabled (false). + * + * @method Phaser.Tilemap#setCollisionByExclusion + * @param {array} indexes - An array of the tile IDs to not be counted for collision. + * @param {boolean} [collides=true] - If true it will enable collision. If false it will clear collision. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to this.currentLayer. + * @param {boolean} [recalculate=true] - Recalculates the tile faces after the update. + */ setCollisionByExclusion: function (indexes, collides, layer, recalculate) { - if (collides === undefined) { collides = true; } if (recalculate === undefined) { recalculate = true; } @@ -996,23 +963,21 @@ Phaser.Tilemap.prototype = { // Now re-calculate interesting faces this.calculateFaces(layer); } - }, /** - * Sets collision values on a tile in the set. - * You shouldn't usually call this method directly, instead use setCollision, setCollisionBetween or setCollisionByExclusion. - * - * @method Phaser.Tilemap#setCollisionByIndex - * @protected - * @param {number} index - The index of the tile on the layer. - * @param {boolean} [collides=true] - If true it will enable collision on the tile. If false it will clear collision values from the tile. - * @param {number} [layer] - The layer to operate on. If not given will default to this.currentLayer. - * @param {boolean} [recalculate=true] - Recalculates the tile faces after the update. - */ + * Sets collision values on a tile in the set. + * You shouldn't usually call this method directly, instead use setCollision, setCollisionBetween or setCollisionByExclusion. + * + * @method Phaser.Tilemap#setCollisionByIndex + * @protected + * @param {number} index - The index of the tile on the layer. + * @param {boolean} [collides=true] - If true it will enable collision on the tile. If false it will clear collision values from the tile. + * @param {number} [layer] - The layer to operate on. If not given will default to this.currentLayer. + * @param {boolean} [recalculate=true] - Recalculates the tile faces after the update. + */ setCollisionByIndex: function (index, collides, layer, recalculate) { - if (collides === undefined) { collides = true; } if (layer === undefined) { layer = this.currentLayer; } if (recalculate === undefined) { recalculate = true; } @@ -1063,20 +1028,18 @@ Phaser.Tilemap.prototype = { } return layer; - }, /** - * Gets the TilemapLayer index as used in the setCollision calls. - * - * @method Phaser.Tilemap#getLayer - * @protected - * @param {number|string|Phaser.TilemapLayer} layer - The layer to operate on. If not given will default to this.currentLayer. - * @return {number} The TilemapLayer index. - */ + * Gets the TilemapLayer index as used in the setCollision calls. + * + * @method Phaser.Tilemap#getLayer + * @protected + * @param {number|string|Phaser.TilemapLayer} layer - The layer to operate on. If not given will default to this.currentLayer. + * @return {number} The TilemapLayer index. + */ getLayer: function (layer) { - if (layer === undefined) { layer = this.currentLayer; @@ -1098,19 +1061,17 @@ Phaser.Tilemap.prototype = { } return layer; - }, /** - * Turn off/on the recalculation of faces for tile or collision updates. - * `setPreventRecalculate(true)` puts recalculation on hold while `setPreventRecalculate(false)` recalculates all the changed layers. - * - * @method Phaser.Tilemap#setPreventRecalculate - * @param {boolean} value - If true it will put the recalculation on hold. - */ + * Turn off/on the recalculation of faces for tile or collision updates. + * `setPreventRecalculate(true)` puts recalculation on hold while `setPreventRecalculate(false)` recalculates all the changed layers. + * + * @method Phaser.Tilemap#setPreventRecalculate + * @param {boolean} value - If true it will put the recalculation on hold. + */ setPreventRecalculate: function (value) { - if (value === true && this.preventingRecalculate !== true) { this.preventingRecalculate = true; @@ -1128,19 +1089,17 @@ Phaser.Tilemap.prototype = { this.needToRecalculate = false; } - }, /** - * Internal function. - * - * @method Phaser.Tilemap#calculateFaces - * @protected - * @param {number} layer - The index of the TilemapLayer to operate on. - */ + * Internal function. + * + * @method Phaser.Tilemap#calculateFaces + * @protected + * @param {number} layer - The index of the TilemapLayer to operate on. + */ calculateFaces: function (layer) { - if (this.preventingRecalculate) { this.needToRecalculate[layer] = true; @@ -1199,123 +1158,111 @@ Phaser.Tilemap.prototype = { } } } - }, /** - * Gets the tile above the tile coordinates given. - * Mostly used as an internal function by calculateFaces. - * - * @method Phaser.Tilemap#getTileAbove - * @param {number} layer - The local layer index to get the tile from. Can be determined by Tilemap.getLayer(). - * @param {number} x - The x coordinate to get the tile from. In tiles, not pixels. - * @param {number} y - The y coordinate to get the tile from. In tiles, not pixels. - */ + * Gets the tile above the tile coordinates given. + * Mostly used as an internal function by calculateFaces. + * + * @method Phaser.Tilemap#getTileAbove + * @param {number} layer - The local layer index to get the tile from. Can be determined by Tilemap.getLayer(). + * @param {number} x - The x coordinate to get the tile from. In tiles, not pixels. + * @param {number} y - The y coordinate to get the tile from. In tiles, not pixels. + */ getTileAbove: function (layer, x, y) { - if (y > 0) { return this.layers[layer].data[y - 1][x]; } return null; - }, /** - * Gets the tile below the tile coordinates given. - * Mostly used as an internal function by calculateFaces. - * - * @method Phaser.Tilemap#getTileBelow - * @param {number} layer - The local layer index to get the tile from. Can be determined by Tilemap.getLayer(). - * @param {number} x - The x coordinate to get the tile from. In tiles, not pixels. - * @param {number} y - The y coordinate to get the tile from. In tiles, not pixels. - */ + * Gets the tile below the tile coordinates given. + * Mostly used as an internal function by calculateFaces. + * + * @method Phaser.Tilemap#getTileBelow + * @param {number} layer - The local layer index to get the tile from. Can be determined by Tilemap.getLayer(). + * @param {number} x - The x coordinate to get the tile from. In tiles, not pixels. + * @param {number} y - The y coordinate to get the tile from. In tiles, not pixels. + */ getTileBelow: function (layer, x, y) { - if (y < this.layers[layer].height - 1) { return this.layers[layer].data[y + 1][x]; } return null; - }, /** - * Gets the tile to the left of the tile coordinates given. - * Mostly used as an internal function by calculateFaces. - * - * @method Phaser.Tilemap#getTileLeft - * @param {number} layer - The local layer index to get the tile from. Can be determined by Tilemap.getLayer(). - * @param {number} x - The x coordinate to get the tile from. In tiles, not pixels. - * @param {number} y - The y coordinate to get the tile from. In tiles, not pixels. - */ + * Gets the tile to the left of the tile coordinates given. + * Mostly used as an internal function by calculateFaces. + * + * @method Phaser.Tilemap#getTileLeft + * @param {number} layer - The local layer index to get the tile from. Can be determined by Tilemap.getLayer(). + * @param {number} x - The x coordinate to get the tile from. In tiles, not pixels. + * @param {number} y - The y coordinate to get the tile from. In tiles, not pixels. + */ getTileLeft: function (layer, x, y) { - if (x > 0) { return this.layers[layer].data[y][x - 1]; } return null; - }, /** - * Gets the tile to the right of the tile coordinates given. - * Mostly used as an internal function by calculateFaces. - * - * @method Phaser.Tilemap#getTileRight - * @param {number} layer - The local layer index to get the tile from. Can be determined by Tilemap.getLayer(). - * @param {number} x - The x coordinate to get the tile from. In tiles, not pixels. - * @param {number} y - The y coordinate to get the tile from. In tiles, not pixels. - */ + * Gets the tile to the right of the tile coordinates given. + * Mostly used as an internal function by calculateFaces. + * + * @method Phaser.Tilemap#getTileRight + * @param {number} layer - The local layer index to get the tile from. Can be determined by Tilemap.getLayer(). + * @param {number} x - The x coordinate to get the tile from. In tiles, not pixels. + * @param {number} y - The y coordinate to get the tile from. In tiles, not pixels. + */ getTileRight: function (layer, x, y) { - if (x < this.layers[layer].width - 1) { return this.layers[layer].data[y][x + 1]; } return null; - }, /** - * Sets the current layer to the given index. - * - * @method Phaser.Tilemap#setLayer - * @param {number|string|Phaser.TilemapLayer} layer - The layer to set as current. - */ + * Sets the current layer to the given index. + * + * @method Phaser.Tilemap#setLayer + * @param {number|string|Phaser.TilemapLayer} layer - The layer to set as current. + */ setLayer: function (layer) { - layer = this.getLayer(layer); if (this.layers[layer]) { this.currentLayer = layer; } - }, /** - * Checks if there is a tile at the given location. - * - * @method Phaser.Tilemap#hasTile - * @param {number} x - X position to check if a tile exists at (given in tile units, not pixels) - * @param {number} y - Y position to check if a tile exists at (given in tile units, not pixels) - * @param {number|string|Phaser.TilemapLayer} layer - The layer to set as current. - * @return {boolean} True if there is a tile at the given location, otherwise false. - */ + * Checks if there is a tile at the given location. + * + * @method Phaser.Tilemap#hasTile + * @param {number} x - X position to check if a tile exists at (given in tile units, not pixels) + * @param {number} y - Y position to check if a tile exists at (given in tile units, not pixels) + * @param {number|string|Phaser.TilemapLayer} layer - The layer to set as current. + * @return {boolean} True if there is a tile at the given location, otherwise false. + */ hasTile: function (x, y, layer) { - layer = this.getLayer(layer); if (this.layers[layer].data[y] === undefined || this.layers[layer].data[y][x] === undefined) @@ -1324,21 +1271,19 @@ Phaser.Tilemap.prototype = { } return (this.layers[layer].data[y][x].index > -1); - }, /** - * Removes the tile located at the given coordinates and updates the collision data. - * - * @method Phaser.Tilemap#removeTile - * @param {number} x - X position to place the tile (given in tile units, not pixels) - * @param {number} y - Y position to place the tile (given in tile units, not pixels) - * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to modify. - * @return {Phaser.Tile} The Tile object that was removed from this map. - */ + * Removes the tile located at the given coordinates and updates the collision data. + * + * @method Phaser.Tilemap#removeTile + * @param {number} x - X position to place the tile (given in tile units, not pixels) + * @param {number} y - Y position to place the tile (given in tile units, not pixels) + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to modify. + * @return {Phaser.Tile} The Tile object that was removed from this map. + */ removeTile: function (x, y, layer) { - layer = this.getLayer(layer); if (x >= 0 && x < this.layers[layer].width && y >= 0 && y < this.layers[layer].height) @@ -1356,46 +1301,42 @@ Phaser.Tilemap.prototype = { return tile; } } - }, /** - * Removes the tile located at the given coordinates and updates the collision data. The coordinates are given in pixel values. - * - * @method Phaser.Tilemap#removeTileWorldXY - * @param {number} x - X position to insert the tile (given in pixels) - * @param {number} y - Y position to insert the tile (given in pixels) - * @param {number} tileWidth - The width of the tile in pixels. - * @param {number} tileHeight - The height of the tile in pixels. - * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to modify. - * @return {Phaser.Tile} The Tile object that was removed from this map. - */ + * Removes the tile located at the given coordinates and updates the collision data. The coordinates are given in pixel values. + * + * @method Phaser.Tilemap#removeTileWorldXY + * @param {number} x - X position to insert the tile (given in pixels) + * @param {number} y - Y position to insert the tile (given in pixels) + * @param {number} tileWidth - The width of the tile in pixels. + * @param {number} tileHeight - The height of the tile in pixels. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to modify. + * @return {Phaser.Tile} The Tile object that was removed from this map. + */ removeTileWorldXY: function (x, y, tileWidth, tileHeight, layer) { - layer = this.getLayer(layer); x = this.game.math.snapToFloor(x, tileWidth) / tileWidth; y = this.game.math.snapToFloor(y, tileHeight) / tileHeight; return this.removeTile(x, y, layer); - }, /** - * Puts a tile of the given index value at the coordinate specified. - * If you pass `null` as the tile it will pass your call over to Tilemap.removeTile instead. - * - * @method Phaser.Tilemap#putTile - * @param {Phaser.Tile|number|null} tile - The index of this tile to set or a Phaser.Tile object. If a Tile object, all of its data will be copied. If null the tile is removed from the map. - * @param {number} x - X position to place the tile (given in tile units, not pixels) - * @param {number} y - Y position to place the tile (given in tile units, not pixels) - * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to modify. - * @return {Phaser.Tile} The Tile object that was created or added to this map. - */ + * Puts a tile of the given index value at the coordinate specified. + * If you pass `null` as the tile it will pass your call over to Tilemap.removeTile instead. + * + * @method Phaser.Tilemap#putTile + * @param {Phaser.Tile|number|null} tile - The index of this tile to set or a Phaser.Tile object. If a Tile object, all of its data will be copied. If null the tile is removed from the map. + * @param {number} x - X position to place the tile (given in tile units, not pixels) + * @param {number} y - Y position to place the tile (given in tile units, not pixels) + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to modify. + * @return {Phaser.Tile} The Tile object that was created or added to this map. + */ putTile: function (tile, x, y, layer) { - if (tile === null) { return this.removeTile(x, y, layer); @@ -1451,52 +1392,48 @@ Phaser.Tilemap.prototype = { } return null; - }, /** - * Puts a tile into the Tilemap layer. The coordinates are given in pixel values. - * - * @method Phaser.Tilemap#putTileWorldXY - * @param {Phaser.Tile|number} tile - The index of this tile to set or a Phaser.Tile object. - * @param {number} x - X position to insert the tile (given in pixels) - * @param {number} y - Y position to insert the tile (given in pixels) - * @param {number} tileWidth - The width of the tile in pixels. - * @param {number} tileHeight - The height of the tile in pixels. - * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to modify. - * @return {Phaser.Tile} The Tile object that was created or added to this map. - */ + * Puts a tile into the Tilemap layer. The coordinates are given in pixel values. + * + * @method Phaser.Tilemap#putTileWorldXY + * @param {Phaser.Tile|number} tile - The index of this tile to set or a Phaser.Tile object. + * @param {number} x - X position to insert the tile (given in pixels) + * @param {number} y - Y position to insert the tile (given in pixels) + * @param {number} tileWidth - The width of the tile in pixels. + * @param {number} tileHeight - The height of the tile in pixels. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to modify. + * @return {Phaser.Tile} The Tile object that was created or added to this map. + */ putTileWorldXY: function (tile, x, y, tileWidth, tileHeight, layer) { - layer = this.getLayer(layer); x = this.game.math.snapToFloor(x, tileWidth) / tileWidth; y = this.game.math.snapToFloor(y, tileHeight) / tileHeight; return this.putTile(tile, x, y, layer); - }, /** - * Searches the entire map layer for the first tile matching the given index, then returns that Phaser.Tile object. - * If no match is found it returns null. - * The search starts from the top-left tile and continues horizontally until it hits the end of the row, then it drops down to the next column. - * If the reverse boolean is true, it scans starting from the bottom-right corner traveling up to the top-left. - * - * @method Phaser.Tilemap#searchTileIndex - * - * @param {number} index - The tile index value to search for. - * @param {number} [skip=0] - The number of times to skip a matching tile before returning. - * @param {number} [reverse=false] - If true it will scan the layer in reverse, starting at the bottom-right. Otherwise it scans from the top-left. - * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to get the tile from. - * @param {number} [all=false] - If true it will scan the layer in reverse, starting at the bottom-right. Otherwise it scans from the top-left. - * - * @return {Phaser.Tile|Phaser.Tile[]} A matching tile, or null (when `all` is false); or an array of zero or more tiles (when `all` is true). - */ + * Searches the entire map layer for the first tile matching the given index, then returns that Phaser.Tile object. + * If no match is found it returns null. + * The search starts from the top-left tile and continues horizontally until it hits the end of the row, then it drops down to the next column. + * If the reverse boolean is true, it scans starting from the bottom-right corner traveling up to the top-left. + * + * @method Phaser.Tilemap#searchTileIndex + * + * @param {number} index - The tile index value to search for. + * @param {number} [skip=0] - The number of times to skip a matching tile before returning. + * @param {number} [reverse=false] - If true it will scan the layer in reverse, starting at the bottom-right. Otherwise it scans from the top-left. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to get the tile from. + * @param {number} [all=false] - If true it will scan the layer in reverse, starting at the bottom-right. Otherwise it scans from the top-left. + * + * @return {Phaser.Tile|Phaser.Tile[]} A matching tile, or null (when `all` is false); or an array of zero or more tiles (when `all` is true). + */ searchTileIndex: function (index, skip, reverse, layer, all) { - if (skip === undefined) { skip = 0; } if (reverse === undefined) { reverse = false; } @@ -1577,22 +1514,20 @@ Phaser.Tilemap.prototype = { } return all ? results : null; - }, /** - * Gets a tile from the Tilemap Layer. The coordinates are given in tile values. - * - * @method Phaser.Tilemap#getTile - * @param {number} x - X position to get the tile from (given in tile units, not pixels) - * @param {number} y - Y position to get the tile from (given in tile units, not pixels) - * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to get the tile from. - * @param {boolean} [nonNull=false] - If true getTile won't return null for empty tiles, but a Tile object with an index of -1. - * @return {Phaser.Tile} The tile at the given coordinates or null if no tile was found or the coordinates were invalid. - */ + * Gets a tile from the Tilemap Layer. The coordinates are given in tile values. + * + * @method Phaser.Tilemap#getTile + * @param {number} x - X position to get the tile from (given in tile units, not pixels) + * @param {number} y - Y position to get the tile from (given in tile units, not pixels) + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to get the tile from. + * @param {boolean} [nonNull=false] - If true getTile won't return null for empty tiles, but a Tile object with an index of -1. + * @return {Phaser.Tile} The tile at the given coordinates or null if no tile was found or the coordinates were invalid. + */ getTile: function (x, y, layer, nonNull) { - if (nonNull === undefined) { nonNull = false; } layer = this.getLayer(layer); @@ -1619,24 +1554,22 @@ Phaser.Tilemap.prototype = { { return null; } - }, /** - * Gets a tile from the Tilemap layer. The coordinates are given in pixel values. - * - * @method Phaser.Tilemap#getTileWorldXY - * @param {number} x - X position to get the tile from (given in pixels) - * @param {number} y - Y position to get the tile from (given in pixels) - * @param {number} [tileWidth] - The width of the tiles. If not given the map default is used. - * @param {number} [tileHeight] - The height of the tiles. If not given the map default is used. - * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to get the tile from. - * @param {boolean} [nonNull=false] - If true getTile won't return null for empty tiles, but a Tile object with an index of -1. - * @return {Phaser.Tile} The tile at the given coordinates. - */ + * Gets a tile from the Tilemap layer. The coordinates are given in pixel values. + * + * @method Phaser.Tilemap#getTileWorldXY + * @param {number} x - X position to get the tile from (given in pixels) + * @param {number} y - Y position to get the tile from (given in pixels) + * @param {number} [tileWidth] - The width of the tiles. If not given the map default is used. + * @param {number} [tileHeight] - The height of the tiles. If not given the map default is used. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to get the tile from. + * @param {boolean} [nonNull=false] - If true getTile won't return null for empty tiles, but a Tile object with an index of -1. + * @return {Phaser.Tile} The tile at the given coordinates. + */ getTileWorldXY: function (x, y, tileWidth, tileHeight, layer, nonNull) { - if (tileWidth === undefined) { tileWidth = this.tileWidth; } if (tileHeight === undefined) { tileHeight = this.tileHeight; } @@ -1646,23 +1579,21 @@ Phaser.Tilemap.prototype = { y = this.game.math.snapToFloor(y, tileHeight) / tileHeight; return this.getTile(x, y, layer, nonNull); - }, /** - * Copies all of the tiles in the given rectangular block into the tilemap data buffer. - * - * @method Phaser.Tilemap#copy - * @param {integer} [x=0] - X position of the top left of the area to copy (given in tiles, not pixels) - * @param {integer} [y=0] - Y position of the top left of the area to copy (given in tiles, not pixels) - * @param {integer} [width] - The width of the area to copy (given in tiles, not pixels) - * @param {integer} [height] - The height of the area to copy (given in tiles, not pixels) - * @param {integer|string|Phaser.TilemapLayer} [layer] - The layer to copy the tiles from. - * @return {array} An array of the tiles that were copied. - */ + * Copies all of the tiles in the given rectangular block into the tilemap data buffer. + * + * @method Phaser.Tilemap#copy + * @param {integer} [x=0] - X position of the top left of the area to copy (given in tiles, not pixels) + * @param {integer} [y=0] - Y position of the top left of the area to copy (given in tiles, not pixels) + * @param {integer} [width] - The width of the area to copy (given in tiles, not pixels) + * @param {integer} [height] - The height of the area to copy (given in tiles, not pixels) + * @param {integer|string|Phaser.TilemapLayer} [layer] - The layer to copy the tiles from. + * @return {array} An array of the tiles that were copied. + */ copy: function (x, y, width, height, layer) { - layer = this.getLayer(layer); if (!this.layers[layer]) @@ -1709,21 +1640,19 @@ Phaser.Tilemap.prototype = { } return this._results; - }, /** - * Pastes a previously copied block of tile data into the given x/y coordinates. Data should have been prepared with Tilemap.copy. - * - * @method Phaser.Tilemap#paste - * @param {number} x - X position of the top left of the area to paste to (given in tiles, not pixels) - * @param {number} y - Y position of the top left of the area to paste to (given in tiles, not pixels) - * @param {array} tileblock - The block of tiles to paste. - * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to paste the tiles into. - */ + * Pastes a previously copied block of tile data into the given x/y coordinates. Data should have been prepared with Tilemap.copy. + * + * @method Phaser.Tilemap#paste + * @param {number} x - X position of the top left of the area to paste to (given in tiles, not pixels) + * @param {number} y - Y position of the top left of the area to paste to (given in tiles, not pixels) + * @param {array} tileblock - The block of tiles to paste. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to paste the tiles into. + */ paste: function (x, y, tileblock, layer) { - if (x === undefined) { x = 0; } if (y === undefined) { y = 0; } @@ -1745,25 +1674,23 @@ Phaser.Tilemap.prototype = { this.layers[layer].dirty = true; this.calculateFaces(layer); - }, /** - * Scans the given area for tiles with an index matching tileA and swaps them with tileB. - * Only the tile indexes are modified. - * - * @method Phaser.Tilemap#swap - * @param {number} tileA - First tile index. - * @param {number} tileB - Second tile index. - * @param {number} x - X position of the top left of the area to operate one, given in tiles, not pixels. - * @param {number} y - Y position of the top left of the area to operate one, given in tiles, not pixels. - * @param {number} width - The width in tiles of the area to operate on. - * @param {number} height - The height in tiles of the area to operate on. - * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. - */ + * Scans the given area for tiles with an index matching tileA and swaps them with tileB. + * Only the tile indexes are modified. + * + * @method Phaser.Tilemap#swap + * @param {number} tileA - First tile index. + * @param {number} tileB - Second tile index. + * @param {number} x - X position of the top left of the area to operate one, given in tiles, not pixels. + * @param {number} y - Y position of the top left of the area to operate one, given in tiles, not pixels. + * @param {number} width - The width in tiles of the area to operate on. + * @param {number} height - The height in tiles of the area to operate on. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. + */ swap: function (tileA, tileB, x, y, width, height, layer) { - layer = this.getLayer(layer); this.copy(x, y, width, height, layer); @@ -1779,19 +1706,17 @@ Phaser.Tilemap.prototype = { this._results.forEach(this.swapHandler, this); this.paste(x, y, this._results, layer); - }, /** - * Internal function that handles the swapping of tiles. - * - * @method Phaser.Tilemap#swapHandler - * @private - * @param {number} value - */ + * Internal function that handles the swapping of tiles. + * + * @method Phaser.Tilemap#swapHandler + * @private + * @param {number} value + */ swapHandler: function (value) { - if (value.index === this._tempA) { // Swap A with B @@ -1802,24 +1727,22 @@ Phaser.Tilemap.prototype = { // Swap B with A value.index = this._tempA; } - }, /** - * For each tile in the given area defined by x/y and width/height run the given callback. - * - * @method Phaser.Tilemap#forEach - * @param {number} callback - The callback. Each tile in the given area will be passed to this callback as the first and only parameter. - * @param {number} context - The context under which the callback should be run. - * @param {number} x - X position of the top left of the area to operate one, given in tiles, not pixels. - * @param {number} y - Y position of the top left of the area to operate one, given in tiles, not pixels. - * @param {number} width - The width in tiles of the area to operate on. - * @param {number} height - The height in tiles of the area to operate on. - * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. - */ + * For each tile in the given area defined by x/y and width/height run the given callback. + * + * @method Phaser.Tilemap#forEach + * @param {number} callback - The callback. Each tile in the given area will be passed to this callback as the first and only parameter. + * @param {number} context - The context under which the callback should be run. + * @param {number} x - X position of the top left of the area to operate one, given in tiles, not pixels. + * @param {number} y - Y position of the top left of the area to operate one, given in tiles, not pixels. + * @param {number} width - The width in tiles of the area to operate on. + * @param {number} height - The height in tiles of the area to operate on. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. + */ forEach: function (callback, context, x, y, width, height, layer) { - layer = this.getLayer(layer); this.copy(x, y, width, height, layer); @@ -1832,25 +1755,23 @@ Phaser.Tilemap.prototype = { this._results.forEach(callback, context); this.paste(x, y, this._results, layer); - }, /** - * Scans the given area for tiles with an index matching `source` and updates their index to match `dest`. - * Only the tile indexes are modified. - * - * @method Phaser.Tilemap#replace - * @param {number} source - The tile index value to scan for. - * @param {number} dest - The tile index value to replace found tiles with. - * @param {number} [x=0] - X position of the top left of the area to operate one, given in tiles, not pixels. - * @param {number} [y=0] - Y position of the top left of the area to operate one, given in tiles, not pixels. - * @param {number} [width] - The width in tiles of the area to operate on. - * @param {number} [height] - The height in tiles of the area to operate on. - * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. - */ + * Scans the given area for tiles with an index matching `source` and updates their index to match `dest`. + * Only the tile indexes are modified. + * + * @method Phaser.Tilemap#replace + * @param {number} source - The tile index value to scan for. + * @param {number} dest - The tile index value to replace found tiles with. + * @param {number} [x=0] - X position of the top left of the area to operate one, given in tiles, not pixels. + * @param {number} [y=0] - Y position of the top left of the area to operate one, given in tiles, not pixels. + * @param {number} [width] - The width in tiles of the area to operate on. + * @param {number} [height] - The height in tiles of the area to operate on. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. + */ replace: function (source, dest, x, y, width, height, layer) { - layer = this.getLayer(layer); this.copy(x, y, width, height, layer); @@ -1869,23 +1790,21 @@ Phaser.Tilemap.prototype = { } this.paste(x, y, this._results, layer); - }, /** - * Randomises a set of tiles in a given area. - * Only the tile indexes are modified. - * - * @method Phaser.Tilemap#random - * @param {number} x - X position of the top left of the area to operate one, given in tiles, not pixels. - * @param {number} y - Y position of the top left of the area to operate one, given in tiles, not pixels. - * @param {number} width - The width in tiles of the area to operate on. - * @param {number} height - The height in tiles of the area to operate on. - * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. - */ + * Randomises a set of tiles in a given area. + * Only the tile indexes are modified. + * + * @method Phaser.Tilemap#random + * @param {number} x - X position of the top left of the area to operate one, given in tiles, not pixels. + * @param {number} y - Y position of the top left of the area to operate one, given in tiles, not pixels. + * @param {number} width - The width in tiles of the area to operate on. + * @param {number} height - The height in tiles of the area to operate on. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. + */ random: function (x, y, width, height, layer) { - layer = this.getLayer(layer); this.copy(x, y, width, height, layer); @@ -1916,23 +1835,21 @@ Phaser.Tilemap.prototype = { } this.paste(x, y, this._results, layer); - }, /** - * Shuffles a set of tiles in a given area. It will only randomise the tiles in that area, so if they're all the same nothing will appear to have changed! - * Only the tile indexes are modified. - * - * @method Phaser.Tilemap#shuffle - * @param {number} x - X position of the top left of the area to operate one, given in tiles, not pixels. - * @param {number} y - Y position of the top left of the area to operate one, given in tiles, not pixels. - * @param {number} width - The width in tiles of the area to operate on. - * @param {number} height - The height in tiles of the area to operate on. - * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. - */ + * Shuffles a set of tiles in a given area. It will only randomise the tiles in that area, so if they're all the same nothing will appear to have changed! + * Only the tile indexes are modified. + * + * @method Phaser.Tilemap#shuffle + * @param {number} x - X position of the top left of the area to operate one, given in tiles, not pixels. + * @param {number} y - Y position of the top left of the area to operate one, given in tiles, not pixels. + * @param {number} width - The width in tiles of the area to operate on. + * @param {number} height - The height in tiles of the area to operate on. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. + */ shuffle: function (x, y, width, height, layer) { - layer = this.getLayer(layer); this.copy(x, y, width, height, layer); @@ -1960,24 +1877,22 @@ Phaser.Tilemap.prototype = { } this.paste(x, y, this._results, layer); - }, /** - * Fills the given area with the specified tile. - * Only the tile indexes are modified. - * - * @method Phaser.Tilemap#fill - * @param {number} index - The index of the tile that the area will be filled with. - * @param {number} x - X position of the top left of the area to operate one, given in tiles, not pixels. - * @param {number} y - Y position of the top left of the area to operate one, given in tiles, not pixels. - * @param {number} width - The width in tiles of the area to operate on. - * @param {number} height - The height in tiles of the area to operate on. - * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. - */ + * Fills the given area with the specified tile. + * Only the tile indexes are modified. + * + * @method Phaser.Tilemap#fill + * @param {number} index - The index of the tile that the area will be filled with. + * @param {number} x - X position of the top left of the area to operate one, given in tiles, not pixels. + * @param {number} y - Y position of the top left of the area to operate one, given in tiles, not pixels. + * @param {number} width - The width in tiles of the area to operate on. + * @param {number} height - The height in tiles of the area to operate on. + * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. + */ fill: function (index, x, y, width, height, layer) { - layer = this.getLayer(layer); this.copy(x, y, width, height, layer); @@ -1993,30 +1908,26 @@ Phaser.Tilemap.prototype = { } this.paste(x, y, this._results, layer); - }, /** - * Removes all layers from this tile map. - * - * @method Phaser.Tilemap#removeAllLayers - */ + * Removes all layers from this tile map. + * + * @method Phaser.Tilemap#removeAllLayers + */ removeAllLayers: function () { - this.layers.length = 0; this.currentLayer = 0; - }, /** - * Dumps the tilemap data out to the console. - * - * @method Phaser.Tilemap#dump - */ + * Dumps the tilemap data out to the console. + * + * @method Phaser.Tilemap#dump + */ dump: function () { - var txt = ''; var args = [ '' ]; @@ -2048,22 +1959,19 @@ Phaser.Tilemap.prototype = { args[0] = txt; console.log.apply(console, args); - }, /** - * Removes all layer data from this tile map and nulls the game reference. - * Note: You are responsible for destroying any TilemapLayer objects you generated yourself, as Tilemap doesn't keep a reference to them. - * - * @method Phaser.Tilemap#destroy - */ + * Removes all layer data from this tile map and nulls the game reference. + * Note: You are responsible for destroying any TilemapLayer objects you generated yourself, as Tilemap doesn't keep a reference to them. + * + * @method Phaser.Tilemap#destroy + */ destroy: function () { - this.removeAllLayers(); this.data = []; this.game = null; - } }; @@ -2071,26 +1979,22 @@ Phaser.Tilemap.prototype = { Phaser.Tilemap.prototype.constructor = Phaser.Tilemap; /** -* @name Phaser.Tilemap#layer -* @property {number|string|Phaser.TilemapLayer} layer - The current layer object. -*/ + * @name Phaser.Tilemap#layer + * @property {number|string|Phaser.TilemapLayer} layer - The current layer object. + */ Object.defineProperty(Phaser.Tilemap.prototype, 'layer', { get: function () { - return this.layers[this.currentLayer]; - }, set: function (value) { - if (value !== this.currentLayer) { this.setLayer(value); } - } }); diff --git a/src/tilemap/TilemapLayer.js b/src/tilemap/TilemapLayer.js index 02400146a..965444b7e 100644 --- a/src/tilemap/TilemapLayer.js +++ b/src/tilemap/TilemapLayer.js @@ -1,101 +1,100 @@ /** -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* A TilemapLayer is a Phaser.Image/Sprite that renders a specific TileLayer of a Tilemap. -* -* Since a TilemapLayer is a Sprite it can be moved around the display, added to other groups or display objects, etc. -* -* By default TilemapLayers have fixedToCamera set to `true`. Changing this will break Camera follow and scrolling behavior. -* -* @class Phaser.TilemapLayer -* @extends Phaser.Sprite -* @constructor -* @param {Phaser.Game} game - Game reference to the currently running game. -* @param {Phaser.Tilemap} tilemap - The tilemap to which this layer belongs. -* @param {integer} index - The index of the TileLayer to render within the Tilemap. -* @param {integer} width - Width of the renderable area of the layer (in pixels). -* @param {integer} height - Height of the renderable area of the layer (in pixels). -*/ + * A TilemapLayer is a Phaser.Image/Sprite that renders a specific TileLayer of a Tilemap. + * + * Since a TilemapLayer is a Sprite it can be moved around the display, added to other groups or display objects, etc. + * + * By default TilemapLayers have fixedToCamera set to `true`. Changing this will break Camera follow and scrolling behavior. + * + * @class Phaser.TilemapLayer + * @extends Phaser.Sprite + * @constructor + * @param {Phaser.Game} game - Game reference to the currently running game. + * @param {Phaser.Tilemap} tilemap - The tilemap to which this layer belongs. + * @param {integer} index - The index of the TileLayer to render within the Tilemap. + * @param {integer} width - Width of the renderable area of the layer (in pixels). + * @param {integer} height - Height of the renderable area of the layer (in pixels). + */ Phaser.TilemapLayer = function (game, tilemap, index, width, height) { - width |= 0; height |= 0; Phaser.Sprite.call(this, game, 0, 0); /** - * The Tilemap to which this layer is bound. - * @property {Phaser.Tilemap} map - * @protected - * @readonly - */ + * The Tilemap to which this layer is bound. + * @property {Phaser.Tilemap} map + * @protected + * @readonly + */ this.map = tilemap; /** - * The index of this layer within the Tilemap. - * @property {number} index - * @protected - * @readonly - */ + * The index of this layer within the Tilemap. + * @property {number} index + * @protected + * @readonly + */ this.index = index; /** - * The layer object within the Tilemap that this layer represents. - * @property {object} layer - * @protected - * @readonly - */ + * The layer object within the Tilemap that this layer represents. + * @property {object} layer + * @protected + * @readonly + */ this.layer = tilemap.layers[index]; /** - * The canvas to which this TilemapLayer draws. - * @property {HTMLCanvasElement} canvas - * @protected - */ + * The canvas to which this TilemapLayer draws. + * @property {HTMLCanvasElement} canvas + * @protected + */ this.canvas = Phaser.CanvasPool.create(this, width, height); /** - * The 2d context of the canvas. - * @property {CanvasRenderingContext2D} context - * @private - */ + * The 2d context of the canvas. + * @property {CanvasRenderingContext2D} context + * @private + */ this.context = this.canvas.getContext('2d'); this.setTexture(new PIXI.Texture(new PIXI.BaseTexture(this.canvas, null, this.game.resolution))); /** - * The const type of this object. - * @property {number} type - * @readonly - * @protected - * @default Phaser.TILEMAPLAYER - */ + * The const type of this object. + * @property {number} type + * @readonly + * @protected + * @default Phaser.TILEMAPLAYER + */ this.type = Phaser.TILEMAPLAYER; /** - * @property {number} physicsType - The const physics body type of this object. - * @readonly - */ + * @property {number} physicsType - The const physics body type of this object. + * @readonly + */ this.physicsType = Phaser.TILEMAPLAYER; /** - * Settings that control standard (non-diagnostic) rendering. - * - * @property {boolean} [enableScrollDelta=true] - Delta scroll rendering only draws tiles/edges as they come into view. - * This can greatly improve scrolling rendering performance, especially when there are many small tiles. - * It should only be disabled in rare cases. - * - * @property {?DOMCanvasElement} [copyCanvas=(auto)] - [Internal] If set, force using a separate (shared) copy canvas. - * Using a canvas bitblt/copy when the source and destinations region overlap produces unexpected behavior - * in some browsers, notably Safari. - * - * @default - */ + * Settings that control standard (non-diagnostic) rendering. + * + * @property {boolean} [enableScrollDelta=true] - Delta scroll rendering only draws tiles/edges as they come into view. + * This can greatly improve scrolling rendering performance, especially when there are many small tiles. + * It should only be disabled in rare cases. + * + * @property {?DOMCanvasElement} [copyCanvas=(auto)] - [Internal] If set, force using a separate (shared) copy canvas. + * Using a canvas bitblt/copy when the source and destinations region overlap produces unexpected behavior + * in some browsers, notably Safari. + * + * @default + */ this.renderSettings = { enableScrollDelta: true, overdrawRatio: 0.20, @@ -103,34 +102,34 @@ Phaser.TilemapLayer = function (game, tilemap, index, width, height) }; /** - * Enable an additional "debug rendering" pass to display collision information. - * - * @property {boolean} debug - * @default - */ + * Enable an additional "debug rendering" pass to display collision information. + * + * @property {boolean} debug + * @default + */ this.debug = false; /** - * @property {boolean} exists - Controls if the core game loop and physics update this game object or not. - */ + * @property {boolean} exists - Controls if the core game loop and physics update this game object or not. + */ this.exists = true; /** - * Settings used for debugging and diagnostics. - * - * @property {?string} missingImageFill - A tile is rendered as a rectangle using the following fill if a valid tileset/image cannot be found. A value of `null` prevents additional rendering for tiles without a valid tileset image. _This takes effect even when debug rendering for the layer is not enabled._ - * - * @property {?string} debuggedTileOverfill - If a Tile has `Tile#debug` true then, after normal tile image rendering, a rectangle with the following fill is drawn above/over it. _This takes effect even when debug rendering for the layer is not enabled._ - * - * @property {boolean} forceFullRedraw - When debug rendering (`debug` is true), and this option is enabled, the a full redraw is forced and rendering optimization is suppressed. - * - * @property {number} debugAlpha - When debug rendering (`debug` is true), the tileset is initially rendered with this alpha level. This can make the tile edges clearer. - * - * @property {?string} facingEdgeStroke - When debug rendering (`debug` is true), this color/stroke is used to draw "face" edges. A value of `null` disables coloring facing edges. - * - * @property {?string} collidingTileOverfill - When debug rendering (`debug` is true), this fill is used for tiles that are collidable. A value of `null` disables applying the additional overfill. - * - */ + * Settings used for debugging and diagnostics. + * + * @property {?string} missingImageFill - A tile is rendered as a rectangle using the following fill if a valid tileset/image cannot be found. A value of `null` prevents additional rendering for tiles without a valid tileset image. _This takes effect even when debug rendering for the layer is not enabled._ + * + * @property {?string} debuggedTileOverfill - If a Tile has `Tile#debug` true then, after normal tile image rendering, a rectangle with the following fill is drawn above/over it. _This takes effect even when debug rendering for the layer is not enabled._ + * + * @property {boolean} forceFullRedraw - When debug rendering (`debug` is true), and this option is enabled, the a full redraw is forced and rendering optimization is suppressed. + * + * @property {number} debugAlpha - When debug rendering (`debug` is true), the tileset is initially rendered with this alpha level. This can make the tile edges clearer. + * + * @property {?string} facingEdgeStroke - When debug rendering (`debug` is true), this color/stroke is used to draw "face" edges. A value of `null` disables coloring facing edges. + * + * @property {?string} collidingTileOverfill - When debug rendering (`debug` is true), this fill is used for tiles that are collidable. A value of `null` disables applying the additional overfill. + * + */ this.debugSettings = { missingImageFill: 'rgb(255,255,255)', @@ -145,47 +144,47 @@ Phaser.TilemapLayer = function (game, tilemap, index, width, height) }; /** - * Speed at which this layer scrolls horizontally, relative to the camera (e.g. scrollFactorX of 0.5 scrolls half as quickly as the 'normal' camera-locked layers do). - * @property {number} scrollFactorX - * @public - * @default - */ + * Speed at which this layer scrolls horizontally, relative to the camera (e.g. scrollFactorX of 0.5 scrolls half as quickly as the 'normal' camera-locked layers do). + * @property {number} scrollFactorX + * @public + * @default + */ this.scrollFactorX = 1; /** - * Speed at which this layer scrolls vertically, relative to the camera (e.g. scrollFactorY of 0.5 scrolls half as quickly as the 'normal' camera-locked layers do) - * @property {number} scrollFactorY - * @public - * @default - */ + * Speed at which this layer scrolls vertically, relative to the camera (e.g. scrollFactorY of 0.5 scrolls half as quickly as the 'normal' camera-locked layers do) + * @property {number} scrollFactorY + * @public + * @default + */ this.scrollFactorY = 1; /** - * If true tiles will be force rendered, even if such is not believed to be required. - * @property {boolean} dirty - * @protected - */ + * If true tiles will be force rendered, even if such is not believed to be required. + * @property {boolean} dirty + * @protected + */ this.dirty = true; /** - * When ray-casting against tiles this is the number of steps it will jump. For larger tile sizes you can increase this to improve performance. - * @property {integer} rayStepRate - * @default - */ + * When ray-casting against tiles this is the number of steps it will jump. For larger tile sizes you can increase this to improve performance. + * @property {integer} rayStepRate + * @default + */ this.rayStepRate = 4; /** - * Flag controlling if the layer tiles wrap at the edges. - * @property {boolean} _wrap - * @private - */ + * Flag controlling if the layer tiles wrap at the edges. + * @property {boolean} _wrap + * @private + */ this._wrap = false; /** - * Local map data and calculation cache. - * @property {object} _mc - * @private - */ + * Local map data and calculation cache. + * @property {object} _mc + * @private + */ this._mc = { // Used to bypass rendering without reliance on `dirty` and detect changes. @@ -197,9 +196,11 @@ Phaser.TilemapLayer = function (game, tilemap, index, width, height) tileWidth: tilemap.tileWidth, tileHeight: tilemap.tileHeight, - // Collision width/height (pixels) - // What purpose do these have? Most things use tile width/height directly. - // This also only extends collisions right and down. + /* + * Collision width/height (pixels) + * What purpose do these have? Most things use tile width/height directly. + * This also only extends collisions right and down. + */ cw: tilemap.tileWidth, ch: tilemap.tileHeight, @@ -209,17 +210,17 @@ Phaser.TilemapLayer = function (game, tilemap, index, width, height) }; /** - * The current canvas left after scroll is applied. - * @property {number} _scrollX - * @private - */ + * The current canvas left after scroll is applied. + * @property {number} _scrollX + * @private + */ this._scrollX = 0; /** - * The current canvas top after scroll is applied. - * @property {number} _scrollY - * @private - */ + * The current canvas top after scroll is applied. + * @property {number} _scrollY + * @private + */ this._scrollY = 0; /** @@ -229,10 +230,10 @@ Phaser.TilemapLayer = function (game, tilemap, index, width, height) this.tileOffset = new Phaser.Point(this.layer.offsetX || 0, this.layer.offsetY || 0); /** - * Used for caching the tiles / array of tiles. - * @property {Phaser.Tile[]} _results - * @private - */ + * Used for caching the tiles / array of tiles. + * @property {Phaser.Tile[]} _results + * @private + */ this._results = []; if (!game.device.canvasBitBltShift) @@ -241,7 +242,6 @@ Phaser.TilemapLayer = function (game, tilemap, index, width, height) } this.fixedToCamera = true; - }; Phaser.TilemapLayer.prototype = Object.create(Phaser.Sprite.prototype); @@ -250,55 +250,50 @@ Phaser.TilemapLayer.prototype.constructor = Phaser.TilemapLayer; Phaser.TilemapLayer.prototype.preUpdateCore = Phaser.Component.Core.preUpdate; /** -* The shared double-copy canvas, created as needed. -* -* @private -* @static -*/ + * The shared double-copy canvas, created as needed. + * + * @private + * @static + */ Phaser.TilemapLayer.sharedCopyCanvas = null; /** -* Create if needed (and return) a shared copy canvas that is shared across all TilemapLayers. -* -* Code that uses the canvas is responsible to ensure the dimensions and save/restore state as appropriate. -* -* @method Phaser.TilemapLayer#ensureSharedCopyCanvas -* @protected -* @static -*/ + * Create if needed (and return) a shared copy canvas that is shared across all TilemapLayers. + * + * Code that uses the canvas is responsible to ensure the dimensions and save/restore state as appropriate. + * + * @method Phaser.TilemapLayer#ensureSharedCopyCanvas + * @protected + * @static + */ Phaser.TilemapLayer.ensureSharedCopyCanvas = function () { - if (!this.sharedCopyCanvas) { this.sharedCopyCanvas = Phaser.CanvasPool.create(this, 2, 2); } return this.sharedCopyCanvas; - }; /** -* Automatically called by World.preUpdate. -* -* @method Phaser.TilemapLayer#preUpdate -*/ + * Automatically called by World.preUpdate. + * + * @method Phaser.TilemapLayer#preUpdate + */ Phaser.TilemapLayer.prototype.preUpdate = function () { - return this.preUpdateCore(); - }; /** -* Automatically called by World.postUpdate. Handles cache updates. -* -* @method Phaser.TilemapLayer#postUpdate -* @protected -*/ + * Automatically called by World.postUpdate. Handles cache updates. + * + * @method Phaser.TilemapLayer#postUpdate + * @protected + */ Phaser.TilemapLayer.prototype.postUpdate = function () { - if (this.fixedToCamera) { this.position.x = (this.game.camera.view.x + this.cameraOffset.x) / this.game.camera.scale.x; @@ -307,19 +302,17 @@ Phaser.TilemapLayer.prototype.postUpdate = function () this._scrollX = (this.game.camera.view.x - this.tileOffset.x) * this.scrollFactorX / this.scale.x; this._scrollY = (this.game.camera.view.y - this.tileOffset.y) * this.scrollFactorY / this.scale.y; - }; /** -* Automatically called by the Canvas Renderer. -* Overrides the Sprite._renderCanvas function. -* -* @method Phaser.TilemapLayer#_renderCanvas -* @private -*/ + * Automatically called by the Canvas Renderer. + * Overrides the Sprite._renderCanvas function. + * + * @method Phaser.TilemapLayer#_renderCanvas + * @private + */ Phaser.TilemapLayer.prototype._renderCanvas = function (renderSession) { - if (this.fixedToCamera) { this.position.x = (this.game.camera.view.x + this.cameraOffset.x) / this.game.camera.scale.x; @@ -332,19 +325,17 @@ Phaser.TilemapLayer.prototype._renderCanvas = function (renderSession) this.render(); PIXI.Sprite.prototype._renderCanvas.call(this, renderSession); - }; /** -* Automatically called by the Canvas Renderer. -* Overrides the Sprite._renderWebGL function. -* -* @method Phaser.TilemapLayer#_renderWebGL -* @private -*/ + * Automatically called by the Canvas Renderer. + * Overrides the Sprite._renderWebGL function. + * + * @method Phaser.TilemapLayer#_renderWebGL + * @private + */ Phaser.TilemapLayer.prototype._renderWebGL = function (renderSession) { - if (this.fixedToCamera) { this.position.x = (this.game.camera.view.x + this.cameraOffset.x) / this.game.camera.scale.x; @@ -357,39 +348,35 @@ Phaser.TilemapLayer.prototype._renderWebGL = function (renderSession) this.render(); PIXI.Sprite.prototype._renderWebGL.call(this, renderSession); - }; /** -* Destroys this TilemapLayer. -* -* @method Phaser.TilemapLayer#destroy -*/ + * Destroys this TilemapLayer. + * + * @method Phaser.TilemapLayer#destroy + */ Phaser.TilemapLayer.prototype.destroy = function () { - Phaser.CanvasPool.remove(this); Phaser.Component.Destroy.prototype.destroy.call(this); - }; /** -* Resizes the internal canvas and texture frame used by this TilemapLayer. -* -* This is an expensive call, so don't bind it to a window resize event! But instead call it at carefully -* selected times. -* -* Be aware that no validation of the new sizes takes place and the current map scroll coordinates are not -* modified either. You will have to handle both of these things from your game code if required. -* -* @method Phaser.TilemapLayer#resize -* @param {number} width - The new width of the TilemapLayer -* @param {number} height - The new height of the TilemapLayer -*/ + * Resizes the internal canvas and texture frame used by this TilemapLayer. + * + * This is an expensive call, so don't bind it to a window resize event! But instead call it at carefully + * selected times. + * + * Be aware that no validation of the new sizes takes place and the current map scroll coordinates are not + * modified either. You will have to handle both of these things from your game code if required. + * + * @method Phaser.TilemapLayer#resize + * @param {number} width - The new width of the TilemapLayer + * @param {number} height - The new height of the TilemapLayer + */ Phaser.TilemapLayer.prototype.resize = function (width, height) { - this.canvas.width = width; this.canvas.height = height; @@ -410,20 +397,17 @@ Phaser.TilemapLayer.prototype.resize = function (width, height) this.texture._updateUvs(); this.dirty = true; - }; /** -* Sets the world size to match the size of this layer. -* -* @method Phaser.TilemapLayer#resizeWorld -* @public -*/ + * Sets the world size to match the size of this layer. + * + * @method Phaser.TilemapLayer#resizeWorld + * @public + */ Phaser.TilemapLayer.prototype.resizeWorld = function () { - this.game.world.setBounds(0, 0, this.layer.widthInPixels * this.scale.x, this.layer.heightInPixels * this.scale.y); - }; /** @@ -435,9 +419,7 @@ Phaser.TilemapLayer.prototype.resizeWorld = function () */ Phaser.TilemapLayer.prototype.getTileOffsetX = function () { - return this.tileOffset.x || ((!this.fixedToCamera) ? this.position.x : 0); - }; /** @@ -449,22 +431,19 @@ Phaser.TilemapLayer.prototype.getTileOffsetX = function () */ Phaser.TilemapLayer.prototype.getTileOffsetY = function () { - return this.tileOffset.y || ((!this.fixedToCamera) ? this.position.y : 0); - }; /** -* Take an x coordinate that doesn't account for scrollFactorX and 'fix' it into a scrolled local space. -* -* @method Phaser.TilemapLayer#_fixX -* @private -* @param {number} x - x coordinate in camera space -* @return {number} x coordinate in scrollFactor-adjusted dimensions -*/ + * Take an x coordinate that doesn't account for scrollFactorX and 'fix' it into a scrolled local space. + * + * @method Phaser.TilemapLayer#_fixX + * @private + * @param {number} x - x coordinate in camera space + * @return {number} x coordinate in scrollFactor-adjusted dimensions + */ Phaser.TilemapLayer.prototype._fixX = function (x) { - if (this.scrollFactorX === 1 || (this.scrollFactorX === 0 && this.position.x === 0)) { return x; @@ -477,40 +456,36 @@ Phaser.TilemapLayer.prototype._fixX = function (x) } return this._scrollX + (x - (this._scrollX / this.scrollFactorX)); - }; /** -* Take an x coordinate that _does_ account for scrollFactorX and 'unfix' it back to camera space. -* -* @method Phaser.TilemapLayer#_unfixX -* @private -* @param {number} x - x coordinate in scrollFactor-adjusted dimensions -* @return {number} x coordinate in camera space -*/ + * Take an x coordinate that _does_ account for scrollFactorX and 'unfix' it back to camera space. + * + * @method Phaser.TilemapLayer#_unfixX + * @private + * @param {number} x - x coordinate in scrollFactor-adjusted dimensions + * @return {number} x coordinate in camera space + */ Phaser.TilemapLayer.prototype._unfixX = function (x) { - if (this.scrollFactorX === 1) { return x; } return (this._scrollX / this.scrollFactorX) + (x - this._scrollX); - }; /** -* Take a y coordinate that doesn't account for scrollFactorY and 'fix' it into a scrolled local space. -* -* @method Phaser.TilemapLayer#_fixY -* @private -* @param {number} y - y coordinate in camera space -* @return {number} y coordinate in scrollFactor-adjusted dimensions -*/ + * Take a y coordinate that doesn't account for scrollFactorY and 'fix' it into a scrolled local space. + * + * @method Phaser.TilemapLayer#_fixY + * @private + * @param {number} y - y coordinate in camera space + * @return {number} y coordinate in scrollFactor-adjusted dimensions + */ Phaser.TilemapLayer.prototype._fixY = function (y) { - if (this.scrollFactorY === 1 || (this.scrollFactorY === 0 && this.position.y === 0)) { return y; @@ -523,95 +498,85 @@ Phaser.TilemapLayer.prototype._fixY = function (y) } return this._scrollY + (y - (this._scrollY / this.scrollFactorY)); - }; /** -* Take a y coordinate that _does_ account for scrollFactorY and 'unfix' it back to camera space. -* -* @method Phaser.TilemapLayer#_unfixY -* @private -* @param {number} y - y coordinate in scrollFactor-adjusted dimensions -* @return {number} y coordinate in camera space -*/ + * Take a y coordinate that _does_ account for scrollFactorY and 'unfix' it back to camera space. + * + * @method Phaser.TilemapLayer#_unfixY + * @private + * @param {number} y - y coordinate in scrollFactor-adjusted dimensions + * @return {number} y coordinate in camera space + */ Phaser.TilemapLayer.prototype._unfixY = function (y) { - if (this.scrollFactorY === 1) { return y; } return (this._scrollY / this.scrollFactorY) + (y - this._scrollY); - }; /** -* Convert a pixel value to a tile coordinate. -* -* @method Phaser.TilemapLayer#getTileX -* @public -* @param {number} x - X position of the point in target tile (in pixels). -* @return {integer} The X map location of the tile. -*/ + * Convert a pixel value to a tile coordinate. + * + * @method Phaser.TilemapLayer#getTileX + * @public + * @param {number} x - X position of the point in target tile (in pixels). + * @return {integer} The X map location of the tile. + */ Phaser.TilemapLayer.prototype.getTileX = function (x) { - // var tileWidth = this.tileWidth * this.scale.x; return Math.floor(this._fixX(x) / this._mc.tileWidth); - }; /** -* Convert a pixel value to a tile coordinate. -* -* @method Phaser.TilemapLayer#getTileY -* @public -* @param {number} y - Y position of the point in target tile (in pixels). -* @return {integer} The Y map location of the tile. -*/ + * Convert a pixel value to a tile coordinate. + * + * @method Phaser.TilemapLayer#getTileY + * @public + * @param {number} y - Y position of the point in target tile (in pixels). + * @return {integer} The Y map location of the tile. + */ Phaser.TilemapLayer.prototype.getTileY = function (y) { - // var tileHeight = this.tileHeight * this.scale.y; return Math.floor(this._fixY(y) / this._mc.tileHeight); - }; /** -* Convert a pixel coordinate to a tile coordinate. -* -* @method Phaser.TilemapLayer#getTileXY -* @public -* @param {number} x - X position of the point in target tile (in pixels). -* @param {number} y - Y position of the point in target tile (in pixels). -* @param {(Phaser.Point|object)} point - The Point/object to update. -* @return {(Phaser.Point|object)} A Point/object with its `x` and `y` properties set. -*/ + * Convert a pixel coordinate to a tile coordinate. + * + * @method Phaser.TilemapLayer#getTileXY + * @public + * @param {number} x - X position of the point in target tile (in pixels). + * @param {number} y - Y position of the point in target tile (in pixels). + * @param {(Phaser.Point|object)} point - The Point/object to update. + * @return {(Phaser.Point|object)} A Point/object with its `x` and `y` properties set. + */ Phaser.TilemapLayer.prototype.getTileXY = function (x, y, point) { - point.x = this.getTileX(x); point.y = this.getTileY(y); return point; - }; /** -* Gets all tiles that intersect with the given line. -* -* @method Phaser.TilemapLayer#getRayCastTiles -* @public -* @param {Phaser.Line} line - The line used to determine which tiles to return. -* @param {integer} [stepRate=(rayStepRate)] - How many steps through the ray will we check? Defaults to `rayStepRate`. -* @param {boolean} [collides=false] - If true, _only_ return tiles that collide on one or more faces. -* @param {boolean} [interestingFace=false] - If true, _only_ return tiles that have interesting faces. -* @return {Phaser.Tile[]} An array of Phaser.Tiles. -*/ + * Gets all tiles that intersect with the given line. + * + * @method Phaser.TilemapLayer#getRayCastTiles + * @public + * @param {Phaser.Line} line - The line used to determine which tiles to return. + * @param {integer} [stepRate=(rayStepRate)] - How many steps through the ray will we check? Defaults to `rayStepRate`. + * @param {boolean} [collides=false] - If true, _only_ return tiles that collide on one or more faces. + * @param {boolean} [interestingFace=false] - If true, _only_ return tiles that have interesting faces. + * @return {Phaser.Tile[]} An array of Phaser.Tiles. + */ Phaser.TilemapLayer.prototype.getRayCastTiles = function (line, stepRate, collides, interestingFace) { - if (!stepRate) { stepRate = this.rayStepRate; } if (collides === undefined) { collides = false; } if (interestingFace === undefined) { interestingFace = false; } @@ -643,25 +608,23 @@ Phaser.TilemapLayer.prototype.getRayCastTiles = function (line, stepRate, collid } return results; - }; /** -* Get all tiles that exist within the given area, defined by the top-left corner, width and height. Values given are in pixels, not tiles. -* -* @method Phaser.TilemapLayer#getTiles -* @public -* @param {number} x - X position of the top left corner (in pixels). -* @param {number} y - Y position of the top left corner (in pixels). -* @param {number} width - Width of the area to get (in pixels). -* @param {number} height - Height of the area to get (in pixels). -* @param {boolean} [collides=false] - If true, _only_ return tiles that collide on one or more faces. -* @param {boolean} [interestingFace=false] - If true, _only_ return tiles that have interesting faces. -* @return {array} An array of Tiles. -*/ + * Get all tiles that exist within the given area, defined by the top-left corner, width and height. Values given are in pixels, not tiles. + * + * @method Phaser.TilemapLayer#getTiles + * @public + * @param {number} x - X position of the top left corner (in pixels). + * @param {number} y - Y position of the top left corner (in pixels). + * @param {number} width - Width of the area to get (in pixels). + * @param {number} height - Height of the area to get (in pixels). + * @param {boolean} [collides=false] - If true, _only_ return tiles that collide on one or more faces. + * @param {boolean} [interestingFace=false] - If true, _only_ return tiles that have interesting faces. + * @return {array} An array of Tiles. + */ Phaser.TilemapLayer.prototype.getTiles = function (x, y, width, height, collides, interestingFace) { - // Should we only get tiles that have at least one of their collision flags set? (true = yes, false = no just get them all) if (collides === undefined) { collides = false; } if (interestingFace === undefined) { interestingFace = false; } @@ -702,21 +665,19 @@ Phaser.TilemapLayer.prototype.getTiles = function (x, y, width, height, collides } return this._results.slice(); - }; /** -* Returns the appropriate tileset for the index, updating the internal cache as required. -* This should only be called if `tilesets[index]` evaluates to undefined. -* -* @method Phaser.TilemapLayer#resolveTileset -* @private -* @param {integer} Tile index -* @return {Phaser.Tileset|null} Returns the associated tileset or null if there is no such mapping. -*/ + * Returns the appropriate tileset for the index, updating the internal cache as required. + * This should only be called if `tilesets[index]` evaluates to undefined. + * + * @method Phaser.TilemapLayer#resolveTileset + * @private + * @param {integer} Tile index + * @return {Phaser.Tileset|null} Returns the associated tileset or null if there is no such mapping. + */ Phaser.TilemapLayer.prototype.resolveTileset = function (tileIndex) { - var tilesets = this._mc.tilesets; // Try for dense array if reasonable @@ -741,27 +702,24 @@ Phaser.TilemapLayer.prototype.resolveTileset = function (tileIndex) } return (tilesets[tileIndex] = null); - }; /** -* The TilemapLayer caches tileset look-ups. -* -* Call this method of clear the cache if tilesets have been added or updated after the layer has been rendered. -* -* @method Phaser.TilemapLayer#resetTilesetCache -* @public -*/ + * The TilemapLayer caches tileset look-ups. + * + * Call this method of clear the cache if tilesets have been added or updated after the layer has been rendered. + * + * @method Phaser.TilemapLayer#resetTilesetCache + * @public + */ Phaser.TilemapLayer.prototype.resetTilesetCache = function () { - var tilesets = this._mc.tilesets; while (tilesets.length) { tilesets.pop(); } - }; /** @@ -773,7 +731,6 @@ Phaser.TilemapLayer.prototype.resetTilesetCache = function () */ Phaser.TilemapLayer.prototype.setScale = function (xScale, yScale) { - xScale = xScale || 1; yScale = yScale || xScale; @@ -794,23 +751,21 @@ Phaser.TilemapLayer.prototype.setScale = function (xScale, yScale) } this.scale.setTo(xScale, yScale); - }; /** -* Shifts the contents of the canvas - does extra math so that different browsers agree on the result. -* -* The specified (x/y) will be shifted to (0,0) after the copy and the newly exposed canvas area will need to be filled in. -* -* @method Phaser.TilemapLayer#shiftCanvas -* @private -* @param {CanvasRenderingContext2D} context - The context to shift -* @param {integer} x -* @param {integer} y -*/ + * Shifts the contents of the canvas - does extra math so that different browsers agree on the result. + * + * The specified (x/y) will be shifted to (0,0) after the copy and the newly exposed canvas area will need to be filled in. + * + * @method Phaser.TilemapLayer#shiftCanvas + * @private + * @param {CanvasRenderingContext2D} context - The context to shift + * @param {integer} x + * @param {integer} y + */ Phaser.TilemapLayer.prototype.shiftCanvas = function (context, x, y) { - var canvas = context.canvas; var copyW = canvas.width - Math.abs(x); var copyH = canvas.height - Math.abs(y); @@ -837,8 +792,10 @@ Phaser.TilemapLayer.prototype.shiftCanvas = function (context, x, y) if (copyCanvas) { - // Use a second copy buffer, without slice support, for Safari .. again. - // Ensure copy canvas is large enough + /* + * Use a second copy buffer, without slice support, for Safari .. again. + * Ensure copy canvas is large enough + */ if (copyCanvas.width < copyW || copyCanvas.height < copyH) { copyCanvas.width = copyW; @@ -855,32 +812,32 @@ Phaser.TilemapLayer.prototype.shiftCanvas = function (context, x, y) } else { - // Avoids a second copy but flickers in Safari / Safari Mobile - // Ref. https://github.com/photonstorm/phaser/issues/1439 + /* + * Avoids a second copy but flickers in Safari / Safari Mobile + * Ref. https://github.com/photonstorm/phaser/issues/1439 + */ context.save(); context.globalCompositeOperation = 'copy'; context.drawImage(canvas, dx, dy, copyW, copyH, sx, sy, copyW, copyH); context.restore(); } - }; /** -* Render tiles in the given area given by the virtual tile coordinates biased by the given scroll factor. -* This will constrain the tile coordinates based on wrapping but not physical coordinates. -* -* @method Phaser.TilemapLayer#renderRegion -* @private -* @param {integer} scrollX - Render x offset/scroll. -* @param {integer} scrollY - Render y offset/scroll. -* @param {integer} left - Leftmost column to render. -* @param {integer} top - Topmost row to render. -* @param {integer} right - Rightmost column to render. -* @param {integer} bottom - Bottommost row to render. -*/ + * Render tiles in the given area given by the virtual tile coordinates biased by the given scroll factor. + * This will constrain the tile coordinates based on wrapping but not physical coordinates. + * + * @method Phaser.TilemapLayer#renderRegion + * @private + * @param {integer} scrollX - Render x offset/scroll. + * @param {integer} scrollY - Render y offset/scroll. + * @param {integer} left - Leftmost column to render. + * @param {integer} top - Topmost row to render. + * @param {integer} right - Rightmost column to render. + * @param {integer} bottom - Bottommost row to render. + */ Phaser.TilemapLayer.prototype.renderRegion = function (scrollX, scrollY, left, top, right, bottom) { - var context = this.context; var width = this.layer.width; @@ -913,9 +870,11 @@ Phaser.TilemapLayer.prototype.renderRegion = function (scrollX, scrollY, left, t var normStartX = (left + ((1 << 20) * width)) % width; var normStartY = (top + ((1 << 20) * height)) % height; - // tx/ty - are pixel coordinates where tile is drawn - // x/y - is cell location, normalized [0..width/height) in loop - // xmax/ymax - remaining cells to render on column/row + /* + * tx/ty - are pixel coordinates where tile is drawn + * x/y - is cell location, normalized [0..width/height) in loop + * xmax/ymax - remaining cells to render on column/row + */ var tx, ty, x, y, xmax, ymax; for (y = normStartY, ymax = bottom - top, ty = baseY; ymax >= 0; y++, ymax--, ty += th) @@ -989,22 +948,18 @@ Phaser.TilemapLayer.prototype.renderRegion = function (scrollX, scrollY, left, t context.fillStyle = this.debugSettings.debuggedTileOverfill; context.fillRect(tx, ty, tw, th); } - } - } - }; /** -* Shifts the canvas and render damaged edge tiles. -* -* @method Phaser.TilemapLayer#renderDeltaScroll -* @private -*/ + * Shifts the canvas and render damaged edge tiles. + * + * @method Phaser.TilemapLayer#renderDeltaScroll + * @private + */ Phaser.TilemapLayer.prototype.renderDeltaScroll = function (shiftX, shiftY) { - var scrollX = this._mc.scrollX; var scrollY = this._mc.scrollY; @@ -1071,18 +1026,16 @@ Phaser.TilemapLayer.prototype.renderDeltaScroll = function (shiftX, shiftY) var trueRight = Math.floor((renderW - 1 + scrollX) / tw); this.renderRegion(scrollX, scrollY, trueLeft, top, trueRight, bottom); } - }; /** -* Clear and render the entire canvas. -* -* @method Phaser.TilemapLayer#renderFull -* @private -*/ + * Clear and render the entire canvas. + * + * @method Phaser.TilemapLayer#renderFull + * @private + */ Phaser.TilemapLayer.prototype.renderFull = function () { - var scrollX = this._mc.scrollX; var scrollY = this._mc.scrollY; @@ -1100,18 +1053,16 @@ Phaser.TilemapLayer.prototype.renderFull = function () this.context.clearRect(0, 0, renderW, renderH); this.renderRegion(scrollX, scrollY, left, top, right, bottom); - }; /** -* Renders the tiles to the layer canvas and pushes to the display. -* -* @method Phaser.TilemapLayer#render -* @protected -*/ + * Renders the tiles to the layer canvas and pushes to the display. + * + * @method Phaser.TilemapLayer#render + * @protected + */ Phaser.TilemapLayer.prototype.render = function () { - var redrawAll = false; if (!this.visible) @@ -1191,20 +1142,18 @@ Phaser.TilemapLayer.prototype.render = function () this.context.restore(); return true; - }; /** -* Renders a debug overlay on-top of the canvas. Called automatically by render when `debug` is true. -* -* See `debugSettings` for assorted configuration options. -* -* @method Phaser.TilemapLayer#renderDebug -* @private -*/ + * Renders a debug overlay on-top of the canvas. Called automatically by render when `debug` is true. + * + * See `debugSettings` for assorted configuration options. + * + * @method Phaser.TilemapLayer#renderDebug + * @private + */ Phaser.TilemapLayer.prototype.renderDebug = function () { - var scrollX = this._mc.scrollX; var scrollY = this._mc.scrollY; @@ -1292,21 +1241,18 @@ Phaser.TilemapLayer.prototype.renderDebug = function () context.stroke(); } - } - } - }; /** -* Flag controlling if the layer tiles wrap at the edges. Only works if the World size matches the Map size. -* -* @property {boolean} wrap -* @memberof Phaser.TilemapLayer -* @public -* @default false -*/ + * Flag controlling if the layer tiles wrap at the edges. Only works if the World size matches the Map size. + * + * @property {boolean} wrap + * @memberof Phaser.TilemapLayer + * @public + * @default false + */ Object.defineProperty(Phaser.TilemapLayer.prototype, 'wrap', { get: function () @@ -1323,12 +1269,12 @@ Object.defineProperty(Phaser.TilemapLayer.prototype, 'wrap', { }); /** -* Scrolls the map horizontally or returns the current x position. -* -* @property {number} scrollX -* @memberof Phaser.TilemapLayer -* @public -*/ + * Scrolls the map horizontally or returns the current x position. + * + * @property {number} scrollX + * @memberof Phaser.TilemapLayer + * @public + */ Object.defineProperty(Phaser.TilemapLayer.prototype, 'scrollX', { get: function () @@ -1344,12 +1290,12 @@ Object.defineProperty(Phaser.TilemapLayer.prototype, 'scrollX', { }); /** -* Scrolls the map vertically or returns the current y position. -* -* @property {number} scrollY -* @memberof Phaser.TilemapLayer -* @public -*/ + * Scrolls the map vertically or returns the current y position. + * + * @property {number} scrollY + * @memberof Phaser.TilemapLayer + * @public + */ Object.defineProperty(Phaser.TilemapLayer.prototype, 'scrollY', { get: function () @@ -1365,12 +1311,12 @@ Object.defineProperty(Phaser.TilemapLayer.prototype, 'scrollY', { }); /** -* The width of the collision tiles (in pixels). -* -* @property {integer} collisionWidth -* @memberof Phaser.TilemapLayer -* @public -*/ + * The width of the collision tiles (in pixels). + * + * @property {integer} collisionWidth + * @memberof Phaser.TilemapLayer + * @public + */ Object.defineProperty(Phaser.TilemapLayer.prototype, 'collisionWidth', { get: function () @@ -1387,12 +1333,12 @@ Object.defineProperty(Phaser.TilemapLayer.prototype, 'collisionWidth', { }); /** -* The height of the collision tiles (in pixels). -* -* @property {integer} collisionHeight -* @memberof Phaser.TilemapLayer -* @public -*/ + * The height of the collision tiles (in pixels). + * + * @property {integer} collisionHeight + * @memberof Phaser.TilemapLayer + * @public + */ Object.defineProperty(Phaser.TilemapLayer.prototype, 'collisionHeight', { get: function () diff --git a/src/tilemap/TilemapParser.js b/src/tilemap/TilemapParser.js index 8517ac6c3..0d9954afc 100644 --- a/src/tilemap/TilemapParser.js +++ b/src/tilemap/TilemapParser.js @@ -1,15 +1,15 @@ /** -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* Phaser.TilemapParser parses data objects from Phaser.Loader that need more preparation before they can be inserted into a Tilemap. -* -* @class Phaser.TilemapParser -* @static -*/ + * Phaser.TilemapParser parses data objects from Phaser.Loader that need more preparation before they can be inserted into a Tilemap. + * + * @class Phaser.TilemapParser + * @static + */ Phaser.TilemapParser = { /** @@ -26,20 +26,19 @@ Phaser.TilemapParser = { INSERT_NULL: false, /** - * Parse tilemap data from the cache and creates data for a Tilemap object. - * - * @method Phaser.TilemapParser.parse - * @param {Phaser.Game} game - Game reference to the currently running game. - * @param {string} key - The key of the tilemap in the Cache. - * @param {number} [tileWidth=32] - The pixel width of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data. - * @param {number} [tileHeight=32] - The pixel height of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data. - * @param {number} [width=10] - The width of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this. - * @param {number} [height=10] - The height of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this. - * @return {object} The parsed map object. - */ + * Parse tilemap data from the cache and creates data for a Tilemap object. + * + * @method Phaser.TilemapParser.parse + * @param {Phaser.Game} game - Game reference to the currently running game. + * @param {string} key - The key of the tilemap in the Cache. + * @param {number} [tileWidth=32] - The pixel width of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data. + * @param {number} [tileHeight=32] - The pixel height of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data. + * @param {number} [width=10] - The width of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this. + * @param {number} [height=10] - The height of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this. + * @return {object} The parsed map object. + */ parse: function (game, key, tileWidth, tileHeight, width, height) { - if (tileWidth === undefined) { tileWidth = 32; } if (tileHeight === undefined) { tileHeight = 32; } if (width === undefined) { width = 10; } @@ -72,22 +71,20 @@ Phaser.TilemapParser = { { console.warn('No map data found for key "%s"', key); } - }, /** - * Parses a CSV file into valid map data. - * - * @method Phaser.TilemapParser.parseCSV - * @param {string} key - The name you want to give the map data. - * @param {string} data - The CSV file data. - * @param {number} [tileWidth=32] - The pixel width of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data. - * @param {number} [tileHeight=32] - The pixel height of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data. - * @return {object} Generated map data. - */ + * Parses a CSV file into valid map data. + * + * @method Phaser.TilemapParser.parseCSV + * @param {string} key - The name you want to give the map data. + * @param {string} data - The CSV file data. + * @param {number} [tileWidth=32] - The pixel width of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data. + * @param {number} [tileHeight=32] - The pixel height of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data. + * @return {object} Generated map data. + */ parseCSV: function (key, data, tileWidth, tileHeight) { - var map = this.getEmptyData(); // Trim any rogue whitespace from the data @@ -131,18 +128,16 @@ Phaser.TilemapParser = { map.layers[0].data = output; return map; - }, /** - * Returns an empty map data object. - * - * @method Phaser.TilemapParser.getEmptyData - * @return {object} Generated map data. - */ + * Returns an empty map data object. + * + * @method Phaser.TilemapParser.getEmptyData + * @return {object} Generated map data. + */ getEmptyData: function (tileWidth, tileHeight, width, height) { - return { width: (width !== undefined && width !== null) ? width : 0, height: (height !== undefined && height !== null) ? height : 0, @@ -177,7 +172,6 @@ Phaser.TilemapParser = { tilesets: [], tiles: [] }; - }, _slice: function (obj, fields) @@ -198,18 +192,17 @@ Phaser.TilemapParser = { }, /** - * Parses an object group in Tiled JSON files. Object groups can be found in both layers and tilesets. Called internally in parseTiledJSON. - * @method Phaser.TilemapParser.parseObjectGroup - * @param {object} objectGroup - A JSON object group. - * @param {object} objectsCollection - An object into which new array of Tiled map objects will be added. - * @param {object} collisionCollection - An object into which new array of collision objects will be added. Currently only polylines are added. - * @param {string} [nameKey=objectGroup.name] - Key under which to store objects in collisions in objectsCollection and collisionCollection - * @param {object} [relativePosition={x: 0, y: 0}] - Coordinates the object group's position is relative to. - * @return {object} A object literal containing the objectsCollection and collisionCollection - */ + * Parses an object group in Tiled JSON files. Object groups can be found in both layers and tilesets. Called internally in parseTiledJSON. + * @method Phaser.TilemapParser.parseObjectGroup + * @param {object} objectGroup - A JSON object group. + * @param {object} objectsCollection - An object into which new array of Tiled map objects will be added. + * @param {object} collisionCollection - An object into which new array of collision objects will be added. Currently only polylines are added. + * @param {string} [nameKey=objectGroup.name] - Key under which to store objects in collisions in objectsCollection and collisionCollection + * @param {object} [relativePosition={x: 0, y: 0}] - Coordinates the object group's position is relative to. + * @return {object} A object literal containing the objectsCollection and collisionCollection + */ parseObjectGroup: function (objectGroup, objectsCollection, collisionCollection, nameKey, relativePosition) { - var nameKey = nameKey || objectGroup.name; var relativePosition = relativePosition || {x: 0, y: 0}; var slice = this._slice; @@ -334,14 +327,13 @@ Phaser.TilemapParser = { }, /** - * Parses a Tiled JSON file into valid map data. - * @method Phaser.TilemapParser.parseTiledJSON - * @param {object} json - The JSON map data. - * @return {object} Generated and parsed map data. - */ + * Parses a Tiled JSON file into valid map data. + * @method Phaser.TilemapParser.parseTiledJSON + * @param {object} json - The JSON map data. + * @return {object} Generated and parsed map data. + */ parseTiledJSON: function (json) { - if (json.orientation !== 'orthogonal') { console.warn('Phaser CE supports only orthogonal maps. This map\'s orientation is "%s".', json.orientation); @@ -380,8 +372,10 @@ Phaser.TilemapParser = { var curl = json.layers[i]; - // Base64 decode data if necessary - // NOTE: uncompressed base64 only. + /* + * Base64 decode data if necessary + * NOTE: uncompressed base64 only. + */ if (!curl.compression && curl.encoding && curl.encoding === 'base64') { @@ -389,8 +383,10 @@ Phaser.TilemapParser = { var len = binaryString.length; var bytes = new Array(len); - // Interpret binaryString as an array of bytes representing - // little-endian encoded uint32 values. + /* + * Interpret binaryString as an array of bytes representing + * little-endian encoded uint32 values. + */ for (var j = 0; j < len; j += 4) { bytes[j / 4] = ( @@ -444,9 +440,11 @@ Phaser.TilemapParser = { // Loop through the data field in the JSON. - // This is an array containing the tile indexes, one after the other. -1 = no tile, everything else = the tile index (starting at 1 for Tiled, 0 for CSV) - // If the map contains multiple tilesets then the indexes are relative to that which the set starts from. - // Need to set which tileset in the cache = which tileset in the JSON, if you do this manually it means you can use the same map data but a new tileset. + /* + * This is an array containing the tile indexes, one after the other. -1 = no tile, everything else = the tile index (starting at 1 for Tiled, 0 for CSV) + * If the map contains multiple tilesets then the indexes are relative to that which the set starts from. + * Need to set which tileset in the cache = which tileset in the JSON, if you do this manually it means you can use the same map data but a new tileset. + */ for (var t = 0, len = curl.data.length; t < len; t++) { @@ -588,7 +586,6 @@ Phaser.TilemapParser = { } images.push(image); - } map.images = images; @@ -617,8 +614,10 @@ Phaser.TilemapParser = { newSet.tileProperties = set.tileproperties; } - // For a normal sliced tileset the row/count/size information is computed when updated. - // This is done (again) after the image is set. + /* + * For a normal sliced tileset the row/count/size information is computed when updated. + * This is done (again) after the image is set. + */ newSet.updateTileData(set.imagewidth, set.imageheight); tilesets.push(newSet); @@ -733,7 +732,6 @@ Phaser.TilemapParser = { } } } - } // assign tile properties @@ -792,13 +790,11 @@ Phaser.TilemapParser = { y: tile.worldY + objectGroup.y }); } - } } } return map; - } }; diff --git a/src/tilemap/Tileset.js b/src/tilemap/Tileset.js index af55c5fd1..c43db5873 100644 --- a/src/tilemap/Tileset.js +++ b/src/tilemap/Tileset.js @@ -1,139 +1,136 @@ /** -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* A Tile set is a combination of an image containing the tiles and collision data per tile. -* -* Tilesets are normally created automatically when Tiled data is loaded. -* -* @class Phaser.Tileset -* @constructor -* @param {string} name - The name of the tileset in the map data. -* @param {integer} firstgid - The first tile index this tileset contains. -* @param {integer} [width=32] - Width of each tile (in pixels). -* @param {integer} [height=32] - Height of each tile (in pixels). -* @param {integer} [margin=0] - The margin around all tiles in the sheet (in pixels). -* @param {integer} [spacing=0] - The spacing between each tile in the sheet (in pixels). -* @param {object} [properties={}] - Custom Tileset properties. -*/ + * A Tile set is a combination of an image containing the tiles and collision data per tile. + * + * Tilesets are normally created automatically when Tiled data is loaded. + * + * @class Phaser.Tileset + * @constructor + * @param {string} name - The name of the tileset in the map data. + * @param {integer} firstgid - The first tile index this tileset contains. + * @param {integer} [width=32] - Width of each tile (in pixels). + * @param {integer} [height=32] - Height of each tile (in pixels). + * @param {integer} [margin=0] - The margin around all tiles in the sheet (in pixels). + * @param {integer} [spacing=0] - The spacing between each tile in the sheet (in pixels). + * @param {object} [properties={}] - Custom Tileset properties. + */ Phaser.Tileset = function (name, firstgid, width, height, margin, spacing, properties) { - if (width === undefined || width <= 0) { width = 32; } if (height === undefined || height <= 0) { height = 32; } if (margin === undefined) { margin = 0; } if (spacing === undefined) { spacing = 0; } /** - * The name of the Tileset. - * @property {string} name - */ + * The name of the Tileset. + * @property {string} name + */ this.name = name; /** - * The Tiled firstgid value. - * This is the starting index of the first tile index this Tileset contains. - * @property {integer} firstgid - */ + * The Tiled firstgid value. + * This is the starting index of the first tile index this Tileset contains. + * @property {integer} firstgid + */ this.firstgid = firstgid | 0; /** - * The width of each tile (in pixels). - * @property {integer} tileWidth - * @readonly - */ + * The width of each tile (in pixels). + * @property {integer} tileWidth + * @readonly + */ this.tileWidth = width | 0; /** - * The height of each tile (in pixels). - * @property {integer} tileHeight - * @readonly - */ + * The height of each tile (in pixels). + * @property {integer} tileHeight + * @readonly + */ this.tileHeight = height | 0; /** - * The margin around the tiles in the sheet (in pixels). - * Use `setSpacing` to change. - * @property {integer} tileMarge - * @readonly - */ + * The margin around the tiles in the sheet (in pixels). + * Use `setSpacing` to change. + * @property {integer} tileMarge + * @readonly + */ // Modified internally this.tileMargin = margin | 0; /** - * The spacing between each tile in the sheet (in pixels). - * Use `setSpacing` to change. - * @property {integer} tileSpacing - * @readonly - */ + * The spacing between each tile in the sheet (in pixels). + * Use `setSpacing` to change. + * @property {integer} tileSpacing + * @readonly + */ this.tileSpacing = spacing | 0; /** - * Tileset-specific properties that are typically defined in the Tiled editor. - * @property {object} properties - */ + * Tileset-specific properties that are typically defined in the Tiled editor. + * @property {object} properties + */ this.properties = properties || {}; /** - * The cached image that contains the individual tiles. Use {@link Phaser.Tileset.setImage setImage} to set. - * @property {?object} image - * @readonly - */ + * The cached image that contains the individual tiles. Use {@link Phaser.Tileset.setImage setImage} to set. + * @property {?object} image + * @readonly + */ // Modified internally this.image = null; /** - * The number of tile rows in the the tileset. - * @property {integer} - * @readonly - */ + * The number of tile rows in the the tileset. + * @property {integer} + * @readonly + */ // Modified internally this.rows = 0; /** - * The number of tile columns in the tileset. - * @property {integer} columns - * @readonly - */ + * The number of tile columns in the tileset. + * @property {integer} columns + * @readonly + */ // Modified internally this.columns = 0; /** - * The total number of tiles in the tileset. - * @property {integer} total - * @readonly - */ + * The total number of tiles in the tileset. + * @property {integer} total + * @readonly + */ // Modified internally this.total = 0; /** - * The look-up table to specific tile image offsets. - * The coordinates are interlaced such that it is [x0, y0, x1, y1 .. xN, yN] and the tile with the index of firstgid is found at indices 0/1. - * @property {integer[]} drawCoords - * @private - */ + * The look-up table to specific tile image offsets. + * The coordinates are interlaced such that it is [x0, y0, x1, y1 .. xN, yN] and the tile with the index of firstgid is found at indices 0/1. + * @property {integer[]} drawCoords + * @private + */ this.drawCoords = []; - }; Phaser.Tileset.prototype = { /** - * Draws a tile from this Tileset at the given coordinates on the context. - * - * @method Phaser.Tileset#draw - * @public - * @param {CanvasRenderingContext2D} context - The context to draw the tile onto. - * @param {number} x - The x coordinate to draw to. - * @param {number} y - The y coordinate to draw to. - * @param {integer} index - The index of the tile within the set to draw. - */ + * Draws a tile from this Tileset at the given coordinates on the context. + * + * @method Phaser.Tileset#draw + * @public + * @param {CanvasRenderingContext2D} context - The context to draw the tile onto. + * @param {number} x - The x coordinate to draw to. + * @param {number} y - The y coordinate to draw to. + * @param {integer} index - The index of the tile within the set to draw. + */ draw: function (context, x, y, index) { - // Correct the tile index for the set and bias for interlacing var coordIndex = (index - this.firstgid) << 1; @@ -151,53 +148,47 @@ Phaser.Tileset.prototype = { this.tileHeight ); } - }, /** - * Returns true if and only if this tileset contains the given tile index. - * - * @method Phaser.Tileset#containsTileIndex - * @public - * @param {number} tileIndex - * @return {boolean} True if this tileset contains the given index. - */ + * Returns true if and only if this tileset contains the given tile index. + * + * @method Phaser.Tileset#containsTileIndex + * @public + * @param {number} tileIndex + * @return {boolean} True if this tileset contains the given index. + */ containsTileIndex: function (tileIndex) { - return ( tileIndex >= this.firstgid && tileIndex < (this.firstgid + this.total) ); - }, /** - * Set the image associated with this Tileset and update the tile data. - * - * @method Phaser.Tileset#setImage - * @public - * @param {Image} image - The image that contains the tiles. - */ + * Set the image associated with this Tileset and update the tile data. + * + * @method Phaser.Tileset#setImage + * @public + * @param {Image} image - The image that contains the tiles. + */ setImage: function (image) { - this.image = image; this.updateTileData(image.width, image.height); - }, /** - * Sets tile spacing and margins. - * - * @method Phaser.Tileset#setSpacing - * @public - * @param {integer} [margin=0] - The margin around the tiles in the sheet (in pixels). - * @param {integer} [spacing=0] - The spacing between the tiles in the sheet (in pixels). - */ + * Sets tile spacing and margins. + * + * @method Phaser.Tileset#setSpacing + * @public + * @param {integer} [margin=0] - The margin around the tiles in the sheet (in pixels). + * @param {integer} [spacing=0] - The spacing between the tiles in the sheet (in pixels). + */ setSpacing: function (margin, spacing) { - this.tileMargin = margin | 0; this.tileSpacing = spacing | 0; @@ -205,20 +196,18 @@ Phaser.Tileset.prototype = { { this.updateTileData(this.image.width, this.image.height); } - }, /** - * Updates tile coordinates and tileset data. - * - * @method Phaser.Tileset#updateTileData - * @private - * @param {integer} imageWidth - The (expected) width of the image to slice. - * @param {integer} imageHeight - The (expected) height of the image to slice. - */ + * Updates tile coordinates and tileset data. + * + * @method Phaser.Tileset#updateTileData + * @private + * @param {integer} imageWidth - The (expected) width of the image to slice. + * @param {integer} imageHeight - The (expected) height of the image to slice. + */ updateTileData: function (imageWidth, imageHeight) { - // May be fractional values var rowCount = (imageHeight - this.tileMargin * 2 + this.tileSpacing) / (this.tileHeight + this.tileSpacing); var colCount = (imageWidth - this.tileMargin * 2 + this.tileSpacing) / (this.tileWidth + this.tileSpacing); @@ -231,8 +220,10 @@ Phaser.Tileset.prototype = { ); } - // In Tiled a tileset image that is not an even multiple of the tile dimensions - // is truncated - hence the floor when calculating the rows/columns. + /* + * In Tiled a tileset image that is not an even multiple of the tile dimensions + * is truncated - hence the floor when calculating the rows/columns. + */ rowCount = Math.floor(rowCount); colCount = Math.floor(colCount); @@ -265,7 +256,6 @@ Phaser.Tileset.prototype = { tx = this.tileMargin; ty += this.tileHeight + this.tileSpacing; } - } }; diff --git a/src/time/Time.js b/src/time/Time.js index 7444cc683..7f36b9086 100644 --- a/src/time/Time.js +++ b/src/time/Time.js @@ -1,383 +1,376 @@ /** -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* This is the core internal game clock. -* -* It manages the elapsed time and calculation of elapsed values, used for game object motion and tweens, -* and also handles the standard Timer pool. -* -* To create a general timed event, use the master {@link Phaser.Timer} accessible through {@link Phaser.Time.events events}. -* -* There are different *types* of time in Phaser: -* -* - ***Game time*** always runs at the speed of time in real life. -* -* Unlike wall-clock time, *game time stops when Phaser is paused*. -* -* Game time is used for {@link Phaser.Timer timer events}. -* -* - ***Physics time*** represents the amount of time given to physics calculations. -* -* *When {@link #slowMotion} is in effect physics time runs slower than game time.* -* Like game time, physics time stops when Phaser is paused. -* -* Physics time is used for physics calculations and {@link Phaser.Tween tweens}. -* -* - {@link https://en.wikipedia.org/wiki/Wall-clock_time ***Wall-clock time***} represents the duration between two events in real life time. -* -* This time is independent of Phaser and always progresses, regardless of if Phaser is paused. -* -* @class Phaser.Time -* @constructor -* @param {Phaser.Game} game A reference to the currently running game. -*/ + * This is the core internal game clock. + * + * It manages the elapsed time and calculation of elapsed values, used for game object motion and tweens, + * and also handles the standard Timer pool. + * + * To create a general timed event, use the master {@link Phaser.Timer} accessible through {@link Phaser.Time.events events}. + * + * There are different *types* of time in Phaser: + * + * - ***Game time*** always runs at the speed of time in real life. + * + * Unlike wall-clock time, *game time stops when Phaser is paused*. + * + * Game time is used for {@link Phaser.Timer timer events}. + * + * - ***Physics time*** represents the amount of time given to physics calculations. + * + * *When {@link #slowMotion} is in effect physics time runs slower than game time.* + * Like game time, physics time stops when Phaser is paused. + * + * Physics time is used for physics calculations and {@link Phaser.Tween tweens}. + * + * - {@link https://en.wikipedia.org/wiki/Wall-clock_time ***Wall-clock time***} represents the duration between two events in real life time. + * + * This time is independent of Phaser and always progresses, regardless of if Phaser is paused. + * + * @class Phaser.Time + * @constructor + * @param {Phaser.Game} game A reference to the currently running game. + */ Phaser.Time = function (game) { - /** - * @property {Phaser.Game} game - Local reference to game. - * @protected - */ + * @property {Phaser.Game} game - Local reference to game. + * @protected + */ this.game = game; /** - * The `Date.now()` value when the time was last updated. - * @property {integer} time - * @protected - */ + * The `Date.now()` value when the time was last updated. + * @property {integer} time + * @protected + */ this.time = 0; /** - * The `now` when the previous update occurred. - * @property {number} prevTime - * @protected - */ + * The `now` when the previous update occurred. + * @property {number} prevTime + * @protected + */ this.prevTime = 0; /** - * An increasing value representing cumulative milliseconds since an undisclosed epoch. - * - * While this value is in milliseconds and can be used to compute time deltas, - * it must must _not_ be used with `Date.now()` as it may not use the same epoch / starting reference. - * - * The source may either be from a high-res source (eg. if RAF is available) or the standard Date.now; - * the value can only be relied upon within a particular game instance. - * - * @property {number} now - * @protected - */ + * An increasing value representing cumulative milliseconds since an undisclosed epoch. + * + * While this value is in milliseconds and can be used to compute time deltas, + * it must must _not_ be used with `Date.now()` as it may not use the same epoch / starting reference. + * + * The source may either be from a high-res source (eg. if RAF is available) or the standard Date.now; + * the value can only be relied upon within a particular game instance. + * + * @property {number} now + * @protected + */ this.now = 0; /** - * Elapsed time since the last time update, in milliseconds, based on `now`. - * - * This value _may_ include time that the game is paused/inactive. - * - * While the game is active, this will be similar to (1000 / {@link #fps}). - * - * This is updated only once per game loop, even if multiple logic update steps are done. - * Use {@link Phaser.Time#physicsElapsed physicsElapsed} as a basis of game/logic calculations instead. - * - * @property {number} elapsed - * @see Phaser.Time.time - * @protected - */ + * Elapsed time since the last time update, in milliseconds, based on `now`. + * + * This value _may_ include time that the game is paused/inactive. + * + * While the game is active, this will be similar to (1000 / {@link #fps}). + * + * This is updated only once per game loop, even if multiple logic update steps are done. + * Use {@link Phaser.Time#physicsElapsed physicsElapsed} as a basis of game/logic calculations instead. + * + * @property {number} elapsed + * @see Phaser.Time.time + * @protected + */ this.elapsed = 0; /** - * The time in ms since the last time update, in milliseconds, based on `time`. - * - * This value is corrected for game pauses and will be "about zero" after a game is resumed. - * - * This is updated at each logic update, possibly more than once per game loop. - * If multiple logic update steps are done, the `elapsedMS` values will differ greatly. - * - * Use {@link Phaser.Time#physicsElapsedMS physicsElapsedMS} as a basis of game/logic calculations instead. - * - * @property {integer} elapsedMS - * @protected - */ + * The time in ms since the last time update, in milliseconds, based on `time`. + * + * This value is corrected for game pauses and will be "about zero" after a game is resumed. + * + * This is updated at each logic update, possibly more than once per game loop. + * If multiple logic update steps are done, the `elapsedMS` values will differ greatly. + * + * Use {@link Phaser.Time#physicsElapsedMS physicsElapsedMS} as a basis of game/logic calculations instead. + * + * @property {integer} elapsedMS + * @protected + */ this.elapsedMS = 0; /** - * The physics update delta, in fractional seconds. - * - * This should be used as an applicable multiplier by all logic update steps (eg. `preUpdate/postUpdate/update`) - * to ensure consistent game timing. Game/logic timing can drift from real-world time if the system - * is unable to consistently maintain the desired FPS. - * - * With fixed-step updates this is normally equivalent to `1.0 / desiredFps`. - * - * @property {number} physicsElapsed - */ + * The physics update delta, in fractional seconds. + * + * This should be used as an applicable multiplier by all logic update steps (eg. `preUpdate/postUpdate/update`) + * to ensure consistent game timing. Game/logic timing can drift from real-world time if the system + * is unable to consistently maintain the desired FPS. + * + * With fixed-step updates this is normally equivalent to `1.0 / desiredFps`. + * + * @property {number} physicsElapsed + */ this.physicsElapsed = 1 / 60; /** - * The physics update delta, in milliseconds - equivalent to `physicsElapsed * 1000`. - * - * @property {number} physicsElapsedMS - */ + * The physics update delta, in milliseconds - equivalent to `physicsElapsed * 1000`. + * + * @property {number} physicsElapsedMS + */ this.physicsElapsedMS = (1 / 60) * 1000; /** - * The desiredFps multiplier as used by Game.update. - * @property {integer} desiredFpsMult - * @protected - */ + * The desiredFps multiplier as used by Game.update. + * @property {integer} desiredFpsMult + * @protected + */ this.desiredFpsMult = 1.0 / 60; /** - * The desired frame rate of the game. - * - * This is used is used to calculate the physic/logic multiplier and how to apply catch-up logic updates. - * - * @property {number} _desiredFps - * @private - * @default - */ + * The desired frame rate of the game. + * + * This is used is used to calculate the physic/logic multiplier and how to apply catch-up logic updates. + * + * @property {number} _desiredFps + * @private + * @default + */ this._desiredFps = 60; /** - * The suggested frame rate for your game, based on an averaged real frame rate. - * This value is only populated if `Time.advancedTiming` is enabled. - * - * _Note:_ This is not available until after a few frames have passed; until then - * it's set to the same value as desiredFps. - * - * @property {number} suggestedFps - * @default - */ + * The suggested frame rate for your game, based on an averaged real frame rate. + * This value is only populated if `Time.advancedTiming` is enabled. + * + * _Note:_ This is not available until after a few frames have passed; until then + * it's set to the same value as desiredFps. + * + * @property {number} suggestedFps + * @default + */ this.suggestedFps = this.desiredFps; /** - * Scaling factor to make the game move smoothly in slow motion (or fast motion) - * - * - 1.0 = normal speed - * - 2.0 = half speed - * - 0.5 = double speed - * - * You likely need to adjust {@link #desiredFps} as well such that `desiredFps / slowMotion === 60`. - * - * @property {number} slowMotion - * @default - */ + * Scaling factor to make the game move smoothly in slow motion (or fast motion) + * + * - 1.0 = normal speed + * - 2.0 = half speed + * - 0.5 = double speed + * + * You likely need to adjust {@link #desiredFps} as well such that `desiredFps / slowMotion === 60`. + * + * @property {number} slowMotion + * @default + */ this.slowMotion = 1.0; /** - * If true then advanced profiling, including the fps rate, fps min/max, suggestedFps and msMin/msMax are updated. This isn't expensive, but displaying it with {@link Phaser.Utils.Debug#text} can be, especially in WebGL mode. - * @property {boolean} advancedTiming - * @default - */ + * If true then advanced profiling, including the fps rate, fps min/max, suggestedFps and msMin/msMax are updated. This isn't expensive, but displaying it with {@link Phaser.Utils.Debug#text} can be, especially in WebGL mode. + * @property {boolean} advancedTiming + * @default + */ this.advancedTiming = false; /** - * Advanced timing result: The number of animation frames received from the browser in the last second. - * - * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled. - * @property {integer} frames - * @readonly - */ + * Advanced timing result: The number of animation frames received from the browser in the last second. + * + * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled. + * @property {integer} frames + * @readonly + */ this.frames = 0; /** - * Advanced timing result: The number of {@link Phaser.Game#updateLogic logic updates} made in the last second. - * - * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled. - * @property {integer} updates - * @readonly - */ + * Advanced timing result: The number of {@link Phaser.Game#updateLogic logic updates} made in the last second. + * + * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled. + * @property {integer} updates + * @readonly + */ this.updates = 0; /** - * Advanced timing result: The number of {@link Phaser.Game#updateRender renders} made in the last second. - * - * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled. - * @property {integer} renders - * @readonly - */ + * Advanced timing result: The number of {@link Phaser.Game#updateRender renders} made in the last second. + * + * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled. + * @property {integer} renders + * @readonly + */ this.renders = 0; /** - * Advanced timing result: Frames per second. - * - * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled. - * @property {number} fps - * @readonly - */ + * Advanced timing result: Frames per second. + * + * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled. + * @property {number} fps + * @readonly + */ this.fps = 0; /** - * Advanced timing result: Logic updates per second. - * - * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled. - * @property {number} ups - * @readonly - */ + * Advanced timing result: Logic updates per second. + * + * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled. + * @property {number} ups + * @readonly + */ this.ups = 0; /** - * Advanced timing result: Renders per second. - * - * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled. - * @property {number} rps - * @readonly - */ + * Advanced timing result: Renders per second. + * + * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled. + * @property {number} rps + * @readonly + */ this.rps = 0; /** - * Advanced timing result: The lowest rate the fps has dropped to. - * - * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled. - * This value can be manually reset. - * @property {number} fpsMin - */ + * Advanced timing result: The lowest rate the fps has dropped to. + * + * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled. + * This value can be manually reset. + * @property {number} fpsMin + */ this.fpsMin = 1000; /** - * Advanced timing result: The highest rate the fps has reached (usually no higher than 60fps). - * - * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled. - * This value can be manually reset. - * @property {number} fpsMax - */ + * Advanced timing result: The highest rate the fps has reached (usually no higher than 60fps). + * + * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled. + * This value can be manually reset. + * @property {number} fpsMax + */ this.fpsMax = 0; /** - * Advanced timing result: The minimum amount of time the game has taken between consecutive frames. - * - * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled. - * This value can be manually reset. - * @property {number} msMin - * @default - */ + * Advanced timing result: The minimum amount of time the game has taken between consecutive frames. + * + * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled. + * This value can be manually reset. + * @property {number} msMin + * @default + */ this.msMin = 1000; /** - * Advanced timing result: The maximum amount of time the game has taken between consecutive frames. - * - * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled. - * This value can be manually reset. - * @property {number} msMax - */ + * Advanced timing result: The maximum amount of time the game has taken between consecutive frames. + * + * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled. + * This value can be manually reset. + * @property {number} msMax + */ this.msMax = 0; /** - * Records how long the game was last paused, in milliseconds. - * (This is not updated until the game is resumed.) - * @property {number} pauseDuration - */ + * Records how long the game was last paused, in milliseconds. + * (This is not updated until the game is resumed.) + * @property {number} pauseDuration + */ this.pauseDuration = 0; /** - * @property {number} timeToCall - The value that setTimeout needs to work out when to next update - * @protected - */ + * @property {number} timeToCall - The value that setTimeout needs to work out when to next update + * @protected + */ this.timeToCall = 0; /** - * @property {number} timeExpected - The time when the next call is expected when using setTimer to control the update loop - * @protected - */ + * @property {number} timeExpected - The time when the next call is expected when using setTimer to control the update loop + * @protected + */ this.timeExpected = 0; /** - * A {@link Phaser.Timer} object bound to the master clock (this Time object) which events can be added to. - * @property {Phaser.Timer} events - */ + * A {@link Phaser.Timer} object bound to the master clock (this Time object) which events can be added to. + * @property {Phaser.Timer} events + */ this.events = new Phaser.Timer(this.game, false); /** - * @property {number} _frameCount - count the number of calls to time.update since the last suggestedFps was calculated - * @private - */ + * @property {number} _frameCount - count the number of calls to time.update since the last suggestedFps was calculated + * @private + */ this._frameCount = 0; /** - * @property {number} _elapsedAcumulator - sum of the elapsed time since the last suggestedFps was calculated - * @private - */ + * @property {number} _elapsedAcumulator - sum of the elapsed time since the last suggestedFps was calculated + * @private + */ this._elapsedAccumulator = 0; /** - * @property {number} _started - The time at which the Game instance started. - * @private - */ + * @property {number} _started - The time at which the Game instance started. + * @private + */ this._started = 0; /** - * @property {number} _timeLastSecond - The time (in ms) that the last second counter ticked over. - * @private - */ + * @property {number} _timeLastSecond - The time (in ms) that the last second counter ticked over. + * @private + */ this._timeLastSecond = 0; /** - * @property {number} _pauseStarted - The time the game started being paused. - * @private - */ + * @property {number} _pauseStarted - The time the game started being paused. + * @private + */ this._pauseStarted = 0; /** - * @property {boolean} _justResumed - Internal value used to recover from the game pause state. - * @private - */ + * @property {boolean} _justResumed - Internal value used to recover from the game pause state. + * @private + */ this._justResumed = false; /** - * @property {Phaser.Timer[]} _timers - Internal store of Phaser.Timer objects. - * @private - */ + * @property {Phaser.Timer[]} _timers - Internal store of Phaser.Timer objects. + * @private + */ this._timers = []; - }; Phaser.Time.prototype = { /** - * Called automatically by Phaser.Game after boot. Should not be called directly. - * - * @method Phaser.Time#boot - * @protected - */ + * Called automatically by Phaser.Game after boot. Should not be called directly. + * + * @method Phaser.Time#boot + * @protected + */ boot: function () { - this._started = Date.now(); this.time = Date.now(); this.events.start(); this.timeExpected = this.time; - }, /** - * Adds an existing Phaser.Timer object to the Timer pool. - * - * @method Phaser.Time#add - * @param {Phaser.Timer} timer - An existing Phaser.Timer object. - * @return {Phaser.Timer} The given Phaser.Timer object. - */ + * Adds an existing Phaser.Timer object to the Timer pool. + * + * @method Phaser.Time#add + * @param {Phaser.Timer} timer - An existing Phaser.Timer object. + * @return {Phaser.Timer} The given Phaser.Timer object. + */ add: function (timer) { - this._timers.push(timer); return timer; - }, /** - * Creates a new stand-alone Phaser.Timer object. - * - * @method Phaser.Time#create - * @param {boolean} [autoDestroy=true] - A Timer that is set to automatically destroy itself will do so after all of its events have been dispatched (assuming no looping events). - * @return {Phaser.Timer} The Timer object that was created. - */ + * Creates a new stand-alone Phaser.Timer object. + * + * @method Phaser.Time#create + * @param {boolean} [autoDestroy=true] - A Timer that is set to automatically destroy itself will do so after all of its events have been dispatched (assuming no looping events). + * @return {Phaser.Timer} The Timer object that was created. + */ create: function (autoDestroy) { - if (autoDestroy === undefined) { autoDestroy = true; } var timer = new Phaser.Timer(this.game, autoDestroy); @@ -385,17 +378,15 @@ Phaser.Time.prototype = { this._timers.push(timer); return timer; - }, /** - * Remove all Timer objects, regardless of their state and clears all Timers from the {@link Phaser.Time#events events} timer. - * - * @method Phaser.Time#removeAll - */ + * Remove all Timer objects, regardless of their state and clears all Timers from the {@link Phaser.Time#events events} timer. + * + * @method Phaser.Time#removeAll + */ removeAll: function () { - for (var i = 0; i < this._timers.length; i++) { this._timers[i].destroy(); @@ -404,17 +395,15 @@ Phaser.Time.prototype = { this._timers = []; this.events.removeAll(); - }, /** - * Refreshes the Time.time and Time.elapsedMS properties from the system clock. - * - * @method Phaser.Time#refresh - */ + * Refreshes the Time.time and Time.elapsedMS properties from the system clock. + * + * @method Phaser.Time#refresh + */ refresh: function () { - // Set to the old Date.now value var previousDateNow = this.time; @@ -423,19 +412,17 @@ Phaser.Time.prototype = { // Adjust accordingly. this.elapsedMS = this.time - previousDateNow; - }, /** - * Updates the game clock and if enabled the advanced timing data. This is called automatically by Phaser.Game. - * - * @method Phaser.Time#update - * @protected - * @param {number} time - The current relative timestamp; see {@link Phaser.Time#now now}. - */ + * Updates the game clock and if enabled the advanced timing data. This is called automatically by Phaser.Game. + * + * @method Phaser.Time#update + * @protected + * @param {number} time - The current relative timestamp; see {@link Phaser.Time#now now}. + */ update: function (time) { - // Set to the old Date.now value var previousDateNow = this.time; @@ -448,8 +435,10 @@ Phaser.Time.prototype = { // 'now' is currently still holding the time of the last call, move it into prevTime this.prevTime = this.now; - // update 'now' to hold the current time - // this.now may hold the RAF high resolution time value if RAF is available (otherwise it also holds Date.now) + /* + * update 'now' to hold the current time + * this.now may hold the RAF high resolution time value if RAF is available (otherwise it also holds Date.now) + */ this.now = time; // elapsed time between previous call and now - this could be a high resolution value @@ -484,19 +473,17 @@ Phaser.Time.prototype = { this.updateTimers(); } } - }, /** - * Handles the updating of the Phaser.Timers (if any) - * Called automatically by Time.update. - * - * @method Phaser.Time#updateTimers - * @private - */ + * Handles the updating of the Phaser.Timers (if any) + * Called automatically by Time.update. + * + * @method Phaser.Time#updateTimers + * @private + */ updateTimers: function () { - // Any game level timers var i = 0; var len = this._timers.length; @@ -514,19 +501,17 @@ Phaser.Time.prototype = { len--; } } - }, /** - * Handles the updating of the advanced timing values (if enabled) - * Called automatically by Time.update. - * - * @method Phaser.Time#updateAdvancedTiming - * @private - */ + * Handles the updating of the advanced timing values (if enabled) + * Called automatically by Time.update. + * + * @method Phaser.Time#updateAdvancedTiming + * @private + */ updateAdvancedTiming: function () { - // count the number of time.update calls this._frameCount++; this._elapsedAccumulator += this.elapsed; @@ -558,50 +543,44 @@ Phaser.Time.prototype = { this.updates = 0; this.renders = 0; } - }, /** - * Counts one logic update (if advanced timing is enabled). - * - * @method Phaser.Time#preUpdate - * @private - */ + * Counts one logic update (if advanced timing is enabled). + * + * @method Phaser.Time#preUpdate + * @private + */ preUpdate: function () { - if (this.advancedTiming) { this.updates++; } - }, /** - * Counts one render (if advanced timing is enabled). - * - * @method Phaser.Time#countRender - * @private - */ + * Counts one render (if advanced timing is enabled). + * + * @method Phaser.Time#countRender + * @private + */ preRender: function () { - if (this.advancedTiming) { this.renders++; } - }, /** - * Called when the game enters a paused state. - * - * @method Phaser.Time#gamePaused - * @private - */ + * Called when the game enters a paused state. + * + * @method Phaser.Time#gamePaused + * @private + */ gamePaused: function () { - this._pauseStarted = Date.now(); this.events.pause(); @@ -612,18 +591,16 @@ Phaser.Time.prototype = { { this._timers[i]._pause(); } - }, /** - * Called when the game resumes from a paused state. - * - * @method Phaser.Time#gameResumed - * @private - */ + * Called when the game resumes from a paused state. + * + * @method Phaser.Time#gameResumed + * @private + */ gameResumed: function () { - // Set the parameter which stores Date.now() to make sure it's correct on resume this.time = Date.now(); @@ -637,92 +614,87 @@ Phaser.Time.prototype = { { this._timers[i]._resume(); } - }, /** - * The number of seconds that have elapsed since the game was started. - * - * @method Phaser.Time#totalElapsedSeconds - * @return {number} The number of seconds that have elapsed since the game was started. - */ + * The number of seconds that have elapsed since the game was started. + * + * @method Phaser.Time#totalElapsedSeconds + * @return {number} The number of seconds that have elapsed since the game was started. + */ totalElapsedSeconds: function () { return (this.time - this._started) * 0.001; }, /** - * How long has passed since the given time. - * - * @method Phaser.Time#elapsedSince - * @param {number} since - The time you want to measure against. - * @return {number} The difference between the given time and now. - */ + * How long has passed since the given time. + * + * @method Phaser.Time#elapsedSince + * @param {number} since - The time you want to measure against. + * @return {number} The difference between the given time and now. + */ elapsedSince: function (since) { return this.time - since; }, /** - * How long has passed since the given time (in seconds). - * - * @method Phaser.Time#elapsedSecondsSince - * @param {number} since - The time you want to measure (in seconds). - * @return {number} Duration between given time and now (in seconds). - */ + * How long has passed since the given time (in seconds). + * + * @method Phaser.Time#elapsedSecondsSince + * @param {number} since - The time you want to measure (in seconds). + * @return {number} Duration between given time and now (in seconds). + */ elapsedSecondsSince: function (since) { return (this.time - since) * 0.001; }, /** - * Resets the private _started value to now and removes all currently running Timers. - * - * @method Phaser.Time#reset - */ + * Resets the private _started value to now and removes all currently running Timers. + * + * @method Phaser.Time#reset + */ reset: function () { - this._started = this.time; this.removeAll(); - } }; /** -* The number of logic updates per second. -* -* This is used is used to calculate the physic / logic multiplier and how to apply catch-up logic updates. -* -* The render rate is unaffected unless you also turn off {@link Phaser.Game#forceSingleRender}. -* -* @name Phaser.Time#desiredFps -* @type {integer} -* @default 60 -*/ + * The number of logic updates per second. + * + * This is used is used to calculate the physic / logic multiplier and how to apply catch-up logic updates. + * + * The render rate is unaffected unless you also turn off {@link Phaser.Game#forceSingleRender}. + * + * @name Phaser.Time#desiredFps + * @type {integer} + * @default 60 + */ Object.defineProperty(Phaser.Time.prototype, 'desiredFps', { get: function () { - return this._desiredFps; - }, set: function (value) { - this._desiredFps = value; - // Set the physics elapsed time... this will always be 1 / this.desiredFps - // because we're using fixed time steps in game.update + /* + * Set the physics elapsed time... this will always be 1 / this.desiredFps + * because we're using fixed time steps in game.update + */ this.physicsElapsed = 1 / value; this.physicsElapsedMS = this.physicsElapsed * 1000; this.desiredFpsMult = 1.0 / value; - } }); diff --git a/src/time/Timer.js b/src/time/Timer.js index e90c84f75..1b5d5415a 100644 --- a/src/time/Timer.js +++ b/src/time/Timer.js @@ -1,207 +1,204 @@ /** -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* A Timer is a way to create and manage {@link Phaser.TimerEvent timer events} that wait for a specific duration and then run a callback. -* Many different timer events, with individual delays, can be added to the same Timer. -* -* All Timer delays are in milliseconds (there are 1000 ms in 1 second); so a delay value of 250 represents a quarter of a second. -* -* Timers are based on real life time, adjusted for game pause durations. -* That is, *timer events are based on elapsed {@link Phaser.Time game time}* and do *not* take physics time or slow motion into account. -* -* @class Phaser.Timer -* @constructor -* @param {Phaser.Game} game - A reference to the currently running game. -* @param {boolean} [autoDestroy=true] - If true, the timer will automatically destroy itself after all the events have been dispatched (assuming no looping events). -*/ + * A Timer is a way to create and manage {@link Phaser.TimerEvent timer events} that wait for a specific duration and then run a callback. + * Many different timer events, with individual delays, can be added to the same Timer. + * + * All Timer delays are in milliseconds (there are 1000 ms in 1 second); so a delay value of 250 represents a quarter of a second. + * + * Timers are based on real life time, adjusted for game pause durations. + * That is, *timer events are based on elapsed {@link Phaser.Time game time}* and do *not* take physics time or slow motion into account. + * + * @class Phaser.Timer + * @constructor + * @param {Phaser.Game} game - A reference to the currently running game. + * @param {boolean} [autoDestroy=true] - If true, the timer will automatically destroy itself after all the events have been dispatched (assuming no looping events). + */ Phaser.Timer = function (game, autoDestroy) { - if (autoDestroy === undefined) { autoDestroy = true; } /** - * @property {Phaser.Game} game - Local reference to game. - * @protected - */ + * @property {Phaser.Game} game - Local reference to game. + * @protected + */ this.game = game; /** - * True if the Timer is actively running. - * - * Do not modify this boolean - use {@link Phaser.Timer#pause pause} (and {@link Phaser.Timer#resume resume}) to pause the timer. - * @property {boolean} running - * @default - * @readonly - */ + * True if the Timer is actively running. + * + * Do not modify this boolean - use {@link Phaser.Timer#pause pause} (and {@link Phaser.Timer#resume resume}) to pause the timer. + * @property {boolean} running + * @default + * @readonly + */ this.running = false; /** - * If true, the timer will automatically destroy itself after all the events have been dispatched (assuming no looping events). - * @property {boolean} autoDestroy - */ + * If true, the timer will automatically destroy itself after all the events have been dispatched (assuming no looping events). + * @property {boolean} autoDestroy + */ this.autoDestroy = autoDestroy; /** - * @property {boolean} expired - An expired Timer is one in which all of its events have been dispatched and none are pending. - * @readonly - * @default - */ + * @property {boolean} expired - An expired Timer is one in which all of its events have been dispatched and none are pending. + * @readonly + * @default + */ this.expired = false; /** - * @property {number} elapsed - Elapsed time since the last frame (in ms). - * @protected - */ + * @property {number} elapsed - Elapsed time since the last frame (in ms). + * @protected + */ this.elapsed = 0; /** - * @property {Phaser.TimerEvent[]} events - An array holding all of this timers Phaser.TimerEvent objects. Use the methods add, repeat and loop to populate it. - */ + * @property {Phaser.TimerEvent[]} events - An array holding all of this timers Phaser.TimerEvent objects. Use the methods add, repeat and loop to populate it. + */ this.events = []; /** - * This signal will be dispatched when this Timer has completed which means that there are no more events in the queue. - * - * The signal is supplied with one argument, `timer`, which is this Timer object. - * - * @property {Phaser.Signal} onComplete - */ + * This signal will be dispatched when this Timer has completed which means that there are no more events in the queue. + * + * The signal is supplied with one argument, `timer`, which is this Timer object. + * + * @property {Phaser.Signal} onComplete + */ this.onComplete = new Phaser.Signal(); /** - * @property {number} nextTick - The time the next tick will occur. - * @readonly - * @protected - */ + * @property {number} nextTick - The time the next tick will occur. + * @readonly + * @protected + */ this.nextTick = 0; /** - * @property {number} timeCap - If the difference in time between two frame updates exceeds this value, the event times are reset to avoid catch-up situations. - */ + * @property {number} timeCap - If the difference in time between two frame updates exceeds this value, the event times are reset to avoid catch-up situations. + */ this.timeCap = 1000; /** - * @property {boolean} paused - The paused state of the Timer. You can pause the timer by calling Timer.pause() and Timer.resume() or by the game pausing. - * @readonly - * @default - */ + * @property {boolean} paused - The paused state of the Timer. You can pause the timer by calling Timer.pause() and Timer.resume() or by the game pausing. + * @readonly + * @default + */ this.paused = false; /** - * @property {boolean} _codePaused - Was the Timer paused by code or by Game focus loss? - * @private - */ + * @property {boolean} _codePaused - Was the Timer paused by code or by Game focus loss? + * @private + */ this._codePaused = false; /** - * @property {number} _started - The time at which this Timer instance started running. - * @private - * @default - */ + * @property {number} _started - The time at which this Timer instance started running. + * @private + * @default + */ this._started = 0; /** - * @property {number} _pauseStarted - The time the game started being paused. - * @private - */ + * @property {number} _pauseStarted - The time the game started being paused. + * @private + */ this._pauseStarted = 0; /** - * @property {number} _pauseTotal - Total paused time. - * @private - */ + * @property {number} _pauseTotal - Total paused time. + * @private + */ this._pauseTotal = 0; /** - * @property {number} _now - The current start-time adjusted time. - * @private - */ + * @property {number} _now - The current start-time adjusted time. + * @private + */ this._now = Date.now(); /** - * @property {number} _len - Temp. array length variable. - * @private - */ + * @property {number} _len - Temp. array length variable. + * @private + */ this._len = 0; /** - * @property {number} _marked - Temp. counter variable. - * @private - */ + * @property {number} _marked - Temp. counter variable. + * @private + */ this._marked = 0; /** - * @property {number} _i - Temp. array counter variable. - * @private - */ + * @property {number} _i - Temp. array counter variable. + * @private + */ this._i = 0; /** - * @property {number} _diff - Internal cache var. - * @private - */ + * @property {number} _diff - Internal cache var. + * @private + */ this._diff = 0; /** - * @property {number} _newTick - Internal cache var. - * @private - */ + * @property {number} _newTick - Internal cache var. + * @private + */ this._newTick = 0; - }; /** -* Number of milliseconds in a minute. -* @constant -* @type {integer} -*/ + * Number of milliseconds in a minute. + * @constant + * @type {integer} + */ Phaser.Timer.MINUTE = 60000; /** -* Number of milliseconds in a second. -* @constant -* @type {integer} -*/ + * Number of milliseconds in a second. + * @constant + * @type {integer} + */ Phaser.Timer.SECOND = 1000; /** -* Number of milliseconds in half a second. -* @constant -* @type {integer} -*/ + * Number of milliseconds in half a second. + * @constant + * @type {integer} + */ Phaser.Timer.HALF = 500; /** -* Number of milliseconds in a quarter of a second. -* @constant -* @type {integer} -*/ + * Number of milliseconds in a quarter of a second. + * @constant + * @type {integer} + */ Phaser.Timer.QUARTER = 250; Phaser.Timer.prototype = { /** - * Creates a new TimerEvent on this Timer. - * - * Use {@link Phaser.Timer#add}, {@link Phaser.Timer#repeat}, or {@link Phaser.Timer#loop} methods to create a new event. - * - * @method Phaser.Timer#create - * @private - * @param {integer} delay - The number of milliseconds, in {@link Phaser.Time game time}, before the timer event occurs. - * @param {boolean} loop - Should the event loop or not? - * @param {number} repeatCount - The number of times the event will repeat. - * @param {function} callback - The callback that will be called when the timer event occurs. - * @param {object} callbackContext - The context in which the callback will be called. - * @param {any[]} arguments - The values to be sent to your callback function when it is called. - * @return {Phaser.TimerEvent} The Phaser.TimerEvent object that was created. - */ + * Creates a new TimerEvent on this Timer. + * + * Use {@link Phaser.Timer#add}, {@link Phaser.Timer#repeat}, or {@link Phaser.Timer#loop} methods to create a new event. + * + * @method Phaser.Timer#create + * @private + * @param {integer} delay - The number of milliseconds, in {@link Phaser.Time game time}, before the timer event occurs. + * @param {boolean} loop - Should the event loop or not? + * @param {number} repeatCount - The number of times the event will repeat. + * @param {function} callback - The callback that will be called when the timer event occurs. + * @param {object} callbackContext - The context in which the callback will be called. + * @param {any[]} arguments - The values to be sent to your callback function when it is called. + * @return {Phaser.TimerEvent} The Phaser.TimerEvent object that was created. + */ create: function (delay, loop, repeatCount, callback, callbackContext, args) { - delay = Math.round(delay); var tick = delay; @@ -224,85 +221,77 @@ Phaser.Timer.prototype = { this.expired = false; return event; - }, /** - * Adds a new Event to this Timer. - * - * The event will fire after the given amount of `delay` in milliseconds has passed, once the Timer has started running. - * The delay is in relation to when the Timer starts, not the time it was added. If the Timer is already running the delay will be calculated based on the timers current time. - * - * Make sure to call {@link Phaser.Timer#start start} after adding all of the Events you require for this Timer. - * - * @method Phaser.Timer#add - * @param {integer} delay - The number of milliseconds, in {@link Phaser.Time game time}, before the timer event occurs. - * @param {function} callback - The callback that will be called when the timer event occurs. - * @param {object} callbackContext - The context in which the callback will be called. - * @param {...*} arguments - Additional arguments that will be supplied to the callback. - * @return {Phaser.TimerEvent} The Phaser.TimerEvent object that was created. - */ + * Adds a new Event to this Timer. + * + * The event will fire after the given amount of `delay` in milliseconds has passed, once the Timer has started running. + * The delay is in relation to when the Timer starts, not the time it was added. If the Timer is already running the delay will be calculated based on the timers current time. + * + * Make sure to call {@link Phaser.Timer#start start} after adding all of the Events you require for this Timer. + * + * @method Phaser.Timer#add + * @param {integer} delay - The number of milliseconds, in {@link Phaser.Time game time}, before the timer event occurs. + * @param {function} callback - The callback that will be called when the timer event occurs. + * @param {object} callbackContext - The context in which the callback will be called. + * @param {...*} arguments - Additional arguments that will be supplied to the callback. + * @return {Phaser.TimerEvent} The Phaser.TimerEvent object that was created. + */ add: function (delay, callback, callbackContext) { - return this.create(delay, false, 0, callback, callbackContext, Array.prototype.slice.call(arguments, 3)); - }, /** - * Adds a new TimerEvent that will always play through once and then repeat for the given number of iterations. - * - * The event will fire after the given amount of `delay` in milliseconds has passed, once the Timer has started running. - * The delay is in relation to when the Timer starts, not the time it was added. - * If the Timer is already running the delay will be calculated based on the timers current time. - * - * Make sure to call {@link Phaser.Timer#start start} after adding all of the Events you require for this Timer. - * - * @method Phaser.Timer#repeat - * @param {integer} delay - The number of milliseconds, in {@link Phaser.Time game time}, before the timer event occurs. - * @param {number} repeatCount - The number of times the event will repeat once is has finished playback. A repeatCount of 1 means it will repeat itself once, playing the event twice in total. - * @param {function} callback - The callback that will be called when the timer event occurs. - * @param {object} callbackContext - The context in which the callback will be called. - * @param {...*} arguments - Additional arguments that will be supplied to the callback. - * @return {Phaser.TimerEvent} The Phaser.TimerEvent object that was created. - */ + * Adds a new TimerEvent that will always play through once and then repeat for the given number of iterations. + * + * The event will fire after the given amount of `delay` in milliseconds has passed, once the Timer has started running. + * The delay is in relation to when the Timer starts, not the time it was added. + * If the Timer is already running the delay will be calculated based on the timers current time. + * + * Make sure to call {@link Phaser.Timer#start start} after adding all of the Events you require for this Timer. + * + * @method Phaser.Timer#repeat + * @param {integer} delay - The number of milliseconds, in {@link Phaser.Time game time}, before the timer event occurs. + * @param {number} repeatCount - The number of times the event will repeat once is has finished playback. A repeatCount of 1 means it will repeat itself once, playing the event twice in total. + * @param {function} callback - The callback that will be called when the timer event occurs. + * @param {object} callbackContext - The context in which the callback will be called. + * @param {...*} arguments - Additional arguments that will be supplied to the callback. + * @return {Phaser.TimerEvent} The Phaser.TimerEvent object that was created. + */ repeat: function (delay, repeatCount, callback, callbackContext) { - return this.create(delay, false, repeatCount, callback, callbackContext, Array.prototype.slice.call(arguments, 4)); - }, /** - * Adds a new looped Event to this Timer that will repeat forever or until the Timer is stopped. - * - * The event will fire after the given amount of `delay` in milliseconds has passed, once the Timer has started running. - * The delay is in relation to when the Timer starts, not the time it was added. If the Timer is already running the delay will be calculated based on the timers current time. - * - * Make sure to call {@link Phaser.Timer#start start} after adding all of the Events you require for this Timer. - * - * @method Phaser.Timer#loop - * @param {integer} delay - The number of milliseconds, in {@link Phaser.Time game time}, before the timer event occurs. - * @param {function} callback - The callback that will be called when the timer event occurs. - * @param {object} callbackContext - The context in which the callback will be called. - * @param {...*} arguments - Additional arguments that will be supplied to the callback. - * @return {Phaser.TimerEvent} The Phaser.TimerEvent object that was created. - */ + * Adds a new looped Event to this Timer that will repeat forever or until the Timer is stopped. + * + * The event will fire after the given amount of `delay` in milliseconds has passed, once the Timer has started running. + * The delay is in relation to when the Timer starts, not the time it was added. If the Timer is already running the delay will be calculated based on the timers current time. + * + * Make sure to call {@link Phaser.Timer#start start} after adding all of the Events you require for this Timer. + * + * @method Phaser.Timer#loop + * @param {integer} delay - The number of milliseconds, in {@link Phaser.Time game time}, before the timer event occurs. + * @param {function} callback - The callback that will be called when the timer event occurs. + * @param {object} callbackContext - The context in which the callback will be called. + * @param {...*} arguments - Additional arguments that will be supplied to the callback. + * @return {Phaser.TimerEvent} The Phaser.TimerEvent object that was created. + */ loop: function (delay, callback, callbackContext) { - return this.create(delay, true, 0, callback, callbackContext, Array.prototype.slice.call(arguments, 3)); - }, /** - * Starts this Timer running. - * @method Phaser.Timer#start - * @param {integer} [delay=0] - The number of milliseconds, in {@link Phaser.Time game time}, that should elapse before the Timer will start. - */ + * Starts this Timer running. + * @method Phaser.Timer#start + * @param {integer} [delay=0] - The number of milliseconds, in {@link Phaser.Time game time}, that should elapse before the Timer will start. + */ start: function (delay) { - if (this.running) { return; @@ -316,17 +305,15 @@ Phaser.Timer.prototype = { { this.events[i].tick = this.events[i].delay + this._started; } - }, /** - * Stops this Timer from running. Does not cause it to be destroyed if autoDestroy is set to true. - * @method Phaser.Timer#stop - * @param {boolean} [clearEvents=true] - If true all the events in Timer will be cleared, otherwise they will remain. - */ + * Stops this Timer from running. Does not cause it to be destroyed if autoDestroy is set to true. + * @method Phaser.Timer#stop + * @param {boolean} [clearEvents=true] - If true all the events in Timer will be cleared, otherwise they will remain. + */ stop: function (clearEvents) { - this.running = false; if (clearEvents === undefined) { clearEvents = true; } @@ -335,17 +322,15 @@ Phaser.Timer.prototype = { { this.events.length = 0; } - }, /** - * Removes a pending TimerEvent from the queue. - * @param {Phaser.TimerEvent} event - The event to remove from the queue. - * @method Phaser.Timer#remove - */ + * Removes a pending TimerEvent from the queue. + * @param {Phaser.TimerEvent} event - The event to remove from the queue. + * @method Phaser.Timer#remove + */ remove: function (event) { - for (var i = 0; i < this.events.length; i++) { if (this.events[i] === event) @@ -356,18 +341,16 @@ Phaser.Timer.prototype = { } return false; - }, /** - * Orders the events on this Timer so they are in tick order. - * This is called automatically when new events are created. - * @method Phaser.Timer#order - * @protected - */ + * Orders the events on this Timer so they are in tick order. + * This is called automatically when new events are created. + * @method Phaser.Timer#order + * @protected + */ order: function () { - if (this.events.length > 0) { // Sort the events so the one with the lowest tick is first @@ -375,17 +358,15 @@ Phaser.Timer.prototype = { this.nextTick = this.events[0].tick; } - }, /** - * Sort handler used by Phaser.Timer.order. - * @method Phaser.Timer#sortHandler - * @private - */ + * Sort handler used by Phaser.Timer.order. + * @method Phaser.Timer#sortHandler + * @private + */ sortHandler: function (a, b) { - if (a.tick < b.tick) { return -1; @@ -396,18 +377,16 @@ Phaser.Timer.prototype = { } return 0; - }, /** - * Clears any events from the Timer which have pendingDelete set to true and then resets the private _len and _i values. - * - * @method Phaser.Timer#clearPendingEvents - * @protected - */ + * Clears any events from the Timer which have pendingDelete set to true and then resets the private _len and _i values. + * + * @method Phaser.Timer#clearPendingEvents + * @protected + */ clearPendingEvents: function () { - this._i = this.events.length; while (this._i--) @@ -420,20 +399,18 @@ Phaser.Timer.prototype = { this._len = this.events.length; this._i = 0; - }, /** - * The main Timer update event, called automatically by Phaser.Time.update. - * - * @method Phaser.Timer#update - * @protected - * @param {number} time - The time from the core game clock. - * @return {boolean} True if there are still events waiting to be dispatched, otherwise false if this Timer can be destroyed. - */ + * The main Timer update event, called automatically by Phaser.Time.update. + * + * @method Phaser.Timer#update + * @protected + * @param {number} time - The time from the core game clock. + * @return {boolean} True if there are still events waiting to be dispatched, otherwise false if this Timer can be destroyed. + */ update: function (time) { - if (this.paused) { return true; @@ -445,9 +422,11 @@ Phaser.Timer.prototype = { // spike-dislike if (this.elapsed > this.timeCap) { - // For some reason the time between now and the last time the game was updated was larger than our timeCap. - // This can happen if the Stage.disableVisibilityChange is true and you swap tabs, which makes the raf pause. - // In this case we need to adjust the TimerEvents and nextTick. + /* + * For some reason the time between now and the last time the game was updated was larger than our timeCap. + * This can happen if the Stage.disableVisibilityChange is true and you swap tabs, which makes the raf pause. + * In this case we need to adjust the TimerEvents and nextTick. + */ this.adjustEvents(time - this.elapsed); } @@ -518,16 +497,14 @@ Phaser.Timer.prototype = { { return true; } - }, /** - * Pauses the Timer and all events in the queue. - * @method Phaser.Timer#pause - */ + * Pauses the Timer and all events in the queue. + * @method Phaser.Timer#pause + */ pause: function () { - if (!this.running) { return; @@ -543,17 +520,15 @@ Phaser.Timer.prototype = { this._pauseStarted = this.game.time.time; this.paused = true; - }, /** - * Internal pause/resume control - user code should use Timer.pause instead. - * @method Phaser.Timer#_pause - * @private - */ + * Internal pause/resume control - user code should use Timer.pause instead. + * @method Phaser.Timer#_pause + * @private + */ _pause: function () { - if (this.paused || !this.running) { return; @@ -562,18 +537,16 @@ Phaser.Timer.prototype = { this._pauseStarted = this.game.time.time; this.paused = true; - }, /** - * Adjusts the time of all pending events and the nextTick by the given baseTime. - * - * @method Phaser.Timer#adjustEvents - * @protected - */ + * Adjusts the time of all pending events and the nextTick by the given baseTime. + * + * @method Phaser.Timer#adjustEvents + * @protected + */ adjustEvents: function (baseTime) { - for (var i = 0; i < this.events.length; i++) { if (!this.events[i].pendingDelete) @@ -601,17 +574,15 @@ Phaser.Timer.prototype = { { this.nextTick = this._now + d; } - }, /** - * Resumes the Timer and updates all pending events. - * - * @method Phaser.Timer#resume - */ + * Resumes the Timer and updates all pending events. + * + * @method Phaser.Timer#resume + */ resume: function () { - if (!this.paused) { return; @@ -625,17 +596,15 @@ Phaser.Timer.prototype = { this.paused = false; this._codePaused = false; - }, /** - * Internal pause/resume control - user code should use Timer.resume instead. - * @method Phaser.Timer#_resume - * @private - */ + * Internal pause/resume control - user code should use Timer.resume instead. + * @method Phaser.Timer#_resume + * @private + */ _resume: function () { - if (this._codePaused) { return; @@ -644,50 +613,45 @@ Phaser.Timer.prototype = { { this.resume(); } - }, /** - * Removes all Events from this Timer and all callbacks linked to onComplete, but leaves the Timer running. - * The onComplete callbacks won't be called. - * - * @method Phaser.Timer#removeAll - */ + * Removes all Events from this Timer and all callbacks linked to onComplete, but leaves the Timer running. + * The onComplete callbacks won't be called. + * + * @method Phaser.Timer#removeAll + */ removeAll: function () { - this.onComplete.removeAll(); this.events.length = 0; this._len = 0; this._i = 0; - }, /** - * Destroys this Timer. Any pending Events are not dispatched. - * The onComplete callbacks won't be called. - * - * @method Phaser.Timer#destroy - */ + * Destroys this Timer. Any pending Events are not dispatched. + * The onComplete callbacks won't be called. + * + * @method Phaser.Timer#destroy + */ destroy: function () { - this.onComplete.removeAll(); this.running = false; this.expired = true; this.events = []; this._len = 0; this._i = 0; - } }; /** -* @name Phaser.Timer#next -* @property {number} next - The time at which the next event will occur. -* @readonly -*/ + * @name Phaser.Timer#next + * @property {number} next - The time at which the next event will occur. + * @readonly + */ Object.defineProperty(Phaser.Timer.prototype, 'next', { get: function () @@ -698,15 +662,14 @@ Object.defineProperty(Phaser.Timer.prototype, 'next', { }); /** -* @name Phaser.Timer#duration -* @property {number} duration - The duration in ms remaining until the next event will occur. -* @readonly -*/ + * @name Phaser.Timer#duration + * @property {number} duration - The duration in ms remaining until the next event will occur. + * @readonly + */ Object.defineProperty(Phaser.Timer.prototype, 'duration', { get: function () { - if (this.running && this.nextTick > this._now) { return this.nextTick - this._now; @@ -715,16 +678,15 @@ Object.defineProperty(Phaser.Timer.prototype, 'duration', { { return 0; } - } }); /** -* @name Phaser.Timer#length -* @property {number} length - The number of pending events in the queue. -* @readonly -*/ + * @name Phaser.Timer#length + * @property {number} length - The number of pending events in the queue. + * @readonly + */ Object.defineProperty(Phaser.Timer.prototype, 'length', { get: function () @@ -735,15 +697,14 @@ Object.defineProperty(Phaser.Timer.prototype, 'length', { }); /** -* @name Phaser.Timer#ms -* @property {number} ms - The duration in milliseconds that this Timer has been running for. -* @readonly -*/ + * @name Phaser.Timer#ms + * @property {number} ms - The duration in milliseconds that this Timer has been running for. + * @readonly + */ Object.defineProperty(Phaser.Timer.prototype, 'ms', { get: function () { - if (this.running) { return this._now - this._started - this._pauseTotal; @@ -752,21 +713,19 @@ Object.defineProperty(Phaser.Timer.prototype, 'ms', { { return 0; } - } }); /** -* @name Phaser.Timer#seconds -* @property {number} seconds - The duration in seconds that this Timer has been running for. -* @readonly -*/ + * @name Phaser.Timer#seconds + * @property {number} seconds - The duration in seconds that this Timer has been running for. + * @readonly + */ Object.defineProperty(Phaser.Timer.prototype, 'seconds', { get: function () { - if (this.running) { return this.ms * 0.001; @@ -775,7 +734,6 @@ Object.defineProperty(Phaser.Timer.prototype, 'seconds', { { return 0; } - } }); diff --git a/src/time/TimerEvent.js b/src/time/TimerEvent.js index f2c943a4f..e82d740a9 100644 --- a/src/time/TimerEvent.js +++ b/src/time/TimerEvent.js @@ -1,81 +1,79 @@ /** -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* A TimerEvent is a single event that is processed by a Phaser.Timer. -* -* It consists of a delay, which is a value in milliseconds after which the event will fire. -* When the event fires it calls a specific callback with the specified arguments. -* -* TimerEvents are removed by their parent timer once finished firing or repeating. -* -* Use {@link Phaser.Timer#add}, {@link Phaser.Timer#repeat}, or {@link Phaser.Timer#loop} methods to create a new event. -* -* @class Phaser.TimerEvent -* @constructor -* @param {Phaser.Timer} timer - The Timer object that this TimerEvent belongs to. -* @param {number} delay - The delay in ms at which this TimerEvent fires. -* @param {number} tick - The tick is the next game clock time that this event will fire at. -* @param {number} repeatCount - If this TimerEvent repeats it will do so this many times. -* @param {boolean} loop - True if this TimerEvent loops, otherwise false. -* @param {function} callback - The callback that will be called when the TimerEvent occurs. -* @param {object} callbackContext - The context in which the callback will be called. -* @param {any[]} arguments - Additional arguments to be passed to the callback. -*/ + * A TimerEvent is a single event that is processed by a Phaser.Timer. + * + * It consists of a delay, which is a value in milliseconds after which the event will fire. + * When the event fires it calls a specific callback with the specified arguments. + * + * TimerEvents are removed by their parent timer once finished firing or repeating. + * + * Use {@link Phaser.Timer#add}, {@link Phaser.Timer#repeat}, or {@link Phaser.Timer#loop} methods to create a new event. + * + * @class Phaser.TimerEvent + * @constructor + * @param {Phaser.Timer} timer - The Timer object that this TimerEvent belongs to. + * @param {number} delay - The delay in ms at which this TimerEvent fires. + * @param {number} tick - The tick is the next game clock time that this event will fire at. + * @param {number} repeatCount - If this TimerEvent repeats it will do so this many times. + * @param {boolean} loop - True if this TimerEvent loops, otherwise false. + * @param {function} callback - The callback that will be called when the TimerEvent occurs. + * @param {object} callbackContext - The context in which the callback will be called. + * @param {any[]} arguments - Additional arguments to be passed to the callback. + */ Phaser.TimerEvent = function (timer, delay, tick, repeatCount, loop, callback, callbackContext, args) { - /** - * @property {Phaser.Timer} timer - The Timer object that this TimerEvent belongs to. - * @protected - * @readonly - */ + * @property {Phaser.Timer} timer - The Timer object that this TimerEvent belongs to. + * @protected + * @readonly + */ this.timer = timer; /** - * @property {number} delay - The delay in ms at which this TimerEvent fires. - */ + * @property {number} delay - The delay in ms at which this TimerEvent fires. + */ this.delay = delay; /** - * @property {number} tick - The tick is the next game clock time that this event will fire at. - */ + * @property {number} tick - The tick is the next game clock time that this event will fire at. + */ this.tick = tick; /** - * @property {number} repeatCount - If this TimerEvent repeats it will do so this many times. - */ + * @property {number} repeatCount - If this TimerEvent repeats it will do so this many times. + */ this.repeatCount = repeatCount - 1; /** - * @property {boolean} loop - True if this TimerEvent loops, otherwise false. - */ + * @property {boolean} loop - True if this TimerEvent loops, otherwise false. + */ this.loop = loop; /** - * @property {function} callback - The callback that will be called when the TimerEvent occurs. - */ + * @property {function} callback - The callback that will be called when the TimerEvent occurs. + */ this.callback = callback; /** - * @property {object} callbackContext - The context in which the callback will be called. - */ + * @property {object} callbackContext - The context in which the callback will be called. + */ this.callbackContext = callbackContext; /** - * @property {any[]} arguments - Additional arguments to be passed to the callback. - */ + * @property {any[]} arguments - Additional arguments to be passed to the callback. + */ this.args = args; /** - * @property {boolean} pendingDelete - A flag that controls if the TimerEvent is pending deletion. - * @protected - */ + * @property {boolean} pendingDelete - A flag that controls if the TimerEvent is pending deletion. + * @protected + */ this.pendingDelete = false; - }; Phaser.TimerEvent.prototype.constructor = Phaser.TimerEvent; diff --git a/src/tween/Easing.js b/src/tween/Easing.js index 1bb1e461d..2eb0feb52 100644 --- a/src/tween/Easing.js +++ b/src/tween/Easing.js @@ -1,429 +1,384 @@ /* jshint curly: false */ /** -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* A collection of easing methods defining ease-in and ease-out curves. -* -* @class Phaser.Easing -*/ + * A collection of easing methods defining ease-in and ease-out curves. + * + * @class Phaser.Easing + */ Phaser.Easing = { /** - * Linear easing. - * - * @class Phaser.Easing.Linear - */ + * Linear easing. + * + * @class Phaser.Easing.Linear + */ Linear: { /** - * Linear Easing (no variation). - * - * @method Phaser.Easing.Linear#None - * @param {number} k - The value to be tweened. - * @returns {number} k. - */ + * Linear Easing (no variation). + * + * @method Phaser.Easing.Linear#None + * @param {number} k - The value to be tweened. + * @returns {number} k. + */ None: function (k) { - return k; - } }, /** - * Quadratic easing. - * - * @class Phaser.Easing.Quadratic - */ + * Quadratic easing. + * + * @class Phaser.Easing.Quadratic + */ Quadratic: { /** - * Ease-in. - * - * @method Phaser.Easing.Quadratic#In - * @param {number} k - The value to be tweened. - * @returns {number} k^2. - */ + * Ease-in. + * + * @method Phaser.Easing.Quadratic#In + * @param {number} k - The value to be tweened. + * @returns {number} k^2. + */ In: function (k) { - return k * k; - }, /** - * Ease-out. - * - * @method Phaser.Easing.Quadratic#Out - * @param {number} k - The value to be tweened. - * @returns {number} k* (2-k). - */ + * Ease-out. + * + * @method Phaser.Easing.Quadratic#Out + * @param {number} k - The value to be tweened. + * @returns {number} k* (2-k). + */ Out: function (k) { - return k * (2 - k); - }, /** - * Ease-in/out. - * - * @method Phaser.Easing.Quadratic#InOut - * @param {number} k - The value to be tweened. - * @returns {number} The tweened value. - */ + * Ease-in/out. + * + * @method Phaser.Easing.Quadratic#InOut + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ InOut: function (k) { - if ((k *= 2) < 1) { return 0.5 * k * k; } return - 0.5 * (--k * (k - 2) - 1); - } }, /** - * Cubic easing. - * - * @class Phaser.Easing.Cubic - */ + * Cubic easing. + * + * @class Phaser.Easing.Cubic + */ Cubic: { /** - * Cubic ease-in. - * - * @method Phaser.Easing.Cubic#In - * @param {number} k - The value to be tweened. - * @returns {number} The tweened value. - */ + * Cubic ease-in. + * + * @method Phaser.Easing.Cubic#In + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ In: function (k) { - return k * k * k; - }, /** - * Cubic ease-out. - * - * @method Phaser.Easing.Cubic#Out - * @param {number} k - The value to be tweened. - * @returns {number} The tweened value. - */ + * Cubic ease-out. + * + * @method Phaser.Easing.Cubic#Out + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ Out: function (k) { - return --k * k * k + 1; - }, /** - * Cubic ease-in/out. - * - * @method Phaser.Easing.Cubic#InOut - * @param {number} k - The value to be tweened. - * @returns {number} The tweened value. - */ + * Cubic ease-in/out. + * + * @method Phaser.Easing.Cubic#InOut + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ InOut: function (k) { - if ((k *= 2) < 1) { return 0.5 * k * k * k; } return 0.5 * ((k -= 2) * k * k + 2); - } }, /** - * Quartic easing. - * - * @class Phaser.Easing.Quartic - */ + * Quartic easing. + * + * @class Phaser.Easing.Quartic + */ Quartic: { /** - * Quartic ease-in. - * - * @method Phaser.Easing.Quartic#In - * @param {number} k - The value to be tweened. - * @returns {number} The tweened value. - */ + * Quartic ease-in. + * + * @method Phaser.Easing.Quartic#In + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ In: function (k) { - return k * k * k * k; - }, /** - * Quartic ease-out. - * - * @method Phaser.Easing.Quartic#Out - * @param {number} k - The value to be tweened. - * @returns {number} The tweened value. - */ + * Quartic ease-out. + * + * @method Phaser.Easing.Quartic#Out + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ Out: function (k) { - return 1 - (--k * k * k * k); - }, /** - * Quartic ease-in/out. - * - * @method Phaser.Easing.Quartic#InOut - * @param {number} k - The value to be tweened. - * @returns {number} The tweened value. - */ + * Quartic ease-in/out. + * + * @method Phaser.Easing.Quartic#InOut + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ InOut: function (k) { - if ((k *= 2) < 1) { return 0.5 * k * k * k * k; } return - 0.5 * ((k -= 2) * k * k * k - 2); - } }, /** - * Quintic easing. - * - * @class Phaser.Easing.Quintic - */ + * Quintic easing. + * + * @class Phaser.Easing.Quintic + */ Quintic: { /** - * Quintic ease-in. - * - * @method Phaser.Easing.Quintic#In - * @param {number} k - The value to be tweened. - * @returns {number} The tweened value. - */ + * Quintic ease-in. + * + * @method Phaser.Easing.Quintic#In + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ In: function (k) { - return k * k * k * k * k; - }, /** - * Quintic ease-out. - * - * @method Phaser.Easing.Quintic#Out - * @param {number} k - The value to be tweened. - * @returns {number} The tweened value. - */ + * Quintic ease-out. + * + * @method Phaser.Easing.Quintic#Out + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ Out: function (k) { - return --k * k * k * k * k + 1; - }, /** - * Quintic ease-in/out. - * - * @method Phaser.Easing.Quintic#InOut - * @param {number} k - The value to be tweened. - * @returns {number} The tweened value. - */ + * Quintic ease-in/out. + * + * @method Phaser.Easing.Quintic#InOut + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ InOut: function (k) { - if ((k *= 2) < 1) { return 0.5 * k * k * k * k * k; } return 0.5 * ((k -= 2) * k * k * k * k + 2); - } }, /** - * Sinusoidal easing. - * - * @class Phaser.Easing.Sinusoidal - */ + * Sinusoidal easing. + * + * @class Phaser.Easing.Sinusoidal + */ Sinusoidal: { /** - * Sinusoidal ease-in. - * - * @method Phaser.Easing.Sinusoidal#In - * @param {number} k - The value to be tweened. - * @returns {number} The tweened value. - */ + * Sinusoidal ease-in. + * + * @method Phaser.Easing.Sinusoidal#In + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ In: function (k) { - if (k === 0) { return 0; } if (k === 1) { return 1; } return 1 - Math.cos(k * Math.PI / 2); - }, /** - * Sinusoidal ease-out. - * - * @method Phaser.Easing.Sinusoidal#Out - * @param {number} k - The value to be tweened. - * @returns {number} The tweened value. - */ + * Sinusoidal ease-out. + * + * @method Phaser.Easing.Sinusoidal#Out + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ Out: function (k) { - if (k === 0) { return 0; } if (k === 1) { return 1; } return Math.sin(k * Math.PI / 2); - }, /** - * Sinusoidal ease-in/out. - * - * @method Phaser.Easing.Sinusoidal#InOut - * @param {number} k - The value to be tweened. - * @returns {number} The tweened value. - */ + * Sinusoidal ease-in/out. + * + * @method Phaser.Easing.Sinusoidal#InOut + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ InOut: function (k) { - if (k === 0) { return 0; } if (k === 1) { return 1; } return 0.5 * (1 - Math.cos(Math.PI * k)); - } }, /** - * Exponential easing. - * - * @class Phaser.Easing.Exponential - */ + * Exponential easing. + * + * @class Phaser.Easing.Exponential + */ Exponential: { /** - * Exponential ease-in. - * - * @method Phaser.Easing.Exponential#In - * @param {number} k - The value to be tweened. - * @returns {number} The tweened value. - */ + * Exponential ease-in. + * + * @method Phaser.Easing.Exponential#In + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ In: function (k) { - return k === 0 ? 0 : Math.pow(1024, k - 1); - }, /** - * Exponential ease-out. - * - * @method Phaser.Easing.Exponential#Out - * @param {number} k - The value to be tweened. - * @returns {number} The tweened value. - */ + * Exponential ease-out. + * + * @method Phaser.Easing.Exponential#Out + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ Out: function (k) { - return k === 1 ? 1 : 1 - Math.pow(2, - 10 * k); - }, /** - * Exponential ease-in/out. - * - * @method Phaser.Easing.Exponential#InOut - * @param {number} k - The value to be tweened. - * @returns {number} The tweened value. - */ + * Exponential ease-in/out. + * + * @method Phaser.Easing.Exponential#InOut + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ InOut: function (k) { - if (k === 0) { return 0; } if (k === 1) { return 1; } if ((k *= 2) < 1) { return 0.5 * Math.pow(1024, k - 1); } return 0.5 * (- Math.pow(2, - 10 * (k - 1)) + 2); - } }, /** - * Circular easing. - * - * @class Phaser.Easing.Circular - */ + * Circular easing. + * + * @class Phaser.Easing.Circular + */ Circular: { /** - * Circular ease-in. - * - * @method Phaser.Easing.Circular#In - * @param {number} k - The value to be tweened. - * @returns {number} The tweened value. - */ + * Circular ease-in. + * + * @method Phaser.Easing.Circular#In + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ In: function (k) { - return 1 - Math.sqrt(1 - k * k); - }, /** - * Circular ease-out. - * - * @method Phaser.Easing.Circular#Out - * @param {number} k - The value to be tweened. - * @returns {number} The tweened value. - */ + * Circular ease-out. + * + * @method Phaser.Easing.Circular#Out + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ Out: function (k) { - return Math.sqrt(1 - (--k * k)); - }, /** - * Circular ease-in/out. - * - * @method Phaser.Easing.Circular#InOut - * @param {number} k - The value to be tweened. - * @returns {number} The tweened value. - */ + * Circular ease-in/out. + * + * @method Phaser.Easing.Circular#InOut + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ InOut: function (k) { - if ((k *= 2) < 1) { return - 0.5 * (Math.sqrt(1 - k * k) - 1); } return 0.5 * (Math.sqrt(1 - (k -= 2) * k) + 1); - } }, /** - * Elastic easing. - * - * @class Phaser.Easing.Elastic - */ + * Elastic easing. + * + * @class Phaser.Easing.Elastic + */ Elastic: { /** - * Elastic ease-in. - * - * @method Phaser.Easing.Elastic#In - * @param {number} k - The value to be tweened. - * @returns {number} The tweened value. - */ + * Elastic ease-in. + * + * @method Phaser.Easing.Elastic#In + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ In: function (k) { - var s, a = 1, p = 0.4; @@ -431,19 +386,17 @@ Phaser.Easing = { if (k === 1) { return 1; } s = p / 4; return - (a * Math.pow(2, 10 * (k -= 1)) * Math.sin((k - s) * (2 * Math.PI) / p)); - }, /** - * Elastic ease-out. - * - * @method Phaser.Easing.Elastic#Out - * @param {number} k - The value to be tweened. - * @returns {number} The tweened value. - */ + * Elastic ease-out. + * + * @method Phaser.Easing.Elastic#Out + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ Out: function (k) { - var s, a = 1, p = 0.4; @@ -451,19 +404,17 @@ Phaser.Easing = { if (k === 1) { return 1; } s = p / 4; return (a * Math.pow(2, - 10 * k) * Math.sin((k - s) * (2 * Math.PI) / p) + 1); - }, /** - * Elastic ease-in/out. - * - * @method Phaser.Easing.Elastic#InOut - * @param {number} k - The value to be tweened. - * @returns {number} The tweened value. - */ + * Elastic ease-in/out. + * + * @method Phaser.Easing.Elastic#InOut + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ InOut: function (k) { - var s, a = 1, p = 0.4; @@ -472,137 +423,116 @@ Phaser.Easing = { s = p / 4; if ((k *= 2) < 1) { return - 0.5 * (a * Math.pow(2, 10 * (k -= 1)) * Math.sin((k - s) * (2 * Math.PI) / p)); } return a * Math.pow(2, -10 * (k -= 1)) * Math.sin((k - s) * (2 * Math.PI) / p) * 0.5 + 1; - } }, /** - * Back easing. - * - * @class Phaser.Easing.Back - */ + * Back easing. + * + * @class Phaser.Easing.Back + */ Back: { /** - * Back ease-in. - * - * @method Phaser.Easing.Back#In - * @param {number} k - The value to be tweened. - * @returns {number} The tweened value. - */ + * Back ease-in. + * + * @method Phaser.Easing.Back#In + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ In: function (k) { - var s = 1.70158; return k * k * ((s + 1) * k - s); - }, /** - * Back ease-out. - * - * @method Phaser.Easing.Back#Out - * @param {number} k - The value to be tweened. - * @returns {number} The tweened value. - */ + * Back ease-out. + * + * @method Phaser.Easing.Back#Out + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ Out: function (k) { - var s = 1.70158; return --k * k * ((s + 1) * k + s) + 1; - }, /** - * Back ease-in/out. - * - * @method Phaser.Easing.Back#InOut - * @param {number} k - The value to be tweened. - * @returns {number} The tweened value. - */ + * Back ease-in/out. + * + * @method Phaser.Easing.Back#InOut + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ InOut: function (k) { - var s = 1.70158 * 1.525; if ((k *= 2) < 1) { return 0.5 * (k * k * ((s + 1) * k - s)); } return 0.5 * ((k -= 2) * k * ((s + 1) * k + s) + 2); - } }, /** - * Bounce easing. - * - * @class Phaser.Easing.Bounce - */ + * Bounce easing. + * + * @class Phaser.Easing.Bounce + */ Bounce: { /** - * Bounce ease-in. - * - * @method Phaser.Easing.Bounce#In - * @param {number} k - The value to be tweened. - * @returns {number} The tweened value. - */ + * Bounce ease-in. + * + * @method Phaser.Easing.Bounce#In + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ In: function (k) { - return 1 - Phaser.Easing.Bounce.Out(1 - k); - }, /** - * Bounce ease-out. - * - * @method Phaser.Easing.Bounce#Out - * @param {number} k - The value to be tweened. - * @returns {number} The tweened value. - */ + * Bounce ease-out. + * + * @method Phaser.Easing.Bounce#Out + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ Out: function (k) { - if (k < (1 / 2.75)) { - return 7.5625 * k * k; - } else if (k < (2 / 2.75)) { - return 7.5625 * (k -= (1.5 / 2.75)) * k + 0.75; - } else if (k < (2.5 / 2.75)) { - return 7.5625 * (k -= (2.25 / 2.75)) * k + 0.9375; - } else { - return 7.5625 * (k -= (2.625 / 2.75)) * k + 0.984375; - } - }, /** - * Bounce ease-in/out. - * - * @method Phaser.Easing.Bounce#InOut - * @param {number} k - The value to be tweened. - * @returns {number} The tweened value. - */ + * Bounce ease-in/out. + * + * @method Phaser.Easing.Bounce#InOut + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ InOut: function (k) { - if (k < 0.5) { return Phaser.Easing.Bounce.In(k * 2) * 0.5; } return Phaser.Easing.Bounce.Out(k * 2 - 1) * 0.5 + 0.5; - } } diff --git a/src/tween/Tween.js b/src/tween/Tween.js index c05f6f92e..cffbf84b5 100644 --- a/src/tween/Tween.js +++ b/src/tween/Tween.js @@ -1,240 +1,236 @@ /** -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* A Tween allows you to alter one or more properties of a target object over a defined period of time. -* This can be used for things such as alpha fading Sprites, scaling them or motion. -* Use `Tween.to` or `Tween.from` to set-up the tween values. You can create multiple tweens on the same object -* by calling Tween.to multiple times on the same Tween. Additional tweens specified in this way become "child" tweens and -* are played through in sequence. You can use Tween.timeScale and Tween.reverse to control the playback of this Tween and all of its children. -* -* @class Phaser.Tween -* @constructor -* @param {object} target - The target object, such as a Phaser.Sprite or Phaser.Sprite.scale. -* @param {Phaser.Game} game - Current game instance. -* @param {Phaser.TweenManager} manager - The TweenManager responsible for looking after this Tween. -*/ + * A Tween allows you to alter one or more properties of a target object over a defined period of time. + * This can be used for things such as alpha fading Sprites, scaling them or motion. + * Use `Tween.to` or `Tween.from` to set-up the tween values. You can create multiple tweens on the same object + * by calling Tween.to multiple times on the same Tween. Additional tweens specified in this way become "child" tweens and + * are played through in sequence. You can use Tween.timeScale and Tween.reverse to control the playback of this Tween and all of its children. + * + * @class Phaser.Tween + * @constructor + * @param {object} target - The target object, such as a Phaser.Sprite or Phaser.Sprite.scale. + * @param {Phaser.Game} game - Current game instance. + * @param {Phaser.TweenManager} manager - The TweenManager responsible for looking after this Tween. + */ Phaser.Tween = function (target, game, manager) { - /** - * @property {Phaser.Game} game - A reference to the currently running Game. - */ + * @property {Phaser.Game} game - A reference to the currently running Game. + */ this.game = game; /** - * @property {object} target - The target object, such as a Phaser.Sprite or property like Phaser.Sprite.scale. - */ + * @property {object} target - The target object, such as a Phaser.Sprite or property like Phaser.Sprite.scale. + */ this.target = target; /** - * @property {Phaser.TweenManager} manager - Reference to the TweenManager responsible for updating this Tween. - */ + * @property {Phaser.TweenManager} manager - Reference to the TweenManager responsible for updating this Tween. + */ this.manager = manager; /** - * @property {Array} timeline - An Array of TweenData objects that comprise the different parts of this Tween. - */ + * @property {Array} timeline - An Array of TweenData objects that comprise the different parts of this Tween. + */ this.timeline = []; /** - * If set to `true` the current tween will play in reverse. - * If the tween hasn't yet started this has no effect. - * If there are child tweens then all child tweens will play in reverse from the current point. - * @property {boolean} reverse - * @default - */ + * If set to `true` the current tween will play in reverse. + * If the tween hasn't yet started this has no effect. + * If there are child tweens then all child tweens will play in reverse from the current point. + * @property {boolean} reverse + * @default + */ this.reverse = false; /** - * The speed at which the tweens will run. A value of 1 means it will match the game frame rate. 0.5 will run at half the frame rate. 2 at double the frame rate, etc. - * If a tweens duration is 1 second but timeScale is 0.5 then it will take 2 seconds to complete. - * - * @property {number} timeScale - * @default - */ + * The speed at which the tweens will run. A value of 1 means it will match the game frame rate. 0.5 will run at half the frame rate. 2 at double the frame rate, etc. + * If a tweens duration is 1 second but timeScale is 0.5 then it will take 2 seconds to complete. + * + * @property {number} timeScale + * @default + */ this.timeScale = 1; /** - * @property {number} repeatCounter - If the Tween and any child tweens are set to repeat this contains the current repeat count. - */ + * @property {number} repeatCounter - If the Tween and any child tweens are set to repeat this contains the current repeat count. + */ this.repeatCounter = 0; /** - * @property {boolean} pendingDelete - True if this Tween is ready to be deleted by the TweenManager. - * @default - * @readonly - */ + * @property {boolean} pendingDelete - True if this Tween is ready to be deleted by the TweenManager. + * @default + * @readonly + */ this.pendingDelete = false; /** - * The onStart event is fired when the Tween begins. If there is a delay before the tween starts then onStart fires after the delay is finished. - * It will be sent 2 parameters: the target object and this tween. - * @property {Phaser.Signal} onStart - */ + * The onStart event is fired when the Tween begins. If there is a delay before the tween starts then onStart fires after the delay is finished. + * It will be sent 2 parameters: the target object and this tween. + * @property {Phaser.Signal} onStart + */ this.onStart = new Phaser.Signal(); /** - * The onLoop event is fired if the Tween, or any child tweens loop. - * It will be sent 2 parameters: the target object and this tween. - * - * @property {Phaser.Signal} onLoop - */ + * The onLoop event is fired if the Tween, or any child tweens loop. + * It will be sent 2 parameters: the target object and this tween. + * + * @property {Phaser.Signal} onLoop + */ this.onLoop = new Phaser.Signal(); /** - * The onRepeat event is fired if the Tween and all of its children repeats. If this tween has no children this will never be fired. - * It will be sent 2 parameters: the target object and this tween. - * @property {Phaser.Signal} onRepeat - */ + * The onRepeat event is fired if the Tween and all of its children repeats. If this tween has no children this will never be fired. + * It will be sent 2 parameters: the target object and this tween. + * @property {Phaser.Signal} onRepeat + */ this.onRepeat = new Phaser.Signal(); /** - * The onChildComplete event is fired when the Tween or any of its children completes. - * Fires every time a child completes unless a child is set to repeat forever. - * It will be sent 2 parameters: the target object and this tween. - * @property {Phaser.Signal} onChildComplete - */ + * The onChildComplete event is fired when the Tween or any of its children completes. + * Fires every time a child completes unless a child is set to repeat forever. + * It will be sent 2 parameters: the target object and this tween. + * @property {Phaser.Signal} onChildComplete + */ this.onChildComplete = new Phaser.Signal(); /** - * The onComplete event is fired when the Tween and all of its children completes. Does not fire if the Tween is set to loop or repeatAll(-1). - * It will be sent 2 parameters: the target object and this tween. - * @property {Phaser.Signal} onComplete - */ + * The onComplete event is fired when the Tween and all of its children completes. Does not fire if the Tween is set to loop or repeatAll(-1). + * It will be sent 2 parameters: the target object and this tween. + * @property {Phaser.Signal} onComplete + */ this.onComplete = new Phaser.Signal(); /** - * @property {boolean} isRunning - If the tween is running this is set to true, otherwise false. Tweens that are in a delayed state or waiting to start are considered as being running. - * @default - */ + * @property {boolean} isRunning - If the tween is running this is set to true, otherwise false. Tweens that are in a delayed state or waiting to start are considered as being running. + * @default + */ this.isRunning = false; /** - * @property {number} current - The current Tween child being run. - * @default - * @readonly - */ + * @property {number} current - The current Tween child being run. + * @default + * @readonly + */ this.current = 0; /** - * @property {object} properties - Target property cache used when building the child data values. - */ + * @property {object} properties - Target property cache used when building the child data values. + */ this.properties = {}; /** - * @property {Phaser.Tween} chainedTween - If this Tween is chained to another this holds a reference to it. - */ + * @property {Phaser.Tween} chainedTween - If this Tween is chained to another this holds a reference to it. + */ this.chainedTween = null; /** - * @property {boolean} isPaused - Is this Tween paused or not? - * @default - */ + * @property {boolean} isPaused - Is this Tween paused or not? + * @default + */ this.isPaused = false; /** - * Is this Tween frame or time based? A frame based tween will use the physics elapsed timer when updating. This means - * it will retain the same consistent frame rate, regardless of the speed of the device. The duration value given should - * be given in frames. - * - * If the Tween uses a time based update (which is the default) then the duration is given in milliseconds. - * In this situation a 2000ms tween will last exactly 2 seconds, regardless of the device and how many visual updates the tween - * has actually been through. For very short tweens you may wish to experiment with a frame based update instead. - * - * The default value is whatever you've set in TweenManager.frameBased. - * - * @property {boolean} frameBased - * @default - */ + * Is this Tween frame or time based? A frame based tween will use the physics elapsed timer when updating. This means + * it will retain the same consistent frame rate, regardless of the speed of the device. The duration value given should + * be given in frames. + * + * If the Tween uses a time based update (which is the default) then the duration is given in milliseconds. + * In this situation a 2000ms tween will last exactly 2 seconds, regardless of the device and how many visual updates the tween + * has actually been through. For very short tweens you may wish to experiment with a frame based update instead. + * + * The default value is whatever you've set in TweenManager.frameBased. + * + * @property {boolean} frameBased + * @default + */ this.frameBased = manager.frameBased; /** - * @property {function} _onUpdateCallback - An onUpdate callback. - * @private - * @default null - */ + * @property {function} _onUpdateCallback - An onUpdate callback. + * @private + * @default null + */ this._onUpdateCallback = null; /** - * @property {object} _onUpdateCallbackContext - The context in which to call the onUpdate callback. - * @private - * @default null - */ + * @property {object} _onUpdateCallbackContext - The context in which to call the onUpdate callback. + * @private + * @default null + */ this._onUpdateCallbackContext = null; /** - * @property {number} _pausedTime - Private pause timer. - * @private - * @default - */ + * @property {number} _pausedTime - Private pause timer. + * @private + * @default + */ this._pausedTime = 0; /** - * @property {boolean} _codePaused - Was the Tween paused by code or by Game focus loss? - * @private - */ + * @property {boolean} _codePaused - Was the Tween paused by code or by Game focus loss? + * @private + */ this._codePaused = false; /** - * @property {boolean} _hasStarted - Internal var to track if the Tween has started yet or not. - * @private - */ + * @property {boolean} _hasStarted - Internal var to track if the Tween has started yet or not. + * @private + */ this._hasStarted = false; }; /** -* A helper for tweening {@link Phaser.Color.createColor color objects}. -* -* It can be passed to {@link #onUpdateCallback}. -* -* ```javascript -* var color = Phaser.Color.createColor(255, 0, 0); // red -* -* var tween = game.add.tween(color).to({ -* r: 0, g: 0, b: 255 // blue -* }); -* -* tween.onUpdateCallback(Phaser.Tween.updateColor); -* -* tween.start(); -* ``` -* -* @method Phaser.Tween.updateColor -* @static -* @param {Phaser.Tween} tween - A Tween with a {@link #target} that is a {@link Phaser.Color.createColor color object}. -*/ + * A helper for tweening {@link Phaser.Color.createColor color objects}. + * + * It can be passed to {@link #onUpdateCallback}. + * + * ```javascript + * var color = Phaser.Color.createColor(255, 0, 0); // red + * + * var tween = game.add.tween(color).to({ + * r: 0, g: 0, b: 255 // blue + * }); + * + * tween.onUpdateCallback(Phaser.Tween.updateColor); + * + * tween.start(); + * ``` + * + * @method Phaser.Tween.updateColor + * @static + * @param {Phaser.Tween} tween - A Tween with a {@link #target} that is a {@link Phaser.Color.createColor color object}. + */ Phaser.Tween.updateColor = function (tween) { - Phaser.Color.updateColor(tween.target); - }; Phaser.Tween.prototype = { /** - * Sets this tween to be a `to` tween on the properties given. A `to` tween starts at the current value and tweens to the destination value given. - * For example a Sprite with an `x` coordinate of 100 could be tweened to `x` 200 by giving a properties object of `{ x: 200 }`. - * The ease function allows you define the rate of change. You can pass either a function such as Phaser.Easing.Circular.Out or a string such as "Circ". - * ".easeIn", ".easeOut" and "easeInOut" variants are all supported for all ease types. - * - * @method Phaser.Tween#to - * @param {object} properties - An object containing the properties you want to tween, such as `Sprite.x` or `Sound.volume`. Given as a JavaScript object. - * @param {number} [duration=1000] - Duration of this tween in ms. Or if `Tween.frameBased` is true this represents the number of frames that should elapse. - * @param {function|string} [ease=null] - Easing function. If not set it will default to Phaser.Easing.Default, which is Phaser.Easing.Linear.None by default but can be over-ridden. - * @param {boolean} [autoStart=false] - Set to `true` to allow this tween to start automatically. Otherwise call Tween.start(). - * @param {number} [delay=0] - Delay before this tween will start in milliseconds. Defaults to 0, no delay. - * @param {number} [repeat=0] - Should the tween automatically restart once complete? If you want it to run forever set as -1. This only effects this individual tween, not any chained tweens. - * @param {boolean} [yoyo=false] - A tween that yoyos will reverse itself and play backwards automatically. A yoyo'd tween doesn't fire the Tween.onComplete event, so listen for Tween.onLoop instead. - * @return {Phaser.Tween} This Tween object. - */ + * Sets this tween to be a `to` tween on the properties given. A `to` tween starts at the current value and tweens to the destination value given. + * For example a Sprite with an `x` coordinate of 100 could be tweened to `x` 200 by giving a properties object of `{ x: 200 }`. + * The ease function allows you define the rate of change. You can pass either a function such as Phaser.Easing.Circular.Out or a string such as "Circ". + * ".easeIn", ".easeOut" and "easeInOut" variants are all supported for all ease types. + * + * @method Phaser.Tween#to + * @param {object} properties - An object containing the properties you want to tween, such as `Sprite.x` or `Sound.volume`. Given as a JavaScript object. + * @param {number} [duration=1000] - Duration of this tween in ms. Or if `Tween.frameBased` is true this represents the number of frames that should elapse. + * @param {function|string} [ease=null] - Easing function. If not set it will default to Phaser.Easing.Default, which is Phaser.Easing.Linear.None by default but can be over-ridden. + * @param {boolean} [autoStart=false] - Set to `true` to allow this tween to start automatically. Otherwise call Tween.start(). + * @param {number} [delay=0] - Delay before this tween will start in milliseconds. Defaults to 0, no delay. + * @param {number} [repeat=0] - Should the tween automatically restart once complete? If you want it to run forever set as -1. This only effects this individual tween, not any chained tweens. + * @param {boolean} [yoyo=false] - A tween that yoyos will reverse itself and play backwards automatically. A yoyo'd tween doesn't fire the Tween.onComplete event, so listen for Tween.onLoop instead. + * @return {Phaser.Tween} This Tween object. + */ to: function (properties, duration, ease, autoStart, delay, repeat, yoyo) { - if (duration === undefined || duration <= 0) { duration = 1000; } if (ease === undefined || ease === null) { ease = Phaser.Easing.Default; } if (autoStart === undefined) { autoStart = false; } @@ -261,28 +257,26 @@ Phaser.Tween.prototype = { } return this; - }, /** - * Sets this tween to be a `from` tween on the properties given. A `from` tween sets the target to the destination value and tweens to its current value. - * For example a Sprite with an `x` coordinate of 100 tweened from `x` 500 would be set to `x` 500 and then tweened to `x` 100 by giving a properties object of `{ x: 500 }`. - * The ease function allows you define the rate of change. You can pass either a function such as Phaser.Easing.Circular.Out or a string such as "Circ". - * ".easeIn", ".easeOut" and "easeInOut" variants are all supported for all ease types. - * - * @method Phaser.Tween#from - * @param {object} properties - An object containing the properties you want to tween., such as `Sprite.x` or `Sound.volume`. Given as a JavaScript object. - * @param {number} [duration=1000] - Duration of this tween in ms. Or if `Tween.frameBased` is true this represents the number of frames that should elapse. - * @param {function|string} [ease=null] - Easing function. If not set it will default to Phaser.Easing.Default, which is Phaser.Easing.Linear.None by default but can be over-ridden. - * @param {boolean} [autoStart=false] - Set to `true` to allow this tween to start automatically. Otherwise call Tween.start(). - * @param {number} [delay=0] - Delay before this tween will start in milliseconds. Defaults to 0, no delay. - * @param {number} [repeat=0] - Should the tween automatically restart once complete? If you want it to run forever set as -1. This only effects this individual tween, not any chained tweens. - * @param {boolean} [yoyo=false] - A tween that yoyos will reverse itself and play backwards automatically. A yoyo'd tween doesn't fire the Tween.onComplete event, so listen for Tween.onLoop instead. - * @return {Phaser.Tween} This Tween object. - */ + * Sets this tween to be a `from` tween on the properties given. A `from` tween sets the target to the destination value and tweens to its current value. + * For example a Sprite with an `x` coordinate of 100 tweened from `x` 500 would be set to `x` 500 and then tweened to `x` 100 by giving a properties object of `{ x: 500 }`. + * The ease function allows you define the rate of change. You can pass either a function such as Phaser.Easing.Circular.Out or a string such as "Circ". + * ".easeIn", ".easeOut" and "easeInOut" variants are all supported for all ease types. + * + * @method Phaser.Tween#from + * @param {object} properties - An object containing the properties you want to tween., such as `Sprite.x` or `Sound.volume`. Given as a JavaScript object. + * @param {number} [duration=1000] - Duration of this tween in ms. Or if `Tween.frameBased` is true this represents the number of frames that should elapse. + * @param {function|string} [ease=null] - Easing function. If not set it will default to Phaser.Easing.Default, which is Phaser.Easing.Linear.None by default but can be over-ridden. + * @param {boolean} [autoStart=false] - Set to `true` to allow this tween to start automatically. Otherwise call Tween.start(). + * @param {number} [delay=0] - Delay before this tween will start in milliseconds. Defaults to 0, no delay. + * @param {number} [repeat=0] - Should the tween automatically restart once complete? If you want it to run forever set as -1. This only effects this individual tween, not any chained tweens. + * @param {boolean} [yoyo=false] - A tween that yoyos will reverse itself and play backwards automatically. A yoyo'd tween doesn't fire the Tween.onComplete event, so listen for Tween.onLoop instead. + * @return {Phaser.Tween} This Tween object. + */ from: function (properties, duration, ease, autoStart, delay, repeat, yoyo) { - if (duration === undefined) { duration = 1000; } if (ease === undefined || ease === null) { ease = Phaser.Easing.Default; } if (autoStart === undefined) { autoStart = false; } @@ -309,23 +303,21 @@ Phaser.Tween.prototype = { } return this; - }, /** - * Starts the tween running. Can also be called by the `autoStart` parameter of {@link #to} or {@link #from}. - * This sets the {@link #isRunning} property to `true` and dispatches the {@link #onStart} signal. - * If the tween has a delay set then nothing will start tweening until the delay has expired. - * If the tween is already running, is flagged for deletion (such as after {@link #stop}), - * or has an empty timeline, calling start has no effect and the `onStart` signal is not dispatched. - * - * @method Phaser.Tween#start - * @param {number} [index=0] - If this Tween contains child tweens you can specify which one to start from. The default is zero, i.e. the first tween created. - * @return {Phaser.Tween} This tween. Useful for method chaining. - */ + * Starts the tween running. Can also be called by the `autoStart` parameter of {@link #to} or {@link #from}. + * This sets the {@link #isRunning} property to `true` and dispatches the {@link #onStart} signal. + * If the tween has a delay set then nothing will start tweening until the delay has expired. + * If the tween is already running, is flagged for deletion (such as after {@link #stop}), + * or has an empty timeline, calling start has no effect and the `onStart` signal is not dispatched. + * + * @method Phaser.Tween#start + * @param {number} [index=0] - If this Tween contains child tweens you can specify which one to start from. The default is zero, i.e. the first tween created. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ start: function (index) { - if (index === undefined) { index = 0; } if (this.pendingDelete) @@ -374,22 +366,20 @@ Phaser.Tween.prototype = { this.timeline[this.current].start(); return this; - }, /** - * Stops the tween if running and flags it for deletion from the TweenManager. The tween can't be {@link #start restarted} after this. - * The {@link #onComplete} signal is not dispatched and no chained tweens are started unless the `complete` parameter is set to `true`. - * If you just wish to pause a tween then use {@link #pause} instead. - * If the tween is not running, it is **not** flagged for deletion and can be started again. - * - * @method Phaser.Tween#stop - * @param {boolean} [complete=false] - Set to `true` to dispatch the Tween.onComplete signal. - * @return {Phaser.Tween} This tween. Useful for method chaining. - */ + * Stops the tween if running and flags it for deletion from the TweenManager. The tween can't be {@link #start restarted} after this. + * The {@link #onComplete} signal is not dispatched and no chained tweens are started unless the `complete` parameter is set to `true`. + * If you just wish to pause a tween then use {@link #pause} instead. + * If the tween is not running, it is **not** flagged for deletion and can be started again. + * + * @method Phaser.Tween#stop + * @param {boolean} [complete=false] - Set to `true` to dispatch the Tween.onComplete signal. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ stop: function (complete) { - if (complete === undefined) { complete = false; } this.isRunning = false; @@ -411,23 +401,21 @@ Phaser.Tween.prototype = { this.manager.remove(this); return this; - }, /** - * Updates either a single TweenData or all TweenData objects properties to the given value. - * Used internally by methods like Tween.delay, Tween.yoyo, etc. but can also be called directly if you know which property you want to tweak. - * The property is not checked, so if you pass an invalid one you'll generate a run-time error. - * - * @method Phaser.Tween#updateTweenData - * @param {string} property - The property to update. - * @param {number|function} value - The value to set the property to. - * @param {number} [index=0] - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set the delay on all the children. - * @return {Phaser.Tween} This tween. Useful for method chaining. - */ + * Updates either a single TweenData or all TweenData objects properties to the given value. + * Used internally by methods like Tween.delay, Tween.yoyo, etc. but can also be called directly if you know which property you want to tweak. + * The property is not checked, so if you pass an invalid one you'll generate a run-time error. + * + * @method Phaser.Tween#updateTweenData + * @param {string} property - The property to update. + * @param {number|function} value - The value to set the property to. + * @param {number} [index=0] - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set the delay on all the children. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ updateTweenData: function (property, value, index) { - if (this.timeline.length === 0) { return this; } if (index === undefined) { index = 0; } @@ -445,193 +433,175 @@ Phaser.Tween.prototype = { } return this; - }, /** - * Sets the delay in milliseconds before this tween will start. If there are child tweens it sets the delay before the first child starts. - * The delay is invoked as soon as you call `Tween.start`. If the tween is already running this method doesn't do anything for the current active tween. - * If you have not yet called `Tween.to` or `Tween.from` at least once then this method will do nothing, as there are no tweens to delay. - * If you have child tweens and pass -1 as the index value it sets the delay across all of them. - * - * @method Phaser.Tween#delay - * @param {number} duration - The amount of time in ms that the Tween should wait until it begins once started is called. Set to zero to remove any active delay. - * @param {number} [index=0] - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set the delay on all the children. - * @return {Phaser.Tween} This tween. Useful for method chaining. - */ + * Sets the delay in milliseconds before this tween will start. If there are child tweens it sets the delay before the first child starts. + * The delay is invoked as soon as you call `Tween.start`. If the tween is already running this method doesn't do anything for the current active tween. + * If you have not yet called `Tween.to` or `Tween.from` at least once then this method will do nothing, as there are no tweens to delay. + * If you have child tweens and pass -1 as the index value it sets the delay across all of them. + * + * @method Phaser.Tween#delay + * @param {number} duration - The amount of time in ms that the Tween should wait until it begins once started is called. Set to zero to remove any active delay. + * @param {number} [index=0] - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set the delay on all the children. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ delay: function (duration, index) { - return this.updateTweenData('delay', duration, index); - }, /** - * Sets the number of times this tween will repeat. - * If you have not yet called `Tween.to` or `Tween.from` at least once then this method will do nothing, as there are no tweens to repeat. - * If you have child tweens and pass -1 as the index value it sets the number of times they'll repeat across all of them. - * If you wish to define how many times this Tween and all children will repeat see Tween.repeatAll. - * - * @method Phaser.Tween#repeat - * @param {number} total - How many times a tween should repeat before completing. Set to zero to remove an active repeat. Set to -1 to repeat forever. - * @param {number} [repeat=0] - This is the amount of time to pause (in ms) before the repeat will start. - * @param {number} [index=0] - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set the repeat value on all the children. - * @return {Phaser.Tween} This tween. Useful for method chaining. - */ + * Sets the number of times this tween will repeat. + * If you have not yet called `Tween.to` or `Tween.from` at least once then this method will do nothing, as there are no tweens to repeat. + * If you have child tweens and pass -1 as the index value it sets the number of times they'll repeat across all of them. + * If you wish to define how many times this Tween and all children will repeat see Tween.repeatAll. + * + * @method Phaser.Tween#repeat + * @param {number} total - How many times a tween should repeat before completing. Set to zero to remove an active repeat. Set to -1 to repeat forever. + * @param {number} [repeat=0] - This is the amount of time to pause (in ms) before the repeat will start. + * @param {number} [index=0] - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set the repeat value on all the children. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ repeat: function (total, repeatDelay, index) { - if (repeatDelay === undefined) { repeatDelay = 0; } this.updateTweenData('repeatCounter', total, index); this.updateTweenData('repeatTotal', total, index); return this.updateTweenData('repeatDelay', repeatDelay, index); - }, /** - * Sets the delay in milliseconds before this tween will repeat itself. - * The repeatDelay is invoked as soon as you call `Tween.start`. If the tween is already running this method doesn't do anything for the current active tween. - * If you have not yet called `Tween.to` or `Tween.from` at least once then this method will do nothing, as there are no tweens to set repeatDelay on. - * If you have child tweens and pass -1 as the index value it sets the repeatDelay across all of them. - * - * @method Phaser.Tween#repeatDelay - * @param {number} duration - The amount of time in ms that the Tween should wait until it repeats or yoyos once start is called. Set to zero to remove any active repeatDelay. - * @param {number} [index=0] - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set the repeatDelay on all the children. - * @return {Phaser.Tween} This tween. Useful for method chaining. - */ + * Sets the delay in milliseconds before this tween will repeat itself. + * The repeatDelay is invoked as soon as you call `Tween.start`. If the tween is already running this method doesn't do anything for the current active tween. + * If you have not yet called `Tween.to` or `Tween.from` at least once then this method will do nothing, as there are no tweens to set repeatDelay on. + * If you have child tweens and pass -1 as the index value it sets the repeatDelay across all of them. + * + * @method Phaser.Tween#repeatDelay + * @param {number} duration - The amount of time in ms that the Tween should wait until it repeats or yoyos once start is called. Set to zero to remove any active repeatDelay. + * @param {number} [index=0] - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set the repeatDelay on all the children. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ repeatDelay: function (duration, index) { - return this.updateTweenData('repeatDelay', duration, index); - }, /** - * A Tween that has yoyo set to true will run through from its starting values to its end values and then play back in reverse from end to start. - * Used in combination with repeat you can create endless loops. - * If you have not yet called `Tween.to` or `Tween.from` at least once then this method will do nothing, as there are no tweens to yoyo. - * If you have child tweens and pass -1 as the index value it sets the yoyo property across all of them. - * If you wish to yoyo this Tween and all of its children then see Tween.yoyoAll. - * - * @method Phaser.Tween#yoyo - * @param {boolean} enable - Set to true to yoyo this tween, or false to disable an already active yoyo. - * @param {number} [yoyoDelay=0] - This is the amount of time to pause (in ms) before the yoyo will start. - * @param {number} [index=0] - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set yoyo on all the children. - * @return {Phaser.Tween} This tween. Useful for method chaining. - */ + * A Tween that has yoyo set to true will run through from its starting values to its end values and then play back in reverse from end to start. + * Used in combination with repeat you can create endless loops. + * If you have not yet called `Tween.to` or `Tween.from` at least once then this method will do nothing, as there are no tweens to yoyo. + * If you have child tweens and pass -1 as the index value it sets the yoyo property across all of them. + * If you wish to yoyo this Tween and all of its children then see Tween.yoyoAll. + * + * @method Phaser.Tween#yoyo + * @param {boolean} enable - Set to true to yoyo this tween, or false to disable an already active yoyo. + * @param {number} [yoyoDelay=0] - This is the amount of time to pause (in ms) before the yoyo will start. + * @param {number} [index=0] - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set yoyo on all the children. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ yoyo: function (enable, yoyoDelay, index) { - if (yoyoDelay === undefined) { yoyoDelay = 0; } this.updateTweenData('yoyo', enable, index); return this.updateTweenData('yoyoDelay', yoyoDelay, index); - }, /** - * Sets the delay in milliseconds before this tween will run a yoyo (only applies if yoyo is enabled). - * The repeatDelay is invoked as soon as you call `Tween.start`. If the tween is already running this method doesn't do anything for the current active tween. - * If you have not yet called `Tween.to` or `Tween.from` at least once then this method will do nothing, as there are no tweens to set repeatDelay on. - * If you have child tweens and pass -1 as the index value it sets the repeatDelay across all of them. - * - * @method Phaser.Tween#yoyoDelay - * @param {number} duration - The amount of time in ms that the Tween should wait until it repeats or yoyos once start is called. Set to zero to remove any active yoyoDelay. - * @param {number} [index=0] - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set the yoyoDelay on all the children. - * @return {Phaser.Tween} This tween. Useful for method chaining. - */ + * Sets the delay in milliseconds before this tween will run a yoyo (only applies if yoyo is enabled). + * The repeatDelay is invoked as soon as you call `Tween.start`. If the tween is already running this method doesn't do anything for the current active tween. + * If you have not yet called `Tween.to` or `Tween.from` at least once then this method will do nothing, as there are no tweens to set repeatDelay on. + * If you have child tweens and pass -1 as the index value it sets the repeatDelay across all of them. + * + * @method Phaser.Tween#yoyoDelay + * @param {number} duration - The amount of time in ms that the Tween should wait until it repeats or yoyos once start is called. Set to zero to remove any active yoyoDelay. + * @param {number} [index=0] - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set the yoyoDelay on all the children. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ yoyoDelay: function (duration, index) { - return this.updateTweenData('yoyoDelay', duration, index); - }, /** - * Set easing function this tween will use, i.e. Phaser.Easing.Linear.None. - * The ease function allows you define the rate of change. You can pass either a function such as Phaser.Easing.Circular.Out or a string such as "Circ". - * ".easeIn", ".easeOut" and "easeInOut" variants are all supported for all ease types. - * If you have child tweens and pass -1 as the index value it sets the easing function defined here across all of them. - * - * @method Phaser.Tween#easing - * @param {function|string} ease - The easing function this tween will use, i.e. Phaser.Easing.Linear.None. - * @param {number} [index=0] - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set the easing function on all children. - * @return {Phaser.Tween} This tween. Useful for method chaining. - */ + * Set easing function this tween will use, i.e. Phaser.Easing.Linear.None. + * The ease function allows you define the rate of change. You can pass either a function such as Phaser.Easing.Circular.Out or a string such as "Circ". + * ".easeIn", ".easeOut" and "easeInOut" variants are all supported for all ease types. + * If you have child tweens and pass -1 as the index value it sets the easing function defined here across all of them. + * + * @method Phaser.Tween#easing + * @param {function|string} ease - The easing function this tween will use, i.e. Phaser.Easing.Linear.None. + * @param {number} [index=0] - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set the easing function on all children. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ easing: function (ease, index) { - if (typeof ease === 'string' && this.manager.easeMap[ease]) { ease = this.manager.easeMap[ease]; } return this.updateTweenData('easingFunction', ease, index); - }, /** - * Sets the interpolation function the tween will use. By default it uses Phaser.Math.linearInterpolation. - * Also available: Phaser.Math.bezierInterpolation and Phaser.Math.catmullRomInterpolation. - * The interpolation function is only used if the target properties is an array. - * If you have child tweens and pass -1 as the index value and it will set the interpolation function across all of them. - * - * @method Phaser.Tween#interpolation - * @param {function} interpolation - The interpolation function to use (Phaser.Math.linearInterpolation by default) - * @param {object} [context] - The context under which the interpolation function will be run. - * @param {number} [index=0] - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set the interpolation function on all children. - * @return {Phaser.Tween} This tween. Useful for method chaining. - */ + * Sets the interpolation function the tween will use. By default it uses Phaser.Math.linearInterpolation. + * Also available: Phaser.Math.bezierInterpolation and Phaser.Math.catmullRomInterpolation. + * The interpolation function is only used if the target properties is an array. + * If you have child tweens and pass -1 as the index value and it will set the interpolation function across all of them. + * + * @method Phaser.Tween#interpolation + * @param {function} interpolation - The interpolation function to use (Phaser.Math.linearInterpolation by default) + * @param {object} [context] - The context under which the interpolation function will be run. + * @param {number} [index=0] - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set the interpolation function on all children. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ interpolation: function (interpolation, context, index) { - if (context === undefined) { context = Phaser.Math; } this.updateTweenData('interpolationFunction', interpolation, index); return this.updateTweenData('interpolationContext', context, index); - }, /** - * Set how many times this tween and all of its children will repeat. - * A tween (A) with 3 children (B,C,D) with a `repeatAll` value of 2 would play as: ABCDABCD before completing. - * - * @method Phaser.Tween#repeatAll - * @param {number} [total=0] - How many times this tween and all children should repeat before completing. Set to zero to remove an active repeat. Set to -1 to repeat forever. - * @return {Phaser.Tween} This tween. Useful for method chaining. - */ + * Set how many times this tween and all of its children will repeat. + * A tween (A) with 3 children (B,C,D) with a `repeatAll` value of 2 would play as: ABCDABCD before completing. + * + * @method Phaser.Tween#repeatAll + * @param {number} [total=0] - How many times this tween and all children should repeat before completing. Set to zero to remove an active repeat. Set to -1 to repeat forever. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ repeatAll: function (total) { - if (total === undefined) { total = 0; } this.repeatCounter = total; return this; - }, /** - * This method allows you to chain tweens together. Any tween chained to this tween will have its `Tween.start` method called - * as soon as this tween completes. If this tween never completes (i.e. repeatAll or loop is set) then the chain will never progress. - * Note that `Tween.onComplete` will fire when *this* tween completes, not when the whole chain completes. - * For that you should listen to `onComplete` on the final tween in your chain. - * - * If you pass multiple tweens to this method they will be joined into a single long chain. - * For example if this is Tween A and you pass in B, C and D then B will be chained to A, C will be chained to B and D will be chained to C. - * Any previously chained tweens that may have been set will be overwritten. - * - * @method Phaser.Tween#chain - * @param {...Phaser.Tween} tweens - One or more tweens that will be chained to this one. - * @return {Phaser.Tween} This tween. Useful for method chaining. - */ + * This method allows you to chain tweens together. Any tween chained to this tween will have its `Tween.start` method called + * as soon as this tween completes. If this tween never completes (i.e. repeatAll or loop is set) then the chain will never progress. + * Note that `Tween.onComplete` will fire when *this* tween completes, not when the whole chain completes. + * For that you should listen to `onComplete` on the final tween in your chain. + * + * If you pass multiple tweens to this method they will be joined into a single long chain. + * For example if this is Tween A and you pass in B, C and D then B will be chained to A, C will be chained to B and D will be chained to C. + * Any previously chained tweens that may have been set will be overwritten. + * + * @method Phaser.Tween#chain + * @param {...Phaser.Tween} tweens - One or more tweens that will be chained to this one. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ chain: function () { - var i = arguments.length; while (i--) @@ -647,104 +617,94 @@ Phaser.Tween.prototype = { } return this; - }, /** - * Enables the looping of this tween. The tween will loop forever, and onComplete will never fire. - * - * If `value` is `true` then this is the same as setting `Tween.repeatAll(-1)`. - * If `value` is `false` it is the same as setting `Tween.repeatAll(0)` and will reset the `repeatCounter` to zero. - * - * Usage: - * game.add.tween(p).to({ x: 700 }, 1000, Phaser.Easing.Linear.None, true) - * .to({ y: 300 }, 1000, Phaser.Easing.Linear.None) - * .to({ x: 0 }, 1000, Phaser.Easing.Linear.None) - * .to({ y: 0 }, 1000, Phaser.Easing.Linear.None) - * .loop(); - * @method Phaser.Tween#loop - * @param {boolean} [value=true] - If `true` this tween will loop once it reaches the end. Set to `false` to remove an active loop. - * @return {Phaser.Tween} This tween. Useful for method chaining. - */ + * Enables the looping of this tween. The tween will loop forever, and onComplete will never fire. + * + * If `value` is `true` then this is the same as setting `Tween.repeatAll(-1)`. + * If `value` is `false` it is the same as setting `Tween.repeatAll(0)` and will reset the `repeatCounter` to zero. + * + * Usage: + * game.add.tween(p).to({ x: 700 }, 1000, Phaser.Easing.Linear.None, true) + * .to({ y: 300 }, 1000, Phaser.Easing.Linear.None) + * .to({ x: 0 }, 1000, Phaser.Easing.Linear.None) + * .to({ y: 0 }, 1000, Phaser.Easing.Linear.None) + * .loop(); + * @method Phaser.Tween#loop + * @param {boolean} [value=true] - If `true` this tween will loop once it reaches the end. Set to `false` to remove an active loop. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ loop: function (value) { - if (value === undefined) { value = true; } this.repeatCounter = (value) ? -1 : 0; return this; - }, /** - * Sets a callback to be fired each time this tween updates. - * - * The callback receives the current Tween, the {@link Phaser.TweenData#value 'value' of the current TweenData}, and the current {@link Phaser.TweenData TweenData}. The second parameter is most useful. - * - * ```javascript - * tween.onUpdateCallback(function (tween, value, tweenData) { - * console.log('Tween running -- percent: %.2f value: %.2f', tweenData.percent, value); - * }); - * ``` - * - * @method Phaser.Tween#onUpdateCallback - * @param {function} callback - The callback to invoke each time this tween is updated. Set to `null` to remove an already active callback. - * @param {object} callbackContext - The context in which to call the onUpdate callback. - * @return {Phaser.Tween} This tween. Useful for method chaining. - */ + * Sets a callback to be fired each time this tween updates. + * + * The callback receives the current Tween, the {@link Phaser.TweenData#value 'value' of the current TweenData}, and the current {@link Phaser.TweenData TweenData}. The second parameter is most useful. + * + * ```javascript + * tween.onUpdateCallback(function (tween, value, tweenData) { + * console.log('Tween running -- percent: %.2f value: %.2f', tweenData.percent, value); + * }); + * ``` + * + * @method Phaser.Tween#onUpdateCallback + * @param {function} callback - The callback to invoke each time this tween is updated. Set to `null` to remove an already active callback. + * @param {object} callbackContext - The context in which to call the onUpdate callback. + * @return {Phaser.Tween} This tween. Useful for method chaining. + */ onUpdateCallback: function (callback, callbackContext) { - this._onUpdateCallback = callback; this._onUpdateCallbackContext = callbackContext; return this; - }, /** - * Pauses the tween. Resume playback with Tween.resume. - * - * @method Phaser.Tween#pause - */ + * Pauses the tween. Resume playback with Tween.resume. + * + * @method Phaser.Tween#pause + */ pause: function () { - this.isPaused = true; this._codePaused = true; this._pausedTime = this.game.time.time; - }, /** - * This is called by the core Game loop. Do not call it directly, instead use Tween.pause. - * - * @private - * @method Phaser.Tween#_pause - */ + * This is called by the core Game loop. Do not call it directly, instead use Tween.pause. + * + * @private + * @method Phaser.Tween#_pause + */ _pause: function () { - if (!this._codePaused) { this.isPaused = true; this._pausedTime = this.game.time.time; } - }, /** - * Resumes a paused tween. - * - * @method Phaser.Tween#resume - */ + * Resumes a paused tween. + * + * @method Phaser.Tween#resume + */ resume: function () { - if (this.isPaused) { this.isPaused = false; @@ -759,17 +719,15 @@ Phaser.Tween.prototype = { } } } - }, /** - * This is called by the core Game loop. Do not call it directly, instead use Tween.pause. - * @method Phaser.Tween#_resume - * @private - */ + * This is called by the core Game loop. Do not call it directly, instead use Tween.pause. + * @method Phaser.Tween#_resume + * @private + */ _resume: function () { - if (this._codePaused) { return; @@ -778,19 +736,17 @@ Phaser.Tween.prototype = { { this.resume(); } - }, /** - * Core tween update function called by the TweenManager. Does not need to be invoked directly. - * - * @method Phaser.Tween#update - * @param {number} time - A timestamp passed in by the TweenManager. - * @return {boolean} false if the tween and all child tweens have completed and should be deleted from the manager, otherwise true (still active). - */ + * Core tween update function called by the TweenManager. Does not need to be invoked directly. + * + * @method Phaser.Tween#update + * @param {number} time - A timestamp passed in by the TweenManager. + * @return {boolean} false if the tween and all child tweens have completed and should be deleted from the manager, otherwise true (still active). + */ update: function (time) { - if (this.pendingDelete || !this.target) { return false; @@ -902,23 +858,21 @@ Phaser.Tween.prototype = { return true; } } - }, /** - * This will generate an array populated with the tweened object values from start to end. - * It works by running the tween simulation at the given frame rate based on the values set-up in Tween.to and Tween.from. - * It ignores delay and repeat counts and any chained tweens, but does include child tweens. - * Just one play through of the tween data is returned, including yoyo if set. - * - * @method Phaser.Tween#generateData - * @param {number} [frameRate=60] - The speed in frames per second that the data should be generated at. The higher the value, the larger the array it creates. - * @param {array} [data] - If given the generated data will be appended to this array, otherwise a new array will be returned. - * @return {array} An array of tweened values. - */ + * This will generate an array populated with the tweened object values from start to end. + * It works by running the tween simulation at the given frame rate based on the values set-up in Tween.to and Tween.from. + * It ignores delay and repeat counts and any chained tweens, but does include child tweens. + * Just one play through of the tween data is returned, including yoyo if set. + * + * @method Phaser.Tween#generateData + * @param {number} [frameRate=60] - The speed in frames per second that the data should be generated at. The higher the value, the larger the array it creates. + * @param {array} [data] - If given the generated data will be appended to this array, otherwise a new array will be returned. + * @return {array} An array of tweened values. + */ generateData: function (frameRate, data) { - if (this.game === null || this.target === null) { return null; @@ -954,20 +908,18 @@ Phaser.Tween.prototype = { } return data; - } }; /** -* @name Phaser.Tween#totalDuration -* @property {number} totalDuration - Gets the total duration of this Tween, including all child tweens, in milliseconds. -*/ + * @name Phaser.Tween#totalDuration + * @property {number} totalDuration - Gets the total duration of this Tween, including all child tweens, in milliseconds. + */ Object.defineProperty(Phaser.Tween.prototype, 'totalDuration', { get: function () { - var total = 0; for (var i = 0; i < this.timeline.length; i++) @@ -976,7 +928,6 @@ Object.defineProperty(Phaser.Tween.prototype, 'totalDuration', { } return total; - } }); diff --git a/src/tween/TweenData.js b/src/tween/TweenData.js index 2b58027cc..0d66977fd 100644 --- a/src/tween/TweenData.js +++ b/src/tween/TweenData.js @@ -1,203 +1,200 @@ /** -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* A Phaser.Tween contains at least one TweenData object. It contains all of the tween data values, such as the -* starting and ending values, the ease function, interpolation and duration. The Tween acts as a timeline manager for -* TweenData objects and can contain multiple TweenData objects. -* -* @class Phaser.TweenData -* @constructor -* @param {Phaser.Tween} parent - The Tween that owns this TweenData object. -*/ + * A Phaser.Tween contains at least one TweenData object. It contains all of the tween data values, such as the + * starting and ending values, the ease function, interpolation and duration. The Tween acts as a timeline manager for + * TweenData objects and can contain multiple TweenData objects. + * + * @class Phaser.TweenData + * @constructor + * @param {Phaser.Tween} parent - The Tween that owns this TweenData object. + */ Phaser.TweenData = function (parent) { - /** - * @property {Phaser.Tween} parent - The Tween which owns this TweenData. - */ + * @property {Phaser.Tween} parent - The Tween which owns this TweenData. + */ this.parent = parent; /** - * @property {Phaser.Game} game - A reference to the currently running Game. - */ + * @property {Phaser.Game} game - A reference to the currently running Game. + */ this.game = parent.game; /** - * @property {object} vStart - An object containing the values at the start of the tween. - * @private - */ + * @property {object} vStart - An object containing the values at the start of the tween. + * @private + */ this.vStart = {}; /** - * @property {object} vStartCache - Cached starting values. - * @private - */ + * @property {object} vStartCache - Cached starting values. + * @private + */ this.vStartCache = {}; /** - * @property {object} vEnd - An object containing the values at the end of the tween. - * @private - */ + * @property {object} vEnd - An object containing the values at the end of the tween. + * @private + */ this.vEnd = {}; /** - * @property {object} vEndCache - Cached ending values. - * @private - */ + * @property {object} vEndCache - Cached ending values. + * @private + */ this.vEndCache = {}; /** - * @property {number} duration - The duration of the tween in ms. - * @default - */ + * @property {number} duration - The duration of the tween in ms. + * @default + */ this.duration = 1000; /** - * @property {number} percent - A value between 0 and 1 that represents how far through the duration this tween is. - * @readonly - */ + * @property {number} percent - A value between 0 and 1 that represents how far through the duration this tween is. + * @readonly + */ this.percent = 0; /** - * @property {number} value - The output of the easing function for the current {@link #percent}. Depending on the easing function, this will be within [0, 1] or a slightly larger range (e.g., Bounce). When easing is Linear, this will be identical to {@link #percent}. - * @readonly - */ + * @property {number} value - The output of the easing function for the current {@link #percent}. Depending on the easing function, this will be within [0, 1] or a slightly larger range (e.g., Bounce). When easing is Linear, this will be identical to {@link #percent}. + * @readonly + */ this.value = 0; /** - * @property {number} repeatCounter - If the Tween is set to repeat this is the number of repeats remaining (and `repeatTotal - repeatCounter` is the number of repeats completed). - */ + * @property {number} repeatCounter - If the Tween is set to repeat this is the number of repeats remaining (and `repeatTotal - repeatCounter` is the number of repeats completed). + */ this.repeatCounter = 0; /** - * @property {number} repeatDelay - The amount of time in ms between repeats of this tween. - */ + * @property {number} repeatDelay - The amount of time in ms between repeats of this tween. + */ this.repeatDelay = 0; /** - * @property {number} repeatTotal - The total number of times this Tween will repeat. - * @readonly - */ + * @property {number} repeatTotal - The total number of times this Tween will repeat. + * @readonly + */ this.repeatTotal = 0; /** - * @property {boolean} interpolate - True if the Tween will use interpolation (i.e. is an Array to Array tween) - * @default - * @todo Appears unused. - */ + * @property {boolean} interpolate - True if the Tween will use interpolation (i.e. is an Array to Array tween) + * @default + * @todo Appears unused. + */ this.interpolate = false; /** - * @property {boolean} yoyo - True if the Tween is set to yoyo, otherwise false. - * @default - */ + * @property {boolean} yoyo - True if the Tween is set to yoyo, otherwise false. + * @default + */ this.yoyo = false; /** - * @property {number} yoyoDelay - The amount of time in ms between yoyos of this tween. - */ + * @property {number} yoyoDelay - The amount of time in ms between yoyos of this tween. + */ this.yoyoDelay = 0; /** - * @property {boolean} inReverse - When a Tween is yoyoing this value holds if it's currently playing forwards (false) or in reverse (true). - * @default - */ + * @property {boolean} inReverse - When a Tween is yoyoing this value holds if it's currently playing forwards (false) or in reverse (true). + * @default + */ this.inReverse = false; /** - * @property {number} delay - The amount to delay by until the Tween starts (in ms). Only applies to the start, use repeatDelay to handle repeats. - * @default - */ + * @property {number} delay - The amount to delay by until the Tween starts (in ms). Only applies to the start, use repeatDelay to handle repeats. + * @default + */ this.delay = 0; /** - * @property {number} dt - Current time value. - */ + * @property {number} dt - Current time value. + */ this.dt = 0; /** - * @property {number} startTime - The time the Tween started or null if it hasn't yet started. - */ + * @property {number} startTime - The time the Tween started or null if it hasn't yet started. + */ this.startTime = null; /** - * @property {function} easingFunction - The easing function used for the Tween. - * @default Phaser.Easing.Default - */ + * @property {function} easingFunction - The easing function used for the Tween. + * @default Phaser.Easing.Default + */ this.easingFunction = Phaser.Easing.Default; /** - * @property {function} interpolationFunction - The interpolation function used for Array-based Tween. - * @default Phaser.Math.linearInterpolation - */ + * @property {function} interpolationFunction - The interpolation function used for Array-based Tween. + * @default Phaser.Math.linearInterpolation + */ this.interpolationFunction = Phaser.Math.linearInterpolation; /** - * @property {object} interpolationContext - The interpolation function context used for the Tween. - * @default Phaser.Math - */ + * @property {object} interpolationContext - The interpolation function context used for the Tween. + * @default Phaser.Math + */ this.interpolationContext = Phaser.Math; /** - * @property {boolean} isRunning - If the tween is running this is set to `true`. Unless Phaser.Tween a TweenData that is waiting for a delay to expire is *not* considered as running. - * @default - */ + * @property {boolean} isRunning - If the tween is running this is set to `true`. Unless Phaser.Tween a TweenData that is waiting for a delay to expire is *not* considered as running. + * @default + */ this.isRunning = false; /** - * @property {boolean} isFrom - Is this a from tween or a to tween? - * @default - */ + * @property {boolean} isFrom - Is this a from tween or a to tween? + * @default + */ this.isFrom = false; - }; /** -* @constant -* @type {number} -*/ + * @constant + * @type {number} + */ Phaser.TweenData.PENDING = 0; /** -* @constant -* @type {number} -*/ + * @constant + * @type {number} + */ Phaser.TweenData.RUNNING = 1; /** -* @constant -* @type {number} -*/ + * @constant + * @type {number} + */ Phaser.TweenData.LOOPED = 2; /** -* @constant -* @type {number} -*/ + * @constant + * @type {number} + */ Phaser.TweenData.COMPLETE = 3; Phaser.TweenData.prototype = { /** - * Sets this tween to be a `to` tween on the properties given. A `to` tween starts at the current value and tweens to the destination value given. - * For example a Sprite with an `x` coordinate of 100 could be tweened to `x` 200 by giving a properties object of `{ x: 200 }`. - * - * @method Phaser.TweenData#to - * @param {object} properties - The properties you want to tween, such as `Sprite.x` or `Sound.volume`. Given as a JavaScript object. - * @param {number} [duration=1000] - Duration of this tween in ms. - * @param {function} [ease=null] - Easing function. If not set it will default to Phaser.Easing.Default, which is Phaser.Easing.Linear.None by default but can be over-ridden at will. - * @param {number} [delay=0] - Delay before this tween will start, defaults to 0 (no delay). Value given is in ms. - * @param {number} [repeat=0] - Should the tween automatically restart once complete? If you want it to run forever set as -1. This ignores any chained tweens. - * @param {boolean} [yoyo=false] - A tween that yoyos will reverse itself and play backwards automatically. A yoyo'd tween doesn't fire the Tween.onComplete event, so listen for Tween.onLoop instead. - * @return {Phaser.TweenData} This Tween object. - */ + * Sets this tween to be a `to` tween on the properties given. A `to` tween starts at the current value and tweens to the destination value given. + * For example a Sprite with an `x` coordinate of 100 could be tweened to `x` 200 by giving a properties object of `{ x: 200 }`. + * + * @method Phaser.TweenData#to + * @param {object} properties - The properties you want to tween, such as `Sprite.x` or `Sound.volume`. Given as a JavaScript object. + * @param {number} [duration=1000] - Duration of this tween in ms. + * @param {function} [ease=null] - Easing function. If not set it will default to Phaser.Easing.Default, which is Phaser.Easing.Linear.None by default but can be over-ridden at will. + * @param {number} [delay=0] - Delay before this tween will start, defaults to 0 (no delay). Value given is in ms. + * @param {number} [repeat=0] - Should the tween automatically restart once complete? If you want it to run forever set as -1. This ignores any chained tweens. + * @param {boolean} [yoyo=false] - A tween that yoyos will reverse itself and play backwards automatically. A yoyo'd tween doesn't fire the Tween.onComplete event, so listen for Tween.onLoop instead. + * @return {Phaser.TweenData} This Tween object. + */ to: function (properties, duration, ease, delay, repeat, yoyo) { - this.vEnd = properties; this.duration = duration; this.easingFunction = ease; @@ -208,25 +205,23 @@ Phaser.TweenData.prototype = { this.isFrom = false; return this; - }, /** - * Sets this tween to be a `from` tween on the properties given. A `from` tween sets the target to the destination value and tweens to its current value. - * For example a Sprite with an `x` coordinate of 100 tweened from `x` 500 would be set to `x` 500 and then tweened to `x` 100 by giving a properties object of `{ x: 500 }`. - * - * @method Phaser.TweenData#from - * @param {object} properties - The properties you want to tween, such as `Sprite.x` or `Sound.volume`. Given as a JavaScript object. - * @param {number} [duration=1000] - Duration of this tween in ms. - * @param {function} [ease=null] - Easing function. If not set it will default to Phaser.Easing.Default, which is Phaser.Easing.Linear.None by default but can be over-ridden at will. - * @param {number} [delay=0] - Delay before this tween will start, defaults to 0 (no delay). Value given is in ms. - * @param {number} [repeat=0] - Should the tween automatically restart once complete? If you want it to run forever set as -1. This ignores any chained tweens. - * @param {boolean} [yoyo=false] - A tween that yoyos will reverse itself and play backwards automatically. A yoyo'd tween doesn't fire the Tween.onComplete event, so listen for Tween.onLoop instead. - * @return {Phaser.TweenData} This Tween object. - */ + * Sets this tween to be a `from` tween on the properties given. A `from` tween sets the target to the destination value and tweens to its current value. + * For example a Sprite with an `x` coordinate of 100 tweened from `x` 500 would be set to `x` 500 and then tweened to `x` 100 by giving a properties object of `{ x: 500 }`. + * + * @method Phaser.TweenData#from + * @param {object} properties - The properties you want to tween, such as `Sprite.x` or `Sound.volume`. Given as a JavaScript object. + * @param {number} [duration=1000] - Duration of this tween in ms. + * @param {function} [ease=null] - Easing function. If not set it will default to Phaser.Easing.Default, which is Phaser.Easing.Linear.None by default but can be over-ridden at will. + * @param {number} [delay=0] - Delay before this tween will start, defaults to 0 (no delay). Value given is in ms. + * @param {number} [repeat=0] - Should the tween automatically restart once complete? If you want it to run forever set as -1. This ignores any chained tweens. + * @param {boolean} [yoyo=false] - A tween that yoyos will reverse itself and play backwards automatically. A yoyo'd tween doesn't fire the Tween.onComplete event, so listen for Tween.onLoop instead. + * @return {Phaser.TweenData} This Tween object. + */ from: function (properties, duration, ease, delay, repeat, yoyo) { - this.vEnd = properties; this.duration = duration; this.easingFunction = ease; @@ -237,18 +232,16 @@ Phaser.TweenData.prototype = { this.isFrom = true; return this; - }, /** - * Starts the Tween running. - * - * @method Phaser.TweenData#start - * @return {Phaser.TweenData} This Tween object. - */ + * Starts the Tween running. + * + * @method Phaser.TweenData#start + * @return {Phaser.TweenData} This Tween object. + */ start: function () { - this.startTime = this.game.time.time + this.delay; if (this.parent.reverse) @@ -284,19 +277,17 @@ Phaser.TweenData.prototype = { this.repeatCounter = this.repeatTotal; return this; - }, /** - * Loads the values from the target object into this Tween. - * - * @private - * @method Phaser.TweenData#loadValues - * @return {Phaser.TweenData} This Tween object. - */ + * Loads the values from the target object into this Tween. + * + * @private + * @method Phaser.TweenData#loadValues + * @return {Phaser.TweenData} This Tween object. + */ loadValues: function () { - for (var property in this.parent.properties) { // Load the property from the parent object @@ -312,8 +303,10 @@ Phaser.TweenData.prototype = { if (this.percent === 0) { - // Put the start value at the beginning of the array - // but we only want to do this once, if the Tween hasn't run before + /* + * Put the start value at the beginning of the array + * but we only want to do this once, if the Tween hasn't run before + */ this.vEnd[property] = [ this.vStart[property] ].concat(this.vEnd[property]); } } @@ -339,20 +332,18 @@ Phaser.TweenData.prototype = { } return this; - }, /** - * Updates this Tween. This is called automatically by Phaser.Tween. - * - * @protected - * @method Phaser.TweenData#update - * @param {number} time - A timestamp passed in by the Tween parent. - * @return {number} The current status of this Tween. One of the Phaser.TweenData constants: PENDING, RUNNING, LOOPED or COMPLETE. - */ + * Updates this Tween. This is called automatically by Phaser.Tween. + * + * @protected + * @method Phaser.TweenData#update + * @param {number} time - A timestamp passed in by the Tween parent. + * @return {number} The current status of this Tween. One of the Phaser.TweenData constants: PENDING, RUNNING, LOOPED or COMPLETE. + */ update: function (time) { - if (!this.isRunning) { if (time >= this.startTime) @@ -411,21 +402,19 @@ Phaser.TweenData.prototype = { } return Phaser.TweenData.RUNNING; - }, /** - * This will generate an array populated with the tweened object values from start to end. - * It works by running the tween simulation at the given frame rate based on the values set-up in Tween.to and Tween.from. - * Just one play through of the tween data is returned, including yoyo if set. - * - * @method Phaser.TweenData#generateData - * @param {number} [frameRate=60] - The speed in frames per second that the data should be generated at. The higher the value, the larger the array it creates. - * @return {array} An array of tweened values. - */ + * This will generate an array populated with the tweened object values from start to end. + * It works by running the tween simulation at the given frame rate based on the values set-up in Tween.to and Tween.from. + * Just one play through of the tween data is returned, including yoyo if set. + * + * @method Phaser.TweenData#generateData + * @param {number} [frameRate=60] - The speed in frames per second that the data should be generated at. The higher the value, the larger the array it creates. + * @return {array} An array of tweened values. + */ generateData: function (frameRate) { - if (this.parent.reverse) { this.dt = this.duration; @@ -479,7 +468,6 @@ Phaser.TweenData.prototype = { { complete = true; } - } while (!complete); if (this.yoyo) @@ -490,19 +478,17 @@ Phaser.TweenData.prototype = { } return data; - }, /** - * Checks if this Tween is meant to repeat or yoyo and handles doing so. - * - * @private - * @method Phaser.TweenData#repeat - * @return {number} Either Phaser.TweenData.LOOPED or Phaser.TweenData.COMPLETE. - */ + * Checks if this Tween is meant to repeat or yoyo and handles doing so. + * + * @private + * @method Phaser.TweenData#repeat + * @return {number} Either Phaser.TweenData.LOOPED or Phaser.TweenData.COMPLETE. + */ repeat: function () { - // If not a yoyo and repeatCounter = 0 then we're done if (this.yoyo) { @@ -547,8 +533,10 @@ Phaser.TweenData.prototype = { this.vEnd[property] = this.vEndCache[property]; } - // -1 means repeat forever, otherwise decrement the repeatCounter - // We only decrement this counter if the tween isn't doing a yoyo, as that doesn't count towards the repeat total + /* + * -1 means repeat forever, otherwise decrement the repeatCounter + * We only decrement this counter if the tween isn't doing a yoyo, as that doesn't count towards the repeat total + */ if (this.repeatCounter > 0) { this.repeatCounter--; @@ -576,7 +564,6 @@ Phaser.TweenData.prototype = { } return Phaser.TweenData.LOOPED; - } }; diff --git a/src/tween/TweenManager.js b/src/tween/TweenManager.js index bc7769594..0056375a9 100644 --- a/src/tween/TweenManager.js +++ b/src/tween/TweenManager.js @@ -1,53 +1,52 @@ /** -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* Phaser.Game has a single instance of the TweenManager through which all Tween objects are created and updated. -* Tweens are hooked into the game clock and pause system, adjusting based on the game state. -* -* TweenManager is based heavily on tween.js by http://soledadpenades.com. -* The difference being that tweens belong to a games instance of TweenManager, rather than to a global TWEEN object. -* It also has callbacks swapped for Signals and a few issues patched with regard to properties and completion errors. -* Please see https://github.com/sole/tween.js for a full list of contributors. -* -* @class Phaser.TweenManager -* @constructor -* @param {Phaser.Game} game - A reference to the currently running game. -*/ + * Phaser.Game has a single instance of the TweenManager through which all Tween objects are created and updated. + * Tweens are hooked into the game clock and pause system, adjusting based on the game state. + * + * TweenManager is based heavily on tween.js by http://soledadpenades.com. + * The difference being that tweens belong to a games instance of TweenManager, rather than to a global TWEEN object. + * It also has callbacks swapped for Signals and a few issues patched with regard to properties and completion errors. + * Please see https://github.com/sole/tween.js for a full list of contributors. + * + * @class Phaser.TweenManager + * @constructor + * @param {Phaser.Game} game - A reference to the currently running game. + */ Phaser.TweenManager = function (game) { - /** - * @property {Phaser.Game} game - Local reference to game. - */ + * @property {Phaser.Game} game - Local reference to game. + */ this.game = game; /** - * Are all newly created Tweens frame or time based? A frame based tween will use the physics elapsed timer when updating. This means - * it will retain the same consistent frame rate, regardless of the speed of the device. The duration value given should - * be given in frames. - * - * If the Tween uses a time based update (which is the default) then the duration is given in milliseconds. - * In this situation a 2000ms tween will last exactly 2 seconds, regardless of the device and how many visual updates the tween - * has actually been through. For very short tweens you may wish to experiment with a frame based update instead. - * @property {boolean} frameBased - * @default - */ + * Are all newly created Tweens frame or time based? A frame based tween will use the physics elapsed timer when updating. This means + * it will retain the same consistent frame rate, regardless of the speed of the device. The duration value given should + * be given in frames. + * + * If the Tween uses a time based update (which is the default) then the duration is given in milliseconds. + * In this situation a 2000ms tween will last exactly 2 seconds, regardless of the device and how many visual updates the tween + * has actually been through. For very short tweens you may wish to experiment with a frame based update instead. + * @property {boolean} frameBased + * @default + */ this.frameBased = false; /** - * @property {array} _tweens - All of the currently running tweens. - * @private - */ + * @property {array} _tweens - All of the currently running tweens. + * @private + */ this._tweens = []; /** - * @property {array} _add - All of the tweens queued to be added in the next update. - * @private - */ + * @property {array} _add - All of the tweens queued to be added in the next update. + * @private + */ this._add = []; this.easeMap = { @@ -107,49 +106,43 @@ Phaser.TweenManager = function (game) this.game.onPause.add(this._pauseAll, this); this.game.onResume.add(this._resumeAll, this); - }; Phaser.TweenManager.prototype = { /** - * Get all the tween objects in an array. - * @method Phaser.TweenManager#getAll - * @returns {Phaser.Tween[]} Array with all tween objects. - */ + * Get all the tween objects in an array. + * @method Phaser.TweenManager#getAll + * @returns {Phaser.Tween[]} Array with all tween objects. + */ getAll: function () { - return this._tweens; - }, /** - * Remove all tweens running and in the queue. Doesn't call any of the tween onComplete events. - * @method Phaser.TweenManager#removeAll - */ + * Remove all tweens running and in the queue. Doesn't call any of the tween onComplete events. + * @method Phaser.TweenManager#removeAll + */ removeAll: function () { - for (var i = 0; i < this._tweens.length; i++) { this._tweens[i].pendingDelete = true; } this._add = []; - }, /** - * Remove all tweens from a specific object, array of objects or Group. - * - * @method Phaser.TweenManager#removeFrom - * @param {object|object[]|Phaser.Group} obj - The object you want to remove the tweens from. - * @param {boolean} [children=true] - If passing a group, setting this to true will remove the tweens from all of its children instead of the group itself. - */ + * Remove all tweens from a specific object, array of objects or Group. + * + * @method Phaser.TweenManager#removeFrom + * @param {object|object[]|Phaser.Group} obj - The object you want to remove the tweens from. + * @param {boolean} [children=true] - If passing a group, setting this to true will remove the tweens from all of its children instead of the group itself. + */ removeFrom: function (obj, children) { - if (children === undefined) { children = true; } var i; @@ -187,47 +180,41 @@ Phaser.TweenManager.prototype = { } } } - }, /** - * Add a new tween into the TweenManager. - * - * @method Phaser.TweenManager#add - * @param {Phaser.Tween} tween - The tween object you want to add. - * @returns {Phaser.Tween} The tween object you added to the manager. - */ + * Add a new tween into the TweenManager. + * + * @method Phaser.TweenManager#add + * @param {Phaser.Tween} tween - The tween object you want to add. + * @returns {Phaser.Tween} The tween object you added to the manager. + */ add: function (tween) { - tween._manager = this; this._add.push(tween); - }, /** - * Create a tween object for a specific object. The object can be any JavaScript object or Phaser object such as Sprite. - * - * @method Phaser.TweenManager#create - * @param {object} object - Object the tween will be run on. - * @returns {Phaser.Tween} The newly created tween object. - */ + * Create a tween object for a specific object. The object can be any JavaScript object or Phaser object such as Sprite. + * + * @method Phaser.TweenManager#create + * @param {object} object - Object the tween will be run on. + * @returns {Phaser.Tween} The newly created tween object. + */ create: function (object) { - return new Phaser.Tween(object, this.game, this); - }, /** - * Remove a tween from this manager. - * - * @method Phaser.TweenManager#remove - * @param {Phaser.Tween} tween - The tween object you want to remove. - */ + * Remove a tween from this manager. + * + * @method Phaser.TweenManager#remove + * @param {Phaser.Tween} tween - The tween object you want to remove. + */ remove: function (tween) { - var i = this._tweens.indexOf(tween); if (i !== -1) @@ -243,18 +230,16 @@ Phaser.TweenManager.prototype = { this._add[i].pendingDelete = true; } } - }, /** - * Update all the tween objects you added to this manager. - * - * @method Phaser.TweenManager#update - * @returns {boolean} Return false if there's no tween to update, otherwise return true. - */ + * Update all the tween objects you added to this manager. + * + * @method Phaser.TweenManager#update + * @returns {boolean} Return false if there's no tween to update, otherwise return true. + */ update: function () { - var addTweens = this._add.length; var numTweens = this._tweens.length; @@ -287,108 +272,95 @@ Phaser.TweenManager.prototype = { } return true; - }, /** - * Checks to see if a particular Sprite is currently being tweened. - * - * The `checkIsRunning` parameter will exclude tweens that have **just** completed or been stopped but haven't yet been removed from the manager. - * - * @method Phaser.TweenManager#isTweening - * @param {object} object - The object to check for tweens against. - * @param {boolean} [checkIsRunning=false] - Also check that the tween is running and is not marked for deletion. - * @returns {boolean} Returns true if the object is currently being tweened, false if not. - */ + * Checks to see if a particular Sprite is currently being tweened. + * + * The `checkIsRunning` parameter will exclude tweens that have **just** completed or been stopped but haven't yet been removed from the manager. + * + * @method Phaser.TweenManager#isTweening + * @param {object} object - The object to check for tweens against. + * @param {boolean} [checkIsRunning=false] - Also check that the tween is running and is not marked for deletion. + * @returns {boolean} Returns true if the object is currently being tweened, false if not. + */ isTweening: function (object, checkIsRunning) { - if (!checkIsRunning) { checkIsRunning = false; } return this._tweens.some(function (tween) { return (tween.target === object) && (!checkIsRunning || (tween.isRunning && !tween.pendingDelete)); }); - }, /** - * Private. Called by game focus loss. Pauses all currently running tweens. - * - * @method Phaser.TweenManager#_pauseAll - * @private - */ + * Private. Called by game focus loss. Pauses all currently running tweens. + * + * @method Phaser.TweenManager#_pauseAll + * @private + */ _pauseAll: function () { - for (var i = this._tweens.length - 1; i >= 0; i--) { this._tweens[i]._pause(); } - }, /** - * Private. Called by game focus loss. Resumes all currently paused tweens. - * - * @method Phaser.TweenManager#_resumeAll - * @private - */ + * Private. Called by game focus loss. Resumes all currently paused tweens. + * + * @method Phaser.TweenManager#_resumeAll + * @private + */ _resumeAll: function () { - for (var i = this._tweens.length - 1; i >= 0; i--) { this._tweens[i]._resume(); } - }, /** - * Pauses all currently running tweens. - * - * @method Phaser.TweenManager#pauseAll - */ + * Pauses all currently running tweens. + * + * @method Phaser.TweenManager#pauseAll + */ pauseAll: function () { - for (var i = this._tweens.length - 1; i >= 0; i--) { this._tweens[i].pause(); } - }, /** - * Resumes all currently paused tweens. - * - * @method Phaser.TweenManager#resumeAll - */ + * Resumes all currently paused tweens. + * + * @method Phaser.TweenManager#resumeAll + */ resumeAll: function () { - for (var i = this._tweens.length - 1; i >= 0; i--) { this._tweens[i].resume(true); } - }, /** - * Removes all tweens and deletes queues. - * - * @method Phaser.TweenManager#destroy - */ + * Removes all tweens and deletes queues. + * + * @method Phaser.TweenManager#destroy + */ destroy: function () { - this.game.onPause.remove(this._pauseAll, this); this.game.onResume.remove(this._resumeAll, this); this.game = null; this._add = null; this._tweens = null; - } }; diff --git a/src/utils/ArraySet.js b/src/utils/ArraySet.js index d099239d4..bc8de35d6 100644 --- a/src/utils/ArraySet.js +++ b/src/utils/ArraySet.js @@ -1,87 +1,80 @@ /** -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* ArraySet is a Set data structure (items must be unique within the set) that also maintains order. -* This allows specific items to be easily added or removed from the Set. -* -* Item equality (and uniqueness) is determined by the behavior of `Array.indexOf`. -* -* This used primarily by the Input subsystem. -* -* @class Phaser.ArraySet -* @constructor -* @param {any[]} [list=(new array)] - The backing array: if specified the items in the list _must_ be unique, per `Array.indexOf`, and the ownership of the array _should_ be relinquished to the ArraySet. -*/ + * ArraySet is a Set data structure (items must be unique within the set) that also maintains order. + * This allows specific items to be easily added or removed from the Set. + * + * Item equality (and uniqueness) is determined by the behavior of `Array.indexOf`. + * + * This used primarily by the Input subsystem. + * + * @class Phaser.ArraySet + * @constructor + * @param {any[]} [list=(new array)] - The backing array: if specified the items in the list _must_ be unique, per `Array.indexOf`, and the ownership of the array _should_ be relinquished to the ArraySet. + */ Phaser.ArraySet = function (list) { - /** - * Current cursor position as established by `first` and `next`. - * @property {integer} position - * @default - */ + * Current cursor position as established by `first` and `next`. + * @property {integer} position + * @default + */ this.position = 0; /** - * The backing array. - * @property {any[]} list - */ + * The backing array. + * @property {any[]} list + */ this.list = list || []; - }; Phaser.ArraySet.prototype = { /** - * Adds a new element to the end of the list. - * If the item already exists in the list it is not moved. - * - * @method Phaser.ArraySet#add - * @param {any} item - The element to add to this list. - * @return {any} The item that was added. - */ + * Adds a new element to the end of the list. + * If the item already exists in the list it is not moved. + * + * @method Phaser.ArraySet#add + * @param {any} item - The element to add to this list. + * @return {any} The item that was added. + */ add: function (item) { - if (!this.exists(item)) { this.list.push(item); } return item; - }, /** - * Gets the index of the item in the list, or -1 if it isn't in the list. - * - * @method Phaser.ArraySet#getIndex - * @param {any} item - The element to get the list index for. - * @return {integer} The index of the item or -1 if not found. - */ + * Gets the index of the item in the list, or -1 if it isn't in the list. + * + * @method Phaser.ArraySet#getIndex + * @param {any} item - The element to get the list index for. + * @return {integer} The index of the item or -1 if not found. + */ getIndex: function (item) { - return this.list.indexOf(item); - }, /** - * Gets an item from the set based on the property strictly equaling the value given. - * Returns null if not found. - * - * @method Phaser.ArraySet#getByKey - * @param {string} property - The property to check against the value. - * @param {any} value - The value to check if the property strictly equals. - * @return {any} The item that was found, or null if nothing matched. - */ + * Gets an item from the set based on the property strictly equaling the value given. + * Returns null if not found. + * + * @method Phaser.ArraySet#getByKey + * @param {string} property - The property to check against the value. + * @param {any} value - The value to check if the property strictly equals. + * @return {any} The item that was found, or null if nothing matched. + */ getByKey: function (property, value) { - var i = this.list.length; while (i--) @@ -93,45 +86,39 @@ Phaser.ArraySet.prototype = { } return null; - }, /** - * Checks for the item within this list. - * - * @method Phaser.ArraySet#exists - * @param {any} item - The element to get the list index for. - * @return {boolean} True if the item is found in the list, otherwise false. - */ + * Checks for the item within this list. + * + * @method Phaser.ArraySet#exists + * @param {any} item - The element to get the list index for. + * @return {boolean} True if the item is found in the list, otherwise false. + */ exists: function (item) { - return (this.list.indexOf(item) > -1); - }, /** - * Removes all the items. - * - * @method Phaser.ArraySet#reset - */ + * Removes all the items. + * + * @method Phaser.ArraySet#reset + */ reset: function () { - this.list.length = 0; - }, /** - * Removes the given element from this list if it exists. - * - * @method Phaser.ArraySet#remove - * @param {any} item - The item to be removed from the list. - * @return {any} item - The item that was removed. - */ + * Removes the given element from this list if it exists. + * + * @method Phaser.ArraySet#remove + * @param {any} item - The item to be removed from the list. + * @return {any} item - The item that was removed. + */ remove: function (item) { - var idx = this.list.indexOf(item); if (idx > -1) @@ -139,19 +126,17 @@ Phaser.ArraySet.prototype = { this.list.splice(idx, 1); return item; } - }, /** - * Sets the property `key` to the given value on all members of this list. - * - * @method Phaser.ArraySet#setAll - * @param {any} key - The property of the item to set. - * @param {any} value - The value to set the property to. - */ + * Sets the property `key` to the given value on all members of this list. + * + * @method Phaser.ArraySet#setAll + * @param {any} key - The property of the item to set. + * @param {any} value - The value to set the property to. + */ setAll: function (key, value) { - var i = this.list.length; while (i--) @@ -161,22 +146,20 @@ Phaser.ArraySet.prototype = { this.list[i][key] = value; } } - }, /** - * Calls a function on all members of this list, using the member as the context for the callback. - * - * If the `key` property is present it must be a function. - * The function is invoked using the item as the context. - * - * @method Phaser.ArraySet#callAll - * @param {string} key - The name of the property with the function to call. - * @param {...*} parameter - Additional parameters that will be passed to the callback. - */ + * Calls a function on all members of this list, using the member as the context for the callback. + * + * If the `key` property is present it must be a function. + * The function is invoked using the item as the context. + * + * @method Phaser.ArraySet#callAll + * @param {string} key - The name of the property with the function to call. + * @param {...*} parameter - Additional parameters that will be passed to the callback. + */ callAll: function (key) { - var args = Array.prototype.slice.call(arguments, 1); var i = this.list.length; @@ -188,18 +171,16 @@ Phaser.ArraySet.prototype = { this.list[i][key].apply(this.list[i], args); } } - }, /** - * Removes every member from this ArraySet and optionally destroys it. - * - * @method Phaser.ArraySet#removeAll - * @param {boolean} [destroy=false] - Call `destroy` on each member as it's removed from this set. - */ + * Removes every member from this ArraySet and optionally destroys it. + * + * @method Phaser.ArraySet#removeAll + * @param {boolean} [destroy=false] - Call `destroy` on each member as it's removed from this set. + */ removeAll: function (destroy) { - if (destroy === undefined) { destroy = false; } var i = this.list.length; @@ -219,17 +200,16 @@ Phaser.ArraySet.prototype = { this.position = 0; this.list = []; - } }; /** -* Number of items in the ArraySet. Same as `list.length`. -* -* @name Phaser.ArraySet#total -* @property {integer} total -*/ + * Number of items in the ArraySet. Same as `list.length`. + * + * @name Phaser.ArraySet#total + * @property {integer} total + */ Object.defineProperty(Phaser.ArraySet.prototype, 'total', { get: function () @@ -240,16 +220,15 @@ Object.defineProperty(Phaser.ArraySet.prototype, 'total', { }); /** -* Returns the first item and resets the cursor to the start. -* -* @name Phaser.ArraySet#first -* @property {any} first -*/ + * Returns the first item and resets the cursor to the start. + * + * @name Phaser.ArraySet#first + * @property {any} first + */ Object.defineProperty(Phaser.ArraySet.prototype, 'first', { get: function () { - this.position = 0; if (this.list.length > 0) @@ -260,22 +239,20 @@ Object.defineProperty(Phaser.ArraySet.prototype, 'first', { { return null; } - } }); /** -* Returns the the next item (based on the cursor) and advances the cursor. -* -* @name Phaser.ArraySet#next -* @property {any} next -*/ + * Returns the the next item (based on the cursor) and advances the cursor. + * + * @name Phaser.ArraySet#next + * @property {any} next + */ Object.defineProperty(Phaser.ArraySet.prototype, 'next', { get: function () { - if (this.position < this.list.length) { this.position++; @@ -286,7 +263,6 @@ Object.defineProperty(Phaser.ArraySet.prototype, 'next', { { return null; } - } }); diff --git a/src/utils/ArrayUtils.js b/src/utils/ArrayUtils.js index de9b5f6c6..701f3b672 100644 --- a/src/utils/ArrayUtils.js +++ b/src/utils/ArrayUtils.js @@ -1,32 +1,31 @@ /** -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* Utility functions for dealing with Arrays. -* -* @class Phaser.ArrayUtils -* @static -*/ + * Utility functions for dealing with Arrays. + * + * @class Phaser.ArrayUtils + * @static + */ Phaser.ArrayUtils = { /** - * Fetch a random entry from the given array. - * - * Will return null if there are no array items that fall within the specified range - * or if there is no item for the randomly chosen index. - * - * @method Phaser.ArrayUtils.getRandomItem - * @param {any[]} objects - An array of objects. - * @param {integer} startIndex - Optional offset off the front of the array. Default value is 0, or the beginning of the array. - * @param {integer} length - Optional restriction on the number of values you want to randomly select from. - * @return {object} The random object that was selected. - */ + * Fetch a random entry from the given array. + * + * Will return null if there are no array items that fall within the specified range + * or if there is no item for the randomly chosen index. + * + * @method Phaser.ArrayUtils.getRandomItem + * @param {any[]} objects - An array of objects. + * @param {integer} startIndex - Optional offset off the front of the array. Default value is 0, or the beginning of the array. + * @param {integer} length - Optional restriction on the number of values you want to randomly select from. + * @return {object} The random object that was selected. + */ getRandomItem: function (objects, startIndex, length) { - if (objects === null) { return null; } if (startIndex === undefined) { startIndex = 0; } if (length === undefined) { length = objects.length; } @@ -34,24 +33,22 @@ Phaser.ArrayUtils = { var randomIndex = startIndex + Math.floor(Math.random() * length); return objects[randomIndex] === undefined ? null : objects[randomIndex]; - }, /** - * Removes a random object from the given array and returns it. - * - * Will return null if there are no array items that fall within the specified range - * or if there is no item for the randomly chosen index. - * - * @method Phaser.ArrayUtils.removeRandomItem - * @param {any[]} objects - An array of objects. - * @param {integer} startIndex - Optional offset off the front of the array. Default value is 0, or the beginning of the array. - * @param {integer} length - Optional restriction on the number of values you want to randomly select from. - * @return {object} The random object that was removed. - */ + * Removes a random object from the given array and returns it. + * + * Will return null if there are no array items that fall within the specified range + * or if there is no item for the randomly chosen index. + * + * @method Phaser.ArrayUtils.removeRandomItem + * @param {any[]} objects - An array of objects. + * @param {integer} startIndex - Optional offset off the front of the array. Default value is 0, or the beginning of the array. + * @param {integer} length - Optional restriction on the number of values you want to randomly select from. + * @return {object} The random object that was removed. + */ removeRandomItem: function (objects, startIndex, length) { - if (objects == null) { // undefined or null return null; @@ -70,25 +67,24 @@ Phaser.ArrayUtils = { { return null; } - }, /** - * Remove one or more items at the given index and reorder the array. - * - * The new array length will be `array.length - count`. - * - * This is an alternative to `array.splice(startIndex, count)`. - * - * @see https://github.com/mreinstein/remove-array-items - * @see https://gamealchemist.wordpress.com/2013/05/01/lets-get-those-javascript-arrays-to-work-fast/ - * - * @method Phaser.ArrayUtils.remove - * @param {any[]} array - * @param {integer} startIndex - * @param {integer} [count=1] - * @return {any[]} The modified array. - */ + * Remove one or more items at the given index and reorder the array. + * + * The new array length will be `array.length - count`. + * + * This is an alternative to `array.splice(startIndex, count)`. + * + * @see https://github.com/mreinstein/remove-array-items + * @see https://gamealchemist.wordpress.com/2013/05/01/lets-get-those-javascript-arrays-to-work-fast/ + * + * @method Phaser.ArrayUtils.remove + * @param {any[]} array + * @param {integer} startIndex + * @param {integer} [count=1] + * @return {any[]} The modified array. + */ remove: function (array, startIndex, count) { var length = array.length; @@ -108,15 +104,14 @@ Phaser.ArrayUtils = { }, /** - * A standard Fisher-Yates Array shuffle implementation which modifies the array in place. - * - * @method Phaser.ArrayUtils.shuffle - * @param {any[]} array - The array to shuffle. - * @return {any[]} The original array, now shuffled. - */ + * A standard Fisher-Yates Array shuffle implementation which modifies the array in place. + * + * @method Phaser.ArrayUtils.shuffle + * @param {any[]} array - The array to shuffle. + * @return {any[]} The original array, now shuffled. + */ shuffle: function (array) { - for (var i = array.length - 1; i > 0; i--) { var j = Math.floor(Math.random() * (i + 1)); @@ -126,19 +121,17 @@ Phaser.ArrayUtils = { } return array; - }, /** - * Transposes the elements of the given matrix (array of arrays). - * - * @method Phaser.ArrayUtils.transposeMatrix - * @param {Array} array - The matrix to transpose. - * @return {Array} A new transposed matrix - */ + * Transposes the elements of the given matrix (array of arrays). + * + * @method Phaser.ArrayUtils.transposeMatrix + * @param {Array} array - The matrix to transpose. + * @return {Array} A new transposed matrix + */ transposeMatrix: function (array) { - var sourceRowCount = array.length; var sourceColCount = array[0].length; @@ -155,22 +148,20 @@ Phaser.ArrayUtils = { } return result; - }, /** - * Rotates the given matrix (array of arrays). - * - * Based on the routine from {@link http://jsfiddle.net/MrPolywhirl/NH42z/}. - * - * @method Phaser.ArrayUtils.rotateMatrix - * @param {Array} matrix - The array to rotate; this matrix _may_ be altered. - * @param {number|string} direction - The amount to rotate: the rotation in degrees (90, -90, 270, -270, 180) or a string command ('rotateLeft', 'rotateRight' or 'rotate180'). - * @return {Array} The rotated matrix. The source matrix should be discarded for the returned matrix. - */ + * Rotates the given matrix (array of arrays). + * + * Based on the routine from {@link http://jsfiddle.net/MrPolywhirl/NH42z/}. + * + * @method Phaser.ArrayUtils.rotateMatrix + * @param {Array} matrix - The array to rotate; this matrix _may_ be altered. + * @param {number|string} direction - The amount to rotate: the rotation in degrees (90, -90, 270, -270, 180) or a string command ('rotateLeft', 'rotateRight' or 'rotate180'). + * @return {Array} The rotated matrix. The source matrix should be discarded for the returned matrix. + */ rotateMatrix: function (matrix, direction) { - if (typeof direction !== 'string') { direction = ((direction % 360) + 360) % 360; @@ -197,21 +188,19 @@ Phaser.ArrayUtils = { } return matrix; - }, /** - * Snaps a value to the nearest value in a sorted numeric array. - * The result will always be in the range `[first_value, last_value]`. - * - * @method Phaser.ArrayUtils.findClosest - * @param {number} value - The search value - * @param {number[]} arr - The input array which _must_ be sorted. - * @return {number} The nearest value found. - */ + * Snaps a value to the nearest value in a sorted numeric array. + * The result will always be in the range `[first_value, last_value]`. + * + * @method Phaser.ArrayUtils.findClosest + * @param {number} value - The search value + * @param {number[]} arr - The input array which _must_ be sorted. + * @return {number} The nearest value found. + */ findClosest: function (value, arr) { - if (!arr.length) { return NaN; @@ -231,77 +220,71 @@ Phaser.ArrayUtils = { var high = (i < arr.length) ? arr[i] : Number.POSITIVE_INFINITY; return ((high - value) <= (value - low)) ? high : low; - }, /** - * Moves the element from the end of the array to the start, shifting all items in the process. - * The "rotation" happens to the right. - * - * Before: `[ A, B, C, D, E, F ]` - * After: `[ F, A, B, C, D, E ]` - * - * See also Phaser.ArrayUtils.rotateLeft. - * - * @method Phaser.ArrayUtils.rotateRight - * @param {any[]} array - The array to rotate. The array is modified. - * @return {any} The shifted value. - */ + * Moves the element from the end of the array to the start, shifting all items in the process. + * The "rotation" happens to the right. + * + * Before: `[ A, B, C, D, E, F ]` + * After: `[ F, A, B, C, D, E ]` + * + * See also Phaser.ArrayUtils.rotateLeft. + * + * @method Phaser.ArrayUtils.rotateRight + * @param {any[]} array - The array to rotate. The array is modified. + * @return {any} The shifted value. + */ rotateRight: function (array) { - var s = array.pop(); array.unshift(s); return s; - }, /** - * Moves the element from the start of the array to the end, shifting all items in the process. - * The "rotation" happens to the left. - * - * Before: `[ A, B, C, D, E, F ]` - * After: `[ B, C, D, E, F, A ]` - * - * See also Phaser.ArrayUtils.rotateRight - * - * @method Phaser.ArrayUtils.rotateLeft - * @param {any[]} array - The array to rotate. The array is modified. - * @return {any} The rotated value. - */ + * Moves the element from the start of the array to the end, shifting all items in the process. + * The "rotation" happens to the left. + * + * Before: `[ A, B, C, D, E, F ]` + * After: `[ B, C, D, E, F, A ]` + * + * See also Phaser.ArrayUtils.rotateRight + * + * @method Phaser.ArrayUtils.rotateLeft + * @param {any[]} array - The array to rotate. The array is modified. + * @return {any} The rotated value. + */ rotateLeft: function (array) { - var s = array.shift(); array.push(s); return s; - }, /** - * Create an array representing the inclusive range of numbers (usually integers) in `[start, end]` (or `[0, start]`, if `end` is omitted). - * This is equivalent to `numberArrayStep(start, 1 + end, 1)`. - * - * When exactly one argument is passed, it's used as `end` and 0 is used as `start`. The length of the result is (1 + end). - * - * ##### Examples - * - * ```javascript - * numberArray(3); // -> [0, 1, 2, 3] - * numberArray(0, 3); // -> [0, 1, 2, 3] - * numberArray(1, 3); // -> [1, 2, 3] - * ``` - * - * @method Phaser.ArrayUtils.numberArray - * @param {number} start - The minimum value the array starts with. - * @param {number} [end] - The maximum value the array contains. - * @return {number[]} The array of number values. - */ + * Create an array representing the inclusive range of numbers (usually integers) in `[start, end]` (or `[0, start]`, if `end` is omitted). + * This is equivalent to `numberArrayStep(start, 1 + end, 1)`. + * + * When exactly one argument is passed, it's used as `end` and 0 is used as `start`. The length of the result is (1 + end). + * + * ##### Examples + * + * ```javascript + * numberArray(3); // -> [0, 1, 2, 3] + * numberArray(0, 3); // -> [0, 1, 2, 3] + * numberArray(1, 3); // -> [1, 2, 3] + * ``` + * + * @method Phaser.ArrayUtils.numberArray + * @param {number} start - The minimum value the array starts with. + * @param {number} [end] - The maximum value the array contains. + * @return {number[]} The array of number values. + */ numberArray: function (start, end) { - if (end === undefined || end === null) { end = start; @@ -316,45 +299,43 @@ Phaser.ArrayUtils = { } return result; - }, /** - * Create an array of numbers (positive and/or negative) progressing from `start` - * up to but not including `end` by advancing by `step`. - * - * If `start` is less than `end` a zero-length range is created unless a negative `step` is specified. - * - * Certain values for `start` and `end` (eg. NaN/undefined/null) are currently coerced to 0; - * for forward compatibility make sure to pass in actual numbers. - * - * @method Phaser.ArrayUtils.numberArrayStep - * @param {number} start - The start of the range. - * @param {number} [end] - The end of the range. - * @param {number} [step=1] - The value to increment or decrement by. - * @returns {Array} Returns the new array of numbers. - * @example - * Phaser.ArrayUtils.numberArrayStep(4); - * // => [0, 1, 2, 3] - * - * Phaser.ArrayUtils.numberArrayStep(1, 5); - * // => [1, 2, 3, 4] - * - * Phaser.ArrayUtils.numberArrayStep(0, 20, 5); - * // => [0, 5, 10, 15] - * - * Phaser.ArrayUtils.numberArrayStep(0, -4, -1); - * // => [0, -1, -2, -3] - * - * Phaser.ArrayUtils.numberArrayStep(1, 4, 0); - * // => [1, 1, 1] - * - * Phaser.ArrayUtils.numberArrayStep(0); - * // => [] - */ + * Create an array of numbers (positive and/or negative) progressing from `start` + * up to but not including `end` by advancing by `step`. + * + * If `start` is less than `end` a zero-length range is created unless a negative `step` is specified. + * + * Certain values for `start` and `end` (eg. NaN/undefined/null) are currently coerced to 0; + * for forward compatibility make sure to pass in actual numbers. + * + * @method Phaser.ArrayUtils.numberArrayStep + * @param {number} start - The start of the range. + * @param {number} [end] - The end of the range. + * @param {number} [step=1] - The value to increment or decrement by. + * @returns {Array} Returns the new array of numbers. + * @example + * Phaser.ArrayUtils.numberArrayStep(4); + * // => [0, 1, 2, 3] + * + * Phaser.ArrayUtils.numberArrayStep(1, 5); + * // => [1, 2, 3, 4] + * + * Phaser.ArrayUtils.numberArrayStep(0, 20, 5); + * // => [0, 5, 10, 15] + * + * Phaser.ArrayUtils.numberArrayStep(0, -4, -1); + * // => [0, -1, -2, -3] + * + * Phaser.ArrayUtils.numberArrayStep(1, 4, 0); + * // => [1, 1, 1] + * + * Phaser.ArrayUtils.numberArrayStep(0); + * // => [] + */ numberArrayStep: function (start, end, step) { - if (start === undefined || start === null) { start = 0; } if (end === undefined || end === null) @@ -375,7 +356,6 @@ Phaser.ArrayUtils = { } return result; - } }; diff --git a/src/utils/Canvas.js b/src/utils/Canvas.js index 23e31ed0f..69e166dfc 100644 --- a/src/utils/Canvas.js +++ b/src/utils/Canvas.js @@ -1,32 +1,31 @@ /** -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* The Canvas class handles everything related to creating the `canvas` DOM tag that Phaser will use, -* including styles, offset and aspect ratio. -* -* @class Phaser.Canvas -* @static -*/ + * The Canvas class handles everything related to creating the `canvas` DOM tag that Phaser will use, + * including styles, offset and aspect ratio. + * + * @class Phaser.Canvas + * @static + */ Phaser.Canvas = { /** - * Creates a `canvas` DOM element. The element is not automatically added to the document. - * - * @method Phaser.Canvas.create - * @param {object} parent - The object that will own the canvas that is created. - * @param {number} [width=256] - The width of the canvas element. - * @param {number} [height=256] - The height of the canvas element.. - * @param {string} [id=(none)] - If specified, and not the empty string, this will be set as the ID of the canvas element. Otherwise no ID will be set. - * @param {boolean} [skipPool=false] - If `true` the canvas will not be placed in the CanvasPool global. - * @return {HTMLCanvasElement} The newly created canvas element. - */ + * Creates a `canvas` DOM element. The element is not automatically added to the document. + * + * @method Phaser.Canvas.create + * @param {object} parent - The object that will own the canvas that is created. + * @param {number} [width=256] - The width of the canvas element. + * @param {number} [height=256] - The height of the canvas element.. + * @param {string} [id=(none)] - If specified, and not the empty string, this will be set as the ID of the canvas element. Otherwise no ID will be set. + * @param {boolean} [skipPool=false] - If `true` the canvas will not be placed in the CanvasPool global. + * @return {HTMLCanvasElement} The newly created canvas element. + */ create: function (parent, width, height, id, skipPool) { - width = width || 256; height = height || 256; @@ -42,39 +41,35 @@ Phaser.Canvas = { canvas.style.display = 'block'; return canvas; - }, /** - * Sets the background color behind the canvas. This changes the canvas style property. - * - * @method Phaser.Canvas.setBackgroundColor - * @param {HTMLCanvasElement} canvas - The canvas to set the background color on. - * @param {string} [color='rgb(0,0,0)'] - The color to set. Can be in the format 'rgb(r,g,b)', or '#RRGGBB' or any valid CSS color. - * @return {HTMLCanvasElement} Returns the source canvas. - */ + * Sets the background color behind the canvas. This changes the canvas style property. + * + * @method Phaser.Canvas.setBackgroundColor + * @param {HTMLCanvasElement} canvas - The canvas to set the background color on. + * @param {string} [color='rgb(0,0,0)'] - The color to set. Can be in the format 'rgb(r,g,b)', or '#RRGGBB' or any valid CSS color. + * @return {HTMLCanvasElement} Returns the source canvas. + */ setBackgroundColor: function (canvas, color) { - color = color || 'rgb(0,0,0)'; canvas.style.backgroundColor = color; return canvas; - }, /** - * Sets the touch-action property on the canvas style. Can be used to disable default browser touch actions. - * - * @method Phaser.Canvas.setTouchAction - * @param {HTMLCanvasElement} canvas - The canvas to set the touch action on. - * @param {string} [value] - The touch action to set. Defaults to 'none'. - * @return {HTMLCanvasElement} The source canvas. - */ + * Sets the touch-action property on the canvas style. Can be used to disable default browser touch actions. + * + * @method Phaser.Canvas.setTouchAction + * @param {HTMLCanvasElement} canvas - The canvas to set the touch action on. + * @param {string} [value] - The touch action to set. Defaults to 'none'. + * @return {HTMLCanvasElement} The source canvas. + */ setTouchAction: function (canvas, value) { - value = value || 'none'; canvas.style.msTouchAction = value; @@ -82,20 +77,18 @@ Phaser.Canvas = { canvas.style['touch-action'] = value; return canvas; - }, /** - * Sets the user-select property on the canvas style. Can be used to disable default browser selection actions. - * - * @method Phaser.Canvas.setUserSelect - * @param {HTMLCanvasElement} canvas - The canvas to set the touch action on. - * @param {string} [value] - The touch action to set. Defaults to 'none'. - * @return {HTMLCanvasElement} The source canvas. - */ + * Sets the user-select property on the canvas style. Can be used to disable default browser selection actions. + * + * @method Phaser.Canvas.setUserSelect + * @param {HTMLCanvasElement} canvas - The canvas to set the touch action on. + * @param {string} [value] - The touch action to set. Defaults to 'none'. + * @return {HTMLCanvasElement} The source canvas. + */ setUserSelect: function (canvas, value) { - value = value || 'none'; canvas.style['-webkit-touch-callout'] = value; @@ -107,22 +100,20 @@ Phaser.Canvas = { canvas.style['-webkit-tap-highlight-color'] = 'rgba(0, 0, 0, 0)'; return canvas; - }, /** - * Adds the given canvas element to the DOM. The canvas will be added as a child of the given parent. - * If no parent is given it will be added as a child of the document.body. - * - * @method Phaser.Canvas.addToDOM - * @param {HTMLCanvasElement} canvas - The canvas to be added to the DOM. - * @param {string|HTMLElement} parent - The DOM element to add the canvas to. - * @param {boolean} [overflowHidden=true] - If set to true it will add the overflow='hidden' style to the parent DOM element. - * @return {HTMLCanvasElement} Returns the source canvas. - */ + * Adds the given canvas element to the DOM. The canvas will be added as a child of the given parent. + * If no parent is given it will be added as a child of the document.body. + * + * @method Phaser.Canvas.addToDOM + * @param {HTMLCanvasElement} canvas - The canvas to be added to the DOM. + * @param {string|HTMLElement} parent - The DOM element to add the canvas to. + * @param {boolean} [overflowHidden=true] - If set to true it will add the overflow='hidden' style to the parent DOM element. + * @return {HTMLCanvasElement} Returns the source canvas. + */ addToDOM: function (canvas, parent, overflowHidden) { - var target; if (overflowHidden === undefined) { overflowHidden = true; } @@ -155,62 +146,56 @@ Phaser.Canvas = { target.appendChild(canvas); return canvas; - }, /** - * Removes the given canvas element from the DOM. - * - * @method Phaser.Canvas.removeFromDOM - * @param {HTMLCanvasElement} canvas - The canvas to be removed from the DOM. - */ + * Removes the given canvas element from the DOM. + * + * @method Phaser.Canvas.removeFromDOM + * @param {HTMLCanvasElement} canvas - The canvas to be removed from the DOM. + */ removeFromDOM: function (canvas) { - if (canvas.parentNode) { canvas.parentNode.removeChild(canvas); } - }, /** - * Sets the transform of the given canvas to the matrix values provided. - * - * @method Phaser.Canvas.setTransform - * @param {CanvasRenderingContext2D} context - The context to set the transform on. - * @param {number} translateX - The value to translate horizontally by. - * @param {number} translateY - The value to translate vertically by. - * @param {number} scaleX - The value to scale horizontally by. - * @param {number} scaleY - The value to scale vertically by. - * @param {number} skewX - The value to skew horizontaly by. - * @param {number} skewY - The value to skew vertically by. - * @return {CanvasRenderingContext2D} Returns the source context. - */ + * Sets the transform of the given canvas to the matrix values provided. + * + * @method Phaser.Canvas.setTransform + * @param {CanvasRenderingContext2D} context - The context to set the transform on. + * @param {number} translateX - The value to translate horizontally by. + * @param {number} translateY - The value to translate vertically by. + * @param {number} scaleX - The value to scale horizontally by. + * @param {number} scaleY - The value to scale vertically by. + * @param {number} skewX - The value to skew horizontaly by. + * @param {number} skewY - The value to skew vertically by. + * @return {CanvasRenderingContext2D} Returns the source context. + */ setTransform: function (context, translateX, translateY, scaleX, scaleY, skewX, skewY) { - context.setTransform(scaleX, skewX, skewY, scaleY, translateX, translateY); return context; - }, /** - * Sets the Image Smoothing property on the given context. Set to false to disable image smoothing. - * By default browsers have image smoothing enabled, which isn't always what you visually want, especially - * when using pixel art in a game. Note that this sets the property on the context itself, so that any image - * drawn to the context will be affected. This sets the property across all current browsers but support is - * patchy on earlier browsers, especially on mobile. - * - * @method Phaser.Canvas.setSmoothingEnabled - * @param {CanvasRenderingContext2D} context - The context to enable or disable the image smoothing on. - * @param {boolean} value - If set to true it will enable image smoothing, false will disable it. - * @return {CanvasRenderingContext2D} Returns the source context. - */ + * Sets the Image Smoothing property on the given context. Set to false to disable image smoothing. + * By default browsers have image smoothing enabled, which isn't always what you visually want, especially + * when using pixel art in a game. Note that this sets the property on the context itself, so that any image + * drawn to the context will be affected. This sets the property across all current browsers but support is + * patchy on earlier browsers, especially on mobile. + * + * @method Phaser.Canvas.setSmoothingEnabled + * @param {CanvasRenderingContext2D} context - The context to enable or disable the image smoothing on. + * @param {boolean} value - If set to true it will enable image smoothing, false will disable it. + * @return {CanvasRenderingContext2D} Returns the source context. + */ setSmoothingEnabled: function (context, value) { - var s = Phaser.Canvas.getSmoothingPrefix(context); if (s) @@ -219,19 +204,17 @@ Phaser.Canvas = { } return context; - }, /** - * Gets the Smoothing Enabled vendor prefix being used on the given context, or null if not set. - * - * @method Phaser.Canvas.getSmoothingPrefix - * @param {CanvasRenderingContext2D} context - The context to enable or disable the image smoothing on. - * @return {string|null} Returns the smoothingEnabled vendor prefix, or null if not set on the context. - */ + * Gets the Smoothing Enabled vendor prefix being used on the given context, or null if not set. + * + * @method Phaser.Canvas.getSmoothingPrefix + * @param {CanvasRenderingContext2D} context - The context to enable or disable the image smoothing on. + * @return {string|null} Returns the smoothingEnabled vendor prefix, or null if not set on the context. + */ getSmoothingPrefix: function (context) { - var vendor = [ 'i', 'webkitI', 'msI', 'mozI', 'oI' ]; for (var prefix in vendor) @@ -245,7 +228,6 @@ Phaser.Canvas = { } return null; - }, /** @@ -257,31 +239,28 @@ Phaser.Canvas = { */ getSmoothingEnabled: function (context) { - var s = Phaser.Canvas.getSmoothingPrefix(context); if (s) { return context[s]; } - }, /** - * Sets the CSS image-rendering property to `pixelated` or `crisp-edges`. - * This can remove blurring when the game canvas is scaled up. - * In some browsers this has no visible effect in WEBGL mode. - * Note that if this doesn't given the desired result then see the setSmoothingEnabled. - * - * @method Phaser.Canvas.setImageRenderingCrisp - * @param {HTMLCanvasElement} canvas - The canvas to set image-rendering crisp on. - * @return {HTMLCanvasElement} Returns the source canvas. - * @see https://developer.mozilla.org/en-US/docs/Web/CSS/image-rendering - * @see https://caniuse.com/#feat=css-crisp-edges - */ + * Sets the CSS image-rendering property to `pixelated` or `crisp-edges`. + * This can remove blurring when the game canvas is scaled up. + * In some browsers this has no visible effect in WEBGL mode. + * Note that if this doesn't given the desired result then see the setSmoothingEnabled. + * + * @method Phaser.Canvas.setImageRenderingCrisp + * @param {HTMLCanvasElement} canvas - The canvas to set image-rendering crisp on. + * @return {HTMLCanvasElement} Returns the source canvas. + * @see https://developer.mozilla.org/en-US/docs/Web/CSS/image-rendering + * @see https://caniuse.com/#feat=css-crisp-edges + */ setImageRenderingCrisp: function (canvas) { - var types = [ '-webkit-optimize-contrast', '-moz-crisp-edges', 'crisp-edges', 'pixelated' ]; for (var i = 0; i < types.length; i++) @@ -292,25 +271,22 @@ Phaser.Canvas = { canvas.style.msInterpolationMode = 'nearest-neighbor'; return canvas; - }, /** - * Sets the CSS image-rendering property on the given canvas to be 'bicubic' (aka 'auto'). - * Note that if this doesn't given the desired result then see the CanvasUtils.setSmoothingEnabled method. - * - * @method Phaser.Canvas.setImageRenderingBicubic - * @param {HTMLCanvasElement} canvas The canvas to set image-rendering bicubic on. - * @return {HTMLCanvasElement} Returns the source canvas. - */ + * Sets the CSS image-rendering property on the given canvas to be 'bicubic' (aka 'auto'). + * Note that if this doesn't given the desired result then see the CanvasUtils.setSmoothingEnabled method. + * + * @method Phaser.Canvas.setImageRenderingBicubic + * @param {HTMLCanvasElement} canvas The canvas to set image-rendering bicubic on. + * @return {HTMLCanvasElement} Returns the source canvas. + */ setImageRenderingBicubic: function (canvas) { - canvas.style['image-rendering'] = 'auto'; canvas.style.msInterpolationMode = 'bicubic'; return canvas; - } }; diff --git a/src/utils/CanvasPool.js b/src/utils/CanvasPool.js index e21a0fe0c..007160cfc 100644 --- a/src/utils/CanvasPool.js +++ b/src/utils/CanvasPool.js @@ -1,30 +1,29 @@ /** -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* The CanvasPool is a global static object, that allows Phaser to recycle and pool Canvas DOM elements. -* -* @class Phaser.CanvasPool -* @static -*/ + * The CanvasPool is a global static object, that allows Phaser to recycle and pool Canvas DOM elements. + * + * @class Phaser.CanvasPool + * @static + */ Phaser.CanvasPool = { /** - * Creates a new Canvas DOM element, or pulls one from the pool if free. - * - * @method Phaser.CanvasPool.create - * @static - * @param {any} parent - The parent of the canvas element. - * @param {number} width - The width of the canvas element. - * @param {number} height - The height of the canvas element. - * @return {HTMLCanvasElement} The canvas element. - */ + * Creates a new Canvas DOM element, or pulls one from the pool if free. + * + * @method Phaser.CanvasPool.create + * @static + * @param {any} parent - The parent of the canvas element. + * @param {number} width - The width of the canvas element. + * @param {number} height - The height of the canvas element. + * @return {HTMLCanvasElement} The canvas element. + */ create: function (parent, width, height) { - var idx = Phaser.CanvasPool.getFirst(); var canvas; @@ -53,19 +52,17 @@ Phaser.CanvasPool = { } return canvas; - }, /** - * Gets the first free canvas index from the pool. - * - * @static - * @method Phaser.CanvasPool.getFirst - * @return {number} - */ + * Gets the first free canvas index from the pool. + * + * @static + * @method Phaser.CanvasPool.getFirst + * @return {number} + */ getFirst: function () { - var pool = Phaser.CanvasPool.pool; for (var i = 0; i < pool.length; i++) @@ -77,20 +74,18 @@ Phaser.CanvasPool = { } return -1; - }, /** - * Looks up a canvas based on its parent, and if found puts it back in the pool, freeing it up for re-use. - * The canvas has its width and height set to 1, and its parent attribute nulled. - * - * @static - * @method Phaser.CanvasPool.remove - * @param {any} parent - The parent of the canvas element. - */ + * Looks up a canvas based on its parent, and if found puts it back in the pool, freeing it up for re-use. + * The canvas has its width and height set to 1, and its parent attribute nulled. + * + * @static + * @method Phaser.CanvasPool.remove + * @param {any} parent - The parent of the canvas element. + */ remove: function (parent) { - var pool = Phaser.CanvasPool.pool; for (var i = 0; i < pool.length; i++) @@ -102,20 +97,18 @@ Phaser.CanvasPool = { pool[i].canvas.height = 1; } } - }, /** - * Looks up a canvas based on its type, and if found puts it back in the pool, freeing it up for re-use. - * The canvas has its width and height set to 1, and its parent attribute nulled. - * - * @static - * @method Phaser.CanvasPool.removeByCanvas - * @param {HTMLCanvasElement} canvas - The canvas element to remove. - */ + * Looks up a canvas based on its type, and if found puts it back in the pool, freeing it up for re-use. + * The canvas has its width and height set to 1, and its parent attribute nulled. + * + * @static + * @method Phaser.CanvasPool.removeByCanvas + * @param {HTMLCanvasElement} canvas - The canvas element to remove. + */ removeByCanvas: function (canvas) { - var pool = Phaser.CanvasPool.pool; for (var i = 0; i < pool.length; i++) @@ -127,19 +120,17 @@ Phaser.CanvasPool = { pool[i].canvas.height = 1; } } - }, /** - * Gets the total number of used canvas elements in the pool. - * - * @static - * @method Phaser.CanvasPool.getTotal - * @return {number} The number of in-use (parented) canvas elements in the pool. - */ + * Gets the total number of used canvas elements in the pool. + * + * @static + * @method Phaser.CanvasPool.getTotal + * @return {number} The number of in-use (parented) canvas elements in the pool. + */ getTotal: function () { - var pool = Phaser.CanvasPool.pool; var c = 0; @@ -152,19 +143,17 @@ Phaser.CanvasPool = { } return c; - }, /** - * Gets the total number of free canvas elements in the pool. - * - * @static - * @method Phaser.CanvasPool.getFree - * @return {number} The number of free (un-parented) canvas elements in the pool. - */ + * Gets the total number of free canvas elements in the pool. + * + * @static + * @method Phaser.CanvasPool.getFree + * @return {number} The number of free (un-parented) canvas elements in the pool. + */ getFree: function () { - var pool = Phaser.CanvasPool.pool; var c = 0; @@ -177,26 +166,23 @@ Phaser.CanvasPool = { } return c; - }, /** - * Prints in-use, free, and total counts to console.log. - * - * @static - * @method Phaser.CanvasPool.log - */ + * Prints in-use, free, and total counts to console.log. + * + * @static + * @method Phaser.CanvasPool.log + */ log: function () { - console.log( 'CanvasPool: %s used, %s free, %s total', Phaser.CanvasPool.getTotal(), Phaser.CanvasPool.getFree(), Phaser.CanvasPool.pool.length ); - } }; diff --git a/src/utils/Color.js b/src/utils/Color.js index 49f8b2088..6392093a2 100644 --- a/src/utils/Color.js +++ b/src/utils/Color.js @@ -1,122 +1,121 @@ /** -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* The Phaser.Color class is a set of static methods that assist in color manipulation and conversion. -* -* @class Phaser.Color -*/ + * The Phaser.Color class is a set of static methods that assist in color manipulation and conversion. + * + * @class Phaser.Color + */ Phaser.Color = { /** - * Red (0xff0000) - * - * @type number - * @constant - * @default - */ + * Red (0xff0000) + * + * @type number + * @constant + * @default + */ RED: 0xff0000, /** - * Orange (0xff9900) - * - * @type number - * @constant - * @default - */ + * Orange (0xff9900) + * + * @type number + * @constant + * @default + */ ORANGE: 0xff9900, /** - * Yellow (0xffff00) - * - * @type number - * @constant - * @default - */ + * Yellow (0xffff00) + * + * @type number + * @constant + * @default + */ YELLOW: 0xffff00, /** - * Green (0x00ff00) - * - * @type number - * @constant - * @default - */ + * Green (0x00ff00) + * + * @type number + * @constant + * @default + */ GREEN: 0x00ff00, /** - * Aqua (0x00ffff) - * - * @type number - * @constant - * @default - */ + * Aqua (0x00ffff) + * + * @type number + * @constant + * @default + */ AQUA: 0x00ffff, /** - * Blue (0x0000ff) - * - * @type number - * @constant - * @default - */ + * Blue (0x0000ff) + * + * @type number + * @constant + * @default + */ BLUE: 0x0000ff, /** - * Violet/purple (0xff00ff) - * - * @type number - * @constant - * @default - */ + * Violet/purple (0xff00ff) + * + * @type number + * @constant + * @default + */ VIOLET: 0xff00ff, /** - * White (0xffffff) - * - * @type number - * @constant - * @default - */ + * White (0xffffff) + * + * @type number + * @constant + * @default + */ WHITE: 0xffffff, /** - * Black (0x000000) - * - * @type number - * @constant - * @default - */ + * Black (0x000000) + * + * @type number + * @constant + * @default + */ BLACK: 0, /** - * Gray (0x666666) - * - * @type number - * @constant - * @default - */ + * Gray (0x666666) + * + * @type number + * @constant + * @default + */ GRAY: 0x666666, /** - * Packs the r, g, b, a components into a single integer, for use with Int32Array. - * If device is little endian then ABGR order is used. Otherwise RGBA order is used. - * - * @author Matt DesLauriers (@mattdesl) - * @method Phaser.Color.packPixel - * @static - * @param {number} r - The red color component, in the range 0 - 255. - * @param {number} g - The green color component, in the range 0 - 255. - * @param {number} b - The blue color component, in the range 0 - 255. - * @param {number} a - The alpha color component, in the range 0 - 255. - * @return {number} The packed color as uint32 - */ + * Packs the r, g, b, a components into a single integer, for use with Int32Array. + * If device is little endian then ABGR order is used. Otherwise RGBA order is used. + * + * @author Matt DesLauriers (@mattdesl) + * @method Phaser.Color.packPixel + * @static + * @param {number} r - The red color component, in the range 0 - 255. + * @param {number} g - The green color component, in the range 0 - 255. + * @param {number} b - The blue color component, in the range 0 - 255. + * @param {number} a - The alpha color component, in the range 0 - 255. + * @return {number} The packed color as uint32 + */ packPixel: function (r, g, b, a) { - if (Phaser.Device.LITTLE_ENDIAN) { return ((a << 24) | (b << 16) | (g << 8) | r) >>> 0; @@ -125,31 +124,29 @@ Phaser.Color = { { return ((r << 24) | (g << 16) | (b << 8) | a) >>> 0; } - }, /** - * Unpacks the r, g, b, a components into the specified color object, or a new - * object, for use with Int32Array. If little endian, then ABGR order is used when - * unpacking, otherwise, RGBA order is used. The resulting color object has the - * `r, g, b, a` properties which are unrelated to endianness. - * - * Note that the integer is assumed to be packed in the correct endianness. On little-endian - * the format is 0xAABBGGRR and on big-endian the format is 0xRRGGBBAA. If you want a - * endian-independent method, use fromRGBA(rgba) and toRGBA(r, g, b, a). - * - * @author Matt DesLauriers (@mattdesl) - * @method Phaser.Color.unpackPixel - * @static - * @param {number} rgba - The integer, packed in endian order by packPixel. - * @param {object} [out] - An object into which 3 properties will be created: r, g and b. If not provided a new object will be created. - * @param {boolean} [hsl=false] - Also convert the rgb values into hsl? - * @param {boolean} [hsv=false] - Also convert the rgb values into hsv? - * @return {object} An object with the red, green and blue values set in the r, g and b properties. - */ + * Unpacks the r, g, b, a components into the specified color object, or a new + * object, for use with Int32Array. If little endian, then ABGR order is used when + * unpacking, otherwise, RGBA order is used. The resulting color object has the + * `r, g, b, a` properties which are unrelated to endianness. + * + * Note that the integer is assumed to be packed in the correct endianness. On little-endian + * the format is 0xAABBGGRR and on big-endian the format is 0xRRGGBBAA. If you want a + * endian-independent method, use fromRGBA(rgba) and toRGBA(r, g, b, a). + * + * @author Matt DesLauriers (@mattdesl) + * @method Phaser.Color.unpackPixel + * @static + * @param {number} rgba - The integer, packed in endian order by packPixel. + * @param {object} [out] - An object into which 3 properties will be created: r, g and b. If not provided a new object will be created. + * @param {boolean} [hsl=false] - Also convert the rgb values into hsl? + * @param {boolean} [hsv=false] - Also convert the rgb values into hsv? + * @return {object} An object with the red, green and blue values set in the r, g and b properties. + */ unpackPixel: function (rgba, out, hsl, hsv) { - if (out === undefined || out === null) { out = Phaser.Color.createColor(); } if (hsl === undefined || hsl === null) { hsl = false; } if (hsv === undefined || hsv === null) { hsv = false; } @@ -183,23 +180,21 @@ Phaser.Color = { } return out; - }, /** - * A utility to convert an integer in 0xRRGGBBAA format to a color object. - * This does not rely on endianness. - * - * @author Matt DesLauriers (@mattdesl) - * @method Phaser.Color.fromRGBA - * @static - * @param {number} rgba - An RGBA hex - * @param {object} [out] - The object to use, optional. - * @return {object} A color object. - */ + * A utility to convert an integer in 0xRRGGBBAA format to a color object. + * This does not rely on endianness. + * + * @author Matt DesLauriers (@mattdesl) + * @method Phaser.Color.fromRGBA + * @static + * @param {number} rgba - An RGBA hex + * @param {object} [out] - The object to use, optional. + * @return {object} A color object. + */ fromRGBA: function (rgba, out) { - if (!out) { out = Phaser.Color.createColor(); @@ -213,97 +208,87 @@ Phaser.Color = { out.rgba = 'rgba(' + out.r + ',' + out.g + ',' + out.b + ',' + out.a + ')'; return out; - }, /** - * A utility to convert RGBA components to a 32 bit integer in RRGGBBAA format. - * - * @author Matt DesLauriers (@mattdesl) - * @method Phaser.Color.toRGBA - * @static - * @param {number} r - The red color component, in the range 0 - 255. - * @param {number} g - The green color component, in the range 0 - 255. - * @param {number} b - The blue color component, in the range 0 - 255. - * @param {number} a - The alpha color component, in the range 0 - 255. - * @return {number} A RGBA-packed 32 bit integer - */ + * A utility to convert RGBA components to a 32 bit integer in RRGGBBAA format. + * + * @author Matt DesLauriers (@mattdesl) + * @method Phaser.Color.toRGBA + * @static + * @param {number} r - The red color component, in the range 0 - 255. + * @param {number} g - The green color component, in the range 0 - 255. + * @param {number} b - The blue color component, in the range 0 - 255. + * @param {number} a - The alpha color component, in the range 0 - 255. + * @return {number} A RGBA-packed 32 bit integer + */ toRGBA: function (r, g, b, a) { - return (r << 24) | (g << 16) | (b << 8) | a; - }, /** - * Converts RGBA components to a 32 bit integer in AABBGGRR format. - * - * @method Phaser.Color.toABGR - * @static - * @param {number} r - The red color component, in the range 0 - 255. - * @param {number} g - The green color component, in the range 0 - 255. - * @param {number} b - The blue color component, in the range 0 - 255. - * @param {number} a - The alpha color component, in the range 0 - 255. - * @return {number} A RGBA-packed 32 bit integer - */ + * Converts RGBA components to a 32 bit integer in AABBGGRR format. + * + * @method Phaser.Color.toABGR + * @static + * @param {number} r - The red color component, in the range 0 - 255. + * @param {number} g - The green color component, in the range 0 - 255. + * @param {number} b - The blue color component, in the range 0 - 255. + * @param {number} a - The alpha color component, in the range 0 - 255. + * @return {number} A RGBA-packed 32 bit integer + */ toABGR: function (r, g, b, a) { - return ((a << 24) | (b << 16) | (g << 8) | r) >>> 0; - }, /** - * Converts a hex color value to an [R, G, B] array. - * - * @static - * @method Phaser.Color.hexToRGBArray - * @param {number} color - The color to convert to an RGB array. In the format 0xRRGGBB. - * @return {array} An array with element 0 containing the Red value, 1 containing Green, and 2 containing Blue. - */ + * Converts a hex color value to an [R, G, B] array. + * + * @static + * @method Phaser.Color.hexToRGBArray + * @param {number} color - The color to convert to an RGB array. In the format 0xRRGGBB. + * @return {array} An array with element 0 containing the Red value, 1 containing Green, and 2 containing Blue. + */ hexToRGBArray: function (color) { - return [ (color >> 16 & 0xFF) / 255, (color >> 8 & 0xFF) / 255, (color & 0xFF) / 255 ]; - }, /** - * Converts an RGB color array, in the format: [R, G, B], to a hex color value. - * - * @static - * @method Phaser.Color.RGBArrayToHex - * @param {array} rgb - An array with element 0 containing the Red value, 1 containing Green, and 2 containing Blue. - * @return {number} The color value, in the format 0xRRGGBB. - */ + * Converts an RGB color array, in the format: [R, G, B], to a hex color value. + * + * @static + * @method Phaser.Color.RGBArrayToHex + * @param {array} rgb - An array with element 0 containing the Red value, 1 containing Green, and 2 containing Blue. + * @return {number} The color value, in the format 0xRRGGBB. + */ RGBArrayToHex: function (rgb) { - return ((rgb[0] * 255 << 16) + (rgb[1] * 255 << 8) + rgb[2] * 255); - }, /** - * Converts an RGB color value to HSL (hue, saturation and lightness). - * Conversion forumla from http://en.wikipedia.org/wiki/HSL_color_space. - * Assumes RGB values are contained in the set [0, 255] and returns h, s and l in the set [0, 1]. - * Based on code by Michael Jackson (https://github.com/mjijackson) - * - * @method Phaser.Color.RGBtoHSL - * @static - * @param {number} r - The red color component, in the range 0 - 255. - * @param {number} g - The green color component, in the range 0 - 255. - * @param {number} b - The blue color component, in the range 0 - 255. - * @param {object} [out] - An object into which 3 properties will be created, h, s and l. If not provided a new object will be created. - * @return {object} An object with the hue, saturation and lightness values set in the h, s and l properties. - */ + * Converts an RGB color value to HSL (hue, saturation and lightness). + * Conversion forumla from http://en.wikipedia.org/wiki/HSL_color_space. + * Assumes RGB values are contained in the set [0, 255] and returns h, s and l in the set [0, 1]. + * Based on code by Michael Jackson (https://github.com/mjijackson) + * + * @method Phaser.Color.RGBtoHSL + * @static + * @param {number} r - The red color component, in the range 0 - 255. + * @param {number} g - The green color component, in the range 0 - 255. + * @param {number} b - The blue color component, in the range 0 - 255. + * @param {object} [out] - An object into which 3 properties will be created, h, s and l. If not provided a new object will be created. + * @return {object} An object with the hue, saturation and lightness values set in the h, s and l properties. + */ RGBtoHSL: function (r, g, b, out) { - if (!out) { out = Phaser.Color.createColor(r, g, b, 1); @@ -344,26 +329,24 @@ Phaser.Color = { } return out; - }, /** - * Converts an HSL (hue, saturation and lightness) color value to RGB. - * Conversion forumla from http://en.wikipedia.org/wiki/HSL_color_space. - * Assumes HSL values are contained in the set [0, 1] and returns r, g and b values in the set [0, 255]. - * Based on code by Michael Jackson (https://github.com/mjijackson) - * - * @method Phaser.Color.HSLtoRGB - * @static - * @param {number} h - The hue, in the range 0 - 1. - * @param {number} s - The saturation, in the range 0 - 1. - * @param {number} l - The lightness, in the range 0 - 1. - * @param {object} [out] - An object into which 3 properties will be created: r, g and b. If not provided a new object will be created. - * @return {object} An object with the red, green and blue values set in the r, g and b properties. - */ + * Converts an HSL (hue, saturation and lightness) color value to RGB. + * Conversion forumla from http://en.wikipedia.org/wiki/HSL_color_space. + * Assumes HSL values are contained in the set [0, 1] and returns r, g and b values in the set [0, 255]. + * Based on code by Michael Jackson (https://github.com/mjijackson) + * + * @method Phaser.Color.HSLtoRGB + * @static + * @param {number} h - The hue, in the range 0 - 1. + * @param {number} s - The saturation, in the range 0 - 1. + * @param {number} l - The lightness, in the range 0 - 1. + * @param {object} [out] - An object into which 3 properties will be created: r, g and b. If not provided a new object will be created. + * @return {object} An object with the red, green and blue values set in the r, g and b properties. + */ HSLtoRGB: function (h, s, l, out) { - if (!out) { out = Phaser.Color.createColor(l, l, l); @@ -385,9 +368,11 @@ Phaser.Color = { out.b = Phaser.Color.hueToColor(p, q, h - 1 / 3); } - // out.r = (out.r * 255 | 0); - // out.g = (out.g * 255 | 0); - // out.b = (out.b * 255 | 0); + /* + * out.r = (out.r * 255 | 0); + * out.g = (out.g * 255 | 0); + * out.b = (out.b * 255 | 0); + */ out.r = Math.floor((out.r * 255 | 0)); out.g = Math.floor((out.g * 255 | 0)); @@ -396,26 +381,24 @@ Phaser.Color = { Phaser.Color.updateColor(out); return out; - }, /** - * Converts an RGB color value to HSV (hue, saturation and value). - * Conversion forumla from http://en.wikipedia.org/wiki/HSL_color_space. - * Assumes RGB values are contained in the set [0, 255] and returns h, s and v in the set [0, 1]. - * Based on code by Michael Jackson (https://github.com/mjijackson) - * - * @method Phaser.Color.RGBtoHSV - * @static - * @param {number} r - The red color component, in the range 0 - 255. - * @param {number} g - The green color component, in the range 0 - 255. - * @param {number} b - The blue color component, in the range 0 - 255. - * @param {object} [out] - An object into which 3 properties will be created, h, s and v. If not provided a new object will be created. - * @return {object} An object with the hue, saturation and value set in the h, s and v properties. - */ + * Converts an RGB color value to HSV (hue, saturation and value). + * Conversion forumla from http://en.wikipedia.org/wiki/HSL_color_space. + * Assumes RGB values are contained in the set [0, 255] and returns h, s and v in the set [0, 1]. + * Based on code by Michael Jackson (https://github.com/mjijackson) + * + * @method Phaser.Color.RGBtoHSV + * @static + * @param {number} r - The red color component, in the range 0 - 255. + * @param {number} g - The green color component, in the range 0 - 255. + * @param {number} b - The blue color component, in the range 0 - 255. + * @param {object} [out] - An object into which 3 properties will be created, h, s and v. If not provided a new object will be created. + * @return {object} An object with the hue, saturation and value set in the h, s and v properties. + */ RGBtoHSV: function (r, g, b, out) { - if (!out) { out = Phaser.Color.createColor(r, g, b, 255); @@ -453,26 +436,24 @@ Phaser.Color = { } return out; - }, /** - * Converts an HSV (hue, saturation and value) color value to RGB. - * Conversion forumla from http://en.wikipedia.org/wiki/HSL_color_space. - * Assumes HSV values are contained in the set [0, 1] and returns r, g and b values in the set [0, 255]. - * Based on code by Michael Jackson (https://github.com/mjijackson) - * - * @method Phaser.Color.HSVtoRGB - * @static - * @param {number} h - The hue, in the range 0 - 1. - * @param {number} s - The saturation, in the range 0 - 1. - * @param {number} v - The value, in the range 0 - 1. - * @param {object} [out] - An object into which 3 properties will be created: r, g and b. If not provided a new object will be created. - * @return {object} An object with the red, green and blue values set in the r, g and b properties. - */ + * Converts an HSV (hue, saturation and value) color value to RGB. + * Conversion forumla from http://en.wikipedia.org/wiki/HSL_color_space. + * Assumes HSV values are contained in the set [0, 1] and returns r, g and b values in the set [0, 255]. + * Based on code by Michael Jackson (https://github.com/mjijackson) + * + * @method Phaser.Color.HSVtoRGB + * @static + * @param {number} h - The hue, in the range 0 - 1. + * @param {number} s - The saturation, in the range 0 - 1. + * @param {number} v - The value, in the range 0 - 1. + * @param {object} [out] - An object into which 3 properties will be created: r, g and b. If not provided a new object will be created. + * @return {object} An object with the red, green and blue values set in the r, g and b properties. + */ HSVtoRGB: function (h, s, v, out) { - if (out === undefined) { out = Phaser.Color.createColor(0, 0, 0, 1, h, s, 0, v); } var r, g, b; @@ -523,23 +504,21 @@ Phaser.Color = { Phaser.Color.updateColor(out); return out; - }, /** - * Converts a hue to an RGB color. - * Based on code by Michael Jackson (https://github.com/mjijackson) - * - * @method Phaser.Color.hueToColor - * @static - * @param {number} p - * @param {number} q - * @param {number} t - * @return {number} The color component value. - */ + * Converts a hue to an RGB color. + * Based on code by Michael Jackson (https://github.com/mjijackson) + * + * @method Phaser.Color.hueToColor + * @static + * @param {number} p + * @param {number} q + * @param {number} t + * @return {number} The color component value. + */ hueToColor: function (p, q, t) { - if (t < 0) { t += 1; @@ -566,107 +545,97 @@ Phaser.Color = { } return p; - }, /** - * A utility function to create a lightweight 'color' object with the default components. - * Any components that are not specified will default to zero. - * - * This is useful when you want to use a shared color object for the getPixel and getPixelAt methods. - * - * @author Matt DesLauriers (@mattdesl) - * @method Phaser.Color.createColor - * @static - * @param {number} [r=0] - The red color component, in the range 0 - 255. - * @param {number} [g=0] - The green color component, in the range 0 - 255. - * @param {number} [b=0] - The blue color component, in the range 0 - 255. - * @param {number} [a=1] - The alpha color component, in the range 0 - 1. - * @param {number} [h=0] - The hue, in the range 0 - 1. - * @param {number} [s=0] - The saturation, in the range 0 - 1. - * @param {number} [l=0] - The lightness, in the range 0 - 1. - * @param {number} [v=0] - The value, in the range 0 - 1. - * @return {object} The resulting object with r, g, b, a properties and h, s, l and v. - */ + * A utility function to create a lightweight 'color' object with the default components. + * Any components that are not specified will default to zero. + * + * This is useful when you want to use a shared color object for the getPixel and getPixelAt methods. + * + * @author Matt DesLauriers (@mattdesl) + * @method Phaser.Color.createColor + * @static + * @param {number} [r=0] - The red color component, in the range 0 - 255. + * @param {number} [g=0] - The green color component, in the range 0 - 255. + * @param {number} [b=0] - The blue color component, in the range 0 - 255. + * @param {number} [a=1] - The alpha color component, in the range 0 - 1. + * @param {number} [h=0] - The hue, in the range 0 - 1. + * @param {number} [s=0] - The saturation, in the range 0 - 1. + * @param {number} [l=0] - The lightness, in the range 0 - 1. + * @param {number} [v=0] - The value, in the range 0 - 1. + * @return {object} The resulting object with r, g, b, a properties and h, s, l and v. + */ createColor: function (r, g, b, a, h, s, l, v) { - var out = { r: r || 0, g: g || 0, b: b || 0, a: a || 1, h: h || 0, s: s || 0, l: l || 0, v: v || 0, color: 0, color32: 0, rgba: '' }; return Phaser.Color.updateColor(out); - }, /** - * Takes a color object and updates the rgba, color and color32 properties. - * - * @method Phaser.Color.updateColor - * @static - * @param {object} out - The color object to update. - * @returns {number} A native color value integer (format: 0xAARRGGBB). - */ + * Takes a color object and updates the rgba, color and color32 properties. + * + * @method Phaser.Color.updateColor + * @static + * @param {object} out - The color object to update. + * @returns {number} A native color value integer (format: 0xAARRGGBB). + */ updateColor: function (out) { - out.rgba = 'rgba(' + out.r.toFixed() + ',' + out.g.toFixed() + ',' + out.b.toFixed() + ',' + out.a.toString() + ')'; out.color = Phaser.Color.getColor(out.r, out.g, out.b); out.color32 = Phaser.Color.getColor32(out.a * 255, out.r, out.g, out.b); return out; - }, /** - * Given an alpha and 3 color values this will return an integer representation of it. - * - * @method Phaser.Color.getColor32 - * @static - * @param {number} a - The alpha color component, in the range 0 - 255. - * @param {number} r - The red color component, in the range 0 - 255. - * @param {number} g - The green color component, in the range 0 - 255. - * @param {number} b - The blue color component, in the range 0 - 255. - * @returns {number} A native color value integer (format: 0xAARRGGBB). - */ + * Given an alpha and 3 color values this will return an integer representation of it. + * + * @method Phaser.Color.getColor32 + * @static + * @param {number} a - The alpha color component, in the range 0 - 255. + * @param {number} r - The red color component, in the range 0 - 255. + * @param {number} g - The green color component, in the range 0 - 255. + * @param {number} b - The blue color component, in the range 0 - 255. + * @returns {number} A native color value integer (format: 0xAARRGGBB). + */ getColor32: function (a, r, g, b) { - return a << 24 | r << 16 | g << 8 | b; - }, /** - * Given 3 color values this will return an integer representation of it. - * - * @method Phaser.Color.getColor - * @static - * @param {number} r - The red color component, in the range 0 - 255. - * @param {number} g - The green color component, in the range 0 - 255. - * @param {number} b - The blue color component, in the range 0 - 255. - * @returns {number} A native color value integer (format: 0xRRGGBB). - */ + * Given 3 color values this will return an integer representation of it. + * + * @method Phaser.Color.getColor + * @static + * @param {number} r - The red color component, in the range 0 - 255. + * @param {number} g - The green color component, in the range 0 - 255. + * @param {number} b - The blue color component, in the range 0 - 255. + * @returns {number} A native color value integer (format: 0xRRGGBB). + */ getColor: function (r, g, b) { - return r << 16 | g << 8 | b; - }, /** - * Converts the given color values into a string. - * If prefix was '#' it will be in the format `#RRGGBB` otherwise `0xAARRGGBB`. - * - * @method Phaser.Color.RGBtoString - * @static - * @param {number} r - The red color component, in the range 0 - 255. - * @param {number} g - The green color component, in the range 0 - 255. - * @param {number} b - The blue color component, in the range 0 - 255. - * @param {number} [a=255] - The alpha color component, in the range 0 - 255. - * @param {string} [prefix='#'] - The prefix used in the return string. If '#' it will return `#RRGGBB`, else `0xAARRGGBB`. - * @return {string} A string containing the color values. If prefix was '#' it will be in the format `#RRGGBB` otherwise `0xAARRGGBB`. - */ + * Converts the given color values into a string. + * If prefix was '#' it will be in the format `#RRGGBB` otherwise `0xAARRGGBB`. + * + * @method Phaser.Color.RGBtoString + * @static + * @param {number} r - The red color component, in the range 0 - 255. + * @param {number} g - The green color component, in the range 0 - 255. + * @param {number} b - The blue color component, in the range 0 - 255. + * @param {number} [a=255] - The alpha color component, in the range 0 - 255. + * @param {string} [prefix='#'] - The prefix used in the return string. If '#' it will return `#RRGGBB`, else `0xAARRGGBB`. + * @return {string} A string containing the color values. If prefix was '#' it will be in the format `#RRGGBB` otherwise `0xAARRGGBB`. + */ RGBtoString: function (r, g, b, a, prefix) { - if (a === undefined) { a = 255; } if (prefix === undefined) { prefix = '#'; } @@ -678,45 +647,41 @@ Phaser.Color = { { return '0x' + Phaser.Color.componentToHex(a) + Phaser.Color.componentToHex(r) + Phaser.Color.componentToHex(g) + Phaser.Color.componentToHex(b); } - }, /** - * Converts a hex string into an integer color value. - * - * @method Phaser.Color.hexToRGB - * @static - * @param {string} hex - The hex string to convert. Can be in the short-hand format `#03f` or `#0033ff`. - * @return {number} The rgb color value in the format 0xAARRGGBB. - */ + * Converts a hex string into an integer color value. + * + * @method Phaser.Color.hexToRGB + * @static + * @param {string} hex - The hex string to convert. Can be in the short-hand format `#03f` or `#0033ff`. + * @return {number} The rgb color value in the format 0xAARRGGBB. + */ hexToRGB: function (hex) { - var rgb = Phaser.Color.hexToColor(hex); if (rgb) { return Phaser.Color.getColor32(rgb.a, rgb.r, rgb.g, rgb.b); } - }, /** - * Converts a hex string into a Phaser Color object. - * - * The hex string can supplied as `'#0033ff'` or the short-hand format of `'#03f'`; it can begin with an optional "#" or "0x", or be unprefixed. - * - * An alpha channel is _not_ supported. - * - * @method Phaser.Color.hexToColor - * @static - * @param {string} hex - The color string in a hex format. - * @param {object} [out] - An object into which 3 properties will be created or set: r, g and b. If not provided a new object will be created. - * @return {object} An object with the red, green and blue values set in the r, g and b properties. - */ + * Converts a hex string into a Phaser Color object. + * + * The hex string can supplied as `'#0033ff'` or the short-hand format of `'#03f'`; it can begin with an optional "#" or "0x", or be unprefixed. + * + * An alpha channel is _not_ supported. + * + * @method Phaser.Color.hexToColor + * @static + * @param {string} hex - The color string in a hex format. + * @param {object} [out] - An object into which 3 properties will be created or set: r, g and b. If not provided a new object will be created. + * @return {object} An object with the red, green and blue values set in the r, g and b properties. + */ hexToColor: function (hex, out) { - // Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF") hex = hex.replace(/^(?:#|0x)?([a-f\d])([a-f\d])([a-f\d])$/i, function (m, r, g, b) { @@ -744,23 +709,21 @@ Phaser.Color = { } return out; - }, /** - * Converts a CSS 'web' string into a Phaser Color object. - * - * The web string can be in the format `'rgb(r,g,b)'` or `'rgba(r,g,b,a)'` where r/g/b are in the range [0..255] and a is in the range [0..1]. - * - * @method Phaser.Color.webToColor - * @static - * @param {string} web - The color string in CSS 'web' format. - * @param {object} [out] - An object into which 4 properties will be created: r, g, b and a. If not provided a new object will be created. - * @return {object} An object with the red, green, blue and alpha values set in the r, g, b and a properties. - */ + * Converts a CSS 'web' string into a Phaser Color object. + * + * The web string can be in the format `'rgb(r,g,b)'` or `'rgba(r,g,b,a)'` where r/g/b are in the range [0..255] and a is in the range [0..1]. + * + * @method Phaser.Color.webToColor + * @static + * @param {string} web - The color string in CSS 'web' format. + * @param {object} [out] - An object into which 4 properties will be created: r, g, b and a. If not provided a new object will be created. + * @return {object} An object with the red, green, blue and alpha values set in the r, g, b and a properties. + */ webToColor: function (web, out) { - if (!out) { out = Phaser.Color.createColor(); @@ -778,27 +741,27 @@ Phaser.Color = { } return out; - }, /** - * Converts a value - a "hex" string, a "CSS 'web' string", or a number - into red, green, blue, and alpha components. - * - * The value can be a string (see `hexToColor` and `webToColor` for the supported formats) or a packed integer (see `getRGB`). - * - * An alpha channel is _not_ supported when specifying a hex string. - * - * @method Phaser.Color.valueToColor - * @static - * @param {string|number} value - The color expressed as a recognized string format or a packed integer. - * @param {object} [out] - The object to use for the output. If not provided a new object will be created. - * @return {object} The (`out`) object with the red, green, blue, and alpha values set as the r/g/b/a properties. - */ + * Converts a value - a "hex" string, a "CSS 'web' string", or a number - into red, green, blue, and alpha components. + * + * The value can be a string (see `hexToColor` and `webToColor` for the supported formats) or a packed integer (see `getRGB`). + * + * An alpha channel is _not_ supported when specifying a hex string. + * + * @method Phaser.Color.valueToColor + * @static + * @param {string|number} value - The color expressed as a recognized string format or a packed integer. + * @param {object} [out] - The object to use for the output. If not provided a new object will be created. + * @return {object} The (`out`) object with the red, green, blue, and alpha values set as the r/g/b/a properties. + */ valueToColor: function (value, out) { - - // The behavior is not consistent between hexToColor/webToColor on invalid input. - // This unifies both by returning a new object, but returning null may be better. + /* + * The behavior is not consistent between hexToColor/webToColor on invalid input. + * This unifies both by returning a new object, but returning null may be better. + */ if (!out) { out = Phaser.Color.createColor(); @@ -819,8 +782,10 @@ Phaser.Color = { } else if (typeof value === 'number') { - // `getRGB` does not take optional object to modify; - // alpha is also adjusted to match `createColor`. + /* + * `getRGB` does not take optional object to modify; + * alpha is also adjusted to match `createColor`. + */ var tempColor = Phaser.Color.getRGB(value); out.r = tempColor.r; out.g = tempColor.g; @@ -832,38 +797,34 @@ Phaser.Color = { { return out; } - }, /** - * Return a string containing a hex representation of the given color component. - * - * @method Phaser.Color.componentToHex - * @static - * @param {number} color - The color channel to get the hex value for, must be a value between 0 and 255. - * @returns {string} A string of length 2 characters, i.e. 255 = ff, 100 = 64. - */ + * Return a string containing a hex representation of the given color component. + * + * @method Phaser.Color.componentToHex + * @static + * @param {number} color - The color channel to get the hex value for, must be a value between 0 and 255. + * @returns {string} A string of length 2 characters, i.e. 255 = ff, 100 = 64. + */ componentToHex: function (color) { - var hex = color.toString(16); return (hex.length === 1) ? '0' + hex : hex; - }, /** - * Get HSV color wheel values in an array which will be 360 elements in size. - * - * @method Phaser.Color.HSVColorWheel - * @static - * @param {number} [s=1] - The saturation, in the range 0 - 1. - * @param {number} [v=1] - The value, in the range 0 - 1. - * @return {array} An array containing 360 elements corresponding to the HSV color wheel. - */ + * Get HSV color wheel values in an array which will be 360 elements in size. + * + * @method Phaser.Color.HSVColorWheel + * @static + * @param {number} [s=1] - The saturation, in the range 0 - 1. + * @param {number} [v=1] - The value, in the range 0 - 1. + * @return {array} An array containing 360 elements corresponding to the HSV color wheel. + */ HSVColorWheel: function (s, v) { - if (s === undefined) { s = 1.0; } if (v === undefined) { v = 1.0; } @@ -875,21 +836,19 @@ Phaser.Color = { } return colors; - }, /** - * Get HSL color wheel values in an array which will be 360 elements in size. - * - * @method Phaser.Color.HSLColorWheel - * @static - * @param {number} [s=0.5] - The saturation, in the range 0 - 1. - * @param {number} [l=0.5] - The lightness, in the range 0 - 1. - * @return {array} An array containing 360 elements corresponding to the HSL color wheel. - */ + * Get HSL color wheel values in an array which will be 360 elements in size. + * + * @method Phaser.Color.HSLColorWheel + * @static + * @param {number} [s=0.5] - The saturation, in the range 0 - 1. + * @param {number} [l=0.5] - The lightness, in the range 0 - 1. + * @return {array} An array containing 360 elements corresponding to the HSL color wheel. + */ HSLColorWheel: function (s, l) { - if (s === undefined) { s = 0.5; } if (l === undefined) { l = 0.5; } @@ -901,25 +860,23 @@ Phaser.Color = { } return colors; - }, /** - * Interpolates the two given colours based on the supplied step and currentStep properties. - * - * @method Phaser.Color.interpolateColor - * @static - * @param {number} color1 - The first color value. - * @param {number} color2 - The second color value. - * @param {number} steps - The number of steps to run the interpolation over. - * @param {number} currentStep - The currentStep value. If the interpolation will take 100 steps, a currentStep value of 50 would be half-way between the two. - * @param {number} [alpha] - The alpha of the returned color. - * @param {number} [colorSpace=0] - The color space to interpolate in. 0 = RGB, 1 = HSV. - * @returns {number} The interpolated color value. - */ + * Interpolates the two given colours based on the supplied step and currentStep properties. + * + * @method Phaser.Color.interpolateColor + * @static + * @param {number} color1 - The first color value. + * @param {number} color2 - The second color value. + * @param {number} steps - The number of steps to run the interpolation over. + * @param {number} currentStep - The currentStep value. If the interpolation will take 100 steps, a currentStep value of 50 would be half-way between the two. + * @param {number} [alpha] - The alpha of the returned color. + * @param {number} [colorSpace=0] - The color space to interpolate in. 0 = RGB, 1 = HSV. + * @returns {number} The interpolated color value. + */ interpolateColor: function (color1, color2, steps, currentStep, alpha, colorSpace) { - if (alpha === undefined) { alpha = 255; } if (colorSpace === undefined) { colorSpace = 0; } @@ -970,118 +927,108 @@ Phaser.Color = { } return Phaser.Color.getColor32(alpha, r, g, b); - }, /** - * Interpolates the two given colours based on the supplied step and currentStep properties. - * - * @method Phaser.Color.interpolateColorWithRGB - * @static - * @param {number} color - The first color value. - * @param {number} r - The red color value, between 0 and 0xFF (255). - * @param {number} g - The green color value, between 0 and 0xFF (255). - * @param {number} b - The blue color value, between 0 and 0xFF (255). - * @param {number} steps - The number of steps to run the interpolation over. - * @param {number} currentStep - The currentStep value. If the interpolation will take 100 steps, a currentStep value of 50 would be half-way between the two. - * @returns {number} The interpolated color value. - */ + * Interpolates the two given colours based on the supplied step and currentStep properties. + * + * @method Phaser.Color.interpolateColorWithRGB + * @static + * @param {number} color - The first color value. + * @param {number} r - The red color value, between 0 and 0xFF (255). + * @param {number} g - The green color value, between 0 and 0xFF (255). + * @param {number} b - The blue color value, between 0 and 0xFF (255). + * @param {number} steps - The number of steps to run the interpolation over. + * @param {number} currentStep - The currentStep value. If the interpolation will take 100 steps, a currentStep value of 50 would be half-way between the two. + * @returns {number} The interpolated color value. + */ interpolateColorWithRGB: function (color, r, g, b, steps, currentStep) { - var src = Phaser.Color.getRGB(color); var or = (((r - src.red) * currentStep) / steps) + src.red; var og = (((g - src.green) * currentStep) / steps) + src.green; var ob = (((b - src.blue) * currentStep) / steps) + src.blue; return Phaser.Color.getColor(or, og, ob); - }, /** - * Interpolates the two given colours based on the supplied step and currentStep properties. - * @method Phaser.Color.interpolateRGB - * @static - * @param {number} r1 - The red color value, between 0 and 0xFF (255). - * @param {number} g1 - The green color value, between 0 and 0xFF (255). - * @param {number} b1 - The blue color value, between 0 and 0xFF (255). - * @param {number} r2 - The red color value, between 0 and 0xFF (255). - * @param {number} g2 - The green color value, between 0 and 0xFF (255). - * @param {number} b2 - The blue color value, between 0 and 0xFF (255). - * @param {number} steps - The number of steps to run the interpolation over. - * @param {number} currentStep - The currentStep value. If the interpolation will take 100 steps, a currentStep value of 50 would be half-way between the two. - * @returns {number} The interpolated color value. - */ + * Interpolates the two given colours based on the supplied step and currentStep properties. + * @method Phaser.Color.interpolateRGB + * @static + * @param {number} r1 - The red color value, between 0 and 0xFF (255). + * @param {number} g1 - The green color value, between 0 and 0xFF (255). + * @param {number} b1 - The blue color value, between 0 and 0xFF (255). + * @param {number} r2 - The red color value, between 0 and 0xFF (255). + * @param {number} g2 - The green color value, between 0 and 0xFF (255). + * @param {number} b2 - The blue color value, between 0 and 0xFF (255). + * @param {number} steps - The number of steps to run the interpolation over. + * @param {number} currentStep - The currentStep value. If the interpolation will take 100 steps, a currentStep value of 50 would be half-way between the two. + * @returns {number} The interpolated color value. + */ interpolateRGB: function (r1, g1, b1, r2, g2, b2, steps, currentStep) { - var r = (((r2 - r1) * currentStep) / steps) + r1; var g = (((g2 - g1) * currentStep) / steps) + g1; var b = (((b2 - b1) * currentStep) / steps) + b1; return Phaser.Color.getColor(r, g, b); - }, /** - * Calculates a linear (interpolation) value of two colors over t. - * - * This is a slightly simpler interface to {@link Phaser.Color.interpolateColor}. - * - * The arguments are similar to {@link Phaser.Math.linear}. - * - * @method Phaser.Color.linear - * @param {number} color1 - The first color value. - * @param {number} color2 - The second color value. - * @param {number} t - A value between 0 and 1. - * @return {number} The interpolated color value. - */ + * Calculates a linear (interpolation) value of two colors over t. + * + * This is a slightly simpler interface to {@link Phaser.Color.interpolateColor}. + * + * The arguments are similar to {@link Phaser.Math.linear}. + * + * @method Phaser.Color.linear + * @param {number} color1 - The first color value. + * @param {number} color2 - The second color value. + * @param {number} t - A value between 0 and 1. + * @return {number} The interpolated color value. + */ linear: function (color1, color2, t) { - return this.interpolateColor(color1, color2, 1, t); - }, /** - * Calculates a linear (interpolation) value of an array of colors over t. - * - * The arguments are similar to {@link Phaser.Math.linearInterpolation}. - * - * This can be used as a {@link Phaser.TweenData#interpolationFunction}. - * - * @method Phaser.Color.linearInterpolation - * @param {number[]} colors - The input array of color values to interpolate between. - * @param {number} t - The amount of interpolation, between 0 (start) and 1 (end). - * @return {number} The interpolated color value. - */ + * Calculates a linear (interpolation) value of an array of colors over t. + * + * The arguments are similar to {@link Phaser.Math.linearInterpolation}. + * + * This can be used as a {@link Phaser.TweenData#interpolationFunction}. + * + * @method Phaser.Color.linearInterpolation + * @param {number[]} colors - The input array of color values to interpolate between. + * @param {number} t - The amount of interpolation, between 0 (start) and 1 (end). + * @return {number} The interpolated color value. + */ linearInterpolation: function (colors, t) { - var k = Phaser.Math.linear(0, colors.length - 1, t); var color1 = colors[Math.floor(k)]; var color2 = colors[Math.ceil(k)]; return this.linear(color1, color2, k % 1); - }, /** - * Returns a random color value between black and white - * Set the min value to start each channel from the given offset. - * Set the max value to restrict the maximum color used per channel. - * - * @method Phaser.Color.getRandomColor - * @static - * @param {number} [min=0] - The lowest value to use for the color. - * @param {number} [max=255] - The highest value to use for the color. - * @param {number} [alpha=255] - The alpha value of the returning color (default 255 = fully opaque). - * @returns {number} 32-bit color value with alpha. - */ + * Returns a random color value between black and white + * Set the min value to start each channel from the given offset. + * Set the max value to restrict the maximum color used per channel. + * + * @method Phaser.Color.getRandomColor + * @static + * @param {number} [min=0] - The lowest value to use for the color. + * @param {number} [max=255] - The highest value to use for the color. + * @param {number} [alpha=255] - The alpha value of the returning color (default 255 = fully opaque). + * @returns {number} 32-bit color value with alpha. + */ getRandomColor: function (min, max, alpha) { - if (min === undefined) { min = 0; } if (max === undefined) { max = 255; } if (alpha === undefined) { alpha = 255; } @@ -1097,22 +1044,20 @@ Phaser.Color = { var blue = min + Math.round(Math.random() * (max - min)); return Phaser.Color.getColor32(alpha, red, green, blue); - }, /** - * Return the component parts of a color as an Object with the properties alpha, red, green, blue. - * - * Alpha will only be set if it exist in the given color (0xAARRGGBB) - * - * @method Phaser.Color.getRGB - * @static - * @param {number} color - Color in RGB (0xRRGGBB) or ARGB format (0xAARRGGBB). - * @returns {object} An Object with properties: alpha, red, green, blue (also r, g, b and a). Alpha will only be present if a color value > 16777215 was given. - */ + * Return the component parts of a color as an Object with the properties alpha, red, green, blue. + * + * Alpha will only be set if it exist in the given color (0xAARRGGBB) + * + * @method Phaser.Color.getRGB + * @static + * @param {number} color - Color in RGB (0xRRGGBB) or ARGB format (0xAARRGGBB). + * @returns {object} An Object with properties: alpha, red, green, blue (also r, g, b and a). Alpha will only be present if a color value > 16777215 was given. + */ getRGB: function (color) { - if (color > 16777215) { // The color value has an alpha component @@ -1140,20 +1085,18 @@ Phaser.Color = { b: color & 0xFF }; } - }, /** - * Returns a CSS friendly string value from the given color. - * - * @method Phaser.Color.getWebRGB - * @static - * @param {number|Object} color - Color in RGB (0xRRGGBB), ARGB format (0xAARRGGBB) or an Object with r, g, b, a properties. - * @returns {string} A string in the format: 'rgba(r,g,b,a)' - */ + * Returns a CSS friendly string value from the given color. + * + * @method Phaser.Color.getWebRGB + * @static + * @param {number|Object} color - Color in RGB (0xRRGGBB), ARGB format (0xAARRGGBB) or an Object with r, g, b, a properties. + * @returns {string} A string in the format: 'rgba(r,g,b,a)' + */ getWebRGB: function (color) { - if (typeof color === 'object') { return 'rgba(' + color.r.toString() + ',' + color.g.toString() + ',' + color.b.toString() + ',' + (color.a / 255).toString() + ')'; @@ -1163,461 +1106,460 @@ Phaser.Color = { var rgb = Phaser.Color.getRGB(color); return 'rgba(' + rgb.r.toString() + ',' + rgb.g.toString() + ',' + rgb.b.toString() + ',' + (rgb.a / 255).toString() + ')'; } - }, /** - * Given a native color value (in the format 0xAARRGGBB) this will return the Alpha component, as a value between 0 and 255. - * - * @method Phaser.Color.getAlpha - * @static - * @param {number} color - In the format 0xAARRGGBB. - * @returns {number} The Alpha component of the color, will be between 0 and 1 (0 being no Alpha (opaque), 1 full Alpha (transparent)). - */ + * Given a native color value (in the format 0xAARRGGBB) this will return the Alpha component, as a value between 0 and 255. + * + * @method Phaser.Color.getAlpha + * @static + * @param {number} color - In the format 0xAARRGGBB. + * @returns {number} The Alpha component of the color, will be between 0 and 1 (0 being no Alpha (opaque), 1 full Alpha (transparent)). + */ getAlpha: function (color) { return color >>> 24; }, /** - * Given a native color value (in the format 0xAARRGGBB) this will return the Alpha component as a value between 0 and 1. - * - * @method Phaser.Color.getAlphaFloat - * @static - * @param {number} color - In the format 0xAARRGGBB. - * @returns {number} The Alpha component of the color, will be between 0 and 1 (0 being no Alpha (opaque), 1 full Alpha (transparent)). - */ + * Given a native color value (in the format 0xAARRGGBB) this will return the Alpha component as a value between 0 and 1. + * + * @method Phaser.Color.getAlphaFloat + * @static + * @param {number} color - In the format 0xAARRGGBB. + * @returns {number} The Alpha component of the color, will be between 0 and 1 (0 being no Alpha (opaque), 1 full Alpha (transparent)). + */ getAlphaFloat: function (color) { return (color >>> 24) / 255; }, /** - * Given a native color value (in the format 0xAARRGGBB) this will return the Red component, as a value between 0 and 255. - * - * @method Phaser.Color.getRed - * @static - * @param {number} color In the format 0xAARRGGBB. - * @returns {number} The Red component of the color, will be between 0 and 255 (0 being no color, 255 full Red). - */ + * Given a native color value (in the format 0xAARRGGBB) this will return the Red component, as a value between 0 and 255. + * + * @method Phaser.Color.getRed + * @static + * @param {number} color In the format 0xAARRGGBB. + * @returns {number} The Red component of the color, will be between 0 and 255 (0 being no color, 255 full Red). + */ getRed: function (color) { return color >> 16 & 0xFF; }, /** - * Given a native color value (in the format 0xAARRGGBB) this will return the Green component, as a value between 0 and 255. - * - * @method Phaser.Color.getGreen - * @static - * @param {number} color - In the format 0xAARRGGBB. - * @returns {number} The Green component of the color, will be between 0 and 255 (0 being no color, 255 full Green). - */ + * Given a native color value (in the format 0xAARRGGBB) this will return the Green component, as a value between 0 and 255. + * + * @method Phaser.Color.getGreen + * @static + * @param {number} color - In the format 0xAARRGGBB. + * @returns {number} The Green component of the color, will be between 0 and 255 (0 being no color, 255 full Green). + */ getGreen: function (color) { return color >> 8 & 0xFF; }, /** - * Given a native color value (in the format 0xAARRGGBB) this will return the Blue component, as a value between 0 and 255. - * - * @method Phaser.Color.getBlue - * @static - * @param {number} color - In the format 0xAARRGGBB. - * @returns {number} The Blue component of the color, will be between 0 and 255 (0 being no color, 255 full Blue). - */ + * Given a native color value (in the format 0xAARRGGBB) this will return the Blue component, as a value between 0 and 255. + * + * @method Phaser.Color.getBlue + * @static + * @param {number} color - In the format 0xAARRGGBB. + * @returns {number} The Blue component of the color, will be between 0 and 255 (0 being no color, 255 full Blue). + */ getBlue: function (color) { return color & 0xFF; }, /** - * Blends the source color, ignoring the backdrop. - * - * @method Phaser.Color.blendNormal - * @static - * @param {integer} a - The source color to blend, in the range 1 to 255. - * @param {integer} b - The backdrop color to blend, in the range 1 to 255. - * @returns {integer} The blended color value, in the range 1 to 255. - */ + * Blends the source color, ignoring the backdrop. + * + * @method Phaser.Color.blendNormal + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ blendNormal: function (a) { return a; }, /** - * Selects the lighter of the backdrop and source colors. - * - * @method Phaser.Color.blendLighten - * @static - * @param {integer} a - The source color to blend, in the range 1 to 255. - * @param {integer} b - The backdrop color to blend, in the range 1 to 255. - * @returns {integer} The blended color value, in the range 1 to 255. - */ + * Selects the lighter of the backdrop and source colors. + * + * @method Phaser.Color.blendLighten + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ blendLighten: function (a, b) { return (b > a) ? b : a; }, /** - * Selects the darker of the backdrop and source colors. - * - * @method Phaser.Color.blendDarken - * @static - * @param {integer} a - The source color to blend, in the range 1 to 255. - * @param {integer} b - The backdrop color to blend, in the range 1 to 255. - * @returns {integer} The blended color value, in the range 1 to 255. - */ + * Selects the darker of the backdrop and source colors. + * + * @method Phaser.Color.blendDarken + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ blendDarken: function (a, b) { return (b > a) ? a : b; }, /** - * Multiplies the backdrop and source color values. - * The result color is always at least as dark as either of the two constituent - * colors. Multiplying any color with black produces black; - * multiplying with white leaves the original color unchanged. - * - * @method Phaser.Color.blendMultiply - * @static - * @param {integer} a - The source color to blend, in the range 1 to 255. - * @param {integer} b - The backdrop color to blend, in the range 1 to 255. - * @returns {integer} The blended color value, in the range 1 to 255. - */ + * Multiplies the backdrop and source color values. + * The result color is always at least as dark as either of the two constituent + * colors. Multiplying any color with black produces black; + * multiplying with white leaves the original color unchanged. + * + * @method Phaser.Color.blendMultiply + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ blendMultiply: function (a, b) { return (a * b) / 255; }, /** - * Takes the average of the source and backdrop colors. - * - * @method Phaser.Color.blendAverage - * @static - * @param {integer} a - The source color to blend, in the range 1 to 255. - * @param {integer} b - The backdrop color to blend, in the range 1 to 255. - * @returns {integer} The blended color value, in the range 1 to 255. - */ + * Takes the average of the source and backdrop colors. + * + * @method Phaser.Color.blendAverage + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ blendAverage: function (a, b) { return (a + b) / 2; }, /** - * Adds the source and backdrop colors together and returns the value, up to a maximum of 255. - * - * @method Phaser.Color.blendAdd - * @static - * @param {integer} a - The source color to blend, in the range 1 to 255. - * @param {integer} b - The backdrop color to blend, in the range 1 to 255. - * @returns {integer} The blended color value, in the range 1 to 255. - */ + * Adds the source and backdrop colors together and returns the value, up to a maximum of 255. + * + * @method Phaser.Color.blendAdd + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ blendAdd: function (a, b) { return Math.min(255, a + b); }, /** - * Combines the source and backdrop colors and returns their value minus 255. - * - * @method Phaser.Color.blendSubtract - * @static - * @param {integer} a - The source color to blend, in the range 1 to 255. - * @param {integer} b - The backdrop color to blend, in the range 1 to 255. - * @returns {integer} The blended color value, in the range 1 to 255. - */ + * Combines the source and backdrop colors and returns their value minus 255. + * + * @method Phaser.Color.blendSubtract + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ blendSubtract: function (a, b) { return Math.max(0, a + b - 255); }, /** - * Subtracts the darker of the two constituent colors from the lighter. - * - * Painting with white inverts the backdrop color; painting with black produces no change. - * - * @method Phaser.Color.blendDifference - * @static - * @param {integer} a - The source color to blend, in the range 1 to 255. - * @param {integer} b - The backdrop color to blend, in the range 1 to 255. - * @returns {integer} The blended color value, in the range 1 to 255. - */ + * Subtracts the darker of the two constituent colors from the lighter. + * + * Painting with white inverts the backdrop color; painting with black produces no change. + * + * @method Phaser.Color.blendDifference + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ blendDifference: function (a, b) { return Math.abs(a - b); }, /** - * Negation blend mode. - * - * @method Phaser.Color.blendNegation - * @static - * @param {integer} a - The source color to blend, in the range 1 to 255. - * @param {integer} b - The backdrop color to blend, in the range 1 to 255. - * @returns {integer} The blended color value, in the range 1 to 255. - */ + * Negation blend mode. + * + * @method Phaser.Color.blendNegation + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ blendNegation: function (a, b) { return 255 - Math.abs(255 - a - b); }, /** - * Multiplies the complements of the backdrop and source color values, then complements the result. - * The result color is always at least as light as either of the two constituent colors. - * Screening any color with white produces white; screening with black leaves the original color unchanged. - * - * @method Phaser.Color.blendScreen - * @static - * @param {integer} a - The source color to blend, in the range 1 to 255. - * @param {integer} b - The backdrop color to blend, in the range 1 to 255. - * @returns {integer} The blended color value, in the range 1 to 255. - */ + * Multiplies the complements of the backdrop and source color values, then complements the result. + * The result color is always at least as light as either of the two constituent colors. + * Screening any color with white produces white; screening with black leaves the original color unchanged. + * + * @method Phaser.Color.blendScreen + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ blendScreen: function (a, b) { return 255 - (((255 - a) * (255 - b)) >> 8); }, /** - * Produces an effect similar to that of the Difference mode, but lower in contrast. - * Painting with white inverts the backdrop color; painting with black produces no change. - * - * @method Phaser.Color.blendExclusion - * @static - * @param {integer} a - The source color to blend, in the range 1 to 255. - * @param {integer} b - The backdrop color to blend, in the range 1 to 255. - * @returns {integer} The blended color value, in the range 1 to 255. - */ + * Produces an effect similar to that of the Difference mode, but lower in contrast. + * Painting with white inverts the backdrop color; painting with black produces no change. + * + * @method Phaser.Color.blendExclusion + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ blendExclusion: function (a, b) { return a + b - 2 * a * b / 255; }, /** - * Multiplies or screens the colors, depending on the backdrop color. - * Source colors overlay the backdrop while preserving its highlights and shadows. - * The backdrop color is not replaced, but is mixed with the source color to reflect the lightness or darkness of the backdrop. - * - * @method Phaser.Color.blendOverlay - * @static - * @param {integer} a - The source color to blend, in the range 1 to 255. - * @param {integer} b - The backdrop color to blend, in the range 1 to 255. - * @returns {integer} The blended color value, in the range 1 to 255. - */ + * Multiplies or screens the colors, depending on the backdrop color. + * Source colors overlay the backdrop while preserving its highlights and shadows. + * The backdrop color is not replaced, but is mixed with the source color to reflect the lightness or darkness of the backdrop. + * + * @method Phaser.Color.blendOverlay + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ blendOverlay: function (a, b) { return b < 128 ? (2 * a * b / 255) : (255 - 2 * (255 - a) * (255 - b) / 255); }, /** - * Darkens or lightens the colors, depending on the source color value. - * - * If the source color is lighter than 0.5, the backdrop is lightened, as if it were dodged; - * this is useful for adding highlights to a scene. - * - * If the source color is darker than 0.5, the backdrop is darkened, as if it were burned in. - * The degree of lightening or darkening is proportional to the difference between the source color and 0.5; - * if it is equal to 0.5, the backdrop is unchanged. - * - * Painting with pure black or white produces a distinctly darker or lighter area, but does not result in pure black or white. - * The effect is similar to shining a diffused spotlight on the backdrop. - * - * @method Phaser.Color.blendSoftLight - * @static - * @param {integer} a - The source color to blend, in the range 1 to 255. - * @param {integer} b - The backdrop color to blend, in the range 1 to 255. - * @returns {integer} The blended color value, in the range 1 to 255. - */ + * Darkens or lightens the colors, depending on the source color value. + * + * If the source color is lighter than 0.5, the backdrop is lightened, as if it were dodged; + * this is useful for adding highlights to a scene. + * + * If the source color is darker than 0.5, the backdrop is darkened, as if it were burned in. + * The degree of lightening or darkening is proportional to the difference between the source color and 0.5; + * if it is equal to 0.5, the backdrop is unchanged. + * + * Painting with pure black or white produces a distinctly darker or lighter area, but does not result in pure black or white. + * The effect is similar to shining a diffused spotlight on the backdrop. + * + * @method Phaser.Color.blendSoftLight + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ blendSoftLight: function (a, b) { return b < 128 ? (2 * ((a >> 1) + 64)) * (b / 255) : 255 - (2 * (255 - ((a >> 1) + 64)) * (255 - b) / 255); }, /** - * Multiplies or screens the colors, depending on the source color value. - * - * If the source color is lighter than 0.5, the backdrop is lightened, as if it were screened; - * this is useful for adding highlights to a scene. - * - * If the source color is darker than 0.5, the backdrop is darkened, as if it were multiplied; - * this is useful for adding shadows to a scene. - * - * The degree of lightening or darkening is proportional to the difference between the source color and 0.5; - * if it is equal to 0.5, the backdrop is unchanged. - * - * Painting with pure black or white produces pure black or white. The effect is similar to shining a harsh spotlight on the backdrop. - * - * @method Phaser.Color.blendHardLight - * @static - * @param {integer} a - The source color to blend, in the range 1 to 255. - * @param {integer} b - The backdrop color to blend, in the range 1 to 255. - * @returns {integer} The blended color value, in the range 1 to 255. - */ + * Multiplies or screens the colors, depending on the source color value. + * + * If the source color is lighter than 0.5, the backdrop is lightened, as if it were screened; + * this is useful for adding highlights to a scene. + * + * If the source color is darker than 0.5, the backdrop is darkened, as if it were multiplied; + * this is useful for adding shadows to a scene. + * + * The degree of lightening or darkening is proportional to the difference between the source color and 0.5; + * if it is equal to 0.5, the backdrop is unchanged. + * + * Painting with pure black or white produces pure black or white. The effect is similar to shining a harsh spotlight on the backdrop. + * + * @method Phaser.Color.blendHardLight + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ blendHardLight: function (a, b) { return Phaser.Color.blendOverlay(b, a); }, /** - * Brightens the backdrop color to reflect the source color. - * Painting with black produces no change. - * - * @method Phaser.Color.blendColorDodge - * @static - * @param {integer} a - The source color to blend, in the range 1 to 255. - * @param {integer} b - The backdrop color to blend, in the range 1 to 255. - * @returns {integer} The blended color value, in the range 1 to 255. - */ + * Brightens the backdrop color to reflect the source color. + * Painting with black produces no change. + * + * @method Phaser.Color.blendColorDodge + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ blendColorDodge: function (a, b) { return b === 255 ? b : Math.min(255, ((a << 8) / (255 - b))); }, /** - * Darkens the backdrop color to reflect the source color. - * Painting with white produces no change. - * - * @method Phaser.Color.blendColorBurn - * @static - * @param {integer} a - The source color to blend, in the range 1 to 255. - * @param {integer} b - The backdrop color to blend, in the range 1 to 255. - * @returns {integer} The blended color value, in the range 1 to 255. - */ + * Darkens the backdrop color to reflect the source color. + * Painting with white produces no change. + * + * @method Phaser.Color.blendColorBurn + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ blendColorBurn: function (a, b) { return b === 0 ? b : Math.max(0, (255 - ((255 - a) << 8) / b)); }, /** - * An alias for blendAdd, it simply sums the values of the two colors. - * - * @method Phaser.Color.blendLinearDodge - * @static - * @param {integer} a - The source color to blend, in the range 1 to 255. - * @param {integer} b - The backdrop color to blend, in the range 1 to 255. - * @returns {integer} The blended color value, in the range 1 to 255. - */ + * An alias for blendAdd, it simply sums the values of the two colors. + * + * @method Phaser.Color.blendLinearDodge + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ blendLinearDodge: function (a, b) { return Phaser.Color.blendAdd(a, b); }, /** - * An alias for blendSubtract, it simply sums the values of the two colors and subtracts 255. - * - * @method Phaser.Color.blendLinearBurn - * @static - * @param {integer} a - The source color to blend, in the range 1 to 255. - * @param {integer} b - The backdrop color to blend, in the range 1 to 255. - * @returns {integer} The blended color value, in the range 1 to 255. - */ + * An alias for blendSubtract, it simply sums the values of the two colors and subtracts 255. + * + * @method Phaser.Color.blendLinearBurn + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ blendLinearBurn: function (a, b) { return Phaser.Color.blendSubtract(a, b); }, /** - * This blend mode combines Linear Dodge and Linear Burn (rescaled so that neutral colors become middle gray). - * Dodge applies to values of top layer lighter than middle gray, and burn to darker values. - * The calculation simplifies to the sum of bottom layer and twice the top layer, subtract 128. The contrast decreases. - * - * @method Phaser.Color.blendLinearLight - * @static - * @param {integer} a - The source color to blend, in the range 1 to 255. - * @param {integer} b - The backdrop color to blend, in the range 1 to 255. - * @returns {integer} The blended color value, in the range 1 to 255. - */ + * This blend mode combines Linear Dodge and Linear Burn (rescaled so that neutral colors become middle gray). + * Dodge applies to values of top layer lighter than middle gray, and burn to darker values. + * The calculation simplifies to the sum of bottom layer and twice the top layer, subtract 128. The contrast decreases. + * + * @method Phaser.Color.blendLinearLight + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ blendLinearLight: function (a, b) { return b < 128 ? Phaser.Color.blendLinearBurn(a, 2 * b) : Phaser.Color.blendLinearDodge(a, (2 * (b - 128))); }, /** - * This blend mode combines Color Dodge and Color Burn (rescaled so that neutral colors become middle gray). - * Dodge applies when values in the top layer are lighter than middle gray, and burn to darker values. - * The middle gray is the neutral color. When color is lighter than this, this effectively moves the white point of the bottom - * layer down by twice the difference; when it is darker, the black point is moved up by twice the difference. The perceived contrast increases. - * - * @method Phaser.Color.blendVividLight - * @static - * @param {integer} a - The source color to blend, in the range 1 to 255. - * @param {integer} b - The backdrop color to blend, in the range 1 to 255. - * @returns {integer} The blended color value, in the range 1 to 255. - */ + * This blend mode combines Color Dodge and Color Burn (rescaled so that neutral colors become middle gray). + * Dodge applies when values in the top layer are lighter than middle gray, and burn to darker values. + * The middle gray is the neutral color. When color is lighter than this, this effectively moves the white point of the bottom + * layer down by twice the difference; when it is darker, the black point is moved up by twice the difference. The perceived contrast increases. + * + * @method Phaser.Color.blendVividLight + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ blendVividLight: function (a, b) { return b < 128 ? Phaser.Color.blendColorBurn(a, 2 * b) : Phaser.Color.blendColorDodge(a, (2 * (b - 128))); }, /** - * If the backdrop color (light source) is lighter than 50%, the blendDarken mode is used, and colors lighter than the backdrop color do not change. - * If the backdrop color is darker than 50% gray, colors lighter than the blend color are replaced, and colors darker than the blend color do not change. - * - * @method Phaser.Color.blendPinLight - * @static - * @param {integer} a - The source color to blend, in the range 1 to 255. - * @param {integer} b - The backdrop color to blend, in the range 1 to 255. - * @returns {integer} The blended color value, in the range 1 to 255. - */ + * If the backdrop color (light source) is lighter than 50%, the blendDarken mode is used, and colors lighter than the backdrop color do not change. + * If the backdrop color is darker than 50% gray, colors lighter than the blend color are replaced, and colors darker than the blend color do not change. + * + * @method Phaser.Color.blendPinLight + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ blendPinLight: function (a, b) { return b < 128 ? Phaser.Color.blendDarken(a, 2 * b) : Phaser.Color.blendLighten(a, (2 * (b - 128))); }, /** - * Runs blendVividLight on the source and backdrop colors. - * If the resulting color is 128 or more, it receives a value of 255; if less than 128, a value of 0. - * Therefore, all blended pixels have red, green, and blue channel values of either 0 or 255. - * This changes all pixels to primary additive colors (red, green, or blue), white, or black. - * - * @method Phaser.Color.blendHardMix - * @static - * @param {integer} a - The source color to blend, in the range 1 to 255. - * @param {integer} b - The backdrop color to blend, in the range 1 to 255. - * @returns {integer} The blended color value, in the range 1 to 255. - */ + * Runs blendVividLight on the source and backdrop colors. + * If the resulting color is 128 or more, it receives a value of 255; if less than 128, a value of 0. + * Therefore, all blended pixels have red, green, and blue channel values of either 0 or 255. + * This changes all pixels to primary additive colors (red, green, or blue), white, or black. + * + * @method Phaser.Color.blendHardMix + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ blendHardMix: function (a, b) { return Phaser.Color.blendVividLight(a, b) < 128 ? 0 : 255; }, /** - * Reflect blend mode. This mode is useful when adding shining objects or light zones to images. - * - * @method Phaser.Color.blendReflect - * @static - * @param {integer} a - The source color to blend, in the range 1 to 255. - * @param {integer} b - The backdrop color to blend, in the range 1 to 255. - * @returns {integer} The blended color value, in the range 1 to 255. - */ + * Reflect blend mode. This mode is useful when adding shining objects or light zones to images. + * + * @method Phaser.Color.blendReflect + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ blendReflect: function (a, b) { return b === 255 ? b : Math.min(255, (a * a / (255 - b))); }, /** - * Glow blend mode. This mode is a variation of reflect mode with the source and backdrop colors swapped. - * - * @method Phaser.Color.blendGlow - * @static - * @param {integer} a - The source color to blend, in the range 1 to 255. - * @param {integer} b - The backdrop color to blend, in the range 1 to 255. - * @returns {integer} The blended color value, in the range 1 to 255. - */ + * Glow blend mode. This mode is a variation of reflect mode with the source and backdrop colors swapped. + * + * @method Phaser.Color.blendGlow + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ blendGlow: function (a, b) { return Phaser.Color.blendReflect(b, a); }, /** - * Phoenix blend mode. This subtracts the lighter color from the darker color, and adds 255, giving a bright result. - * - * @method Phaser.Color.blendPhoenix - * @static - * @param {integer} a - The source color to blend, in the range 1 to 255. - * @param {integer} b - The backdrop color to blend, in the range 1 to 255. - * @returns {integer} The blended color value, in the range 1 to 255. - */ + * Phoenix blend mode. This subtracts the lighter color from the darker color, and adds 255, giving a bright result. + * + * @method Phaser.Color.blendPhoenix + * @static + * @param {integer} a - The source color to blend, in the range 1 to 255. + * @param {integer} b - The backdrop color to blend, in the range 1 to 255. + * @returns {integer} The blended color value, in the range 1 to 255. + */ blendPhoenix: function (a, b) { return Math.min(a, b) - Math.max(a, b) + 255; diff --git a/src/utils/DOM.js b/src/utils/DOM.js index ddb09ef4a..97f2ed5c5 100644 --- a/src/utils/DOM.js +++ b/src/utils/DOM.js @@ -1,35 +1,34 @@ /** -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* DOM utility class. -* -* Provides a useful Window and Element functions as well as cross-browser compatibility buffer. -* -* Some code originally derived from {@link https://github.com/ryanve/verge verge}. -* Some parts were inspired by the research of Ryan Van Etten, released under MIT License 2013. -* -* @class Phaser.DOM -* @static -*/ + * DOM utility class. + * + * Provides a useful Window and Element functions as well as cross-browser compatibility buffer. + * + * Some code originally derived from {@link https://github.com/ryanve/verge verge}. + * Some parts were inspired by the research of Ryan Van Etten, released under MIT License 2013. + * + * @class Phaser.DOM + * @static + */ Phaser.DOM = { /** - * Get the [absolute] position of the element relative to the Document. - * - * The value may vary slightly as the page is scrolled due to rounding errors. - * - * @method Phaser.DOM.getOffset - * @param {DOMElement} element - The targeted element that we want to retrieve the offset. - * @param {Phaser.Point} [point] - The point we want to take the x/y values of the offset. - * @return {Phaser.Point} - A point objet with the offsetX and Y as its properties. - */ + * Get the [absolute] position of the element relative to the Document. + * + * The value may vary slightly as the page is scrolled due to rounding errors. + * + * @method Phaser.DOM.getOffset + * @param {DOMElement} element - The targeted element that we want to retrieve the offset. + * @param {Phaser.Point} [point] - The point we want to take the x/y values of the offset. + * @return {Phaser.Point} - A point objet with the offsetX and Y as its properties. + */ getOffset: function (element, point) { - point = point || new Phaser.Point(); var box = element.getBoundingClientRect(); @@ -43,25 +42,23 @@ Phaser.DOM = { point.y = box.top + scrollTop - clientTop; return point; - }, /** - * A cross-browser element.getBoundingClientRect method with optional cushion. - * - * Returns a plain object containing the properties `top/bottom/left/right/width/height` with respect to the top-left corner of the current viewport. - * Its properties match the native rectangle. - * The cushion parameter is an amount of pixels (+/-) to cushion the element. - * It adjusts the measurements such that it is possible to detect when an element is near the viewport. - * - * @method Phaser.DOM.getBounds - * @param {DOMElement|Object} element - The element or stack (uses first item) to get the bounds for. - * @param {number} [cushion] - A +/- pixel adjustment amount. - * @return {Object|boolean} A plain object containing the properties `top/bottom/left/right/width/height` or `false` if a non-valid element is given. - */ + * A cross-browser element.getBoundingClientRect method with optional cushion. + * + * Returns a plain object containing the properties `top/bottom/left/right/width/height` with respect to the top-left corner of the current viewport. + * Its properties match the native rectangle. + * The cushion parameter is an amount of pixels (+/-) to cushion the element. + * It adjusts the measurements such that it is possible to detect when an element is near the viewport. + * + * @method Phaser.DOM.getBounds + * @param {DOMElement|Object} element - The element or stack (uses first item) to get the bounds for. + * @param {number} [cushion] - A +/- pixel adjustment amount. + * @return {Object|boolean} A plain object containing the properties `top/bottom/left/right/width/height` or `false` if a non-valid element is given. + */ getBounds: function (element, cushion) { - if (cushion === undefined) { cushion = 0; } element = element && !element.nodeType ? element[0] : element; @@ -74,21 +71,19 @@ Phaser.DOM = { { return this.calibrate(element.getBoundingClientRect(), cushion); } - }, /** - * Calibrates element coordinates for `inLayoutViewport` checks. - * - * @method Phaser.DOM.calibrate - * @private - * @param {object} coords - An object containing the following properties: `{top: number, right: number, bottom: number, left: number}` - * @param {number} [cushion] - A value to adjust the coordinates by. - * @return {object} The calibrated element coordinates - */ + * Calibrates element coordinates for `inLayoutViewport` checks. + * + * @method Phaser.DOM.calibrate + * @private + * @param {object} coords - An object containing the following properties: `{top: number, right: number, bottom: number, left: number}` + * @param {number} [cushion] - A value to adjust the coordinates by. + * @return {object} The calibrated element coordinates + */ calibrate: function (coords, cushion) { - cushion = +cushion || 0; var output = { width: 0, height: 0, left: 0, right: 0, top: 0, bottom: 0 }; @@ -97,19 +92,17 @@ Phaser.DOM = { output.height = (output.bottom = coords.bottom + cushion) - (output.top = coords.top - cushion); return output; - }, /** - * Get the Visual viewport aspect ratio (or the aspect ratio of an object or element) - * - * @method Phaser.DOM.getAspectRatio - * @param {(DOMElement|Object)} [object=(visualViewport)] - The object to determine the aspect ratio for. Must have public `width` and `height` properties or methods. - * @return {number} The aspect ratio. - */ + * Get the Visual viewport aspect ratio (or the aspect ratio of an object or element) + * + * @method Phaser.DOM.getAspectRatio + * @param {(DOMElement|Object)} [object=(visualViewport)] - The object to determine the aspect ratio for. Must have public `width` and `height` properties or methods. + * @return {number} The aspect ratio. + */ getAspectRatio: function (object) { - object = object == null ? this.visualBounds : object.nodeType === 1 ? this.getBounds(object) : object; var w = object.width; @@ -126,59 +119,55 @@ Phaser.DOM = { } return w / h; - }, /** - * Tests if the given DOM element is within the Layout viewport. - * - * The optional cushion parameter allows you to specify a distance. - * - * inLayoutViewport(element, 100) is `true` if the element is in the viewport or 100px near it. - * inLayoutViewport(element, -100) is `true` if the element is in the viewport or at least 100px near it. - * - * @method Phaser.DOM.inLayoutViewport - * @param {DOMElement|Object} element - The DOM element to check. If no element is given it defaults to the Phaser game canvas. - * @param {number} [cushion] - The cushion allows you to specify a distance within which the element must be within the viewport. - * @return {boolean} True if the element is within the viewport, or within `cushion` distance from it. - */ + * Tests if the given DOM element is within the Layout viewport. + * + * The optional cushion parameter allows you to specify a distance. + * + * inLayoutViewport(element, 100) is `true` if the element is in the viewport or 100px near it. + * inLayoutViewport(element, -100) is `true` if the element is in the viewport or at least 100px near it. + * + * @method Phaser.DOM.inLayoutViewport + * @param {DOMElement|Object} element - The DOM element to check. If no element is given it defaults to the Phaser game canvas. + * @param {number} [cushion] - The cushion allows you to specify a distance within which the element must be within the viewport. + * @return {boolean} True if the element is within the viewport, or within `cushion` distance from it. + */ inLayoutViewport: function (element, cushion) { - var r = this.getBounds(element, cushion); return !!r && r.bottom >= 0 && r.right >= 0 && r.top <= this.layoutBounds.width && r.left <= this.layoutBounds.height; - }, /** - * Returns the device screen orientation. - * - * Orientation values: 'portrait-primary', 'landscape-primary', 'portrait-secondary', 'landscape-secondary'. - * - * Order of resolving: - * - Screen Orientation API, or variation of - Future track. Most desktop and mobile browsers. - * - Screen size ratio check - If fallback is 'screen', suited for desktops. - * - Viewport size ratio check - If fallback is 'viewport', suited for mobile. - * - window.orientation - If fallback is 'window.orientation', works iOS and probably most Android; non-recommended track. - * - Media query - * - Viewport size ratio check (probably only IE9 and legacy mobile gets here..) - * - * See - * - https://w3c.github.io/screen-orientation/ (conflicts with mozOrientation/msOrientation) - * - https://developer.mozilla.org/en-US/docs/Web/API/Screen.orientation (mozOrientation) - * - http://msdn.microsoft.com/en-us/library/ie/dn342934(v=vs.85).aspx - * - https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Testing_media_queries - * - http://stackoverflow.com/questions/4917664/detect-viewport-orientation - * - http://www.matthewgifford.com/blog/2011/12/22/a-misconception-about-window-orientation - * - * @method Phaser.DOM.getScreenOrientation - * @protected - * @param {string} [primaryFallback=(none)] - Specify 'screen', 'viewport', or 'window.orientation'. - */ + * Returns the device screen orientation. + * + * Orientation values: 'portrait-primary', 'landscape-primary', 'portrait-secondary', 'landscape-secondary'. + * + * Order of resolving: + * - Screen Orientation API, or variation of - Future track. Most desktop and mobile browsers. + * - Screen size ratio check - If fallback is 'screen', suited for desktops. + * - Viewport size ratio check - If fallback is 'viewport', suited for mobile. + * - window.orientation - If fallback is 'window.orientation', works iOS and probably most Android; non-recommended track. + * - Media query + * - Viewport size ratio check (probably only IE9 and legacy mobile gets here..) + * + * See + * - https://w3c.github.io/screen-orientation/ (conflicts with mozOrientation/msOrientation) + * - https://developer.mozilla.org/en-US/docs/Web/API/Screen.orientation (mozOrientation) + * - http://msdn.microsoft.com/en-us/library/ie/dn342934(v=vs.85).aspx + * - https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Testing_media_queries + * - http://stackoverflow.com/questions/4917664/detect-viewport-orientation + * - http://www.matthewgifford.com/blog/2011/12/22/a-misconception-about-window-orientation + * + * @method Phaser.DOM.getScreenOrientation + * @protected + * @param {string} [primaryFallback=(none)] - Specify 'screen', 'viewport', or 'window.orientation'. + */ getScreenOrientation: function (primaryFallback) { - var screen = window.screen; var orientation = screen.orientation || screen.mozOrientation || screen.msOrientation; @@ -222,68 +211,66 @@ Phaser.DOM = { } return (this.visualBounds.height > this.visualBounds.width) ? PORTRAIT : LANDSCAPE; - }, /** - * The bounds of the Visual viewport, as discussed in - * {@link http://www.quirksmode.org/mobile/viewports.html A tale of two viewports — part one} - * with one difference: the viewport size _excludes_ scrollbars, as found on some desktop browsers. - * - * Supported mobile: - * iOS/Safari, Android 4, IE10, Firefox OS (maybe not Firefox Android), Opera Mobile 16 - * - * The properties change dynamically. - * - * @type {Phaser.Rectangle} - * @property {number} x - Scroll, left offset - eg. "scrollX" - * @property {number} y - Scroll, top offset - eg. "scrollY" - * @property {number} width - Viewport width in pixels. - * @property {number} height - Viewport height in pixels. - * @readonly - */ + * The bounds of the Visual viewport, as discussed in + * {@link http://www.quirksmode.org/mobile/viewports.html A tale of two viewports — part one} + * with one difference: the viewport size _excludes_ scrollbars, as found on some desktop browsers. + * + * Supported mobile: + * iOS/Safari, Android 4, IE10, Firefox OS (maybe not Firefox Android), Opera Mobile 16 + * + * The properties change dynamically. + * + * @type {Phaser.Rectangle} + * @property {number} x - Scroll, left offset - eg. "scrollX" + * @property {number} y - Scroll, top offset - eg. "scrollY" + * @property {number} width - Viewport width in pixels. + * @property {number} height - Viewport height in pixels. + * @readonly + */ visualBounds: new Phaser.Rectangle(), /** - * The bounds of the Layout viewport, as discussed in - * {@link http://www.quirksmode.org/mobile/viewports2.html A tale of two viewports — part two}; - * but honoring the constraints as specified applicable viewport meta-tag. - * - * The bounds returned are not guaranteed to be fully aligned with CSS media queries (see - * {@link http://www.matanich.com/2013/01/07/viewport-size/ What size is my viewport?}). - * - * This is _not_ representative of the Visual bounds: in particular the non-primary axis will - * generally be significantly larger than the screen height on mobile devices when running with a - * constrained viewport. - * - * The properties change dynamically. - * - * @type {Phaser.Rectangle} - * @property {number} width - Viewport width in pixels. - * @property {number} height - Viewport height in pixels. - * @readonly - */ + * The bounds of the Layout viewport, as discussed in + * {@link http://www.quirksmode.org/mobile/viewports2.html A tale of two viewports — part two}; + * but honoring the constraints as specified applicable viewport meta-tag. + * + * The bounds returned are not guaranteed to be fully aligned with CSS media queries (see + * {@link http://www.matanich.com/2013/01/07/viewport-size/ What size is my viewport?}). + * + * This is _not_ representative of the Visual bounds: in particular the non-primary axis will + * generally be significantly larger than the screen height on mobile devices when running with a + * constrained viewport. + * + * The properties change dynamically. + * + * @type {Phaser.Rectangle} + * @property {number} width - Viewport width in pixels. + * @property {number} height - Viewport height in pixels. + * @readonly + */ layoutBounds: new Phaser.Rectangle(), /** - * The size of the document / Layout viewport. - * - * This incorrectly reports the dimensions in IE. - * - * The properties change dynamically. - * - * @type {Phaser.Rectangle} - * @property {number} width - Document width in pixels. - * @property {number} height - Document height in pixels. - * @readonly - */ + * The size of the document / Layout viewport. + * + * This incorrectly reports the dimensions in IE. + * + * The properties change dynamically. + * + * @type {Phaser.Rectangle} + * @property {number} width - Document width in pixels. + * @property {number} height - Document height in pixels. + * @readonly + */ documentBounds: new Phaser.Rectangle() }; Phaser.Device.whenReady(function (device) { - // All target browsers should support page[XY]Offset. var scrollX = window && ('pageXOffset' in window) ? function () { return window.pageXOffset; } : @@ -294,23 +281,23 @@ Phaser.Device.whenReady(function (device) function () { return document.documentElement.scrollTop; }; /** - * A cross-browser window.scrollX. - * - * @name Phaser.DOM.scrollX - * @property {number} scrollX - * @readonly - * @protected - */ + * A cross-browser window.scrollX. + * + * @name Phaser.DOM.scrollX + * @property {number} scrollX + * @readonly + * @protected + */ Object.defineProperty(Phaser.DOM, 'scrollX', {get: scrollX}); /** - * A cross-browser window.scrollY. - * - * @name Phaser.DOM.scrollY - * @property {number} scrollY - * @readonly - * @protected - */ + * A cross-browser window.scrollY. + * + * @name Phaser.DOM.scrollY + * @property {number} scrollY + * @readonly + * @protected + */ Object.defineProperty(Phaser.DOM, 'scrollY', {get: scrollY}); Object.defineProperty(Phaser.DOM.visualBounds, 'x', {get: scrollX}); @@ -325,14 +312,17 @@ Phaser.Device.whenReady(function (device) (document.documentElement.clientWidth <= window.innerWidth) && (document.documentElement.clientHeight <= window.innerHeight); - // Desktop browsers align the layout viewport with the visual viewport. - // This differs from mobile browsers with their zooming design. - // Ref. http://quirksmode.org/mobile/tableViewport.html + /* + * Desktop browsers align the layout viewport with the visual viewport. + * This differs from mobile browsers with their zooming design. + * Ref. http://quirksmode.org/mobile/tableViewport.html + */ if (treatAsDesktop) { - - // PST- When scrollbars are not included this causes upstream issues in ScaleManager. - // So reverted to the old "include scrollbars." + /* + * PST- When scrollbars are not included this causes upstream issues in ScaleManager. + * So reverted to the old "include scrollbars." + */ var clientWidth = function () { return Math.max(window.innerWidth, document.documentElement.clientWidth); @@ -350,11 +340,9 @@ Phaser.Device.whenReady(function (device) Object.defineProperty(Phaser.DOM.layoutBounds, 'width', {get: clientWidth}); Object.defineProperty(Phaser.DOM.layoutBounds, 'height', {get: clientHeight}); - } else { - Object.defineProperty(Phaser.DOM.visualBounds, 'width', { get: function () { @@ -392,11 +380,12 @@ Phaser.Device.whenReady(function (device) } }); - } - // For Phaser.DOM.documentBounds - // Ref. http://www.quirksmode.org/mobile/tableViewport_desktop.html + /* + * For Phaser.DOM.documentBounds + * Ref. http://www.quirksmode.org/mobile/tableViewport_desktop.html + */ Object.defineProperty(Phaser.DOM.documentBounds, 'x', {value: 0}); @@ -421,5 +410,4 @@ Phaser.Device.whenReady(function (device) } }); - }, null, true); diff --git a/src/utils/Debug.js b/src/utils/Debug.js index 70a85f10f..93508c47d 100644 --- a/src/utils/Debug.js +++ b/src/utils/Debug.js @@ -1,112 +1,111 @@ /** -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* A collection of methods for displaying debug information about game objects. -* -* If your game is running in Canvas mode, then you should invoke all of the Debug methods from -* your game's `render` function. This is because they are drawn directly onto the game canvas -* itself, so if you call any debug methods outside of `render` they are likely to be overwritten -* by the game itself. -* -* If your game is running in WebGL then Debug will create a Sprite that is placed at the top of the Stage display list and bind a canvas texture -* to it, which must be uploaded every frame. Be advised: this is very expensive, especially in browsers like Firefox. So please only enable Debug -* in WebGL mode if you really need it (or your desktop can cope with it well) and disable it for production! -* -* @class Phaser.Utils.Debug -* @constructor -* @param {Phaser.Game} game - A reference to the currently running game. -*/ + * A collection of methods for displaying debug information about game objects. + * + * If your game is running in Canvas mode, then you should invoke all of the Debug methods from + * your game's `render` function. This is because they are drawn directly onto the game canvas + * itself, so if you call any debug methods outside of `render` they are likely to be overwritten + * by the game itself. + * + * If your game is running in WebGL then Debug will create a Sprite that is placed at the top of the Stage display list and bind a canvas texture + * to it, which must be uploaded every frame. Be advised: this is very expensive, especially in browsers like Firefox. So please only enable Debug + * in WebGL mode if you really need it (or your desktop can cope with it well) and disable it for production! + * + * @class Phaser.Utils.Debug + * @constructor + * @param {Phaser.Game} game - A reference to the currently running game. + */ Phaser.Utils.Debug = function (game) { - /** - * @property {Phaser.Game} game - A reference to the currently running Game. - */ + * @property {Phaser.Game} game - A reference to the currently running Game. + */ this.game = game; /** - * @property {Phaser.Image} sprite - If debugging in WebGL mode, this is the Image displaying the debug {@link #bmd BitmapData}. - */ + * @property {Phaser.Image} sprite - If debugging in WebGL mode, this is the Image displaying the debug {@link #bmd BitmapData}. + */ this.sprite = null; /** - * @property {Phaser.BitmapData} bmd - In WebGL mode this BitmapData contains a copy of the debug canvas. - */ + * @property {Phaser.BitmapData} bmd - In WebGL mode this BitmapData contains a copy of the debug canvas. + */ this.bmd = null; /** - * @property {HTMLCanvasElement} canvas - The canvas to which Debug calls draws. - */ + * @property {HTMLCanvasElement} canvas - The canvas to which Debug calls draws. + */ this.canvas = null; /** - * @property {CanvasRenderingContext2D} context - The 2d context of the canvas. - */ + * @property {CanvasRenderingContext2D} context - The 2d context of the canvas. + */ this.context = null; /** - * @property {string} font - The font that the debug information is rendered in. - * @default - */ + * @property {string} font - The font that the debug information is rendered in. + * @default + */ this.font = '14px monospace'; /** - * @property {number} columnWidth - The spacing between columns. - * @default - */ + * @property {number} columnWidth - The spacing between columns. + * @default + */ this.columnWidth = 100; /** - * @property {number} lineHeight - The line height between the debug text. - * @default - */ + * @property {number} lineHeight - The line height between the debug text. + * @default + */ this.lineHeight = 16; /** - * @property {number} lineWidth - The width of the stroke on lines and shapes. A positive number. - * @default - */ + * @property {number} lineWidth - The width of the stroke on lines and shapes. A positive number. + * @default + */ this.lineWidth = 1; /** - * @property {boolean} renderShadow - Should the text be rendered with a slight shadow? Makes it easier to read on different types of background. - * @default - */ + * @property {boolean} renderShadow - Should the text be rendered with a slight shadow? Makes it easier to read on different types of background. + * @default + */ this.renderShadow = true; /** - * @property {string} currentColor - The color last set by {@link #start} or {@link #text}. - * @default - * @protected - */ + * @property {string} currentColor - The color last set by {@link #start} or {@link #text}. + * @default + * @protected + */ this.currentColor = null; /** - * @property {number} currentX - The current X position the debug information will be rendered at. - * @default - */ + * @property {number} currentX - The current X position the debug information will be rendered at. + * @default + */ this.currentX = 0; /** - * @property {number} currentY - The current Y position the debug information will be rendered at. - * @default - */ + * @property {number} currentY - The current Y position the debug information will be rendered at. + * @default + */ this.currentY = 0; /** - * @property {number} currentAlpha - The alpha of the Debug context, set before all debug information is rendered to it. - * @default - */ + * @property {number} currentAlpha - The alpha of the Debug context, set before all debug information is rendered to it. + * @default + */ this.currentAlpha = 1; /** - * @property {boolean} dirty - Does the canvas need re-rendering? - * @default - */ + * @property {boolean} dirty - Does the canvas need re-rendering? + * @default + */ this.dirty = false; /** @@ -127,56 +126,54 @@ Phaser.Utils.Debug = function (game) * @private */ this._rect = null; - }; /** -* @constant -* @type {integer} -*/ + * @constant + * @type {integer} + */ Phaser.Utils.Debug.GEOM_AUTO = 0; /** -* @constant -* @type {integer} -*/ + * @constant + * @type {integer} + */ Phaser.Utils.Debug.GEOM_RECTANGLE = 1; /** -* @constant -* @type {integer} -*/ + * @constant + * @type {integer} + */ Phaser.Utils.Debug.GEOM_CIRCLE = 2; /** -* @constant -* @type {integer} -*/ + * @constant + * @type {integer} + */ Phaser.Utils.Debug.GEOM_POINT = 3; /** -* @constant -* @type {integer} -*/ + * @constant + * @type {integer} + */ Phaser.Utils.Debug.GEOM_LINE = 4; /** -* @constant -* @type {integer} -*/ + * @constant + * @type {integer} + */ Phaser.Utils.Debug.GEOM_ELLIPSE = 5; Phaser.Utils.Debug.prototype = { /** - * Internal method that boots the debug displayer. - * - * @method Phaser.Utils.Debug#boot - * @protected - */ + * Internal method that boots the debug displayer. + * + * @method Phaser.Utils.Debug#boot + * @protected + */ boot: function () { - if (this.game.renderType === Phaser.CANVAS) { this.context = this.game.context; @@ -195,35 +192,31 @@ Phaser.Utils.Debug.prototype = { this._line = new Phaser.Line(); this._rect = new Phaser.Rectangle(); - }, /** - * Internal method that resizes the BitmapData and Canvas. - * Called by ScaleManager.onSizeChange only in WebGL mode. - * - * @method Phaser.Utils.Debug#resize - * @protected - */ + * Internal method that resizes the BitmapData and Canvas. + * Called by ScaleManager.onSizeChange only in WebGL mode. + * + * @method Phaser.Utils.Debug#resize + * @protected + */ resize: function () { - this.bmd.resize(this.game.width, this.game.height); this.canvas.width = this.game.width; this.canvas.height = this.game.height; - }, /** - * Internal method that clears the canvas (if a Sprite) ready for a new debug session. - * - * @method Phaser.Utils.Debug#preUpdate - * @protected - */ + * Internal method that clears the canvas (if a Sprite) ready for a new debug session. + * + * @method Phaser.Utils.Debug#preUpdate + * @protected + */ preUpdate: function () { - if (this.dirty && this.sprite) { this.bmd.clear(); @@ -232,17 +225,15 @@ Phaser.Utils.Debug.prototype = { this.context.clearRect(0, 0, this.game.width, this.game.height); this.dirty = false; } - }, /** - * Clears the Debug canvas. - * - * @method Phaser.Utils.Debug#reset - */ + * Clears the Debug canvas. + * + * @method Phaser.Utils.Debug#reset + */ reset: function () { - if (this.context) { this.context.clearRect(0, 0, this.game.width, this.game.height); @@ -252,22 +243,20 @@ Phaser.Utils.Debug.prototype = { { this.bmd.clear(); } - }, /** - * Internal method that resets and starts the debug output values. - * - * @method Phaser.Utils.Debug#start - * @protected - * @param {number} [x=0] - The X value the debug info will start from. - * @param {number} [y=0] - The Y value the debug info will start from. - * @param {string} [color='rgb(255,255,255)'] - The color the debug text will drawn in. - * @param {number} [columnWidth=0] - The spacing between columns. - */ + * Internal method that resets and starts the debug output values. + * + * @method Phaser.Utils.Debug#start + * @protected + * @param {number} [x=0] - The X value the debug info will start from. + * @param {number} [y=0] - The Y value the debug info will start from. + * @param {string} [color='rgb(255,255,255)'] - The color the debug text will drawn in. + * @param {number} [columnWidth=0] - The spacing between columns. + */ start: function (x, y, color, columnWidth) { - if (typeof x !== 'number') { x = 0; } if (typeof y !== 'number') { y = 0; } color = color || 'rgb(255,255,255)'; @@ -286,31 +275,27 @@ Phaser.Utils.Debug.prototype = { this.context.fillStyle = color; this.context.font = this.font; this.context.globalAlpha = this.currentAlpha; - }, /** - * Internal method that stops the debug output. - * - * @method Phaser.Utils.Debug#stop - * @protected - */ + * Internal method that stops the debug output. + * + * @method Phaser.Utils.Debug#stop + * @protected + */ stop: function () { - this.context.restore(); - }, /** - * Internal method that outputs a single line of text split over as many columns as needed, one per parameter. - * - * @method Phaser.Utils.Debug#line - * @protected - */ + * Internal method that outputs a single line of text split over as many columns as needed, one per parameter. + * + * @method Phaser.Utils.Debug#line + * @protected + */ line: function () { - var x = this.currentX; for (var i = 0; i < arguments.length; i++) @@ -328,20 +313,18 @@ Phaser.Utils.Debug.prototype = { } this.currentY += this.lineHeight; - }, /** - * Render game info (ID, renderer, paused, stepping). - * - * @method Phaser.Utils.Debug#gameInfo - * @param {number} x - X position of the debug info to be rendered. - * @param {number} y - Y position of the debug info to be rendered. - * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). - */ + * Render game info (ID, renderer, paused, stepping). + * + * @method Phaser.Utils.Debug#gameInfo + * @param {number} x - X position of the debug info to be rendered. + * @param {number} y - Y position of the debug info to be rendered. + * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). + */ gameInfo: function (x, y, color) { - var game = this.game; this.start(x, y, color); @@ -352,20 +335,18 @@ Phaser.Utils.Debug.prototype = { this.line('Stepping: ' + game.stepping + ' (' + game.stepCount + ')'); this.stop(); - }, /** - * Render Sound Manager information, including volume, mute, audio mode, and locked status. - * - * @method Phaser.Utils.Debug#sound - * @param {number} x - X position of the debug info to be rendered. - * @param {number} y - Y position of the debug info to be rendered. - * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). - */ + * Render Sound Manager information, including volume, mute, audio mode, and locked status. + * + * @method Phaser.Utils.Debug#sound + * @param {number} x - X position of the debug info to be rendered. + * @param {number} y - Y position of the debug info to be rendered. + * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). + */ sound: function (x, y, color) { - var sound = this.game.sound; this.start(x, y, color); @@ -384,21 +365,19 @@ Phaser.Utils.Debug.prototype = { } this.stop(); - }, /** - * Render Sound information, including decoded state, duration, volume and more. - * - * @method Phaser.Utils.Debug#soundInfo - * @param {Phaser.Sound} sound - The sound object to debug. - * @param {number} x - X position of the debug info to be rendered. - * @param {number} y - Y position of the debug info to be rendered. - * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). - */ + * Render Sound information, including decoded state, duration, volume and more. + * + * @method Phaser.Utils.Debug#soundInfo + * @param {Phaser.Sound} sound - The sound object to debug. + * @param {number} x - X position of the debug info to be rendered. + * @param {number} y - Y position of the debug info to be rendered. + * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). + */ soundInfo: function (sound, x, y, color) { - this.start(x, y, color); this.line('Sound: ' + sound.key + ' Touch locked: ' + sound.game.sound.touchLocked); this.line('Is Ready?: ' + this.game.cache.isSoundReady(sound.key) + ' Pending Playback: ' + sound.pendingPlayback); @@ -434,20 +413,18 @@ Phaser.Utils.Debug.prototype = { } this.stop(); - }, /** - * Marks the follow {@link #target} and {@link #deadzone}. - * - * @method Phaser.Utils.Debug#camera - * @param {Phaser.Camera} camera - The Phaser.Camera to show the debug information for. - * @param {string} [color] - Color of the debug shapes to be rendered (format is css color string). - * @param {boolean} [filled=true] - Render the shapes filled (default, true) or stroked (false). - */ + * Marks the follow {@link #target} and {@link #deadzone}. + * + * @method Phaser.Utils.Debug#camera + * @param {Phaser.Camera} camera - The Phaser.Camera to show the debug information for. + * @param {string} [color] - Color of the debug shapes to be rendered (format is css color string). + * @param {boolean} [filled=true] - Render the shapes filled (default, true) or stroked (false). + */ camera: function (camera, color, filled) { - var deadzone = camera.deadzone; var target = camera.target; var view = camera.view; @@ -464,21 +441,19 @@ Phaser.Utils.Debug.prototype = { this.geom(this._line, color, filled); this.geom(target, color, false, 3); } - }, /** - * Render camera information including dimensions and location. - * - * @method Phaser.Utils.Debug#cameraInfo - * @param {Phaser.Camera} camera - The Phaser.Camera to show the debug information for. - * @param {number} x - X position of the debug info to be rendered. - * @param {number} y - Y position of the debug info to be rendered. - * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). - */ + * Render camera information including dimensions and location. + * + * @method Phaser.Utils.Debug#cameraInfo + * @param {Phaser.Camera} camera - The Phaser.Camera to show the debug information for. + * @param {number} x - X position of the debug info to be rendered. + * @param {number} y - Y position of the debug info to be rendered. + * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). + */ cameraInfo: function (camera, x, y, color) { - var bounds = camera.bounds; var deadzone = camera.deadzone; var target = camera.target; @@ -495,43 +470,39 @@ Phaser.Utils.Debug.prototype = { this.line('At limit: x: ' + camera.atLimit.x + ' y: ' + camera.atLimit.y); this.line('Target: ' + (target ? (target.name || target) : 'none')); this.stop(); - }, /** - * Render Timer information. - * - * @method Phaser.Utils.Debug#timer - * @param {Phaser.Timer} timer - The Phaser.Timer to show the debug information for. - * @param {number} x - X position of the debug info to be rendered. - * @param {number} y - Y position of the debug info to be rendered. - * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). - */ + * Render Timer information. + * + * @method Phaser.Utils.Debug#timer + * @param {Phaser.Timer} timer - The Phaser.Timer to show the debug information for. + * @param {number} x - X position of the debug info to be rendered. + * @param {number} y - Y position of the debug info to be rendered. + * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). + */ timer: function (timer, x, y, color) { - this.start(x, y, color); this.line('Timer (running: ' + timer.running + ' expired: ' + timer.expired + ')'); this.line('Next Tick: ' + timer.next + ' Duration: ' + timer.duration); this.line('Paused: ' + timer.paused + ' Length: ' + timer.length); this.stop(); - }, /** - * Renders the Pointer.circle object onto the stage in green if down or yellow if up along with debug text. - * - * @method Phaser.Utils.Debug#pointer - * @param {Phaser.Pointer} pointer - The Pointer you wish to display. - * @param {boolean} [hideIfUp=false] - Doesn't render the circle if the pointer is up. - * @param {string} [downColor='rgba(0,255,0,0.5)'] - The color the circle is rendered in if the Pointer is down. - * @param {string} [upColor='rgba(255,255,0,0.5)'] - The color the circle is rendered in if the Pointer is up (and hideIfUp is false). - * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). - * @param {string} [inactiveColor='rgb(255,0,0,0.5)'] - The color the circle is rendered in if the Pointer is inactive. - */ + * Renders the Pointer.circle object onto the stage in green if down or yellow if up along with debug text. + * + * @method Phaser.Utils.Debug#pointer + * @param {Phaser.Pointer} pointer - The Pointer you wish to display. + * @param {boolean} [hideIfUp=false] - Doesn't render the circle if the pointer is up. + * @param {string} [downColor='rgba(0,255,0,0.5)'] - The color the circle is rendered in if the Pointer is down. + * @param {string} [upColor='rgba(255,255,0,0.5)'] - The color the circle is rendered in if the Pointer is up (and hideIfUp is false). + * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). + * @param {string} [inactiveColor='rgb(255,0,0,0.5)'] - The color the circle is rendered in if the Pointer is inactive. + */ pointer: function (pointer, hideIfUp, downColor, upColor, color, inactiveColor) { - if (pointer == null) { return; @@ -602,7 +573,6 @@ Phaser.Utils.Debug.prototype = { } this.stop(); - }, _pointerButtonIcon: function (btn) @@ -614,17 +584,16 @@ Phaser.Utils.Debug.prototype = { }, /** - * Render Sprite Input Debug information. - * - * @method Phaser.Utils.Debug#spriteInputInfo - * @param {Phaser.Sprite|Phaser.Image} sprite - The sprite to display the input data for. - * @param {number} x - X position of the debug info to be rendered. - * @param {number} y - Y position of the debug info to be rendered. - * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). - */ + * Render Sprite Input Debug information. + * + * @method Phaser.Utils.Debug#spriteInputInfo + * @param {Phaser.Sprite|Phaser.Image} sprite - The sprite to display the input data for. + * @param {number} x - X position of the debug info to be rendered. + * @param {number} y - Y position of the debug info to be rendered. + * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). + */ spriteInputInfo: function (sprite, x, y, color) { - this.start(x, y, color); this.line('Sprite Input: (' + sprite.width + ' x ' + sprite.height + ')'); this.line('x: ' + sprite.input.pointerX().toFixed(1) + ' y: ' + sprite.input.pointerY().toFixed(1)); @@ -632,21 +601,19 @@ Phaser.Utils.Debug.prototype = { this.line('down: ' + sprite.input.pointerDown() + ' duration: ' + sprite.input.downDuration().toFixed(0)); this.line('just over: ' + sprite.input.justOver() + ' just out: ' + sprite.input.justOut()); this.stop(); - }, /** - * Renders Phaser.Key object information. - * - * @method Phaser.Utils.Debug#key - * @param {Phaser.Key} key - The Key to render the information for. - * @param {number} x - X position of the debug info to be rendered. - * @param {number} y - Y position of the debug info to be rendered. - * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). - */ + * Renders Phaser.Key object information. + * + * @method Phaser.Utils.Debug#key + * @param {Phaser.Key} key - The Key to render the information for. + * @param {number} x - X position of the debug info to be rendered. + * @param {number} y - Y position of the debug info to be rendered. + * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). + */ key: function (key, x, y, color) { - this.start(x, y, color, 150); this.line('Key:', key.keyCode, 'isDown:', key.isDown); @@ -654,21 +621,19 @@ Phaser.Utils.Debug.prototype = { this.line('Time Down:', key.timeDown.toFixed(0), 'duration:', key.duration.toFixed(0)); this.stop(); - }, /** - * Render debug information about the Input object. - * - * @method Phaser.Utils.Debug#inputInfo - * @param {number} x - X position of the debug info to be rendered. - * @param {number} y - Y position of the debug info to be rendered. - * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). - * @param {boolean} [showDetails=true] - Also describe input sources and pointers. - */ + * Render debug information about the Input object. + * + * @method Phaser.Utils.Debug#inputInfo + * @param {number} x - X position of the debug info to be rendered. + * @param {number} y - Y position of the debug info to be rendered. + * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). + * @param {boolean} [showDetails=true] - Also describe input sources and pointers. + */ inputInfo: function (x, y, color, showDetails) { - var input = this.game.input; if (showDetails === undefined) @@ -718,7 +683,6 @@ Phaser.Utils.Debug.prototype = { this.line(' Active: ' + active + ' Free: ' + free + ' Max: ' + input.maxPointers); this.stop(); - }, /** @@ -772,59 +736,52 @@ Phaser.Utils.Debug.prototype = { _inputHandlerStatusIcon: function (handler) { - if (!handler.active) { return ' '; } return handler.enabled ? '+' : '-'; - }, _inputHandlerCaptureIcon: function (handler) { - if (!handler.active) { return ' '; } return (handler.capture || handler.preventDefault) ? '*' : ' '; - }, /** - * Renders the Sprites bounds. Note: This is really expensive as it has to calculate the bounds every time you call it! - * - * @method Phaser.Utils.Debug#spriteBounds - * @param {Phaser.Sprite|Phaser.Image} sprite - The sprite to display the bounds of. - * @param {string} [color] - Color of the debug info to be rendered (format is css color string). - * @param {boolean} [filled=true] - Render the rectangle as a fillRect (default, true) or a strokeRect (false) - */ + * Renders the Sprites bounds. Note: This is really expensive as it has to calculate the bounds every time you call it! + * + * @method Phaser.Utils.Debug#spriteBounds + * @param {Phaser.Sprite|Phaser.Image} sprite - The sprite to display the bounds of. + * @param {string} [color] - Color of the debug info to be rendered (format is css color string). + * @param {boolean} [filled=true] - Render the rectangle as a fillRect (default, true) or a strokeRect (false) + */ spriteBounds: function (sprite, color, filled) { - var bounds = sprite.getBounds(); bounds.x += this.game.camera.x; bounds.y += this.game.camera.y; this.rectangle(bounds, color, filled); - }, /** - * Renders the Rope's segments. Note: This is really expensive as it has to calculate new segments every time you call it - * - * @method Phaser.Utils.Debug#ropeSegments - * @param {Phaser.Rope} rope - The rope to display the segments of. - * @param {string} [color] - Color of the debug info to be rendered (format is css color string). - * @param {boolean} [filled=true] - Render the rectangle as a fillRect (default, true) or a strokeRect (false) - */ + * Renders the Rope's segments. Note: This is really expensive as it has to calculate new segments every time you call it + * + * @method Phaser.Utils.Debug#ropeSegments + * @param {Phaser.Rope} rope - The rope to display the segments of. + * @param {string} [color] - Color of the debug info to be rendered (format is css color string). + * @param {boolean} [filled=true] - Render the rectangle as a fillRect (default, true) or a strokeRect (false) + */ ropeSegments: function (rope, color, filled) { - var segments = rope.segments; var self = this; @@ -833,21 +790,19 @@ Phaser.Utils.Debug.prototype = { { self.rectangle(segment, color, filled); }, this); - }, /** - * Render debug infos (including name, bounds info, position and some other properties) about the Sprite. - * - * @method Phaser.Utils.Debug#spriteInfo - * @param {Phaser.Sprite} sprite - The Sprite to display the information of. - * @param {number} x - X position of the debug info to be rendered. - * @param {number} y - Y position of the debug info to be rendered. - * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). - */ + * Render debug infos (including name, bounds info, position and some other properties) about the Sprite. + * + * @method Phaser.Utils.Debug#spriteInfo + * @param {Phaser.Sprite} sprite - The Sprite to display the information of. + * @param {number} x - X position of the debug info to be rendered. + * @param {number} y - Y position of the debug info to be rendered. + * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). + */ spriteInfo: function (sprite, x, y, color) { - this.start(x, y, color); this.line('Sprite: ' + (sprite.name || '') + ' (' + sprite.width + ' x ' + sprite.height + ') anchor: ' + sprite.anchor.x + ' x ' + sprite.anchor.y); @@ -858,21 +813,19 @@ Phaser.Utils.Debug.prototype = { this.line('parent: ' + (sprite.parent ? (sprite.parent.name || '(DisplayObject)') : '(none)')); this.stop(); - }, /** - * Renders the sprite coordinates in local, positional and world space. - * - * @method Phaser.Utils.Debug#spriteCoords - * @param {Phaser.Sprite|Phaser.Image} sprite - The sprite to display the coordinates for. - * @param {number} x - X position of the debug info to be rendered. - * @param {number} y - Y position of the debug info to be rendered. - * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). - */ + * Renders the sprite coordinates in local, positional and world space. + * + * @method Phaser.Utils.Debug#spriteCoords + * @param {Phaser.Sprite|Phaser.Image} sprite - The sprite to display the coordinates for. + * @param {number} x - X position of the debug info to be rendered. + * @param {number} y - Y position of the debug info to be rendered. + * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). + */ spriteCoords: function (sprite, x, y, color) { - this.start(x, y, color, 100); if (sprite.name) @@ -885,62 +838,56 @@ Phaser.Utils.Debug.prototype = { this.line('world x:', sprite.world.x.toFixed(2), 'world y:', sprite.world.y.toFixed(2)); this.stop(); - }, /** - * Renders Line information in the given color. - * - * @method Phaser.Utils.Debug#lineInfo - * @param {Phaser.Line} line - The Line to display the data for. - * @param {number} x - X position of the debug info to be rendered. - * @param {number} y - Y position of the debug info to be rendered. - * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). - */ + * Renders Line information in the given color. + * + * @method Phaser.Utils.Debug#lineInfo + * @param {Phaser.Line} line - The Line to display the data for. + * @param {number} x - X position of the debug info to be rendered. + * @param {number} y - Y position of the debug info to be rendered. + * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). + */ lineInfo: function (line, x, y, color) { - this.start(x, y, color, 80); this.line('start.x:', line.start.x.toFixed(2), 'start.y:', line.start.y.toFixed(2)); this.line('end.x:', line.end.x.toFixed(2), 'end.y:', line.end.y.toFixed(2)); this.line('length:', line.length.toFixed(2), 'angle:', line.angle); this.stop(); - }, /** - * Renders a single pixel at the given size. - * - * @method Phaser.Utils.Debug#pixel - * @param {number} x - X position of the pixel to be rendered. - * @param {number} y - Y position of the pixel to be rendered. - * @param {string} [color] - Color of the pixel (format is css color string). - * @param {number} [size=2] - The width and height of the rendered pixel. - */ + * Renders a single pixel at the given size. + * + * @method Phaser.Utils.Debug#pixel + * @param {number} x - X position of the pixel to be rendered. + * @param {number} y - Y position of the pixel to be rendered. + * @param {string} [color] - Color of the pixel (format is css color string). + * @param {number} [size=2] - The width and height of the rendered pixel. + */ pixel: function (x, y, color, size) { - size = size || 2; this.start(); this.context.fillStyle = color; this.context.fillRect(x, y, size, size); this.stop(); - }, /** - * Renders a Phaser geometry object including Rectangle, Circle, Ellipse, Point or Line. - * - * @method Phaser.Utils.Debug#geom - * @param {Phaser.Rectangle|Phaser.Circle|Phaser.Ellipse|Phaser.Point|Phaser.Line} object - The geometry object to render. - * @param {string} [color] - Color of the debug info to be rendered (format is css color string). - * @param {boolean} [filled=true] - Render the objected as a filled (default, true) or a stroked (false) - * @param {number} [forceType=Phaser.Utils.Debug.GEOM_AUTO] - Force rendering of a specific type: (0) GEOM_AUTO, 1 GEOM_RECTANGLE, (2) GEOM_CIRCLE, (3) GEOM_POINT, (4) GEOM_LINE, (5) GEOM_ELLIPSE. + * Renders a Phaser geometry object including Rectangle, Circle, Ellipse, Point or Line. + * + * @method Phaser.Utils.Debug#geom + * @param {Phaser.Rectangle|Phaser.Circle|Phaser.Ellipse|Phaser.Point|Phaser.Line} object - The geometry object to render. + * @param {string} [color] - Color of the debug info to be rendered (format is css color string). + * @param {boolean} [filled=true] - Render the objected as a filled (default, true) or a stroked (false) + * @param {number} [forceType=Phaser.Utils.Debug.GEOM_AUTO] - Force rendering of a specific type: (0) GEOM_AUTO, 1 GEOM_RECTANGLE, (2) GEOM_CIRCLE, (3) GEOM_POINT, (4) GEOM_LINE, (5) GEOM_ELLIPSE. */ geom: function (object, color, filled, forceType) { - if (filled === undefined) { filled = true; } if (forceType === undefined) { forceType = 0; } @@ -1009,20 +956,18 @@ Phaser.Utils.Debug.prototype = { } this.stop(); - }, /** - * Renders a Rectangle. - * - * @method Phaser.Utils.Debug#rectangle - * @param {Phaser.Rectangle|object} object - The rectangle to render. - * @param {string} [color] - Color of the debug info to be rendered (format is css color string). - * @param {boolean} [filled=true] - Render the rectangle as filled (default, true) or a stroked (false) - */ + * Renders a Rectangle. + * + * @method Phaser.Utils.Debug#rectangle + * @param {Phaser.Rectangle|object} object - The rectangle to render. + * @param {string} [color] - Color of the debug info to be rendered (format is css color string). + * @param {boolean} [filled=true] - Render the rectangle as filled (default, true) or a stroked (false) + */ rectangle: function (object, color, filled) { - if (filled === undefined) { filled = true; } color = color || 'rgba(0, 255, 0, 0.4)'; @@ -1042,22 +987,20 @@ Phaser.Utils.Debug.prototype = { } this.stop(); - }, /** - * Render a string of text. - * - * @method Phaser.Utils.Debug#text - * @param {string} text - The line of text to draw. - * @param {number} x - X position of the debug info to be rendered. - * @param {number} y - Y position of the debug info to be rendered. - * @param {string} [color] - Color of the debug info to be rendered (format is css color string). - * @param {string} [font] - The font of text to draw. - */ + * Render a string of text. + * + * @method Phaser.Utils.Debug#text + * @param {string} text - The line of text to draw. + * @param {number} x - X position of the debug info to be rendered. + * @param {number} y - Y position of the debug info to be rendered. + * @param {string} [color] - Color of the debug info to be rendered (format is css color string). + * @param {string} [font] - The font of text to draw. + */ text: function (text, x, y, color, font) { - color = color || 'rgb(255,255,255)'; font = font || this.font; @@ -1074,19 +1017,17 @@ Phaser.Utils.Debug.prototype = { this.context.fillText(text, x, y); this.stop(); - }, /** - * Visually renders a QuadTree to the display. - * - * @method Phaser.Utils.Debug#quadTree - * @param {Phaser.QuadTree} quadtree - The quadtree to render. - * @param {string} color - The color of the lines in the quadtree. - */ + * Visually renders a QuadTree to the display. + * + * @method Phaser.Utils.Debug#quadTree + * @param {Phaser.QuadTree} quadtree - The quadtree to render. + * @param {string} color - The color of the lines in the quadtree. + */ quadTree: function (quadtree, color) { - color = color || 'rgba(255,0,0,0.3)'; this.start(); @@ -1115,22 +1056,20 @@ Phaser.Utils.Debug.prototype = { } this.stop(); - }, /** - * Render a Sprites Physics body if it has one set. The body is rendered as a filled or stroked rectangle. - * This only works for Arcade Physics, Ninja Physics (AABB and Circle only) and Box2D Physics bodies. - * To display a P2 Physics body you should enable debug mode on the body when creating it. - * - * @method Phaser.Utils.Debug#body - * @param {Phaser.Sprite} sprite - The Sprite who's body will be rendered. - * @param {string} [color='rgba(0,255,0,0.4)'] - Color of the debug rectangle to be rendered. The format is a CSS color string such as '#ff0000' or 'rgba(255,0,0,0.5)'. - * @param {boolean} [filled=true] - Render the body as a filled rectangle (true) or a stroked rectangle (false) - */ + * Render a Sprites Physics body if it has one set. The body is rendered as a filled or stroked rectangle. + * This only works for Arcade Physics, Ninja Physics (AABB and Circle only) and Box2D Physics bodies. + * To display a P2 Physics body you should enable debug mode on the body when creating it. + * + * @method Phaser.Utils.Debug#body + * @param {Phaser.Sprite} sprite - The Sprite who's body will be rendered. + * @param {string} [color='rgba(0,255,0,0.4)'] - Color of the debug rectangle to be rendered. The format is a CSS color string such as '#ff0000' or 'rgba(255,0,0,0.5)'. + * @param {boolean} [filled=true] - Render the body as a filled rectangle (true) or a stroked rectangle (false) + */ body: function (sprite, color, filled) { - if (sprite.body) { this.start(); @@ -1150,21 +1089,19 @@ Phaser.Utils.Debug.prototype = { this.stop(); } - }, /** - * Render a Sprites Physic Body information. - * - * @method Phaser.Utils.Debug#bodyInfo - * @param {Phaser.Sprite} sprite - The sprite to be rendered. - * @param {number} x - X position of the debug info to be rendered. - * @param {number} y - Y position of the debug info to be rendered. - * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). - */ + * Render a Sprites Physic Body information. + * + * @method Phaser.Utils.Debug#bodyInfo + * @param {Phaser.Sprite} sprite - The sprite to be rendered. + * @param {number} x - X position of the debug info to be rendered. + * @param {number} y - Y position of the debug info to be rendered. + * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). + */ bodyInfo: function (sprite, x, y, color) { - if (sprite.body) { this.start(x, y, color, 210); @@ -1180,58 +1117,52 @@ Phaser.Utils.Debug.prototype = { this.stop(); } - }, /** - * Renders 'debug draw' data for the Box2D world if it exists. - * This uses the standard debug drawing feature of Box2D, so colors will be decided by - * the Box2D engine. - * - * @method Phaser.Utils.Debug#box2dWorld - */ + * Renders 'debug draw' data for the Box2D world if it exists. + * This uses the standard debug drawing feature of Box2D, so colors will be decided by + * the Box2D engine. + * + * @method Phaser.Utils.Debug#box2dWorld + */ box2dWorld: function () { - this.start(); this.context.translate(-this.game.camera.view.x, -this.game.camera.view.y, 0); this.game.physics.box2d.renderDebugDraw(this.context); this.stop(); - }, /** - * Renders 'debug draw' data for the given Box2D body. - * This uses the standard debug drawing feature of Box2D, so colors will be decided by the Box2D engine. - * - * @method Phaser.Utils.Debug#box2dBody - * @param {Phaser.Physics.Box2D.Body} body - The body to be rendered. - * @param {string} [color='rgb(0,255,0)'] - Color of the rendering (format is css color string). - */ + * Renders 'debug draw' data for the given Box2D body. + * This uses the standard debug drawing feature of Box2D, so colors will be decided by the Box2D engine. + * + * @method Phaser.Utils.Debug#box2dBody + * @param {Phaser.Physics.Box2D.Body} body - The body to be rendered. + * @param {string} [color='rgb(0,255,0)'] - Color of the rendering (format is css color string). + */ box2dBody: function (body, color) { - this.start(); Phaser.Physics.Box2D.renderBody(this.context, body, color); this.stop(); - }, /** - * Call this function from the Dev Tools console. - * - * It will scan the display list and output all of the Objects it finds, and their renderOrderIDs. - * - * **Note** Requires a browser that supports console.group and console.groupEnd (such as Chrome) - * - * @method Phaser.Utils.Debug#displayList - * @param {Object} [displayObject] - The displayObject level display object to start from. Defaults to the World. - */ + * Call this function from the Dev Tools console. + * + * It will scan the display list and output all of the Objects it finds, and their renderOrderIDs. + * + * **Note** Requires a browser that supports console.group and console.groupEnd (such as Chrome) + * + * @method Phaser.Utils.Debug#displayList + * @param {Object} [displayObject] - The displayObject level display object to start from. Defaults to the World. + */ displayList: function (displayObject) { - if (displayObject === undefined) { displayObject = this.game.world; } if (displayObject.hasOwnProperty('renderOrderID')) @@ -1250,7 +1181,6 @@ Phaser.Utils.Debug.prototype = { this.game.debug.displayList(displayObject.children[i]); } } - }, /** @@ -1263,7 +1193,6 @@ Phaser.Utils.Debug.prototype = { */ renderer: function (x, y, color) { - var r = this.game.renderer; var s = r.renderSession; @@ -1298,7 +1227,6 @@ Phaser.Utils.Debug.prototype = { } this.stop(); - }, canvasPool: function (x, y, color, columnWidth) @@ -1314,19 +1242,17 @@ Phaser.Utils.Debug.prototype = { }, /** - * Render each physics {@link #body} in a group. - * - * @method Phaser.Utils.Debug#physicsGroup - * @param {Phaser.Group} group - A group containing physics-enabled sprites. - * @param {string} [color='rgba(0,255,0,0.4)'] - Color of the debug rectangle to be rendered. The format is a CSS color string such as '#ff0000' or 'rgba(255,0,0,0.5)'. - * @param {boolean} [filled=true] - Render the body as a filled rectangle (true) or a stroked rectangle (false). - * @param {boolean} [checkExists=false] Render only children with `exists=true`. - */ + * Render each physics {@link #body} in a group. + * + * @method Phaser.Utils.Debug#physicsGroup + * @param {Phaser.Group} group - A group containing physics-enabled sprites. + * @param {string} [color='rgba(0,255,0,0.4)'] - Color of the debug rectangle to be rendered. The format is a CSS color string such as '#ff0000' or 'rgba(255,0,0,0.5)'. + * @param {boolean} [filled=true] - Render the body as a filled rectangle (true) or a stroked rectangle (false). + * @param {boolean} [checkExists=false] Render only children with `exists=true`. + */ physicsGroup: function (group, color, filled, checkExists) { - group.forEach(this.body, this, checkExists, color, filled); - }, /** @@ -1339,25 +1265,22 @@ Phaser.Utils.Debug.prototype = { */ phaser: function (x, y, color) { - this.text('Phaser v' + Phaser.VERSION + ' ' + (this.game.renderType === Phaser.WEBGL ? 'WebGL' : 'Canvas') + ' ' + (this.game.device.webAudio ? 'WebAudio' : 'HTML Audio'), x, y, color, this.font); - }, /** - * Prints game/canvas dimensions and {@link Phaser.ScaleManager game scale} settings. - * - * @method Phaser.Utils.Debug#scale - * @param {number} x - The X value the debug info will start from. - * @param {number} y - The Y value the debug info will start from. - * @param {string} [color='rgb(255,255,255)'] - The color the debug text will drawn in. - */ + * Prints game/canvas dimensions and {@link Phaser.ScaleManager game scale} settings. + * + * @method Phaser.Utils.Debug#scale + * @param {number} x - The X value the debug info will start from. + * @param {number} y - The Y value the debug info will start from. + * @param {string} [color='rgb(255,255,255)'] - The color the debug text will drawn in. + */ scale: function (x, y, color) { - this.start(x, y, color); var scale = this.game.scale; @@ -1379,26 +1302,24 @@ Phaser.Utils.Debug.prototype = { (scale.incorrectOrientation ? ' (incorrect)' : '')); this.stop(); - }, /** - * Prints the progress of a {@link Phaser.Loader}. - * - * Typically you would call this within a {@link State#loadRender} callback and pass `game.load` ({@link Phaser.Game#load}). - * - * You can enable {@link Phaser.Loader#resetLocked} to temporarily hold the loader in its 'complete' state. - * Just remember to disable it before restarting the loader (such as when changing states). - * - * @method Phaser.Utils.Debug#loader - * @param {Phaser.Loader} loader - The loader. Usually `game.load` ({@link Phaser.Game#load}). - * @param {number} x - The X value the debug info will start from. - * @param {number} y - The Y value the debug info will start from. - * @param {string} [color='rgb(255,255,255)'] - The color the debug text will drawn in. - */ + * Prints the progress of a {@link Phaser.Loader}. + * + * Typically you would call this within a {@link State#loadRender} callback and pass `game.load` ({@link Phaser.Game#load}). + * + * You can enable {@link Phaser.Loader#resetLocked} to temporarily hold the loader in its 'complete' state. + * Just remember to disable it before restarting the loader (such as when changing states). + * + * @method Phaser.Utils.Debug#loader + * @param {Phaser.Loader} loader - The loader. Usually `game.load` ({@link Phaser.Game#load}). + * @param {number} x - The X value the debug info will start from. + * @param {number} y - The Y value the debug info will start from. + * @param {string} [color='rgb(255,255,255)'] - The color the debug text will drawn in. + */ loader: function (loader, x, y, color) { - var pad = Phaser.Utils.pad; this.start(x, y, color); @@ -1426,17 +1347,16 @@ Phaser.Utils.Debug.prototype = { } this.stop(); - }, /** - * Shows device capabilities: Pointer Events, Touch Events, Web Audio, WebGL. - * - * @method Phaser.Utils.Debug#device - * @param {number} x - * @param {number} y - * @param {string} [color] - */ + * Shows device capabilities: Pointer Events, Touch Events, Web Audio, WebGL. + * + * @method Phaser.Utils.Debug#device + * @param {number} x + * @param {number} y + * @param {string} [color] + */ device: function (x, y, color) { var device = this.game.device; @@ -1450,19 +1370,16 @@ Phaser.Utils.Debug.prototype = { this.line('WebGL: ' + device.webGL); this.stop(); - }, /** - * Destroy this object. - * - * @method Phaser.Utils.Debug#destroy - */ + * Destroy this object. + * + * @method Phaser.Utils.Debug#destroy + */ destroy: function () { - Phaser.CanvasPool.remove(this); - } }; diff --git a/src/utils/Device.js b/src/utils/Device.js index 15ab56ad8..388faf17c 100644 --- a/src/utils/Device.js +++ b/src/utils/Device.js @@ -1,597 +1,596 @@ /* eslint-env browser, node */ /** -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* @classdesc -* Detects device support capabilities and is responsible for device initialization - see {@link Phaser.Device.whenReady whenReady}. -* -* This class represents a singleton object that can be accessed directly as `game.device` -* (or, as a fallback, `Phaser.Device` when a game instance is not available) without the need to instantiate it. -* -* Unless otherwise noted the device capabilities are only guaranteed after initialization. Initialization -* occurs automatically and is guaranteed complete before {@link Phaser.Game} begins its "boot" phase. -* Feature detection can be modified in the {@link Phaser.Device.onInitialized onInitialized} signal, e.g., -* -* ```javascript -* Phaser.Device.onInitialized.add(function (device) { -* -* device.canvasBitBltShift = true; -* device.mspointer = false; -* -* }); -* -* var game = new Phaser.Game(); -* ``` -* -* When checking features using the exposed properties only the *truth-iness* of the value should be relied upon -* unless the documentation states otherwise: properties may return `false`, `''`, `null`, or even `undefined` -* when indicating the lack of a feature. -* -* Uses elements from System.js by MrDoob and Modernizr -* -* @description -* It is not possible to instantiate the Device class manually. -* -* @class -* @protected -*/ + * @classdesc + * Detects device support capabilities and is responsible for device initialization - see {@link Phaser.Device.whenReady whenReady}. + * + * This class represents a singleton object that can be accessed directly as `game.device` + * (or, as a fallback, `Phaser.Device` when a game instance is not available) without the need to instantiate it. + * + * Unless otherwise noted the device capabilities are only guaranteed after initialization. Initialization + * occurs automatically and is guaranteed complete before {@link Phaser.Game} begins its "boot" phase. + * Feature detection can be modified in the {@link Phaser.Device.onInitialized onInitialized} signal, e.g., + * + * ```javascript + * Phaser.Device.onInitialized.add(function (device) { + * + * device.canvasBitBltShift = true; + * device.mspointer = false; + * + * }); + * + * var game = new Phaser.Game(); + * ``` + * + * When checking features using the exposed properties only the *truth-iness* of the value should be relied upon + * unless the documentation states otherwise: properties may return `false`, `''`, `null`, or even `undefined` + * when indicating the lack of a feature. + * + * Uses elements from System.js by MrDoob and Modernizr + * + * @description + * It is not possible to instantiate the Device class manually. + * + * @class + * @protected + */ Phaser.Device = function () { - /** - * The time the device became ready. - * @property {integer} deviceReadyAt - * @protected - */ + * The time the device became ready. + * @property {integer} deviceReadyAt + * @protected + */ this.deviceReadyAt = 0; /** - * The time as which initialization has completed. - * @property {boolean} initialized - * @protected - */ + * The time as which initialization has completed. + * @property {boolean} initialized + * @protected + */ this.initialized = false; // Browser / Host / Operating System /** - * @property {boolean} desktop - Is running on a desktop? - * @default - */ + * @property {boolean} desktop - Is running on a desktop? + * @default + */ this.desktop = false; /** - * @property {boolean} iOS - Is running on iOS? - * @default - */ + * @property {boolean} iOS - Is running on iOS? + * @default + */ this.iOS = false; /** - * @property {number} iOSVersion - If running in iOS this will contain the major version number. - * @default - */ + * @property {number} iOSVersion - If running in iOS this will contain the major version number. + * @default + */ this.iOSVersion = 0; /** - * @property {boolean} cocoonJS - Is the game running under CocoonJS? - * @default - */ + * @property {boolean} cocoonJS - Is the game running under CocoonJS? + * @default + */ this.cocoonJS = false; /** - * @property {boolean} cocoonJSApp - Is this game running with CocoonJS.App? - * @default - */ + * @property {boolean} cocoonJSApp - Is this game running with CocoonJS.App? + * @default + */ this.cocoonJSApp = false; /** - * @property {boolean} cordova - Is the game running under Apache Cordova? - * @default - */ + * @property {boolean} cordova - Is the game running under Apache Cordova? + * @default + */ this.cordova = false; /** - * @property {boolean} node - Is the game running under Node.js? - * @default - */ + * @property {boolean} node - Is the game running under Node.js? + * @default + */ this.node = false; /** - * @property {boolean} nodeWebkit - Is the game running under Node-Webkit? - * @default - */ + * @property {boolean} nodeWebkit - Is the game running under Node-Webkit? + * @default + */ this.nodeWebkit = false; /** - * @property {boolean} electron - Is the game running under GitHub Electron? - * @default - */ + * @property {boolean} electron - Is the game running under GitHub Electron? + * @default + */ this.electron = false; /** - * @property {boolean} ejecta - Is the game running under Ejecta? - * @default - */ + * @property {boolean} ejecta - Is the game running under Ejecta? + * @default + */ this.ejecta = false; /** - * @property {boolean} crosswalk - Is the game running under the Intel Crosswalk XDK? - * @default - */ + * @property {boolean} crosswalk - Is the game running under the Intel Crosswalk XDK? + * @default + */ this.crosswalk = false; /** - * @property {boolean} android - Is running on android? - * @default - */ + * @property {boolean} android - Is running on android? + * @default + */ this.android = false; /** - * @property {boolean} chromeOS - Is running on chromeOS? - * @default - */ + * @property {boolean} chromeOS - Is running on chromeOS? + * @default + */ this.chromeOS = false; /** - * @property {boolean} linux - Is running on linux? - * @default - */ + * @property {boolean} linux - Is running on linux? + * @default + */ this.linux = false; /** - * @property {boolean} macOS - Is running on macOS? - * @default - */ + * @property {boolean} macOS - Is running on macOS? + * @default + */ this.macOS = false; /** - * @property {boolean} windows - Is running on windows? - * @default - */ + * @property {boolean} windows - Is running on windows? + * @default + */ this.windows = false; /** - * @property {boolean} windowsPhone - Is running on a Windows Phone? - * @default - */ + * @property {boolean} windowsPhone - Is running on a Windows Phone? + * @default + */ this.windowsPhone = false; // Features /** - * @property {boolean} canvas - Is canvas available? - * @default - */ + * @property {boolean} canvas - Is canvas available? + * @default + */ this.canvas = false; /** - * @property {?boolean} canvasBitBltShift - True if canvas supports a 'copy' bitblt onto itself when the source and destination regions overlap. - * @default - */ + * @property {?boolean} canvasBitBltShift - True if canvas supports a 'copy' bitblt onto itself when the source and destination regions overlap. + * @default + */ this.canvasBitBltShift = null; /** - * If the browser isn't capable of handling tinting with alpha this will be false. - * @property {boolean} canHandleAlpha - * @default - */ + * If the browser isn't capable of handling tinting with alpha this will be false. + * @property {boolean} canHandleAlpha + * @default + */ this.canHandleAlpha = false; /** - * Whether or not the {@link http://caniuse.com/#feat=canvas-blending Canvas Blend Modes} are supported, consequently the ability to tint using the multiply method. - * - * Expect `false` in Internet Explorer <= 11. - * - * @property {boolean} canUseMultiply - * @default - */ + * Whether or not the {@link http://caniuse.com/#feat=canvas-blending Canvas Blend Modes} are supported, consequently the ability to tint using the multiply method. + * + * Expect `false` in Internet Explorer <= 11. + * + * @property {boolean} canUseMultiply + * @default + */ this.canUseMultiply = false; /** - * @property {boolean} webGL - Is webGL available? - * @see Phaser.Game#renderType - * @default - */ + * @property {boolean} webGL - Is webGL available? + * @see Phaser.Game#renderType + * @default + */ this.webGL = false; /** - * @property {boolean} file - Is file available? - * @default - */ + * @property {boolean} file - Is file available? + * @default + */ this.file = false; /** - * @property {boolean} fileSystem - Is fileSystem available? - * @default - */ + * @property {boolean} fileSystem - Is fileSystem available? + * @default + */ this.fileSystem = false; /** - * @property {boolean} localStorage - Is localStorage available? - * @default - */ + * @property {boolean} localStorage - Is localStorage available? + * @default + */ this.localStorage = false; /** - * @property {boolean} worker - Is worker available? - * @default - */ + * @property {boolean} worker - Is worker available? + * @default + */ this.worker = false; /** - * @property {boolean} css3D - Is css3D available? - * @default - */ + * @property {boolean} css3D - Is css3D available? + * @default + */ this.css3D = false; /** - * @property {boolean} pointerLock - Is Pointer Lock available? - * @default - */ + * @property {boolean} pointerLock - Is Pointer Lock available? + * @default + */ this.pointerLock = false; /** - * @property {boolean} typedArray - Does the browser support TypedArrays? - * @default - */ + * @property {boolean} typedArray - Does the browser support TypedArrays? + * @default + */ this.typedArray = false; /** - * @property {boolean} vibration - Does the device support the Vibration API? - * @default - */ + * @property {boolean} vibration - Does the device support the Vibration API? + * @default + */ this.vibration = false; /** - * @property {boolean} getUserMedia - Does the device support the getUserMedia API? - * @default - */ + * @property {boolean} getUserMedia - Does the device support the getUserMedia API? + * @default + */ this.getUserMedia = true; /** - * @property {boolean} quirksMode - Is the browser running in strict mode (false) or quirks mode? (true) - * @default - */ + * @property {boolean} quirksMode - Is the browser running in strict mode (false) or quirks mode? (true) + * @default + */ this.quirksMode = false; // Input /** - * @property {boolean} touch - Is touch available? - * @default - */ + * @property {boolean} touch - Is touch available? + * @default + */ this.touch = false; /** - * @property {boolean} mspointer - Is mspointer available? - * @default - */ + * @property {boolean} mspointer - Is mspointer available? + * @default + */ this.mspointer = false; /** - * @property {?string} wheelType - The newest type of Wheel/Scroll event supported: 'wheel', 'mousewheel', 'DOMMouseScroll' - * @default - * @protected - */ + * @property {?string} wheelType - The newest type of Wheel/Scroll event supported: 'wheel', 'mousewheel', 'DOMMouseScroll' + * @default + * @protected + */ this.wheelEvent = null; // Browser /** - * @property {boolean} arora - Set to true if running in Arora. - * @default - */ + * @property {boolean} arora - Set to true if running in Arora. + * @default + */ this.arora = false; /** - * @property {boolean} chrome - Set to true if running in Chrome. - * @default - */ + * @property {boolean} chrome - Set to true if running in Chrome. + * @default + */ this.chrome = false; /** - * @property {number} chromeVersion - If running in Chrome this will contain the major version number. - * @default - */ + * @property {number} chromeVersion - If running in Chrome this will contain the major version number. + * @default + */ this.chromeVersion = 0; /** - * @property {boolean} epiphany - Set to true if running in Epiphany. - * @default - */ + * @property {boolean} epiphany - Set to true if running in Epiphany. + * @default + */ this.epiphany = false; /** - * @property {boolean} firefox - Set to true if running in Firefox. - * @default - */ + * @property {boolean} firefox - Set to true if running in Firefox. + * @default + */ this.firefox = false; /** - * @property {number} firefoxVersion - If running in Firefox this will contain the major version number. - * @default - */ + * @property {number} firefoxVersion - If running in Firefox this will contain the major version number. + * @default + */ this.firefoxVersion = 0; /** - * @property {boolean} ie - Set to true if running in Internet Explorer. - * @default - */ + * @property {boolean} ie - Set to true if running in Internet Explorer. + * @default + */ this.ie = false; /** - * @property {number} ieVersion - If running in Internet Explorer this will contain the major version number. Beyond IE10 you should use Device.trident and Device.tridentVersion. - * @default - */ + * @property {number} ieVersion - If running in Internet Explorer this will contain the major version number. Beyond IE10 you should use Device.trident and Device.tridentVersion. + * @default + */ this.ieVersion = 0; /** - * @property {boolean} trident - Set to true if running a Trident version of Internet Explorer (IE11+) - * @default - */ + * @property {boolean} trident - Set to true if running a Trident version of Internet Explorer (IE11+) + * @default + */ this.trident = false; /** - * @property {number} tridentVersion - If running in Internet Explorer 11 this will contain the major version number. See {@link http://msdn.microsoft.com/en-us/library/ie/ms537503(v=vs.85).aspx} - * @default - */ + * @property {number} tridentVersion - If running in Internet Explorer 11 this will contain the major version number. See {@link http://msdn.microsoft.com/en-us/library/ie/ms537503(v=vs.85).aspx} + * @default + */ this.tridentVersion = 0; /** - * @property {boolean} edge - Set to true if running in Microsoft Edge browser. - * @default - */ + * @property {boolean} edge - Set to true if running in Microsoft Edge browser. + * @default + */ this.edge = false; /** - * @property {boolean} mobileSafari - Set to true if running in Mobile Safari. - * @default - */ + * @property {boolean} mobileSafari - Set to true if running in Mobile Safari. + * @default + */ this.mobileSafari = false; /** - * @property {boolean} midori - Set to true if running in Midori. - * @default - */ + * @property {boolean} midori - Set to true if running in Midori. + * @default + */ this.midori = false; /** - * @property {boolean} opera - Set to true if running in Opera. - * @default - */ + * @property {boolean} opera - Set to true if running in Opera. + * @default + */ this.opera = false; /** - * @property {boolean} safari - Set to true if running in Safari. - * @default - */ + * @property {boolean} safari - Set to true if running in Safari. + * @default + */ this.safari = false; /** - * @property {number} safariVersion - If running in Safari this will contain the major version number. - * @default - */ + * @property {number} safariVersion - If running in Safari this will contain the major version number. + * @default + */ this.safariVersion = 0; /** - * @property {boolean} webApp - Set to true if running as a WebApp, i.e. within a WebView - * @default - */ + * @property {boolean} webApp - Set to true if running as a WebApp, i.e. within a WebView + * @default + */ this.webApp = false; /** - * @property {boolean} silk - Set to true if running in the Silk browser (as used on the Amazon Kindle) - * @default - */ + * @property {boolean} silk - Set to true if running in the Silk browser (as used on the Amazon Kindle) + * @default + */ this.silk = false; // Audio /** - * @property {boolean} audioData - Are Audio tags available? - * @default - */ + * @property {boolean} audioData - Are Audio tags available? + * @default + */ this.audioData = false; /** - * @property {boolean} webAudio - Is the WebAudio API available? - * @default - * @see http://mohayonao.github.io/web-audio-test-api/ - */ + * @property {boolean} webAudio - Is the WebAudio API available? + * @default + * @see http://mohayonao.github.io/web-audio-test-api/ + */ this.webAudio = false; /** - * @property {boolean} ogg - Can this device play ogg files? - * @default - */ + * @property {boolean} ogg - Can this device play ogg files? + * @default + */ this.ogg = false; /** - * @property {boolean} opus - Can this device play opus files? - * @default - */ + * @property {boolean} opus - Can this device play opus files? + * @default + */ this.opus = false; /** - * @property {boolean} mp3 - Can this device play mp3 files? - * @default - */ + * @property {boolean} mp3 - Can this device play mp3 files? + * @default + */ this.mp3 = false; /** - * @property {boolean} wav - Can this device play wav files? - * @default - */ + * @property {boolean} wav - Can this device play wav files? + * @default + */ this.wav = false; /** - * Can this device play m4a files? - * @property {boolean} m4a - True if this device can play m4a files. - * @default - */ + * Can this device play m4a files? + * @property {boolean} m4a - True if this device can play m4a files. + * @default + */ this.m4a = false; /** - * @property {boolean} webm - Can this device play webm files? - * @default - */ + * @property {boolean} webm - Can this device play webm files? + * @default + */ this.webm = false; /** - * @property {boolean} dolby - Can this device play EC-3 Dolby Digital Plus files? - * @default - */ + * @property {boolean} dolby - Can this device play EC-3 Dolby Digital Plus files? + * @default + */ this.dolby = false; // Video /** - * @property {boolean} oggVideo - Can this device play ogg video files? - * @default - */ + * @property {boolean} oggVideo - Can this device play ogg video files? + * @default + */ this.oggVideo = false; /** - * @property {boolean} h264Video - Can this device play h264 mp4 video files? - * @default - */ + * @property {boolean} h264Video - Can this device play h264 mp4 video files? + * @default + */ this.h264Video = false; /** - * @property {boolean} mp4Video - Can this device play h264 mp4 video files? - * @default - */ + * @property {boolean} mp4Video - Can this device play h264 mp4 video files? + * @default + */ this.mp4Video = false; /** - * @property {boolean} webmVideo - Can this device play webm video files? - * @default - */ + * @property {boolean} webmVideo - Can this device play webm video files? + * @default + */ this.webmVideo = false; /** - * @property {boolean} vp9Video - Can this device play vp9 video files? - * @default - */ + * @property {boolean} vp9Video - Can this device play vp9 video files? + * @default + */ this.vp9Video = false; /** - * @property {boolean} hlsVideo - Can this device play hls video files? - * @default - */ + * @property {boolean} hlsVideo - Can this device play hls video files? + * @default + */ this.hlsVideo = false; // Device /** - * @property {boolean} iPhone - Is running on iPhone? - * @default - */ + * @property {boolean} iPhone - Is running on iPhone? + * @default + */ this.iPhone = false; /** - * @property {boolean} iPhone4 - Is running on iPhone4? - * @default - */ + * @property {boolean} iPhone4 - Is running on iPhone4? + * @default + */ this.iPhone4 = false; /** - * @property {boolean} iPad - Is running on iPad? - * @default - */ + * @property {boolean} iPad - Is running on iPad? + * @default + */ this.iPad = false; // Device features /** - * @property {number} pixelRatio - PixelRatio of the host device? - * @default - */ + * @property {number} pixelRatio - PixelRatio of the host device? + * @default + */ this.pixelRatio = 0; /** - * @property {boolean} littleEndian - Is the device big or little endian? (only detected if the browser supports TypedArrays) - * @default - */ + * @property {boolean} littleEndian - Is the device big or little endian? (only detected if the browser supports TypedArrays) + * @default + */ this.littleEndian = false; /** - * @property {boolean} LITTLE_ENDIAN - Same value as `littleEndian`. - * @default - */ + * @property {boolean} LITTLE_ENDIAN - Same value as `littleEndian`. + * @default + */ this.LITTLE_ENDIAN = false; /** - * @property {boolean} support32bit - Does the device context support 32bit pixel manipulation using array buffer views? - * @default - */ + * @property {boolean} support32bit - Does the device context support 32bit pixel manipulation using array buffer views? + * @default + */ this.support32bit = false; /** - * @property {boolean} fullscreen - Does the browser support the Full Screen API? - * @default - */ + * @property {boolean} fullscreen - Does the browser support the Full Screen API? + * @default + */ this.fullscreen = false; /** - * @property {string} requestFullscreen - If the browser supports the Full Screen API this holds the call you need to use to activate it. - * @default - */ + * @property {string} requestFullscreen - If the browser supports the Full Screen API this holds the call you need to use to activate it. + * @default + */ this.requestFullscreen = ''; /** - * @property {string} cancelFullscreen - If the browser supports the Full Screen API this holds the call you need to use to cancel it. - * @default - */ + * @property {string} cancelFullscreen - If the browser supports the Full Screen API this holds the call you need to use to cancel it. + * @default + */ this.cancelFullscreen = ''; /** - * @property {boolean} fullscreenKeyboard - Does the browser support access to the Keyboard during Full Screen mode? - * @default - */ + * @property {boolean} fullscreenKeyboard - Does the browser support access to the Keyboard during Full Screen mode? + * @default + */ this.fullscreenKeyboard = false; - }; -// Device is really a singleton/static entity; instantiate it -// and add new methods directly sans-prototype. +/* + * Device is really a singleton/static entity; instantiate it + * and add new methods directly sans-prototype. + */ Phaser.Device = new Phaser.Device(); /** -* This signal is dispatched after device initialization occurs but before any of the ready -* callbacks (see {@link Phaser.Device.whenReady whenReady}) have been invoked. -* -* Local "patching" for a particular device can/should be done in this event. -* -* _Note_: This signal is removed after the device has been readied; if a handler has not been -* added _before_ `new Phaser.Game(..)` it is probably too late. -* -* @type {?Phaser.Signal} -* @static -*/ + * This signal is dispatched after device initialization occurs but before any of the ready + * callbacks (see {@link Phaser.Device.whenReady whenReady}) have been invoked. + * + * Local "patching" for a particular device can/should be done in this event. + * + * _Note_: This signal is removed after the device has been readied; if a handler has not been + * added _before_ `new Phaser.Game(..)` it is probably too late. + * + * @type {?Phaser.Signal} + * @static + */ Phaser.Device.onInitialized = new Phaser.Signal(); /** -* Add a device-ready handler and ensure the device ready sequence is started. -* -* Phaser.Device will _not_ activate or initialize until at least one `whenReady` handler is added, -* which is normally done automatically be calling `new Phaser.Game(..)`. -* -* The handler is invoked when the device is considered "ready", which may be immediately -* if the device is already "ready". See {@link Phaser.Device#deviceReadyAt deviceReadyAt}. -* -* @method -* @param {function} handler - Callback to invoke when the device is ready. It is invoked with the given context the Phaser.Device object is supplied as the first argument. -* @param {object} [context] - Context in which to invoke the handler -* @param {boolean} [nonPrimer=false] - If true the device ready check will not be started. -*/ + * Add a device-ready handler and ensure the device ready sequence is started. + * + * Phaser.Device will _not_ activate or initialize until at least one `whenReady` handler is added, + * which is normally done automatically be calling `new Phaser.Game(..)`. + * + * The handler is invoked when the device is considered "ready", which may be immediately + * if the device is already "ready". See {@link Phaser.Device#deviceReadyAt deviceReadyAt}. + * + * @method + * @param {function} handler - Callback to invoke when the device is ready. It is invoked with the given context the Phaser.Device object is supplied as the first argument. + * @param {object} [context] - Context in which to invoke the handler + * @param {boolean} [nonPrimer=false] - If true the device ready check will not be started. + */ Phaser.Device.whenReady = function (callback, context, nonPrimer) { - var readyCheck = this._readyCheck; if (this.deviceReadyAt || !readyCheck) @@ -619,8 +618,10 @@ Phaser.Device.whenReady = function (callback, context, nonPrimer) } else if (cordova && !cocoonJS) { - // Ref. http://docs.phonegap.com/en/3.5.0/cordova_events_events.md.html#deviceready - // Cordova, but NOT Cocoon? + /* + * Ref. http://docs.phonegap.com/en/3.5.0/cordova_events_events.md.html#deviceready + * Cordova, but NOT Cocoon? + */ document.addEventListener('deviceready', readyCheck._monitor, false); } else @@ -629,19 +630,17 @@ Phaser.Device.whenReady = function (callback, context, nonPrimer) window.addEventListener('load', readyCheck._monitor, false); } } - }; /** -* Internal method used for checking when the device is ready. -* This function is removed from Phaser.Device when the device becomes ready. -* -* @method -* @private -*/ + * Internal method used for checking when the device is ready. + * This function is removed from Phaser.Device when the device becomes ready. + * + * @method + * @private + */ Phaser.Device._readyCheck = function () { - var readyCheck = this._readyCheck; if (!document.body) @@ -674,27 +673,24 @@ Phaser.Device._readyCheck = function () this._initialize = null; this.onInitialized = null; } - }; /** -* Internal method to initialize the capability checks. -* This function is removed from Phaser.Device once the device is initialized. -* -* @method -* @private -*/ + * Internal method to initialize the capability checks. + * This function is removed from Phaser.Device once the device is initialized. + * + * @method + * @private + */ Phaser.Device._initialize = function () { - var device = this; /** - * Check which OS is game running on. - */ + * Check which OS is game running on. + */ function _checkOS () { - var ua = navigator.userAgent; if ((/Playstation Vita/).test(ua)) @@ -705,8 +701,10 @@ Phaser.Device._initialize = function () { device.kindle = true; - // This will NOT detect early generations of Kindle Fire, I think there is no reliable way... - // E.g. "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_3; en-us; Silk/1.1.0-80) AppleWebKit/533.16 (KHTML, like Gecko) Version/5.0 Safari/533.16 Silk-Accelerated=true" + /* + * This will NOT detect early generations of Kindle Fire, I think there is no reliable way... + * E.g. "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_3; en-us; Silk/1.1.0-80) AppleWebKit/533.16 (KHTML, like Gecko) Version/5.0 Safari/533.16 Silk-Accelerated=true" + */ } else if ((/Android/).test(ua)) { @@ -756,17 +754,15 @@ Phaser.Device._initialize = function () { device.desktop = false; } - } /** - * Checks if the browser correctly supports putImageData alpha channels. - * If the browser isn't capable of handling tinting with alpha, `Device.canHandleAlpha` will be false. - * Also checks whether the Canvas BlendModes are supported by the current browser for drawImage. - */ + * Checks if the browser correctly supports putImageData alpha channels. + * If the browser isn't capable of handling tinting with alpha, `Device.canHandleAlpha` will be false. + * Also checks whether the Canvas BlendModes are supported by the current browser for drawImage. + */ function _checkCanvasFeatures () { - var canvas = Phaser.CanvasPool.create(this, 6, 1); var context = canvas.getContext('2d'); @@ -802,15 +798,13 @@ Phaser.Device._initialize = function () Phaser.CanvasPool.removeByCanvas(canvas); PIXI.CanvasTinter.tintMethod = (device.canUseMultiply) ? PIXI.CanvasTinter.tintWithMultiply : PIXI.CanvasTinter.tintWithPerPixel; - } /** - * Check HTML5 features of the host environment. - */ + * Check HTML5 features of the host environment. + */ function _checkFeatures () { - device.canvas = !!window.CanvasRenderingContext2D || device.cocoonJS; try @@ -859,8 +853,10 @@ Phaser.Device._initialize = function () // TODO: replace canvasBitBltShift detection with actual feature check - // Excludes iOS versions as they generally wrap UIWebView (eg. Safari WebKit) and it - // is safer to not try and use the fast copy-over method. + /* + * Excludes iOS versions as they generally wrap UIWebView (eg. Safari WebKit) and it + * is safer to not try and use the fast copy-over method. + */ if (!device.iOS && (device.ie || device.firefox || device.chrome)) { device.canvasBitBltShift = true; @@ -871,15 +867,13 @@ Phaser.Device._initialize = function () { device.canvasBitBltShift = false; } - } /** - * Checks/configures various input. - */ + * Checks/configures various input. + */ function _checkInput () { - if ('ontouchstart' in document.documentElement || (window.navigator.maxTouchPoints && window.navigator.maxTouchPoints >= 1)) { device.touch = true; @@ -909,15 +903,13 @@ Phaser.Device._initialize = function () device.wheelEvent = 'DOMMouseScroll'; } } - } /** - * Checks for support of the Full Screen API. - */ + * Checks for support of the Full Screen API. + */ function _checkFullScreenSupport () { - var fs = [ 'requestFullscreen', 'requestFullScreen', @@ -969,15 +961,13 @@ Phaser.Device._initialize = function () { device.fullscreenKeyboard = true; } - } /** - * Check what browser is game running in. - */ + * Check what browser is game running in. + */ function _checkBrowser () { - var ua = navigator.userAgent; if ((/Arora/).test(ua)) @@ -1091,15 +1081,13 @@ Phaser.Device._initialize = function () { device.crosswalk = true; } - } /** - * Check video support. - */ + * Check video support. + */ function _checkVideo () { - var videoElement = document.createElement('video'); try @@ -1138,11 +1126,10 @@ Phaser.Device._initialize = function () } /** - * Check audio support. - */ + * Check audio support. + */ function _checkAudio () { - device.audioData = !!(window.Audio); device.webAudio = !!(window.AudioContext || window.webkitAudioContext); var audioElement = document.createElement('audio'); @@ -1166,9 +1153,11 @@ Phaser.Device._initialize = function () device.mp3 = true; } - // Mimetypes accepted: - // developer.mozilla.org/En/Media_formats_supported_by_the_audio_and_video_elements - // bit.ly/iphoneoscodecs + /* + * Mimetypes accepted: + * developer.mozilla.org/En/Media_formats_supported_by_the_audio_and_video_elements + * bit.ly/iphoneoscodecs + */ if (audioElement.canPlayType('audio/wav; codecs="1"').replace(/^no$/, '')) { device.wav = true; @@ -1208,17 +1197,15 @@ Phaser.Device._initialize = function () } catch (e) {} // eslint-disable-line no-empty - } /** - * Check Little or Big Endian system. - * - * @author Matt DesLauriers (@mattdesl) - */ + * Check Little or Big Endian system. + * + * @author Matt DesLauriers (@mattdesl) + */ function _checkIsLittleEndian () { - var a = new ArrayBuffer(4); var b = new Uint8Array(a); var c = new Uint32Array(a); @@ -1242,17 +1229,15 @@ Phaser.Device._initialize = function () // Could not determine endianness return null; } - } /** - * Test to see if ImageData uses CanvasPixelArray or Uint8ClampedArray. - * - * @author Matt DesLauriers (@mattdesl) - */ + * Test to see if ImageData uses CanvasPixelArray or Uint8ClampedArray. + * + * @author Matt DesLauriers (@mattdesl) + */ function _checkIsUint8ClampedImageData () { - if (Uint8ClampedArray === undefined) { return false; @@ -1271,15 +1256,13 @@ Phaser.Device._initialize = function () Phaser.CanvasPool.remove(this); return image.data instanceof Uint8ClampedArray; - } /** - * Check PixelRatio, iOS device, Vibration API, ArrayBuffers and endianess. - */ + * Check PixelRatio, iOS device, Vibration API, ArrayBuffers and endianess. + */ function _checkDevice () { - device.pixelRatio = window.devicePixelRatio || 1; device.iPhone = navigator.userAgent.toLowerCase().indexOf('iphone') !== -1; device.iPhone4 = (device.pixelRatio === 2 && device.iPhone); @@ -1308,15 +1291,13 @@ Phaser.Device._initialize = function () { device.vibration = true; } - } /** - * Check whether the host environment support 3D CSS. - */ + * Check whether the host environment support 3D CSS. + */ function _checkCSS3D () { - var el = document.createElement('p'); var has3d; var transforms = { @@ -1341,7 +1322,6 @@ Phaser.Device._initialize = function () document.body.removeChild(el); device.css3D = (has3d !== undefined && has3d.length > 0 && has3d !== 'none'); - } // Run the checks @@ -1355,20 +1335,18 @@ Phaser.Device._initialize = function () _checkCanvasFeatures(); _checkFullScreenSupport(); _checkInput(); - }; /** -* Check whether the host environment can play audio. -* -* @method canPlayAudio -* @memberof Phaser.Device.prototype -* @param {string} type - One of 'mp3, 'ogg', 'm4a', 'wav', 'webm' or 'opus'. -* @return {boolean} True if the given file type is supported by the browser, otherwise false. -*/ + * Check whether the host environment can play audio. + * + * @method canPlayAudio + * @memberof Phaser.Device.prototype + * @param {string} type - One of 'mp3, 'ogg', 'm4a', 'wav', 'webm' or 'opus'. + * @return {boolean} True if the given file type is supported by the browser, otherwise false. + */ Phaser.Device.canPlayAudio = function (type) { - if (type === 'mp3' && this.mp3) { return true; @@ -1399,20 +1377,18 @@ Phaser.Device.canPlayAudio = function (type) } return false; - }; /** -* Check whether the host environment can play video files. -* -* @method canPlayVideo -* @memberof Phaser.Device.prototype -* @param {string} type - One of 'mp4, 'ogg', 'webm' or 'mpeg'. -* @return {boolean} True if the given file type is supported by the browser, otherwise false. -*/ + * Check whether the host environment can play video files. + * + * @method canPlayVideo + * @memberof Phaser.Device.prototype + * @param {string} type - One of 'mp4, 'ogg', 'webm' or 'mpeg'. + * @return {boolean} True if the given file type is supported by the browser, otherwise false. + */ Phaser.Device.canPlayVideo = function (type) { - if (type === 'webm' && (this.webmVideo || this.vp9Video)) { return true; @@ -1431,7 +1407,6 @@ Phaser.Device.canPlayVideo = function (type) } return false; - }; /** @@ -1447,21 +1422,19 @@ Phaser.Device.needsTouchUnlock = function () }; /** -* Detect if the host is a an Android Stock browser. -* This is available before the device "ready" event. -* -* Authors might want to scale down on effects and switch to the CANVAS rendering method on those devices. -* -* @example -* var defaultRenderingMode = Phaser.Device.isAndroidStockBrowser() ? Phaser.CANVAS : Phaser.AUTO; -* -* @method isAndroidStockBrowser -* @memberof Phaser.Device.prototype -*/ + * Detect if the host is a an Android Stock browser. + * This is available before the device "ready" event. + * + * Authors might want to scale down on effects and switch to the CANVAS rendering method on those devices. + * + * @example + * var defaultRenderingMode = Phaser.Device.isAndroidStockBrowser() ? Phaser.CANVAS : Phaser.AUTO; + * + * @method isAndroidStockBrowser + * @memberof Phaser.Device.prototype + */ Phaser.Device.isAndroidStockBrowser = function () { - var matches = window.navigator.userAgent.match(/Android.*AppleWebKit\/([\d.]+)/); return matches && matches[1] < 537; - }; diff --git a/src/utils/EarCut.js b/src/utils/EarCut.js index 46667d54a..95df1ff9c 100644 --- a/src/utils/EarCut.js +++ b/src/utils/EarCut.js @@ -1,29 +1,28 @@ /* jshint ignore:start */ /* -Copyright (c) 2016, Mapbox - -Permission to use, copy, modify, and/or distribute this software for any purpose -with or without fee is hereby granted, provided that the above copyright notice -and this permission notice appear in all copies. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH -REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, -INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS -OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER -TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF -THIS SOFTWARE. -*/ + * Copyright (c) 2016, Mapbox + * + * Permission to use, copy, modify, and/or distribute this software for any purpose + * with or without fee is hereby granted, provided that the above copyright notice + * and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND + * FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS + * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER + * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF + * THIS SOFTWARE. + */ /** -* @class EarCut -*/ + * @class EarCut + */ Phaser.EarCut = {}; Phaser.EarCut.Triangulate = function (data, holeIndices, dim) { - dim = dim || 2; var hasHoles = holeIndices && holeIndices.length, @@ -108,7 +107,6 @@ Phaser.EarCut.filterPoints = function (start, end) p = end = p.prev; if (p === p.next) { return null; } again = true; - } else { @@ -261,7 +259,6 @@ Phaser.EarCut.cureLocalIntersections = function (start, triangles, dim) // a self-intersection where edge (v[i-1],v[i]) intersects (v[i+1],v[i+2]) if (Phaser.EarCut.intersects(a, p, p.next, b) && Phaser.EarCut.locallyInside(a, b) && Phaser.EarCut.locallyInside(b, a)) { - triangles.push(a.i / dim); triangles.push(p.i / dim); triangles.push(b.i / dim); @@ -364,8 +361,10 @@ Phaser.EarCut.findHoleBridge = function (hole, outerNode) qx = -Infinity, m; - // find a segment intersected by a ray from the hole's leftmost point to the left; - // segment's endpoint with lesser x will be potential connection point + /* + * find a segment intersected by a ray from the hole's leftmost point to the left; + * segment's endpoint with lesser x will be potential connection point + */ do { if (hy <= p.y && hy >= p.next.y) @@ -384,9 +383,11 @@ Phaser.EarCut.findHoleBridge = function (hole, outerNode) if (hole.x === m.x) { return m.prev; } // hole touches outer segment; pick lower endpoint - // look for points inside the triangle of hole point, segment intersection and endpoint; - // if there are no points found, we have a valid connection; - // otherwise choose the point of the minimum angle with the ray as connection point + /* + * look for points inside the triangle of hole point, segment intersection and endpoint; + * if there are no points found, we have a valid connection; + * otherwise choose the point of the minimum angle with the ray as connection point + */ var stop = m, tanMin = Infinity, @@ -399,7 +400,6 @@ Phaser.EarCut.findHoleBridge = function (hole, outerNode) if (hx >= p.x && p.x >= m.x && Phaser.EarCut.pointInTriangle(hy < m.y ? hx : qx, hy, m.x, m.y, hy < m.y ? qx : hx, hy, p.x, p.y)) { - tan = Math.abs(hy - p.y) / (hx - p.x); // tangential if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && Phaser.EarCut.locallyInside(p, hole)) @@ -434,8 +434,10 @@ Phaser.EarCut.indexCurve = function (start, minX, minY, size) Phaser.EarCut.sortLinked(p); }; -// Simon Tatham's linked list merge sort algorithm -// http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html +/* + * Simon Tatham's linked list merge sort algorithm + * http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html + */ Phaser.EarCut.sortLinked = function (list) { @@ -465,7 +467,6 @@ Phaser.EarCut.sortLinked = function (list) while (pSize > 0 || (qSize > 0 && q)) { - if (pSize === 0) { e = q; @@ -503,7 +504,6 @@ Phaser.EarCut.sortLinked = function (list) tail.nextZ = null; inSize *= 2; - } while (numMerges > 1); return list; @@ -626,8 +626,10 @@ Phaser.EarCut.middleInside = function (a, b) return inside; }; -// link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two; -// if one belongs to the outer ring and another to a hole, it merges it into a single ring +/* + * link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two; + * if one belongs to the outer ring and another to a hole, it merges it into a single ring + */ Phaser.EarCut.splitPolygon = function (a, b) { @@ -661,7 +663,6 @@ Phaser.EarCut.insertNode = function (i, x, y, last) { p.prev = p; p.next = p; - } else { diff --git a/src/utils/LinkedList.js b/src/utils/LinkedList.js index c10d82df2..f71e24643 100644 --- a/src/utils/LinkedList.js +++ b/src/utils/LinkedList.js @@ -1,72 +1,69 @@ /** -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* A basic Linked List data structure. -* -* This implementation _modifies_ the `prev` and `next` properties of each item added: -* - The `prev` and `next` properties must be writable and should not be used for any other purpose. -* - Items _cannot_ be added to multiple LinkedLists at the same time. -* - Only objects can be added. -* -* @class Phaser.LinkedList -* @constructor -*/ + * A basic Linked List data structure. + * + * This implementation _modifies_ the `prev` and `next` properties of each item added: + * - The `prev` and `next` properties must be writable and should not be used for any other purpose. + * - Items _cannot_ be added to multiple LinkedLists at the same time. + * - Only objects can be added. + * + * @class Phaser.LinkedList + * @constructor + */ Phaser.LinkedList = function () { - /** - * Next element in the list. - * @property {object} next - * @default - */ + * Next element in the list. + * @property {object} next + * @default + */ this.next = null; /** - * Previous element in the list. - * @property {object} prev - * @default - */ + * Previous element in the list. + * @property {object} prev + * @default + */ this.prev = null; /** - * First element in the list. - * @property {object} first - * @default - */ + * First element in the list. + * @property {object} first + * @default + */ this.first = null; /** - * Last element in the list. - * @property {object} last - * @default - */ + * Last element in the list. + * @property {object} last + * @default + */ this.last = null; /** - * Number of elements in the list. - * @property {integer} total - * @default - */ + * Number of elements in the list. + * @property {integer} total + * @default + */ this.total = 0; - }; Phaser.LinkedList.prototype = { /** - * Adds a new element to this linked list. - * - * @method Phaser.LinkedList#add - * @param {object} item - The element to add to this list. Can be a Phaser.Sprite or any other object you need to quickly iterate through. - * @return {object} The item that was added. - */ + * Adds a new element to this linked list. + * + * @method Phaser.LinkedList#add + * @param {object} item - The element to add to this list. Can be a Phaser.Sprite or any other object you need to quickly iterate through. + * @return {object} The item that was added. + */ add: function (item) { - // If the list is empty if (this.total === 0 && this.first === null && this.last === null) { @@ -88,34 +85,30 @@ Phaser.LinkedList.prototype = { this.total++; return item; - }, /** - * Resets the first, last, next and previous node pointers in this list. - * - * @method Phaser.LinkedList#reset - */ + * Resets the first, last, next and previous node pointers in this list. + * + * @method Phaser.LinkedList#reset + */ reset: function () { - this.first = null; this.last = null; this.next = null; this.prev = null; this.total = 0; - }, /** - * Removes the given element from this linked list if it exists. - * - * @method Phaser.LinkedList#remove - * @param {object} item - The item to be removed from the list. - */ + * Removes the given element from this linked list if it exists. + * + * @method Phaser.LinkedList#remove + * @param {object} item - The item to be removed from the list. + */ remove: function (item) { - if (this.total === 1) { this.reset(); @@ -154,19 +147,17 @@ Phaser.LinkedList.prototype = { } this.total--; - }, /** - * Calls a function on all members of this list, using the member as the context for the callback. - * The function must exist on the member. - * - * @method Phaser.LinkedList#callAll - * @param {function} callback - The function to call. - */ + * Calls a function on all members of this list, using the member as the context for the callback. + * The function must exist on the member. + * + * @method Phaser.LinkedList#callAll + * @param {function} callback - The function to call. + */ callAll: function (callback) { - if (!this.first || !this.last) { return; @@ -182,10 +173,8 @@ Phaser.LinkedList.prototype = { } entity = entity.next; - } while (entity !== this.last.next); - } }; diff --git a/src/utils/RequestAnimationFrame.js b/src/utils/RequestAnimationFrame.js index daf49497d..dc0887ab0 100644 --- a/src/utils/RequestAnimationFrame.js +++ b/src/utils/RequestAnimationFrame.js @@ -1,36 +1,35 @@ /** -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* Abstracts away the use of RAF or setTimeOut for the core game update loop. -* -* @class Phaser.RequestAnimationFrame -* @constructor -* @param {Phaser.Game} game - A reference to the currently running game. -* @param {boolean} [forceSetTimeOut=false] - Tell Phaser to use setTimeOut even if raf is available. -*/ + * Abstracts away the use of RAF or setTimeOut for the core game update loop. + * + * @class Phaser.RequestAnimationFrame + * @constructor + * @param {Phaser.Game} game - A reference to the currently running game. + * @param {boolean} [forceSetTimeOut=false] - Tell Phaser to use setTimeOut even if raf is available. + */ Phaser.RequestAnimationFrame = function (game, forceSetTimeOut) { - if (forceSetTimeOut === undefined) { forceSetTimeOut = false; } /** - * @property {Phaser.Game} game - The currently running game. - */ + * @property {Phaser.Game} game - The currently running game. + */ this.game = game; /** - * @property {boolean} isRunning - true if RequestAnimationFrame is running, otherwise false. - * @default - */ + * @property {boolean} isRunning - true if RequestAnimationFrame is running, otherwise false. + * @default + */ this.isRunning = false; /** - * @property {boolean} forceSetTimeOut - Tell Phaser to use setTimeOut even if raf is available. - */ + * @property {boolean} forceSetTimeOut - Tell Phaser to use setTimeOut even if raf is available. + */ this.forceSetTimeOut = forceSetTimeOut; var vendors = [ @@ -47,34 +46,32 @@ Phaser.RequestAnimationFrame = function (game, forceSetTimeOut) } /** - * @property {boolean} _isSetTimeOut - true if the browser is using setTimeout instead of raf. - * @private - */ + * @property {boolean} _isSetTimeOut - true if the browser is using setTimeout instead of raf. + * @private + */ this._isSetTimeOut = false; /** - * @property {function} _onLoop - The function called by the update. - * @private - */ + * @property {function} _onLoop - The function called by the update. + * @private + */ this._onLoop = null; /** - * @property {number} _timeOutID - The callback ID used when calling cancel. - * @private - */ + * @property {number} _timeOutID - The callback ID used when calling cancel. + * @private + */ this._timeOutID = null; - }; Phaser.RequestAnimationFrame.prototype = { /** - * Starts the requestAnimationFrame running or setTimeout if unavailable in browser - * @method Phaser.RequestAnimationFrame#start - */ + * Starts the requestAnimationFrame running or setTimeout if unavailable in browser + * @method Phaser.RequestAnimationFrame#start + */ start: function () { - this.isRunning = true; var _this = this; @@ -101,16 +98,14 @@ Phaser.RequestAnimationFrame.prototype = { this._timeOutID = window.requestAnimationFrame(this._onLoop); } - }, /** - * The update method for the requestAnimationFrame - * @method Phaser.RequestAnimationFrame#updateRAF - */ + * The update method for the requestAnimationFrame + * @method Phaser.RequestAnimationFrame#updateRAF + */ updateRAF: function (rafTime) { - if (this.isRunning) { // floor the rafTime to make it equivalent to the Date.now() provided by updateSetTimeout (just below) @@ -118,32 +113,28 @@ Phaser.RequestAnimationFrame.prototype = { this._timeOutID = window.requestAnimationFrame(this._onLoop); } - }, /** - * The update method for the setTimeout. - * @method Phaser.RequestAnimationFrame#updateSetTimeout - */ + * The update method for the setTimeout. + * @method Phaser.RequestAnimationFrame#updateSetTimeout + */ updateSetTimeout: function () { - if (this.isRunning) { this.game.update(Date.now()); this._timeOutID = window.setTimeout(this._onLoop, this.game.time.timeToCall); } - }, /** - * Stops the requestAnimationFrame from running. - * @method Phaser.RequestAnimationFrame#stop - */ + * Stops the requestAnimationFrame from running. + * @method Phaser.RequestAnimationFrame#stop + */ stop: function () { - if (this._isSetTimeOut) { clearTimeout(this._timeOutID); @@ -154,24 +145,23 @@ Phaser.RequestAnimationFrame.prototype = { } this.isRunning = false; - }, /** - * Is the browser using setTimeout? - * @method Phaser.RequestAnimationFrame#isSetTimeOut - * @return {boolean} - */ + * Is the browser using setTimeout? + * @method Phaser.RequestAnimationFrame#isSetTimeOut + * @return {boolean} + */ isSetTimeOut: function () { return this._isSetTimeOut; }, /** - * Is the browser using requestAnimationFrame? - * @method Phaser.RequestAnimationFrame#isRAF - * @return {boolean} - */ + * Is the browser using requestAnimationFrame? + * @method Phaser.RequestAnimationFrame#isRAF + * @return {boolean} + */ isRAF: function () { return (this._isSetTimeOut === false); diff --git a/src/utils/Utils.js b/src/utils/Utils.js index b79a3605e..121dc73ef 100644 --- a/src/utils/Utils.js +++ b/src/utils/Utils.js @@ -1,13 +1,13 @@ /** -* @author Richard Davey -* @copyright 2016 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ + * @author Richard Davey + * @copyright 2016 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ /** -* @class Phaser.Utils -* @static -*/ + * @class Phaser.Utils + * @static + */ Phaser.Utils = { defaults: function (target, defaults) @@ -28,31 +28,28 @@ Phaser.Utils = { }, /** - * Takes the given string and reverses it, returning the reversed string. - * For example if given the string `Atari 520ST` it would return `TS025 iratA`. - * - * @method Phaser.Utils.reverseString - * @param {string} string - The string to be reversed. - * @return {string} The reversed string. - */ + * Takes the given string and reverses it, returning the reversed string. + * For example if given the string `Atari 520ST` it would return `TS025 iratA`. + * + * @method Phaser.Utils.reverseString + * @param {string} string - The string to be reversed. + * @return {string} The reversed string. + */ reverseString: function (string) { - return string.split('').reverse().join(''); - }, /** - * Gets an object's property by string. - * - * @method Phaser.Utils.getProperty - * @param {object} obj - The object to traverse. - * @param {string} name - The property name, or a series of names separated by `.` (for nested properties). - * @return {any} - The value of the property or `undefined` if the property isn't found. - */ + * Gets an object's property by string. + * + * @method Phaser.Utils.getProperty + * @param {object} obj - The object to traverse. + * @param {string} name - The property name, or a series of names separated by `.` (for nested properties). + * @return {any} - The value of the property or `undefined` if the property isn't found. + */ getProperty: function (obj, name) { - var parts = name.split('.'); switch (parts.length) @@ -68,7 +65,6 @@ Phaser.Utils = { default: return this._getProperty(obj, name); } - }, /** @@ -89,14 +85,12 @@ Phaser.Utils = { */ setProperties: function (obj, props) { - for (var name in props) { this.setProperty(obj, name, props[name]); } return obj; - }, /** @@ -115,7 +109,6 @@ Phaser.Utils = { setProperty: function (obj, name, value) { - var parts = name.split('.'); switch (parts.length) @@ -148,7 +141,6 @@ Phaser.Utils = { */ _getProperty: function (obj, name) { - var parts = name.split('.'), len = parts.length, i = 0, @@ -170,7 +162,6 @@ Phaser.Utils = { } return val; - }, /** @@ -185,7 +176,6 @@ Phaser.Utils = { */ _setProperty: function (obj, name, value) { - var parts = name.split('.'), len = parts.length, i = 0, @@ -209,19 +199,18 @@ Phaser.Utils = { } return obj; - }, /** - * Generate a random bool result based on the chance value. - * - * Returns true or false based on the chance value (default 50%). For example if you wanted a player to have a 30% chance - * of getting a bonus, call chanceRoll(30) - true means the chance passed, false means it failed. - * - * @method Phaser.Utils#chanceRoll - * @param {number} chance - The chance of receiving the value. A number between 0 and 100 (effectively 0% to 100%). - * @return {boolean} True if the roll passed, or false otherwise. - */ + * Generate a random bool result based on the chance value. + * + * Returns true or false based on the chance value (default 50%). For example if you wanted a player to have a 30% chance + * of getting a bonus, call chanceRoll(30) - true means the chance passed, false means it failed. + * + * @method Phaser.Utils#chanceRoll + * @param {number} chance - The chance of receiving the value. A number between 0 and 100 (effectively 0% to 100%). + * @return {boolean} True if the roll passed, or false otherwise. + */ chanceRoll: function (chance) { if (chance === undefined) { chance = 50; } @@ -229,29 +218,28 @@ Phaser.Utils = { }, /** - * Choose between one of two values randomly. - * - * @method Phaser.Utils#randomChoice - * @param {any} choice1 - * @param {any} choice2 - * @return {any} The randomly selected choice - */ + * Choose between one of two values randomly. + * + * @method Phaser.Utils#randomChoice + * @param {any} choice1 + * @param {any} choice2 + * @return {any} The randomly selected choice + */ randomChoice: function (choice1, choice2) { return (Math.random() < 0.5) ? choice1 : choice2; }, /** - * Get a unit dimension from a string. - * - * @method Phaser.Utils.parseDimension - * @param {string|number} size - The size to parse. - * @param {number} dimension - The window dimension to check. - * @return {number} The parsed dimension. - */ + * Get a unit dimension from a string. + * + * @method Phaser.Utils.parseDimension + * @param {string|number} size - The size to parse. + * @param {number} dimension - The window dimension to check. + * @return {number} The parsed dimension. + */ parseDimension: function (size, dimension) { - var f = 0; var px = 0; @@ -282,39 +270,37 @@ Phaser.Utils = { } return px; - }, /** - * Takes the given string and pads it out, to the length required, using the character - * specified. For example if you need a string to be 6 characters long, you can call: - * - * `pad('bob', 6, '-', 2)` - * - * This would return: `bob---` as it has padded it out to 6 characters, using the `-` on the right. - * - * You can also use it to pad numbers (they are always returned as strings): - * - * `pad(512, 6, '0', 1)` - * - * Would return: `000512` with the string padded to the left. - * - * If you don't specify a direction it'll pad to both sides: - * - * `pad('c64', 7, '*')` - * - * Would return: `**c64**` - * - * @method Phaser.Utils.pad - * @param {string} str - The target string. `toString()` will be called on the string, which means you can also pass in common data types like numbers. - * @param {integer} [len=0] - The number of characters to be added. - * @param {string} [pad=" "] - The string to pad it out with (defaults to a space). - * @param {integer} [dir=3] - The direction dir = 1 (left), 2 (right), 3 (both). - * @return {string} The padded string. - */ + * Takes the given string and pads it out, to the length required, using the character + * specified. For example if you need a string to be 6 characters long, you can call: + * + * `pad('bob', 6, '-', 2)` + * + * This would return: `bob---` as it has padded it out to 6 characters, using the `-` on the right. + * + * You can also use it to pad numbers (they are always returned as strings): + * + * `pad(512, 6, '0', 1)` + * + * Would return: `000512` with the string padded to the left. + * + * If you don't specify a direction it'll pad to both sides: + * + * `pad('c64', 7, '*')` + * + * Would return: `**c64**` + * + * @method Phaser.Utils.pad + * @param {string} str - The target string. `toString()` will be called on the string, which means you can also pass in common data types like numbers. + * @param {integer} [len=0] - The number of characters to be added. + * @param {string} [pad=" "] - The string to pad it out with (defaults to a space). + * @param {integer} [dir=3] - The direction dir = 1 (left), 2 (right), 3 (both). + * @return {string} The padded string. + */ pad: function (str, len, pad, dir) { - if (len === undefined) { var len = 0; } if (pad === undefined) { var pad = ' '; } if (dir === undefined) { var dir = 3; } @@ -344,32 +330,34 @@ Phaser.Utils = { } return str; - }, /** - * This is a slightly modified version of jQuery.isPlainObject. - * A plain object is an object whose internal class property is [object Object]. - * @method Phaser.Utils.isPlainObject - * @param {object} obj - The object to inspect. - * @return {boolean} - true if the object is plain, otherwise false. - */ + * This is a slightly modified version of jQuery.isPlainObject. + * A plain object is an object whose internal class property is [object Object]. + * @method Phaser.Utils.isPlainObject + * @param {object} obj - The object to inspect. + * @return {boolean} - true if the object is plain, otherwise false. + */ isPlainObject: function (obj) { - - // Not plain objects: - // - Any object or value whose internal [[Class]] property is not "[object Object]" - // - DOM nodes - // - window + /* + * Not plain objects: + * - Any object or value whose internal [[Class]] property is not "[object Object]" + * - DOM nodes + * - window + */ if (typeof(obj) !== 'object' || obj.nodeType || obj === obj.window) { return false; } - // Support: Firefox <20 - // The try/catch suppresses exceptions thrown when attempting to access - // the "constructor" property of certain host objects, ie. |window.location| - // https://bugzilla.mozilla.org/show_bug.cgi?id=814622 + /* + * Support: Firefox <20 + * The try/catch suppresses exceptions thrown when attempting to access + * the "constructor" property of certain host objects, ie. |window.location| + * https://bugzilla.mozilla.org/show_bug.cgi?id=814622 + */ try { if (obj.constructor && !({}).hasOwnProperty.call(obj.constructor.prototype, 'isPrototypeOf')) @@ -382,22 +370,23 @@ Phaser.Utils = { return false; } - // If the function hasn't returned already, we're confident that - // |obj| is a plain object, created by {} or constructed with new Object + /* + * If the function hasn't returned already, we're confident that + * |obj| is a plain object, created by {} or constructed with new Object + */ return true; }, /** - * This is a slightly modified version of http://api.jquery.com/jQuery.extend/ - * - * @method Phaser.Utils.extend - * @param {boolean} deep - Perform a deep copy? - * @param {object} target - The target object to copy to. - * @return {object} The extended object. - */ + * This is a slightly modified version of http://api.jquery.com/jQuery.extend/ + * + * @method Phaser.Utils.extend + * @param {boolean} deep - Perform a deep copy? + * @param {object} target - The target object to copy to. + * @return {object} The extended object. + */ extend: function () { - var options, name, src, copy, copyIsArray, clone, target = arguments[0] || {}, i = 1, @@ -466,24 +455,22 @@ Phaser.Utils = { // Return the modified object return target; - }, /** - * Mixes in an existing mixin object with the target. - * - * Values in the mixin that have either `get` or `set` functions are created as properties via `defineProperty` - * _except_ if they also define a `clone` method - if a clone method is defined that is called instead and - * the result is assigned directly. - * - * @method Phaser.Utils.mixinPrototype - * @param {object} target - The target object to receive the new functions. - * @param {object} mixin - The object to copy the functions from. - * @param {boolean} [replace=false] - If the target object already has a matching function should it be overwritten or not? - */ + * Mixes in an existing mixin object with the target. + * + * Values in the mixin that have either `get` or `set` functions are created as properties via `defineProperty` + * _except_ if they also define a `clone` method - if a clone method is defined that is called instead and + * the result is assigned directly. + * + * @method Phaser.Utils.mixinPrototype + * @param {object} target - The target object to receive the new functions. + * @param {object} mixin - The object to copy the functions from. + * @param {boolean} [replace=false] - If the target object already has a matching function should it be overwritten or not? + */ mixinPrototype: function (target, mixin, replace) { - if (replace === undefined) { replace = false; } var mixinKeys = Object.keys(mixin); @@ -517,21 +504,19 @@ Phaser.Utils = { target[key] = value; } } - }, /** - * Mixes the source object into the destination object, returning the newly modified destination object. - * Based on original code by @mudcube - * - * @method Phaser.Utils.mixin - * @param {object} from - The object to copy (the source object). - * @param {object} to - The object to copy to (the destination object). - * @return {object} The modified destination object. - */ + * Mixes the source object into the destination object, returning the newly modified destination object. + * Based on original code by @mudcube + * + * @method Phaser.Utils.mixin + * @param {object} from - The object to copy (the source object). + * @param {object} to - The object to copy to (the destination object). + * @return {object} The modified destination object. + */ mixin: function (from, to) { - if (!from || typeof (from) !== 'object') { return to; @@ -567,7 +552,6 @@ Phaser.Utils = { } return to; - } };