From 299115ca5d5b1e27fea42de57f25b232d082574d Mon Sep 17 00:00:00 2001 From: photonstorm Date: Mon, 25 Nov 2013 04:40:04 +0000 Subject: [PATCH] The entire Phaser library has been updated to match the new JSHint configuration. --- README.md | 4 +- src/PixiPatch.js | 390 +-- src/core/Group.js | 108 +- src/core/PluginManager.js | 14 +- src/core/Signal.js | 64 +- src/core/Stage.js | 4 +- src/core/StateManager.js | 8 +- src/gameobjects/BitmapData.js | 10 +- src/gameobjects/BitmapText.js | 68 +- src/gameobjects/GameObjectFactory.js | 62 +- src/gameobjects/Sprite.js | 6 +- src/gameobjects/Text.js | 68 +- src/geom/Circle.js | 6 +- src/geom/Point.js | 34 +- src/input/Input.js | 8 +- src/input/Touch.js | 4 +- src/loader/Cache.js | 205 +- src/loader/Loader.js | 2116 ++++++++--------- src/loader/LoaderParser.js | 14 +- src/math/Math.js | 830 +++---- src/math/QuadTree.js | 369 +-- src/math/RandomDataGenerator.js | 381 +-- src/net/Net.js | 250 +- src/particles/Particles.js | 87 +- src/particles/arcade/Emitter.js | 260 +- src/physics/advanced/collision/QuadTree.js | 10 +- .../advanced/collision/SAP1DBroadphase.js | 24 +- .../advanced/constraints/Constraint.js | 24 +- src/physics/advanced/constraints/Equation.js | 48 +- .../advanced/constraints/FrictionEquation.js | 24 +- src/physics/advanced/events/EventEmitter.js | 48 +- .../advanced/material/ContactMaterial.js | 72 +- src/physics/advanced/material/Material.js | 8 +- src/physics/advanced/math/polyk.js | 2 +- src/physics/advanced/objects/Body.js | 186 +- src/physics/advanced/objects/Spring.js | 56 +- src/physics/advanced/shapes/Circle.js | 8 +- src/physics/advanced/shapes/Convex.js | 32 +- src/physics/advanced/shapes/Line.js | 8 +- src/physics/advanced/shapes/Shape.js | 80 +- src/physics/advanced/solver/GSSolver.js | 32 +- src/physics/advanced/solver/Island.js | 16 +- src/physics/advanced/solver/IslandSolver.js | 16 +- src/physics/advanced/solver/Solver.js | 10 +- src/physics/advanced/world/World.js | 130 +- src/physics/arcade/ArcadePhysics.js | 24 +- src/physics/arcade/Body.js | 280 +-- src/pixi/core/Circle.js | 24 +- src/pixi/core/Ellipse.js | 32 +- src/pixi/display/Sprite.js | 6 +- src/pixi/loaders/AssetLoader.js | 22 +- src/pixi/loaders/BitmapFontLoader.js | 50 +- src/pixi/loaders/ImageLoader.js | 18 +- src/pixi/loaders/SpriteSheetLoader.js | 20 +- src/pixi/primitives/Graphics.js | 54 +- src/sound/Sound.js | 219 +- src/sound/SoundManager.js | 90 +- src/system/Canvas.js | 6 +- src/system/Device.js | 2 +- src/system/RequestAnimationFrame.js | 204 +- src/system/StageScaleMode.js | 17 +- src/tilemap/Tile.js | 3 +- src/tilemap/Tilemap.js | 66 +- src/tilemap/TilemapLayer.js | 94 +- src/tilemap/TilemapParser.js | 268 +-- src/tilemap/Tileset.js | 4 +- src/time/Time.js | 72 +- src/time/Timer.js | 142 +- src/tween/Easing.js | 748 +++--- src/tween/Tween.js | 565 +++-- src/tween/TweenManager.js | 291 +-- src/utils/Color.js | 10 +- src/utils/Debug.js | 86 +- src/utils/Utils.js | 348 +-- 74 files changed, 4992 insertions(+), 4977 deletions(-) diff --git a/README.md b/README.md index bfe3705a2..d6d0ff52a 100644 --- a/README.md +++ b/README.md @@ -42,6 +42,7 @@ Change Log Version 1.1.3 - in build * New: Added a .jshintrc so contributions can be run through JSHint to help retain formatting across the library (thanks kevinthompson) +* New: The entire Phaser library has been updated to match the new JSHint configuration. * New: Added a new in-built texture. Sprites now use __default if no texture was provided (a 32x32 transparent PNG) or __missing if one was given but not found (a 32x32 black box with a green cross through it) * New: Added Phaser.Filter. A new way to use the new WebGL shaders/filters that the new version of Pixi supports. * New: The object returned by Math.sinCosGenerator now contains a length property. @@ -84,13 +85,12 @@ Version 1.1.3 - in build * Updated: Tided up the Graphics object (thanks BorisKozo) * Updated: If running in Canvas mode and you have a render function it will save the context and reset the transform before running your render function. * Updated: Sprite will now check the exists property of the Group it is in, if the Group.exists = false the Sprite won't update. -* Updated: Lots of documentation tweaks across various files such as Pointer, Sound and Color. +* Updated: Lots of documentation fixes and updates across nearly all files. * Updated: If you specify 'null' as a Group parent it will now revert to using the World as the parent (before only 'undefined' worked) * Updated: Skip preupdate/update for PIXI hierarchies in which an ancestor doesn't exist (thanks cocoademon) * Updated: Loader.audio can now accept either an array of URL strings or a single URL string (thanks crazysam + kevinthompson) * Updated: MSPointer updated to support IE11 by dropping the prefix from the event listeners. - You can view the complete Change Log for all previous versions at https://github.com/photonstorm/phaser/changelog.md How to Build diff --git a/src/PixiPatch.js b/src/PixiPatch.js index db56ae7b4..a085f69a7 100644 --- a/src/PixiPatch.js +++ b/src/PixiPatch.js @@ -16,238 +16,240 @@ */ PIXI.CanvasRenderer.prototype.render = function(stage) { - PIXI.texturesToUpdate.length = 0; - PIXI.texturesToDestroy.length = 0; - - PIXI.visibleCount++; - stage.updateTransform(); - - // update the background color - // if(this.view.style.backgroundColor!=stage.backgroundColorString && !this.transparent)this.view.style.backgroundColor = stage.backgroundColorString; + PIXI.texturesToUpdate.length = 0; + PIXI.texturesToDestroy.length = 0; + + PIXI.visibleCount++; + stage.updateTransform(); + + // update the background color + // if(this.view.style.backgroundColor!=stage.backgroundColorString && !this.transparent)this.view.style.backgroundColor = stage.backgroundColorString; - this.context.setTransform(1, 0, 0, 1, 0, 0); - // this.context.clearRect(0, 0, this.width, this.height) + this.context.setTransform(1, 0, 0, 1, 0, 0); + // this.context.clearRect(0, 0, this.width, this.height) this.renderDisplayObject(stage); - // Remove frame updates - if (PIXI.Texture.frameUpdates.length > 0) - { - PIXI.Texture.frameUpdates.length = 0; - } - + // Remove frame updates + if (PIXI.Texture.frameUpdates.length > 0) + { + PIXI.Texture.frameUpdates.length = 0; + } + } PIXI.CanvasRenderer.prototype.renderDisplayObject = function(displayObject) { - // Once the display object hits this we can break the loop - var testObject = displayObject.last._iNext; - displayObject = displayObject.first; - - do - { - //transform = displayObject.worldTransform; - - if (!displayObject.visible) - { - displayObject = displayObject.last._iNext; - continue; - } - - if (!displayObject.renderable || displayObject.alpha === 0) - { - displayObject = displayObject._iNext; - continue; - } - - if (displayObject instanceof PIXI.Sprite) - { - // var frame = displayObject.texture.frame; - - if (displayObject.texture.frame) - { - this.context.globalAlpha = displayObject.worldAlpha; - - if (displayObject.texture.trimmed) - { - this.context.setTransform(displayObject.worldTransform[0], displayObject.worldTransform[3], displayObject.worldTransform[1], displayObject.worldTransform[4], displayObject.worldTransform[2] + displayObject.texture.trim.x, displayObject.worldTransform[5] + displayObject.texture.trim.y); - } - else - { - this.context.setTransform(displayObject.worldTransform[0], displayObject.worldTransform[3], displayObject.worldTransform[1], displayObject.worldTransform[4], displayObject.worldTransform[2], displayObject.worldTransform[5]); - } - - this.context.drawImage( - displayObject.texture.baseTexture.source, - displayObject.texture.frame.x, - displayObject.texture.frame.y, - displayObject.texture.frame.width, - displayObject.texture.frame.height, - (displayObject.anchor.x) * -displayObject.texture.frame.width, - (displayObject.anchor.y) * -displayObject.texture.frame.height, - displayObject.texture.frame.width, - displayObject.texture.frame.height); - } - } - else if (displayObject instanceof PIXI.Strip) - { - this.context.setTransform(displayObject.worldTransform[0], displayObject.worldTransform[3], displayObject.worldTransform[1], displayObject.worldTransform[4], displayObject.worldTransform[2], displayObject.worldTransform[5]) - this.renderStrip(displayObject); - } - else if (displayObject instanceof PIXI.TilingSprite) - { - this.context.setTransform(displayObject.worldTransform[0], displayObject.worldTransform[3], displayObject.worldTransform[1], displayObject.worldTransform[4], displayObject.worldTransform[2], displayObject.worldTransform[5]) - this.renderTilingSprite(displayObject); - } - else if (displayObject instanceof PIXI.CustomRenderable) - { - displayObject.renderCanvas(this); - } - else if (displayObject instanceof PIXI.Graphics) - { - this.context.setTransform(displayObject.worldTransform[0], displayObject.worldTransform[3], displayObject.worldTransform[1], displayObject.worldTransform[4], displayObject.worldTransform[2], displayObject.worldTransform[5]) - PIXI.CanvasGraphics.renderGraphics(displayObject, this.context); - } - else if (displayObject instanceof PIXI.FilterBlock) - { - if (displayObject.open) - { - this.context.save(); - - var cacheAlpha = displayObject.mask.alpha; - var maskTransform = displayObject.mask.worldTransform; - - this.context.setTransform(maskTransform[0], maskTransform[3], maskTransform[1], maskTransform[4], maskTransform[2], maskTransform[5]) - - displayObject.mask.worldAlpha = 0.5; - - this.context.worldAlpha = 0; - - PIXI.CanvasGraphics.renderGraphicsMask(displayObject.mask, this.context); - this.context.clip(); - - displayObject.mask.worldAlpha = cacheAlpha; - } - else - { - this.context.restore(); - } - } - // count++ - displayObject = displayObject._iNext; - } - while(displayObject != testObject) - + // Once the display object hits this we can break the loop + var testObject = displayObject.last._iNext; + displayObject = displayObject.first; + + do + { + //transform = displayObject.worldTransform; + + if (!displayObject.visible) + { + displayObject = displayObject.last._iNext; + continue; + } + + if (!displayObject.renderable || displayObject.alpha === 0) + { + displayObject = displayObject._iNext; + continue; + } + + if (displayObject instanceof PIXI.Sprite) + { + // var frame = displayObject.texture.frame; + + if (displayObject.texture.frame) + { + this.context.globalAlpha = displayObject.worldAlpha; + + if (displayObject.texture.trimmed) + { + this.context.setTransform(displayObject.worldTransform[0], displayObject.worldTransform[3], displayObject.worldTransform[1], displayObject.worldTransform[4], displayObject.worldTransform[2] + displayObject.texture.trim.x, displayObject.worldTransform[5] + displayObject.texture.trim.y); + } + else + { + this.context.setTransform(displayObject.worldTransform[0], displayObject.worldTransform[3], displayObject.worldTransform[1], displayObject.worldTransform[4], displayObject.worldTransform[2], displayObject.worldTransform[5]); + } + + this.context.drawImage( + displayObject.texture.baseTexture.source, + displayObject.texture.frame.x, + displayObject.texture.frame.y, + displayObject.texture.frame.width, + displayObject.texture.frame.height, + (displayObject.anchor.x) * -displayObject.texture.frame.width, + (displayObject.anchor.y) * -displayObject.texture.frame.height, + displayObject.texture.frame.width, + displayObject.texture.frame.height); + } + } + else if (displayObject instanceof PIXI.Strip) + { + this.context.setTransform(displayObject.worldTransform[0], displayObject.worldTransform[3], displayObject.worldTransform[1], displayObject.worldTransform[4], displayObject.worldTransform[2], displayObject.worldTransform[5]) + this.renderStrip(displayObject); + } + else if (displayObject instanceof PIXI.TilingSprite) + { + this.context.setTransform(displayObject.worldTransform[0], displayObject.worldTransform[3], displayObject.worldTransform[1], displayObject.worldTransform[4], displayObject.worldTransform[2], displayObject.worldTransform[5]) + this.renderTilingSprite(displayObject); + } + else if (displayObject instanceof PIXI.CustomRenderable) + { + displayObject.renderCanvas(this); + } + else if (displayObject instanceof PIXI.Graphics) + { + this.context.setTransform(displayObject.worldTransform[0], displayObject.worldTransform[3], displayObject.worldTransform[1], displayObject.worldTransform[4], displayObject.worldTransform[2], displayObject.worldTransform[5]) + PIXI.CanvasGraphics.renderGraphics(displayObject, this.context); + } + else if (displayObject instanceof PIXI.FilterBlock) + { + if (displayObject.open) + { + this.context.save(); + + var cacheAlpha = displayObject.mask.alpha; + var maskTransform = displayObject.mask.worldTransform; + + this.context.setTransform(maskTransform[0], maskTransform[3], maskTransform[1], maskTransform[4], maskTransform[2], maskTransform[5]) + + displayObject.mask.worldAlpha = 0.5; + + this.context.worldAlpha = 0; + + PIXI.CanvasGraphics.renderGraphicsMask(displayObject.mask, this.context); + this.context.clip(); + + displayObject.mask.worldAlpha = cacheAlpha; + } + else + { + this.context.restore(); + } + } + // count++ + displayObject = displayObject._iNext; + } + while(displayObject != testObject) + } PIXI.WebGLBatch.prototype.update = function() { - var gl = this.gl; - var worldTransform, width, height, aX, aY, w0, w1, h0, h1, index, index2, index3 + // var gl = this.gl; + // var worldTransform, width, height, aX, aY, w0, w1, h0, h1, index, index2, index3 - var a, b, c, d, tx, ty; + var worldTransform, width, height, aX, aY, w0, w1, h0, h1, index; - var indexRun = 0; + var a, b, c, d, tx, ty; - var displayObject = this.head; + var indexRun = 0; - while(displayObject) - { - if(displayObject.vcount === PIXI.visibleCount) - { - width = displayObject.texture.frame.width; - height = displayObject.texture.frame.height; + var displayObject = this.head; - // TODO trim?? - aX = displayObject.anchor.x;// - displayObject.texture.trim.x - aY = displayObject.anchor.y; //- displayObject.texture.trim.y - w0 = width * (1-aX); - w1 = width * -aX; + while(displayObject) + { + if(displayObject.vcount === PIXI.visibleCount) + { + width = displayObject.texture.frame.width; + height = displayObject.texture.frame.height; - h0 = height * (1-aY); - h1 = height * -aY; + // TODO trim?? + aX = displayObject.anchor.x;// - displayObject.texture.trim.x + aY = displayObject.anchor.y; //- displayObject.texture.trim.y + w0 = width * (1-aX); + w1 = width * -aX; - index = indexRun * 8; + h0 = height * (1-aY); + h1 = height * -aY; - worldTransform = displayObject.worldTransform; + index = indexRun * 8; - a = worldTransform[0]; - b = worldTransform[3]; - c = worldTransform[1]; - d = worldTransform[4]; - tx = worldTransform[2]; - ty = worldTransform[5]; + worldTransform = displayObject.worldTransform; - if (displayObject.texture.trimmed) - { - tx += displayObject.texture.trim.x; - ty += displayObject.texture.trim.y; - } + a = worldTransform[0]; + b = worldTransform[3]; + c = worldTransform[1]; + d = worldTransform[4]; + tx = worldTransform[2]; + ty = worldTransform[5]; - this.verticies[index + 0 ] = a * w1 + c * h1 + tx; - this.verticies[index + 1 ] = d * h1 + b * w1 + ty; + if (displayObject.texture.trimmed) + { + tx += displayObject.texture.trim.x; + ty += displayObject.texture.trim.y; + } - this.verticies[index + 2 ] = a * w0 + c * h1 + tx; - this.verticies[index + 3 ] = d * h1 + b * w0 + ty; + this.verticies[index + 0 ] = a * w1 + c * h1 + tx; + this.verticies[index + 1 ] = d * h1 + b * w1 + ty; - this.verticies[index + 4 ] = a * w0 + c * h0 + tx; - this.verticies[index + 5 ] = d * h0 + b * w0 + ty; + this.verticies[index + 2 ] = a * w0 + c * h1 + tx; + this.verticies[index + 3 ] = d * h1 + b * w0 + ty; - this.verticies[index + 6] = a * w1 + c * h0 + tx; - this.verticies[index + 7] = d * h0 + b * w1 + ty; + this.verticies[index + 4 ] = a * w0 + c * h0 + tx; + this.verticies[index + 5 ] = d * h0 + b * w0 + ty; - if(displayObject.updateFrame || displayObject.texture.updateFrame) - { - this.dirtyUVS = true; + this.verticies[index + 6] = a * w1 + c * h0 + tx; + this.verticies[index + 7] = d * h0 + b * w1 + ty; - var texture = displayObject.texture; + if(displayObject.updateFrame || displayObject.texture.updateFrame) + { + this.dirtyUVS = true; - var frame = texture.frame; - var tw = texture.baseTexture.width; - var th = texture.baseTexture.height; + var texture = displayObject.texture; - this.uvs[index + 0] = frame.x / tw; - this.uvs[index +1] = frame.y / th; + var frame = texture.frame; + var tw = texture.baseTexture.width; + var th = texture.baseTexture.height; - this.uvs[index +2] = (frame.x + frame.width) / tw; - this.uvs[index +3] = frame.y / th; + this.uvs[index + 0] = frame.x / tw; + this.uvs[index +1] = frame.y / th; - this.uvs[index +4] = (frame.x + frame.width) / tw; - this.uvs[index +5] = (frame.y + frame.height) / th; + this.uvs[index +2] = (frame.x + frame.width) / tw; + this.uvs[index +3] = frame.y / th; - this.uvs[index +6] = frame.x / tw; - this.uvs[index +7] = (frame.y + frame.height) / th; + this.uvs[index +4] = (frame.x + frame.width) / tw; + this.uvs[index +5] = (frame.y + frame.height) / th; - displayObject.updateFrame = false; - } + this.uvs[index +6] = frame.x / tw; + this.uvs[index +7] = (frame.y + frame.height) / th; - // TODO this probably could do with some optimisation.... - if(displayObject.cacheAlpha != displayObject.worldAlpha) - { - displayObject.cacheAlpha = displayObject.worldAlpha; + displayObject.updateFrame = false; + } - var colorIndex = indexRun * 4; - this.colors[colorIndex] = this.colors[colorIndex + 1] = this.colors[colorIndex + 2] = this.colors[colorIndex + 3] = displayObject.worldAlpha; - this.dirtyColors = true; - } - } - else - { - index = indexRun * 8; + // TODO this probably could do with some optimisation.... + if(displayObject.cacheAlpha != displayObject.worldAlpha) + { + displayObject.cacheAlpha = displayObject.worldAlpha; - this.verticies[index + 0 ] = 0; - this.verticies[index + 1 ] = 0; + var colorIndex = indexRun * 4; + this.colors[colorIndex] = this.colors[colorIndex + 1] = this.colors[colorIndex + 2] = this.colors[colorIndex + 3] = displayObject.worldAlpha; + this.dirtyColors = true; + } + } + else + { + index = indexRun * 8; - this.verticies[index + 2 ] = 0; - this.verticies[index + 3 ] = 0; + this.verticies[index + 0 ] = 0; + this.verticies[index + 1 ] = 0; - this.verticies[index + 4 ] = 0; - this.verticies[index + 5 ] = 0; + this.verticies[index + 2 ] = 0; + this.verticies[index + 3 ] = 0; - this.verticies[index + 6] = 0; - this.verticies[index + 7] = 0; - } + this.verticies[index + 4 ] = 0; + this.verticies[index + 5 ] = 0; - indexRun++; - displayObject = displayObject.__next; - } + this.verticies[index + 6] = 0; + this.verticies[index + 7] = 0; + } + + indexRun++; + displayObject = displayObject.__next; + } } diff --git a/src/core/Group.js b/src/core/Group.js index fb1287bd7..ba0cd61c8 100644 --- a/src/core/Group.js +++ b/src/core/Group.js @@ -571,14 +571,14 @@ Phaser.Group.prototype = { }, /** - * Sets the given property to the given value on the child. The operation controls the assignment of the value. - * - * @method Phaser.Group#setProperty - * @param {*} child - The child to set the property value on. - * @param {array} key - An array of strings that make up the property that will be set. - * @param {*} value - The value that will be set. - * @param {number} [operation=0] - Controls how the value is assigned. A value of 0 replaces the value with the new one. A value of 1 adds it, 2 subtracts it, 3 multiplies it and 4 divides it. - */ + * Sets the given property to the given value on the child. The operation controls the assignment of the value. + * + * @method Phaser.Group#setProperty + * @param {*} child - The child to set the property value on. + * @param {array} key - An array of strings that make up the property that will be set. + * @param {*} value - The value that will be set. + * @param {number} [operation=0] - Controls how the value is assigned. A value of 0 replaces the value with the new one. A value of 1 adds it, 2 subtracts it, 3 multiplies it and 4 divides it. + */ setProperty: function (child, key, value, operation) { operation = operation || 0; @@ -633,16 +633,16 @@ Phaser.Group.prototype = { }, /** - * This function allows you to quickly set the same property across all children of this Group to a new value. - * The operation parameter controls how the new value is assigned to the property, from simple replacement to addition and multiplication. - * - * @method Phaser.Group#setAll - * @param {string} key - The property, as a string, to be set. For example: 'body.velocity.x' - * @param {*} value - The value that will be set. - * @param {boolean} [checkAlive=false] - If set then only children with alive=true will be updated. - * @param {boolean} [checkVisible=false] - If set then only children with visible=true will be updated. - * @param {number} [operation=0] - Controls how the value is assigned. A value of 0 replaces the value with the new one. A value of 1 adds it, 2 subtracts it, 3 multiplies it and 4 divides it. - */ + * This function allows you to quickly set the same property across all children of this Group to a new value. + * The operation parameter controls how the new value is assigned to the property, from simple replacement to addition and multiplication. + * + * @method Phaser.Group#setAll + * @param {string} key - The property, as a string, to be set. For example: 'body.velocity.x' + * @param {*} value - The value that will be set. + * @param {boolean} [checkAlive=false] - If set then only children with alive=true will be updated. + * @param {boolean} [checkVisible=false] - If set then only children with visible=true will be updated. + * @param {number} [operation=0] - Controls how the value is assigned. A value of 0 replaces the value with the new one. A value of 1 adds it, 2 subtracts it, 3 multiplies it and 4 divides it. + */ setAll: function (key, value, checkAlive, checkVisible, operation) { key = key.split('.'); @@ -671,15 +671,15 @@ Phaser.Group.prototype = { }, /** - * Adds the amount to the given property on all children in this Group. - * Group.addAll('x', 10) will add 10 to the child.x value. - * - * @method Phaser.Group#addAll - * @param {string} property - The property to increment, for example 'body.velocity.x' or 'angle'. - * @param {number} amount - The amount to increment the property by. If child.x = 10 then addAll('x', 40) would make child.x = 50. - * @param {boolean} checkAlive - If true the property will only be changed if the child is alive. - * @param {boolean} checkVisible - If true the property will only be changed if the child is visible. - */ + * Adds the amount to the given property on all children in this Group. + * Group.addAll('x', 10) will add 10 to the child.x value. + * + * @method Phaser.Group#addAll + * @param {string} property - The property to increment, for example 'body.velocity.x' or 'angle'. + * @param {number} amount - The amount to increment the property by. If child.x = 10 then addAll('x', 40) would make child.x = 50. + * @param {boolean} checkAlive - If true the property will only be changed if the child is alive. + * @param {boolean} checkVisible - If true the property will only be changed if the child is visible. + */ addAll: function (property, amount, checkAlive, checkVisible) { this.setAll(property, amount, checkAlive, checkVisible, 1); @@ -687,15 +687,15 @@ Phaser.Group.prototype = { }, /** - * Subtracts the amount from the given property on all children in this Group. - * Group.subAll('x', 10) will minus 10 from the child.x value. - * - * @method Phaser.Group#subAll - * @param {string} property - The property to decrement, for example 'body.velocity.x' or 'angle'. - * @param {number} amount - The amount to subtract from the property. If child.x = 50 then subAll('x', 40) would make child.x = 10. - * @param {boolean} checkAlive - If true the property will only be changed if the child is alive. - * @param {boolean} checkVisible - If true the property will only be changed if the child is visible. - */ + * Subtracts the amount from the given property on all children in this Group. + * Group.subAll('x', 10) will minus 10 from the child.x value. + * + * @method Phaser.Group#subAll + * @param {string} property - The property to decrement, for example 'body.velocity.x' or 'angle'. + * @param {number} amount - The amount to subtract from the property. If child.x = 50 then subAll('x', 40) would make child.x = 10. + * @param {boolean} checkAlive - If true the property will only be changed if the child is alive. + * @param {boolean} checkVisible - If true the property will only be changed if the child is visible. + */ subAll: function (property, amount, checkAlive, checkVisible) { this.setAll(property, amount, checkAlive, checkVisible, 2); @@ -703,15 +703,15 @@ Phaser.Group.prototype = { }, /** - * Multiplies the given property by the amount on all children in this Group. - * Group.multiplyAll('x', 2) will x2 the child.x value. - * - * @method Phaser.Group#multiplyAll - * @param {string} property - The property to multiply, for example 'body.velocity.x' or 'angle'. - * @param {number} amount - The amount to multiply the property by. If child.x = 10 then multiplyAll('x', 2) would make child.x = 20. - * @param {boolean} checkAlive - If true the property will only be changed if the child is alive. - * @param {boolean} checkVisible - If true the property will only be changed if the child is visible. - */ + * Multiplies the given property by the amount on all children in this Group. + * Group.multiplyAll('x', 2) will x2 the child.x value. + * + * @method Phaser.Group#multiplyAll + * @param {string} property - The property to multiply, for example 'body.velocity.x' or 'angle'. + * @param {number} amount - The amount to multiply the property by. If child.x = 10 then multiplyAll('x', 2) would make child.x = 20. + * @param {boolean} checkAlive - If true the property will only be changed if the child is alive. + * @param {boolean} checkVisible - If true the property will only be changed if the child is visible. + */ multiplyAll: function (property, amount, checkAlive, checkVisible) { this.setAll(property, amount, checkAlive, checkVisible, 3); @@ -719,15 +719,15 @@ Phaser.Group.prototype = { }, /** - * Divides the given property by the amount on all children in this Group. - * Group.divideAll('x', 2) will half the child.x value. - * - * @method Phaser.Group#divideAll - * @param {string} property - The property to divide, for example 'body.velocity.x' or 'angle'. - * @param {number} amount - The amount to divide the property by. If child.x = 100 then divideAll('x', 2) would make child.x = 50. - * @param {boolean} checkAlive - If true the property will only be changed if the child is alive. - * @param {boolean} checkVisible - If true the property will only be changed if the child is visible. - */ + * Divides the given property by the amount on all children in this Group. + * Group.divideAll('x', 2) will half the child.x value. + * + * @method Phaser.Group#divideAll + * @param {string} property - The property to divide, for example 'body.velocity.x' or 'angle'. + * @param {number} amount - The amount to divide the property by. If child.x = 100 then divideAll('x', 2) would make child.x = 50. + * @param {boolean} checkAlive - If true the property will only be changed if the child is alive. + * @param {boolean} checkVisible - If true the property will only be changed if the child is visible. + */ divideAll: function (property, amount, checkAlive, checkVisible) { this.setAll(property, amount, checkAlive, checkVisible, 4); diff --git a/src/core/PluginManager.js b/src/core/PluginManager.js index 5838e94c3..1ca1f92d3 100644 --- a/src/core/PluginManager.js +++ b/src/core/PluginManager.js @@ -127,10 +127,10 @@ Phaser.PluginManager.prototype = { }, /** - * Remove a Plugin from the PluginManager. - * @method Phaser.PluginManager#remove - * @param {Phaser.Plugin} plugin - The plugin to be removed. - */ + * Remove a Plugin from the PluginManager. + * @method Phaser.PluginManager#remove + * @param {Phaser.Plugin} plugin - The plugin to be removed. + */ remove: function (plugin) { if (this._pluginsLength === 0) @@ -151,9 +151,9 @@ Phaser.PluginManager.prototype = { }, /** - * Removes all Plugins from the PluginManager. - * @method Phaser.PluginManager#removeAll - */ + * Removes all Plugins from the PluginManager. + * @method Phaser.PluginManager#removeAll + */ removeAll: function() { for (this._p = 0; this._p < this._pluginsLength; this._p++) diff --git a/src/core/Signal.js b/src/core/Signal.js index 05b18376e..7a3db73c7 100644 --- a/src/core/Signal.js +++ b/src/core/Signal.js @@ -73,14 +73,14 @@ Phaser.Signal.prototype = { }, /** - * @method Phaser.Signal#_registerListener - * @param {function} listener - Signal handler function. - * @param {boolean} isOnce - Description. - * @param {object} [listenerContext] - Description. - * @param {number} [priority] - The priority level of the event listener. Listeners with higher priority will be executed before listeners with lower priority. Listeners with same priority level will be executed at the same order as they were added. (default = 0). - * @return {Phaser.SignalBinding} An Object representing the binding between the Signal and listener. - * @private - */ + * @method Phaser.Signal#_registerListener + * @param {function} listener - Signal handler function. + * @param {boolean} isOnce - Description. + * @param {object} [listenerContext] - Description. + * @param {number} [priority] - The priority level of the event listener. Listeners with higher priority will be executed before listeners with lower priority. Listeners with same priority level will be executed at the same order as they were added. (default = 0). + * @return {Phaser.SignalBinding} An Object representing the binding between the Signal and listener. + * @private + */ _registerListener: function (listener, isOnce, listenerContext, priority) { var prevIndex = this._indexOfListener(listener, listenerContext), @@ -104,10 +104,10 @@ Phaser.Signal.prototype = { }, /** - * @method Phaser.Signal#_addBinding - * @param {Phaser.SignalBinding} binding - An Object representing the binding between the Signal and listener. - * @private - */ + * @method Phaser.Signal#_addBinding + * @param {Phaser.SignalBinding} binding - An Object representing the binding between the Signal and listener. + * @private + */ _addBinding: function (binding) { //simplified insertion sort var n = this._bindings.length; @@ -116,11 +116,11 @@ Phaser.Signal.prototype = { }, /** - * @method Phaser.Signal#_indexOfListener - * @param {function} listener - Signal handler function. - * @return {number} Description. - * @private - */ + * @method Phaser.Signal#_indexOfListener + * @param {function} listener - Signal handler function. + * @return {number} Description. + * @private + */ _indexOfListener: function (listener, context) { var n = this._bindings.length, cur; @@ -134,26 +134,26 @@ Phaser.Signal.prototype = { }, /** - * Check if listener was attached to Signal. - * - * @method Phaser.Signal#has - * @param {Function} listener - Signal handler function. - * @param {Object} [context] - Context on which listener will be executed (object that should represent the `this` variable inside listener function). - * @return {boolean} If Signal has the specified listener. - */ + * Check if listener was attached to Signal. + * + * @method Phaser.Signal#has + * @param {Function} listener - Signal handler function. + * @param {Object} [context] - Context on which listener will be executed (object that should represent the `this` variable inside listener function). + * @return {boolean} If Signal has the specified listener. + */ has: function (listener, context) { return this._indexOfListener(listener, context) !== -1; }, /** - * Add a listener to the signal. - * - * @method Phaser.Signal#add - * @param {function} listener - Signal handler function. - * @param {object} [listenerContext] Context on which listener will be executed (object that should represent the `this` variable inside listener function). - * @param {number} [priority] The priority level of the event listener. Listeners with higher priority will be executed before listeners with lower priority. Listeners with same priority level will be executed at the same order as they were added. (default = 0). - * @return {Phaser.SignalBinding} An Object representing the binding between the Signal and listener. - */ + * Add a listener to the signal. + * + * @method Phaser.Signal#add + * @param {function} listener - Signal handler function. + * @param {object} [listenerContext] Context on which listener will be executed (object that should represent the `this` variable inside listener function). + * @param {number} [priority] The priority level of the event listener. Listeners with higher priority will be executed before listeners with lower priority. Listeners with same priority level will be executed at the same order as they were added. (default = 0). + * @return {Phaser.SignalBinding} An Object representing the binding between the Signal and listener. + */ add: function (listener, listenerContext, priority) { this.validateListener(listener, 'add'); return this._registerListener(listener, false, listenerContext, priority); diff --git a/src/core/Stage.js b/src/core/Stage.js index fdd20717d..38c06883d 100644 --- a/src/core/Stage.js +++ b/src/core/Stage.js @@ -58,8 +58,8 @@ Phaser.Stage = function (game, width, height) { this.scale = new Phaser.StageScaleMode(this.game, width, height); /** - * @property {number} aspectRatio - Aspect ratio. - */ + * @property {number} aspectRatio - Aspect ratio. + */ this.aspectRatio = width / height; /** diff --git a/src/core/StateManager.js b/src/core/StateManager.js index 65d084607..b5ee71b67 100644 --- a/src/core/StateManager.js +++ b/src/core/StateManager.js @@ -172,10 +172,10 @@ Phaser.StateManager.prototype = { }, /** - * 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) diff --git a/src/gameobjects/BitmapData.js b/src/gameobjects/BitmapData.js index d5227b906..4f3a0aeea 100644 --- a/src/gameobjects/BitmapData.js +++ b/src/gameobjects/BitmapData.js @@ -172,7 +172,7 @@ Phaser.BitmapData.prototype = { { this.data32[y * this.width + x] = (red << 24) | (green << 16) | (blue << 8) | alpha; } - */ + */ // this.imageData.data.set(this.data8); @@ -229,10 +229,10 @@ Phaser.BitmapData.prototype = { }, /** - * Get pixels in array in a specific Rectangle. - * @param rect {Rectangle} The specific Rectangle. - * @return {array} CanvasPixelArray. - */ + * Get pixels in array in a specific Rectangle. + * @param rect {Rectangle} The specific Rectangle. + * @return {array} CanvasPixelArray. + */ getPixels: function (rect) { return this.context.getImageData(rect.x, rect.y, rect.width, rect.height); diff --git a/src/gameobjects/BitmapText.js b/src/gameobjects/BitmapText.js index 831e1aa3b..e3bd57e2c 100644 --- a/src/gameobjects/BitmapText.js +++ b/src/gameobjects/BitmapText.js @@ -21,10 +21,14 @@ Phaser.BitmapText = function (game, x, y, text, style) { x = x || 0; y = y || 0; - text = text || ''; style = style || ''; + /** + * @property {Phaser.Game} game - A reference to the currently running Game. + */ + this.game = game; + /** * @property {boolean} exists - If exists = false then the Sprite isn't updated by the core game loop or physics subsystem at all. * @default @@ -38,53 +42,51 @@ Phaser.BitmapText = function (game, x, y, text, style) { this.alive = true; /** - * @property {Description} group - Description. - * @default + * @property {Phaser.Group} group - The parent Group of this BitmapText. */ this.group = null; /** - * @property {string} name - Description. + * @property {string} name - The user defined name given to this BitmapText. * @default */ this.name = ''; /** - * @property {Phaser.Game} game - A reference to the currently running Game. + * @property {number} type - The const type of this object. + * @readonly */ - this.game = game; + this.type = Phaser.BITMAPTEXT; PIXI.BitmapText.call(this, text, style); /** - * @property {Description} type - Description. - */ - this.type = Phaser.BITMAPTEXT; - - /** - * @property {number} position.x - Description. + * @property {number} position.x - The x position of this object. */ this.position.x = x; /** - * @property {number} position.y - Description. + * @property {number} position.y - The y position of this object. */ this.position.y = y; - // Replaces the PIXI.Point with a slightly more flexible one /** - * @property {Phaser.Point} anchor - Description. + * The anchor sets the origin point of the texture. + * The default is 0,0 this means the textures origin is the top left + * Setting than anchor to 0.5,0.5 means the textures origin is centered + * Setting the anchor to 1,1 would mean the textures origin points will be the bottom right + * + * @property {Phaser.Point} anchor - The anchor around which rotation and scaling takes place. */ this.anchor = new Phaser.Point(); /** - * @property {Phaser.Point} scale - Description. + * @property {Phaser.Point} scale - The scale of the object when rendered. By default it's set to 1 (no scale). You can modify it via scale.x or scale.y or scale.setTo(x, y). A value of 1 means no change to the scale, 0.5 means "half the size", 2 means "twice the size", etc. */ this.scale = new Phaser.Point(1, 1); - // A mini cache for storing all of the calculated values /** - * @property {function} _cache - Description. + * @property {object} _cache - A mini cache for storing all of the calculated values. * @private */ this._cache = { @@ -114,15 +116,13 @@ Phaser.BitmapText = function (game, x, y, text, style) { this._cache.y = this.y; /** - * @property {boolean} renderable - Description. - * @private + * @property {boolean} renderable - A renderable object will be rendered to the context each frame. */ this.renderable = true; }; Phaser.BitmapText.prototype = Object.create(PIXI.BitmapText.prototype); -// Phaser.BitmapText.prototype = Phaser.Utils.extend(true, PIXI.BitmapText.prototype); Phaser.BitmapText.prototype.constructor = Phaser.BitmapText; /** @@ -180,11 +180,11 @@ Phaser.BitmapText.prototype.destroy = function() { } /** -* Get -* @returns {Description} -*//** -* Set -* @param {Description} value - Description +* Indicates the rotation of the BitmapText, in degrees, from its original orientation. Values from 0 to 180 represent clockwise rotation; values from 0 to -180 represent counterclockwise rotation. +* Values outside this range are added to or subtracted from 360 to obtain a value within the range. For example, the statement player.angle = 450 is the same as player.angle = 90. +* If you wish to work in radians instead of degrees use the property Sprite.rotation instead. +* @name Phaser.BitmapText#angle +* @property {number} angle - Gets or sets the angle of rotation in degrees. */ Object.defineProperty(Phaser.BitmapText.prototype, 'angle', { @@ -199,11 +199,9 @@ Object.defineProperty(Phaser.BitmapText.prototype, 'angle', { }); /** -* Get -* @returns {Description} -*//** -* Set -* @param {Description} value - Description +* The x coordinate of this object in world space. +* @name Phaser.BitmapText#x +* @property {number} x - The x coordinate of this object in world space. */ Object.defineProperty(Phaser.BitmapText.prototype, 'x', { @@ -218,11 +216,9 @@ Object.defineProperty(Phaser.BitmapText.prototype, 'x', { }); /** -* Get -* @returns {Description} -*//** -* Set -* @param {Description} value - Description +* The y coordinate of this object in world space. +* @name Phaser.BitmapText#y +* @property {number} y - The y coordinate of this object in world space. */ Object.defineProperty(Phaser.BitmapText.prototype, 'y', { diff --git a/src/gameobjects/GameObjectFactory.js b/src/gameobjects/GameObjectFactory.js index 85ea5289b..a69a7c8b9 100644 --- a/src/gameobjects/GameObjectFactory.js +++ b/src/gameobjects/GameObjectFactory.js @@ -100,14 +100,14 @@ Phaser.GameObjectFactory.prototype = { }, /** - * Creates a new instance of the Sound class. - * + * Creates a new instance of the Sound class. + * * @method Phaser.GameObjectFactory#audio - * @param {string} key - The Game.cache key of the sound that this object will use. - * @param {number} volume - The volume at which the sound will be played. - * @param {boolean} loop - Whether or not the sound will loop. - * @return {Phaser.Sound} The newly created text object. - */ + * @param {string} key - The Game.cache key of the sound that this object will use. + * @param {number} volume - The volume at which the sound will be played. + * @param {boolean} loop - Whether or not the sound will loop. + * @return {Phaser.Sound} The newly created text object. + */ audio: function (key, volume, loop) { return this.game.sound.add(key, volume, loop); @@ -115,17 +115,17 @@ Phaser.GameObjectFactory.prototype = { }, /** - * Creates a new TileSprite. - * + * Creates a new TileSprite. + * * @method Phaser.GameObjectFactory#tileSprite - * @param {number} x - X position of the new tileSprite. - * @param {number} y - Y position of the new tileSprite. - * @param {number} width - the width of the tilesprite. - * @param {number} height - the height of the tilesprite. - * @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 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 {Phaser.TileSprite} The newly created tileSprite object. - */ + * @param {number} x - X position of the new tileSprite. + * @param {number} y - Y position of the new tileSprite. + * @param {number} width - the width of the tilesprite. + * @param {number} height - the height of the tilesprite. + * @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 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 {Phaser.TileSprite} The newly created tileSprite object. + */ tileSprite: function (x, y, width, height, key, frame) { return this.world.add(new Phaser.TileSprite(this.game, x, y, width, height, key, frame)); @@ -133,15 +133,15 @@ Phaser.GameObjectFactory.prototype = { }, /** - * Creates a new Text. - * + * Creates a new Text. + * * @method Phaser.GameObjectFactory#text - * @param {number} x - X position of the new text object. - * @param {number} y - Y position of the new text object. - * @param {string} text - The actual text that will be written. - * @param {object} style - The style object containing style attributes like font, font size , etc. - * @return {Phaser.Text} The newly created text object. - */ + * @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 this.world.add(new Phaser.Text(this.game, x, y, text, style)); @@ -169,13 +169,13 @@ Phaser.GameObjectFactory.prototype = { }, /** - * Creates a new Graphics object. - * + * Creates a new Graphics object. + * * @method Phaser.GameObjectFactory#graphics - * @param {number} x - X position of the new graphics object. - * @param {number} y - Y position of the new graphics object. - * @return {Phaser.Graphics} The newly created graphics object. - */ + * @param {number} x - X position of the new graphics object. + * @param {number} y - Y position of the new graphics object. + * @return {Phaser.Graphics} The newly created graphics object. + */ graphics: function (x, y) { return this.world.add(new Phaser.Graphics(this.game, x, y)); diff --git a/src/gameobjects/Sprite.js b/src/gameobjects/Sprite.js index 889877199..1cf92f7f1 100644 --- a/src/gameobjects/Sprite.js +++ b/src/gameobjects/Sprite.js @@ -165,17 +165,17 @@ Phaser.Sprite = function (game, x, y, key, frame) { * Setting than anchor to 0.5,0.5 means the textures origin is centered * Setting the anchor to 1,1 would mean the textures origin points will be the bottom right * - * @property {Phaser.Point} anchor - The anchor around with Sprite rotation and scaling takes place. + * @property {Phaser.Point} anchor - The anchor around which rotation and scaling takes place. */ this.anchor = new Phaser.Point(); /** - * @property {number} x - The x coordinate (in world space) of this Sprite. + * @property {number} x - The x coordinate in world space of this Sprite. */ this.x = x; /** - * @property {number} y - The y coordinate (in world space) of this Sprite. + * @property {number} y - The y coordinate in world space of this Sprite. */ this.y = y; diff --git a/src/gameobjects/Text.js b/src/gameobjects/Text.js index be088e186..63873f3a2 100644 --- a/src/gameobjects/Text.js +++ b/src/gameobjects/Text.js @@ -27,24 +27,24 @@ Phaser.Text = function (game, x, y, text, style) { this.game = game; /** - * @property {boolean} exists - If exists = false then the Sprite isn't updated by the core game loop or physics subsystem at all. + * @property {boolean} exists - If exists = false then the Text isn't updated by the core game loop. * @default */ this.exists = true; /** - * @property {boolean} alive - This is a handy little var your game can use to determine if a sprite is alive or not, it doesn't effect rendering. + * @property {boolean} alive - This is a handy little var your game can use to determine if an object is alive or not, it doesn't effect rendering. * @default */ this.alive = true; /** - * @property {Phaser.Group} group - The parent Group of this Sprite. This is usually set after Sprite instantiation by the parent. + * @property {Phaser.Group} group - The parent Group of this Text object. */ this.group = null; /** - * @property {string} name - The user defined name given to this Sprite. + * @property {string} name - The user defined name given to this object. * @default */ this.name = ''; @@ -70,8 +70,8 @@ Phaser.Text = function (game, x, y, text, style) { PIXI.Text.call(this, text, style); /** - * @property {Phaser.Point} position - The position of this Text object in world space. - */ + * @property {Phaser.Point} position - The position of this Text object in world space. + */ this.position.x = this.x = x; this.position.y = this.y = y; @@ -81,7 +81,7 @@ Phaser.Text = function (game, x, y, text, style) { * Setting than anchor to 0.5,0.5 means the textures origin is centered * Setting the anchor to 1,1 would mean the textures origin points will be the bottom right * - * @property {Phaser.Point} anchor - The anchor around with Sprite rotation and scaling takes place. + * @property {Phaser.Point} anchor - The anchor around which rotation and scaling takes place. */ this.anchor = new Phaser.Point(); @@ -182,11 +182,11 @@ Phaser.Text.prototype.destroy = function() { } /** -* Get -* @returns {Description} -*//** -* Set -* @param {Description} value - Description +* Indicates the rotation of the Text, in degrees, from its original orientation. Values from 0 to 180 represent clockwise rotation; values from 0 to -180 represent counterclockwise rotation. +* Values outside this range are added to or subtracted from 360 to obtain a value within the range. For example, the statement player.angle = 450 is the same as player.angle = 90. +* If you wish to work in radians instead of degrees use the property Sprite.rotation instead. +* @name Phaser.Text#angle +* @property {number} angle - Gets or sets the angle of rotation in degrees. */ Object.defineProperty(Phaser.Text.prototype, 'angle', { @@ -200,6 +200,45 @@ Object.defineProperty(Phaser.Text.prototype, 'angle', { }); +/** +* The x coordinate of this object in world space. +* @name Phaser.BitmapText#x +* @property {number} x - The x coordinate of this object in world space. +*/ +Object.defineProperty(Phaser.BitmapText.prototype, 'x', { + + get: function() { + return this.position.x; + }, + + set: function(value) { + this.position.x = value; + } + +}); + +/** +* The y coordinate of this object in world space. +* @name Phaser.BitmapText#y +* @property {number} y - The y coordinate of this object in world space. +*/ +Object.defineProperty(Phaser.BitmapText.prototype, 'y', { + + get: function() { + return this.position.y; + }, + + set: function(value) { + this.position.y = value; + } + +}); + +/** +* The string to be rendered by this Text object. +* @name Phaser.Text#content +* @property {string} content - The string to be rendered by this Text object. +*/ Object.defineProperty(Phaser.Text.prototype, 'content', { get: function() { @@ -219,6 +258,11 @@ Object.defineProperty(Phaser.Text.prototype, 'content', { }); +/** +* The font the text will be rendered in. +* @name Phaser.Text#font +* @property {string} font - The font the text will be rendered in. +*/ Object.defineProperty(Phaser.Text.prototype, 'font', { get: function() { diff --git a/src/geom/Circle.js b/src/geom/Circle.js index a1529cd4e..78b2765c3 100644 --- a/src/geom/Circle.js +++ b/src/geom/Circle.js @@ -39,9 +39,9 @@ Phaser.Circle = function (x, y, diameter) { if (diameter > 0) { /** - * @property {number} _radius - The radius of the circle. - * @private - */ + * @property {number} _radius - The radius of the circle. + * @private + */ this._radius = diameter * 0.5; } else diff --git a/src/geom/Point.js b/src/geom/Point.js index b03ca2878..3b090b5b8 100644 --- a/src/geom/Point.js +++ b/src/geom/Point.js @@ -233,29 +233,29 @@ Phaser.Point.prototype = { }, /** - * Calculates the length of the vector - * @method Phaser.Point#getMagnitude - * @return {number} the length of the vector - */ + * Calculates the length of the vector + * @method Phaser.Point#getMagnitude + * @return {number} the length of the vector + */ getMagnitude: function() { return Math.sqrt((this.x * this.x) + (this.y * this.y)); }, /** - * Alters the length of the vector without changing the direction - * @method Phaser.Point#getMagnitude - * @param {number} magnitude the desired magnitude of the resulting vector - * @return {Phaser.Point} the modified original vector - */ + * Alters the length of the vector without changing the direction + * @method Phaser.Point#getMagnitude + * @param {number} magnitude the desired magnitude of the resulting vector + * @return {Phaser.Point} the modified original vector + */ setMagnitude: function(magnitude) { return this.normalize().multiply(magnitude, magnitude); }, /** - * Alters the vector so that its length is 1, but it retains the same direction - * @method Phaser.Point#normalize - * @return {Phaser.Point} the modified original vector - */ + * Alters the vector so that its length is 1, but it retains the same direction + * @method Phaser.Point#normalize + * @return {Phaser.Point} the modified original vector + */ normalize: function() { if(!this.isZero()) { @@ -269,10 +269,10 @@ Phaser.Point.prototype = { }, /** - * 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); }, diff --git a/src/input/Input.js b/src/input/Input.js index 29f3a2836..42d3c0ef0 100644 --- a/src/input/Input.js +++ b/src/input/Input.js @@ -62,10 +62,10 @@ Phaser.Input.prototype = { pollRate: 0, /** - * @property {number} _pollCounter - Internal var holding the current poll counter. - * @private - * @default - */ + * @property {number} _pollCounter - Internal var holding the current poll counter. + * @private + * @default + */ _pollCounter: 0, /** diff --git a/src/input/Touch.js b/src/input/Touch.js index 1be40ee10..65c59e8bc 100644 --- a/src/input/Touch.js +++ b/src/input/Touch.js @@ -273,7 +273,7 @@ Phaser.Touch.prototype = { { //console.log('touch enter'); } - */ + */ }, @@ -302,7 +302,7 @@ Phaser.Touch.prototype = { { //console.log('touch leave'); } - */ + */ }, diff --git a/src/loader/Cache.js b/src/loader/Cache.js index 0481db686..ab380a3cf 100644 --- a/src/loader/Cache.js +++ b/src/loader/Cache.js @@ -16,44 +16,44 @@ Phaser.Cache = function (game) { /** - * @property {Phaser.Game} game - Local reference to game. - */ - this.game = game; + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = game; - /** - * @property {object} game - Canvas key-value container. - * @private - */ + /** + * @property {object} game - Canvas key-value container. + * @private + */ this._canvases = {}; /** - * @property {object} _images - Image key-value container. - * @private - */ + * @property {object} _images - Image key-value container. + * @private + */ this._images = {}; /** - * @property {object} _textures - RenderTexture key-value container. - * @private - */ + * @property {object} _textures - RenderTexture key-value container. + * @private + */ this._textures = {}; /** - * @property {object} _sounds - Sound key-value container. - * @private - */ + * @property {object} _sounds - Sound key-value container. + * @private + */ this._sounds = {}; /** - * @property {object} _text - Text key-value container. - * @private - */ + * @property {object} _text - Text key-value container. + * @private + */ this._text = {}; /** - * @property {object} _tilemaps - Tilemap key-value container. - * @private - */ + * @property {object} _tilemaps - Tilemap key-value container. + * @private + */ this._tilemaps = {}; /** @@ -72,9 +72,9 @@ Phaser.Cache = function (game) { this.addMissingImage(); /** - * @property {Phaser.Signal} onSoundUnlock - Description. - */ - this.onSoundUnlock = new Phaser.Signal; + * @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(); }; @@ -282,7 +282,7 @@ Phaser.Cache.prototype = { * @param {string} key - Asset key for the text data. * @param {string} url - URL of this text data file. * @param {object} data - Extra text data. - */ + */ addText: function (key, url, data) { this._text[key] = { @@ -326,7 +326,6 @@ Phaser.Cache.prototype = { webAudio = webAudio || true; audioTag = audioTag || false; - var locked = this.game.sound.touchLocked; var decoded = false; if (audioTag) @@ -388,13 +387,13 @@ Phaser.Cache.prototype = { }, - /** - * Add a new decoded sound. + /** + * Add a new decoded sound. * * @method Phaser.Cache#decodedSound - * @param {string} key - Asset key for the sound. - * @param {object} data - Extra sound data. - */ + * @param {string} key - Asset key for the sound. + * @param {object} data - Extra sound data. + */ decodedSound: function (key, data) { this._sounds[key].data = data; @@ -403,13 +402,13 @@ Phaser.Cache.prototype = { }, - /** - * Get a canvas object from the cache by its key. + /** + * Get a canvas object from the cache by its key. * * @method Phaser.Cache#getCanvas - * @param {string} key - Asset key of the canvas you want. - * @return {object} The canvas you want. - */ + * @param {string} key - Asset key of the canvas you want. + * @return {object} The canvas you want. + */ getCanvas: function (key) { if (this._canvases[key]) @@ -445,7 +444,7 @@ Phaser.Cache.prototype = { * @method Phaser.Cache#checkImageKey * @param {string} key - Asset key of the image you want. * @return {boolean} True if the key exists, otherwise false. - */ + */ checkImageKey: function (key) { if (this._images[key]) @@ -457,13 +456,13 @@ Phaser.Cache.prototype = { }, - /** - * Get image data by key. + /** + * Get image data by key. * * @method Phaser.Cache#getImage - * @param {string} key - Asset key of the image you want. - * @return {object} The image data you want. - */ + * @param {string} key - Asset key of the image you want. + * @return {object} The image data you want. + */ getImage: function (key) { if (this._images[key]) @@ -481,7 +480,7 @@ Phaser.Cache.prototype = { * @method Phaser.Cache#getTileSetImage * @param {string} key - Asset key of the image you want. * @return {object} The image data you want. - */ + */ getTilesetImage: function (key) { if (this._tilesets[key]) @@ -499,7 +498,7 @@ Phaser.Cache.prototype = { * @method Phaser.Cache#getTileset * @param {string} key - Asset key of the image you want. * @return {Phaser.Tileset} The tileset data. The tileset image is in the data property, the tile data in tileData. - */ + */ getTileset: function (key) { if (this._tilesets[key]) @@ -528,13 +527,13 @@ Phaser.Cache.prototype = { return null; }, - /** - * Get frame data by key. + /** + * Get frame data by key. * * @method Phaser.Cache#getFrameData - * @param {string} key - Asset key of the frame data you want. - * @return {Phaser.FrameData} The frame data you want. - */ + * @param {string} key - Asset key of the frame data you want. + * @return {Phaser.FrameData} The frame data you want. + */ getFrameData: function (key) { if (this._images[key] && this._images[key].frameData) @@ -631,13 +630,13 @@ Phaser.Cache.prototype = { }, - /** - * Get sound by key. + /** + * Get sound by key. * * @method Phaser.Cache#getSound - * @param {string} key - Asset key of the sound you want. - * @return {Phaser.Sound} The sound you want. - */ + * @param {string} key - Asset key of the sound you want. + * @return {Phaser.Sound} The sound you want. + */ getSound: function (key) { if (this._sounds[key]) @@ -649,13 +648,13 @@ Phaser.Cache.prototype = { }, - /** - * Get sound data by key. + /** + * Get sound data by key. * * @method Phaser.Cache#getSoundData - * @param {string} key - Asset key of the sound you want. - * @return {object} The sound data you want. - */ + * @param {string} key - Asset key of the sound you want. + * @return {object} The sound data you want. + */ getSoundData: function (key) { if (this._sounds[key]) @@ -667,13 +666,13 @@ Phaser.Cache.prototype = { }, - /** - * Check if the given sound has finished decoding. + /** + * Check if the given sound has finished decoding. * * @method Phaser.Cache#isSoundDecoded - * @param {string} key - Asset key of the sound you want. - * @return {boolean} The decoded state of the Sound object. - */ + * @param {string} key - Asset key of the sound you want. + * @return {boolean} The decoded state of the Sound object. + */ isSoundDecoded: function (key) { if (this._sounds[key]) @@ -683,26 +682,26 @@ Phaser.Cache.prototype = { }, - /** - * 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. + /** + * Check if the given sound is ready for playback. A sound is considered ready when it has finished decoding and the device is no longer touch locked. * * @method Phaser.Cache#isSoundReady - * @param {string} key - Asset key of the sound you want. - * @return {boolean} True if the sound is decoded and the device is not touch locked. - */ + * @param {string} key - Asset key of the sound you want. + * @return {boolean} True if the sound is decoded and the device is not touch locked. + */ isSoundReady: function (key) { return (this._sounds[key] && this._sounds[key].decoded && this.game.sound.touchLocked === false); }, - /** - * Check whether an image asset is sprite sheet or not. + /** + * Check whether an image asset is sprite sheet or not. * * @method Phaser.Cache#isSpriteSheet - * @param {string} key - Asset key of the sprite sheet you want. - * @return {boolean} True if the image is a sprite sheet. - */ + * @param {string} key - Asset key of the sprite sheet you want. + * @return {boolean} True if the image is a sprite sheet. + */ isSpriteSheet: function (key) { if (this._images[key]) @@ -714,13 +713,13 @@ Phaser.Cache.prototype = { }, - /** - * Get text data by key. + /** + * Get text data by key. * * @method Phaser.Cache#getText - * @param {string} key - Asset key of the text data you want. - * @return {object} The text data you want. - */ + * @param {string} key - Asset key of the text data you want. + * @return {object} The text data you want. + */ getText: function (key) { if (this._text[key]) @@ -756,42 +755,42 @@ Phaser.Cache.prototype = { }, - /** - * Returns an array containing all of the keys of Images in the Cache. + /** + * Returns an array containing all of the keys of Images in the Cache. * * @method Phaser.Cache#getImageKeys - * @return {Array} The string based keys in the Cache. - */ + * @return {Array} The string based keys in the Cache. + */ getImageKeys: function () { - return this.getKeys(this._images); + return this.getKeys(this._images); }, - /** - * Returns an array containing all of the keys of Sounds in the Cache. + /** + * Returns an array containing all of the keys of Sounds in the Cache. * * @method Phaser.Cache#getSoundKeys - * @return {Array} The string based keys in the Cache. - */ + * @return {Array} The string based keys in the Cache. + */ getSoundKeys: function () { - return this.getKeys(this._sounds); + return this.getKeys(this._sounds); }, - /** - * Returns an array containing all of the keys of Text Files in the Cache. + /** + * Returns an array containing all of the keys of Text Files in the Cache. * * @method Phaser.Cache#getTextKeys - * @return {Array} The string based keys in the Cache. - */ + * @return {Array} The string based keys in the Cache. + */ getTextKeys: function () { - return this.getKeys(this._text); + return this.getKeys(this._text); }, - /** - * Removes a canvas from the cache. + /** + * Removes a canvas from the cache. * - * @method Phaser.Cache#removeCanvas + * @method Phaser.Cache#removeCanvas * @param {string} key - Key of the asset you want to remove. - */ + */ removeCanvas: function (key) { delete this._canvases[key]; }, @@ -826,11 +825,11 @@ Phaser.Cache.prototype = { delete this._text[key]; }, - /** - * Clears the cache. Removes every local cache object reference. + /** + * Clears the cache. Removes every local cache object reference. * - * @method Phaser.Cache#destroy - */ + * @method Phaser.Cache#destroy + */ destroy: function () { for (var item in this._canvases) diff --git a/src/loader/Loader.js b/src/loader/Loader.js index e786415d5..ec79ce9e5 100644 --- a/src/loader/Loader.js +++ b/src/loader/Loader.js @@ -16,101 +16,101 @@ */ Phaser.Loader = function (game) { - /** + /** * @property {Phaser.Game} game - Local reference to game. - */ - this.game = game; - - /** - * @property {array} _keys - Array stores assets keys. So you can get that asset by its unique key. - * @private */ - this._keys = []; + this.game = game; - /** - * @property {Description} _fileList - Contains all the assets file infos. - * @private + /** + * @property {array} _keys - Array stores assets keys. So you can get that asset by its unique key. + * @private */ - this._fileList = {}; + this._keys = []; - /** - * @property {number} _progressChunk - Indicates assets loading progress. (from 0 to 100) - * @private - * @default - */ - this._progressChunk = 0; + /** + * @property {Description} _fileList - Contains all the assets file infos. + * @private + */ + this._fileList = {}; - /** - * @property {XMLHttpRequest} - An XMLHttpRequest object used for loading text and audio data. - * @private - */ - this._xhr = new XMLHttpRequest(); + /** + * @property {number} _progressChunk - Indicates assets loading progress. (from 0 to 100) + * @private + * @default + */ + this._progressChunk = 0; - /** - * @property {number} - Length of assets queue. - * @default - */ - this.queueSize = 0; + /** + * @property {XMLHttpRequest} - An XMLHttpRequest object used for loading text and audio data. + * @private + */ + this._xhr = new XMLHttpRequest(); - /** - * @property {boolean} isLoading - True if the Loader is in the process of loading the queue. - * @default - */ - this.isLoading = false; + /** + * @property {number} - Length of assets queue. + * @default + */ + this.queueSize = 0; - /** - * @property {boolean} hasLoaded - True if all assets in the queue have finished loading. - * @default - */ - this.hasLoaded = false; + /** + * @property {boolean} isLoading - True if the Loader is in the process of loading the queue. + * @default + */ + this.isLoading = false; - /** - * @property {number} progress - The Load progress percentage value (from 0 to 100) - * @default - */ - this.progress = 0; + /** + * @property {boolean} hasLoaded - True if all assets in the queue have finished loading. + * @default + */ + this.hasLoaded = false; - /** - * You can optionally link a sprite to the preloader. - * If you do so the Sprite's width or height will be cropped based on the percentage loaded. - * @property {Description} preloadSprite - * @default - */ - this.preloadSprite = null; + /** + * @property {number} progress - The Load progress percentage value (from 0 to 100) + * @default + */ + this.progress = 0; - /** - * @property {string} crossOrigin - The crossOrigin value applied to loaded images - */ - this.crossOrigin = ''; + /** + * You can optionally link a sprite to the preloader. + * If you do so the Sprite's width or height will be cropped based on the percentage loaded. + * @property {Description} preloadSprite + * @default + */ + this.preloadSprite = null; - /** - * If you want to append a URL before the path of any asset you can set this here. - * Useful if you need to allow an asset url to be configured outside of the game code. - * MUST have / on the end of it! - * @property {string} baseURL - * @default - */ - this.baseURL = ''; + /** + * @property {string} crossOrigin - The crossOrigin value applied to loaded images + */ + this.crossOrigin = ''; - /** - * @property {Phaser.Signal} onFileComplete - Event signal. - */ - this.onFileComplete = new Phaser.Signal; - - /** - * @property {Phaser.Signal} onFileError - Event signal. - */ - this.onFileError = new Phaser.Signal; - - /** - * @property {Phaser.Signal} onLoadStart - Event signal. - */ - this.onLoadStart = new Phaser.Signal; - - /** - * @property {Phaser.Signal} onLoadComplete - Event signal. - */ - this.onLoadComplete = new Phaser.Signal; + /** + * If you want to append a URL before the path of any asset you can set this here. + * Useful if you need to allow an asset url to be configured outside of the game code. + * MUST have / on the end of it! + * @property {string} baseURL + * @default + */ + this.baseURL = ''; + + /** + * @property {Phaser.Signal} onFileComplete - Event signal. + */ + this.onFileComplete = new Phaser.Signal(); + + /** + * @property {Phaser.Signal} onFileError - Event signal. + */ + this.onFileError = new Phaser.Signal(); + + /** + * @property {Phaser.Signal} onLoadStart - Event signal. + */ + this.onLoadStart = new Phaser.Signal(); + + /** + * @property {Phaser.Signal} onLoadComplete - Event signal. + */ + this.onLoadComplete = new Phaser.Signal(); }; @@ -134,985 +134,985 @@ Phaser.Loader.TEXTURE_ATLAS_XML_STARLING = 2; Phaser.Loader.prototype = { - /** - * You can set a Sprite to be a "preload" sprite by passing it to this method. - * A "preload" sprite will have its width or height crop adjusted based on the percentage of the loader in real-time. - * This allows you to easily make loading bars for games. - * - * @method Phaser.Loader#setPreloadSprite + /** + * You can set a Sprite to be a "preload" sprite by passing it to this method. + * A "preload" sprite will have its width or height crop adjusted based on the percentage of the loader in real-time. + * This allows you to easily make loading bars for games. + * + * @method Phaser.Loader#setPreloadSprite * @param {Phaser.Sprite} sprite - The sprite that will be cropped during the load. * @param {number} [direction=0] - A value of zero means the sprite width will be cropped, a value of 1 means its height will be cropped. */ - setPreloadSprite: function (sprite, direction) { - - direction = direction || 0; - - this.preloadSprite = { sprite: sprite, direction: direction, width: sprite.width, height: sprite.height, crop: null }; - - if (direction === 0) - { - // Horizontal crop - this.preloadSprite.crop = new Phaser.Rectangle(0, 0, 1, sprite.height); - } - else - { - // Vertical crop - this.preloadSprite.crop = new Phaser.Rectangle(0, 0, sprite.width, 1); - } - - sprite.crop = this.preloadSprite.crop; - sprite.cropEnabled = true; - - }, - - /** - * Check whether asset exists with a specific key. - * - * @method Phaser.Loader#checkKeyExists - * @param {string} key - Key of the asset you want to check. - * @return {boolean} Return true if exists, otherwise return false. - */ - checkKeyExists: function (key) { - - if (this._fileList[key]) - { - return true; - } - else - { - return false; - } - - }, - - /** - * Reset loader, this will remove all loaded assets. - * - * @method Phaser.Loader#reset - */ - reset: function () { - - this.preloadSprite = null; - this.queueSize = 0; - this.isLoading = false; - - }, - - /** - * Internal function that adds a new entry to the file list. Do not call directly. - * - * @method Phaser.Loader#addToFileList - * @param {Description} type - Description. - * @param {string} key - Description. - * @param {string} url - URL of Description. - * @param {Description} properties - Description. - * @protected - */ - addToFileList: function (type, key, url, properties) { - - var entry = { - type: type, - key: key, - url: url, - data: null, - error: false, - loaded: false - }; - - if (typeof properties !== "undefined") - { - for (var prop in properties) - { - entry[prop] = properties[prop]; - } - } - - this._fileList[key] = entry; - - this._keys.push(key); - - this.queueSize++; - - }, - - /** - * Add an image to the Loader. - * - * @method Phaser.Loader#image - * @param {string} key - Unique asset key of this image file. - * @param {string} url - URL of image file. - * @param {boolean} overwrite - If an entry with a matching key already exists this will over-write it - */ - image: function (key, url, overwrite) { - - if (typeof overwrite === "undefined") { overwrite = false; } - - if (overwrite || this.checkKeyExists(key) === false) - { - this.addToFileList('image', key, url); - } - - return this; - - }, - - /** - * Add a text file to the Loader. - * - * @method Phaser.Loader#text - * @param {string} key - Unique asset key of the text file. - * @param {string} url - URL of the text file. - * @param {boolean} overwrite - True if Description. - */ - text: function (key, url, overwrite) { - - if (typeof overwrite === "undefined") { overwrite = false; } - - if (overwrite || this.checkKeyExists(key) === false) - { - this.addToFileList('text', key, url); - } - - return this; - - }, - - /** - * Add a new sprite sheet to the loader. - * - * @method Phaser.Loader#spritesheet - * @param {string} key - Unique asset key of the sheet file. - * @param {string} url - URL of the sheet file. - * @param {number} frameWidth - Width of each single frame. - * @param {number} frameHeight - Height of each single frame. - * @param {number} [frameMax=-1] - How many frames in this sprite sheet. If not specified it will divide the whole image into frames. - */ - spritesheet: function (key, url, frameWidth, frameHeight, frameMax) { - - if (typeof frameMax === "undefined") { frameMax = -1; } - - if (this.checkKeyExists(key) === false) - { - this.addToFileList('spritesheet', key, url, { frameWidth: frameWidth, frameHeight: frameHeight, frameMax: frameMax }); - } - - return this; - - }, - - /** - * Add a new tile set to the loader. These are used in the rendering of tile maps. - * - * @method Phaser.Loader#tileset - * @param {string} key - Unique asset key of the tileset file. - * @param {string} url - URL of the tileset. - * @param {number} tileWidth - Width of each single tile in pixels. - * @param {number} tileHeight - Height of each single tile in pixels. - * @param {number} [tileMax=-1] - How many tiles in this tileset. If not specified it will divide the whole image into tiles. - * @param {number} [tileMargin=0] - If the tiles have been drawn with a margin, specify the amount here. - * @param {number} [tileSpacing=0] - If the tiles have been drawn with spacing between them, specify the amount here. - */ - tileset: function (key, url, tileWidth, tileHeight, tileMax, tileMargin, tileSpacing) { - - if (typeof tileMax === "undefined") { tileMax = -1; } - if (typeof tileMargin === "undefined") { tileMargin = 0; } - if (typeof tileSpacing === "undefined") { tileSpacing = 0; } - - if (this.checkKeyExists(key) === false) - { - this.addToFileList('tileset', key, url, { tileWidth: tileWidth, tileHeight: tileHeight, tileMax: tileMax, tileMargin: tileMargin, tileSpacing: tileSpacing }); - } - - return this; - - }, - - /** - * Add a new audio file to the loader. - * - * @method Phaser.Loader#audio - * @param {string} key - Unique asset key of the audio file. - * @param {Array|string} urls - An array containing the URLs of the audio files, i.e.: [ 'jump.mp3', 'jump.ogg', 'jump.m4a' ] or a single string containing just one URL. - * @param {boolean} autoDecode - When using Web Audio the audio files can either be decoded at load time or run-time. They can't be played until they are decoded, but this let's you control when that happens. Decoding is a non-blocking async process. - */ - audio: function (key, urls, autoDecode) { - - if (typeof autoDecode === "undefined") { autoDecode = true; } - - if (this.checkKeyExists(key) === false) - { - this.addToFileList('audio', key, urls, { buffer: null, autoDecode: autoDecode }); - } - - return this; - - }, - - /** - * Add a new tilemap loading request. - * - * @method Phaser.Loader#tilemap - * @param {string} key - Unique asset key of the tilemap data. - * @param {string} tilesetURL - The url of the tile set image file. - * @param {string} [mapDataURL] - The url of the map data file (csv/json) - * @param {object} [mapData] - An optional JSON data object (can be given in place of a URL). - * @param {string} [format] - The format of the map data. - */ - tilemap: function (key, mapDataURL, mapData, format) { - - if (typeof mapDataURL === "undefined") { mapDataURL = null; } - if (typeof mapData === "undefined") { mapData = null; } - if (typeof format === "undefined") { format = Phaser.Tilemap.CSV; } - - if (mapDataURL == null && mapData == null) - { - console.warn('Phaser.Loader.tilemap - Both mapDataURL and mapData are null. One must be set.'); - - return this; - } - - if (this.checkKeyExists(key) === false) - { - // A URL to a json/csv file has been given - if (mapDataURL) - { - this.addToFileList('tilemap', key, mapDataURL, { format: format }); - } - else - { - switch (format) - { - // A csv string or object has been given - case Phaser.Tilemap.CSV: - break; - - // An xml string or object has been given - case Phaser.Tilemap.TILED_JSON: - - if (typeof mapData === 'string') - { - mapData = JSON.parse(mapData); - } - break; - } - - this.game.cache.addTilemap(key, null, mapData, format); - - } - } - - return this; - - }, - - /** - * Add a new bitmap font loading request. - * - * @method Phaser.Loader#bitmapFont - * @param {string} key - Unique asset key of the bitmap font. - * @param {string} textureURL - The url of the font image file. - * @param {string} [xmlURL] - The url of the font data file (xml/fnt) - * @param {object} [xmlData] - An optional XML data object. - */ - bitmapFont: function (key, textureURL, xmlURL, xmlData) { - - if (typeof xmlURL === "undefined") { xmlURL = null; } - if (typeof xmlData === "undefined") { xmlData = null; } - - if (this.checkKeyExists(key) === false) - { - // A URL to a json/xml file has been given - if (xmlURL) - { - this.addToFileList('bitmapfont', key, textureURL, { xmlURL: xmlURL }); - } - else - { - // An xml string or object has been given - if (typeof xmlData === 'string') - { - var xml; - - try { - if (window['DOMParser']) - { - var domparser = new DOMParser(); - xml = domparser.parseFromString(xmlData, "text/xml"); - } - else - { - xml = new ActiveXObject("Microsoft.XMLDOM"); - xml.async = 'false'; - xml.loadXML(xmlData); - } - } - catch (e) - { - xml = undefined; - } - - if (!xml || !xml.documentElement || xml.getElementsByTagName("parsererror").length) - { - throw new Error("Phaser.Loader. Invalid Bitmap Font XML given"); - } - else - { - this.addToFileList('bitmapfont', key, textureURL, { xmlURL: null, xmlData: xml }); - } - } - } - } - - return this; - - }, - - /** - * Add a new texture atlas to the loader. This atlas uses the JSON Array data format. - * - * @method Phaser.Loader#atlasJSONArray - * @param {string} key - Unique asset key of the bitmap font. - * @param {Description} atlasURL - The url of the Description. - * @param {Description} atlasData - Description. - */ - atlasJSONArray: function (key, textureURL, atlasURL, atlasData) { - - return this.atlas(key, textureURL, atlasURL, atlasData, Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY); - - }, - - /** - * Add a new texture atlas to the loader. This atlas uses the JSON Hash data format. - * - * @method Phaser.Loader#atlasJSONHash - * @param {string} key - Unique asset key of the bitmap font. - * @param {Description} atlasURL - The url of the Description. - * @param {Description} atlasData - Description. - */ - atlasJSONHash: function (key, textureURL, atlasURL, atlasData) { - - return this.atlas(key, textureURL, atlasURL, atlasData, Phaser.Loader.TEXTURE_ATLAS_JSON_HASH); - - }, - - /** - * Add a new texture atlas to the loader. This atlas uses the Starling XML data format. - * - * @method Phaser.Loader#atlasXML - * @param {string} key - Unique asset key of the bitmap font. - * @param {Description} atlasURL - The url of the Description. - * @param {Description} atlasData - Description. - */ - atlasXML: function (key, textureURL, atlasURL, atlasData) { - - return this.atlas(key, textureURL, atlasURL, atlasData, Phaser.Loader.TEXTURE_ATLAS_XML_STARLING); - - }, - - /** - * Add a new texture atlas to the loader. - * - * @method Phaser.Loader#atlas - * @param {string} key - Unique asset key of the texture atlas file. - * @param {string} textureURL - The url of the texture atlas image file. - * @param {string} [atlasURL] - The url of the texture atlas data file (json/xml). You don't need this if you are passing an atlasData object instead. - * @param {object} [atlasData] - A JSON or XML data object. You don't need this if the data is being loaded from a URL. - * @param {number} [format] - A value describing the format of the data, the default is Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY. - */ - atlas: function (key, textureURL, atlasURL, atlasData, format) { - - if (typeof atlasURL === "undefined") { atlasURL = null; } - if (typeof atlasData === "undefined") { atlasData = null; } - if (typeof format === "undefined") { format = Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY; } - - if (this.checkKeyExists(key) === false) - { - // A URL to a json/xml file has been given - if (atlasURL) - { - this.addToFileList('textureatlas', key, textureURL, { atlasURL: atlasURL, format: format }); - } - else - { - switch (format) - { - // A json string or object has been given - case Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY: - - if (typeof atlasData === 'string') - { - atlasData = JSON.parse(atlasData); - } - break; - - // An xml string or object has been given - case Phaser.Loader.TEXTURE_ATLAS_XML_STARLING: - - if (typeof atlasData === 'string') - { - var xml; - - try { - if (window['DOMParser']) - { - var domparser = new DOMParser(); - xml = domparser.parseFromString(atlasData, "text/xml"); - } - else - { - xml = new ActiveXObject("Microsoft.XMLDOM"); - xml.async = 'false'; - xml.loadXML(atlasData); - } - } - catch (e) - { - xml = undefined; - } - - if (!xml || !xml.documentElement || xml.getElementsByTagName("parsererror").length) - { - throw new Error("Phaser.Loader. Invalid Texture Atlas XML given"); - } - else - { - atlasData = xml; - } - } - break; - } - - this.addToFileList('textureatlas', key, textureURL, { atlasURL: null, atlasData: atlasData, format: format }); - - } - - } - - return this; - - }, - - /** - * Remove loading request of a file. - * - * @method Phaser.Loader#removeFile - * @param key {string} Key of the file you want to remove. - */ - removeFile: function (key) { - - delete this._fileList[key]; - - }, - - /** - * Remove all file loading requests. - * - * @method Phaser.Loader#removeAll - */ - removeAll: function () { - - this._fileList = {}; - - }, - - /** - * Start loading the assets. Normally you don't need to call this yourself as the StateManager will do so. - * - * @method Phaser.Loader#start - */ - start: function () { - - if (this.isLoading) - { - return; - } - - this.progress = 0; - this.hasLoaded = false; - this.isLoading = true; - - this.onLoadStart.dispatch(this.queueSize); - - if (this._keys.length > 0) - { - this._progressChunk = 100 / this._keys.length; - this.loadFile(); - } - else - { - this.progress = 100; - this.hasLoaded = true; - this.onLoadComplete.dispatch(); - } - - }, - - /** - * Load files. Private method ONLY used by loader. - * - * @method Phaser.Loader#loadFile - * @private - */ - loadFile: function () { - - var file = this._fileList[this._keys.shift()]; - var _this = this; - - // Image or Data? - switch (file.type) - { - case 'image': - case 'spritesheet': - case 'textureatlas': - case 'bitmapfont': - case 'tileset': - file.data = new Image(); - file.data.name = file.key; - file.data.onload = function () { - return _this.fileComplete(file.key); - }; - file.data.onerror = function () { - return _this.fileError(file.key); - }; - file.data.crossOrigin = this.crossOrigin; - file.data.src = this.baseURL + file.url; - break; - - case 'audio': - file.url = this.getAudioURL(file.url); - - if (file.url !== null) - { - // WebAudio or Audio Tag? - if (this.game.sound.usingWebAudio) - { - this._xhr.open("GET", this.baseURL + file.url, true); - this._xhr.responseType = "arraybuffer"; - this._xhr.onload = function () { - return _this.fileComplete(file.key); - }; - this._xhr.onerror = function () { - return _this.fileError(file.key); - }; - this._xhr.send(); - } - else if (this.game.sound.usingAudioTag) - { - if (this.game.sound.touchLocked) - { - // If audio is locked we can't do this yet, so need to queue this load request. Bum. - file.data = new Audio(); - file.data.name = file.key; - file.data.preload = 'auto'; - file.data.src = this.baseURL + file.url; - this.fileComplete(file.key); - } - else - { - file.data = new Audio(); - file.data.name = file.key; - file.data.onerror = function () { - return _this.fileError(file.key); - }; - file.data.preload = 'auto'; - file.data.src = this.baseURL + file.url; - file.data.addEventListener('canplaythrough', Phaser.GAMES[this.game.id].load.fileComplete(file.key), false); - file.data.load(); - } - } - } - else - { - this.fileError(file.key); - } - - break; - - case 'tilemap': - this._xhr.open("GET", this.baseURL + file.url, true); - this._xhr.responseType = "text"; - - if (file.format == Phaser.Tilemap.TILED_JSON) - { - this._xhr.onload = function () { - return _this.jsonLoadComplete(file.key); - }; - } - else if (file.format == Phaser.Tilemap.CSV) - { - this._xhr.onload = function () { - return _this.csvLoadComplete(file.key); - }; - } - else - { - throw new Error("Phaser.Loader. Invalid Tilemap format: " + file.format); - } - - this._xhr.onerror = function () { - return _this.dataLoadError(file.key); - }; - this._xhr.send(); - break; - - case 'text': - this._xhr.open("GET", this.baseURL + file.url, true); - this._xhr.responseType = "text"; - this._xhr.onload = function () { - return _this.fileComplete(file.key); - }; - this._xhr.onerror = function () { - return _this.fileError(file.key); - }; - this._xhr.send(); - break; - } - - }, - - /** - * Private method ONLY used by loader. - * @method Phaser.Loader#getAudioURL - * @param {array|string} urls - Either an array of audio file URLs or a string containing a single URL path. - * @private - */ - getAudioURL: function (urls) { - - var extension; - - if (typeof urls === 'string') { urls = [urls]; } - - for (var i = 0; i < urls.length; i++) - { - extension = urls[i].toLowerCase(); - extension = extension.substr((Math.max(0, extension.lastIndexOf(".")) || Infinity) + 1); - - if (this.game.device.canPlayAudio(extension)) - { - return urls[i]; - } - - } - - return null; - - }, - - /** - * Error occured when load a file. - * - * @method Phaser.Loader#fileError - * @param {string} key - Key of the error loading file. - */ - fileError: function (key) { - - this._fileList[key].loaded = true; - this._fileList[key].error = true; - - this.onFileError.dispatch(key); - - console.warn("Phaser.Loader error loading file: " + key + ' from URL ' + this._fileList[key].url); - - this.nextFile(key, false); - - }, - - /** - * Called when a file is successfully loaded. - * - * @method Phaser.Loader#fileComplete - * @param {string} key - Key of the successfully loaded file. - */ - fileComplete: function (key) { - - if (!this._fileList[key]) - { - console.warn('Phaser.Loader fileComplete invalid key ' + key); - return; - } - - this._fileList[key].loaded = true; - - var file = this._fileList[key]; - var loadNext = true; - var _this = this; - - switch (file.type) - { - case 'image': - - this.game.cache.addImage(file.key, file.url, file.data); - break; - - case 'spritesheet': - - this.game.cache.addSpriteSheet(file.key, file.url, file.data, file.frameWidth, file.frameHeight, file.frameMax); - break; - - case 'tileset': - - this.game.cache.addTileset(file.key, file.url, file.data, file.tileWidth, file.tileHeight, file.tileMax, file.tileMargin, file.tileSpacing); - break; - - case 'textureatlas': - - if (file.atlasURL == null) - { - this.game.cache.addTextureAtlas(file.key, file.url, file.data, file.atlasData, file.format); - } - else - { - // Load the JSON or XML before carrying on with the next file - loadNext = false; - this._xhr.open("GET", this.baseURL + file.atlasURL, true); - this._xhr.responseType = "text"; - - if (file.format == Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY || file.format == Phaser.Loader.TEXTURE_ATLAS_JSON_HASH) - { - this._xhr.onload = function () { - return _this.jsonLoadComplete(file.key); - }; - } - else if (file.format == Phaser.Loader.TEXTURE_ATLAS_XML_STARLING) - { - this._xhr.onload = function () { - return _this.xmlLoadComplete(file.key); - }; - } - else - { - throw new Error("Phaser.Loader. Invalid Texture Atlas format: " + file.format); - } - - this._xhr.onerror = function () { - return _this.dataLoadError(file.key); - }; - this._xhr.send(); - } - break; - - case 'bitmapfont': - - if (file.xmlURL == null) - { - this.game.cache.addBitmapFont(file.key, file.url, file.data, file.xmlData); - } - else - { - // Load the XML before carrying on with the next file - loadNext = false; - this._xhr.open("GET", this.baseURL + file.xmlURL, true); - this._xhr.responseType = "text"; - - this._xhr.onload = function () { - return _this.xmlLoadComplete(file.key); - }; - - this._xhr.onerror = function () { - return _this.dataLoadError(file.key); - }; - this._xhr.send(); - } - break; - - case 'audio': - - if (this.game.sound.usingWebAudio) - { - file.data = this._xhr.response; - - this.game.cache.addSound(file.key, file.url, file.data, true, false); - - if (file.autoDecode) - { - this.game.cache.updateSound(key, 'isDecoding', true); - - var that = this; - var key = file.key; - - this.game.sound.context.decodeAudioData(file.data, function (buffer) { - if (buffer) - { - that.game.cache.decodedSound(key, buffer); - } - }); - } - } - else - { - file.data.removeEventListener('canplaythrough', Phaser.GAMES[this.game.id].load.fileComplete); - this.game.cache.addSound(file.key, file.url, file.data, false, true); - } - break; - - case 'text': - file.data = this._xhr.responseText; - this.game.cache.addText(file.key, file.url, file.data); - break; - } - - if (loadNext) - { - this.nextFile(key, true); - } - - }, - - /** - * Successfully loaded a JSON file. - * - * @method Phaser.Loader#jsonLoadComplete - * @param {string} key - Key of the loaded JSON file. - */ - jsonLoadComplete: function (key) { - - var data = JSON.parse(this._xhr.responseText); - var file = this._fileList[key]; - - if (file.type == 'tilemap') - { - this.game.cache.addTilemap(file.key, file.url, data, file.format); - } - else - { - this.game.cache.addTextureAtlas(file.key, file.url, file.data, data, file.format); - } - - this.nextFile(key, true); - - }, - - /** - * Successfully loaded a CSV file. - * - * @method Phaser.Loader#csvLoadComplete - * @param {string} key - Key of the loaded CSV file. - */ - csvLoadComplete: function (key) { - - var data = this._xhr.responseText; - var file = this._fileList[key]; - - this.game.cache.addTilemap(file.key, file.url, data, file.format); - - this.nextFile(key, true); - - }, - - /** - * Error occured when load a JSON. - * - * @method Phaser.Loader#dataLoadError - * @param {string} key - Key of the error loading JSON file. - */ - dataLoadError: function (key) { - - var file = this._fileList[key]; - - file.error = true; - - console.warn("Phaser.Loader dataLoadError: " + key); - - this.nextFile(key, true); - - }, - - /** - * Successfully loaded an XML file. - * - * @method Phaser.Loader#xmlLoadComplete - * @param {string} key - Key of the loaded XML file. - */ - xmlLoadComplete: function (key) { - - var data = this._xhr.responseText; - var xml; - - try - { - if (window['DOMParser']) - { - var domparser = new DOMParser(); - xml = domparser.parseFromString(data, "text/xml"); - } - else - { - xml = new ActiveXObject("Microsoft.XMLDOM"); - xml.async = 'false'; - xml.loadXML(data); - } - } - catch (e) - { - xml = undefined; - } - - if (!xml || !xml.documentElement || xml.getElementsByTagName("parsererror").length) - { - throw new Error("Phaser.Loader. Invalid XML given"); - } - - var file = this._fileList[key]; - - if (file.type == 'bitmapfont') - { - this.game.cache.addBitmapFont(file.key, file.url, file.data, xml); - } - else if (file.type == 'textureatlas') - { - this.game.cache.addTextureAtlas(file.key, file.url, file.data, xml, file.format); - } - - this.nextFile(key, true); - - }, - - /** - * Handle loading next file. - * - * @param previousKey {string} Key of previous loaded asset. - * @param success {boolean} Whether the previous asset loaded successfully or not. - * @private - */ - nextFile: function (previousKey, success) { - - this.progress = Math.round(this.progress + this._progressChunk); - - if (this.progress > 100) - { - this.progress = 100; - } - - if (this.preloadSprite !== null) - { - if (this.preloadSprite.direction === 0) - { - this.preloadSprite.crop.width = Math.floor((this.preloadSprite.width / 100) * this.progress); - } - else - { - this.preloadSprite.crop.height = Math.floor((this.preloadSprite.height / 100) * this.progress); - } - - this.preloadSprite.sprite.crop = this.preloadSprite.crop; - } - - this.onFileComplete.dispatch(this.progress, previousKey, success, this.queueSize - this._keys.length, this.queueSize); - - if (this._keys.length > 0) - { - this.loadFile(); - } - else - { - this.hasLoaded = true; - this.isLoading = false; - - this.removeAll(); - - this.onLoadComplete.dispatch(); - } - - } + setPreloadSprite: function (sprite, direction) { + + direction = direction || 0; + + this.preloadSprite = { sprite: sprite, direction: direction, width: sprite.width, height: sprite.height, crop: null }; + + if (direction === 0) + { + // Horizontal crop + this.preloadSprite.crop = new Phaser.Rectangle(0, 0, 1, sprite.height); + } + else + { + // Vertical crop + this.preloadSprite.crop = new Phaser.Rectangle(0, 0, sprite.width, 1); + } + + sprite.crop = this.preloadSprite.crop; + sprite.cropEnabled = true; + + }, + + /** + * Check whether asset exists with a specific key. + * + * @method Phaser.Loader#checkKeyExists + * @param {string} key - Key of the asset you want to check. + * @return {boolean} Return true if exists, otherwise return false. + */ + checkKeyExists: function (key) { + + if (this._fileList[key]) + { + return true; + } + else + { + return false; + } + + }, + + /** + * Reset loader, this will remove all loaded assets. + * + * @method Phaser.Loader#reset + */ + reset: function () { + + this.preloadSprite = null; + this.queueSize = 0; + this.isLoading = false; + + }, + + /** + * Internal function that adds a new entry to the file list. Do not call directly. + * + * @method Phaser.Loader#addToFileList + * @param {Description} type - Description. + * @param {string} key - Description. + * @param {string} url - URL of Description. + * @param {Description} properties - Description. + * @protected + */ + addToFileList: function (type, key, url, properties) { + + var entry = { + type: type, + key: key, + url: url, + data: null, + error: false, + loaded: false + }; + + if (typeof properties !== "undefined") + { + for (var prop in properties) + { + entry[prop] = properties[prop]; + } + } + + this._fileList[key] = entry; + + this._keys.push(key); + + this.queueSize++; + + }, + + /** + * Add an image to the Loader. + * + * @method Phaser.Loader#image + * @param {string} key - Unique asset key of this image file. + * @param {string} url - URL of image file. + * @param {boolean} overwrite - If an entry with a matching key already exists this will over-write it + */ + image: function (key, url, overwrite) { + + if (typeof overwrite === "undefined") { overwrite = false; } + + if (overwrite || this.checkKeyExists(key) === false) + { + this.addToFileList('image', key, url); + } + + return this; + + }, + + /** + * Add a text file to the Loader. + * + * @method Phaser.Loader#text + * @param {string} key - Unique asset key of the text file. + * @param {string} url - URL of the text file. + * @param {boolean} overwrite - True if Description. + */ + text: function (key, url, overwrite) { + + if (typeof overwrite === "undefined") { overwrite = false; } + + if (overwrite || this.checkKeyExists(key) === false) + { + this.addToFileList('text', key, url); + } + + return this; + + }, + + /** + * Add a new sprite sheet to the loader. + * + * @method Phaser.Loader#spritesheet + * @param {string} key - Unique asset key of the sheet file. + * @param {string} url - URL of the sheet file. + * @param {number} frameWidth - Width of each single frame. + * @param {number} frameHeight - Height of each single frame. + * @param {number} [frameMax=-1] - How many frames in this sprite sheet. If not specified it will divide the whole image into frames. + */ + spritesheet: function (key, url, frameWidth, frameHeight, frameMax) { + + if (typeof frameMax === "undefined") { frameMax = -1; } + + if (this.checkKeyExists(key) === false) + { + this.addToFileList('spritesheet', key, url, { frameWidth: frameWidth, frameHeight: frameHeight, frameMax: frameMax }); + } + + return this; + + }, + + /** + * Add a new tile set to the loader. These are used in the rendering of tile maps. + * + * @method Phaser.Loader#tileset + * @param {string} key - Unique asset key of the tileset file. + * @param {string} url - URL of the tileset. + * @param {number} tileWidth - Width of each single tile in pixels. + * @param {number} tileHeight - Height of each single tile in pixels. + * @param {number} [tileMax=-1] - How many tiles in this tileset. If not specified it will divide the whole image into tiles. + * @param {number} [tileMargin=0] - If the tiles have been drawn with a margin, specify the amount here. + * @param {number} [tileSpacing=0] - If the tiles have been drawn with spacing between them, specify the amount here. + */ + tileset: function (key, url, tileWidth, tileHeight, tileMax, tileMargin, tileSpacing) { + + if (typeof tileMax === "undefined") { tileMax = -1; } + if (typeof tileMargin === "undefined") { tileMargin = 0; } + if (typeof tileSpacing === "undefined") { tileSpacing = 0; } + + if (this.checkKeyExists(key) === false) + { + this.addToFileList('tileset', key, url, { tileWidth: tileWidth, tileHeight: tileHeight, tileMax: tileMax, tileMargin: tileMargin, tileSpacing: tileSpacing }); + } + + return this; + + }, + + /** + * Add a new audio file to the loader. + * + * @method Phaser.Loader#audio + * @param {string} key - Unique asset key of the audio file. + * @param {Array|string} urls - An array containing the URLs of the audio files, i.e.: [ 'jump.mp3', 'jump.ogg', 'jump.m4a' ] or a single string containing just one URL. + * @param {boolean} autoDecode - When using Web Audio the audio files can either be decoded at load time or run-time. They can't be played until they are decoded, but this let's you control when that happens. Decoding is a non-blocking async process. + */ + audio: function (key, urls, autoDecode) { + + if (typeof autoDecode === "undefined") { autoDecode = true; } + + if (this.checkKeyExists(key) === false) + { + this.addToFileList('audio', key, urls, { buffer: null, autoDecode: autoDecode }); + } + + return this; + + }, + + /** + * Add a new tilemap loading request. + * + * @method Phaser.Loader#tilemap + * @param {string} key - Unique asset key of the tilemap data. + * @param {string} tilesetURL - The url of the tile set image file. + * @param {string} [mapDataURL] - The url of the map data file (csv/json) + * @param {object} [mapData] - An optional JSON data object (can be given in place of a URL). + * @param {string} [format] - The format of the map data. + */ + tilemap: function (key, mapDataURL, mapData, format) { + + if (typeof mapDataURL === "undefined") { mapDataURL = null; } + if (typeof mapData === "undefined") { mapData = null; } + if (typeof format === "undefined") { format = Phaser.Tilemap.CSV; } + + if (mapDataURL == null && mapData == null) + { + console.warn('Phaser.Loader.tilemap - Both mapDataURL and mapData are null. One must be set.'); + + return this; + } + + if (this.checkKeyExists(key) === false) + { + // A URL to a json/csv file has been given + if (mapDataURL) + { + this.addToFileList('tilemap', key, mapDataURL, { format: format }); + } + else + { + switch (format) + { + // A csv string or object has been given + case Phaser.Tilemap.CSV: + break; + + // An xml string or object has been given + case Phaser.Tilemap.TILED_JSON: + + if (typeof mapData === 'string') + { + mapData = JSON.parse(mapData); + } + break; + } + + this.game.cache.addTilemap(key, null, mapData, format); + + } + } + + return this; + + }, + + /** + * Add a new bitmap font loading request. + * + * @method Phaser.Loader#bitmapFont + * @param {string} key - Unique asset key of the bitmap font. + * @param {string} textureURL - The url of the font image file. + * @param {string} [xmlURL] - The url of the font data file (xml/fnt) + * @param {object} [xmlData] - An optional XML data object. + */ + bitmapFont: function (key, textureURL, xmlURL, xmlData) { + + if (typeof xmlURL === "undefined") { xmlURL = null; } + if (typeof xmlData === "undefined") { xmlData = null; } + + if (this.checkKeyExists(key) === false) + { + // A URL to a json/xml file has been given + if (xmlURL) + { + this.addToFileList('bitmapfont', key, textureURL, { xmlURL: xmlURL }); + } + else + { + // An xml string or object has been given + if (typeof xmlData === 'string') + { + var xml; + + try { + if (window['DOMParser']) + { + var domparser = new DOMParser(); + xml = domparser.parseFromString(xmlData, "text/xml"); + } + else + { + xml = new ActiveXObject("Microsoft.XMLDOM"); + xml.async = 'false'; + xml.loadXML(xmlData); + } + } + catch (e) + { + xml = undefined; + } + + if (!xml || !xml.documentElement || xml.getElementsByTagName("parsererror").length) + { + throw new Error("Phaser.Loader. Invalid Bitmap Font XML given"); + } + else + { + this.addToFileList('bitmapfont', key, textureURL, { xmlURL: null, xmlData: xml }); + } + } + } + } + + return this; + + }, + + /** + * Add a new texture atlas to the loader. This atlas uses the JSON Array data format. + * + * @method Phaser.Loader#atlasJSONArray + * @param {string} key - Unique asset key of the bitmap font. + * @param {Description} atlasURL - The url of the Description. + * @param {Description} atlasData - Description. + */ + atlasJSONArray: function (key, textureURL, atlasURL, atlasData) { + + return this.atlas(key, textureURL, atlasURL, atlasData, Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY); + + }, + + /** + * Add a new texture atlas to the loader. This atlas uses the JSON Hash data format. + * + * @method Phaser.Loader#atlasJSONHash + * @param {string} key - Unique asset key of the bitmap font. + * @param {Description} atlasURL - The url of the Description. + * @param {Description} atlasData - Description. + */ + atlasJSONHash: function (key, textureURL, atlasURL, atlasData) { + + return this.atlas(key, textureURL, atlasURL, atlasData, Phaser.Loader.TEXTURE_ATLAS_JSON_HASH); + + }, + + /** + * Add a new texture atlas to the loader. This atlas uses the Starling XML data format. + * + * @method Phaser.Loader#atlasXML + * @param {string} key - Unique asset key of the bitmap font. + * @param {Description} atlasURL - The url of the Description. + * @param {Description} atlasData - Description. + */ + atlasXML: function (key, textureURL, atlasURL, atlasData) { + + return this.atlas(key, textureURL, atlasURL, atlasData, Phaser.Loader.TEXTURE_ATLAS_XML_STARLING); + + }, + + /** + * Add a new texture atlas to the loader. + * + * @method Phaser.Loader#atlas + * @param {string} key - Unique asset key of the texture atlas file. + * @param {string} textureURL - The url of the texture atlas image file. + * @param {string} [atlasURL] - The url of the texture atlas data file (json/xml). You don't need this if you are passing an atlasData object instead. + * @param {object} [atlasData] - A JSON or XML data object. You don't need this if the data is being loaded from a URL. + * @param {number} [format] - A value describing the format of the data, the default is Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY. + */ + atlas: function (key, textureURL, atlasURL, atlasData, format) { + + if (typeof atlasURL === "undefined") { atlasURL = null; } + if (typeof atlasData === "undefined") { atlasData = null; } + if (typeof format === "undefined") { format = Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY; } + + if (this.checkKeyExists(key) === false) + { + // A URL to a json/xml file has been given + if (atlasURL) + { + this.addToFileList('textureatlas', key, textureURL, { atlasURL: atlasURL, format: format }); + } + else + { + switch (format) + { + // A json string or object has been given + case Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY: + + if (typeof atlasData === 'string') + { + atlasData = JSON.parse(atlasData); + } + break; + + // An xml string or object has been given + case Phaser.Loader.TEXTURE_ATLAS_XML_STARLING: + + if (typeof atlasData === 'string') + { + var xml; + + try { + if (window['DOMParser']) + { + var domparser = new DOMParser(); + xml = domparser.parseFromString(atlasData, "text/xml"); + } + else + { + xml = new ActiveXObject("Microsoft.XMLDOM"); + xml.async = 'false'; + xml.loadXML(atlasData); + } + } + catch (e) + { + xml = undefined; + } + + if (!xml || !xml.documentElement || xml.getElementsByTagName("parsererror").length) + { + throw new Error("Phaser.Loader. Invalid Texture Atlas XML given"); + } + else + { + atlasData = xml; + } + } + break; + } + + this.addToFileList('textureatlas', key, textureURL, { atlasURL: null, atlasData: atlasData, format: format }); + + } + + } + + return this; + + }, + + /** + * Remove loading request of a file. + * + * @method Phaser.Loader#removeFile + * @param key {string} Key of the file you want to remove. + */ + removeFile: function (key) { + + delete this._fileList[key]; + + }, + + /** + * Remove all file loading requests. + * + * @method Phaser.Loader#removeAll + */ + removeAll: function () { + + this._fileList = {}; + + }, + + /** + * Start loading the assets. Normally you don't need to call this yourself as the StateManager will do so. + * + * @method Phaser.Loader#start + */ + start: function () { + + if (this.isLoading) + { + return; + } + + this.progress = 0; + this.hasLoaded = false; + this.isLoading = true; + + this.onLoadStart.dispatch(this.queueSize); + + if (this._keys.length > 0) + { + this._progressChunk = 100 / this._keys.length; + this.loadFile(); + } + else + { + this.progress = 100; + this.hasLoaded = true; + this.onLoadComplete.dispatch(); + } + + }, + + /** + * Load files. Private method ONLY used by loader. + * + * @method Phaser.Loader#loadFile + * @private + */ + loadFile: function () { + + var file = this._fileList[this._keys.shift()]; + var _this = this; + + // Image or Data? + switch (file.type) + { + case 'image': + case 'spritesheet': + case 'textureatlas': + case 'bitmapfont': + case 'tileset': + file.data = new Image(); + file.data.name = file.key; + file.data.onload = function () { + return _this.fileComplete(file.key); + }; + file.data.onerror = function () { + return _this.fileError(file.key); + }; + file.data.crossOrigin = this.crossOrigin; + file.data.src = this.baseURL + file.url; + break; + + case 'audio': + file.url = this.getAudioURL(file.url); + + if (file.url !== null) + { + // WebAudio or Audio Tag? + if (this.game.sound.usingWebAudio) + { + this._xhr.open("GET", this.baseURL + file.url, true); + this._xhr.responseType = "arraybuffer"; + this._xhr.onload = function () { + return _this.fileComplete(file.key); + }; + this._xhr.onerror = function () { + return _this.fileError(file.key); + }; + this._xhr.send(); + } + else if (this.game.sound.usingAudioTag) + { + if (this.game.sound.touchLocked) + { + // If audio is locked we can't do this yet, so need to queue this load request. Bum. + file.data = new Audio(); + file.data.name = file.key; + file.data.preload = 'auto'; + file.data.src = this.baseURL + file.url; + this.fileComplete(file.key); + } + else + { + file.data = new Audio(); + file.data.name = file.key; + file.data.onerror = function () { + return _this.fileError(file.key); + }; + file.data.preload = 'auto'; + file.data.src = this.baseURL + file.url; + file.data.addEventListener('canplaythrough', Phaser.GAMES[this.game.id].load.fileComplete(file.key), false); + file.data.load(); + } + } + } + else + { + this.fileError(file.key); + } + + break; + + case 'tilemap': + this._xhr.open("GET", this.baseURL + file.url, true); + this._xhr.responseType = "text"; + + if (file.format == Phaser.Tilemap.TILED_JSON) + { + this._xhr.onload = function () { + return _this.jsonLoadComplete(file.key); + }; + } + else if (file.format == Phaser.Tilemap.CSV) + { + this._xhr.onload = function () { + return _this.csvLoadComplete(file.key); + }; + } + else + { + throw new Error("Phaser.Loader. Invalid Tilemap format: " + file.format); + } + + this._xhr.onerror = function () { + return _this.dataLoadError(file.key); + }; + this._xhr.send(); + break; + + case 'text': + this._xhr.open("GET", this.baseURL + file.url, true); + this._xhr.responseType = "text"; + this._xhr.onload = function () { + return _this.fileComplete(file.key); + }; + this._xhr.onerror = function () { + return _this.fileError(file.key); + }; + this._xhr.send(); + break; + } + + }, + + /** + * Private method ONLY used by loader. + * @method Phaser.Loader#getAudioURL + * @param {array|string} urls - Either an array of audio file URLs or a string containing a single URL path. + * @private + */ + getAudioURL: function (urls) { + + var extension; + + if (typeof urls === 'string') { urls = [urls]; } + + for (var i = 0; i < urls.length; i++) + { + extension = urls[i].toLowerCase(); + extension = extension.substr((Math.max(0, extension.lastIndexOf(".")) || Infinity) + 1); + + if (this.game.device.canPlayAudio(extension)) + { + return urls[i]; + } + + } + + return null; + + }, + + /** + * Error occured when load a file. + * + * @method Phaser.Loader#fileError + * @param {string} key - Key of the error loading file. + */ + fileError: function (key) { + + this._fileList[key].loaded = true; + this._fileList[key].error = true; + + this.onFileError.dispatch(key); + + console.warn("Phaser.Loader error loading file: " + key + ' from URL ' + this._fileList[key].url); + + this.nextFile(key, false); + + }, + + /** + * Called when a file is successfully loaded. + * + * @method Phaser.Loader#fileComplete + * @param {string} key - Key of the successfully loaded file. + */ + fileComplete: function (key) { + + if (!this._fileList[key]) + { + console.warn('Phaser.Loader fileComplete invalid key ' + key); + return; + } + + this._fileList[key].loaded = true; + + var file = this._fileList[key]; + var loadNext = true; + var _this = this; + + switch (file.type) + { + case 'image': + + this.game.cache.addImage(file.key, file.url, file.data); + break; + + case 'spritesheet': + + this.game.cache.addSpriteSheet(file.key, file.url, file.data, file.frameWidth, file.frameHeight, file.frameMax); + break; + + case 'tileset': + + this.game.cache.addTileset(file.key, file.url, file.data, file.tileWidth, file.tileHeight, file.tileMax, file.tileMargin, file.tileSpacing); + break; + + case 'textureatlas': + + if (file.atlasURL == null) + { + this.game.cache.addTextureAtlas(file.key, file.url, file.data, file.atlasData, file.format); + } + else + { + // Load the JSON or XML before carrying on with the next file + loadNext = false; + this._xhr.open("GET", this.baseURL + file.atlasURL, true); + this._xhr.responseType = "text"; + + if (file.format == Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY || file.format == Phaser.Loader.TEXTURE_ATLAS_JSON_HASH) + { + this._xhr.onload = function () { + return _this.jsonLoadComplete(file.key); + }; + } + else if (file.format == Phaser.Loader.TEXTURE_ATLAS_XML_STARLING) + { + this._xhr.onload = function () { + return _this.xmlLoadComplete(file.key); + }; + } + else + { + throw new Error("Phaser.Loader. Invalid Texture Atlas format: " + file.format); + } + + this._xhr.onerror = function () { + return _this.dataLoadError(file.key); + }; + this._xhr.send(); + } + break; + + case 'bitmapfont': + + if (file.xmlURL == null) + { + this.game.cache.addBitmapFont(file.key, file.url, file.data, file.xmlData); + } + else + { + // Load the XML before carrying on with the next file + loadNext = false; + this._xhr.open("GET", this.baseURL + file.xmlURL, true); + this._xhr.responseType = "text"; + + this._xhr.onload = function () { + return _this.xmlLoadComplete(file.key); + }; + + this._xhr.onerror = function () { + return _this.dataLoadError(file.key); + }; + this._xhr.send(); + } + break; + + case 'audio': + + if (this.game.sound.usingWebAudio) + { + file.data = this._xhr.response; + + this.game.cache.addSound(file.key, file.url, file.data, true, false); + + if (file.autoDecode) + { + this.game.cache.updateSound(key, 'isDecoding', true); + + var that = this; + var key = file.key; + + this.game.sound.context.decodeAudioData(file.data, function (buffer) { + if (buffer) + { + that.game.cache.decodedSound(key, buffer); + } + }); + } + } + else + { + file.data.removeEventListener('canplaythrough', Phaser.GAMES[this.game.id].load.fileComplete); + this.game.cache.addSound(file.key, file.url, file.data, false, true); + } + break; + + case 'text': + file.data = this._xhr.responseText; + this.game.cache.addText(file.key, file.url, file.data); + break; + } + + if (loadNext) + { + this.nextFile(key, true); + } + + }, + + /** + * Successfully loaded a JSON file. + * + * @method Phaser.Loader#jsonLoadComplete + * @param {string} key - Key of the loaded JSON file. + */ + jsonLoadComplete: function (key) { + + var data = JSON.parse(this._xhr.responseText); + var file = this._fileList[key]; + + if (file.type == 'tilemap') + { + this.game.cache.addTilemap(file.key, file.url, data, file.format); + } + else + { + this.game.cache.addTextureAtlas(file.key, file.url, file.data, data, file.format); + } + + this.nextFile(key, true); + + }, + + /** + * Successfully loaded a CSV file. + * + * @method Phaser.Loader#csvLoadComplete + * @param {string} key - Key of the loaded CSV file. + */ + csvLoadComplete: function (key) { + + var data = this._xhr.responseText; + var file = this._fileList[key]; + + this.game.cache.addTilemap(file.key, file.url, data, file.format); + + this.nextFile(key, true); + + }, + + /** + * Error occured when load a JSON. + * + * @method Phaser.Loader#dataLoadError + * @param {string} key - Key of the error loading JSON file. + */ + dataLoadError: function (key) { + + var file = this._fileList[key]; + + file.error = true; + + console.warn("Phaser.Loader dataLoadError: " + key); + + this.nextFile(key, true); + + }, + + /** + * Successfully loaded an XML file. + * + * @method Phaser.Loader#xmlLoadComplete + * @param {string} key - Key of the loaded XML file. + */ + xmlLoadComplete: function (key) { + + var data = this._xhr.responseText; + var xml; + + try + { + if (window['DOMParser']) + { + var domparser = new DOMParser(); + xml = domparser.parseFromString(data, "text/xml"); + } + else + { + xml = new ActiveXObject("Microsoft.XMLDOM"); + xml.async = 'false'; + xml.loadXML(data); + } + } + catch (e) + { + xml = undefined; + } + + if (!xml || !xml.documentElement || xml.getElementsByTagName("parsererror").length) + { + throw new Error("Phaser.Loader. Invalid XML given"); + } + + var file = this._fileList[key]; + + if (file.type == 'bitmapfont') + { + this.game.cache.addBitmapFont(file.key, file.url, file.data, xml); + } + else if (file.type == 'textureatlas') + { + this.game.cache.addTextureAtlas(file.key, file.url, file.data, xml, file.format); + } + + this.nextFile(key, true); + + }, + + /** + * Handle loading next file. + * + * @param previousKey {string} Key of previous loaded asset. + * @param success {boolean} Whether the previous asset loaded successfully or not. + * @private + */ + nextFile: function (previousKey, success) { + + this.progress = Math.round(this.progress + this._progressChunk); + + if (this.progress > 100) + { + this.progress = 100; + } + + if (this.preloadSprite !== null) + { + if (this.preloadSprite.direction === 0) + { + this.preloadSprite.crop.width = Math.floor((this.preloadSprite.width / 100) * this.progress); + } + else + { + this.preloadSprite.crop.height = Math.floor((this.preloadSprite.height / 100) * this.progress); + } + + this.preloadSprite.sprite.crop = this.preloadSprite.crop; + } + + this.onFileComplete.dispatch(this.progress, previousKey, success, this.queueSize - this._keys.length, this.queueSize); + + if (this._keys.length > 0) + { + this.loadFile(); + } + else + { + this.hasLoaded = true; + this.isLoading = false; + + this.removeAll(); + + this.onLoadComplete.dispatch(); + } + + } }; diff --git a/src/loader/LoaderParser.js b/src/loader/LoaderParser.js index 3cae93484..0f91830cc 100644 --- a/src/loader/LoaderParser.js +++ b/src/loader/LoaderParser.js @@ -10,14 +10,14 @@ * @class Phaser.LoaderParser */ Phaser.LoaderParser = { - + /** * Parse frame data from an XML file. * @method Phaser.LoaderParser.bitmapFont * @param {object} xml - XML data you want to parse. * @return {FrameData} Generated FrameData object. */ - bitmapFont: function (game, xml, cacheKey) { + bitmapFont: function (game, xml, cacheKey) { // Malformed? if (!xml.getElementsByTagName('font')) @@ -50,8 +50,8 @@ Phaser.LoaderParser = { height: parseInt(letters[i].attributes.getNamedItem("height").nodeValue, 10) }; - // Note: This means you can only have 1 BitmapFont loaded at once! - // Need to replace this with our own handler soon. + // Note: This means you can only have 1 BitmapFont loaded at once! + // Need to replace this with our own handler soon. PIXI.TextureCache[charCode] = new PIXI.Texture(texture, textureRect); data.chars[charCode] = { @@ -69,9 +69,9 @@ Phaser.LoaderParser = { for (i = 0; i < kernings.length; i++) { - var first = parseInt(kernings[i].attributes.getNamedItem("first").nodeValue, 10); - var second = parseInt(kernings[i].attributes.getNamedItem("second").nodeValue, 10); - var amount = parseInt(kernings[i].attributes.getNamedItem("amount").nodeValue, 10); + var first = parseInt(kernings[i].attributes.getNamedItem("first").nodeValue, 10); + var second = parseInt(kernings[i].attributes.getNamedItem("second").nodeValue, 10); + var amount = parseInt(kernings[i].attributes.getNamedItem("amount").nodeValue, 10); data.chars[second].kerning[first] = amount; } diff --git a/src/math/Math.js b/src/math/Math.js index 13962e742..c03440904 100644 --- a/src/math/Math.js +++ b/src/math/Math.js @@ -11,78 +11,78 @@ */ Phaser.Math = { - /** - * = 2 π - * @method Phaser.Math#PI2 - */ - PI2: Math.PI * 2, + /** + * = 2 π + * @method Phaser.Math#PI2 + */ + PI2: Math.PI * 2, - /** - * Two number are fuzzyEqual if their difference is less than ε. - * @method Phaser.Math#fuzzyEqual - * @param {number} a - * @param {number} b - * @param {number} epsilon - * @return {boolean} True if |a-b|<ε - */ + /** + * Two number are fuzzyEqual if their difference is less than ε. + * @method Phaser.Math#fuzzyEqual + * @param {number} a + * @param {number} b + * @param {number} epsilon + * @return {boolean} True if |a-b|<ε + */ fuzzyEqual: function (a, b, epsilon) { if (typeof epsilon === "undefined") { epsilon = 0.0001; } return Math.abs(a - b) < epsilon; }, - /** - * a is fuzzyLessThan b if it is less than b + ε. - * @method Phaser.Math#fuzzyEqual - * @param {number} a - * @param {number} b - * @param {number} epsilon - * @return {boolean} True if ab+ε - */ + /** + * a is fuzzyGreaterThan b if it is more than b - ε. + * @method Phaser.Math#fuzzyGreaterThan + * @param {number} a + * @param {number} b + * @param {number} epsilon + * @return {boolean} True if a>b+ε + */ fuzzyGreaterThan: function (a, b, epsilon) { if (typeof epsilon === "undefined") { epsilon = 0.0001; } return a > b - epsilon; }, - /** - * @method Phaser.Math#fuzzyCeil - * @param {number} val - * @param {number} epsilon - * @return {boolean} ceiling(val-ε) - */ + /** + * @method Phaser.Math#fuzzyCeil + * @param {number} val + * @param {number} epsilon + * @return {boolean} ceiling(val-ε) + */ fuzzyCeil: function (val, epsilon) { if (typeof epsilon === "undefined") { epsilon = 0.0001; } return Math.ceil(val - epsilon); }, - /** - * @method Phaser.Math#fuzzyFloor - * @param {number} val - * @param {number} epsilon - * @return {boolean} floor(val-ε) - */ + /** + * @method Phaser.Math#fuzzyFloor + * @param {number} val + * @param {number} epsilon + * @return {boolean} floor(val-ε) + */ fuzzyFloor: function (val, epsilon) { if (typeof epsilon === "undefined") { epsilon = 0.0001; } return Math.floor(val + epsilon); }, - /** + /** * Averages all values passed to the function and returns the result. You can pass as many parameters as you like. - * @method Phaser.Math#average + * @method Phaser.Math#average * @return {number} The average of all given values. - */ + */ average: function () { var args = []; @@ -101,35 +101,35 @@ Phaser.Math = { }, - /** - * @method Phaser.Math#truncate + /** + * @method Phaser.Math#truncate * @param {number} n * @return {number} - */ + */ truncate: function (n) { return (n > 0) ? Math.floor(n) : Math.ceil(n); }, - /** - * @method Phaser.Math#shear - * @param {number} n - * @return {number} n mod 1 - */ + /** + * @method Phaser.Math#shear + * @param {number} n + * @return {number} n mod 1 + */ shear: function (n) { return n % 1; }, - /** - * Snap a value to nearest grid slice, using rounding. - * - * Example: if you have an interval gap of 5 and a position of 12... you will snap to 10 whereas 14 will snap to 15. - * - * @method Phaser.Math#snapTo - * @param {number} input - The value to snap. - * @param {number} gap - The interval gap of the grid. - * @param {number} [start] - Optional starting offset for gap. + /** + * Snap a value to nearest grid slice, using rounding. + * + * Example: if you have an interval gap of 5 and a position of 12... you will snap to 10 whereas 14 will snap to 15. + * + * @method Phaser.Math#snapTo + * @param {number} input - The value to snap. + * @param {number} gap - The interval gap of the grid. + * @param {number} [start] - Optional starting offset for gap. * @return {number} - */ + */ snapTo: function (input, gap, start) { if (typeof start === "undefined") { start = 0; } @@ -145,7 +145,7 @@ Phaser.Math = { }, - /** + /** * 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 @@ -171,17 +171,17 @@ Phaser.Math = { }, - /** - * 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. - * + /** + * Snap a value to nearest grid slice, using ceil. + * + * Example: if you have an interval gap of 5 and a position of 12... you will snap to 15. As will 14 will snap to 15... but 16 will snap to 20. + * * @method Phaser.Math#snapToCeil * @param {number} input - The value to snap. * @param {number} gap - The interval gap of the grid. * @param {number} [start] - Optional starting offset for gap. * @return {number} - */ + */ snapToCeil: function (input, gap, start) { if (typeof start === "undefined") { start = 0; } @@ -198,14 +198,14 @@ Phaser.Math = { }, - /** - * Snaps a value to the nearest value in an array. - * @method Phaser.Math#snapToInArray - * @param {number} input - * @param {array} arr - * @param {boolean} sort - True if the array needs to be sorted. + /** + * Snaps a value to the nearest value in an array. + * @method Phaser.Math#snapToInArray + * @param {number} input + * @param {array} arr + * @param {boolean} sort - True if the array needs to be sorted. * @return {number} - */ + */ snapToInArray: function (input, arr, sort) { if (typeof sort === "undefined") { sort = true; } @@ -231,42 +231,42 @@ Phaser.Math = { }, - /** - * Round to some place comparative to a 'base', default is 10 for decimal place. - * - * 'place' is represented by the power applied to 'base' to get that place - * e.g. - * 2000/7 ~= 285.714285714285714285714 ~= (bin)100011101.1011011011011011 - * - * roundTo(2000/7,3) === 0 - * roundTo(2000/7,2) == 300 - * roundTo(2000/7,1) == 290 - * roundTo(2000/7,0) == 286 - * roundTo(2000/7,-1) == 285.7 - * roundTo(2000/7,-2) == 285.71 - * roundTo(2000/7,-3) == 285.714 - * roundTo(2000/7,-4) == 285.7143 - * roundTo(2000/7,-5) == 285.71429 - * - * roundTo(2000/7,3,2) == 288 -- 100100000 - * roundTo(2000/7,2,2) == 284 -- 100011100 - * roundTo(2000/7,1,2) == 286 -- 100011110 - * roundTo(2000/7,0,2) == 286 -- 100011110 - * roundTo(2000/7,-1,2) == 285.5 -- 100011101.1 - * roundTo(2000/7,-2,2) == 285.75 -- 100011101.11 - * roundTo(2000/7,-3,2) == 285.75 -- 100011101.11 - * roundTo(2000/7,-4,2) == 285.6875 -- 100011101.1011 - * roundTo(2000/7,-5,2) == 285.71875 -- 100011101.10111 - * - * Note what occurs when we round to the 3rd space (8ths place), 100100000, this is to be assumed - * because we are rounding 100011.1011011011011011 which rounds up. - * - * @method Phaser.Math#roundTo - * @param {number} value - The value to round. - * @param {number} place - The place to round to. - * @param {number} base - The base to round in... default is 10 for decimal. + /** + * Round to some place comparative to a 'base', default is 10 for decimal place. + * + * 'place' is represented by the power applied to 'base' to get that place + * e.g. + * 2000/7 ~= 285.714285714285714285714 ~= (bin)100011101.1011011011011011 + * + * roundTo(2000/7,3) === 0 + * roundTo(2000/7,2) == 300 + * roundTo(2000/7,1) == 290 + * roundTo(2000/7,0) == 286 + * roundTo(2000/7,-1) == 285.7 + * roundTo(2000/7,-2) == 285.71 + * roundTo(2000/7,-3) == 285.714 + * roundTo(2000/7,-4) == 285.7143 + * roundTo(2000/7,-5) == 285.71429 + * + * roundTo(2000/7,3,2) == 288 -- 100100000 + * roundTo(2000/7,2,2) == 284 -- 100011100 + * roundTo(2000/7,1,2) == 286 -- 100011110 + * roundTo(2000/7,0,2) == 286 -- 100011110 + * roundTo(2000/7,-1,2) == 285.5 -- 100011101.1 + * roundTo(2000/7,-2,2) == 285.75 -- 100011101.11 + * roundTo(2000/7,-3,2) == 285.75 -- 100011101.11 + * roundTo(2000/7,-4,2) == 285.6875 -- 100011101.1011 + * roundTo(2000/7,-5,2) == 285.71875 -- 100011101.10111 + * + * Note what occurs when we round to the 3rd space (8ths place), 100100000, this is to be assumed + * because we are rounding 100011.1011011011011011 which rounds up. + * + * @method Phaser.Math#roundTo + * @param {number} value - The value to round. + * @param {number} place - The place to round to. + * @param {number} base - The base to round in... default is 10 for decimal. * @return {number} - */ + */ roundTo: function (value, place, base) { if (typeof place === "undefined") { place = 0; } @@ -279,12 +279,12 @@ Phaser.Math = { }, /** - * @method Phaser.Math#floorTo - * @param {number} value - The value to round. - * @param {number} place - The place to round to. - * @param {number} base - The base to round in... default is 10 for decimal. + * @method Phaser.Math#floorTo + * @param {number} value - The value to round. + * @param {number} place - The place to round to. + * @param {number} base - The base to round in... default is 10 for decimal. * @return {number} - */ + */ floorTo: function (value, place, base) { if (typeof place === "undefined") { place = 0; } @@ -297,12 +297,12 @@ Phaser.Math = { }, /** - * @method Phaser.Math#ceilTo - * @param {number} value - The value to round. - * @param {number} place - The place to round to. - * @param {number} base - The base to round in... default is 10 for decimal. + * @method Phaser.Math#ceilTo + * @param {number} value - The value to round. + * @param {number} place - The place to round to. + * @param {number} base - The base to round in... default is 10 for decimal. * @return {number} - */ + */ ceilTo: function (value, place, base) { if (typeof place === "undefined") { place = 0; } @@ -314,38 +314,38 @@ Phaser.Math = { }, - /** - * A one dimensional linear interpolation of a value. - * @method Phaser.Math#interpolateFloat - * @param {number} a - * @param {number} b - * @param {number} weight + /** + * A one dimensional linear interpolation of a value. + * @method Phaser.Math#interpolateFloat + * @param {number} a + * @param {number} b + * @param {number} weight * @return {number} - */ + */ interpolateFloat: function (a, b, weight) { return (b - a) * weight + a; }, - /** - * Find the angle of a segment from (x1, y1) -> (x2, y2 ). - * @method Phaser.Math#angleBetween - * @param {number} x1 - * @param {number} y1 - * @param {number} x2 - * @param {number} y2 + /** + * Find the angle of a segment from (x1, y1) -> (x2, y2 ). + * @method Phaser.Math#angleBetween + * @param {number} x1 + * @param {number} y1 + * @param {number} x2 + * @param {number} y2 * @return {number} - */ + */ angleBetween: function (x1, y1, x2, y2) { return Math.atan2(y2 - y1, x2 - x1); }, - /** - * Set an angle within the bounds of -π toπ. - * @method Phaser.Math#normalizeAngle - * @param {number} angle - * @param {boolean} radians - True if angle size is expressed in radians. + /** + * Set an angle within the bounds of -π toπ. + * @method Phaser.Math#normalizeAngle + * @param {number} angle + * @param {boolean} radians - True if angle size is expressed in radians. * @return {number} - */ + */ normalizeAngle: function (angle, radians) { if (typeof radians === "undefined") { radians = true; } @@ -355,15 +355,15 @@ Phaser.Math = { }, - /** - * Closest angle between two angles from a1 to a2 - * absolute value the return for exact angle - * @method Phaser.Math#nearestAngleBetween - * @param {number} a1 - * @param {number} a2 - * @param {boolean} radians - True if angle sizes are expressed in radians. + /** + * Closest angle between two angles from a1 to a2 + * absolute value the return for exact angle + * @method Phaser.Math#nearestAngleBetween + * @param {number} a1 + * @param {number} a2 + * @param {boolean} radians - True if angle sizes are expressed in radians. * @return {number} - */ + */ nearestAngleBetween: function (a1, a2, radians) { if (typeof radians === "undefined") { radians = true; } @@ -386,16 +386,16 @@ Phaser.Math = { }, - /** - * Interpolate across the shortest arc between two angles. - * @method Phaser.Math#interpolateAngles - * @param {number} a1 - Description. - * @param {number} a2 - Description. - * @param {number} weight - Description. - * @param {boolean} radians - True if angle sizes are expressed in radians. - * @param {Description} ease - Description. + /** + * Interpolate across the shortest arc between two angles. + * @method Phaser.Math#interpolateAngles + * @param {number} a1 - Description. + * @param {number} a2 - Description. + * @param {number} weight - Description. + * @param {boolean} radians - True if angle sizes are expressed in radians. + * @param {Description} ease - Description. * @return {number} - */ + */ interpolateAngles: function (a1, a2, weight, radians, ease) { if (typeof radians === "undefined") { radians = true; } @@ -408,16 +408,16 @@ Phaser.Math = { }, - /** - * 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.Math#chanceRoll - * @param {number} chance - The chance of receiving the value. A number between 0 and 100 (effectively 0% to 100%). - * @return {boolean} True if the roll passed, or false otherwise. - */ + /** + * 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.Math#chanceRoll + * @param {number} chance - The chance of receiving the value. A number between 0 and 100 (effectively 0% to 100%). + * @return {boolean} True if the roll passed, or false otherwise. + */ chanceRoll: function (chance) { if (typeof chance === "undefined") { chance = 50; } @@ -465,15 +465,15 @@ Phaser.Math = { }, - /** - * 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. + /** + * Adds the given amount to the value, but never lets the value go over the specified maximum. + * + * @method Phaser.Math#maxAdd + * @param {number} value - The value to add the amount to. + * @param {number} amount - The amount to add to the value. + * @param {number} max- The maximum the value is allowed to be. * @return {number} - */ + */ maxAdd: function (value, amount, max) { value += amount; @@ -487,15 +487,15 @@ Phaser.Math = { }, - /** - * 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) { value -= amount; @@ -543,11 +543,11 @@ Phaser.Math = { * Adds value to amount and ensures that the result always stays between 0 and max, by wrapping the value around. *

Values must be positive integers, and are passed through Math.abs

* - * @method Phaser.Math#wrapValue - * @param {number} value - The value to add the amount to. - * @param {number} amount - The amount to add to the value. - * @param {number} max - The maximum the value is allowed to be. - * @return {number} The wrapped value. + * @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) { @@ -561,36 +561,36 @@ Phaser.Math = { }, - /** - * Randomly returns either a 1 or -1. - * - * @method Phaser.Math#randomSign - * @return {number} 1 or -1 - */ + /** + * Randomly returns either a 1 or -1. + * + * @method Phaser.Math#randomSign + * @return {number} 1 or -1 + */ randomSign: function () { return (Math.random() > 0.5) ? 1 : -1; }, - /** - * Returns true if the number given is odd. - * - * @method Phaser.Math#isOdd - * @param {number} n - The number to check. - * @return {boolean} True if the given number is odd. False if the given number is even. - */ + /** + * Returns true if the number given is odd. + * + * @method Phaser.Math#isOdd + * @param {number} n - The number to check. + * @return {boolean} True if the given number is odd. False if the given number is even. + */ isOdd: function (n) { return (n & 1); }, - /** - * Returns true if the number given is even. - * - * @method Phaser.Math#isEven - * @param {number} n - The number to check. - * @return {boolean} True if the given number is even. False if the given number is odd. - */ + /** + * Returns true if the number given is even. + * + * @method Phaser.Math#isEven + * @param {number} n - The number to check. + * @return {boolean} True if the given number is even. False if the given number is odd. + */ isEven: function (n) { if (n & 1) @@ -646,30 +646,30 @@ Phaser.Math = { }, - /** - * Keeps an angle value between -180 and +180
- * Should be called whenever the angle is updated on the Sprite to stop it from going insane. - * - * @method Phaser.Math#wrapAngle - * @param {number} angle - The angle value to check - * @return {number} The new angle value, returns the same as the input angle if it was within bounds. - */ + /** + * Keeps an angle value between -180 and +180
+ * Should be called whenever the angle is updated on the Sprite to stop it from going insane. + * + * @method Phaser.Math#wrapAngle + * @param {number} angle - The angle value to check + * @return {number} The new angle value, returns the same as the input angle if it was within bounds. + */ wrapAngle: function (angle) { return this.wrap(angle, -180, 180); }, - /** - * Keeps an angle value between the given min and max values. - * - * @method Phaser.Math#angleLimit - * @param {number} angle - The angle value to check. Must be between -180 and +180. - * @param {number} min - The minimum angle that is allowed (must be -180 or greater). - * @param {number} max - The maximum angle that is allowed (must be 180 or less). - * - * @return {number} The new angle value, returns the same as the input angle if it was within bounds - */ + /** + * Keeps an angle value between the given min and max values. + * + * @method Phaser.Math#angleLimit + * @param {number} angle - The angle value to check. Must be between -180 and +180. + * @param {number} min - The minimum angle that is allowed (must be -180 or greater). + * @param {number} max - The maximum angle that is allowed (must be 180 or less). + * + * @return {number} The new angle value, returns the same as the input angle if it was within bounds + */ angleLimit: function (angle, min, max) { var result = angle; @@ -687,13 +687,13 @@ Phaser.Math = { }, - /** - * Description. - * @method Phaser.Math#linearInterpolation - * @param {number} v - * @param {number} k - * @return {number} - */ + /** + * Description. + * @method Phaser.Math#linearInterpolation + * @param {number} v + * @param {number} k + * @return {number} + */ linearInterpolation: function (v, k) { var m = v.length - 1; @@ -714,13 +714,13 @@ Phaser.Math = { }, - /** - * Description. - * @method Phaser.Math#bezierInterpolation - * @param {number} v - * @param {number} k - * @return {number} - */ + /** + * Description. + * @method Phaser.Math#bezierInterpolation + * @param {number} v + * @param {number} k + * @return {number} + */ bezierInterpolation: function (v, k) { var b = 0; @@ -735,13 +735,13 @@ Phaser.Math = { }, - /** - * Description. - * @method Phaser.Math#catmullRomInterpolation - * @param {number} v - * @param {number} k - * @return {number} - */ + /** + * Description. + * @method Phaser.Math#catmullRomInterpolation + * @param {number} v + * @param {number} k + * @return {number} + */ catmullRomInterpolation: function (v, k) { var m = v.length - 1; @@ -775,38 +775,38 @@ Phaser.Math = { }, - /** - * Description. - * @method Phaser.Math#Linear - * @param {number} p0 - * @param {number} p1 - * @param {number} t - * @return {number} - */ + /** + * Description. + * @method Phaser.Math#Linear + * @param {number} p0 + * @param {number} p1 + * @param {number} t + * @return {number} + */ linear: function (p0, p1, t) { return (p1 - p0) * t + p0; }, - /** - * @method Phaser.Math#bernstein - * @param {number} n - * @param {number} i - * @return {number} - */ + /** + * @method Phaser.Math#bernstein + * @param {number} n + * @param {number} i + * @return {number} + */ bernstein: function (n, i) { return this.factorial(n) / this.factorial(i) / this.factorial(n - i); }, - /** - * Description. - * @method Phaser.Math#catmullRom - * @param {number} p0 - * @param {number} p1 - * @param {number} p2 - * @param {number} p3 - * @param {number} t - * @return {number} - */ + /** + * Description. + * @method Phaser.Math#catmullRom + * @param {number} p0 + * @param {number} p1 + * @param {number} p2 + * @param {number} p3 + * @param {number} t + * @return {number} + */ catmullRom: function (p0, p1, p2, p3, t) { var v0 = (p2 - p0) * 0.5, v1 = (p3 - p1) * 0.5, t2 = t * t, t3 = t * t2; @@ -825,16 +825,16 @@ Phaser.Math = { return Math.abs(a - b); }, - /** - * Fetch a random entry from the given array. - * Will return null if random selection is missing, or array has no entries. - * - * @method Phaser.Math#getRandom - * @param {array} objects - An array of objects. - * @param {number} startIndex - Optional offset off the front of the array. Default value is 0, or the beginning of the array. - * @param {number} length - Optional restriction on the number of values you want to randomly select from. - * @return {object} The random object that was selected. - */ + /** + * Fetch a random entry from the given array. + * Will return null if random selection is missing, or array has no entries. + * + * @method Phaser.Math#getRandom + * @param {array} objects - An array of objects. + * @param {number} startIndex - Optional offset off the front of the array. Default value is 0, or the beginning of the array. + * @param {number} length - Optional restriction on the number of values you want to randomly select from. + * @return {object} The random object that was selected. + */ getRandom: function (objects, startIndex, length) { if (typeof startIndex === "undefined") { startIndex = 0; } @@ -859,13 +859,13 @@ Phaser.Math = { }, - /** - * Round down to the next whole number. E.g. floor(1.7) == 1, and floor(-2.7) == -2. - * - * @method Phaser.Math#floor - * @param {number} Value Any number. - * @return {number} The rounded value of that number. - */ + /** + * Round down to the next whole number. E.g. floor(1.7) == 1, and floor(-2.7) == -2. + * + * @method Phaser.Math#floor + * @param {number} Value Any number. + * @return {number} The rounded value of that number. + */ floor: function (value) { var n = value | 0; @@ -874,19 +874,19 @@ Phaser.Math = { }, - /** - * Round up to the next whole number. E.g. ceil(1.3) == 2, and ceil(-2.3) == -3. - * + /** + * Round up to the next whole number. E.g. ceil(1.3) == 2, and ceil(-2.3) == -3. + * * @method Phaser.Math#ceil - * @param {number} value - Any number. - * @return {number} The rounded value of that number. - */ + * @param {number} value - Any number. + * @return {number} The rounded value of that number. + */ ceil: function (value) { var n = value | 0; return (value > 0) ? ((n != value) ? (n + 1) : (n)) : (n); }, - /** + /** * Generate a sine and cosine table simultaneously and extremely quickly. Based on research by Franky of scene.at *

* The parameters allow you to specify the length, amplitude and frequency of the wave. Once you have called this function @@ -926,9 +926,9 @@ Phaser.Math = { }, - /** - * Removes the top element from the stack and re-inserts it onto the bottom, then returns it. - * The original stack is modified in the process. This effectively moves the position of the data from the start to the end of the table. + /** + * Removes the top element from the stack and re-inserts it onto the bottom, then returns it. + * The original stack is modified in the process. This effectively moves the position of the data from the start to the end of the table. * * @method Phaser.Math#shift * @param {array} stack - The array to shift. @@ -936,14 +936,14 @@ Phaser.Math = { */ shift: function (stack) { - var s = stack.shift(); - stack.push(s); + var s = stack.shift(); + stack.push(s); - return s; + return s; }, - /** + /** * Shuffles the data in the given array into a new order * @method Phaser.Math#shuffleArray * @param {array} array - The array to shuffle @@ -963,7 +963,7 @@ Phaser.Math = { }, - /** + /** * Returns the distance between the two given set of coordinates. * * @method Phaser.Math#distance @@ -994,39 +994,39 @@ Phaser.Math = { */ distanceRounded: function (x1, y1, x2, y2) { - return Math.round(Phaser.Math.distance(x1, y1, x2, y2)); + return Math.round(Phaser.Math.distance(x1, y1, x2, y2)); }, - /** - * Force a value within the boundaries of two values. - * Clamp value to range - * - * @method Phaser.Math#clamp - * @param {number} x - * @param {number} a - * @param {number} b + /** + * Force a value within the boundaries of two values. + * Clamp value to range + * + * @method Phaser.Math#clamp + * @param {number} x + * @param {number} a + * @param {number} b * @return {number} - */ - clamp: function ( x, a, b ) { + */ + clamp: function ( x, a, b ) { - return ( x < a ) ? a : ( ( x > b ) ? b : x ); + return ( x < a ) ? a : ( ( x > b ) ? b : x ); - }, + }, - /** - * Clamp value to range to range - * - * @method Phaser.Math#mapLinear - * @param {number} x - * @param {number} a1 - * @param {number} a1 - * @param {number} a2 - * @param {number} b1 - * @param {number} b2 - * @return {number} - */ - mapLinear: function ( x, a1, a2, b1, b2 ) { + /** + * Linear mapping from range to range + * + * @method Phaser.Math#mapLinear + * @param {number} x + * @param {number} a1 + * @param {number} a1 + * @param {number} a2 + * @param {number} b1 + * @param {number} b2 + * @return {number} + */ + mapLinear: function ( x, a1, a2, b1, b2 ) { - return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 ); + return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 ); - }, + }, - /** - * Smoothstep function as detailed at http://en.wikipedia.org/wiki/Smoothstep - * - * @method Phaser.Math#smoothstep - * @param {number} x - * @param {number} min - * @param {number} max - * @return {number} - */ - smoothstep: function ( x, min, max ) { + /** + * Smoothstep function as detailed at http://en.wikipedia.org/wiki/Smoothstep + * + * @method Phaser.Math#smoothstep + * @param {number} x + * @param {number} min + * @param {number} max + * @return {number} + */ + smoothstep: function ( x, min, max ) { - if ( x <= min ) return 0; - if ( x >= max ) return 1; + if (x <= min) + { + return 0; + } - x = ( x - min )/( max - min ); + if (x >= max) + { + return 1; + } - return x*x*(3 - 2*x); + x = (x - min) / (max - min); - }, + return x * x * (3 - 2 * x); - /** + }, + + /** * Smootherstep function as detailed at http://en.wikipedia.org/wiki/Smoothstep - * - * @method Phaser.Math#smootherstep - * @param {number} x - * @param {number} min - * @param {number} max - * @return {number} - */ - smootherstep: function ( x, min, max ) { + * + * @method Phaser.Math#smootherstep + * @param {number} x + * @param {number} min + * @param {number} max + * @return {number} + */ + smootherstep: function ( x, min, max ) { - if ( x <= min ) return 0; - if ( x >= max ) return 1; + if (x <= min) + { + return 0; + } - x = ( x - min )/( max - min ); + if (x >= max) + { + return 1; + } - return x*x*x*(x*(x*6 - 15) + 10); + x = (x - min) / (max - min); - }, + return x * x * x * (x * (x * 6 - 15) + 10); - /** - * A value representing the sign of the value. - * -1 for negative, +1 for positive, 0 if value is 0 - * - * @method Phaser.Math#sign - * @param {number} x - * @return {number} - */ - sign: function ( x ) { + }, - return ( x < 0 ) ? -1 : ( ( x > 0 ) ? 1 : 0 ); + /** + * A value representing the sign of the value. + * -1 for negative, +1 for positive, 0 if value is 0 + * + * @method Phaser.Math#sign + * @param {number} x + * @return {number} + */ + sign: function ( x ) { - }, + return ( x < 0 ) ? -1 : ( ( x > 0 ) ? 1 : 0 ); - /** - * Convert degrees to radians. - * - * @method Phaser.Math#degToRad - * @return {function} - */ - degToRad: function() { + }, - var degreeToRadiansFactor = Math.PI / 180; + /** + * Convert degrees to radians. + * + * @method Phaser.Math#degToRad + * @return {function} + */ + degToRad: function() { - return function ( degrees ) { + var degreeToRadiansFactor = Math.PI / 180; - return degrees * degreeToRadiansFactor; + return function ( degrees ) { - }; + return degrees * degreeToRadiansFactor; - }(), + }; - /** - * Convert degrees to radians. - * - * @method Phaser.Math#radToDeg - * @return {function} - */ - radToDeg: function() { + }(), - var radianToDegreesFactor = 180 / Math.PI; + /** + * Convert degrees to radians. + * + * @method Phaser.Math#radToDeg + * @return {function} + */ + radToDeg: function() { - return function ( radians ) { + var radianToDegreesFactor = 180 / Math.PI; - return radians * radianToDegreesFactor; + return function ( radians ) { - }; + return radians * radianToDegreesFactor; - }() + }; + + }() }; diff --git a/src/math/QuadTree.js b/src/math/QuadTree.js index 350465388..5f2bd374f 100644 --- a/src/math/QuadTree.js +++ b/src/math/QuadTree.js @@ -58,207 +58,208 @@ * @param {number} level - Description. */ Phaser.QuadTree = function (physicsManager, x, y, width, height, maxObjects, maxLevels, level) { - - this.physicsManager = physicsManager; - this.ID = physicsManager.quadTreeID; - physicsManager.quadTreeID++; + + this.physicsManager = physicsManager; + this.ID = physicsManager.quadTreeID; + physicsManager.quadTreeID++; - this.maxObjects = maxObjects || 10; - this.maxLevels = maxLevels || 4; - this.level = level || 0; + this.maxObjects = maxObjects || 10; + this.maxLevels = maxLevels || 4; + this.level = level || 0; - this.bounds = { - x: Math.round(x), - y: Math.round(y), - width: width, - height: height, - subWidth: Math.floor(width / 2), - subHeight: Math.floor(height / 2), - right: Math.round(x) + Math.floor(width / 2), - bottom: Math.round(y) + Math.floor(height / 2) - }; - - this.objects = []; - this.nodes = []; + this.bounds = { + x: Math.round(x), + y: Math.round(y), + width: width, + height: height, + subWidth: Math.floor(width / 2), + subHeight: Math.floor(height / 2), + right: Math.round(x) + Math.floor(width / 2), + bottom: Math.round(y) + Math.floor(height / 2) + }; + + this.objects = []; + this.nodes = []; }; Phaser.QuadTree.prototype = { - /* - * Split the node into 4 subnodes - * - * @method Phaser.QuadTree#split - */ - split: function() { + /* + * Split the node into 4 subnodes + * + * @method Phaser.QuadTree#split + */ + split: function() { - this.level++; - - // top right node - this.nodes[0] = new Phaser.QuadTree(this.physicsManager, this.bounds.right, this.bounds.y, this.bounds.subWidth, this.bounds.subHeight, this.maxObjects, this.maxLevels, this.level); - - // top left node - this.nodes[1] = new Phaser.QuadTree(this.physicsManager, this.bounds.x, this.bounds.y, this.bounds.subWidth, this.bounds.subHeight, this.maxObjects, this.maxLevels, this.level); - - // bottom left node - this.nodes[2] = new Phaser.QuadTree(this.physicsManager, this.bounds.x, this.bounds.bottom, this.bounds.subWidth, this.bounds.subHeight, this.maxObjects, this.maxLevels, this.level); - - // bottom right node - this.nodes[3] = new Phaser.QuadTree(this.physicsManager, this.bounds.right, this.bounds.bottom, this.bounds.subWidth, this.bounds.subHeight, this.maxObjects, this.maxLevels, this.level); + this.level++; + + // top right node + this.nodes[0] = new Phaser.QuadTree(this.physicsManager, this.bounds.right, this.bounds.y, this.bounds.subWidth, this.bounds.subHeight, this.maxObjects, this.maxLevels, this.level); + + // top left node + this.nodes[1] = new Phaser.QuadTree(this.physicsManager, this.bounds.x, this.bounds.y, this.bounds.subWidth, this.bounds.subHeight, this.maxObjects, this.maxLevels, this.level); + + // bottom left node + this.nodes[2] = new Phaser.QuadTree(this.physicsManager, this.bounds.x, this.bounds.bottom, this.bounds.subWidth, this.bounds.subHeight, this.maxObjects, this.maxLevels, this.level); + + // bottom right node + this.nodes[3] = new Phaser.QuadTree(this.physicsManager, this.bounds.right, this.bounds.bottom, this.bounds.subWidth, this.bounds.subHeight, this.maxObjects, this.maxLevels, this.level); - }, + }, - /* - * Insert the object into the node. If the node - * exceeds the capacity, it will split and add all - * objects to their corresponding subnodes. - * - * @method Phaser.QuadTree#insert - * @param {object} body - Description. - */ - insert: function (body) { - - var i = 0; - var index; - - // if we have subnodes ... - if (this.nodes[0] != null) - { - index = this.getIndex(body); - - if (index !== -1) - { - this.nodes[index].insert(body); - return; - } - } - - this.objects.push(body); - - if (this.objects.length > this.maxObjects && this.level < this.maxLevels) - { - // Split if we don't already have subnodes - if (this.nodes[0] == null) - { - this.split(); - } - - // Add objects to subnodes - while (i < this.objects.length) - { - index = this.getIndex(this.objects[i]); - - if (index !== -1) - { - // this is expensive - see what we can do about it - this.nodes[index].insert(this.objects.splice(i, 1)[0]); - } - else - { - i++; - } - } - } - }, - - /* - * Determine which node the object belongs to. - * - * @method Phaser.QuadTree#getIndex - * @param {object} rect - Description. - * @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; + /* + * 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 {object} body - Description. + */ + insert: function (body) { + + var i = 0; + var index; + + // if we have subnodes ... + if (this.nodes[0] != null) + { + index = this.getIndex(body); + + if (index !== -1) + { + this.nodes[index].insert(body); + return; + } + } + + this.objects.push(body); + + if (this.objects.length > this.maxObjects && this.level < this.maxLevels) + { + // Split if we don't already have subnodes + if (this.nodes[0] == null) + { + this.split(); + } + + // Add objects to subnodes + while (i < this.objects.length) + { + index = this.getIndex(this.objects[i]); + + if (index !== -1) + { + // this is expensive - see what we can do about it + this.nodes[index].insert(this.objects.splice(i, 1)[0]); + } + else + { + i++; + } + } + } - if (rect.x < this.bounds.right && rect.right < this.bounds.right) - { - if ((rect.y < this.bounds.bottom && rect.bottom < this.bounds.bottom)) - { - // rect fits within the top-left quadrant of this quadtree - index = 1; - } - else if ((rect.y > this.bounds.bottom)) - { - // rect fits within the bottom-left quadrant of this quadtree - index = 2; - } - } - else if (rect.x > this.bounds.right) - { - // rect can completely fit within the right quadrants - if ((rect.y < this.bounds.bottom && rect.bottom < this.bounds.bottom)) - { - // rect fits within the top-right quadrant of this quadtree - index = 0; - } - else if ((rect.y > this.bounds.bottom)) - { - // rect fits within the bottom-right quadrant of this quadtree - index = 3; - } - } - - return index; + }, + + /* + * Determine which node the object belongs to. + * + * @method Phaser.QuadTree#getIndex + * @param {object} rect - Description. + * @return {number} index - Index of the subnode (0-3), or -1 if rect cannot completely fit within a subnode and is part of the parent node. + */ + getIndex: function (rect) { + + // default is that rect doesn't fit, i.e. it straddles the internal quadrants + var index = -1; - }, + if (rect.x < this.bounds.right && rect.right < this.bounds.right) + { + if ((rect.y < this.bounds.bottom && rect.bottom < this.bounds.bottom)) + { + // rect fits within the top-left quadrant of this quadtree + index = 1; + } + else if ((rect.y > this.bounds.bottom)) + { + // rect fits within the bottom-left quadrant of this quadtree + index = 2; + } + } + else if (rect.x > this.bounds.right) + { + // rect can completely fit within the right quadrants + if ((rect.y < this.bounds.bottom && rect.bottom < this.bounds.bottom)) + { + // rect fits within the top-right quadrant of this quadtree + index = 0; + } + else if ((rect.y > this.bounds.bottom)) + { + // rect fits within the bottom-right quadrant of this quadtree + index = 3; + } + } + + return index; - /* - * Return all objects that could collide with the given object. - * - * @method Phaser.QuadTree#retrieve - * @param {object} rect - Description. - * @Return {array} - Array with all detected objects. - */ - retrieve: function (sprite) { - - var returnObjects = this.objects; + }, - sprite.body.quadTreeIndex = this.getIndex(sprite.body); + /* + * Return all objects that could collide with the given object. + * + * @method Phaser.QuadTree#retrieve + * @param {object} rect - Description. + * @Return {array} - Array with all detected objects. + */ + retrieve: function (sprite) { + + var returnObjects = this.objects; - // Temp store for the node IDs this sprite is in, we can use this for fast elimination later - sprite.body.quadTreeIDs.push(this.ID); + sprite.body.quadTreeIndex = this.getIndex(sprite.body); - if (this.nodes[0]) - { - // if rect fits into a subnode .. - if (sprite.body.quadTreeIndex !== -1) - { - returnObjects = returnObjects.concat(this.nodes[sprite.body.quadTreeIndex].retrieve(sprite)); - } - else - { - // if rect does not fit into a subnode, check it against all subnodes (unrolled for speed) - returnObjects = returnObjects.concat(this.nodes[0].retrieve(sprite)); - returnObjects = returnObjects.concat(this.nodes[1].retrieve(sprite)); - returnObjects = returnObjects.concat(this.nodes[2].retrieve(sprite)); - returnObjects = returnObjects.concat(this.nodes[3].retrieve(sprite)); - } - } - - return returnObjects; + // Temp store for the node IDs this sprite is in, we can use this for fast elimination later + sprite.body.quadTreeIDs.push(this.ID); - }, + if (this.nodes[0]) + { + // if rect fits into a subnode .. + if (sprite.body.quadTreeIndex !== -1) + { + returnObjects = returnObjects.concat(this.nodes[sprite.body.quadTreeIndex].retrieve(sprite)); + } + else + { + // if rect does not fit into a subnode, check it against all subnodes (unrolled for speed) + returnObjects = returnObjects.concat(this.nodes[0].retrieve(sprite)); + returnObjects = returnObjects.concat(this.nodes[1].retrieve(sprite)); + returnObjects = returnObjects.concat(this.nodes[2].retrieve(sprite)); + returnObjects = returnObjects.concat(this.nodes[3].retrieve(sprite)); + } + } + + return returnObjects; - /* - * Clear the quadtree. - * @method Phaser.QuadTree#clear - */ - clear: function () { - - this.objects = []; - - for (var i = 0, len = this.nodes.length; i < len; i++) - { - // if (typeof this.nodes[i] !== 'undefined') - if (this.nodes[i]) - { - this.nodes[i].clear(); - delete this.nodes[i]; - } - } - } + }, + + /* + * Clear the quadtree. + * @method Phaser.QuadTree#clear + */ + clear: function () { + + this.objects = []; + + for (var i = 0, len = this.nodes.length; i < len; i++) + { + // if (typeof this.nodes[i] !== 'undefined') + if (this.nodes[i]) + { + this.nodes[i].clear(); + delete this.nodes[i]; + } + } + } }; diff --git a/src/math/RandomDataGenerator.js b/src/math/RandomDataGenerator.js index 7155902ce..afffa5cee 100644 --- a/src/math/RandomDataGenerator.js +++ b/src/math/RandomDataGenerator.js @@ -1,3 +1,5 @@ +/* jshint noempty: false */ + /** * @author Richard Davey * @copyright 2013 Photon Storm Ltd. @@ -16,231 +18,230 @@ * @param {array} seeds */ Phaser.RandomDataGenerator = function (seeds) { - - if (typeof seeds === "undefined") { seeds = []; } + + if (typeof seeds === "undefined") { seeds = []; } - this.sow(seeds); + /** + * @property {number} c - Internal var. + * @private + */ + this.c = 1; + + /** + * @property {number} s0 - Internal var. + * @private + */ + this.s0 = 0; + + /** + * @property {number} s1 - Internal var. + * @private + */ + this.s1 = 0; + + /** + * @property {number} s2 - Internal var. + * @private + */ + this.s2 = 0; + + this.sow(seeds); }; Phaser.RandomDataGenerator.prototype = { - /** - * @property {number} c - * @private - */ - c: 1, + /** + * Private random helper. + * @method Phaser.RandomDataGenerator#rnd + * @private + * @return {number} + */ + rnd: function () { - /** - * @property {number} s0 - * @private - */ - s0: 0, + var t = 2091639 * this.s0 + this.c * 2.3283064365386963e-10; // 2^-32 - /** - * @property {number} s1 - * @private - */ - s1: 0, + this.c = t | 0; + this.s0 = this.s1; + this.s1 = this.s2; + this.s2 = t - this.c; - /** - * @property {number} s2 - * @private - */ - s2: 0, + return this.s2; + }, - /** - * Private random helper. - * @method Phaser.RandomDataGenerator#rnd - * @private - * @return {number} Description. - */ - rnd: function () { + /** + * Reset the seed of the random data generator. + * + * @method Phaser.RandomDataGenerator#sow + * @param {array} seeds + */ + sow: function (seeds) { - var t = 2091639 * this.s0 + this.c * 2.3283064365386963e-10; // 2^-32 + if (typeof seeds === "undefined") { seeds = []; } - this.c = t | 0; - this.s0 = this.s1; - this.s1 = this.s2; - this.s2 = t - this.c; + this.s0 = this.hash(' '); + this.s1 = this.hash(this.s0); + this.s2 = this.hash(this.s1); + this.c = 1; - return this.s2; - }, + var seed; - /** - * Reset the seed of the random data generator. - * - * @method Phaser.RandomDataGenerator#sow - * @param {array} seeds - */ - sow: function (seeds) { + for (var i = 0; seed = seeds[i++]; ) + { + this.s0 -= this.hash(seed); + this.s0 += ~~(this.s0 < 0); + this.s1 -= this.hash(seed); + this.s1 += ~~(this.s1 < 0); + this.s2 -= this.hash(seed); + this.s2 += ~~(this.s2 < 0); + } + + }, - if (typeof seeds === "undefined") { seeds = []; } + /** + * Internal method that creates a seed hash. + * @method Phaser.RandomDataGenerator#hash + * @param {Any} data + * @private + * @return {number} hashed value. + */ + hash: function (data) { - this.s0 = this.hash(' '); - this.s1 = this.hash(this.s0); - this.s2 = this.hash(this.s1); - this.c = 1; + var h, i, n; + n = 0xefc8249d; + data = data.toString(); - var seed; + for (i = 0; i < data.length; i++) { + n += data.charCodeAt(i); + h = 0.02519603282416938 * n; + n = h >>> 0; + h -= n; + h *= n; + n = h >>> 0; + h -= n; + n += h * 0x100000000;// 2^32 + } - for (var i = 0; seed = seeds[i++]; ) - { - this.s0 -= this.hash(seed); - this.s0 += ~~(this.s0 < 0); - this.s1 -= this.hash(seed); - this.s1 += ~~(this.s1 < 0); - this.s2 -= this.hash(seed); - this.s2 += ~~(this.s2 < 0); - } - - }, + return (n >>> 0) * 2.3283064365386963e-10;// 2^-32 - /** - * Description. - * @method Phaser.RandomDataGenerator#hash - * @param {Any} data - * @private - * @return {number} Description. - */ - hash: function (data) { + }, - var h, i, n; - n = 0xefc8249d; - data = data.toString(); + /** + * 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 + }, - for (i = 0; i < data.length; i++) { - n += data.charCodeAt(i); - h = 0.02519603282416938 * n; - n = h >>> 0; - h -= n; - h *= n; - n = h >>> 0; - h -= n; - n += h * 0x100000000;// 2^32 - } + /** + * 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 + }, - return (n >>> 0) * 2.3283064365386963e-10;// 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 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(min, max)); + }, - /** - * Returns a random integer between 0 and 2^32. - * @method Phaser.RandomDataGenerator#integer - * @return {number} - */ - integer: function() { - return this.rnd.apply(this) * 0x100000000;// 2^32 - }, + /** + * 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) { - /** - * Returns a random real number between 0 and 1. - * @method Phaser.RandomDataGenerator#frac - * @return {number} - */ - frac: function() { - return this.rnd.apply(this) + (this.rnd.apply(this) * 0x200000 | 0) * 1.1102230246251565e-16;// 2^-53 - }, + return this.frac() * (max - min) + min; - /** - * Returns a random real number between 0 and 2^32. - * @method Phaser.RandomDataGenerator#real - * @return {number} - */ - real: function() { - return this.integer() + this.frac(); - }, + }, - /** - * Returns a random integer between min and max. - * @method Phaser.RandomDataGenerator#integerInRange - * @param {number} min - * @param {number} max - * @return {number} - */ - integerInRange: function (min, max) { - return Math.floor(this.realInRange(min, max)); - }, + /** + * 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 random real number between min and max. - * @method Phaser.RandomDataGenerator#realInRange - * @param {number} min - * @param {number} max - * @return {number} - */ - realInRange: function (min, max) { + /** + * 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 () { - return this.frac() * (max - min) + min; + var a = ''; + var b = ''; - }, + for (b = a = ''; a++ < 36; b +=~a % 5 | a * 3&4 ? (a^15 ? 8^this.frac() * (a^20 ? 16 : 4) : 4).toString(16) : '-') + { + } - /** - * Returns a random real number between -1 and 1. - * @method Phaser.RandomDataGenerator#normal - * @return {number} - */ - normal: function () { - return 1 - 2 * this.frac(); - }, + return b; - /** - * Returns a valid RFC4122 version4 ID hex string from https://gist.github.com/1308368 - * @method Phaser.RandomDataGenerator#uuid - * @return {string} - */ - uuid: function () { + }, - var a, b; + /** + * Returns a random member of `array`. + * @method Phaser.RandomDataGenerator#pick + * @param {Array} ary - An Array to pick a random member of. + * @return {any} A random member of the array. + */ + pick: function (ary) { + return ary[this.integerInRange(0, ary.length)]; + }, - for ( - b=a=''; - a++<36; - b+=~a%5|a*3&4?(a^15?8^this.frac()*(a^20?16:4):4).toString(16):'-' - ); + /** + * 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)]; + }, - return b; + /** + * 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 member of `array`. - * @method Phaser.RandomDataGenerator#pick - * @param {Any} ary - * @return {number} - */ - pick: function (ary) { - return ary[this.integerInRange(0, ary.length)]; - }, - - /** - * Returns a random member of `array`, favoring the earlier entries. - * @method Phaser.RandomDataGenerator#weightedPick - * @param {Any} ary - * @return {number} - */ - weightedPick: function (ary) { - return ary[~~(Math.pow(this.frac(), 2) * ary.length)]; - }, - - /** - * Returns a random timestamp between min and max, or between the beginning of 2000 and the end of 2020 if min and max aren't specified. - * @method Phaser.RandomDataGenerator#timestamp - * @param {number} min - * @param {number} max - * @return {number} - */ - timestamp: function (a, b) { - return this.realInRange(a || 946684800000, b || 1577862000000); - }, - - /** - * Returns a random angle between -180 and 180. - * @method Phaser.RandomDataGenerator#angle - * @return {number} - */ - angle: function() { - return this.integerInRange(-180, 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); + } }; diff --git a/src/net/Net.js b/src/net/Net.js index cb5dbf23f..b41fb5b6d 100644 --- a/src/net/Net.js +++ b/src/net/Net.js @@ -5,164 +5,160 @@ */ /** -* Description of Phaser.Net +* 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; + + this.game = game; }; Phaser.Net.prototype = { - /** - * Returns the hostname given by the browser. - * - * @method Phaser.Net#getHostName - * @return {string} - */ - getHostName: function () { + /** + * 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; - } + if (window.location && window.location.hostname) { + return window.location.hostname; + } - return null; + 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} - */ - checkDomainName: function (domain) { - return window.location.hostname.indexOf(domain) !== -1; - }, + /** + * Compares the given domain name against the hostname of the browser containing the game. + * If the domain name is found it returns true. + * You can specify a part of a domain, for example 'google' would match 'google.com', 'google.co.uk', etc. + * Do not include 'http://' at the start. + * + * @method Phaser.Net#checkDomainName + * @param {string} domain + * @return {boolean} true if the given domain fragment can be found in the window.location.hostname + */ + checkDomainName: function (domain) { + return window.location.hostname.indexOf(domain) !== -1; + }, - /** - * Updates a value on the Query String and returns it in full. - * If the value doesn't already exist it is set. - * If the value exists it is replaced with the new value given. If you don't provide a new value it is removed from the query string. - * Optionally you can redirect to the new url, or just return it as a string. - * - * @method Phaser.Net#updateQueryString - * @param {string} key - The querystring key to update. - * @param {string} value - The new value to be set. If it already exists it will be replaced. - * @param {boolean} redirect - If true the browser will issue a redirect to the url with the new querystring. - * @param {string} url - The URL to modify. If none is given it uses window.location.href. - * @return {string} If redirect is false then the modified url and query string is returned. - */ - updateQueryString: function (key, value, redirect, url) { + /** + * Updates a value on the Query String and returns it in full. + * If the value doesn't already exist it is set. + * If the value exists it is replaced with the new value given. If you don't provide a new value it is removed from the query string. + * Optionally you can redirect to the new url, or just return it as a string. + * + * @method Phaser.Net#updateQueryString + * @param {string} key - The querystring key to update. + * @param {string} value - The new value to be set. If it already exists it will be replaced. + * @param {boolean} redirect - If true the browser will issue a redirect to the url with the new querystring. + * @param {string} url - The URL to modify. If none is given it uses window.location.href. + * @return {string} If redirect is false then the modified url and query string is returned. + */ + updateQueryString: function (key, value, redirect, url) { - if (typeof redirect === "undefined") { redirect = false; } - if (typeof url === "undefined") { url = ''; } + if (typeof redirect === "undefined") { redirect = false; } + if (typeof url === "undefined" || url === '') { url = window.location.href; } - if (url == '') { - url = window.location.href; - } + var output = ''; + var re = new RegExp("([?|&])" + key + "=.*?(&|#|$)(.*)", "gi"); + + if (re.test(url)) + { + if (typeof value !== 'undefined' && value !== null) + { + output = url.replace(re, '$1' + key + "=" + value + '$2$3'); + } + else + { + output = url.replace(re, '$1$3').replace(/(&|\?)$/, ''); + } + } + else + { + if (typeof value !== 'undefined' && value !== null) + { + var separator = url.indexOf('?') !== -1 ? '&' : '?'; + var hash = url.split('#'); + url = hash[0] + separator + key + '=' + value; - var output = ''; - var re = new RegExp("([?|&])" + key + "=.*?(&|#|$)(.*)", "gi"); - - if (re.test(url)) - { - if (typeof value !== 'undefined' && value !== null) - { - output = url.replace(re, '$1' + key + "=" + value + '$2$3'); - } - else - { - output = url.replace(re, '$1$3').replace(/(&|\?)$/, ''); - } - } - else - { - if (typeof value !== 'undefined' && value !== null) - { - var separator = url.indexOf('?') !== -1 ? '&' : '?'; - var hash = url.split('#'); - url = hash[0] + separator + key + '=' + value; + if (hash[1]) { + url += '#' + hash[1]; + } - if (hash[1]) { - url += '#' + hash[1]; - } + output = url; - output = url; + } + else + { + output = url; + } + } - } - else - { - output = url; - } - } + if (redirect) + { + window.location.href = output; + } + else + { + return output; + } - if (redirect) - { - window.location.href = output; - } - else - { - return output; - } + }, - }, + /** + * Returns the Query String as an object. + * If you specify a parameter it will return just the value of that parameter, should it exist. + * + * @method Phaser.Net#getQueryString + * @param {string} [parameter=''] - If specified this will return just the value for that key. + * @return {string|object} An object containing the key value pairs found in the query string or just the value if a parameter was given. + */ + getQueryString: function (parameter) { - /** - * Returns the Query String as an object. - * If you specify a parameter it will return just the value of that parameter, should it exist. - * - * @method Phaser.Net#getQueryString - * @param {string} [parameter=''] - If specified this will return just the value for that key. - * @return {string|object} An object containing the key value pairs found in the query string or just the value if a parameter was given. - */ - getQueryString: function (parameter) { + if (typeof parameter === "undefined") { parameter = ''; } - if (typeof parameter === "undefined") { parameter = ''; } + var output = {}; + var keyValues = location.search.substring(1).split('&'); - var output = {}; - var keyValues = location.search.substring(1).split('&'); + for (var i in keyValues) { - for (var i in keyValues) { + var key = keyValues[i].split('='); - var key = keyValues[i].split('='); + if (key.length > 1) + { + if (parameter && parameter == this.decodeURI(key[0])) + { + return this.decodeURI(key[1]); + } + else + { + output[this.decodeURI(key[0])] = this.decodeURI(key[1]); + } + } + } - if (key.length > 1) - { - if (parameter && parameter == this.decodeURI(key[0])) - { - return this.decodeURI(key[1]); - } - else - { - output[this.decodeURI(key[0])] = this.decodeURI(key[1]); - } - } - } + return output; - return output; + }, - }, - - /** - * Returns the Query String as an object. - * If you specify a parameter it will return just the value of that parameter, should it exist. - * - * @method Phaser.Net#decodeURI - * @param {string} value - The URI component to be decoded. - * @return {string} The decoded value. - */ - decodeURI: function (value) { - return decodeURIComponent(value.replace(/\+/g, " ")); - } + /** + * Returns the Query String as an object. + * If you specify a parameter it will return just the value of that parameter, should it exist. + * + * @method Phaser.Net#decodeURI + * @param {string} value - The URI component to be decoded. + * @return {string} The decoded value. + */ + decodeURI: function (value) { + return decodeURIComponent(value.replace(/\+/g, " ")); + } }; diff --git a/src/particles/Particles.js b/src/particles/Particles.js index 69d0987e1..9d0f15b16 100644 --- a/src/particles/Particles.js +++ b/src/particles/Particles.js @@ -14,61 +14,66 @@ */ Phaser.Particles = function (game) { - /** - * @property {Description} emitters - Description. - */ - this.emitters = {}; + /** + * @property {Phaser.Game} game - A reference to the currently running Game. + */ + this.game = game; - /** - * @property {number} ID - Description. - * @default - */ - this.ID = 0; + /** + * @property {object} emitters - Internal emitters store. + */ + this.emitters = {}; + + /** + * @property {number} ID - + * @default + */ + this.ID = 0; }; Phaser.Particles.prototype = { - /** - * Adds a new Particle Emitter to the Particle Manager. - * @method Phaser.Particles#add - * @param {Phaser.Emitter} emitter - Description. - * @return {Phaser.Emitter} The emitter that was added. - */ - add: function (emitter) { + /** + * Adds a new Particle Emitter to the Particle Manager. + * @method Phaser.Particles#add + * @param {Phaser.Emitter} emitter - The emitter to be added to the particle manager. + * @return {Phaser.Emitter} The emitter that was added. + */ + add: function (emitter) { - this.emitters[emitter.name] = emitter; + this.emitters[emitter.name] = emitter; - return emitter; + return emitter; - }, + }, - /** - * Removes an existing Particle Emitter from the Particle Manager. - * @method Phaser.Particles#remove - * @param {Phaser.Emitter} emitter - The emitter to remove. - */ - remove: function (emitter) { + /** + * Removes an existing Particle Emitter from the Particle Manager. + * @method Phaser.Particles#remove + * @param {Phaser.Emitter} emitter - The emitter to remove. + */ + remove: function (emitter) { - delete this.emitters[emitter.name]; + delete this.emitters[emitter.name]; - }, + }, - /** - * Called by the core game loop. Updates all Emitters who have their exists value set to true. - * @method Phaser.Particles#update - * @protected - */ - update: function () { + /** + * Called by the core game loop. Updates all Emitters who have their exists value set to true. + * @method Phaser.Particles#update + * @protected + */ + update: function () { - for (var key in this.emitters) - { - if (this.emitters[key].exists) - { - this.emitters[key].update(); - } - } + for (var key in this.emitters) + { + if (this.emitters[key].exists) + { + this.emitters[key].update(); + } + } - } + } }; \ No newline at end of file diff --git a/src/particles/arcade/Emitter.js b/src/particles/arcade/Emitter.js index a76e55805..ab977f697 100644 --- a/src/particles/arcade/Emitter.js +++ b/src/particles/arcade/Emitter.js @@ -26,36 +26,36 @@ Phaser.Particles.Arcade.Emitter = function (game, x, y, maxParticles) { * @property {number} maxParticles - The total number of particles in this emitter.. * @default */ - this.maxParticles = maxParticles || 50; + this.maxParticles = maxParticles || 50; - Phaser.Group.call(this, game); + Phaser.Group.call(this, game); /** - * @property {string} name - Description. - */ + * @property {string} name - Description. + */ this.name = 'emitter' + this.game.particles.ID++; /** - * @property {Description} type - Description. - */ + * @property {Description} type - Description. + */ this.type = Phaser.EMITTER; /** - * @property {number} x - The X position of the top left corner of the emitter in world space. - * @default - */ + * @property {number} x - The X position of the top left corner of the emitter in world space. + * @default + */ this.x = 0; /** - * @property {number} y - The Y position of the top left corner of emitter in world space. - * @default - */ + * @property {number} y - The Y position of the top left corner of emitter in world space. + * @default + */ this.y = 0; /** - * @property {number} width - The width of the emitter. Particles can be randomly generated from anywhere within this box. - * @default - */ + * @property {number} width - The width of the emitter. Particles can be randomly generated from anywhere within this box. + * @default + */ this.width = 1; /** @@ -87,138 +87,138 @@ Phaser.Particles.Arcade.Emitter = function (game, x, y, maxParticles) { this.minParticleScale = 1; /** - * The maximum possible scale of a particle. - * The default value is 1. - * @property {number} maxParticleScale - * @default - */ + * The maximum possible scale of a particle. + * The default value is 1. + * @property {number} maxParticleScale + * @default + */ this.maxParticleScale = 1; /** - * The minimum possible angular velocity of a particle. The default value is -360. - * @property {number} minRotation - * @default - */ + * The minimum possible angular velocity of a particle. The default value is -360. + * @property {number} minRotation + * @default + */ this.minRotation = -360; /** - * The maximum possible angular velocity of a particle. The default value is 360. - * @property {number} maxRotation - * @default - */ + * The maximum possible angular velocity of a particle. The default value is 360. + * @property {number} maxRotation + * @default + */ this.maxRotation = 360; /** - * Sets the gravity.y of each particle to this value on launch. - * @property {number} gravity - * @default - */ + * Sets the gravity.y of each particle to this value on launch. + * @property {number} gravity + * @default + */ this.gravity = 2; /** - * Set your own particle class type here. - * @property {Description} particleClass - * @default - */ + * Set your own particle class type here. + * @property {Description} particleClass + * @default + */ this.particleClass = null; /** - * 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. + * @property {Phaser.Point} particleDrag + */ this.particleDrag = new Phaser.Point(); /** - * The angular drag component of particles launched from the emitter if they are rotating. - * @property {number} angularDrag - * @default - */ + * The angular drag component of particles launched from the emitter if they are rotating. + * @property {number} angularDrag + * @default + */ this.angularDrag = 0; /** - * How often a particle is emitted in ms (if emitter is started with Explode === false). - * @property {boolean} frequency - * @default - */ + * How often a particle is emitted in ms (if emitter is started with Explode === false). + * @property {boolean} frequency + * @default + */ this.frequency = 100; /** - * How long each particle lives once it is emitted in ms. Default is 2 seconds. - * Set lifespan to 'zero' for particles to live forever. - * @property {number} lifespan - * @default - */ + * How long each particle lives once it is emitted in ms. Default is 2 seconds. + * Set lifespan to 'zero' for particles to live forever. + * @property {number} lifespan + * @default + */ this.lifespan = 2000; /** - * 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. + * @property {Phaser.Point} bounce + */ this.bounce = new Phaser.Point(); /** - * Internal helper for deciding how many particles to launch. - * @property {number} _quantity - * @private - * @default - */ + * Internal helper for deciding how many particles to launch. + * @property {number} _quantity + * @private + * @default + */ this._quantity = 0; - /** - * Internal helper for deciding when to launch particles or kill them. - * @property {number} _timer - * @private - * @default - */ + /** + * Internal helper for deciding when to launch particles or kill them. + * @property {number} _timer + * @private + * @default + */ this._timer = 0; /** - * Internal counter for figuring out how many particles to launch. - * @property {number} _counter - * @private - * @default - */ + * Internal counter for figuring out how many particles to launch. + * @property {number} _counter + * @private + * @default + */ this._counter = 0; /** - * Internal helper for the style of particle emission (all at once, or one at a time). - * @property {boolean} _explode - * @private - * @default - */ + * Internal helper for the style of particle emission (all at once, or one at a time). + * @property {boolean} _explode + * @private + * @default + */ this._explode = true; /** - * Determines whether the emitter is currently emitting particles. - * It is totally safe to directly toggle this. - * @property {boolean} on - * @default - */ + * Determines whether the emitter is currently emitting particles. + * It is totally safe to directly toggle this. + * @property {boolean} on + * @default + */ this.on = false; /** - * Determines whether the emitter is being updated by the core game loop. - * @property {boolean} exists - * @default - */ + * Determines whether the emitter is being updated by the core game loop. + * @property {boolean} exists + * @default + */ this.exists = true; /** - * The point the particles are emitted from. - * Emitter.x and Emitter.y control the containers location, which updates all current particles - * Emitter.emitX and Emitter.emitY control the emission location relative to the x/y position. - * @property {boolean} emitX - */ + * The point the particles are emitted from. + * Emitter.x and Emitter.y control the containers location, which updates all current particles + * Emitter.emitX and Emitter.emitY control the emission location relative to the x/y position. + * @property {boolean} emitX + */ this.emitX = x; /** - * The point the particles are emitted from. - * Emitter.x and Emitter.y control the containers location, which updates all current particles - * Emitter.emitX and Emitter.emitY control the emission location relative to the x/y position. - * @property {boolean} emitY - */ + * The point the particles are emitted from. + * Emitter.x and Emitter.y control the containers location, which updates all current particles + * Emitter.emitX and Emitter.emitY control the emission location relative to the x/y position. + * @property {boolean} emitY + */ this.emitY = y; - + }; Phaser.Particles.Arcade.Emitter.prototype = Object.create(Phaser.Group.prototype); @@ -234,12 +234,12 @@ Phaser.Particles.Arcade.Emitter.prototype.update = function () { { if (this._explode) { - this._counter = 0; + this._counter = 0; do { - this.emitParticle(); - this._counter++; + this.emitParticle(); + this._counter++; } while (this._counter < this._quantity); @@ -247,22 +247,22 @@ Phaser.Particles.Arcade.Emitter.prototype.update = function () { } else { - if (this.game.time.now >= this._timer) - { + if (this.game.time.now >= this._timer) + { this.emitParticle(); - - this._counter++; + + this._counter++; if (this._quantity > 0) { - if (this._counter >= this._quantity) - { - this.on = false; - } + if (this._counter >= this._quantity) + { + this.on = false; + } } this._timer = this.game.time.now + this.frequency; - } + } } } @@ -286,7 +286,7 @@ Phaser.Particles.Arcade.Emitter.prototype.makeParticles = function (keys, frames frames = 0; } - quantity = quantity || this.maxParticles; + quantity = quantity || this.maxParticles; collide = collide || 0; if (typeof collideWorldBounds == 'undefined') @@ -315,10 +315,10 @@ Phaser.Particles.Arcade.Emitter.prototype.makeParticles = function (keys, frames particle = new Phaser.Sprite(this.game, 0, 0, rndKey, rndFrame); } - else - { + // else + // { // particle = new this.particleClass(this.game); - } + // } if (collide > 0) { @@ -380,18 +380,18 @@ Phaser.Particles.Arcade.Emitter.prototype.revive = function () { */ Phaser.Particles.Arcade.Emitter.prototype.start = function (explode, lifespan, frequency, quantity) { - if (typeof explode !== 'boolean') - { - explode = true; - } + if (typeof explode !== 'boolean') + { + explode = true; + } - lifespan = lifespan || 0; + lifespan = lifespan || 0; - // How many ms between emissions? - frequency = frequency || 250; + // How many ms between emissions? + frequency = frequency || 250; - // Total number of particles to emit - quantity = quantity || 0; + // Total number of particles to emit + quantity = quantity || 0; this.revive(); @@ -426,16 +426,16 @@ Phaser.Particles.Arcade.Emitter.prototype.emitParticle = function () { if (particle == null) { - return; + return; } if (this.width > 1 || this.height > 1) { - particle.reset(this.game.rnd.integerInRange(this.left, this.right), this.game.rnd.integerInRange(this.top, this.bottom)); + particle.reset(this.game.rnd.integerInRange(this.left, this.right), this.game.rnd.integerInRange(this.top, this.bottom)); } else { - particle.reset(this.emitX, this.emitY); + particle.reset(this.emitX, this.emitY); } particle.lifespan = this.lifespan; @@ -504,8 +504,8 @@ Phaser.Particles.Arcade.Emitter.prototype.setSize = function (width, height) { */ Phaser.Particles.Arcade.Emitter.prototype.setXSpeed = function (min, max) { - min = min || 0; - max = max || 0; + min = min || 0; + max = max || 0; this.minParticleSpeed.x = min; this.maxParticleSpeed.x = max; @@ -520,8 +520,8 @@ Phaser.Particles.Arcade.Emitter.prototype.setXSpeed = function (min, max) { */ Phaser.Particles.Arcade.Emitter.prototype.setYSpeed = function (min, max) { - min = min || 0; - max = max || 0; + min = min || 0; + max = max || 0; this.minParticleSpeed.y = min; this.maxParticleSpeed.y = max; @@ -536,8 +536,8 @@ Phaser.Particles.Arcade.Emitter.prototype.setYSpeed = function (min, max) { */ Phaser.Particles.Arcade.Emitter.prototype.setRotation = function (min, max) { - min = min || 0; - max = max || 0; + min = min || 0; + max = max || 0; this.minRotation = min; this.maxRotation = max; diff --git a/src/physics/advanced/collision/QuadTree.js b/src/physics/advanced/collision/QuadTree.js index b0a48a733..1cf5c58b5 100644 --- a/src/physics/advanced/collision/QuadTree.js +++ b/src/physics/advanced/collision/QuadTree.js @@ -27,10 +27,10 @@ function QuadTree(bounds, pointQuad, maxDepth, maxChildren){ } /** - * The root node of the QuadTree which covers the entire area being segmented. - * @property root - * @type Node - */ + * The root node of the QuadTree which covers the entire area being segmented. + * @property root + * @type Node + */ this.root = node; } @@ -299,7 +299,7 @@ BoundsNode.prototype.insert = function(item){ console.log("radius:",item.boundingRadius); console.log("item x:",item.position[0] - item.boundingRadius,"x range:",node.bounds.x,node.bounds.x+node.bounds.width); console.log("item y:",item.position[1] - item.boundingRadius,"y range:",node.bounds.y,node.bounds.y+node.bounds.height); - */ + */ //todo: make _bounds bounds if( !(item instanceof Plane) && // Plane is infinite.. Make it a "stuck" child diff --git a/src/physics/advanced/collision/SAP1DBroadphase.js b/src/physics/advanced/collision/SAP1DBroadphase.js index 303d38da1..7aa14c7ce 100644 --- a/src/physics/advanced/collision/SAP1DBroadphase.js +++ b/src/physics/advanced/collision/SAP1DBroadphase.js @@ -19,24 +19,24 @@ function SAP1DBroadphase(world){ Broadphase.apply(this); /** - * List of bodies currently in the broadphase. - * @property axisList - * @type {Array} - */ + * List of bodies currently in the broadphase. + * @property axisList + * @type {Array} + */ this.axisList = world.bodies.slice(0); /** - * The world to search in. - * @property world - * @type {World} - */ + * The world to search in. + * @property world + * @type {World} + */ this.world = world; /** - * Axis to sort the bodies along. Set to 0 for x axis, and 1 for y axis. For best performance, choose an axis that the bodies are spread out more on. - * @property axisIndex - * @type {Number} - */ + * Axis to sort the bodies along. Set to 0 for x axis, and 1 for y axis. For best performance, choose an axis that the bodies are spread out more on. + * @property axisIndex + * @type {Number} + */ this.axisIndex = 0; // Add listeners to update the list of bodies. diff --git a/src/physics/advanced/constraints/Constraint.js b/src/physics/advanced/constraints/Constraint.js index df838cb1c..b73c03765 100644 --- a/src/physics/advanced/constraints/Constraint.js +++ b/src/physics/advanced/constraints/Constraint.js @@ -12,24 +12,24 @@ module.exports = Constraint; function Constraint(bodyA,bodyB){ /** - * Equations to be solved in this constraint - * @property equations - * @type {Array} - */ + * Equations to be solved in this constraint + * @property equations + * @type {Array} + */ this.equations = []; /** - * First body participating in the constraint. - * @property bodyA - * @type {Body} - */ + * First body participating in the constraint. + * @property bodyA + * @type {Body} + */ this.bodyA = bodyA; /** - * Second body participating in the constraint. - * @property bodyB - * @type {Body} - */ + * Second body participating in the constraint. + * @property bodyB + * @type {Body} + */ this.bodyB = bodyB; }; diff --git a/src/physics/advanced/constraints/Equation.js b/src/physics/advanced/constraints/Equation.js index 877f12227..2bbd564b4 100644 --- a/src/physics/advanced/constraints/Equation.js +++ b/src/physics/advanced/constraints/Equation.js @@ -12,45 +12,45 @@ module.exports = Equation; function Equation(bi,bj,minForce,maxForce){ /** - * Minimum force to apply when solving - * @property minForce - * @type {Number} - */ + * Minimum force to apply when solving + * @property minForce + * @type {Number} + */ this.minForce = typeof(minForce)=="undefined" ? -1e6 : minForce; /** - * Max force to apply when solving - * @property maxForce - * @type {Number} - */ + * Max force to apply when solving + * @property maxForce + * @type {Number} + */ this.maxForce = typeof(maxForce)=="undefined" ? 1e6 : maxForce; /** - * First body participating in the constraint - * @property bi - * @type {Body} - */ + * First body participating in the constraint + * @property bi + * @type {Body} + */ this.bi = bi; /** - * Second body participating in the constraint - * @property bj - * @type {Body} - */ + * Second body participating in the constraint + * @property bj + * @type {Body} + */ this.bj = bj; /** - * The stiffness of this equation. Typically chosen to a large number (~1e7), but can be chosen somewhat freely to get a stable simulation. - * @property stiffness - * @type {Number} - */ + * The stiffness of this equation. Typically chosen to a large number (~1e7), but can be chosen somewhat freely to get a stable simulation. + * @property stiffness + * @type {Number} + */ this.stiffness = 1e6; /** - * The number of time steps needed to stabilize the constraint equation. Typically between 3 and 5 time steps. - * @property relaxation - * @type {Number} - */ + * The number of time steps needed to stabilize the constraint equation. Typically between 3 and 5 time steps. + * @property relaxation + * @type {Number} + */ this.relaxation = 4; this.a = 0; diff --git a/src/physics/advanced/constraints/FrictionEquation.js b/src/physics/advanced/constraints/FrictionEquation.js index a8b09184f..d0a3e8120 100644 --- a/src/physics/advanced/constraints/FrictionEquation.js +++ b/src/physics/advanced/constraints/FrictionEquation.js @@ -31,24 +31,24 @@ function FrictionEquation(bi,bj,slipForce){ Equation.call(this,bi,bj,-slipForce,slipForce); /** - * Relative vector from center of body i to the contact point, in world coords. - * @property ri - * @type {Float32Array} - */ + * Relative vector from center of body i to the contact point, in world coords. + * @property ri + * @type {Float32Array} + */ this.ri = vec2.create(); /** - * Relative vector from center of body j to the contact point, in world coords. - * @property rj - * @type {Float32Array} - */ + * Relative vector from center of body j to the contact point, in world coords. + * @property rj + * @type {Float32Array} + */ this.rj = vec2.create(); /** - * Tangent vector that the friction force will act along, in world coords. - * @property t - * @type {Float32Array} - */ + * Tangent vector that the friction force will act along, in world coords. + * @property t + * @type {Float32Array} + */ this.t = vec2.create(); this.rixt = 0; diff --git a/src/physics/advanced/events/EventEmitter.js b/src/physics/advanced/events/EventEmitter.js index 576d20249..35bfbc7df 100644 --- a/src/physics/advanced/events/EventEmitter.js +++ b/src/physics/advanced/events/EventEmitter.js @@ -11,12 +11,12 @@ EventEmitter.prototype = { constructor: EventEmitter, /** - * Add an event listener - * @method on - * @param {String} type - * @param {Function} listener - * @return {EventEmitter} The self object, for chainability. - */ + * Add an event listener + * @method on + * @param {String} type + * @param {Function} listener + * @return {EventEmitter} The self object, for chainability. + */ on: function ( type, listener ) { if ( this._listeners === undefined ) this._listeners = {}; var listeners = this._listeners; @@ -30,12 +30,12 @@ EventEmitter.prototype = { }, /** - * Check if an event listener is added - * @method has - * @param {String} type - * @param {Function} listener - * @return {Boolean} - */ + * Check if an event listener is added + * @method has + * @param {String} type + * @param {Function} listener + * @return {Boolean} + */ has: function ( type, listener ) { if ( this._listeners === undefined ) return false; var listeners = this._listeners; @@ -46,12 +46,12 @@ EventEmitter.prototype = { }, /** - * Remove an event listener - * @method off - * @param {String} type - * @param {Function} listener - * @return {EventEmitter} The self object, for chainability. - */ + * Remove an event listener + * @method off + * @param {String} type + * @param {Function} listener + * @return {EventEmitter} The self object, for chainability. + */ off: function ( type, listener ) { if ( this._listeners === undefined ) return; var listeners = this._listeners; @@ -63,12 +63,12 @@ EventEmitter.prototype = { }, /** - * Emit an event. - * @method emit - * @param {Object} event - * @param {String} event.type - * @return {EventEmitter} The self object, for chainability. - */ + * Emit an event. + * @method emit + * @param {Object} event + * @param {String} event.type + * @return {EventEmitter} The self object, for chainability. + */ emit: function ( event ) { if ( this._listeners === undefined ) return; var listeners = this._listeners; diff --git a/src/physics/advanced/material/ContactMaterial.js b/src/physics/advanced/material/ContactMaterial.js index 6040c2d6e..0577e6081 100644 --- a/src/physics/advanced/material/ContactMaterial.js +++ b/src/physics/advanced/material/ContactMaterial.js @@ -17,65 +17,65 @@ function ContactMaterial(materialA, materialB, options){ options = options || {}; /** - * The contact material identifier - * @property id - * @type {Number} - */ + * The contact material identifier + * @property id + * @type {Number} + */ this.id = idCounter++; /** - * First material participating in the contact material - * @property materialA - * @type {Material} - */ + * First material participating in the contact material + * @property materialA + * @type {Material} + */ this.materialA = materialA; /** - * Second material participating in the contact material - * @property materialB - * @type {Material} - */ + * Second material participating in the contact material + * @property materialB + * @type {Material} + */ this.materialB = materialB; /** - * Friction to use in the contact of these two materials - * @property friction - * @type {Number} - */ + * Friction to use in the contact of these two materials + * @property friction + * @type {Number} + */ this.friction = typeof(options.friction) !== "undefined" ? Number(options.friction) : 0.3; /** - * Restitution to use in the contact of these two materials - * @property restitution - * @type {Number} - */ + * Restitution to use in the contact of these two materials + * @property restitution + * @type {Number} + */ this.restitution = typeof(options.restitution) !== "undefined" ? Number(options.restitution) : 0.3; /** - * Stiffness of the resulting ContactEquation that this ContactMaterial generate - * @property stiffness - * @type {Number} - */ + * Stiffness of the resulting ContactEquation that this ContactMaterial generate + * @property stiffness + * @type {Number} + */ this.stiffness = typeof(options.stiffness) !== "undefined" ? Number(options.stiffness) : 1e7; /** - * Relaxation of the resulting ContactEquation that this ContactMaterial generate - * @property relaxation - * @type {Number} - */ + * Relaxation of the resulting ContactEquation that this ContactMaterial generate + * @property relaxation + * @type {Number} + */ this.relaxation = typeof(options.relaxation) !== "undefined" ? Number(options.relaxation) : 3; /** - * Stiffness of the resulting FrictionEquation that this ContactMaterial generate - * @property frictionStiffness - * @type {Number} - */ + * Stiffness of the resulting FrictionEquation that this ContactMaterial generate + * @property frictionStiffness + * @type {Number} + */ this.frictionStiffness = typeof(options.frictionStiffness) !== "undefined" ? Number(options.frictionStiffness) : 1e7; /** - * Relaxation of the resulting FrictionEquation that this ContactMaterial generate - * @property frictionRelaxation - * @type {Number} - */ + * Relaxation of the resulting FrictionEquation that this ContactMaterial generate + * @property frictionRelaxation + * @type {Number} + */ this.frictionRelaxation = typeof(options.frictionRelaxation) !== "undefined" ? Number(options.frictionRelaxation) : 3; }; diff --git a/src/physics/advanced/material/Material.js b/src/physics/advanced/material/Material.js index 7c878dd9e..7ae21ea2d 100644 --- a/src/physics/advanced/material/Material.js +++ b/src/physics/advanced/material/Material.js @@ -11,9 +11,9 @@ var idCounter = 0; */ function Material(){ /** - * The material identifier - * @property id - * @type {Number} - */ + * The material identifier + * @property id + * @type {Number} + */ this.id = idCounter++; }; diff --git a/src/physics/advanced/math/polyk.js b/src/physics/advanced/math/polyk.js index 7be208332..6f4b4d5f4 100644 --- a/src/physics/advanced/math/polyk.js +++ b/src/physics/advanced/math/polyk.js @@ -472,6 +472,6 @@ PolyK._tp = []; for(var i=0; i<10; i++) PolyK._tp.push(new PolyK._P(0,0)); - */ + */ module.exports = PolyK; diff --git a/src/physics/advanced/objects/Body.js b/src/physics/advanced/objects/Body.js index eeaa004d1..701df13df 100644 --- a/src/physics/advanced/objects/Body.js +++ b/src/physics/advanced/objects/Body.js @@ -25,155 +25,155 @@ function Body(options){ options = options || {}; /** - * The body identifyer - * @property id - * @type {Number} - */ + * The body identifyer + * @property id + * @type {Number} + */ this.id = ++Body._idCounter; /** - * The shapes of the body. The local transform of the shape in .shapes[i] is - * defined by .shapeOffsets[i] and .shapeAngles[i]. - * - * @property shapes - * @type {Array} - */ + * The shapes of the body. The local transform of the shape in .shapes[i] is + * defined by .shapeOffsets[i] and .shapeAngles[i]. + * + * @property shapes + * @type {Array} + */ this.shapes = []; /** - * The local shape offsets, relative to the body center of mass. This is an - * array of Float32Array. - * @property shapeOffsets - * @type {Array} - */ + * The local shape offsets, relative to the body center of mass. This is an + * array of Float32Array. + * @property shapeOffsets + * @type {Array} + */ this.shapeOffsets = []; /** - * The body-local shape angle transforms. This is an array of numbers (angles). - * @property shapeAngles - * @type {Array} - */ + * The body-local shape angle transforms. This is an array of numbers (angles). + * @property shapeAngles + * @type {Array} + */ this.shapeAngles = []; /** - * The mass of the body. - * @property mass - * @type {number} - */ + * The mass of the body. + * @property mass + * @type {number} + */ this.mass = options.mass || 0; /** - * The inverse mass of the body. - * @property invMass - * @type {number} - */ + * The inverse mass of the body. + * @property invMass + * @type {number} + */ this.invMass = 0; /** - * The inertia of the body around the Z axis. - * @property inertia - * @type {number} - */ + * The inertia of the body around the Z axis. + * @property inertia + * @type {number} + */ this.inertia = 0; /** - * The inverse inertia of the body. - * @property invInertia - * @type {number} - */ + * The inverse inertia of the body. + * @property invInertia + * @type {number} + */ this.invInertia = 0; this.updateMassProperties(); /** - * The position of the body - * @property position - * @type {Float32Array} - */ + * The position of the body + * @property position + * @type {Float32Array} + */ this.position = vec2.fromValues(0,0); if(options.position) vec2.copy(this.position, options.position); /** - * The velocity of the body - * @property velocity - * @type {Float32Array} - */ + * The velocity of the body + * @property velocity + * @type {Float32Array} + */ this.velocity = vec2.fromValues(0,0); if(options.velocity) vec2.copy(this.velocity, options.velocity); /** - * Constraint velocity that was added to the body during the last step. - * @property vlambda - * @type {Float32Array} - */ + * Constraint velocity that was added to the body during the last step. + * @property vlambda + * @type {Float32Array} + */ this.vlambda = vec2.fromValues(0,0); /** - * Angular constraint velocity that was added to the body during last step. - * @property wlambda - * @type {Float32Array} - */ + * Angular constraint velocity that was added to the body during last step. + * @property wlambda + * @type {Float32Array} + */ this.wlambda = 0; /** - * The angle of the body - * @property angle - * @type {number} - */ + * The angle of the body + * @property angle + * @type {number} + */ this.angle = options.angle || 0; /** - * The angular velocity of the body - * @property angularVelocity - * @type {number} - */ + * The angular velocity of the body + * @property angularVelocity + * @type {number} + */ this.angularVelocity = options.angularVelocity || 0; /** - * The force acting on the body - * @property force - * @type {Float32Array} - */ + * The force acting on the body + * @property force + * @type {Float32Array} + */ this.force = vec2.create(); if(options.force) vec2.copy(this.force, options.force); /** - * The angular force acting on the body - * @property angularForce - * @type {number} - */ + * The angular force acting on the body + * @property angularForce + * @type {number} + */ this.angularForce = options.angularForce || 0; /** - * The type of motion this body has. Should be one of: Body.STATIC (the body - * does not move), Body.DYNAMIC (body can move and respond to collisions) - * and Body.KINEMATIC (only moves according to its .velocity). - * - * @property motionState - * @type {number} - * - * @example - * // This body will move and interact with other bodies - * var dynamicBody = new Body(); - * dynamicBody.motionState = Body.DYNAMIC; - * - * @example - * // This body will not move at all - * var staticBody = new Body(); - * staticBody.motionState = Body.STATIC; - * - * @example - * // This body will only move if you change its velocity - * var kinematicBody = new Body(); - * kinematicBody.motionState = Body.KINEMATIC; - */ + * The type of motion this body has. Should be one of: Body.STATIC (the body + * does not move), Body.DYNAMIC (body can move and respond to collisions) + * and Body.KINEMATIC (only moves according to its .velocity). + * + * @property motionState + * @type {number} + * + * @example + * // This body will move and interact with other bodies + * var dynamicBody = new Body(); + * dynamicBody.motionState = Body.DYNAMIC; + * + * @example + * // This body will not move at all + * var staticBody = new Body(); + * staticBody.motionState = Body.STATIC; + * + * @example + * // This body will only move if you change its velocity + * var kinematicBody = new Body(); + * kinematicBody.motionState = Body.KINEMATIC; + */ this.motionState = this.mass === 0 ? Body.STATIC : Body.DYNAMIC; /** - * Bounding circle radius - * @property boundingRadius - * @type {Number} - */ + * Bounding circle radius + * @property boundingRadius + * @type {Number} + */ this.boundingRadius = 0; }; diff --git a/src/physics/advanced/objects/Spring.js b/src/physics/advanced/objects/Spring.js index 44f7131cc..8105a9c5a 100644 --- a/src/physics/advanced/objects/Spring.js +++ b/src/physics/advanced/objects/Spring.js @@ -22,52 +22,52 @@ function Spring(bodyA,bodyB,options){ options = options || {}; /** - * Rest length of the spring. - * @property restLength - * @type {number} - */ + * Rest length of the spring. + * @property restLength + * @type {number} + */ this.restLength = typeof(options.restLength)=="number" ? options.restLength : 1; /** - * Stiffness of the spring. - * @property stiffness - * @type {number} - */ + * Stiffness of the spring. + * @property stiffness + * @type {number} + */ this.stiffness = options.stiffness || 100; /** - * Damping of the spring. - * @property damping - * @type {number} - */ + * Damping of the spring. + * @property damping + * @type {number} + */ this.damping = options.damping || 1; /** - * First connected body. - * @property bodyA - * @type {Body} - */ + * First connected body. + * @property bodyA + * @type {Body} + */ this.bodyA = bodyA; /** - * Second connected body. - * @property bodyB - * @type {Body} - */ + * Second connected body. + * @property bodyB + * @type {Body} + */ this.bodyB = bodyB; /** - * Anchor for bodyA in local bodyA coordinates. - * @property localAnchorA - * @type {Array} - */ + * Anchor for bodyA in local bodyA coordinates. + * @property localAnchorA + * @type {Array} + */ this.localAnchorA = vec2.fromValues(0,0); /** - * Anchor for bodyB in local bodyB coordinates. - * @property localAnchorB - * @type {Array} - */ + * Anchor for bodyB in local bodyB coordinates. + * @property localAnchorB + * @type {Array} + */ this.localAnchorB = vec2.fromValues(0,0); if(options.localAnchorA) vec2.copy(this.localAnchorA, options.localAnchorA); diff --git a/src/physics/advanced/shapes/Circle.js b/src/physics/advanced/shapes/Circle.js index 447e2cd94..9c2a1aeb6 100644 --- a/src/physics/advanced/shapes/Circle.js +++ b/src/physics/advanced/shapes/Circle.js @@ -12,10 +12,10 @@ module.exports = Circle; function Circle(radius){ /** - * The radius of the circle. - * @property radius - * @type {number} - */ + * The radius of the circle. + * @property radius + * @type {number} + */ this.radius = radius || 1; Shape.call(this,Shape.CIRCLE); diff --git a/src/physics/advanced/shapes/Convex.js b/src/physics/advanced/shapes/Convex.js index 8599608b2..61c4912d3 100644 --- a/src/physics/advanced/shapes/Convex.js +++ b/src/physics/advanced/shapes/Convex.js @@ -14,24 +14,24 @@ module.exports = Convex; function Convex(vertices){ /** - * Vertices defined in the local frame. - * @property vertices - * @type {Array} - */ + * Vertices defined in the local frame. + * @property vertices + * @type {Array} + */ this.vertices = vertices || []; /** - * The center of mass of the Convex - * @property centerOfMass - * @type {Float32Array} - */ + * The center of mass of the Convex + * @property centerOfMass + * @type {Float32Array} + */ this.centerOfMass = vec2.fromValues(0,0); /** - * Triangulated version of this convex. The structure is Array of 3-Arrays, and each subarray contains 3 integers, referencing the vertices. - * @property triangles - * @type {Array} - */ + * Triangulated version of this convex. The structure is Array of 3-Arrays, and each subarray contains 3 integers, referencing the vertices. + * @property triangles + * @type {Array} + */ this.triangles = []; if(this.vertices.length){ @@ -40,10 +40,10 @@ function Convex(vertices){ } /** - * The bounding radius of the convex - * @property boundingRadius - * @type {Number} - */ + * The bounding radius of the convex + * @property boundingRadius + * @type {Number} + */ this.boundingRadius = 0; this.updateBoundingRadius(); diff --git a/src/physics/advanced/shapes/Line.js b/src/physics/advanced/shapes/Line.js index 30fc9205c..630523eb1 100644 --- a/src/physics/advanced/shapes/Line.js +++ b/src/physics/advanced/shapes/Line.js @@ -11,10 +11,10 @@ module.exports = Line; function Line(length){ /** - * Length of this line - * @property length - * @type {Number} - */ + * Length of this line + * @property length + * @type {Number} + */ this.length = length; Shape.call(this,Shape.LINE); diff --git a/src/physics/advanced/shapes/Shape.js b/src/physics/advanced/shapes/Shape.js index 1d349b40a..b0a9d7088 100644 --- a/src/physics/advanced/shapes/Shape.js +++ b/src/physics/advanced/shapes/Shape.js @@ -9,56 +9,56 @@ function Shape(type){ this.type = type; /** - * Bounding circle radius of this shape - * @property boundingRadius - * @type {Number} - */ + * Bounding circle radius of this shape + * @property boundingRadius + * @type {Number} + */ this.boundingRadius = 0; /** - * Collision group that this shape belongs to (bit mask). See this tutorial. - * @property collisionGroup - * @type {Number} - * @example - * // Setup bits for each available group - * var PLAYER = Math.pow(2,0), - * ENEMY = Math.pow(2,1), - * GROUND = Math.pow(2,2) - * - * // Put shapes into their groups - * player1Shape.collisionGroup = PLAYER; - * player2Shape.collisionGroup = PLAYER; - * enemyShape .collisionGroup = ENEMY; - * groundShape .collisionGroup = GROUND; - * - * // Assign groups that each shape collide with. - * // Note that the players can collide with ground and enemies, but not with other players. - * player1Shape.collisionMask = ENEMY | GROUND; - * player2Shape.collisionMask = ENEMY | GROUND; - * enemyShape .collisionMask = PLAYER | GROUND; - * groundShape .collisionMask = PLAYER | ENEMY; - * - * @example - * // How collision check is done - * if(shapeA.collisionGroup & shapeB.collisionMask)!=0 && (shapeB.collisionGroup & shapeA.collisionMask)!=0){ - * // The shapes will collide - * } - */ + * Collision group that this shape belongs to (bit mask). See this tutorial. + * @property collisionGroup + * @type {Number} + * @example + * // Setup bits for each available group + * var PLAYER = Math.pow(2,0), + * ENEMY = Math.pow(2,1), + * GROUND = Math.pow(2,2) + * + * // Put shapes into their groups + * player1Shape.collisionGroup = PLAYER; + * player2Shape.collisionGroup = PLAYER; + * enemyShape .collisionGroup = ENEMY; + * groundShape .collisionGroup = GROUND; + * + * // Assign groups that each shape collide with. + * // Note that the players can collide with ground and enemies, but not with other players. + * player1Shape.collisionMask = ENEMY | GROUND; + * player2Shape.collisionMask = ENEMY | GROUND; + * enemyShape .collisionMask = PLAYER | GROUND; + * groundShape .collisionMask = PLAYER | ENEMY; + * + * @example + * // How collision check is done + * if(shapeA.collisionGroup & shapeB.collisionMask)!=0 && (shapeB.collisionGroup & shapeA.collisionMask)!=0){ + * // The shapes will collide + * } + */ this.collisionGroup = 1; /** - * Collision mask of this shape. See .collisionGroup. - * @property collisionMask - * @type {Number} - */ + * Collision mask of this shape. See .collisionGroup. + * @property collisionMask + * @type {Number} + */ this.collisionMask = 1; if(type) this.updateBoundingRadius(); /** - * Material to use in collisions for this Shape. If this is set to null, the world will use default material properties instead. - * @property material - * @type {Material} - */ + * Material to use in collisions for this Shape. If this is set to null, the world will use default material properties instead. + * @property material + * @type {Material} + */ this.material = null; }; diff --git a/src/physics/advanced/solver/GSSolver.js b/src/physics/advanced/solver/GSSolver.js index a2f25cb69..b5f6e7614 100644 --- a/src/physics/advanced/solver/GSSolver.js +++ b/src/physics/advanced/solver/GSSolver.js @@ -30,31 +30,31 @@ function GSSolver(options){ this.invCs = new ARRAY_TYPE(this.arrayStep); /** - * Whether to use .stiffness and .relaxation parameters from the Solver instead of each Equation individually. - * @type {Boolean} - * @property useGlobalEquationParameters - */ + * Whether to use .stiffness and .relaxation parameters from the Solver instead of each Equation individually. + * @type {Boolean} + * @property useGlobalEquationParameters + */ this.useGlobalEquationParameters = true; /** - * Global equation stiffness. - * @property stiffness - * @type {Number} - */ + * Global equation stiffness. + * @property stiffness + * @type {Number} + */ this.stiffness = 1e6; /** - * Global equation relaxation. - * @property relaxation - * @type {Number} - */ + * Global equation relaxation. + * @property relaxation + * @type {Number} + */ this.relaxation = 4; /** - * Set to true to set all right hand side terms to zero when solving. Can be handy for a few applications. - * @property useZeroRHS - * @type {Boolean} - */ + * Set to true to set all right hand side terms to zero when solving. Can be handy for a few applications. + * @property useZeroRHS + * @type {Boolean} + */ this.useZeroRHS = false; }; GSSolver.prototype = new Solver(); diff --git a/src/physics/advanced/solver/Island.js b/src/physics/advanced/solver/Island.js index b3c8635dd..ee5261ca6 100644 --- a/src/physics/advanced/solver/Island.js +++ b/src/physics/advanced/solver/Island.js @@ -8,17 +8,17 @@ module.exports = Island; function Island(){ /** - * Current equations in this island. - * @property equations - * @type {Array} - */ + * Current equations in this island. + * @property equations + * @type {Array} + */ this.equations = []; /** - * Current bodies in this island. - * @property bodies - * @type {Array} - */ + * Current bodies in this island. + * @property bodies + * @type {Array} + */ this.bodies = []; } diff --git a/src/physics/advanced/solver/IslandSolver.js b/src/physics/advanced/solver/IslandSolver.js index 9d4e35bef..73c5b79cb 100644 --- a/src/physics/advanced/solver/IslandSolver.js +++ b/src/physics/advanced/solver/IslandSolver.js @@ -19,17 +19,17 @@ function IslandSolver(subsolver){ var that = this; /** - * The solver used in the workers. - * @property subsolver - * @type {Solver} - */ + * The solver used in the workers. + * @property subsolver + * @type {Solver} + */ this.subsolver = subsolver; /** - * Number of islands - * @property numIslands - * @type {number} - */ + * Number of islands + * @property numIslands + * @type {number} + */ this.numIslands = 0; // Pooling of node objects saves some GC load diff --git a/src/physics/advanced/solver/Solver.js b/src/physics/advanced/solver/Solver.js index 6cb482b9b..5a1f83990 100644 --- a/src/physics/advanced/solver/Solver.js +++ b/src/physics/advanced/solver/Solver.js @@ -10,11 +10,11 @@ module.exports = Solver; function Solver(){ /** - * Current equations in the solver. - * - * @property equations - * @type {Array} - */ + * Current equations in the solver. + * + * @property equations + * @type {Array} + */ this.equations = []; }; diff --git a/src/physics/advanced/world/World.js b/src/physics/advanced/world/World.js index 1c209d39f..4d1e05409 100644 --- a/src/physics/advanced/world/World.js +++ b/src/physics/advanced/world/World.js @@ -48,110 +48,110 @@ function World(options){ options = options || {}; /** - * All springs in the world. - * - * @property springs - * @type {Array} - */ + * All springs in the world. + * + * @property springs + * @type {Array} + */ this.springs = []; /** - * All bodies in the world. - * - * @property bodies - * @type {Array} - */ + * All bodies in the world. + * + * @property bodies + * @type {Array} + */ this.bodies = []; /** - * The solver used to satisfy constraints and contacts. - * - * @property solver - * @type {Solver} - */ + * The solver used to satisfy constraints and contacts. + * + * @property solver + * @type {Solver} + */ this.solver = options.solver || new GSSolver(); /** - * The nearphase to use to generate contacts. - * - * @property nearphase - * @type {Nearphase} - */ + * The nearphase to use to generate contacts. + * + * @property nearphase + * @type {Nearphase} + */ this.nearphase = new Nearphase(); /** - * Gravity in the world. This is applied on all bodies in the beginning of each step(). - * - * @property - * @type {Float32Array} - */ + * Gravity in the world. This is applied on all bodies in the beginning of each step(). + * + * @property + * @type {Float32Array} + */ this.gravity = options.gravity || vec2.fromValues(0, -9.78); /** - * Whether to do timing measurements during the step() or not. - * - * @property doPofiling - * @type {Boolean} - */ + * Whether to do timing measurements during the step() or not. + * + * @property doPofiling + * @type {Boolean} + */ this.doProfiling = options.doProfiling || false; /** - * How many millisecconds the last step() took. This is updated each step if .doProfiling is set to true. - * - * @property lastStepTime - * @type {Number} - */ + * How many millisecconds the last step() took. This is updated each step if .doProfiling is set to true. + * + * @property lastStepTime + * @type {Number} + */ this.lastStepTime = 0.0; /** - * The broadphase algorithm to use. - * - * @property broadphase - * @type {Broadphase} - */ + * The broadphase algorithm to use. + * + * @property broadphase + * @type {Broadphase} + */ this.broadphase = options.broadphase || new NaiveBroadphase(); /** - * User-added constraints. - * - * @property constraints - * @type {Array} - */ + * User-added constraints. + * + * @property constraints + * @type {Array} + */ this.constraints = []; /** - * Friction between colliding bodies. This value is used if no matching ContactMaterial is found for the body pair. - * @property defaultFriction - * @type {Number} - */ + * Friction between colliding bodies. This value is used if no matching ContactMaterial is found for the body pair. + * @property defaultFriction + * @type {Number} + */ this.defaultFriction = 0.1; /** - * For keeping track of what time step size we used last step - * @property lastTimeStep - * @type {Number} - */ + * For keeping track of what time step size we used last step + * @property lastTimeStep + * @type {Number} + */ this.lastTimeStep = 1/60; /** - * Enable to automatically apply spring forces each step. - * @property applySpringForces - * @type {Boolean} - */ + * Enable to automatically apply spring forces each step. + * @property applySpringForces + * @type {Boolean} + */ this.applySpringForces = true; /** - * Enable/disable constraint solving in each step. - * @property solveConstraints - * @type {Boolean} - */ + * Enable/disable constraint solving in each step. + * @property solveConstraints + * @type {Boolean} + */ this.solveConstraints = true; /** - * The ContactMaterials added to the World. - * @property contactMaterials - * @type {Array} - */ + * The ContactMaterials added to the World. + * @property contactMaterials + * @type {Array} + */ this.contactMaterials = []; // Id counters diff --git a/src/physics/arcade/ArcadePhysics.js b/src/physics/arcade/ArcadePhysics.js index 60c76c106..b06959e60 100644 --- a/src/physics/arcade/ArcadePhysics.js +++ b/src/physics/arcade/ArcadePhysics.js @@ -27,7 +27,7 @@ Phaser.Physics.Arcade = function (game) { /** * @property {Phaser.Point} gravity - The World gravity setting. Defaults to x: 0, y: 0, or no gravity. */ - this.gravity = new Phaser.Point; + this.gravity = new Phaser.Point(); /** * @property {Phaser.Rectangle} bounds - The bounds inside of which the physics world exists. Defaults to match the world bounds. @@ -65,13 +65,13 @@ Phaser.Physics.Arcade = function (game) { * @property {Phaser.Rectangle} _bounds1 - Internal cache var. * @private */ - this._bounds1 = new Phaser.Rectangle; + this._bounds1 = new Phaser.Rectangle(); /** * @property {Phaser.Rectangle} _bounds2 - Internal cache var. * @private */ - this._bounds2 = new Phaser.Rectangle; + this._bounds2 = new Phaser.Rectangle(); /** * @property {number} _overlap - Internal cache var. @@ -462,7 +462,7 @@ Phaser.Physics.Arcade.prototype = { { var currentNode = group._container.first._iNext; - do + do { if (currentNode.exists) { @@ -572,7 +572,7 @@ Phaser.Physics.Arcade.prototype = { { var currentNode = group1._container.first._iNext; - do + do { if (currentNode.exists) { @@ -658,7 +658,7 @@ Phaser.Physics.Arcade.prototype = { } // Then adjust their positions and velocities accordingly (if there was any overlap) - if (this._overlap != 0) + if (this._overlap !== 0) { body1.overlapX = this._overlap; body2.overlapX = this._overlap; @@ -766,7 +766,7 @@ Phaser.Physics.Arcade.prototype = { } // Then adjust their positions and velocities accordingly (if there was any overlap) - if (this._overlap != 0) + if (this._overlap !== 0) { body1.overlapY = this._overlap; body2.overlapY = this._overlap; @@ -894,7 +894,7 @@ Phaser.Physics.Arcade.prototype = { } // Then adjust their positions and velocities accordingly (if there was any overlap) - if (this._overlap != 0) + if (this._overlap !== 0) { if (separate) { @@ -980,7 +980,7 @@ Phaser.Physics.Arcade.prototype = { } // Then adjust their positions and velocities accordingly (if there was any overlap) - if (this._overlap != 0) + if (this._overlap !== 0) { if (separate) { @@ -1133,7 +1133,7 @@ Phaser.Physics.Arcade.prototype = { velocityFromAngle: function (angle, speed, point) { if (typeof speed === 'undefined') { speed = 60; } - point = point || new Phaser.Point; + point = point || new Phaser.Point(); return point.setTo((Math.cos(this.game.math.degToRad(angle)) * speed), (Math.sin(this.game.math.degToRad(angle)) * speed)); @@ -1152,7 +1152,7 @@ Phaser.Physics.Arcade.prototype = { velocityFromRotation: function (rotation, speed, point) { if (typeof speed === 'undefined') { speed = 60; } - point = point || new Phaser.Point; + point = point || new Phaser.Point(); return point.setTo((Math.cos(rotation) * speed), (Math.sin(rotation) * speed)); @@ -1171,7 +1171,7 @@ Phaser.Physics.Arcade.prototype = { accelerationFromRotation: function (rotation, speed, point) { if (typeof speed === 'undefined') { speed = 60; } - point = point || new Phaser.Point; + point = point || new Phaser.Point(); return point.setTo((Math.cos(rotation) * speed), (Math.sin(rotation) * speed)); diff --git a/src/physics/arcade/Body.js b/src/physics/arcade/Body.js index c8a5edadf..f1441d5e9 100644 --- a/src/physics/arcade/Body.js +++ b/src/physics/arcade/Body.js @@ -18,91 +18,91 @@ Phaser.Physics.Arcade.Body = function (sprite) { /** * @property {Phaser.Sprite} sprite - Reference to the parent Sprite. */ - this.sprite = sprite; + this.sprite = sprite; /** * @property {Phaser.Game} game - Local reference to game. */ - this.game = sprite.game; + this.game = sprite.game; /** * @property {Phaser.Point} offset - The offset of the Physics Body from the Sprite x/y position. */ - this.offset = new Phaser.Point; + this.offset = new Phaser.Point(); /** * @property {number} x - The x position of the physics body. * @readonly */ - this.x = sprite.x; + this.x = sprite.x; /** * @property {number} y - The y position of the physics body. * @readonly */ - this.y = sprite.y; + this.y = sprite.y; /** * @property {number} preX - The previous x position of the physics body. * @readonly */ - this.preX = sprite.x; + this.preX = sprite.x; /** * @property {number} preY - The previous y position of the physics body. * @readonly */ - this.preY = sprite.y; + this.preY = sprite.y; /** * @property {number} preRotation - The previous rotation of the physics body. * @readonly */ - this.preRotation = sprite.angle; + this.preRotation = sprite.angle; /** * @property {number} screenX - The x position of the physics body translated to screen space. * @readonly */ - this.screenX = sprite.x; + this.screenX = sprite.x; /** * @property {number} screenY - The y position of the physics body translated to screen space. * @readonly */ - this.screenY = sprite.y; + this.screenY = sprite.y; /** * @property {number} sourceWidth - The un-scaled original size. * @readonly */ - this.sourceWidth = sprite.currentFrame.sourceSizeW; + this.sourceWidth = sprite.currentFrame.sourceSizeW; /** * @property {number} sourceHeight - The un-scaled original size. * @readonly */ - this.sourceHeight = sprite.currentFrame.sourceSizeH; + this.sourceHeight = sprite.currentFrame.sourceSizeH; /** * @property {number} width - The calculated width of the physics body. */ - this.width = sprite.currentFrame.sourceSizeW; + this.width = sprite.currentFrame.sourceSizeW; /** * @property .numInternal ID cache */ - this.height = sprite.currentFrame.sourceSizeH; + this.height = sprite.currentFrame.sourceSizeH; /** * @property {number} halfWidth - The calculated width / 2 of the physics body. */ - this.halfWidth = Math.floor(sprite.currentFrame.sourceSizeW / 2); + this.halfWidth = Math.floor(sprite.currentFrame.sourceSizeW / 2); /** * @property {number} halfHeight - The calculated height / 2 of the physics body. */ - this.halfHeight = Math.floor(sprite.currentFrame.sourceSizeH / 2); + this.halfHeight = Math.floor(sprite.currentFrame.sourceSizeH / 2); /** * @property {Phaser.Point} center - The center coordinate of the Physics Body. @@ -113,38 +113,38 @@ Phaser.Physics.Arcade.Body = function (sprite) { * @property {number} _sx - Internal cache var. * @private */ - this._sx = sprite.scale.x; + this._sx = sprite.scale.x; /** * @property {number} _sy - Internal cache var. * @private */ - this._sy = sprite.scale.y; + this._sy = sprite.scale.y; /** * @property {Phaser.Point} velocity - The velocity in pixels per second sq. of the Body. */ - this.velocity = new Phaser.Point; + this.velocity = new Phaser.Point(); /** * @property {Phaser.Point} acceleration - The velocity in pixels per second sq. of the Body. */ - this.acceleration = new Phaser.Point; + this.acceleration = new Phaser.Point(); /** * @property {Phaser.Point} drag - The drag applied to the motion of the Body. */ - this.drag = new Phaser.Point; + this.drag = new Phaser.Point(); /** * @property {Phaser.Point} gravity - A private Gravity setting for the Body. */ - this.gravity = new Phaser.Point; + this.gravity = new Phaser.Point(); /** * @property {Phaser.Point} bounce - The elasticitiy of the Body when colliding. bounce.x/y = 1 means full rebound, bounce.x/y = 0.5 means 50% rebound velocity. */ - this.bounce = new Phaser.Point; + this.bounce = new Phaser.Point(); /** * @property {Phaser.Point} maxVelocity - The maximum velocity in pixels per second sq. that the Body can reach. @@ -200,7 +200,7 @@ Phaser.Physics.Arcade.Body = function (sprite) { */ this.quadTreeIndex = -1; - // Allow collision + // Allow collision /** * Set the allowCollision properties to control which directions collision is processed for this Body. @@ -318,20 +318,20 @@ Phaser.Physics.Arcade.Body.prototype = { * @method Phaser.Physics.Arcade#updateBounds * @protected */ - updateBounds: function (centerX, centerY, scaleX, scaleY) { + updateBounds: function (centerX, centerY, scaleX, scaleY) { - if (scaleX != this._sx || scaleY != this._sy) - { - this.width = this.sourceWidth * scaleX; - this.height = this.sourceHeight * scaleY; - this.halfWidth = Math.floor(this.width / 2); - this.halfHeight = Math.floor(this.height / 2); - this._sx = scaleX; - this._sy = scaleY; + if (scaleX != this._sx || scaleY != this._sy) + { + this.width = this.sourceWidth * scaleX; + this.height = this.sourceHeight * scaleY; + this.halfWidth = Math.floor(this.width / 2); + this.halfHeight = Math.floor(this.height / 2); + this._sx = scaleX; + this._sy = scaleY; this.center.setTo(this.x + this.halfWidth, this.y + this.halfHeight); - } + } - }, + }, /** * Internal method. @@ -339,55 +339,55 @@ Phaser.Physics.Arcade.Body.prototype = { * @method Phaser.Physics.Arcade#preUpdate * @protected */ - preUpdate: function () { + preUpdate: function () { - // Store and reset collision flags - this.wasTouching.none = this.touching.none; - this.wasTouching.up = this.touching.up; - this.wasTouching.down = this.touching.down; - this.wasTouching.left = this.touching.left; - this.wasTouching.right = this.touching.right; + // Store and reset collision flags + this.wasTouching.none = this.touching.none; + this.wasTouching.up = this.touching.up; + this.wasTouching.down = this.touching.down; + this.wasTouching.left = this.touching.left; + this.wasTouching.right = this.touching.right; - this.touching.none = true; - this.touching.up = false; - this.touching.down = false; - this.touching.left = false; - this.touching.right = false; + this.touching.none = true; + this.touching.up = false; + this.touching.down = false; + this.touching.left = false; + this.touching.right = false; - this.embedded = false; + this.embedded = false; - this.screenX = (this.sprite.worldTransform[2] - (this.sprite.anchor.x * this.width)) + this.offset.x; - this.screenY = (this.sprite.worldTransform[5] - (this.sprite.anchor.y * this.height)) + this.offset.y; + this.screenX = (this.sprite.worldTransform[2] - (this.sprite.anchor.x * this.width)) + this.offset.x; + this.screenY = (this.sprite.worldTransform[5] - (this.sprite.anchor.y * this.height)) + this.offset.y; this.preX = (this.sprite.world.x - (this.sprite.anchor.x * this.width)) + this.offset.x; this.preY = (this.sprite.world.y - (this.sprite.anchor.y * this.height)) + this.offset.y; - this.preRotation = this.sprite.angle; + this.preRotation = this.sprite.angle; - this.x = this.preX; - this.y = this.preY; - this.rotation = this.preRotation; + this.x = this.preX; + this.y = this.preY; + this.rotation = this.preRotation; - if (this.moves) - { - this.game.physics.updateMotion(this); + if (this.moves) + { + this.game.physics.updateMotion(this); - if (this.collideWorldBounds) - { - this.checkWorldBounds(); - } + if (this.collideWorldBounds) + { + this.checkWorldBounds(); + } - this.updateHulls(); + this.updateHulls(); } - if (this.skipQuadTree === false && this.allowCollision.none === false && this.sprite.visible && this.sprite.alive) - { - this.quadTreeIDs = []; - this.quadTreeIndex = -1; - this.game.physics.quadTree.insert(this); - } + if (this.skipQuadTree === false && this.allowCollision.none === false && this.sprite.visible && this.sprite.alive) + { + this.quadTreeIDs = []; + this.quadTreeIndex = -1; + this.game.physics.quadTree.insert(this); + } - }, + }, /** * Internal method. @@ -395,25 +395,25 @@ Phaser.Physics.Arcade.Body.prototype = { * @method Phaser.Physics.Arcade#postUpdate * @protected */ - postUpdate: function () { + postUpdate: function () { - if (this.deltaX() < 0) - { - this.facing = Phaser.LEFT; - } - else if (this.deltaX() > 0) - { - this.facing = Phaser.RIGHT; - } + if (this.deltaX() < 0) + { + this.facing = Phaser.LEFT; + } + else if (this.deltaX() > 0) + { + this.facing = Phaser.RIGHT; + } - if (this.deltaY() < 0) - { - this.facing = Phaser.UP; - } - else if (this.deltaY() > 0) - { - this.facing = Phaser.DOWN; - } + if (this.deltaY() < 0) + { + this.facing = Phaser.UP; + } + else if (this.deltaY() > 0) + { + this.facing = Phaser.DOWN; + } if (this.deltaX() !== 0 || this.deltaY() !== 0) { @@ -422,12 +422,12 @@ Phaser.Physics.Arcade.Body.prototype = { this.center.setTo(this.x + this.halfWidth, this.y + this.halfHeight); } - if (this.allowRotation) - { - this.sprite.angle += this.deltaZ(); - } + if (this.allowRotation) + { + this.sprite.angle += this.deltaZ(); + } - }, + }, /** * Internal method. @@ -435,12 +435,12 @@ Phaser.Physics.Arcade.Body.prototype = { * @method Phaser.Physics.Arcade#updateHulls * @protected */ - updateHulls: function () { + updateHulls: function () { - this.hullX.setTo(this.x, this.preY, this.width, this.height); - this.hullY.setTo(this.preX, this.y, this.width, this.height); + this.hullX.setTo(this.x, this.preY, this.width, this.height); + this.hullY.setTo(this.preX, this.y, this.width, this.height); - }, + }, /** * Internal method. @@ -448,31 +448,31 @@ Phaser.Physics.Arcade.Body.prototype = { * @method Phaser.Physics.Arcade#checkWorldBounds * @protected */ - checkWorldBounds: function () { + checkWorldBounds: function () { - if (this.x < this.game.world.bounds.x) - { - this.x = this.game.world.bounds.x; - this.velocity.x *= -this.bounce.x; - } - else if (this.right > this.game.world.bounds.right) - { - this.x = this.game.world.bounds.right - this.width; - this.velocity.x *= -this.bounce.x; - } + if (this.x < this.game.world.bounds.x) + { + this.x = this.game.world.bounds.x; + this.velocity.x *= -this.bounce.x; + } + else if (this.right > this.game.world.bounds.right) + { + this.x = this.game.world.bounds.right - this.width; + this.velocity.x *= -this.bounce.x; + } - if (this.y < this.game.world.bounds.y) - { - this.y = this.game.world.bounds.y; - this.velocity.y *= -this.bounce.y; - } - else if (this.bottom > this.game.world.bounds.bottom) - { - this.y = this.game.world.bounds.bottom - this.height; - this.velocity.y *= -this.bounce.y; - } + if (this.y < this.game.world.bounds.y) + { + this.y = this.game.world.bounds.y; + this.velocity.y *= -this.bounce.y; + } + else if (this.bottom > this.game.world.bounds.bottom) + { + this.y = this.game.world.bounds.bottom - this.height; + this.velocity.y *= -this.bounce.y; + } - }, + }, /** * You can modify the size of the physics Body to be any dimension you need. @@ -485,46 +485,46 @@ Phaser.Physics.Arcade.Body.prototype = { * @param {number} offsetX - The X offset of the Body from the Sprite position. * @param {number} offsetY - The Y offset of the Body from the Sprite position. */ - setSize: function (width, height, offsetX, offsetY) { + setSize: function (width, height, offsetX, offsetY) { - offsetX = offsetX || this.offset.x; - offsetY = offsetY || this.offset.y; + offsetX = offsetX || this.offset.x; + offsetY = offsetY || this.offset.y; - this.sourceWidth = width; - this.sourceHeight = height; - this.width = this.sourceWidth * this._sx; - this.height = this.sourceHeight * this._sy; - this.halfWidth = Math.floor(this.width / 2); - this.halfHeight = Math.floor(this.height / 2); - this.offset.setTo(offsetX, offsetY); + this.sourceWidth = width; + this.sourceHeight = height; + this.width = this.sourceWidth * this._sx; + this.height = this.sourceHeight * this._sy; + this.halfWidth = Math.floor(this.width / 2); + this.halfHeight = Math.floor(this.height / 2); + this.offset.setTo(offsetX, offsetY); this.center.setTo(this.x + this.halfWidth, this.y + this.halfHeight); - }, + }, /** * Resets all Body values (velocity, acceleration, rotation, etc) * * @method Phaser.Physics.Arcade#reset */ - reset: function () { + reset: function () { - this.velocity.setTo(0, 0); - this.acceleration.setTo(0, 0); + this.velocity.setTo(0, 0); + this.acceleration.setTo(0, 0); - this.angularVelocity = 0; - this.angularAcceleration = 0; + this.angularVelocity = 0; + this.angularAcceleration = 0; this.preX = (this.sprite.world.x - (this.sprite.anchor.x * this.width)) + this.offset.x; this.preY = (this.sprite.world.y - (this.sprite.anchor.y * this.height)) + this.offset.y; - this.preRotation = this.sprite.angle; + this.preRotation = this.sprite.angle; - this.x = this.preX; - this.y = this.preY; - this.rotation = this.preRotation; + this.x = this.preX; + this.y = this.preY; + this.rotation = this.preRotation; this.center.setTo(this.x + this.halfWidth, this.y + this.halfHeight); - }, + }, /** * Returns the absolute delta x value. @@ -591,7 +591,7 @@ Object.defineProperty(Phaser.Physics.Arcade.Body.prototype, "bottom", { * 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. * @method bottom * @param {number} value - */ + */ set: function (value) { if (value <= this.y) @@ -618,7 +618,7 @@ Object.defineProperty(Phaser.Physics.Arcade.Body.prototype, "right", { * However it does affect the width property. * @method right * @return {number} - */ + */ get: function () { return this.x + this.width; }, diff --git a/src/pixi/core/Circle.js b/src/pixi/core/Circle.js index e2728335b..3844f426f 100644 --- a/src/pixi/core/Circle.js +++ b/src/pixi/core/Circle.js @@ -14,24 +14,24 @@ PIXI.Circle = function(x, y, radius) { /** - * @property x - * @type Number - * @default 0 - */ + * @property x + * @type Number + * @default 0 + */ this.x = x || 0; /** - * @property y - * @type Number - * @default 0 - */ + * @property y + * @type Number + * @default 0 + */ this.y = y || 0; /** - * @property radius - * @type Number - * @default 0 - */ + * @property radius + * @type Number + * @default 0 + */ this.radius = radius || 0; } diff --git a/src/pixi/core/Ellipse.js b/src/pixi/core/Ellipse.js index 1a95d20a1..0d05b3ed8 100644 --- a/src/pixi/core/Ellipse.js +++ b/src/pixi/core/Ellipse.js @@ -15,31 +15,31 @@ PIXI.Ellipse = function(x, y, width, height) { /** - * @property x - * @type Number - * @default 0 - */ + * @property x + * @type Number + * @default 0 + */ this.x = x || 0; /** - * @property y - * @type Number - * @default 0 - */ + * @property y + * @type Number + * @default 0 + */ this.y = y || 0; /** - * @property width - * @type Number - * @default 0 - */ + * @property width + * @type Number + * @default 0 + */ this.width = width || 0; /** - * @property height - * @type Number - * @default 0 - */ + * @property height + * @type Number + * @default 0 + */ this.height = height || 0; } diff --git a/src/pixi/display/Sprite.js b/src/pixi/display/Sprite.js index e567c7956..bb36f1b1b 100644 --- a/src/pixi/display/Sprite.js +++ b/src/pixi/display/Sprite.js @@ -26,9 +26,9 @@ PIXI.Sprite = function(texture) * Setting than anchor to 0.5,0.5 means the textures origin is centered * Setting the anchor to 1,1 would mean the textures origin points will be the bottom right * - * @property anchor - * @type Point - */ + * @property anchor + * @type Point + */ this.anchor = new PIXI.Point(); /** diff --git a/src/pixi/loaders/AssetLoader.js b/src/pixi/loaders/AssetLoader.js index ee3b016a7..d984d8898 100644 --- a/src/pixi/loaders/AssetLoader.js +++ b/src/pixi/loaders/AssetLoader.js @@ -24,26 +24,26 @@ PIXI.AssetLoader = function(assetURLs, crossorigin) /** * The array of asset URLs that are going to be loaded - * + * * @property assetURLs * @type Array */ this.assetURLs = assetURLs; /** - * Whether the requests should be treated as cross origin - * - * @property crossorigin - * @type Boolean - */ + * Whether the requests should be treated as cross origin + * + * @property crossorigin + * @type Boolean + */ this.crossorigin = crossorigin; /** - * Maps file extension to loader types - * - * @property loadersByType - * @type Object - */ + * Maps file extension to loader types + * + * @property loadersByType + * @type Object + */ this.loadersByType = { "jpg": PIXI.ImageLoader, "jpeg": PIXI.ImageLoader, diff --git a/src/pixi/loaders/BitmapFontLoader.js b/src/pixi/loaders/BitmapFontLoader.js index ef0509437..f0b0aef93 100644 --- a/src/pixi/loaders/BitmapFontLoader.js +++ b/src/pixi/loaders/BitmapFontLoader.js @@ -17,43 +17,43 @@ PIXI.BitmapFontLoader = function(url, crossorigin) { /* - * i use texture packer to load the assets.. - * http://www.codeandweb.com/texturepacker - * make sure to set the format as "JSON" - */ + * i use texture packer to load the assets.. + * http://www.codeandweb.com/texturepacker + * make sure to set the format as "JSON" + */ PIXI.EventTarget.call(this); /** - * The url of the bitmap font data - * - * @property url - * @type String - */ + * The url of the bitmap font data + * + * @property url + * @type String + */ this.url = url; /** - * Whether the requests should be treated as cross origin - * - * @property crossorigin - * @type Boolean - */ + * Whether the requests should be treated as cross origin + * + * @property crossorigin + * @type Boolean + */ this.crossorigin = crossorigin; /** - * [read-only] The base url of the bitmap font data - * - * @property baseUrl - * @type String - * @readOnly - */ + * [read-only] The base url of the bitmap font data + * + * @property baseUrl + * @type String + * @readOnly + */ this.baseUrl = url.replace(/[^\/]*$/, ""); /** - * [read-only] The texture of the bitmap font - * - * @property baseUrl - * @type String - */ + * [read-only] The texture of the bitmap font + * + * @property baseUrl + * @type String + */ this.texture = null; }; diff --git a/src/pixi/loaders/ImageLoader.js b/src/pixi/loaders/ImageLoader.js index d8a413745..2372b10c5 100644 --- a/src/pixi/loaders/ImageLoader.js +++ b/src/pixi/loaders/ImageLoader.js @@ -18,18 +18,18 @@ PIXI.ImageLoader = function(url, crossorigin) PIXI.EventTarget.call(this); /** - * The texture being loaded - * - * @property texture - * @type Texture - */ + * The texture being loaded + * + * @property texture + * @type Texture + */ this.texture = PIXI.Texture.fromImage(url, crossorigin); /** - * if the image is loaded with loadFramedSpriteSheet - * frames will contain the sprite sheet frames - * - */ + * if the image is loaded with loadFramedSpriteSheet + * frames will contain the sprite sheet frames + * + */ this.frames = []; }; diff --git a/src/pixi/loaders/SpriteSheetLoader.js b/src/pixi/loaders/SpriteSheetLoader.js index 169fb70df..9490d57c7 100644 --- a/src/pixi/loaders/SpriteSheetLoader.js +++ b/src/pixi/loaders/SpriteSheetLoader.js @@ -52,19 +52,19 @@ PIXI.SpriteSheetLoader = function (url, crossorigin) { this.baseUrl = url.replace(/[^\/]*$/, ""); /** - * The texture being loaded - * - * @property texture - * @type Texture - */ + * The texture being loaded + * + * @property texture + * @type Texture + */ this.texture = null; /** - * The frames of the sprite sheet - * - * @property frames - * @type Object - */ + * The frames of the sprite sheet + * + * @property frames + * @type Object + */ this.frames = {}; }; diff --git a/src/pixi/primitives/Graphics.js b/src/pixi/primitives/Graphics.js index 0eeb147c8..c15d701a9 100644 --- a/src/pixi/primitives/Graphics.js +++ b/src/pixi/primitives/Graphics.js @@ -19,45 +19,45 @@ PIXI.Graphics = function() this.renderable = true; /** - * The alpha of the fill of this graphics object - * - * @property fillAlpha - * @type Number - */ + * The alpha of the fill of this graphics object + * + * @property fillAlpha + * @type Number + */ this.fillAlpha = 1; /** - * The width of any lines drawn - * - * @property lineWidth - * @type Number - */ + * The width of any lines drawn + * + * @property lineWidth + * @type Number + */ this.lineWidth = 0; /** - * The color of any lines drawn - * - * @property lineColor - * @type String - */ + * The color of any lines drawn + * + * @property lineColor + * @type String + */ this.lineColor = "black"; /** - * Graphics data - * - * @property graphicsData - * @type Array - * @private - */ + * Graphics data + * + * @property graphicsData + * @type Array + * @private + */ this.graphicsData = []; /** - * Current path - * - * @property currentPath - * @type Object - * @private - */ + * Current path + * + * @property currentPath + * @type Object + * @private + */ this.currentPath = {points:[]}; } diff --git a/src/sound/Sound.js b/src/sound/Sound.js index 95dcd13a6..7c7a48a05 100644 --- a/src/sound/Sound.js +++ b/src/sound/Sound.js @@ -16,9 +16,9 @@ * @param {boolean} [loop=false] - Whether or not the sound will loop. */ Phaser.Sound = function (game, key, volume, loop) { - + if (typeof volume == 'undefined') { volume = 1; } - if (typeof loop == 'undefined') { loop = false; } + if (typeof loop == 'undefined') { loop = false; } /** * A reference to the currently running Game. @@ -27,157 +27,128 @@ Phaser.Sound = function (game, key, volume, loop) { this.game = game; /** - * Name of the sound. - * @property {string} name - * @default + * @property {string} name - Name of the sound. */ this.name = key; /** - * Asset key for the sound. - * @property {string} key + * @property {string} key - Asset key for the sound. */ this.key = key; /** - * Whether or not the sound will loop. - * @property {boolean} loop + * @property {boolean} loop - Whether or not the sound will loop. */ this.loop = loop; /** - * The global audio volume. A value between 0 (silence) and 1 (full volume). - * @property {number} _volume + * @property {number} _volume - The global audio volume. A value between 0 (silence) and 1 (full volume). * @private */ this._volume = volume; /** - * The sound markers, empty by default. - * @property {object} markers + * @property {object} markers - The sound markers. */ this.markers = {}; - /** - * Reference to AudioContext instance. - * @property {AudioContext} context - * @default + * @property {AudioContext} context - Reference to the AudioContext instance. */ this.context = null; /** - * Decoded data buffer / Audio tag. - * @property {Description} _buffer + * @property {Description} _buffer - Decoded data buffer / Audio tag. * @private */ this._buffer = null; /** - * Boolean indicating whether the game is on "mute". - * @property {boolean} _muted + * @property {boolean} _muted - Boolean indicating whether the sound is muted or not. * @private * @default */ this._muted = false; /** - * Boolean indicating whether the sound should start automatically. - * @property {boolean} autoplay - * @private + * @property {boolean} autoplay - Boolean indicating whether the sound should start automatically. */ this.autoplay = false; /** - * The total duration of the sound, in milliseconds - * @property {number} totalDuration - * @default + * @property {number} totalDuration - The total duration of the sound, in milliseconds */ this.totalDuration = 0; /** - * Description. - * @property {number} startTime + * @property {number} startTime - The time the Sound starts at (typically 0 unless starting from a marker) * @default */ this.startTime = 0; /** - * Description. - * @property {number} currentTime - * @default + * @property {number} currentTime - The current time the sound is at. */ this.currentTime = 0; /** - * Description. - * @property {number} duration - * @default + * @property {number} duration - The duration of the sound. */ this.duration = 0; /** - * Description. - * @property {number} stopTime + * @property {number} stopTime - The time the sound stopped. */ this.stopTime = 0; /** - * Description. - * @property {boolean} paused + * @property {boolean} paused - true if the sound is paused, otherwise false. * @default */ this.paused = false; /** - * Description. - * @property {number} pausedPosition + * @property {number} pausedPosition - The position the sound had reached when it was paused. */ this.pausedPosition = 0; /** - * Description. - * @property {number} pausedTime + * @property {number} pausedTime - The game time at which the sound was paused. */ this.pausedTime = 0; /** - * Description. - * @property {boolean} isPlaying + * @property {boolean} isPlaying - true if the sound is currently playing, otherwise false. * @default */ this.isPlaying = false; /** - * Description. - * @property {string} currentMarker + * @property {string} currentMarker - The string ID of the currently playing marker, if any. * @default */ this.currentMarker = ''; /** - * Description. - * @property {boolean} pendingPlayback - * @default + * @property {boolean} pendingPlayback - true if the sound file is pending playback + * @readonly */ this.pendingPlayback = false; /** - * Description. - * @property {boolean} override + * @property {boolean} override - if true when you play this sound it will always start from the beginning. * @default */ this.override = false; /** - * Description. - * @property {boolean} usingWebAudio + * @property {boolean} usingWebAudio - true if this sound is being played with Web Audio. + * @readonly */ this.usingWebAudio = this.game.sound.usingWebAudio; /** - * Description. - * @property {Description} usingAudioTag + * @property {boolean} usingAudioTag - true if the sound is being played via the Audio tag. */ this.usingAudioTag = this.game.sound.usingAudioTag; @@ -217,63 +188,55 @@ Phaser.Sound = function (game, key, volume, loop) { } /** - * Description. - * @property {Phaser.Signal} onDecoded + * @property {Phaser.Signal} onDecoded - The onDecoded event is dispatched when the sound has finished decoding (typically for mp3 files) */ - this.onDecoded = new Phaser.Signal; + this.onDecoded = new Phaser.Signal(); /** - * Description. - * @property {Phaser.Signal} onPlay + * @property {Phaser.Signal} onPlay - The onPlay event is dispatched each time this sound is played. */ - this.onPlay = new Phaser.Signal; + this.onPlay = new Phaser.Signal(); /** - * Description. - * @property {Phaser.Signal} onPause + * @property {Phaser.Signal} onPause - The onPause event is dispatched when this sound is paused. */ - this.onPause = new Phaser.Signal; + this.onPause = new Phaser.Signal(); /** - * Description. - * @property {Phaser.Signal} onResume + * @property {Phaser.Signal} onResume - The onResume event is dispatched when this sound is resumed from a paused state. */ - this.onResume = new Phaser.Signal; + this.onResume = new Phaser.Signal(); /** - * Description. - * @property {Phaser.Signal} onLoop + * @property {Phaser.Signal} onLoop - The onLoop event is dispatched when this sound loops during playback. */ - this.onLoop = new Phaser.Signal; + this.onLoop = new Phaser.Signal(); /** - * Description. - * @property {Phaser.Signal} onStop + * @property {Phaser.Signal} onStop - The onStop event is dispatched when this sound stops playback. */ - this.onStop = new Phaser.Signal; + this.onStop = new Phaser.Signal(); /** - * Description. - * @property {Phaser.Signal} onMute + * @property {Phaser.Signal} onMute - The onMouse event is dispatched when this sound is muted. */ - this.onMute = new Phaser.Signal; + this.onMute = new Phaser.Signal(); /** - * Description. - * @property {Phaser.Signal} onMarkerComplete + * @property {Phaser.Signal} onMarkerComplete - The onMarkerComplete event is dispatched when a marker within this sound completes playback. */ - this.onMarkerComplete = new Phaser.Signal; + this.onMarkerComplete = new Phaser.Signal(); }; Phaser.Sound.prototype = { - /** + /** * Called automatically when this sound is unlocked. - * @method Phaser.Sound#soundHasUnlocked - * @param {string} key - Description. + * @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) @@ -281,22 +244,22 @@ Phaser.Sound.prototype = { this._sound = this.game.cache.getSoundData(this.key); this.totalDuration = this._sound.duration; // console.log('sound has unlocked' + this._sound); - } + } - }, + }, - /** - * Description. - * @method Phaser.Sound#addMarker - * @param {string} name - Description. - * @param {Description} start - Description. - * @param {Description} stop - Description. - * @param {Description} volume - Description. - * @param {Description} loop - Description. + /** + * Description. + * @method Phaser.Sound#addMarker + * @param {string} name - Description. + * @param {Description} start - Description. + * @param {Description} stop - Description. + * @param {Description} volume - Description. + * @param {Description} loop - Description. addMarker: function (name, start, stop, volume, loop) { - volume = volume || 1; - if (typeof loop == 'undefined') { loop = false; } + volume = volume || 1; + if (typeof loop == 'undefined') { loop = false; } this.markers[name] = { name: name, @@ -338,22 +301,22 @@ Phaser.Sound.prototype = { }, - /** - * 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 Phaser.SoundManager. - * @method Phaser.Sound#update + /** + * Called automatically by Phaser.SoundManager. + * @method Phaser.Sound#update * @protected - */ + */ update: function () { if (this.pendingPlayback && this.game.cache.isSoundReady(this.key)) @@ -377,7 +340,7 @@ Phaser.Sound.prototype = { // won't work with markers, needs to reset the position this.onLoop.dispatch(this); - if (this.currentMarker == '') + if (this.currentMarker === '') { //console.log('loop2'); this.currentTime = 0; @@ -411,7 +374,7 @@ Phaser.Sound.prototype = { } }, - /** + /** * 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. @@ -423,12 +386,12 @@ Phaser.Sound.prototype = { */ play: function (marker, position, volume, loop, forceRestart) { - marker = marker || ''; - position = position || 0; + marker = marker || ''; + position = position || 0; if (typeof volume === 'undefined') { volume = this._volume; } - if (typeof loop === 'undefined') { loop = false; } - if (typeof forceRestart === 'undefined') { forceRestart = true; } + if (typeof loop === 'undefined') { loop = false; } + if (typeof forceRestart === 'undefined') { forceRestart = true; } // console.log(this.name + ' play ' + marker + ' position ' + position + ' volume ' + volume + ' loop ' + loop, 'force', forceRestart); @@ -524,7 +487,7 @@ Phaser.Sound.prototype = { this.durationMS = this.totalDuration * 1000; } - if (this.loop && marker == '') + if (this.loop && marker === '') { this._sound.loop = true; } @@ -535,9 +498,9 @@ Phaser.Sound.prototype = { this._sound.noteGrainOn(0, this.position, this.duration); // this._sound.noteGrainOn(0, this.position, this.duration / 1000); //this._sound.noteOn(0); // the zero is vitally important, crashes iOS6 without it - } - else - { + } + else + { // this._sound.start(0, this.position, this.duration / 1000); this._sound.start(0, this.position, this.duration); } @@ -547,9 +510,9 @@ Phaser.Sound.prototype = { this.currentTime = 0; this.stopTime = this.startTime + this.durationMS; this.onPlay.dispatch(this); - } - else - { + } + else + { this.pendingPlayback = true; if (this.game.cache.getSound(this.key) && this.game.cache.getSound(this.key).isDecoding === false) @@ -619,10 +582,10 @@ Phaser.Sound.prototype = { */ restart: function (marker, position, volume, loop) { - marker = marker || ''; - position = position || 0; - volume = volume || 1; - if (typeof loop == 'undefined') { loop = false; } + marker = marker || ''; + position = position || 0; + volume = volume || 1; + if (typeof loop == 'undefined') { loop = false; } this.play(marker, position, volume, loop, true); @@ -666,9 +629,9 @@ Phaser.Sound.prototype = { { this._sound.noteGrainOn(0, p, this.duration); //this._sound.noteOn(0); // the zero is vitally important, crashes iOS6 without it - } - else - { + } + else + { this._sound.start(0, p, this.duration); } } @@ -685,7 +648,7 @@ Phaser.Sound.prototype = { }, - /** + /** * Stop playing this sound. * @method Phaser.Sound#stop */ @@ -752,14 +715,14 @@ Object.defineProperty(Phaser.Sound.prototype, "isDecoded", { * @property {boolean} mute - Gets or sets the muted state of this sound. */ Object.defineProperty(Phaser.Sound.prototype, "mute", { - + get: function () { return this._muted; }, set: function (value) { - value = value || null; + value = value || null; if (value) { diff --git a/src/sound/SoundManager.js b/src/sound/SoundManager.js index 2a2457142..a01b95468 100644 --- a/src/sound/SoundManager.js +++ b/src/sound/SoundManager.js @@ -16,28 +16,28 @@ */ Phaser.SoundManager = function (game) { - /** - * @property {Phaser.Game} game - Local reference to game. - */ - this.game = game; - - /** - * @property {Phaser.Signal} onSoundDecode - Description. - */ - this.onSoundDecode = new Phaser.Signal; - - /** - * @property {boolean} _muted - Description. - * @private - * @default - */ + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = game; + + /** + * @property {Phaser.Signal} onSoundDecode - The event dispatched when a sound decodes (typically only for mp3 files) + */ + this.onSoundDecode = new Phaser.Signal(); + + /** + * @property {boolean} _muted - Internal mute tracking var. + * @private + * @default + */ this._muted = false; - /** - * @property {Description} _unlockSource - Description. - * @private - * @default - */ + /** + * @property {Description} _unlockSource - Internal unlock tracking var. + * @private + * @default + */ this._unlockSource = null; /** @@ -55,41 +55,41 @@ Phaser.SoundManager = function (game) { this._sounds = []; /** - * @property {Description} context - Description. + * @property {AudioContext} context - The AudioContext being used for playback. * @default */ this.context = null; - /** - * @property {boolean} usingWebAudio - Description. - * @default - */ + /** + * @property {boolean} usingWebAudio - true if this sound is being played with Web Audio. + * @readonly + */ this.usingWebAudio = true; - /** - * @property {boolean} usingAudioTag - Description. - * @default - */ + /** + * @property {boolean} usingAudioTag - true if the sound is being played via the Audio tag. + * @readonly + */ this.usingAudioTag = false; - /** - * @property {boolean} noAudio - Description. - * @default - */ + /** + * @property {boolean} noAudio - Has audio been disabled via the PhaserGlobal object? Useful if you need to use a 3rd party audio library instead. + * @default + */ this.noAudio = false; - /** - * @property {boolean} touchLocked - Description. - * @default - */ + /** + * @property {boolean} touchLocked - true if the audio system is currently locked awaiting a touch event. + * @default + */ this.touchLocked = false; - /** - * @property {number} channels - Description. - * @default - */ + /** + * @property {number} channels - The number of audio channels to use in playback. + * @default + */ this.channels = 32; - + }; Phaser.SoundManager.prototype = { @@ -257,9 +257,9 @@ Phaser.SoundManager.prototype = { } } - }, + }, - /** + /** * Decode a sound by its assets key. * @method Phaser.SoundManager#decode * @param {string} key - Assets key of the sound to be decoded. @@ -329,7 +329,7 @@ Phaser.SoundManager.prototype = { add: function (key, volume, loop) { if (typeof volume === 'undefined') { volume = 1; } - if (typeof loop === 'undefined') { loop = false; } + if (typeof loop === 'undefined') { loop = false; } var sound = new Phaser.Sound(this.game, key, volume, loop); diff --git a/src/system/Canvas.js b/src/system/Canvas.js index bdcf2cb86..c763be8cf 100644 --- a/src/system/Canvas.js +++ b/src/system/Canvas.js @@ -40,10 +40,10 @@ Phaser.Canvas = { * @param {HTMLElement} element - The targeted element that we want to retrieve the offset. * @param {Phaser.Point} [point] - The point we want to take the x/y values of the offset. * @return {Phaser.Point} - A point objet with the offsetX and Y as its properties. - */ + */ getOffset: function (element, point) { - point = point || new Phaser.Point; + point = point || new Phaser.Point(); var box = element.getBoundingClientRect(); var clientTop = element.clientTop || document.body.clientTop || 0; @@ -64,7 +64,7 @@ Phaser.Canvas = { * @method Phaser.Canvas.getAspectRatio * @param {HTMLCanvasElement} canvas - The canvas to get the aspect ratio from. * @return {number} The ratio between canvas' width and height. - */ + */ getAspectRatio: function (canvas) { return canvas.width / canvas.height; }, diff --git a/src/system/Device.js b/src/system/Device.js index f6794f5d2..f189e86f9 100644 --- a/src/system/Device.js +++ b/src/system/Device.js @@ -387,7 +387,7 @@ Phaser.Device.prototype = { this.mobileSafari = true; } else if (/MSIE (\d+\.\d+);/.test(ua)) { this.ie = true; - this.ieVersion = parseInt(RegExp.$1); + this.ieVersion = parseInt(RegExp.$1, 10); } else if (/Midori/.test(ua)) { this.midori = true; } else if (/Opera/.test(ua)) { diff --git a/src/system/RequestAnimationFrame.js b/src/system/RequestAnimationFrame.js index b7eeb665f..2fd35a729 100644 --- a/src/system/RequestAnimationFrame.js +++ b/src/system/RequestAnimationFrame.js @@ -12,146 +12,146 @@ * @param {Phaser.Game} game - A reference to the currently running game. */ Phaser.RequestAnimationFrame = function(game) { - - /** - * @property {Phaser.Game} game - The currently running game. - */ - this.game = game; + + /** + * @property {Phaser.Game} game - The currently running game. + */ + this.game = game; - /** - * @property {boolean} isRunning - true if RequestAnimationFrame is running, otherwise false. - * @default - */ - this.isRunning = false; + /** + * @property {boolean} isRunning - true if RequestAnimationFrame is running, otherwise false. + * @default + */ + this.isRunning = false; - var vendors = [ - 'ms', - 'moz', - 'webkit', - 'o' - ]; + var vendors = [ + 'ms', + 'moz', + 'webkit', + 'o' + ]; - for (var x = 0; x < vendors.length && !window.requestAnimationFrame; x++) - { - window.requestAnimationFrame = window[vendors[x] + 'RequestAnimationFrame']; - window.cancelAnimationFrame = window[vendors[x] + 'CancelAnimationFrame']; - } + for (var x = 0; x < vendors.length && !window.requestAnimationFrame; x++) + { + window.requestAnimationFrame = window[vendors[x] + 'RequestAnimationFrame']; + window.cancelAnimationFrame = window[vendors[x] + 'CancelAnimationFrame']; + } - /** - * @property {boolean} _isSetTimeOut - true if the browser is using setTimeout instead of raf. - * @private - */ - this._isSetTimeOut = false; + /** + * @property {boolean} _isSetTimeOut - true if the browser is using setTimeout instead of raf. + * @private + */ + this._isSetTimeOut = false; - /** - * @property {function} _onLoop - The function called by the update. - * @private - */ - this._onLoop = null; + /** + * @property {function} _onLoop - The function called by the update. + * @private + */ + this._onLoop = null; - /** - * @property {number} _timeOutID - The callback ID used when calling cancel. - * @private - */ - this._timeOutID = null; + /** + * @property {number} _timeOutID - The callback ID used when calling cancel. + * @private + */ + this._timeOutID = null; }; Phaser.RequestAnimationFrame.prototype = { - /** - * Starts the requestAnimatioFrame running or setTimeout if unavailable in browser - * @method Phaser.RequestAnimationFrame#start - */ - start: function () { + /** + * Starts the requestAnimatioFrame running or setTimeout if unavailable in browser + * @method Phaser.RequestAnimationFrame#start + */ + start: function () { - this.isRunning = true; + this.isRunning = true; - var _this = this; + var _this = this; - if (!window.requestAnimationFrame) - { - this._isSetTimeOut = true; + if (!window.requestAnimationFrame) + { + this._isSetTimeOut = true; this._onLoop = function () { return _this.updateSetTimeout(); }; - this._timeOutID = window.setTimeout(this._onLoop, 0); - } - else - { - this._isSetTimeOut = false; + this._timeOutID = window.setTimeout(this._onLoop, 0); + } + else + { + this._isSetTimeOut = false; this._onLoop = function (time) { return _this.updateRAF(time); }; - this._timeOutID = window.requestAnimationFrame(this._onLoop); - } + this._timeOutID = window.requestAnimationFrame(this._onLoop); + } - }, + }, - /** - * The update method for the requestAnimationFrame - * @method Phaser.RequestAnimationFrame#updateRAF - * @param {number} time - A timestamp, either from RAF or setTimeOut - */ - updateRAF: function (time) { + /** + * The update method for the requestAnimationFrame + * @method Phaser.RequestAnimationFrame#updateRAF + * @param {number} time - A timestamp, either from RAF or setTimeOut + */ + updateRAF: function (time) { - this.game.update(time); + this.game.update(time); - this._timeOutID = window.requestAnimationFrame(this._onLoop); + this._timeOutID = window.requestAnimationFrame(this._onLoop); - }, + }, - /** - * The update method for the setTimeout. - * @method Phaser.RequestAnimationFrame#updateSetTimeout - */ - updateSetTimeout: function () { + /** + * The update method for the setTimeout. + * @method Phaser.RequestAnimationFrame#updateSetTimeout + */ + updateSetTimeout: function () { - this.game.update(Date.now()); + this.game.update(Date.now()); - this._timeOutID = window.setTimeout(this._onLoop, this.game.time.timeToCall); + this._timeOutID = window.setTimeout(this._onLoop, this.game.time.timeToCall); - }, + }, - /** - * Stops the requestAnimationFrame from running. - * @method Phaser.RequestAnimationFrame#stop - */ - stop: function () { + /** + * Stops the requestAnimationFrame from running. + * @method Phaser.RequestAnimationFrame#stop + */ + stop: function () { - if (this._isSetTimeOut) - { - clearTimeout(this._timeOutID); - } - else - { - window.cancelAnimationFrame(this._timeOutID); - } + if (this._isSetTimeOut) + { + clearTimeout(this._timeOutID); + } + else + { + window.cancelAnimationFrame(this._timeOutID); + } - this.isRunning = false; + this.isRunning = false; - }, + }, - /** - * Is the browser using setTimeout? - * @method Phaser.RequestAnimationFrame#isSetTimeOut - * @return {boolean} - */ - isSetTimeOut: function () { - return this._isSetTimeOut; - }, + /** + * Is the browser using setTimeout? + * @method Phaser.RequestAnimationFrame#isSetTimeOut + * @return {boolean} + */ + isSetTimeOut: function () { + return this._isSetTimeOut; + }, - /** - * Is the browser using requestAnimationFrame? - * @method Phaser.RequestAnimationFrame#isRAF - * @return {boolean} - */ - isRAF: function () { - return (this._isSetTimeOut === false); - } + /** + * Is the browser using requestAnimationFrame? + * @method Phaser.RequestAnimationFrame#isRAF + * @return {boolean} + */ + isRAF: function () { + return (this._isSetTimeOut === false); + } }; \ No newline at end of file diff --git a/src/system/StageScaleMode.js b/src/system/StageScaleMode.js index 8032c7c79..f3abb0098 100644 --- a/src/system/StageScaleMode.js +++ b/src/system/StageScaleMode.js @@ -73,7 +73,7 @@ Phaser.StageScaleMode = function (game, width, height) { * @property {boolean} forcePortrait - If the game should be forced to use Portrait mode, this is set to true by Game.Stage * @default */ - this.forcePortrait = false; + this.forcePortrait = false; /** * @property {boolean} incorrectOrientation - If the game should be forced to use a specific orientation and the device currently isn't in that orientation this is set to true. @@ -188,6 +188,11 @@ Phaser.StageScaleMode = function (game, width, height) { */ this.aspectRatio = 0; + /** + * @property {any} event- The native browser events from full screen API changes. + */ + this.event = null; + var _this = this; window.addEventListener('orientationchange', function (event) { @@ -209,7 +214,7 @@ Phaser.StageScaleMode = function (game, width, height) { document.addEventListener('fullscreenchange', function (event) { return _this.fullScreenChange(event); }, false); - + }; /** @@ -301,6 +306,8 @@ Phaser.StageScaleMode.prototype = { */ fullScreenChange: function (event) { + this.event = event; + if (this.isFullScreen) { this.game.stage.canvas.style['width'] = '100%'; @@ -429,6 +436,8 @@ Phaser.StageScaleMode.prototype = { */ checkOrientation: function (event) { + this.event = event; + this.orientation = window['orientation']; if (this.isLandscape) @@ -454,6 +463,8 @@ Phaser.StageScaleMode.prototype = { */ checkResize: function (event) { + this.event = event; + if (window.outerWidth > window.outerHeight) { this.orientation = 90; @@ -526,7 +537,7 @@ Phaser.StageScaleMode.prototype = { force = false; } - if (this.game.device.iPad === false && this.game.device.webApp === false && this.game.device.desktop === false) + if (this.game.device.iPad === false && this.game.device.webApp === false && this.game.device.desktop === false) { if (this.game.device.android && this.game.device.chrome === false) { diff --git a/src/tilemap/Tile.js b/src/tilemap/Tile.js index dced62a37..3fb2ae84e 100644 --- a/src/tilemap/Tile.js +++ b/src/tilemap/Tile.js @@ -5,7 +5,6 @@ * @module Phaser.Tile */ - /** * Create a new Tile. * @@ -205,7 +204,7 @@ Object.defineProperty(Phaser.Tile.prototype, "right", { * However it does affect the width property. * @method right * @return {number} - */ + */ get: function () { return this.x + this.width; } diff --git a/src/tilemap/Tilemap.js b/src/tilemap/Tilemap.js index e58d1f653..6999ef3af 100644 --- a/src/tilemap/Tilemap.js +++ b/src/tilemap/Tilemap.js @@ -1,25 +1,25 @@ Phaser.Tilemap = function (game, key) { - /** - * @property {Phaser.Game} game - Description. - */ + /** + * @property {Phaser.Game} game - Description. + */ this.game = game; /** * @property {array} layers - Description. */ - this.layers; + this.layers = null; if (typeof key === 'string') { - this.key = key; + this.key = key; - this.layers = game.cache.getTilemapData(key).layers; + this.layers = game.cache.getTilemapData(key).layers; this.calculateIndexes(); } else { - this.layers = []; + this.layers = []; } this.currentLayer = 0; @@ -55,15 +55,15 @@ Phaser.Tilemap.prototype = { this.currentLayer = this.layers.push({ - name: name, - width: width, - height: height, - alpha: 1, - visible: true, - tileMargin: 0, - tileSpacing: 0, - format: Phaser.Tilemap.CSV, - data: data, + name: name, + width: width, + height: height, + alpha: 1, + visible: true, + tileMargin: 0, + tileSpacing: 0, + format: Phaser.Tilemap.CSV, + data: data, indexes: [] }); @@ -96,10 +96,10 @@ Phaser.Tilemap.prototype = { setLayer: function (layer) { - if (this.layers[layer]) - { - this.currentLayer = layer; - } + if (this.layers[layer]) + { + this.currentLayer = layer; + } }, @@ -114,10 +114,10 @@ Phaser.Tilemap.prototype = { if (typeof layer === "undefined") { layer = this.currentLayer; } - if (x >= 0 && x < this.layers[layer].width && y >= 0 && y < this.layers[layer].height) - { - this.layers[layer].data[y][x] = index; - } + if (x >= 0 && x < this.layers[layer].width && y >= 0 && y < this.layers[layer].height) + { + this.layers[layer].data[y][x] = index; + } this.dirty = true; @@ -273,7 +273,7 @@ Phaser.Tilemap.prototype = { }, - swapHandler: function (value, index, array) { + swapHandler: function (value, index) { if (value.index === this._tempA) { @@ -462,14 +462,14 @@ Phaser.Tilemap.prototype = { if (this.layers[this.currentLayer].data[y][x] > 1) { - if (this.debugMap[this.layers[this.currentLayer].data[y][x]]) - { - args.push("background: " + this.debugMap[this.layers[this.currentLayer].data[y][x]]); - } - else - { - args.push("background: #ffffff"); - } + if (this.debugMap[this.layers[this.currentLayer].data[y][x]]) + { + args.push("background: " + this.debugMap[this.layers[this.currentLayer].data[y][x]]); + } + else + { + args.push("background: #ffffff"); + } } else { diff --git a/src/tilemap/TilemapLayer.js b/src/tilemap/TilemapLayer.js index 7cc4cbd77..61c85357c 100644 --- a/src/tilemap/TilemapLayer.js +++ b/src/tilemap/TilemapLayer.js @@ -1,33 +1,33 @@ // Maybe should extend Sprite? Phaser.TilemapLayer = function (game, x, y, renderWidth, renderHeight, tileset, tilemap, layer) { - /** - * @property {Phaser.Game} game - Description. - */ + /** + * @property {Phaser.Game} game - Description. + */ this.game = game; - /** - * @property {Description} canvas - Description. - * @default - */ + /** + * @property {Description} canvas - Description. + * @default + */ this.canvas = Phaser.Canvas.create(renderWidth, renderHeight); - /** - * @property {Description} context - Description. - * @default - */ + /** + * @property {Description} context - Description. + * @default + */ this.context = this.canvas.getContext('2d'); - /** - * @property {Description} baseTexture - Description. - * @default - */ + /** + * @property {Description} baseTexture - Description. + * @default + */ this.baseTexture = new PIXI.BaseTexture(this.canvas); - /** - * @property {Description} texture - Description. - * @default - */ + /** + * @property {Description} texture - Description. + * @default + */ this.texture = new PIXI.Texture(this.baseTexture); this.textureFrame = new Phaser.Frame(0, 0, 0, renderWidth, renderHeight, 'tilemaplayer', game.rnd.uuid()); @@ -145,18 +145,18 @@ Phaser.TilemapLayer = function (game, x, y, renderWidth, renderHeight, tileset, /** * @property {number} scrollFactorX - speed at which this layer scrolls - * horizontally, relative to the camera (e.g. scrollFactorX of 0.5 scrolls - * half as quickly as the 'normal' camera-locked layers do) - * @default 1 + * horizontally, relative to the camera (e.g. scrollFactorX of 0.5 scrolls + * half as quickly as the 'normal' camera-locked layers do) + * @default 1 */ - this.scrollFactorX = 1; + this.scrollFactorX = 1; /** * @property {number} scrollFactorY - speed at which this layer scrolls - * vertically, relative to the camera (e.g. scrollFactorY of 0.5 scrolls - * half as quickly as the 'normal' camera-locked layers do) - * @default 1 + * vertically, relative to the camera (e.g. scrollFactorY of 0.5 scrolls + * half as quickly as the 'normal' camera-locked layers do) + * @default 1 */ - this.scrollFactorY = 1; + this.scrollFactorY = 1; this.tilemap = null; this.layer = null; @@ -251,14 +251,14 @@ Phaser.TilemapLayer.prototype.updateMapData = function (tilemap, layer) { */ Phaser.TilemapLayer.prototype._fixX = function(x) { - if (this.scrollFactorX === 1) + if (this.scrollFactorX === 1) { return x; } - var left_edge = x - (this._x / this.scrollFactorX); + var leftEdge = x - (this._x / this.scrollFactorX); - return this._x + left_edge; + return this._x + leftEdge; } @@ -270,14 +270,14 @@ Phaser.TilemapLayer.prototype._fixX = function(x) { */ Phaser.TilemapLayer.prototype._unfixX = function(x) { - if (this.scrollFactorX === 1) + if (this.scrollFactorX === 1) { return x; } - var left_edge = x - this._x; + var leftEdge = x - this._x; - return (this._x / this.scrollFactorX) + left_edge; + return (this._x / this.scrollFactorX) + leftEdge; } @@ -289,14 +289,14 @@ Phaser.TilemapLayer.prototype._unfixX = function(x) { */ Phaser.TilemapLayer.prototype._fixY = function(y) { - if (this.scrollFactorY === 1) + if (this.scrollFactorY === 1) { return y; } - var top_edge = y - (this._y / this.scrollFactorY); + var topEdge = y - (this._y / this.scrollFactorY); - return this._y + top_edge; + return this._y + topEdge; } @@ -308,14 +308,14 @@ Phaser.TilemapLayer.prototype._fixY = function(y) { */ Phaser.TilemapLayer.prototype._unfixY = function(y) { - if (this.scrollFactorY === 1) + if (this.scrollFactorY === 1) { return y; } - var top_edge = y - this._y; + var topEdge = y - this._y; - return (this._y / this.scrollFactorY) + top_edge; + return (this._y / this.scrollFactorY) + topEdge; } @@ -329,7 +329,7 @@ Phaser.TilemapLayer.prototype.getTileX = function (x) { var tileWidth = this.tileWidth * this.scale.x; - return this.game.math.snapToFloor(this._fixX(x), tileWidth) / tileWidth; + return this.game.math.snapToFloor(this._fixX(x), tileWidth) / tileWidth; } @@ -343,7 +343,7 @@ Phaser.TilemapLayer.prototype.getTileY = function (y) { var tileHeight = this.tileHeight * this.scale.y; - return this.game.math.snapToFloor(this._fixY(y), tileHeight) / tileHeight; + return this.game.math.snapToFloor(this._fixY(y), tileHeight) / tileHeight; } @@ -384,9 +384,9 @@ Phaser.TilemapLayer.prototype.getTiles = function (x, y, width, height, collides y = 0; } - // adjust the x,y coordinates for scrollFactor - x = this._fixX( x ); - y = this._fixY( y ); + // adjust the x,y coordinates for scrollFactor + x = this._fixX( x ); + y = this._fixY( y ); if (width > this.widthInPixels) { @@ -435,9 +435,9 @@ Phaser.TilemapLayer.prototype.getTiles = function (x, y, width, height, collides if (collides === false || (collides && _tile.collideNone === false)) { - // convert tile coordinates back to camera space for return - var _wx = this._unfixX( wx*sx ) / tileWidth; - var _wy = this._unfixY( wy*sy ) / tileHeight; + // convert tile coordinates back to camera space for return + var _wx = this._unfixX( wx*sx ) / tileWidth; + var _wy = this._unfixY( wy*sy ) / tileHeight; this._results.push({ x: _wx * sx, right: (_wx * sx) + sx, y: _wy * sy, bottom: (_wy * sy) + sy, width: sx, height: sy, tx: _wx, ty: _wy, tile: _tile }); } } diff --git a/src/tilemap/TilemapParser.js b/src/tilemap/TilemapParser.js index 638ba60d5..e3ddd83b3 100644 --- a/src/tilemap/TilemapParser.js +++ b/src/tilemap/TilemapParser.js @@ -1,183 +1,183 @@ Phaser.TilemapParser = { - tileset: function (game, key, tileWidth, tileHeight, tileMax, tileMargin, tileSpacing) { + tileset: function (game, key, tileWidth, tileHeight, tileMax, tileMargin, tileSpacing) { - // How big is our image? - var img = game.cache.getTilesetImage(key); + // How big is our image? + var img = game.cache.getTilesetImage(key); - if (img == null) - { - return null; - } + if (img == null) + { + return null; + } - var width = img.width; - var height = img.height; + var width = img.width; + var height = img.height; - // If no tile width/height is given, try and figure it out (won't work if the tileset has margin/spacing) - if (tileWidth <= 0) - { - tileWidth = Math.floor(-width / Math.min(-1, tileWidth)); - } + // If no tile width/height is given, try and figure it out (won't work if the tileset has margin/spacing) + if (tileWidth <= 0) + { + tileWidth = Math.floor(-width / Math.min(-1, tileWidth)); + } - if (tileHeight <= 0) - { - tileHeight = Math.floor(-height / Math.min(-1, tileHeight)); - } + if (tileHeight <= 0) + { + tileHeight = Math.floor(-height / Math.min(-1, tileHeight)); + } - var row = Math.round(width / tileWidth); - var column = Math.round(height / tileHeight); - var total = row * column; - - if (tileMax !== -1) - { - total = tileMax; - } + var row = Math.round(width / tileWidth); + var column = Math.round(height / tileHeight); + var total = row * column; + + if (tileMax !== -1) + { + total = tileMax; + } - // Zero or smaller than tile sizes? - if (width === 0 || height === 0 || width < tileWidth || height < tileHeight || total === 0) - { - console.warn("Phaser.TilemapParser.tileSet: width/height zero or width/height < given tileWidth/tileHeight"); - return null; - } + // Zero or smaller than tile sizes? + if (width === 0 || height === 0 || width < tileWidth || height < tileHeight || total === 0) + { + console.warn("Phaser.TilemapParser.tileSet: width/height zero or width/height < given tileWidth/tileHeight"); + return null; + } - // Let's create some tiles - var x = tileMargin; - var y = tileMargin; + // Let's create some tiles + var x = tileMargin; + var y = tileMargin; - var tileset = new Phaser.Tileset(img, key, tileWidth, tileHeight, tileMargin, tileSpacing); + var tileset = new Phaser.Tileset(img, key, tileWidth, tileHeight, tileMargin, tileSpacing); - for (var i = 0; i < total; i++) - { - tileset.addTile(new Phaser.Tile(tileset, i, x, y, tileWidth, tileHeight)); + for (var i = 0; i < total; i++) + { + tileset.addTile(new Phaser.Tile(tileset, i, x, y, tileWidth, tileHeight)); - x += tileWidth + tileSpacing; + x += tileWidth + tileSpacing; - if (x === width) - { - x = tileMargin; - y += tileHeight + tileSpacing; - } - } + if (x === width) + { + x = tileMargin; + y += tileHeight + tileSpacing; + } + } - return tileset; + return tileset; - }, + }, - parse: function (game, data, format) { + parse: function (game, data, format) { - if (format === Phaser.Tilemap.CSV) - { - return this.parseCSV(data); - } - else if (format === Phaser.Tilemap.TILED_JSON) - { - return this.parseTiledJSON(data); - } + if (format === Phaser.Tilemap.CSV) + { + return this.parseCSV(data); + } + else if (format === Phaser.Tilemap.TILED_JSON) + { + return this.parseTiledJSON(data); + } - }, + }, - /** - * Parse csv map data and generate tiles. - * - * @method Phaser.Tilemap.prototype.parseCSV - * @param {string} data - CSV map data. - */ - parseCSV: function (data) { + /** + * Parse csv map data and generate tiles. + * + * @method Phaser.Tilemap.prototype.parseCSV + * @param {string} data - CSV map data. + */ + parseCSV: function (data) { - // Trim any rogue whitespace from the data - data = data.trim(); + // Trim any rogue whitespace from the data + data = data.trim(); - var output = []; - var rows = data.split("\n"); - var height = rows.length; - var width = 0; + var output = []; + var rows = data.split("\n"); + var height = rows.length; + var width = 0; - for (var i = 0; i < rows.length; i++) - { - output[i] = []; + for (var i = 0; i < rows.length; i++) + { + output[i] = []; - var column = rows[i].split(","); + var column = rows[i].split(","); - for (var c = 0; c < column.length; c++) - { - output[i][c] = parseInt(column[c]); - } + for (var c = 0; c < column.length; c++) + { + output[i][c] = parseInt(column[c], 10); + } if (width === 0) { - width = column.length; + width = column.length; } - } + } - return [{ name: 'csv', width: width, height: height, alpha: 1, visible: true, indexes: [], tileMargin: 0, tileSpacing: 0, data: output }]; + return [{ name: 'csv', width: width, height: height, alpha: 1, visible: true, indexes: [], tileMargin: 0, tileSpacing: 0, data: output }]; - }, + }, - /** - * Parse JSON map data and generate tiles. - * - * @method Phaser.Tilemap.prototype.parseTiledJSON - * @param {string} data - JSON map data. - * @param {string} key - Asset key for tileset image. - */ - parseTiledJSON: function (json) { + /** + * Parse JSON map data and generate tiles. + * + * @method Phaser.Tilemap.prototype.parseTiledJSON + * @param {string} data - JSON map data. + * @param {string} key - Asset key for tileset image. + */ + parseTiledJSON: function (json) { - var layers = []; + var layers = []; - for (var i = 0; i < json.layers.length; i++) - { - // Check it's a data layer - if (!json.layers[i].data) - { - continue; - } + for (var i = 0; i < json.layers.length; i++) + { + // Check it's a data layer + if (!json.layers[i].data) + { + continue; + } - // json.tilewidth - // json.tileheight + // json.tilewidth + // json.tileheight - var layer = { + var layer = { - name: json.layers[i].name, - width: json.layers[i].width, - height: json.layers[i].height, - alpha: json.layers[i].opacity, - visible: json.layers[i].visible, - indexes: [], + name: json.layers[i].name, + width: json.layers[i].width, + height: json.layers[i].height, + alpha: json.layers[i].opacity, + visible: json.layers[i].visible, + indexes: [], - tileMargin: json.tilesets[0].margin, - tileSpacing: json.tilesets[0].spacing, + tileMargin: json.tilesets[0].margin, + tileSpacing: json.tilesets[0].spacing - }; + }; - var output = []; - var c = 0; - var row; + var output = []; + var c = 0; + var row; - for (var t = 0; t < json.layers[i].data.length; t++) - { - if (c === 0) - { - row = []; - } + for (var t = 0; t < json.layers[i].data.length; t++) + { + if (c === 0) + { + row = []; + } - row.push(json.layers[i].data[t]); - c++; + row.push(json.layers[i].data[t]); + c++; - if (c == json.layers[i].width) - { - output.push(row); - c = 0; - } - } + if (c == json.layers[i].width) + { + output.push(row); + c = 0; + } + } - layer.data = output; - - layers.push(layer); + layer.data = output; + + layers.push(layer); - } + } - return layers; + return layers; - } + } } diff --git a/src/tilemap/Tileset.js b/src/tilemap/Tileset.js index 5d3b3fe17..36e332a0d 100644 --- a/src/tilemap/Tileset.js +++ b/src/tilemap/Tileset.js @@ -61,7 +61,7 @@ Phaser.Tileset.prototype = { checkTileIndex: function (index) { - return (this.tiles[index]); + return (this.tiles[index]); }, @@ -84,7 +84,7 @@ Phaser.Tileset.prototype = { this.tiles[index].setCollision(left, right, up, down); } - }, + } } diff --git a/src/time/Time.js b/src/time/Time.js index a587542a1..7f1ac48cc 100644 --- a/src/time/Time.js +++ b/src/time/Time.js @@ -20,124 +20,91 @@ Phaser.Time = function (game) { this.game = game; /** - * The time at which the Game instance started. - * @property {number} _started + * @property {number} _started - The time at which the Game instance started. * @private - * @default */ this._started = 0; /** - * The time (in ms) that the last second counter ticked over. - * @property {number} _timeLastSecond + * @property {number} _timeLastSecond - The time (in ms) that the last second counter ticked over. * @private - * @default */ this._timeLastSecond = 0; /** - * The time the game started being paused. - * @property {number} _pauseStarted + * @property {number} _pauseStarted - The time the game started being paused. * @private - * @default */ this._pauseStarted = 0; /** - * The elapsed time calculated for the physics motion updates. - * @property {number} physicsElapsed - * @default + * @property {number} physicsElapsed - The elapsed time calculated for the physics motion updates. */ this.physicsElapsed = 0; /** - * Game time counter. - * @property {number} time - * @default + * @property {number} time - Game time counter. */ this.time = 0; /** - * Records how long the game has been paused for. Is reset each time the game pauses. - * @property {number} pausedTime - * @default + * @property {number} pausedTime - Records how long the game has been paused for. Is reset each time the game pauses. */ this.pausedTime = 0; /** - * The time right now. - * @property {number} now - * @default + * @property {number} now - The time right now. */ this.now = 0; /** - * Elapsed time since the last frame. - * @property {number} elapsed - * @default + * @property {number} elapsed - Elapsed time since the last frame. */ this.elapsed = 0; /** - * Frames per second. - * @property {number} fps - * @default + * @property {number} fps - Frames per second. */ this.fps = 0; /** - * The lowest rate the fps has dropped to. - * @property {number} fpsMin - * @default + * @property {number} fpsMin - The lowest rate the fps has dropped to. */ this.fpsMin = 1000; /** - * The highest rate the fps has reached (usually no higher than 60fps). - * @property {number} fpsMax - * @default + * @property {number} fpsMax - The highest rate the fps has reached (usually no higher than 60fps). */ this.fpsMax = 0; /** - * The minimum amount of time the game has taken between two frames. - * @property {number} msMin + * @property {number} msMin - The minimum amount of time the game has taken between two frames. * @default */ this.msMin = 1000; /** - * The maximum amount of time the game has taken between two frames. - * @property {number} msMax - * @default + * @property {number} msMax - The maximum amount of time the game has taken between two frames. */ this.msMax = 0; /** - * The number of frames record in the last second. - * @property {number} frames - * @default + * @property {number} frames - The number of frames record in the last second. */ this.frames = 0; /** - * Records how long the game was paused for in miliseconds. - * @property {number} pauseDuration - * @default + * @property {number} pauseDuration - Records how long the game was paused for in miliseconds. */ this.pauseDuration = 0; /** - * The value that setTimeout needs to work out when to next update - * @property {number} timeToCall - * @default + * @property {number} timeToCall - The value that setTimeout needs to work out when to next update */ this.timeToCall = 0; /** - * Internal value used by timeToCall as part of the setTimeout loop - * @property {number} lastTime - * @default + * @property {number} lastTime - Internal value used by timeToCall as part of the setTimeout loop */ this.lastTime = 0; @@ -146,9 +113,8 @@ Phaser.Time = function (game) { this.game.onResume.add(this.gameResumed, this); /** - * Internal value used to recover from the game pause state. - * @property {boolean} _justResumed - * @default + * @property {boolean} _justResumed - Internal value used to recover from the game pause state. + * @private */ this._justResumed = false; diff --git a/src/time/Timer.js b/src/time/Timer.js index 87cf67e05..8677ea467 100644 --- a/src/time/Timer.js +++ b/src/time/Timer.js @@ -14,104 +14,104 @@ */ Phaser.Timer = function (game) { - /** - * @property {Phaser.Game} game - Local reference to game. - */ - this.game = game; + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = game; - /** - * The time at which this Timer instance started. - * @property {number} _started - * @private - * @default - */ - this._started = 0; + /** + * The time at which this Timer instance started. + * @property {number} _started + * @private + * @default + */ + this._started = 0; - /** - * The time (in ms) that the last second counter ticked over. - * @property {number} _timeLastSecond - * @private - * @default - */ - this._timeLastSecond = 0; + /** + * The time (in ms) that the last second counter ticked over. + * @property {number} _timeLastSecond + * @private + * @default + */ + this._timeLastSecond = 0; - this.running = false; + this.running = false; - this.events = []; + this.events = []; - this.onEvent = new Phaser.Signal(); + this.onEvent = new Phaser.Signal(); - // Need to add custom FPS rate, for now we'll just use seconds + // Need to add custom FPS rate, for now we'll just use seconds } Phaser.Timer.prototype = { - // delay could be from now, when the timer is created, or relative to an already running timer + // delay could be from now, when the timer is created, or relative to an already running timer - // add: function (delay, callback, callbackContext) { - add: function (delay) { + // add: function (delay, callback, callbackContext) { + add: function (delay) { - this.events.push({ - delay: delay, - dispatched: false, - args: Array.prototype.splice.call(arguments, 1) - }); + this.events.push({ + delay: delay, + dispatched: false, + args: Array.prototype.splice.call(arguments, 1) + }); - // this.events.push({ - // delay: delay, - // dispatched: false, - // callback: callback, - // callbackContext: callbackContext, - // args: Array.prototype.splice.call(arguments, 3) - // }); + // this.events.push({ + // delay: delay, + // dispatched: false, + // callback: callback, + // callbackContext: callbackContext, + // args: Array.prototype.splice.call(arguments, 3) + // }); - }, + }, - start: function() { + start: function() { - this._started = this.game.time.now; - this.running = true; + this._started = this.game.time.now; + this.running = true; - // sort the events based on delay here, also don't run unless events is populated - // add ability to auto-stop once all events are done - // add support for maximum duration - // add support for delay before starting - // add signals? + // sort the events based on delay here, also don't run unless events is populated + // add ability to auto-stop once all events are done + // add support for maximum duration + // add support for delay before starting + // add signals? - }, + }, - stop: function() { + stop: function() { - this.running = false; - this.events.length = 0; + this.running = false; + this.events.length = 0; - }, + }, - update: function() { + update: function() { - // TODO: Game Paused support + // TODO: Game Paused support - if (this.running) - { - var seconds = this.seconds(); + if (this.running) + { + var seconds = this.seconds(); - for (var i = 0, len = this.events.length; i < len; i++) - { - if (this.events[i].dispatched === false && seconds >= this.events[i].delay) - { - this.events[i].dispatched = true; - // this.events[i].callback.apply(this.events[i].callbackContext, this.events[i].args); - this.onEvent.dispatch.apply(this, this.events[i].args); - // ought to slice it now - } - } - } + for (var i = 0, len = this.events.length; i < len; i++) + { + if (this.events[i].dispatched === false && seconds >= this.events[i].delay) + { + this.events[i].dispatched = true; + // this.events[i].callback.apply(this.events[i].callbackContext, this.events[i].args); + this.onEvent.dispatch.apply(this, this.events[i].args); + // ought to slice it now + } + } + } - }, + }, - seconds: function() { - return (this.game.time.now - this._started) * 0.001; - } + seconds: function() { + return (this.game.time.now - this._started) * 0.001; + } } \ No newline at end of file diff --git a/src/tween/Easing.js b/src/tween/Easing.js index bb52f0876..96dbcd798 100644 --- a/src/tween/Easing.js +++ b/src/tween/Easing.js @@ -1,3 +1,5 @@ +/* jshint curly: false */ + /** * @author Richard Davey * @copyright 2013 Photon Storm Ltd. @@ -16,546 +18,546 @@ Phaser.Easing = { * * @class Phaser.Easing.Linear */ - Linear: { + Linear: { - /** - * Ease-in. - * - * @method Phaser.Easing.Linear#In - * @param {number} k - The value to be tweened. - * @returns {number} k^2. - */ - None: function ( k ) { + /** + * Ease-in. + * + * @method Phaser.Easing.Linear#In + * @param {number} k - The value to be tweened. + * @returns {number} k^2. + */ + None: function ( k ) { - return k; + return k; - } + } - }, + }, /** * Quadratic easing. * * @class Phaser.Easing.Quadratic */ - Quadratic: { + Quadratic: { - /** - * Ease-in. - * - * @method Phaser.Easing.Quadratic#In - * @param {number} k - The value to be tweened. - * @returns {number} k^2. - */ - In: function ( k ) { + /** + * 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; + return k * k; - }, + }, - /** - * Ease-out. - * - * @method Phaser.Easing.Quadratic#Out - * @param {number} k - The value to be tweened. - * @returns {number} k* (2-k). - */ - Out: function ( k ) { + /** + * 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 ); + return k * ( 2 - k ); - }, + }, - /** - * Ease-in/out. - * - * @method Phaser.Easing.Quadratic#InOut - * @param {number} k - The value to be tweened. - * @returns {number} The tweened value. - */ - InOut: function ( k ) { + /** + * 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 ); + if ( ( k *= 2 ) < 1 ) return 0.5 * k * k; + return - 0.5 * ( --k * ( k - 2 ) - 1 ); - } + } - }, + }, /** * Cubic easing. * * @class Phaser.Easing.Cubic */ - Cubic: { + Cubic: { - /** - * Cubic ease-in. - * - * @method Phaser.Easing.Cubic#In - * @param {number} k - The value to be tweened. - * @returns {number} The tweened value. - */ - In: function ( k ) { + /** + * 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; + return k * k * k; - }, + }, - /** - * Cubic ease-out. - * - * @method Phaser.Easing.Cubic#Out - * @param {number} k - The value to be tweened. - * @returns {number} The tweened value. - */ - Out: function ( k ) { + /** + * 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; + return --k * k * k + 1; - }, + }, - /** - * Cubic ease-in/out. - * - * @method Phaser.Easing.Cubic#InOut - * @param {number} k - The value to be tweened. - * @returns {number} The tweened value. - */ - InOut: function ( k ) { + /** + * 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 ); + if ( ( k *= 2 ) < 1 ) return 0.5 * k * k * k; + return 0.5 * ( ( k -= 2 ) * k * k + 2 ); - } + } - }, + }, /** * Quartic easing. * * @class Phaser.Easing.Quartic */ - Quartic: { + Quartic: { - /** - * Quartic ease-in. - * - * @method Phaser.Easing.Quartic#In - * @param {number} k - The value to be tweened. - * @returns {number} The tweened value. - */ - In: function ( k ) { + /** + * 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; + return k * k * k * k; - }, + }, - /** - * Quartic ease-out. - * - * @method Phaser.Easing.Quartic#Out - * @param {number} k - The value to be tweened. - * @returns {number} The tweened value. - */ - Out: function ( k ) { + /** + * 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 ); + return 1 - ( --k * k * k * k ); - }, + }, - /** - * Quartic ease-in/out. - * - * @method Phaser.Easing.Quartic#InOut - * @param {number} k - The value to be tweened. - * @returns {number} The tweened value. - */ - InOut: function ( k ) { + /** + * 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 ); + if ( ( k *= 2 ) < 1) return 0.5 * k * k * k * k; + return - 0.5 * ( ( k -= 2 ) * k * k * k - 2 ); - } + } - }, + }, /** * Quintic easing. * * @class Phaser.Easing.Quintic */ - Quintic: { + Quintic: { - /** - * Quintic ease-in. - * - * @method Phaser.Easing.Quintic#In - * @param {number} k - The value to be tweened. - * @returns {number} The tweened value. - */ - In: function ( k ) { + /** + * 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; + return k * k * k * k * k; - }, + }, - /** - * Quintic ease-out. - * - * @method Phaser.Easing.Quintic#Out - * @param {number} k - The value to be tweened. - * @returns {number} The tweened value. - */ - Out: function ( k ) { + /** + * 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; + return --k * k * k * k * k + 1; - }, + }, - /** - * Quintic ease-in/out. - * - * @method Phaser.Easing.Quintic#InOut - * @param {number} k - The value to be tweened. - * @returns {number} The tweened value. - */ - InOut: function ( k ) { + /** + * 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 ); + if ( ( k *= 2 ) < 1 ) return 0.5 * k * k * k * k * k; + return 0.5 * ( ( k -= 2 ) * k * k * k * k + 2 ); - } + } - }, + }, /** * Sinusoidal easing. * * @class Phaser.Easing.Sinusoidal */ - Sinusoidal: { + Sinusoidal: { - /** - * Sinusoidal ease-in. - * - * @method Phaser.Easing.Sinusoidal#In - * @param {number} k - The value to be tweened. - * @returns {number} The tweened value. - */ - In: function ( k ) { + /** + * Sinusoidal ease-in. + * + * @method Phaser.Easing.Sinusoidal#In + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + In: function ( k ) { - return 1 - Math.cos( k * Math.PI / 2 ); + return 1 - Math.cos( k * Math.PI / 2 ); - }, + }, - /** - * Sinusoidal ease-out. - * - * @method Phaser.Easing.Sinusoidal#Out - * @param {number} k - The value to be tweened. - * @returns {number} The tweened value. - */ - Out: function ( k ) { + /** + * Sinusoidal ease-out. + * + * @method Phaser.Easing.Sinusoidal#Out + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + Out: function ( k ) { - return Math.sin( k * Math.PI / 2 ); + return Math.sin( k * Math.PI / 2 ); - }, + }, - /** - * Sinusoidal ease-in/out. - * - * @method Phaser.Easing.Sinusoidal#InOut - * @param {number} k - The value to be tweened. - * @returns {number} The tweened value. - */ - InOut: function ( k ) { + /** + * Sinusoidal ease-in/out. + * + * @method Phaser.Easing.Sinusoidal#InOut + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + InOut: function ( k ) { - return 0.5 * ( 1 - Math.cos( Math.PI * k ) ); + return 0.5 * ( 1 - Math.cos( Math.PI * k ) ); - } + } - }, + }, /** * Exponential easing. * * @class Phaser.Easing.Exponential */ - Exponential: { + Exponential: { - /** - * Exponential ease-in. - * - * @method Phaser.Easing.Exponential#In - * @param {number} k - The value to be tweened. - * @returns {number} The tweened value. - */ - In: function ( k ) { + /** + * 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 ); + return k === 0 ? 0 : Math.pow( 1024, k - 1 ); - }, + }, - /** - * Exponential ease-out. - * - * @method Phaser.Easing.Exponential#Out - * @param {number} k - The value to be tweened. - * @returns {number} The tweened value. - */ - Out: function ( k ) { + /** + * 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 ); + return k === 1 ? 1 : 1 - Math.pow( 2, - 10 * k ); - }, + }, - /** - * Exponential ease-in/out. - * - * @method Phaser.Easing.Exponential#InOut - * @param {number} k - The value to be tweened. - * @returns {number} The tweened value. - */ - InOut: function ( k ) { + /** + * 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 ); + if ( k === 0 ) return 0; + if ( k === 1 ) return 1; + if ( ( k *= 2 ) < 1 ) return 0.5 * Math.pow( 1024, k - 1 ); + return 0.5 * ( - Math.pow( 2, - 10 * ( k - 1 ) ) + 2 ); - } + } - }, + }, /** * Circular easing. * * @class Phaser.Easing.Circular */ - Circular: { + Circular: { - /** - * Circular ease-in. - * - * @method Phaser.Easing.Circular#In - * @param {number} k - The value to be tweened. - * @returns {number} The tweened value. - */ - In: function ( k ) { - - return 1 - Math.sqrt( 1 - k * k ); - - }, - - /** - * Circular ease-out. - * - * @method Phaser.Easing.Circular#Out - * @param {number} k - The value to be tweened. - * @returns {number} The tweened value. - */ - Out: function ( k ) { - - return Math.sqrt( 1 - ( --k * k ) ); - - }, - - /** - * Circular ease-in/out. + /** + * Circular ease-in. * - * @method Phaser.Easing.Circular#InOut - * @param {number} k - The value to be tweened. - * @returns {number} The tweened value. + * @method Phaser.Easing.Circular#In + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. */ - InOut: function ( k ) { + In: 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); + return 1 - Math.sqrt( 1 - k * k ); - } + }, - }, + /** + * Circular ease-out. + * + * @method Phaser.Easing.Circular#Out + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + Out: function ( k ) { + + return Math.sqrt( 1 - ( --k * k ) ); + + }, + + /** + * Circular ease-in/out. + * + * @method Phaser.Easing.Circular#InOut + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + InOut: function ( k ) { + + if ( ( k *= 2 ) < 1) return - 0.5 * ( Math.sqrt( 1 - k * k) - 1); + return 0.5 * ( Math.sqrt( 1 - ( k -= 2) * k) + 1); + + } + + }, /** * Elastic easing. * * @class Phaser.Easing.Elastic */ - Elastic: { + Elastic: { - /** - * Elastic ease-in. - * - * @method Phaser.Easing.Elastic#In - * @param {number} k - The value to be tweened. - * @returns {number} The tweened value. - */ - In: function ( k ) { + /** + * Elastic ease-in. + * + * @method Phaser.Easing.Elastic#In + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + In: function ( k ) { - var s, a = 0.1, p = 0.4; - if ( k === 0 ) return 0; - if ( k === 1 ) return 1; - if ( !a || a < 1 ) { a = 1; s = p / 4; } - else s = p * Math.asin( 1 / a ) / ( 2 * Math.PI ); - return - ( a * Math.pow( 2, 10 * ( k -= 1 ) ) * Math.sin( ( k - s ) * ( 2 * Math.PI ) / p ) ); + var s, a = 0.1, p = 0.4; + if ( k === 0 ) return 0; + if ( k === 1 ) return 1; + if ( !a || a < 1 ) { a = 1; s = p / 4; } + else s = p * Math.asin( 1 / a ) / ( 2 * Math.PI ); + return - ( a * Math.pow( 2, 10 * ( k -= 1 ) ) * Math.sin( ( k - s ) * ( 2 * Math.PI ) / p ) ); - }, + }, - /** - * Elastic ease-out. - * - * @method Phaser.Easing.Elastic#Out - * @param {number} k - The value to be tweened. - * @returns {number} The tweened value. - */ - Out: function ( k ) { + /** + * Elastic ease-out. + * + * @method Phaser.Easing.Elastic#Out + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + Out: function ( k ) { - var s, a = 0.1, p = 0.4; - if ( k === 0 ) return 0; - if ( k === 1 ) return 1; - if ( !a || a < 1 ) { a = 1; s = p / 4; } - else s = p * Math.asin( 1 / a ) / ( 2 * Math.PI ); - return ( a * Math.pow( 2, - 10 * k) * Math.sin( ( k - s ) * ( 2 * Math.PI ) / p ) + 1 ); + var s, a = 0.1, p = 0.4; + if ( k === 0 ) return 0; + if ( k === 1 ) return 1; + if ( !a || a < 1 ) { a = 1; s = p / 4; } + else s = p * Math.asin( 1 / a ) / ( 2 * Math.PI ); + return ( a * Math.pow( 2, - 10 * k) * Math.sin( ( k - s ) * ( 2 * Math.PI ) / p ) + 1 ); - }, + }, - /** - * Elastic ease-in/out. - * - * @method Phaser.Easing.Elastic#InOut - * @param {number} k - The value to be tweened. - * @returns {number} The tweened value. - */ - InOut: function ( k ) { + /** + * Elastic ease-in/out. + * + * @method Phaser.Easing.Elastic#InOut + * @param {number} k - The value to be tweened. + * @returns {number} The tweened value. + */ + InOut: function ( k ) { - var s, a = 0.1, p = 0.4; - if ( k === 0 ) return 0; - if ( k === 1 ) return 1; - if ( !a || a < 1 ) { a = 1; s = p / 4; } - else s = p * Math.asin( 1 / a ) / ( 2 * Math.PI ); - if ( ( k *= 2 ) < 1 ) return - 0.5 * ( a * Math.pow( 2, 10 * ( k -= 1 ) ) * Math.sin( ( k - s ) * ( 2 * Math.PI ) / p ) ); - return a * Math.pow( 2, -10 * ( k -= 1 ) ) * Math.sin( ( k - s ) * ( 2 * Math.PI ) / p ) * 0.5 + 1; + var s, a = 0.1, p = 0.4; + if ( k === 0 ) return 0; + if ( k === 1 ) return 1; + if ( !a || a < 1 ) { a = 1; s = p / 4; } + else s = p * Math.asin( 1 / a ) / ( 2 * Math.PI ); + if ( ( k *= 2 ) < 1 ) return - 0.5 * ( a * Math.pow( 2, 10 * ( k -= 1 ) ) * Math.sin( ( k - s ) * ( 2 * Math.PI ) / p ) ); + return a * Math.pow( 2, -10 * ( k -= 1 ) ) * Math.sin( ( k - s ) * ( 2 * Math.PI ) / p ) * 0.5 + 1; - } + } - }, + }, /** * Back easing. * * @class Phaser.Easing.Back */ - Back: { + Back: { - /** - * Back ease-in. - * - * @method Phaser.Easing.Back#In - * @param {number} k - The value to be tweened. - * @returns {number} The tweened value. - */ - In: function ( k ) { + /** + * 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 ); + var s = 1.70158; + return k * k * ( ( s + 1 ) * k - s ); - }, + }, - /** - * Back ease-out. - * - * @method Phaser.Easing.Back#Out - * @param {number} k - The value to be tweened. - * @returns {number} The tweened value. - */ - Out: function ( k ) { + /** + * 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; + var s = 1.70158; + return --k * k * ( ( s + 1 ) * k + s ) + 1; - }, + }, - /** - * Back ease-in/out. - * - * @method Phaser.Easing.Back#InOut - * @param {number} k - The value to be tweened. - * @returns {number} The tweened value. - */ - InOut: function ( k ) { + /** + * 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 ); + var s = 1.70158 * 1.525; + if ( ( k *= 2 ) < 1 ) return 0.5 * ( k * k * ( ( s + 1 ) * k - s ) ); + return 0.5 * ( ( k -= 2 ) * k * ( ( s + 1 ) * k + s ) + 2 ); - } + } - }, + }, /** * Bounce easing. * * @class Phaser.Easing.Bounce */ - Bounce: { + Bounce: { - /** - * Bounce ease-in. - * - * @method Phaser.Easing.Bounce#In - * @param {number} k - The value to be tweened. - * @returns {number} The tweened value. - */ - In: function ( k ) { + /** + * 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 ); + return 1 - Phaser.Easing.Bounce.Out( 1 - k ); - }, + }, - /** - * Bounce ease-out. - * - * @method Phaser.Easing.Bounce#Out - * @param {number} k - The value to be tweened. - * @returns {number} The tweened value. - */ - Out: function ( k ) { + /** + * 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 ) ) { + if ( k < ( 1 / 2.75 ) ) { - return 7.5625 * k * k; + return 7.5625 * k * k; - } else if ( k < ( 2 / 2.75 ) ) { + } else if ( k < ( 2 / 2.75 ) ) { - return 7.5625 * ( k -= ( 1.5 / 2.75 ) ) * k + 0.75; + return 7.5625 * ( k -= ( 1.5 / 2.75 ) ) * k + 0.75; - } else if ( k < ( 2.5 / 2.75 ) ) { + } else if ( k < ( 2.5 / 2.75 ) ) { - return 7.5625 * ( k -= ( 2.25 / 2.75 ) ) * k + 0.9375; + return 7.5625 * ( k -= ( 2.25 / 2.75 ) ) * k + 0.9375; - } else { + } else { - return 7.5625 * ( k -= ( 2.625 / 2.75 ) ) * k + 0.984375; + return 7.5625 * ( k -= ( 2.625 / 2.75 ) ) * k + 0.984375; - } + } - }, + }, - /** - * Bounce ease-in/out. - * - * @method Phaser.Easing.Bounce#InOut - * @param {number} k - The value to be tweened. - * @returns {number} The tweened value. - */ - InOut: function ( k ) { + /** + * 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; + 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 d15322bb2..a444fb1c3 100644 --- a/src/tween/Tween.js +++ b/src/tween/Tween.js @@ -20,7 +20,7 @@ Phaser.Tween = function (object, game) { * @property {object} _object * @private */ - this._object = object; + this._object = object; /** * @property {Phaser.Game} game - A reference to the currently running Game. @@ -154,7 +154,7 @@ Phaser.Tween = function (object, game) { // Set all starting values present on the target object for ( var field in object ) { - this._valuesStart[ field ] = parseFloat(object[field], 10); + this._valuesStart[ field ] = parseFloat(object[field], 10); } /** @@ -177,45 +177,45 @@ Phaser.Tween = function (object, game) { Phaser.Tween.prototype = { - /** - * Configure the Tween - * - * @method Phaser.Tween#to - * @param {object} properties - Properties you want to tween. - * @param {number} duration - Duration of this tween. - * @param {function} ease - Easing function. - * @param {boolean} autoStart - Whether this tween will start automatically or not. - * @param {number} delay - Delay before this tween will start, defaults to 0 (no delay). - * @param {boolean} repeat - Should the tween automatically restart once complete? (ignores any chained tweens). - * @param {Phaser.Tween} yoyo - Description. - * @return {Phaser.Tween} Itself. - */ - to: function ( properties, duration, ease, autoStart, delay, repeat, yoyo ) { + /** + * Configure the Tween + * + * @method Phaser.Tween#to + * @param {object} properties - Properties you want to tween. + * @param {number} duration - Duration of this tween. + * @param {function} ease - Easing function. + * @param {boolean} autoStart - Whether this tween will start automatically or not. + * @param {number} delay - Delay before this tween will start, defaults to 0 (no delay). + * @param {boolean} repeat - Should the tween automatically restart once complete? (ignores any chained tweens). + * @param {Phaser.Tween} yoyo - Description. + * @return {Phaser.Tween} Itself. + */ + to: function ( properties, duration, ease, autoStart, delay, repeat, yoyo ) { - duration = duration || 1000; - ease = ease || null; - autoStart = autoStart || false; - delay = delay || 0; - repeat = repeat || 0; - yoyo = yoyo || false; + duration = duration || 1000; + ease = ease || null; + autoStart = autoStart || false; + delay = delay || 0; + repeat = repeat || 0; + yoyo = yoyo || false; - var self; - if (this._parent) - { - self = this._manager.create(this._object); - this._lastChild.chain(self); - this._lastChild = self; - } - else - { - self = this; - this._parent = this; - this._lastChild = this; - } + var self; + if (this._parent) + { + self = this._manager.create(this._object); + this._lastChild.chain(self); + this._lastChild = self; + } + else + { + self = this; + this._parent = this; + this._lastChild = this; + } - self._repeat = repeat; + self._repeat = repeat; self._duration = duration; - self._valuesEnd = properties; + self._valuesEnd = properties; if (ease !== null) { @@ -235,256 +235,255 @@ Phaser.Tween.prototype = { return this; } - }, + }, - /** - * Starts the tween running. Can also be called by the autoStart parameter of Tween.to. - * - * @method Phaser.Tween#start - * @param {number} time - Description. - * @return {Phaser.Tween} Itself. - */ - start: function ( time ) { + /** + * Starts the tween running. Can also be called by the autoStart parameter of Tween.to. + * + * @method Phaser.Tween#start + * @return {Phaser.Tween} Itself. + */ + start: function () { if (this.game === null || this._object === null) { return; } - this._manager.add(this); + this._manager.add(this); - this.onStart.dispatch(this._object); + this.onStart.dispatch(this._object); this.isRunning = true; - this._onStartCallbackFired = false; + this._onStartCallbackFired = false; this._startTime = this.game.time.now + this._delayTime; - for ( var property in this._valuesEnd ) { + for ( var property in this._valuesEnd ) { - // check if an Array was provided as property value - if ( this._valuesEnd[ property ] instanceof Array ) { + // check if an Array was provided as property value + if ( this._valuesEnd[ property ] instanceof Array ) { - if ( this._valuesEnd[ property ].length === 0 ) { + if ( this._valuesEnd[ property ].length === 0 ) { - continue; + continue; - } + } - // create a local copy of the Array with the start value at the front - this._valuesEnd[ property ] = [ this._object[ property ] ].concat( this._valuesEnd[ property ] ); + // create a local copy of the Array with the start value at the front + this._valuesEnd[ property ] = [ this._object[ property ] ].concat( this._valuesEnd[ property ] ); - } + } - this._valuesStart[ property ] = this._object[ property ]; + this._valuesStart[ property ] = this._object[ property ]; - if ( ( this._valuesStart[ property ] instanceof Array ) === false ) { - this._valuesStart[ property ] *= 1.0; // Ensures we're using numbers, not strings - } + if ( ( this._valuesStart[ property ] instanceof Array ) === false ) { + this._valuesStart[ property ] *= 1.0; // Ensures we're using numbers, not strings + } - this._valuesStartRepeat[ property ] = this._valuesStart[ property ] || 0; + this._valuesStartRepeat[ property ] = this._valuesStart[ property ] || 0; - } + } - return this; + return this; - }, + }, - /** - * Stops the tween if running and removes it from the TweenManager. If there are any onComplete callbacks or events they are not dispatched. - * - * @method Phaser.Tween#stop - * @return {Phaser.Tween} Itself. - */ - stop: function () { + /** + * Stops the tween if running and removes it from the TweenManager. If there are any onComplete callbacks or events they are not dispatched. + * + * @method Phaser.Tween#stop + * @return {Phaser.Tween} Itself. + */ + stop: function () { this.isRunning = false; - this._manager.remove(this); + this._manager.remove(this); - return this; + return this; - }, + }, - /** - * Sets a delay time before this tween will start. - * - * @method Phaser.Tween#delay - * @param {number} amount - The amount of the delay in ms. - * @return {Phaser.Tween} Itself. - */ - delay: function ( amount ) { + /** + * Sets a delay time before this tween will start. + * + * @method Phaser.Tween#delay + * @param {number} amount - The amount of the delay in ms. + * @return {Phaser.Tween} Itself. + */ + delay: function ( amount ) { - this._delayTime = amount; - return this; + this._delayTime = amount; + return this; - }, + }, - /** - * Sets the number of times this tween will repeat. - * - * @method Phaser.Tween#repeat - * @param {number} times - How many times to repeat. - * @return {Phaser.Tween} Itself. - */ - repeat: function ( times ) { + /** + * Sets the number of times this tween will repeat. + * + * @method Phaser.Tween#repeat + * @param {number} times - How many times to repeat. + * @return {Phaser.Tween} Itself. + */ + repeat: function ( times ) { - this._repeat = times; - return this; + this._repeat = times; + return this; - }, + }, - /** - * A tween that has yoyo set to true will run through from start to finish, then reverse from finish to start. - * Used in combination with repeat you can create endless loops. - * - * @method Phaser.Tween#yoyo - * @param {boolean} yoyo - Set to true to yoyo this tween. - * @return {Phaser.Tween} Itself. - */ - yoyo: function( yoyo ) { + /** + * A tween that has yoyo set to true will run through from start to finish, then reverse from finish to start. + * Used in combination with repeat you can create endless loops. + * + * @method Phaser.Tween#yoyo + * @param {boolean} yoyo - Set to true to yoyo this tween. + * @return {Phaser.Tween} Itself. + */ + yoyo: function( yoyo ) { - this._yoyo = yoyo; - return this; + this._yoyo = yoyo; + return this; - }, + }, - /** - * Set easing function this tween will use, i.e. Phaser.Easing.Linear.None. - * - * @method Phaser.Tween#easing - * @param {function} easing - The easing function this tween will use, i.e. Phaser.Easing.Linear.None. - * @return {Phaser.Tween} Itself. - */ - easing: function ( easing ) { + /** + * Set easing function this tween will use, i.e. Phaser.Easing.Linear.None. + * + * @method Phaser.Tween#easing + * @param {function} easing - The easing function this tween will use, i.e. Phaser.Easing.Linear.None. + * @return {Phaser.Tween} Itself. + */ + easing: function ( easing ) { - this._easingFunction = easing; - return this; + this._easingFunction = easing; + return this; - }, + }, - /** - * Set interpolation function the tween will use, by default it uses Phaser.Math.linearInterpolation. - * - * @method Phaser.Tween#interpolation - * @param {function} interpolation - The interpolation function to use (Phaser.Math.linearInterpolation by default) - * @return {Phaser.Tween} Itself. - */ - interpolation: function ( interpolation ) { + /** + * Set interpolation function the tween will use, by default it uses Phaser.Math.linearInterpolation. + * + * @method Phaser.Tween#interpolation + * @param {function} interpolation - The interpolation function to use (Phaser.Math.linearInterpolation by default) + * @return {Phaser.Tween} Itself. + */ + interpolation: function ( interpolation ) { - this._interpolationFunction = interpolation; - return this; + this._interpolationFunction = interpolation; + return this; - }, + }, - /** - * You can chain tweens together by passing a reference to the chain function. This enables one tween to call another on completion. - * You can pass as many tweens as you like to this function, they will each be chained in sequence. - * - * @method Phaser.Tween#chain - * @return {Phaser.Tween} Itself. - */ - chain: function () { + /** + * You can chain tweens together by passing a reference to the chain function. This enables one tween to call another on completion. + * You can pass as many tweens as you like to this function, they will each be chained in sequence. + * + * @method Phaser.Tween#chain + * @return {Phaser.Tween} Itself. + */ + chain: function () { - this._chainedTweens = arguments; - return this; + this._chainedTweens = arguments; + return this; - }, + }, - /** - * Loop a chain of tweens - * - * Usage: - * game.add.tween(p).to({ x: 700 }, 1000, Phaser.Easing.Linear.None, true) - * .to({ y: 300 }, 1000, Phaser.Easing.Linear.None) - * .to({ x: 0 }, 1000, Phaser.Easing.Linear.None) - * .to({ y: 0 }, 1000, Phaser.Easing.Linear.None) - * .loop(); - * @method Phaser.Tween#loop - * @return {Phaser.Tween} Itself. - */ - loop: function() { + /** + * Loop a chain of tweens + * + * Usage: + * game.add.tween(p).to({ x: 700 }, 1000, Phaser.Easing.Linear.None, true) + * .to({ y: 300 }, 1000, Phaser.Easing.Linear.None) + * .to({ x: 0 }, 1000, Phaser.Easing.Linear.None) + * .to({ y: 0 }, 1000, Phaser.Easing.Linear.None) + * .loop(); + * @method Phaser.Tween#loop + * @return {Phaser.Tween} Itself. + */ + loop: function() { - this._lastChild.chain(this); - return this; + this._lastChild.chain(this); + return this; - }, + }, - /** - * Sets a callback to be fired when the tween starts. Note: callback will be called in the context of the global scope. - * - * @method Phaser.Tween#onStartCallback - * @param {function} callback - The callback to invoke on start. - * @return {Phaser.Tween} Itself. - */ - onStartCallback: function ( callback ) { + /** + * Sets a callback to be fired when the tween starts. Note: callback will be called in the context of the global scope. + * + * @method Phaser.Tween#onStartCallback + * @param {function} callback - The callback to invoke on start. + * @return {Phaser.Tween} Itself. + */ + onStartCallback: function ( callback ) { - this._onStartCallback = callback; - return this; + this._onStartCallback = callback; + return this; - }, + }, - /** - * Sets a callback to be fired each time this tween updates. Note: callback will be called in the context of the global scope. - * - * @method Phaser.Tween#onUpdateCallback - * @param {function} callback - The callback to invoke each time this tween is updated. - * @return {Phaser.Tween} Itself. - */ - onUpdateCallback: function ( callback ) { + /** + * Sets a callback to be fired each time this tween updates. Note: callback will be called in the context of the global scope. + * + * @method Phaser.Tween#onUpdateCallback + * @param {function} callback - The callback to invoke each time this tween is updated. + * @return {Phaser.Tween} Itself. + */ + onUpdateCallback: function ( callback ) { - this._onUpdateCallback = callback; - return this; + this._onUpdateCallback = callback; + return this; - }, + }, - /** - * Sets a callback to be fired when the tween completes. Note: callback will be called in the context of the global scope. - * - * @method Phaser.Tween#onCompleteCallback - * @param {function} callback - The callback to invoke on completion. - * @return {Phaser.Tween} Itself. - */ - onCompleteCallback: function ( callback ) { + /** + * Sets a callback to be fired when the tween completes. Note: callback will be called in the context of the global scope. + * + * @method Phaser.Tween#onCompleteCallback + * @param {function} callback - The callback to invoke on completion. + * @return {Phaser.Tween} Itself. + */ + onCompleteCallback: function ( callback ) { - this._onCompleteCallback = callback; - return this; + this._onCompleteCallback = callback; + return this; - }, + }, - /** - * Pauses the tween. - * - * @method Phaser.Tween#pause - */ + /** + * Pauses the tween. + * + * @method Phaser.Tween#pause + */ pause: function () { this._paused = true; this._pausedTime = this.game.time.now; }, - /** - * Resumes a paused tween. - * - * @method Phaser.Tween#resume - */ + /** + * Resumes a paused tween. + * + * @method Phaser.Tween#resume + */ resume: function () { this._paused = false; this._startTime += (this.game.time.now - this._pausedTime); }, - /** - * Core tween update function called by the TweenManager. Does not need to be invoked directly. - * - * @method Phaser.Tween#update - * @param {number} time - A timestamp passed in by the TweenManager. - * @return {boolean} false if the tween has completed and should be deleted from the manager, otherwise true (still active). - */ - update: function ( time ) { + /** + * Core tween update function called by the TweenManager. Does not need to be invoked directly. + * + * @method Phaser.Tween#update + * @param {number} time - A timestamp passed in by the TweenManager. + * @return {boolean} false if the tween has completed and should be deleted from the manager, otherwise true (still active). + */ + update: function ( time ) { - if (this.pendingDelete) - { - return false; - } + if (this.pendingDelete) + { + return false; + } if (this._paused || time < this._startTime) { @@ -492,120 +491,120 @@ Phaser.Tween.prototype = { } - var property; + var property; - if ( time < this._startTime ) { + if ( time < this._startTime ) { - return true; + return true; - } + } - if ( this._onStartCallbackFired === false ) { + if ( this._onStartCallbackFired === false ) { - if ( this._onStartCallback !== null ) { + if ( this._onStartCallback !== null ) { - this._onStartCallback.call( this._object ); + this._onStartCallback.call( this._object ); - } + } - this._onStartCallbackFired = true; + this._onStartCallbackFired = true; - } + } - var elapsed = ( time - this._startTime ) / this._duration; - elapsed = elapsed > 1 ? 1 : elapsed; + var elapsed = ( time - this._startTime ) / this._duration; + elapsed = elapsed > 1 ? 1 : elapsed; - var value = this._easingFunction( elapsed ); + var value = this._easingFunction( elapsed ); - for ( property in this._valuesEnd ) { + for ( property in this._valuesEnd ) { - var start = this._valuesStart[ property ] || 0; - var end = this._valuesEnd[ property ]; + var start = this._valuesStart[ property ] || 0; + var end = this._valuesEnd[ property ]; - if ( end instanceof Array ) { + if ( end instanceof Array ) { - this._object[ property ] = this._interpolationFunction( end, value ); + this._object[ property ] = this._interpolationFunction( end, value ); - } else { + } else { // Parses relative end values with start as base (e.g.: +10, -3) - if ( typeof(end) === "string" ) { - end = start + parseFloat(end, 10); - } + if ( typeof(end) === "string" ) { + end = start + parseFloat(end, 10); + } - // protect against non numeric properties. + // protect against non numeric properties. if ( typeof(end) === "number" ) { - this._object[ property ] = start + ( end - start ) * value; - } + this._object[ property ] = start + ( end - start ) * value; + } - } + } - } + } - if ( this._onUpdateCallback !== null ) { + if ( this._onUpdateCallback !== null ) { - this._onUpdateCallback.call( this._object, value ); + this._onUpdateCallback.call( this._object, value ); - } + } - if ( elapsed == 1 ) { + if ( elapsed == 1 ) { - if ( this._repeat > 0 ) { + if ( this._repeat > 0 ) { - if ( isFinite( this._repeat ) ) { - this._repeat--; - } + if ( isFinite( this._repeat ) ) { + this._repeat--; + } - // reassign starting values, restart by making startTime = now - for ( property in this._valuesStartRepeat ) { + // reassign starting values, restart by making startTime = now + for ( property in this._valuesStartRepeat ) { - if ( typeof( this._valuesEnd[ property ] ) === "string" ) { - this._valuesStartRepeat[ property ] = this._valuesStartRepeat[ property ] + parseFloat(this._valuesEnd[ property ], 10); - } + if ( typeof( this._valuesEnd[ property ] ) === "string" ) { + this._valuesStartRepeat[ property ] = this._valuesStartRepeat[ property ] + parseFloat(this._valuesEnd[ property ], 10); + } - if (this._yoyo) { - var tmp = this._valuesStartRepeat[ property ]; - this._valuesStartRepeat[ property ] = this._valuesEnd[ property ]; - this._valuesEnd[ property ] = tmp; - this._reversed = !this._reversed; - } - this._valuesStart[ property ] = this._valuesStartRepeat[ property ]; + if (this._yoyo) { + var tmp = this._valuesStartRepeat[ property ]; + this._valuesStartRepeat[ property ] = this._valuesEnd[ property ]; + this._valuesEnd[ property ] = tmp; + this._reversed = !this._reversed; + } + this._valuesStart[ property ] = this._valuesStartRepeat[ property ]; - } + } - this._startTime = time + this._delayTime; + this._startTime = time + this._delayTime; - this.onComplete.dispatch(this._object); + this.onComplete.dispatch(this._object); - if ( this._onCompleteCallback !== null ) { - this._onCompleteCallback.call( this._object ); - } + if ( this._onCompleteCallback !== null ) { + this._onCompleteCallback.call( this._object ); + } - return true; + return true; - } else { + } else { - this.isRunning = false; - this.onComplete.dispatch(this._object); + this.isRunning = false; + this.onComplete.dispatch(this._object); - if ( this._onCompleteCallback !== null ) { - this._onCompleteCallback.call( this._object ); - } + if ( this._onCompleteCallback !== null ) { + this._onCompleteCallback.call( this._object ); + } - for ( var i = 0, numChainedTweens = this._chainedTweens.length; i < numChainedTweens; i ++ ) { + for ( var i = 0, numChainedTweens = this._chainedTweens.length; i < numChainedTweens; i ++ ) { - this._chainedTweens[ i ].start( time ); + this._chainedTweens[ i ].start( time ); - } + } - return false; + return false; - } + } - } + } - return true; + return true; - } - + } + }; diff --git a/src/tween/TweenManager.js b/src/tween/TweenManager.js index 3e94fe5ed..00974bf32 100644 --- a/src/tween/TweenManager.js +++ b/src/tween/TweenManager.js @@ -22,180 +22,183 @@ */ Phaser.TweenManager = function (game) { - /** - * @property {Phaser.Game} game - Local reference to game. - */ - this.game = game; - - /** - * @property {array} _tweens - Description. - * @private - */ - this._tweens = []; - - /** - * @property {array} _add - Description. - * @private - */ - this._add = []; + /** + * @property {Phaser.Game} game - Local reference to game. + */ + this.game = game; + + /** + * @property {array} _tweens - Description. + * @private + */ + this._tweens = []; + + /** + * @property {array} _add - Description. + * @private + */ + this._add = []; - this.game.onPause.add(this.pauseAll, this); - this.game.onResume.add(this.resumeAll, this); + this.game.onPause.add(this.pauseAll, this); + this.game.onResume.add(this.resumeAll, this); }; Phaser.TweenManager.prototype = { - /** - * Version number of this library. - * @property {string} REVISION - * @default - */ - REVISION: '11dev', + /** + * Version number of this library. + * @property {string} REVISION + * @default + */ + REVISION: '11dev', - /** - * Get all the tween objects in an array. - * @method Phaser.TweenManager#getAll - * @returns {Phaser.Tween[]} Array with all tween objects. - */ - getAll: function () { + /** + * 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; + return this._tweens; - }, + }, - /** - * Remove all tween objects. - * @method Phaser.TweenManager#removeAll - */ - removeAll: function () { + /** + * Remove all tween objects. + * @method Phaser.TweenManager#removeAll + */ + removeAll: function () { - this._tweens = []; + this._tweens = []; - }, + }, - /** - * 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 ) { + /** + * 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 ) { - this._add.push( tween ); + 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); }, - /** - * Remove a tween from this manager. - * - * @method Phaser.TweenManager#remove - * @param {Phaser.Tween} tween - The tween object you want to remove. - */ - remove: function ( tween ) { + /** + * 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 ); + var i = this._tweens.indexOf( tween ); - if ( i !== -1 ) { + if ( i !== -1 ) { - this._tweens[i].pendingDelete = true; + this._tweens[i].pendingDelete = true; - } - - }, - - /** - * Update all the tween objects you added to this manager. - * - * @method Phaser.TweenManager#update - * @returns {boolean} Return false if there's no tween to update, otherwise return true. - */ - update: function () { - - if ( this._tweens.length === 0 && this._add.length === 0 ) return false; - - var i = 0; - var numTweens = this._tweens.length; - - while ( i < numTweens ) { - - if ( this._tweens[ i ].update( this.game.time.now ) ) { - - i++; - - } else { - - this._tweens.splice( i, 1 ); - - numTweens--; - - } - - } - - // If there are any new tweens to be added, do so now - otherwise they can be spliced out of the array before ever running - if (this._add.length > 0) - { - this._tweens = this._tweens.concat(this._add); - this._add.length = 0; - } - - return true; - - }, - - /** - * Checks to see if a particular Sprite is currently being tweened. - * - * @method Phaser.TweenManager#isTweening - * @param {object} object - The object to check for tweens against. - * @returns {boolean} Returns true if the object is currently being tweened, false if not. - */ - isTweening: function(object) { - - return this._tweens.some(function(tween) { - return tween._object === object; - }); - - }, - - /** - * Pauses all currently running tweens. - * - * @method Phaser.TweenManager#update - */ - pauseAll: function () { - - for (var i = this._tweens.length - 1; i >= 0; i--) { - this._tweens[i].pause(); - }; + } }, - /** - * Pauses all currently paused tweens. - * - * @method Phaser.TweenManager#resumeAll - */ - resumeAll: function () { + /** + * 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 () { - for (var i = this._tweens.length - 1; i >= 0; i--) { - this._tweens[i].resume(); - }; + if ( this._tweens.length === 0 && this._add.length === 0 ) + { + return false; + } + + var i = 0; + var numTweens = this._tweens.length; + + while ( i < numTweens ) { + + if ( this._tweens[ i ].update( this.game.time.now ) ) { + + i++; + + } else { + + this._tweens.splice( i, 1 ); + + numTweens--; + + } + + } + + // If there are any new tweens to be added, do so now - otherwise they can be spliced out of the array before ever running + if (this._add.length > 0) + { + this._tweens = this._tweens.concat(this._add); + this._add.length = 0; + } + + return true; + + }, + + /** + * Checks to see if a particular Sprite is currently being tweened. + * + * @method Phaser.TweenManager#isTweening + * @param {object} object - The object to check for tweens against. + * @returns {boolean} Returns true if the object is currently being tweened, false if not. + */ + isTweening: function(object) { + + return this._tweens.some(function(tween) { + return tween._object === object; + }); + + }, + + /** + * Pauses all currently running tweens. + * + * @method Phaser.TweenManager#update + */ + pauseAll: function () { + + for (var i = this._tweens.length - 1; i >= 0; i--) { + this._tweens[i].pause(); + } + + }, + + /** + * Pauses all currently paused tweens. + * + * @method Phaser.TweenManager#resumeAll + */ + resumeAll: function () { + + for (var i = this._tweens.length - 1; i >= 0; i--) { + this._tweens[i].resume(); + } } diff --git a/src/utils/Color.js b/src/utils/Color.js index fd0809a46..55bb11924 100644 --- a/src/utils/Color.js +++ b/src/utils/Color.js @@ -79,13 +79,13 @@ Phaser.Color = { var argb = Phaser.Color.getRGB(color); var hsl = Phaser.Color.RGBtoHSV(color); - // Hex format + // Hex format var result = Phaser.Color.RGBtoHexstring(color) + "\n"; - // RGB format + // RGB format result = result.concat("Alpha: " + argb.alpha + " Red: " + argb.red + " Green: " + argb.green + " Blue: " + argb.blue) + "\n"; - // HSL info + // HSL info result = result.concat("Hue: " + hsl.hue + " Saturation: " + hsl.saturation + " Lightnes: " + hsl.lightness); return result; @@ -232,7 +232,7 @@ Phaser.Color = { if (typeof max === "undefined") { max = 255; } if (typeof alpha === "undefined") { alpha = 255; } - // Sanity checks + // Sanity checks if (max > 255) { return Phaser.Color.getColor(255, 255, 255); } @@ -347,5 +347,5 @@ Phaser.Color = { getBlue: function (color) { return color & 0xFF; } - + }; diff --git a/src/utils/Debug.js b/src/utils/Debug.js index a358ad6ba..18dfa3a9d 100644 --- a/src/utils/Debug.js +++ b/src/utils/Debug.js @@ -15,47 +15,47 @@ 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 {Context} context - The canvas context on which to render the debug information. - */ + /** + * @property {Context} context - The canvas context on which to render the debug information. + */ this.context = game.context; - /** - * @property {string} font - The font that the debug information is rendered in. - * @default '14px Courier' - */ + /** + * @property {string} font - The font that the debug information is rendered in. + * @default '14px Courier' + */ this.font = '14px Courier'; - /** - * @property {number} lineHeight - The line height between the debug text. - */ + /** + * @property {number} lineHeight - The line height between the debug text. + */ this.lineHeight = 16; - /** - * @property {boolean} renderShadow - Should the text be rendered with a slight shadow? Makes it easier to read on different types of background. - */ + /** + * @property {boolean} renderShadow - Should the text be rendered with a slight shadow? Makes it easier to read on different types of background. + */ this.renderShadow = true; - /** - * @property {Context} currentX - The current X position the debug information will be rendered at. - * @default - */ + /** + * @property {Context} currentX - The current X position the debug information will be rendered at. + * @default + */ this.currentX = 0; - /** - * @property {number} currentY - The current Y position the debug information will be rendered at. - * @default - */ + /** + * @property {number} currentY - The current Y position the debug information will be rendered at. + * @default + */ this.currentY = 0; - /** - * @property {number} currentAlpha - The current alpha the debug information will be rendered at. - * @default - */ + /** + * @property {number} currentAlpha - The current alpha the debug information will be rendered at. + * @default + */ this.currentAlpha = 1; }; @@ -184,13 +184,13 @@ Phaser.Utils.Debug.prototype = { }, /** - * Renders the corners and point information of the given Sprite. - * @method Phaser.Utils.Debug#renderSpriteCorners - * @param {Phaser.Sprite} sprite - The sprite to be rendered. - * @param {boolean} [showText=false] - If true the x/y coordinates of each point will be rendered. - * @param {boolean} [showBounds=false] - If true the bounds will be rendered over the top of the sprite. - * @param {string} [color='rgb(255,0,255)'] - The color the text is rendered in. - */ + * Renders the corners and point information of the given Sprite. + * @method Phaser.Utils.Debug#renderSpriteCorners + * @param {Phaser.Sprite} sprite - The sprite to be rendered. + * @param {boolean} [showText=false] - If true the x/y coordinates of each point will be rendered. + * @param {boolean} [showBounds=false] - If true the bounds will be rendered over the top of the sprite. + * @param {string} [color='rgb(255,0,255)'] - The color the text is rendered in. + */ renderSpriteCorners: function (sprite, showText, showBounds, color) { if (this.context == null) @@ -372,7 +372,7 @@ Phaser.Utils.Debug.prototype = { * @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). - */ + */ renderSpriteInputInfo: function (sprite, x, y, color) { color = color || 'rgb(255,255,255)'; @@ -388,13 +388,13 @@ Phaser.Utils.Debug.prototype = { }, /** - * Render Sprite collision. - * @method Phaser.Utils.Debug#renderSpriteCollision - * @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. + * Render Sprite collision. + * @method Phaser.Utils.Debug#renderSpriteCollision + * @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). - */ + */ renderSpriteCollision: function (sprite, x, y, color) { color = color || 'rgb(255,255,255)'; @@ -779,7 +779,7 @@ Phaser.Utils.Debug.prototype = { * @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. - */ + */ renderText: function (text, x, y, color, font) { if (this.context == null) @@ -819,7 +819,7 @@ Phaser.Utils.Debug.prototype = { var testObject = entity.last.next; entity = entity.first; - do + do { var name = entity.sprite.name || '*'; var nameNext = '-'; diff --git a/src/utils/Utils.js b/src/utils/Utils.js index 6afd16a57..8619f78bf 100644 --- a/src/utils/Utils.js +++ b/src/utils/Utils.js @@ -1,3 +1,5 @@ +/* jshint supernew: true */ + /** * @author Richard Davey * @copyright 2013 Photon Storm Ltd. @@ -9,67 +11,69 @@ * @static */ Phaser.Utils = { - - /** - * A standard Fisher-Yates Array shuffle implementation. - * @method Phaser.Utils.shuffle - * @param {array} array - The array to shuffle. - * @return {array} The shuffled array. - */ - shuffle: function (array) { + + /** + * A standard Fisher-Yates Array shuffle implementation. + * @method Phaser.Utils.shuffle + * @param {array} array - The array to shuffle. + * @return {array} The shuffled array. + */ + shuffle: function (array) { - for (var i = array.length - 1; i > 0; i--) - { - var j = Math.floor(Math.random() * (i + 1)); - var temp = array[i]; - array[i] = array[j]; - array[j] = temp; - } + for (var i = array.length - 1; i > 0; i--) + { + var j = Math.floor(Math.random() * (i + 1)); + var temp = array[i]; + array[i] = array[j]; + array[j] = temp; + } - return array; - - }, + return array; + + }, - /** - * Javascript string pad http://www.webtoolkit.info/. - * pad = the string to pad it out with (defaults to a space) - * dir = 1 (left), 2 (right), 3 (both) - * @method Phaser.Utils.pad - * @param {string} str - The target string. - * @param {number} len - Description. - * @param {number} pad - the string to pad it out with (defaults to a space). - * @param {number} [dir=3] the direction dir = 1 (left), 2 (right), 3 (both). - * @return {string} The padded string - */ - pad: function (str, len, pad, dir) { + /** + * Javascript string pad http://www.webtoolkit.info/. + * pad = the string to pad it out with (defaults to a space) + * dir = 1 (left), 2 (right), 3 (both) + * @method Phaser.Utils.pad + * @param {string} str - The target string. + * @param {number} len - Description. + * @param {number} pad - the string to pad it out with (defaults to a space). + * @param {number} [dir=3] the direction dir = 1 (left), 2 (right), 3 (both). + * @return {string} The padded string + */ + pad: function (str, len, pad, dir) { - if (typeof(len) == "undefined") { var len = 0; } - if (typeof(pad) == "undefined") { var pad = ' '; } - if (typeof(dir) == "undefined") { var dir = 3; } + if (typeof(len) == "undefined") { var len = 0; } + if (typeof(pad) == "undefined") { var pad = ' '; } + if (typeof(dir) == "undefined") { var dir = 3; } - if (len + 1 >= str.length) - { - switch (dir) - { - case 1: - str = Array(len + 1 - str.length).join(pad) + str; - break; + var padlen = 0; - case 3: - var right = Math.ceil((padlen = len - str.length) / 2); - var left = padlen - right; - str = Array(left+1).join(pad) + str + Array(right+1).join(pad); - break; + if (len + 1 >= str.length) + { + switch (dir) + { + case 1: + str = Array(len + 1 - str.length).join(pad) + str; + break; - default: - str = str + Array(len + 1 - str.length).join(pad); - break; - } - } + case 3: + var right = Math.ceil((padlen = len - str.length) / 2); + var left = padlen - right; + str = Array(left+1).join(pad) + str + Array(right+1).join(pad); + break; - return str; + default: + str = str + Array(len + 1 - str.length).join(pad); + break; + } + } - }, + return str; + + }, /** * This is a slightly modified version of jQuery.isPlainObject. A plain object is an object whose internal class property is [object Object]. @@ -77,41 +81,41 @@ Phaser.Utils = { * @param {object} obj - The object to inspect. * @return {boolean} - true if the object is plain, otherwise false. */ - isPlainObject: function (obj) { + isPlainObject: function (obj) { - // Not plain objects: - // - Any object or value whose internal [[Class]] property is not "[object Object]" - // - DOM nodes - // - window - if (typeof(obj) !== "object" || obj.nodeType || obj === obj.window) - { - return false; - } + // Not plain objects: + // - Any object or value whose internal [[Class]] property is not "[object Object]" + // - DOM nodes + // - window + if (typeof(obj) !== "object" || obj.nodeType || obj === obj.window) + { + return false; + } - // Support: Firefox <20 - // The try/catch suppresses exceptions thrown when attempting to access - // the "constructor" property of certain host objects, ie. |window.location| - // https://bugzilla.mozilla.org/show_bug.cgi?id=814622 - try { - if (obj.constructor && !hasOwn.call(obj.constructor.prototype, "isPrototypeOf")) - { - return false; - } - } catch (e) { - return false; - } + // Support: Firefox <20 + // The try/catch suppresses exceptions thrown when attempting to access + // the "constructor" property of certain host objects, ie. |window.location| + // https://bugzilla.mozilla.org/show_bug.cgi?id=814622 + try { + if (obj.constructor && !hasOwn.call(obj.constructor.prototype, "isPrototypeOf")) + { + return false; + } + } catch (e) { + return false; + } - // If the function hasn't returned already, we're confident that - // |obj| is a plain object, created by {} or constructed with new Object - return true; - }, + // If the function hasn't returned already, we're confident that + // |obj| is a plain object, created by {} or constructed with new Object + return true; + }, - // deep, target, objects to copy to the target object - // This is a slightly modified version of {@link http://api.jquery.com/jQuery.extend/|jQuery.extend} - // deep (boolean) - // target (object to add to) - // objects ... (objects to recurse and copy from) + // deep, target, objects to copy to the target object + // This is a slightly modified version of {@link http://api.jquery.com/jQuery.extend/|jQuery.extend} + // deep (boolean) + // target (object to add to) + // objects ... (objects to recurse and copy from) /** * This is a slightly modified version of http://api.jquery.com/jQuery.extend/ @@ -120,87 +124,87 @@ Phaser.Utils = { * @param {object} target - The target object to copy to. * @return {object} The extended object. */ - extend: function () { + extend: function () { - var options, name, src, copy, copyIsArray, clone, - target = arguments[0] || {}, - i = 1, - length = arguments.length, - deep = false; + var options, name, src, copy, copyIsArray, clone, + target = arguments[0] || {}, + i = 1, + length = arguments.length, + deep = false; - // Handle a deep copy situation - if (typeof target === "boolean") - { - deep = target; - target = arguments[1] || {}; - // skip the boolean and the target - i = 2; - } + // Handle a deep copy situation + if (typeof target === "boolean") + { + deep = target; + target = arguments[1] || {}; + // skip the boolean and the target + i = 2; + } - // extend Phaser if only one argument is passed - if (length === i) - { - target = this; - --i; - } + // extend Phaser if only one argument is passed + if (length === i) + { + target = this; + --i; + } - for ( ; i < length; i++ ) - { - // Only deal with non-null/undefined values - if ((options = arguments[i]) != null) - { - // Extend the base object - for (name in options) - { - src = target[name]; - copy = options[name]; + for ( ; i < length; i++ ) + { + // Only deal with non-null/undefined values + if ((options = arguments[i]) != null) + { + // Extend the base object + for (name in options) + { + src = target[name]; + copy = options[name]; - // Prevent never-ending loop - if (target === copy) - { - continue; - } + // Prevent never-ending loop + if (target === copy) + { + continue; + } - // Recurse if we're merging plain objects or arrays - if (deep && copy && (Phaser.Utils.isPlainObject(copy) || (copyIsArray = Array.isArray(copy)))) - { - if (copyIsArray) - { - copyIsArray = false; - clone = src && Array.isArray(src) ? src : []; - } - else - { - clone = src && Phaser.Utils.isPlainObject(src) ? src : {}; - } + // Recurse if we're merging plain objects or arrays + if (deep && copy && (Phaser.Utils.isPlainObject(copy) || (copyIsArray = Array.isArray(copy)))) + { + if (copyIsArray) + { + copyIsArray = false; + clone = src && Array.isArray(src) ? src : []; + } + else + { + clone = src && Phaser.Utils.isPlainObject(src) ? src : {}; + } - // Never move original objects, clone them - target[name] = Phaser.Utils.extend(deep, clone, copy); + // Never move original objects, clone them + target[name] = Phaser.Utils.extend(deep, clone, copy); - // Don't bring in undefined values - } - else if (copy !== undefined) - { - target[name] = copy; - } - } - } - } + // Don't bring in undefined values + } + else if (copy !== undefined) + { + target[name] = copy; + } + } + } + } - // Return the modified object - return target; - } + // Return the modified object + return target; + } }; -// Global functions that PIXI needs +// Global functions that PIXI needs (function() { var consoleDisabled = false; if (consoleDisabled) { window.console = undefined; } - if (window.console == undefined) { + if (window.console === undefined) { window.console = { debug: function() { return true; @@ -237,32 +241,42 @@ Phaser.Utils = { * @return {array} */ function HEXtoRGB(hex) { - return [(hex >> 16 & 0xFF) / 255, ( hex >> 8 & 0xFF) / 255, (hex & 0xFF)/ 255]; + return [(hex >> 16 & 0xFF) / 255, ( hex >> 8 & 0xFF) / 255, (hex & 0xFF)/ 255]; } /** * A polyfill for Function.prototype.bind */ if (typeof Function.prototype.bind != 'function') { - Function.prototype.bind = (function () { - var slice = Array.prototype.slice; - return function (thisArg) { - var target = this, boundArgs = slice.call(arguments, 1); - - if (typeof target != 'function') throw new TypeError(); - - function bound() { - var args = boundArgs.concat(slice.call(arguments)); - target.apply(this instanceof bound ? this : thisArg, args); - } - - bound.prototype = (function F(proto) { - proto && (F.prototype = proto); - if (!(this instanceof F)) return new F; - })(target.prototype); - - return bound; - }; - })(); -} + Function.prototype.bind = (function () { + + var slice = Array.prototype.slice; + + return function (thisArg) { + + var target = this, boundArgs = slice.call(arguments, 1); + + if (typeof target != 'function') + { + throw new TypeError(); + } + + function bound() { + var args = boundArgs.concat(slice.call(arguments)); + target.apply(this instanceof bound ? this : thisArg, args); + } + + bound.prototype = (function F(proto) { + proto && (F.prototype = proto); + + if (!(this instanceof F)) + { + return new F; + } + })(target.prototype); + + return bound; + }; + })(); +}