From 09f57fa34603d0af97fdc6dbcc29539d47c1a049 Mon Sep 17 00:00:00 2001 From: Richard Davey Date: Wed, 29 May 2013 02:58:56 +0100 Subject: [PATCH] Preparing new tests --- Phaser/Phaser.csproj | 32 +- Phaser/State.ts | 14 +- Phaser/components/TilemapLayer.ts | 4 +- Phaser/components/sprite/Texture.ts | 47 +- Phaser/{geom => core}/Line.ts | 0 Phaser/gameobjects/DynamicTexture.ts | 14 +- Phaser/gameobjects/GameObjectFactory.ts | 12 +- Phaser/gameobjects/IGameObject.ts | 59 + Phaser/gameobjects/Sprite.ts | 116 +- Phaser/geom/Polygon.ts | 60 - Phaser/geom/Response.ts | 87 - Phaser/input/Input.ts | 9 +- Phaser/{geom => math}/IntersectResult.ts | 0 Phaser/math/LinkedList.ts | 5 +- Phaser/math/QuadTree.ts | 123 +- Phaser/phaser.js | 16 + Phaser/renderers/CanvasRenderer.ts | 95 +- Phaser/renderers/HeadlessRenderer.ts | 4 +- Phaser/renderers/IRenderer.ts | 4 - Phaser/tweens/Tween.ts | 12 + Phaser/utils/CircleUtils.ts | 6 +- Phaser/utils/SpriteUtils.ts | 59 - README.md | 2 +- SpecialFX/Camera/Border.ts | 8 +- SpecialFX/Camera/Fade.ts | 3 +- SpecialFX/Camera/Flash.ts | 3 +- SpecialFX/Camera/Mirror.ts | 14 +- SpecialFX/Camera/Scanlines.ts | 4 +- SpecialFX/Camera/Shadow.ts | 8 +- SpecialFX/Camera/Shake.ts | 5 +- SpecialFX/Camera/Template.ts | 4 +- Tests/Tests.csproj | 289 +- Tests/camera fx/fade.js | 46 - Tests/camera fx/fade.ts | 77 - Tests/camera fx/flash.js | 46 - Tests/camera fx/flash.ts | 77 - Tests/camera fx/mirror.js | 41 - Tests/camera fx/mirror.ts | 68 - Tests/camera fx/scanlines.js | 32 - Tests/camera fx/scanlines.ts | 57 - Tests/camera fx/shake.js | 50 - Tests/camera fx/shake.ts | 85 - Tests/cameras/camera alpha.js | 38 - Tests/cameras/camera alpha.ts | 63 - Tests/cameras/camera bounds.js | 33 - Tests/cameras/camera bounds.ts | 60 - Tests/cameras/camera position.js | 40 - Tests/cameras/camera position.ts | 66 - Tests/cameras/camera rotation.js | 34 - Tests/cameras/camera rotation.ts | 61 - Tests/cameras/camera scale.js | 45 - Tests/cameras/camera scale.ts | 71 - Tests/cameras/camera shadow.js | 47 - Tests/cameras/camera shadow.ts | 73 - Tests/cameras/camera texture.js | 46 - Tests/cameras/camera texture.ts | 72 - Tests/cameras/focus on.js | 36 - Tests/cameras/focus on.ts | 62 - Tests/cameras/follow deadzone.js | 36 - Tests/cameras/follow deadzone.ts | 61 - Tests/cameras/follow sprite.js | 34 - Tests/cameras/follow sprite.ts | 62 - Tests/cameras/follow topdown.js | 34 - Tests/cameras/follow topdown.ts | 59 - Tests/cameras/multicam1.js | 44 - Tests/cameras/multicam1.ts | 70 - Tests/cameras/scroll factor.js | 37 - Tests/cameras/scroll factor.ts | 63 - Tests/collision/collide sprites.js | 35 - Tests/collision/collide sprites.ts | 61 - Tests/collision/falling balls.js | 45 - Tests/collision/falling balls.ts | 72 - Tests/collision/mask animation 1.js | 31 - Tests/collision/mask animation 1.ts | 50 - Tests/collision/mask test 1.js | 38 - Tests/collision/mask test 1.ts | 64 - Tests/collision/mask test 2.js | 35 - Tests/collision/mask test 2.ts | 62 - Tests/geometry/circle.js | 19 - Tests/geometry/circle.ts | 30 - Tests/geometry/line.js | 27 - Tests/geometry/line.ts | 40 - Tests/geometry/multi rotate.js | 31 - Tests/geometry/multi rotate.ts | 49 - Tests/geometry/point.js | 21 - Tests/geometry/point.ts | 33 - Tests/geometry/rect vs rect.js | 22 - Tests/geometry/rect vs rect.ts | 41 - Tests/geometry/rectangle.js | 24 - Tests/geometry/rectangle.ts | 43 - Tests/geometry/rope bridge.js | 34 - Tests/geometry/rope bridge.ts | 55 - Tests/geometry/rotate point 1.js | 21 - Tests/geometry/rotate point 1.ts | 36 - Tests/geometry/rotate point 2.js | 43 - Tests/geometry/rotate point 2.ts | 62 - Tests/geometry/rotate point 3.js | 71 - Tests/geometry/rotate point 3.ts | 95 - Tests/geometry/rotate point 4.js | 54 - Tests/geometry/rotate point 4.ts | 82 - Tests/geometry/verlet 1.js | 26 - Tests/geometry/verlet 1.ts | 33 - Tests/geometry/verlet sprites.js | 34 - Tests/geometry/verlet sprites.ts | 53 - Tests/groups/basic group.js | 39 - Tests/groups/basic group.ts | 66 - Tests/groups/display order.js | 32 - Tests/groups/display order.ts | 56 - Tests/input/mouse scale.js | 35 - Tests/input/mouse scale.ts | 62 - Tests/input/multitouch.js | 23 - Tests/input/multitouch.ts | 40 - Tests/input/single tap.js | 39 - Tests/input/single tap.ts | 64 - Tests/input/single touch.js | 19 - Tests/input/single touch.ts | 31 - Tests/mini games/formula 1.js | 36 - Tests/mini games/formula 1.ts | 59 - Tests/misc/boot screen.js | 5 + Tests/misc/boot screen.ts | 8 + Tests/misc/bootscreen.js | 4 - Tests/misc/bootscreen.ts | 7 - Tests/misc/multi game.js | 58 - Tests/misc/multi game.ts | 104 - Tests/misc/starfield.js | 46 - Tests/misc/starfield.ts | 61 - Tests/misc/time.js | 33 - Tests/misc/time.ts | 58 - Tests/mobile/bunny mobile.js | 58 - Tests/mobile/bunny mobile.ts | 94 - Tests/mobile/fullscreen.html | 62 - Tests/mobile/sprite test 1.js | 46 - Tests/mobile/sprite test 1.ts | 73 - Tests/particles/basic emitter.js | 11 - Tests/particles/basic emitter.ts | 18 - Tests/particles/graphic emitter.js | 14 - Tests/particles/graphic emitter.ts | 25 - Tests/particles/mousetrail.js | 23 - Tests/particles/mousetrail.ts | 38 - Tests/particles/multiple streams.js | 49 - Tests/particles/multiple streams.ts | 73 - Tests/particles/sprite emitter.js | 46 - Tests/particles/sprite emitter.ts | 52 - Tests/particles/when particles collide.js | 30 - Tests/particles/when particles collide.ts | 47 - Tests/phaser-fx.js | 152 +- Tests/phaser.js | 19388 +++++++------------- Tests/physics/temp1.js | 113 - Tests/physics/temp1.ts | 200 - Tests/physics/temp2.js | 1413 -- Tests/physics/temp2.ts | 1934 -- Tests/scrollzones/ballscroller.js | 25 - Tests/scrollzones/ballscroller.ts | 41 - Tests/scrollzones/blasteroids.js | 95 - Tests/scrollzones/blasteroids.ts | 151 - Tests/scrollzones/parallax.js | 31 - Tests/scrollzones/parallax.ts | 53 - Tests/scrollzones/region demo.js | 22 - Tests/scrollzones/region demo.ts | 37 - Tests/scrollzones/scroll window.js | 18 - Tests/scrollzones/scroll window.ts | 31 - Tests/scrollzones/simple scrollzone.js | 16 - Tests/scrollzones/simple scrollzone.ts | 28 - Tests/sprites/align.js | 27 - Tests/sprites/align.ts | 50 - Tests/sprites/animate by framename.js | 34 - Tests/sprites/animate by framename.ts | 40 - Tests/sprites/animation 1.js | 32 - Tests/sprites/animation 1.ts | 55 - Tests/sprites/create sprite 1.js | 14 + Tests/sprites/create sprite 1.ts | 23 + Tests/sprites/dynamic texture 1.js | 59 - Tests/sprites/dynamic texture 1.ts | 82 - Tests/sprites/dynamic texture 2.js | 78 - Tests/sprites/dynamic texture 2.ts | 109 - Tests/sprites/flipped.js | 42 - Tests/sprites/flipped.ts | 64 - Tests/sprites/mark of the bunny.js | 56 - Tests/sprites/mark of the bunny.ts | 89 - Tests/sprites/rotation.js | 22 - Tests/sprites/rotation.ts | 39 - Tests/sprites/scale origin 1.js | 58 + Tests/sprites/scale origin 1.ts | 75 + Tests/sprites/scale sprite 1.js | 20 + Tests/sprites/scale sprite 1.ts | 33 + Tests/sprites/scale sprite 2.js | 20 + Tests/sprites/scale sprite 2.ts | 33 + Tests/sprites/scale sprite 3.js | 17 + Tests/sprites/scale sprite 3.ts | 29 + Tests/sprites/scale sprite 4.js | 39 + Tests/sprites/scale sprite 4.ts | 53 + Tests/sprites/scale sprite 5.js | 52 + Tests/sprites/scale sprite 5.ts | 71 + Tests/sprites/starling texture atlas 1.js | 32 - Tests/sprites/starling texture atlas 1.ts | 52 - Tests/sprites/texture atlas 2.js | 25 - Tests/sprites/texture atlas 2.ts | 43 - Tests/sprites/texture atlas 3.js | 23 - Tests/sprites/texture atlas 3.ts | 40 - Tests/sprites/texture atlas 4.js | 32 - Tests/sprites/texture atlas 4.ts | 50 - Tests/sprites/texture atlas.js | 271 - Tests/sprites/texture atlas.ts | 143 - Tests/sprites/velocity.js | 33 - Tests/sprites/velocity.ts | 58 - Tests/tilemap/basic tilemap.js | 50 - Tests/tilemap/basic tilemap.ts | 82 - Tests/tilemap/collide with tile.js | 66 - Tests/tilemap/collide with tile.ts | 96 - Tests/tilemap/collision.js | 63 - Tests/tilemap/collision.ts | 88 - Tests/tilemap/fill tiles.js | 54 - Tests/tilemap/fill tiles.ts | 86 - Tests/tilemap/get tile.js | 49 - Tests/tilemap/get tile.ts | 78 - Tests/tilemap/map draw.js | 39 - Tests/tilemap/map draw.ts | 58 - Tests/tilemap/put tile.js | 52 - Tests/tilemap/put tile.ts | 83 - Tests/tilemap/random tiles.js | 60 - Tests/tilemap/random tiles.ts | 85 - Tests/tilemap/replace tiles.js | 53 - Tests/tilemap/replace tiles.ts | 85 - Tests/tilemap/small map.js | 42 - Tests/tilemap/small map.ts | 66 - Tests/tilemap/sprite draw tiles.js | 36 - Tests/tilemap/sprite draw tiles.ts | 59 - Tests/tilemap/swap tiles.js | 53 - Tests/tilemap/swap tiles.ts | 85 - Tests/tweens/bounce.js | 22 - Tests/tweens/bounce.ts | 36 - Tests/tweens/elastic.js | 15 - Tests/tweens/elastic.ts | 24 - build/phaser-fx.d.ts | 78 +- build/phaser-fx.js | 44 +- build/phaser.d.ts | 10189 ++++------ build/phaser.js | 3531 ++-- 237 files changed, 13385 insertions(+), 34447 deletions(-) rename Phaser/{geom => core}/Line.ts (100%) create mode 100644 Phaser/gameobjects/IGameObject.ts delete mode 100644 Phaser/geom/Polygon.ts delete mode 100644 Phaser/geom/Response.ts rename Phaser/{geom => math}/IntersectResult.ts (100%) delete mode 100644 Tests/camera fx/fade.js delete mode 100644 Tests/camera fx/fade.ts delete mode 100644 Tests/camera fx/flash.js delete mode 100644 Tests/camera fx/flash.ts delete mode 100644 Tests/camera fx/mirror.js delete mode 100644 Tests/camera fx/mirror.ts delete mode 100644 Tests/camera fx/scanlines.js delete mode 100644 Tests/camera fx/scanlines.ts delete mode 100644 Tests/camera fx/shake.js delete mode 100644 Tests/camera fx/shake.ts delete mode 100644 Tests/cameras/camera alpha.js delete mode 100644 Tests/cameras/camera alpha.ts delete mode 100644 Tests/cameras/camera bounds.js delete mode 100644 Tests/cameras/camera bounds.ts delete mode 100644 Tests/cameras/camera position.js delete mode 100644 Tests/cameras/camera position.ts delete mode 100644 Tests/cameras/camera rotation.js delete mode 100644 Tests/cameras/camera rotation.ts delete mode 100644 Tests/cameras/camera scale.js delete mode 100644 Tests/cameras/camera scale.ts delete mode 100644 Tests/cameras/camera shadow.js delete mode 100644 Tests/cameras/camera shadow.ts delete mode 100644 Tests/cameras/camera texture.js delete mode 100644 Tests/cameras/camera texture.ts delete mode 100644 Tests/cameras/focus on.js delete mode 100644 Tests/cameras/focus on.ts delete mode 100644 Tests/cameras/follow deadzone.js delete mode 100644 Tests/cameras/follow deadzone.ts delete mode 100644 Tests/cameras/follow sprite.js delete mode 100644 Tests/cameras/follow sprite.ts delete mode 100644 Tests/cameras/follow topdown.js delete mode 100644 Tests/cameras/follow topdown.ts delete mode 100644 Tests/cameras/multicam1.js delete mode 100644 Tests/cameras/multicam1.ts delete mode 100644 Tests/cameras/scroll factor.js delete mode 100644 Tests/cameras/scroll factor.ts delete mode 100644 Tests/collision/collide sprites.js delete mode 100644 Tests/collision/collide sprites.ts delete mode 100644 Tests/collision/falling balls.js delete mode 100644 Tests/collision/falling balls.ts delete mode 100644 Tests/collision/mask animation 1.js delete mode 100644 Tests/collision/mask animation 1.ts delete mode 100644 Tests/collision/mask test 1.js delete mode 100644 Tests/collision/mask test 1.ts delete mode 100644 Tests/collision/mask test 2.js delete mode 100644 Tests/collision/mask test 2.ts delete mode 100644 Tests/geometry/circle.js delete mode 100644 Tests/geometry/circle.ts delete mode 100644 Tests/geometry/line.js delete mode 100644 Tests/geometry/line.ts delete mode 100644 Tests/geometry/multi rotate.js delete mode 100644 Tests/geometry/multi rotate.ts delete mode 100644 Tests/geometry/point.js delete mode 100644 Tests/geometry/point.ts delete mode 100644 Tests/geometry/rect vs rect.js delete mode 100644 Tests/geometry/rect vs rect.ts delete mode 100644 Tests/geometry/rectangle.js delete mode 100644 Tests/geometry/rectangle.ts delete mode 100644 Tests/geometry/rope bridge.js delete mode 100644 Tests/geometry/rope bridge.ts delete mode 100644 Tests/geometry/rotate point 1.js delete mode 100644 Tests/geometry/rotate point 1.ts delete mode 100644 Tests/geometry/rotate point 2.js delete mode 100644 Tests/geometry/rotate point 2.ts delete mode 100644 Tests/geometry/rotate point 3.js delete mode 100644 Tests/geometry/rotate point 3.ts delete mode 100644 Tests/geometry/rotate point 4.js delete mode 100644 Tests/geometry/rotate point 4.ts delete mode 100644 Tests/geometry/verlet 1.js delete mode 100644 Tests/geometry/verlet 1.ts delete mode 100644 Tests/geometry/verlet sprites.js delete mode 100644 Tests/geometry/verlet sprites.ts delete mode 100644 Tests/groups/basic group.js delete mode 100644 Tests/groups/basic group.ts delete mode 100644 Tests/groups/display order.js delete mode 100644 Tests/groups/display order.ts delete mode 100644 Tests/input/mouse scale.js delete mode 100644 Tests/input/mouse scale.ts delete mode 100644 Tests/input/multitouch.js delete mode 100644 Tests/input/multitouch.ts delete mode 100644 Tests/input/single tap.js delete mode 100644 Tests/input/single tap.ts delete mode 100644 Tests/input/single touch.js delete mode 100644 Tests/input/single touch.ts delete mode 100644 Tests/mini games/formula 1.js delete mode 100644 Tests/mini games/formula 1.ts create mode 100644 Tests/misc/boot screen.js create mode 100644 Tests/misc/boot screen.ts delete mode 100644 Tests/misc/bootscreen.js delete mode 100644 Tests/misc/bootscreen.ts delete mode 100644 Tests/misc/multi game.js delete mode 100644 Tests/misc/multi game.ts delete mode 100644 Tests/misc/starfield.js delete mode 100644 Tests/misc/starfield.ts delete mode 100644 Tests/misc/time.js delete mode 100644 Tests/misc/time.ts delete mode 100644 Tests/mobile/bunny mobile.js delete mode 100644 Tests/mobile/bunny mobile.ts delete mode 100644 Tests/mobile/fullscreen.html delete mode 100644 Tests/mobile/sprite test 1.js delete mode 100644 Tests/mobile/sprite test 1.ts delete mode 100644 Tests/particles/basic emitter.js delete mode 100644 Tests/particles/basic emitter.ts delete mode 100644 Tests/particles/graphic emitter.js delete mode 100644 Tests/particles/graphic emitter.ts delete mode 100644 Tests/particles/mousetrail.js delete mode 100644 Tests/particles/mousetrail.ts delete mode 100644 Tests/particles/multiple streams.js delete mode 100644 Tests/particles/multiple streams.ts delete mode 100644 Tests/particles/sprite emitter.js delete mode 100644 Tests/particles/sprite emitter.ts delete mode 100644 Tests/particles/when particles collide.js delete mode 100644 Tests/particles/when particles collide.ts delete mode 100644 Tests/physics/temp1.js delete mode 100644 Tests/physics/temp1.ts delete mode 100644 Tests/physics/temp2.js delete mode 100644 Tests/physics/temp2.ts delete mode 100644 Tests/scrollzones/ballscroller.js delete mode 100644 Tests/scrollzones/ballscroller.ts delete mode 100644 Tests/scrollzones/blasteroids.js delete mode 100644 Tests/scrollzones/blasteroids.ts delete mode 100644 Tests/scrollzones/parallax.js delete mode 100644 Tests/scrollzones/parallax.ts delete mode 100644 Tests/scrollzones/region demo.js delete mode 100644 Tests/scrollzones/region demo.ts delete mode 100644 Tests/scrollzones/scroll window.js delete mode 100644 Tests/scrollzones/scroll window.ts delete mode 100644 Tests/scrollzones/simple scrollzone.js delete mode 100644 Tests/scrollzones/simple scrollzone.ts delete mode 100644 Tests/sprites/align.js delete mode 100644 Tests/sprites/align.ts delete mode 100644 Tests/sprites/animate by framename.js delete mode 100644 Tests/sprites/animate by framename.ts delete mode 100644 Tests/sprites/animation 1.js delete mode 100644 Tests/sprites/animation 1.ts create mode 100644 Tests/sprites/create sprite 1.js create mode 100644 Tests/sprites/create sprite 1.ts delete mode 100644 Tests/sprites/dynamic texture 1.js delete mode 100644 Tests/sprites/dynamic texture 1.ts delete mode 100644 Tests/sprites/dynamic texture 2.js delete mode 100644 Tests/sprites/dynamic texture 2.ts delete mode 100644 Tests/sprites/flipped.js delete mode 100644 Tests/sprites/flipped.ts delete mode 100644 Tests/sprites/mark of the bunny.js delete mode 100644 Tests/sprites/mark of the bunny.ts delete mode 100644 Tests/sprites/rotation.js delete mode 100644 Tests/sprites/rotation.ts create mode 100644 Tests/sprites/scale origin 1.js create mode 100644 Tests/sprites/scale origin 1.ts create mode 100644 Tests/sprites/scale sprite 1.js create mode 100644 Tests/sprites/scale sprite 1.ts create mode 100644 Tests/sprites/scale sprite 2.js create mode 100644 Tests/sprites/scale sprite 2.ts create mode 100644 Tests/sprites/scale sprite 3.js create mode 100644 Tests/sprites/scale sprite 3.ts create mode 100644 Tests/sprites/scale sprite 4.js create mode 100644 Tests/sprites/scale sprite 4.ts create mode 100644 Tests/sprites/scale sprite 5.js create mode 100644 Tests/sprites/scale sprite 5.ts delete mode 100644 Tests/sprites/starling texture atlas 1.js delete mode 100644 Tests/sprites/starling texture atlas 1.ts delete mode 100644 Tests/sprites/texture atlas 2.js delete mode 100644 Tests/sprites/texture atlas 2.ts delete mode 100644 Tests/sprites/texture atlas 3.js delete mode 100644 Tests/sprites/texture atlas 3.ts delete mode 100644 Tests/sprites/texture atlas 4.js delete mode 100644 Tests/sprites/texture atlas 4.ts delete mode 100644 Tests/sprites/texture atlas.js delete mode 100644 Tests/sprites/texture atlas.ts delete mode 100644 Tests/sprites/velocity.js delete mode 100644 Tests/sprites/velocity.ts delete mode 100644 Tests/tilemap/basic tilemap.js delete mode 100644 Tests/tilemap/basic tilemap.ts delete mode 100644 Tests/tilemap/collide with tile.js delete mode 100644 Tests/tilemap/collide with tile.ts delete mode 100644 Tests/tilemap/collision.js delete mode 100644 Tests/tilemap/collision.ts delete mode 100644 Tests/tilemap/fill tiles.js delete mode 100644 Tests/tilemap/fill tiles.ts delete mode 100644 Tests/tilemap/get tile.js delete mode 100644 Tests/tilemap/get tile.ts delete mode 100644 Tests/tilemap/map draw.js delete mode 100644 Tests/tilemap/map draw.ts delete mode 100644 Tests/tilemap/put tile.js delete mode 100644 Tests/tilemap/put tile.ts delete mode 100644 Tests/tilemap/random tiles.js delete mode 100644 Tests/tilemap/random tiles.ts delete mode 100644 Tests/tilemap/replace tiles.js delete mode 100644 Tests/tilemap/replace tiles.ts delete mode 100644 Tests/tilemap/small map.js delete mode 100644 Tests/tilemap/small map.ts delete mode 100644 Tests/tilemap/sprite draw tiles.js delete mode 100644 Tests/tilemap/sprite draw tiles.ts delete mode 100644 Tests/tilemap/swap tiles.js delete mode 100644 Tests/tilemap/swap tiles.ts delete mode 100644 Tests/tweens/bounce.js delete mode 100644 Tests/tweens/bounce.ts delete mode 100644 Tests/tweens/elastic.js delete mode 100644 Tests/tweens/elastic.ts diff --git a/Phaser/Phaser.csproj b/Phaser/Phaser.csproj index 1b7e793e5..e9d4de59f 100644 --- a/Phaser/Phaser.csproj +++ b/Phaser/Phaser.csproj @@ -92,6 +92,10 @@ Game.ts + + + IGameObject.ts + GameMath.ts @@ -99,14 +103,9 @@ GameObjectFactory.ts - - - ScrollRegion.ts - Sprite.ts - @@ -131,24 +130,17 @@ PointUtils.ts - - Polygon.ts - - RectangleUtils.ts - - Response.ts - Circle.ts - + IntersectResult.ts - + Line.ts @@ -216,18 +208,10 @@ StageScaleMode.ts - - Tile.ts - - - - TilemapLayer.ts - Tween.ts - @@ -299,8 +283,8 @@ - - + + Group.ts diff --git a/Phaser/State.ts b/Phaser/State.ts index e7bee94b7..da7bc39cd 100644 --- a/Phaser/State.ts +++ b/Phaser/State.ts @@ -21,11 +21,11 @@ module Phaser { this.add = game.add; this.camera = game.camera; this.cache = game.cache; - this.collision = game.collision; + //this.collision = game.collision; this.input = game.input; this.loader = game.loader; this.math = game.math; - this.motion = game.motion; + //this.motion = game.motion; this.sound = game.sound; this.stage = game.stage; this.time = game.time; @@ -55,7 +55,7 @@ module Phaser { * Reference to the collision helper. * @type {Collision} */ - public collision: Collision; + //public collision: Collision; /** * Reference to the GameObject Factory. @@ -85,7 +85,7 @@ module Phaser { * Reference to the motion helper. * @type {Motion} */ - public motion: Motion; + //public motion: Motion; /** * Reference to the sound manager. @@ -161,9 +161,9 @@ module Phaser { * @param context The context in which the callbacks will be called * @returns {boolean} true if the objects overlap, otherwise false. */ - public collide(objectOrGroup1 = null, objectOrGroup2 = null, notifyCallback = null, context? = this.game.callbackContext): bool { - return this.collision.overlap(objectOrGroup1, objectOrGroup2, notifyCallback, Collision.separate, context); - } + //public collide(objectOrGroup1 = null, objectOrGroup2 = null, notifyCallback = null, context? = this.game.callbackContext): bool { + // return this.collision.overlap(objectOrGroup1, objectOrGroup2, notifyCallback, Collision.separate, context); + //} } diff --git a/Phaser/components/TilemapLayer.ts b/Phaser/components/TilemapLayer.ts index 71c6fefe2..17e954adc 100644 --- a/Phaser/components/TilemapLayer.ts +++ b/Phaser/components/TilemapLayer.ts @@ -1,4 +1,6 @@ /// +/// +/// /** * Phaser - TilemapLayer @@ -354,7 +356,7 @@ module Phaser { * @param object {GameObject} Tiles you want to get that overlaps this. * @return {array} Array with tiles informations. (Each contains x, y and the tile.) */ - public getTileOverlaps(object: GameObject) { + public getTileOverlaps(object: IGameObject) { // If the object is outside of the world coordinates then abort the check (tilemap has to exist within world bounds) if (object.collisionMask.x < 0 || object.collisionMask.x > this.widthInPixels || object.collisionMask.y < 0 || object.collisionMask.bottom > this.heightInPixels) diff --git a/Phaser/components/sprite/Texture.ts b/Phaser/components/sprite/Texture.ts index 02e599627..dfb838fdf 100644 --- a/Phaser/components/sprite/Texture.ts +++ b/Phaser/components/sprite/Texture.ts @@ -14,6 +14,7 @@ module Phaser.Components { constructor(parent: Sprite, key?: string = '', canvas?: HTMLCanvasElement = null, context?: CanvasRenderingContext2D = null) { + this._game = parent.game; this._sprite = parent; this.canvas = canvas; @@ -30,6 +31,11 @@ module Phaser.Components { } + /** + * + */ + private _game: Game; + /** * Reference to the Image stored in the Game.Cache that is used as the texture for the Sprite. */ @@ -121,8 +127,32 @@ module Phaser.Components { * @param clearAnimations {boolean} If this Sprite has a set of animation data already loaded you can choose to keep or clear it with this boolean * @return {Sprite} Sprite instance itself. */ - public loadImage(key: string, clearAnimations: bool = true): Sprite { - return Phaser.SpriteUtils.loadTexture(this._sprite, key, clearAnimations); + public loadImage(key: string, clearAnimations: bool = true) { + + //if (clearAnimations && sprite.animations.frameData !== null) + //{ + // sprite.animations.destroy(); + //} + + if (this._game.cache.getImage(key) !== null) + { + this.setTo(this._game.cache.getImage(key), null); + + if (this._game.cache.isSpriteSheet(key)) + { + //sprite.animations.loadFrameData(sprite._game.cache.getFrameData(key)); + //sprite.collisionMask.width = sprite.animations.currentFrame.width; + //sprite.collisionMask.height = sprite.animations.currentFrame.height; + } + else + { + this._sprite.frameBounds.width = this.width; + this._sprite.frameBounds.height = this.height; + //sprite.collisionMask.width = sprite._texture.width; + //sprite.collisionMask.height = sprite._texture.height; + } + } + } /** @@ -130,8 +160,17 @@ module Phaser.Components { * @param texture {DynamicTexture} The texture object to be used by this sprite. * @return {Sprite} Sprite instance itself. */ - public loadDynamicTexture(texture: DynamicTexture): Sprite { - return Phaser.SpriteUtils.loadDynamicTexture(this._sprite, texture); + public loadDynamicTexture(texture: DynamicTexture) { + + //if (sprite.animations.frameData !== null) + //{ + // sprite.animations.destroy(); + //} + + this.setTo(null, texture); + this._sprite.frameBounds.width = this.width; + this._sprite.frameBounds.height = this.height; + } /** diff --git a/Phaser/geom/Line.ts b/Phaser/core/Line.ts similarity index 100% rename from Phaser/geom/Line.ts rename to Phaser/core/Line.ts diff --git a/Phaser/gameobjects/DynamicTexture.ts b/Phaser/gameobjects/DynamicTexture.ts index e5d5f11d3..b06eb423a 100644 --- a/Phaser/gameobjects/DynamicTexture.ts +++ b/Phaser/gameobjects/DynamicTexture.ts @@ -1,4 +1,6 @@ /// +/// +/// /** * Phaser - DynamicTexture @@ -234,7 +236,7 @@ module Phaser { public copyPixels(sourceTexture: DynamicTexture, sourceRect: Rectangle, destPoint: Point) { // Swap for drawImage if the sourceRect is the same size as the sourceTexture to avoid a costly getImageData call - if (sourceRect.equals(this.bounds) == true) + if (Phaser.RectangleUtils.equals(sourceRect, this.bounds) == true) { this.context.drawImage(sourceTexture.canvas, destPoint.x, destPoint.y); } @@ -246,15 +248,15 @@ module Phaser { } /** - * Given an array of GameObjects it will update each of them so that their canvas/contexts reference this DynamicTexture + * Given an array of Sprites it will update each of them so that their canvas/contexts reference this DynamicTexture * @param objects {Array} An array of GameObjects, or objects that inherit from it such as Sprites */ - public assignCanvasToGameObjects(objects: GameObject[]) { + public assignCanvasToGameObjects(objects: IGameObject[]) { for (var i = 0; i < objects.length; i++) { - objects[i].canvas = this.canvas; - objects[i].context = this.context; + objects[i].texture.canvas = this.canvas; + objects[i].texture.context = this.context; } } @@ -275,9 +277,7 @@ module Phaser { * @param y {number} The Y coordinate to render on the stage to (given in screen coordinates, not world) */ public render(x?: number = 0, y?: number = 0) { - this.game.stage.context.drawImage(this.canvas, x, y); - } public get width(): number { diff --git a/Phaser/gameobjects/GameObjectFactory.ts b/Phaser/gameobjects/GameObjectFactory.ts index 3c9ffefec..85197333c 100644 --- a/Phaser/gameobjects/GameObjectFactory.ts +++ b/Phaser/gameobjects/GameObjectFactory.ts @@ -135,9 +135,9 @@ module Phaser { * @param [tileHeight] {number} height of each tile. * @return {Tilemap} The newly created tilemap object. */ - public tilemap(key: string, mapData: string, format: number, resizeWorld: bool = true, tileWidth?: number = 0, tileHeight?: number = 0): Tilemap { - return this._world.group.add(new Tilemap(this._game, key, mapData, format, resizeWorld, tileWidth, tileHeight)); - } + //public tilemap(key: string, mapData: string, format: number, resizeWorld: bool = true, tileWidth?: number = 0, tileHeight?: number = 0): Tilemap { + // return this._world.group.add(new Tilemap(this._game, key, mapData, format, resizeWorld, tileWidth, tileHeight)); + //} /** * Create a tween object for a specific object. @@ -200,9 +200,9 @@ module Phaser { * @param tilemap The Tilemap to add to the Game World * @return {Phaser.Tilemap} The Tilemap object */ - public existingTilemap(tilemap: Tilemap): Tilemap { - return this._world.group.add(tilemap); - } + //public existingTilemap(tilemap: Tilemap): Tilemap { + // return this._world.group.add(tilemap); + //} /** * Add an existing Tween to the current world. diff --git a/Phaser/gameobjects/IGameObject.ts b/Phaser/gameobjects/IGameObject.ts new file mode 100644 index 000000000..98012456b --- /dev/null +++ b/Phaser/gameobjects/IGameObject.ts @@ -0,0 +1,59 @@ +/// + +module Phaser { + + export interface IGameObject { + + /** + * Reference to the main game object + */ + game: Game; + + /** + * The type of game object. + */ + type: number; + + /** + * Reference to the Renderer.renderSprite method. Can be overriden by custom classes. + */ + render; + + /** + * Controls if both update and render are called by the core game loop. + */ + exists: bool; + + /** + * Controls if update() is automatically called by the core game loop. + */ + active: bool; + + /** + * Controls if this Sprite is rendered or skipped during the core game loop. + */ + visible: bool; + + /** + * The position of the Sprite in world and screen coordinates. + */ + position: Phaser.Components.Position; + + /** + * The texture used to render the Sprite. + */ + texture: Phaser.Components.Texture; + + /** + * Scale of the Sprite. A scale of 1.0 is the original size. 0.5 half size. 2.0 double sized. + */ + scale: Phaser.Vec2; + + /** + * The influence of camera movement upon the Sprite. + */ + scrollFactor: Phaser.Vec2; + + } + +} \ No newline at end of file diff --git a/Phaser/gameobjects/Sprite.ts b/Phaser/gameobjects/Sprite.ts index c7806818f..cd3270536 100644 --- a/Phaser/gameobjects/Sprite.ts +++ b/Phaser/gameobjects/Sprite.ts @@ -11,7 +11,7 @@ module Phaser { - export class Sprite { + export class Sprite implements IGameObject { /** * Create a new Sprite. @@ -34,12 +34,18 @@ module Phaser { this.visible = true; this.alive = true; + this.frameBounds = new Rectangle(x, y, width, height); + this.origin = new Phaser.Vec2(0, 0); this.scrollFactor = new Phaser.Vec2(1, 1); this.scale = new Phaser.Vec2(1, 1); this.position = new Phaser.Components.Position(this, x, y); this.texture = new Phaser.Components.Texture(this, key, game.stage.canvas, game.stage.context); + this.width = this.frameBounds.width; + this.height = this.frameBounds.height; + this.rotation = this.position.rotation; + } /** @@ -77,6 +83,10 @@ module Phaser { */ public alive: bool; + // Getters only, don't over-write these values + public width: number; + public height: number; + /** * The position of the Sprite in world and screen coordinates. */ @@ -94,9 +104,102 @@ module Phaser { */ public frameBounds: Phaser.Rectangle; + /** + * Scale of the Sprite. A scale of 1.0 is the original size. 0.5 half size. 2.0 double sized. + */ public scale: Phaser.Vec2; + + /** + * The influence of camera movement upon the Sprite. + */ public scrollFactor: Phaser.Vec2; + /** + * The Sprite origin is the point around which scale and rotation transforms take place. + */ + public origin: Phaser.Vec2; + + /** + * Pre-update is called right before update() on each object in the game loop. + */ + public preUpdate() { + + //this.last.x = this.frameBounds.x; + //this.last.y = this.frameBounds.y; + + //this.collisionMask.preUpdate(); + + } + + /** + * Override this function to update your class's position and appearance. + */ + public update() { + } + + /** + * Automatically called after update() by the game loop. + */ + public postUpdate() { + + /* + this.animations.update(); + + if (this.moves) + { + this.updateMotion(); + } + + if (this.worldBounds != null) + { + if (this.outOfBoundsAction == GameObject.OUT_OF_BOUNDS_KILL) + { + if (this.x < this.worldBounds.x || this.x > this.worldBounds.right || this.y < this.worldBounds.y || this.y > this.worldBounds.bottom) + { + this.kill(); + } + } + else + { + if (this.x < this.worldBounds.x) + { + this.x = this.worldBounds.x; + } + else if (this.x > this.worldBounds.right) + { + this.x = this.worldBounds.right; + } + + if (this.y < this.worldBounds.y) + { + this.y = this.worldBounds.y; + } + else if (this.y > this.worldBounds.bottom) + { + this.y = this.worldBounds.bottom; + } + } + } + + this.collisionMask.update(); + + if (this.inputEnabled) + { + this.updateInput(); + } + + this.wasTouching = this.touching; + this.touching = Collision.NONE; + */ + + } + + /** + * Clean up memory. + */ + public destroy() { + } + /** * x value of the object. */ @@ -130,6 +233,17 @@ module Phaser { this.position.z = value; } + /** + * rotation value of the object. + */ + public get rotation(): number { + return this.position.rotation; + } + + public set rotation(value: number) { + this.position.rotation = value; + } + } } \ No newline at end of file diff --git a/Phaser/geom/Polygon.ts b/Phaser/geom/Polygon.ts deleted file mode 100644 index b262fc7d8..000000000 --- a/Phaser/geom/Polygon.ts +++ /dev/null @@ -1,60 +0,0 @@ -/// - -/** -* Phaser - Polygon -* -*/ - -module Phaser { - - export class Polygon { - - /** - * A *convex* clockwise polygon - * @class Polygon - * @constructor - * @param {Vec2} pos A vector representing the origin of the polygon (all other points are relative to this one) - * @param {Array.} points An Array of vectors representing the points in the polygon, in clockwise order. - **/ - constructor(pos?: Vec2 = new Vec2, points?: Vec2[] = [], parent?:any = null) { - - this.pos = pos; - this.points = points; - this.parent = parent; - this.recalc(); - - } - - public parent: any; - public pos: Vec2; - public points: Vec2[]; - public edges: Vec2[]; - public normals: Vec2[]; - - /** - * Recalculate the edges and normals of the polygon. This - * MUST be called if the points array is modified at all and - * the edges or normals are to be accessed. - */ - public recalc() { - - var points = this.points; - var len = points.length; - - this.edges = []; - this.normals = []; - - for (var i = 0; i < len; i++) - { - var p1 = points[i]; - var p2 = i < len - 1 ? points[i + 1] : points[0]; - var e = new Vec2().copyFrom(p2).sub(p1); - var n = new Vec2().copyFrom(e).perp().normalize(); - this.edges.push(e); - this.normals.push(n); - } - } - - } - -} \ No newline at end of file diff --git a/Phaser/geom/Response.ts b/Phaser/geom/Response.ts deleted file mode 100644 index fa5fc3238..000000000 --- a/Phaser/geom/Response.ts +++ /dev/null @@ -1,87 +0,0 @@ -/// -/// - -/** -* Phaser - Response -* -*/ - -module Phaser { - - export class Response { - - /** - * An object representing the result of an intersection. Contain information about: - * - The two objects participating in the intersection - * - The vector representing the minimum change necessary to extract the first object - * from the second one. - * - Whether the first object is entirely inside the second, or vice versa. - * - * @constructor - */ - constructor() { - - this.a = null; - this.b = null; - this.overlapN = new Vec2; - this.overlapV = new Vec2; - - this.clear(); - - } - - /** - * The first object in the collision - */ - public a; - - /** - * The second object in the collision - */ - public b; - - /** - * The shortest colliding axis (unit-vector) - */ - public overlapN: Vec2; - - /** - * The overlap vector (i.e. overlapN.scale(overlap, overlap)). - * If this vector is subtracted from the position of `a`, `a` and `b` will no longer be colliding. - */ - public overlapV: Vec2; - - /** - * Whether the first object is completely inside the second. - */ - public aInB: bool; - - /** - * Whether the second object is completely inside the first. - */ - public bInA: bool; - - /** - * Magnitude of the overlap on the shortest colliding axis - */ - public overlap: number; - - /** - * Set some values of the response back to their defaults. Call this between tests if - * you are going to reuse a single Response object for multiple intersection tests (recommented) - * - * @return {Response} This for chaining - */ - public clear() { - - this.aInB = true; - this.bInA = true; - this.overlap = Number.MAX_VALUE; - - return this; - - } - - } - -} \ No newline at end of file diff --git a/Phaser/input/Input.ts b/Phaser/input/Input.ts index f8087e0d3..557b7e6c3 100644 --- a/Phaser/input/Input.ts +++ b/Phaser/input/Input.ts @@ -1,10 +1,13 @@ /// -/// +/// +/// +/// /// /// /// -/// -/// +/// +/// +/// /** * Phaser - Input diff --git a/Phaser/geom/IntersectResult.ts b/Phaser/math/IntersectResult.ts similarity index 100% rename from Phaser/geom/IntersectResult.ts rename to Phaser/math/IntersectResult.ts diff --git a/Phaser/math/LinkedList.ts b/Phaser/math/LinkedList.ts index 61ac12d49..085fee2f8 100644 --- a/Phaser/math/LinkedList.ts +++ b/Phaser/math/LinkedList.ts @@ -1,4 +1,5 @@ /// +/// /** * Phaser - LinkedList @@ -21,9 +22,9 @@ module Phaser { } /** - * Stores a reference to an Basic. + * Stores a reference to an IGameObject. */ - public object: Basic; + public object: IGameObject; /** * Stores a reference to the next link in the list. diff --git a/Phaser/math/QuadTree.ts b/Phaser/math/QuadTree.ts index f41fb7fc2..33253e36b 100644 --- a/Phaser/math/QuadTree.ts +++ b/Phaser/math/QuadTree.ts @@ -1,5 +1,6 @@ /// /// +/// /** * Phaser - QuadTree @@ -32,42 +33,39 @@ module Phaser { //Copy the parent's children (if there are any) if (parent != null) { - var iterator: LinkedList; - var ot: LinkedList; - if (parent._headA.object != null) { - iterator = parent._headA; + this._iterator = parent._headA; - while (iterator != null) + while (this._iterator != null) { if (this._tailA.object != null) { - ot = this._tailA; + this._ot = this._tailA; this._tailA = new LinkedList(); - ot.next = this._tailA; + this._ot.next = this._tailA; } - this._tailA.object = iterator.object; - iterator = iterator.next; + this._tailA.object = this._iterator.object; + this._iterator = this._iterator.next; } } if (parent._headB.object != null) { - iterator = parent._headB; + this._iterator = parent._headB; - while (iterator != null) + while (this._iterator != null) { if (this._tailB.object != null) { - ot = this._tailB; + this._ot = this._tailB; this._tailB = new LinkedList(); - ot.next = this._tailB; + this._ot.next = this._tailB; } - this._tailB.object = iterator.object; - iterator = iterator.next; + this._tailB.object = this._iterator.object; + this._iterator = this._iterator.next; } } } @@ -94,6 +92,16 @@ module Phaser { } + // Reused temporary vars to help avoid gc spikes + private _iterator: LinkedList; + private _ot: LinkedList; + private _i; + private _basic; + private _members; + private _l: number; + private _overlapProcessed: bool; + private _checkObject; + /** * Flag for specifying that you want to add an object to the A list. */ @@ -287,13 +295,13 @@ module Phaser { /** * Load objects and/or groups into the quad tree, and register notify and processing callbacks. * - * @param {Basic} objectOrGroup1 Any object that is or extends GameObject or Group. - * @param {Basic} objectOrGroup2 Any object that is or extends GameObject or Group. If null, the first parameter will be checked against itself. + * @param {} objectOrGroup1 Any object that is or extends IGameObject or Group. + * @param {} objectOrGroup2 Any object that is or extends IGameObject or Group. If null, the first parameter will be checked against itself. * @param {Function} notifyCallback A function with the form myFunction(Object1:GameObject,Object2:GameObject) that is called whenever two objects are found to overlap in world space, and either no processCallback is specified, or the processCallback returns true. * @param {Function} processCallback A function with the form myFunction(Object1:GameObject,Object2:GameObject):bool that is called whenever two objects are found to overlap in world space. The notifyCallback is only called if this function returns true. See GameObject.separate(). * @param context The context in which the callbacks will be called */ - public load(objectOrGroup1: Basic, objectOrGroup2: Basic = null, notifyCallback = null, processCallback = null, context = null) { + public load(objectOrGroup1, objectOrGroup2 = null, notifyCallback = null, processCallback = null, context = null) { this.add(objectOrGroup1, QuadTree.A_LIST); @@ -318,33 +326,32 @@ module Phaser { * This function will recursively add all group members, but * not the groups themselves. * - * @param {Basic} objectOrGroup GameObjects are just added, Groups are recursed and their applicable members added accordingly. + * @param {} objectOrGroup GameObjects are just added, Groups are recursed and their applicable members added accordingly. * @param {Number} list A uint flag indicating the list to which you want to add the objects. Options are QuadTree.A_LIST and QuadTree.B_LIST. */ - public add(objectOrGroup: Basic, list: number) { + public add(objectOrGroup, list: number) { QuadTree._list = list; if (objectOrGroup.isGroup == true) { - var i: number = 0; - var basic: Basic; - var members = objectOrGroup['members']; - var l: number = objectOrGroup['length']; + this._i = 0; + this._members = objectOrGroup['members']; + this._l = objectOrGroup['length']; - while (i < l) + while (this._i < this._l) { - basic = members[i++]; + this._basic = this._members[this._i++]; - if ((basic != null) && basic.exists) + if (this._basic != null && this._basic.exists) { - if (basic.isGroup) + if (this._basic.type == Phaser.Types.GROUP) { - this.add(basic, list); + this.add(this._basic, list); } else { - QuadTree._object = basic; + QuadTree._object = this._basic; if (QuadTree._object.exists && QuadTree._object.allowCollisions) { @@ -477,15 +484,13 @@ module Phaser { */ private addToList() { - var ot: LinkedList; - if (QuadTree._list == QuadTree.A_LIST) { if (this._tailA.object != null) { - ot = this._tailA; + this._ot = this._tailA; this._tailA = new LinkedList(); - ot.next = this._tailA; + this._ot.next = this._tailA; } this._tailA.object = QuadTree._object; @@ -494,9 +499,9 @@ module Phaser { { if (this._tailB.object != null) { - ot = this._tailB; + this._ot = this._tailB; this._tailB = new LinkedList(); - ot.next = this._tailB; + this._ot.next = this._tailB; } this._tailB.object = QuadTree._object; @@ -537,16 +542,15 @@ module Phaser { */ public execute(): bool { - var overlapProcessed: bool = false; - var iterator: LinkedList; + this._overlapProcessed = false; if (this._headA.object != null) { - iterator = this._headA; + this._iterator = this._headA; - while (iterator != null) + while (this._iterator != null) { - QuadTree._object = iterator.object; + QuadTree._object = this._iterator.object; if (QuadTree._useBothLists) { @@ -554,15 +558,15 @@ module Phaser { } else { - QuadTree._iterator = iterator.next; + QuadTree._iterator = this._iterator.next; } if (QuadTree._object.exists && (QuadTree._object.allowCollisions > 0) && (QuadTree._iterator != null) && (QuadTree._iterator.object != null) && QuadTree._iterator.object.exists && this.overlapNode()) { - overlapProcessed = true; + this._overlapProcessed = true; } - iterator = iterator.next; + this._iterator = this._iterator.next; } } @@ -570,25 +574,25 @@ module Phaser { //Advance through the tree by calling overlap on each child if ((this._northWestTree != null) && this._northWestTree.execute()) { - overlapProcessed = true; + this._overlapProcessed = true; } if ((this._northEastTree != null) && this._northEastTree.execute()) { - overlapProcessed = true; + this._overlapProcessed = true; } if ((this._southEastTree != null) && this._southEastTree.execute()) { - overlapProcessed = true; + this._overlapProcessed = true; } if ((this._southWestTree != null) && this._southWestTree.execute()) { - overlapProcessed = true; + this._overlapProcessed = true; } - return overlapProcessed; + return this._overlapProcessed; } @@ -600,8 +604,7 @@ module Phaser { private overlapNode(): bool { //Walk the list and check for overlaps - var overlapProcessed: bool = false; - var checkObject; + this._overlapProcessed = false; while (QuadTree._iterator != null) { @@ -610,31 +613,31 @@ module Phaser { break; } - checkObject = QuadTree._iterator.object; + this._checkObject = QuadTree._iterator.object; - if ((QuadTree._object === checkObject) || !checkObject.exists || (checkObject.allowCollisions <= 0)) + if ((QuadTree._object === this._checkObject) || !this._checkObject.exists || (this._checkObject.allowCollisions <= 0)) { QuadTree._iterator = QuadTree._iterator.next; continue; } - if (QuadTree._object.collisionMask.checkHullIntersection(checkObject.collisionMask)) + if (QuadTree._object.collisionMask.checkHullIntersection(this._checkObject.collisionMask)) { //Execute callback functions if they exist - if ((QuadTree._processingCallback == null) || QuadTree._processingCallback(QuadTree._object, checkObject)) + if ((QuadTree._processingCallback == null) || QuadTree._processingCallback(QuadTree._object, this._checkObject)) { - overlapProcessed = true; + this._overlapProcessed = true; } - if (overlapProcessed && (QuadTree._notifyCallback != null)) + if (this._overlapProcessed && (QuadTree._notifyCallback != null)) { if (QuadTree._callbackContext !== null) { - QuadTree._notifyCallback.call(QuadTree._callbackContext, QuadTree._object, checkObject); + QuadTree._notifyCallback.call(QuadTree._callbackContext, QuadTree._object, this._checkObject); } else { - QuadTree._notifyCallback(QuadTree._object, checkObject); + QuadTree._notifyCallback(QuadTree._object, this._checkObject); } } } @@ -643,7 +646,7 @@ module Phaser { } - return overlapProcessed; + return this._overlapProcessed; } } diff --git a/Phaser/phaser.js b/Phaser/phaser.js index ec56656ed..7b20a194e 100644 --- a/Phaser/phaser.js +++ b/Phaser/phaser.js @@ -1,3 +1,19 @@ +/** +* Phaser +* +* v1.0.0 - June XX 2013 +* +* A small and feature-packed 2D canvas game framework born from the firey pits of Flixel and Kiwi. +* +* Richard Davey (@photonstorm) +* +* Many thanks to Adam Saltsman (@ADAMATOMIC) for releasing Flixel, from both which Phaser +* and my love of game development took a lot of inspiration. +* +* "If you want your children to be intelligent, read them fairy tales." +* "If you want them to be more intelligent, read them more fairy tales." +* -- Albert Einstein +*/ var Phaser; (function (Phaser) { Phaser.VERSION = 'Phaser version 1.0.0'; diff --git a/Phaser/renderers/CanvasRenderer.ts b/Phaser/renderers/CanvasRenderer.ts index 577e75484..e8070ea43 100644 --- a/Phaser/renderers/CanvasRenderer.ts +++ b/Phaser/renderers/CanvasRenderer.ts @@ -1,5 +1,4 @@ /// -/// /// /// /// @@ -8,16 +7,14 @@ module Phaser { export class CanvasRenderer implements Phaser.IRenderer { - constructor(game: Game) { - + constructor(game: Phaser.Game) { this._game = game; - } /** * The essential reference to the main game object */ - private _game: Game; + private _game: Phaser.Game; // local rendering related temp vars to help avoid gc spikes with var creation private _sx: number = 0; @@ -28,6 +25,8 @@ module Phaser { private _dy: number = 0; private _dw: number = 0; private _dh: number = 0; + private _fx: number = 1; + private _fy: number = 1; private _cameraList; private _camera: Camera; @@ -73,15 +72,29 @@ module Phaser { sprite.texture.context.globalAlpha = sprite.texture.alpha; } + this._fx = sprite.scale.x; + this._fy = sprite.scale.y; this._sx = 0; this._sy = 0; this._sw = sprite.frameBounds.width; this._sh = sprite.frameBounds.height; + //if (sprite.texture.flippedX) + //{ + // this._fx = -1; + //} + + //if (sprite.texture.flippedY) + //{ + // this._fy = -1; + //} + this._dx = (camera.scaledX * sprite.scrollFactor.x) + sprite.frameBounds.x - (camera.worldView.x * sprite.scrollFactor.x); this._dy = (camera.scaledY * sprite.scrollFactor.y) + sprite.frameBounds.y - (camera.worldView.y * sprite.scrollFactor.y); - this._dw = sprite.frameBounds.width * sprite.scale.x; - this._dh = sprite.frameBounds.height * sprite.scale.y; + //this._dw = sprite.frameBounds.width * sprite.scale.x; + //this._dh = sprite.frameBounds.height * sprite.scale.y; + this._dw = sprite.frameBounds.width; + this._dh = sprite.frameBounds.height; /* if (this._dynamicTexture == false && this.animations.currentFrame !== null) @@ -104,11 +117,35 @@ module Phaser { //this._dy -= (camera.worldView.y * this.scrollFactor.y); } + // Apply origin / alignment + if (sprite.origin.x != 0 || sprite.origin.y != 0) + { + //this._dx += (sprite.origin.x * sprite.scale.x); + //this._dy += (sprite.origin.y * sprite.scale.y); + } + // Rotation and Flipped - if (sprite.position.rotation !== 0 || sprite.position.rotationOffset !== 0 || sprite.texture.flippedX || sprite.texture.flippedY) + if (sprite.scale.x != 1 || sprite.scale.y != 1 || sprite.position.rotation != 0 || sprite.position.rotationOffset != 0 || sprite.texture.flippedX || sprite.texture.flippedY) + //if (sprite.position.rotation != 0 || sprite.position.rotationOffset != 0 || sprite.texture.flippedX || sprite.texture.flippedY) { sprite.texture.context.save(); - sprite.texture.context.translate(this._dx + (this._dw / 2), this._dy + (this._dh / 2)); + + if (sprite.texture.flippedX) + { + this._dx += this._dw * sprite.scale.x; + } + + if (sprite.texture.flippedY) + { + this._dy += this._dh * sprite.scale.y; + } + + sprite.texture.context.translate(this._dx, this._dy); + + //sprite.texture.context.translate(this._dx + (this._dw / 2), this._dy + (this._dh / 2)); + //sprite.texture.context.translate(this._dx + (sprite.origin.x * sprite.scale.x), this._dy + (sprite.origin.y * sprite.scale.y)); + //sprite.texture.context.translate(this._dx + sprite.origin.x, this._dy + sprite.origin.y); + //sprite.texture.context.translate(this._dx + sprite.origin.x - (this._dw / 2), this._dy + sprite.origin.y - (this._dh / 2)); if (sprite.texture.renderRotation == true && (sprite.position.rotation !== 0 || sprite.position.rotationOffset !== 0)) { @@ -116,15 +153,42 @@ module Phaser { sprite.texture.context.rotate((sprite.position.rotationOffset + sprite.position.rotation) * (Math.PI / 180)); } - this._dx = -(this._dw / 2); - this._dy = -(this._dh / 2); - - if (sprite.texture.flippedX || sprite.texture.flippedY) + if (sprite.scale.x != 1 || sprite.scale.y != 1 || sprite.texture.flippedX || sprite.texture.flippedY) { if (sprite.texture.flippedX) { - sprite.texture.context.scale(-1, 1); + this._fx = -sprite.scale.x; } + + if (sprite.texture.flippedY) + { + this._fy = -sprite.scale.y; + } + + sprite.texture.context.scale(this._fx, this._fy); + + } + + //if (sprite.texture.flippedX || sprite.texture.flippedY) + //{ + // sprite.texture.context.scale(this._fx, this._fy); + //} + + this._dx = -(sprite.origin.x * sprite.scale.x); + this._dy = -(sprite.origin.y * sprite.scale.y); + //this._dx = -(sprite.origin.x * sprite.scale.x); + //this._dy = -(sprite.origin.y * sprite.scale.y); + //this._dx = -(this._dw / 2) * sprite.scale.x; + //this._dy = -(this._dh / 2) * sprite.scale.y; + //this._dx = 0; + //this._dy = 0; + } + else + { + if (sprite.origin.x != 0 || sprite.origin.y != 0) + { + //this._dx -= (sprite.origin.x * sprite.scale.x); + //this._dy -= (sprite.origin.y * sprite.scale.y); } } @@ -157,7 +221,8 @@ module Phaser { // this.context.fillRect(this._dx, this._dy, this._dw, this._dh); //} - if (sprite.position.rotation !== 0 || sprite.position.rotationOffset !== 0 || sprite.texture.flippedX || sprite.texture.flippedY) + if (sprite.scale.x != 1 || sprite.scale.y != 1 || sprite.position.rotation != 0 || sprite.position.rotationOffset != 0 || sprite.texture.flippedX || sprite.texture.flippedY) + //if (sprite.position.rotation != 0 || sprite.position.rotationOffset != 0 || sprite.texture.flippedX || sprite.texture.flippedY) { //this.context.translate(0, 0); sprite.texture.context.restore(); diff --git a/Phaser/renderers/HeadlessRenderer.ts b/Phaser/renderers/HeadlessRenderer.ts index 9df50ebcf..940259082 100644 --- a/Phaser/renderers/HeadlessRenderer.ts +++ b/Phaser/renderers/HeadlessRenderer.ts @@ -6,14 +6,14 @@ module Phaser { export class HeadlessRenderer implements Phaser.IRenderer { - constructor(game: Game) { + constructor(game: Phaser.Game) { this._game = game; } /** * The essential reference to the main game object */ - private _game: Game; + private _game: Phaser.Game; public render() {} diff --git a/Phaser/renderers/IRenderer.ts b/Phaser/renderers/IRenderer.ts index 60e5c4ca1..af1190cc6 100644 --- a/Phaser/renderers/IRenderer.ts +++ b/Phaser/renderers/IRenderer.ts @@ -4,10 +4,6 @@ module Phaser { export interface IRenderer { - // properties - _game: Game; - - // methods render(); renderSprite(camera: Camera, sprite: Sprite): bool; diff --git a/Phaser/tweens/Tween.ts b/Phaser/tweens/Tween.ts index 3e2f5aa73..90edf0485 100644 --- a/Phaser/tweens/Tween.ts +++ b/Phaser/tweens/Tween.ts @@ -195,6 +195,18 @@ module Phaser { } + public clear() { + + this._chainedTweens = []; + + this.onStart.removeAll(); + this.onUpdate.removeAll(); + this.onComplete.removeAll(); + + return this; + + } + /** * Stop tweening. */ diff --git a/Phaser/utils/CircleUtils.ts b/Phaser/utils/CircleUtils.ts index 52870381d..f3df6bd1d 100644 --- a/Phaser/utils/CircleUtils.ts +++ b/Phaser/utils/CircleUtils.ts @@ -36,7 +36,8 @@ module Phaser { * @return {Boolean} True if the coordinates are within this circle, otherwise false. **/ static contains(a: Circle, x: number, y: number): bool { - return (a.radius * a.radius >= Collision.distanceSquared(a.x, a.y, x, y)); + //return (a.radius * a.radius >= Collision.distanceSquared(a.x, a.y, x, y)); + return true; } /** @@ -59,7 +60,8 @@ module Phaser { * @return {Boolean} True if the coordinates are within this circle, otherwise false. **/ static containsCircle(a:Circle, b:Circle): bool { - return ((a.radius + b.radius) * (a.radius + b.radius)) >= Collision.distanceSquared(a.x, a.y, b.x, b.y); + //return ((a.radius + b.radius) * (a.radius + b.radius)) >= Collision.distanceSquared(a.x, a.y, b.x, b.y); + return true; } /** diff --git a/Phaser/utils/SpriteUtils.ts b/Phaser/utils/SpriteUtils.ts index 090dfe63f..4511e6a54 100644 --- a/Phaser/utils/SpriteUtils.ts +++ b/Phaser/utils/SpriteUtils.ts @@ -341,65 +341,6 @@ module Phaser { } - /** - * Load graphic for this sprite. (graphic can be SpriteSheet or Texture) - * @param key {string} Key of the graphic you want to load for this sprite. - * @param clearAnimations {boolean} If this Sprite has a set of animation data already loaded you can choose to keep or clear it with this boolean - * @return {Sprite} Sprite instance itself. - */ - static loadTexture(sprite: Phaser.Sprite, key: string, clearAnimations: bool = true): Sprite { - - //if (clearAnimations && sprite.animations.frameData !== null) - //{ - // sprite.animations.destroy(); - //} - - if (sprite.game.cache.getImage(key) !== null) - { - if (sprite.game.cache.isSpriteSheet(key)) - { - sprite.texture.setTo(null, sprite.game.cache.getImage(key)); - //sprite.animations.loadFrameData(sprite._game.cache.getFrameData(key)); - //sprite.collisionMask.width = sprite.animations.currentFrame.width; - //sprite.collisionMask.height = sprite.animations.currentFrame.height; - } - else - { - sprite.texture.setTo(sprite.game.cache.getImage(key), null); - sprite.frameBounds.width = sprite.texture.width; - sprite.frameBounds.height = sprite.texture.height; - //sprite.collisionMask.width = sprite._texture.width; - //sprite.collisionMask.height = sprite._texture.height; - } - } - - return sprite; - - } - - /** - * Load a DynamicTexture as its texture. - * @param texture {DynamicTexture} The texture object to be used by this sprite. - * @return {Sprite} Sprite instance itself. - */ - static loadDynamicTexture(sprite: Phaser.Sprite, texture: DynamicTexture): Sprite { - - //if (sprite.animations.frameData !== null) - //{ - // sprite.animations.destroy(); - //} - - //sprite._texture = texture; - - //sprite.frameBounds.width = sprite._texture.width; - //sprite.frameBounds.height = sprite._texture.height; - - //sprite._dynamicTexture = true; - - return sprite; - - } - /** * This function creates a flat colored square image dynamically. * @param width {number} The width of the sprite you want to generate. diff --git a/README.md b/README.md index 16e98d7db..da0281c28 100644 --- a/README.md +++ b/README.md @@ -38,7 +38,7 @@ V1.0.0 * Heavily optimised Group so it no longer creates any temporary variables in any methods. * Added Game.renderer which can be HEADLESS, CANVAS or WEBGL (coming soon) * Added Sprite.render which is a reference to IRenderer.renderSprite, but can be overridden for custom handling. - +* Refactored QuadTree so it no longer creates any temporary variables in any methods. V0.9.6 diff --git a/SpecialFX/Camera/Border.ts b/SpecialFX/Camera/Border.ts index db2a04130..ac4bf9b11 100644 --- a/SpecialFX/Camera/Border.ts +++ b/SpecialFX/Camera/Border.ts @@ -1,6 +1,4 @@ -/// -/// -/// +/// /** * Phaser - FX - Camera - Border @@ -44,13 +42,13 @@ module Phaser.FX.Camera { * Post-render is called during the objects render cycle, after the children/image data has been rendered. * It happens directly BEFORE a canvas context.restore has happened if added to a Camera. */ - public postRender(camera: Camera, cameraX: number, cameraY: number, cameraWidth: number, cameraHeight: number) { + public postRender(camera: Phaser.Camera, cameraX: number, cameraY: number, cameraWidth: number, cameraHeight: number) { if (this.showBorder == true) { this._game.stage.context.strokeStyle = this.borderColor; this._game.stage.context.lineWidth = 1; - this._game.stage.context.rect(this._sx, this._sy, this.worldView.width, this.worldView.height); + this._game.stage.context.rect(camera.scaledX, camera.scaledY, camera.worldView.width, camera.worldView.height); this._game.stage.context.stroke(); } diff --git a/SpecialFX/Camera/Fade.ts b/SpecialFX/Camera/Fade.ts index bb036d460..bf56780b7 100644 --- a/SpecialFX/Camera/Fade.ts +++ b/SpecialFX/Camera/Fade.ts @@ -1,5 +1,4 @@ -/// -/// +/// /** * Phaser - FX - Camera - Fade diff --git a/SpecialFX/Camera/Flash.ts b/SpecialFX/Camera/Flash.ts index e7dd6a8bf..cc7c3cea7 100644 --- a/SpecialFX/Camera/Flash.ts +++ b/SpecialFX/Camera/Flash.ts @@ -1,5 +1,4 @@ -/// -/// +/// /** * Phaser - FX - Camera - Flash diff --git a/SpecialFX/Camera/Mirror.ts b/SpecialFX/Camera/Mirror.ts index 211da2f1e..a44eb2bc2 100644 --- a/SpecialFX/Camera/Mirror.ts +++ b/SpecialFX/Camera/Mirror.ts @@ -1,6 +1,4 @@ -/// -/// -/// +/// /** * Phaser - FX - Camera - Mirror @@ -49,7 +47,7 @@ module Phaser.FX.Camera { * This is the rectangular region to grab from the Camera used in the Mirror effect * It is rendered to the Stage at Mirror.x/y (note the use of Stage coordinates, not World coordinates) */ - public start(x: number, y: number, region: Phaser.Quad, fillColor?: string = 'rgba(0, 0, 100, 0.5)') { + public start(x: number, y: number, region: Phaser.Rectangle, fillColor?: string = 'rgba(0, 0, 100, 0.5)') { this.x = x; this.y = y; @@ -73,10 +71,10 @@ module Phaser.FX.Camera { */ public postRender(camera: Camera, cameraX: number, cameraY: number, cameraWidth: number, cameraHeight: number) { - if (this.cls) - { - this._context.clearRect(0, 0, this._mirrorWidth, this._mirrorHeight); - } + //if (this.cls) + //{ + // this._context.clearRect(0, 0, this._mirrorWidth, this._mirrorHeight); + //} this._sx = cameraX + this._mirrorX; this._sy = cameraY + this._mirrorY; diff --git a/SpecialFX/Camera/Scanlines.ts b/SpecialFX/Camera/Scanlines.ts index f01cdec49..02cd05f29 100644 --- a/SpecialFX/Camera/Scanlines.ts +++ b/SpecialFX/Camera/Scanlines.ts @@ -1,6 +1,4 @@ -/// -/// -/// +/// /** * Phaser - FX - Camera - Scanlines diff --git a/SpecialFX/Camera/Shadow.ts b/SpecialFX/Camera/Shadow.ts index 89120bfae..60be66616 100644 --- a/SpecialFX/Camera/Shadow.ts +++ b/SpecialFX/Camera/Shadow.ts @@ -1,6 +1,4 @@ -/// -/// -/// +/// /** * Phaser - FX - Camera - Shadow @@ -42,9 +40,9 @@ module Phaser.FX.Camera { /** * Offset of the shadow from camera's position. - * @type {MicroPoint} + * @type {Point} */ - public shadowOffset: MicroPoint = new MicroPoint(4, 4); + public shadowOffset: Point = new Point(4, 4); /** * You can name the function that starts the effect whatever you like, but we used 'start' in our effects. diff --git a/SpecialFX/Camera/Shake.ts b/SpecialFX/Camera/Shake.ts index e1572b2f5..0e782f6d8 100644 --- a/SpecialFX/Camera/Shake.ts +++ b/SpecialFX/Camera/Shake.ts @@ -1,5 +1,4 @@ -/// -/// +/// /** * Phaser - FX - Camera - Shake @@ -24,7 +23,7 @@ module Phaser.FX.Camera { private _fxShakeIntensity: number = 0; private _fxShakeDuration: number = 0; private _fxShakeComplete = null; - private _fxShakeOffset: MicroPoint = new MicroPoint(0, 0); + private _fxShakeOffset: Point = new Point(0, 0); private _fxShakeDirection: number = 0; private _fxShakePrevX: number = 0; private _fxShakePrevY: number = 0; diff --git a/SpecialFX/Camera/Template.ts b/SpecialFX/Camera/Template.ts index e7b9312b5..4bcd7c664 100644 --- a/SpecialFX/Camera/Template.ts +++ b/SpecialFX/Camera/Template.ts @@ -1,6 +1,4 @@ -/// -/// -/// +/// /** * Phaser - FX - Camera - Template diff --git a/Tests/Tests.csproj b/Tests/Tests.csproj index 769ebab55..9f898a472 100644 --- a/Tests/Tests.csproj +++ b/Tests/Tests.csproj @@ -53,279 +53,38 @@ false - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - fade.ts + + create sprite 1.ts - - flash.ts + + + scale origin 1.ts - - - - - mirror.ts + + scale sprite 1.ts - - scanlines.ts + + scale sprite 2.ts - - shake.ts + + scale sprite 3.ts - - - - - - mask animation 1.ts + + scale sprite 4.ts - - mask test 1.ts + + scale sprite 5.ts - - - mask test 2.ts + + + + + + + + + boot screen.ts - - - multi rotate.ts - - - - - - rope bridge.ts - - - rotate point 1.ts - - - rotate point 2.ts - - - - rotate point 3.ts - - - - - rotate point 4.ts - - - verlet 1.ts - - - - verlet sprites.ts - - - display order.ts - - - multitouch.ts - - - - - single tap.ts - - - single touch.ts - - - bootscreen.ts - - - - - - - starfield.ts - - - time.ts - - - bunny mobile.ts - - - sprite test 1.ts - - - - mousetrail.ts - - - - temp1.ts - - - - temp2.ts - - - ballscroller.ts - - - - - blasteroids.ts - - - parallax.ts - - - - - region demo.ts - - - scroll window.ts - - - simple scrollzone.ts - - - align.ts - - - - flipped.ts - - - - - - - - starling texture atlas 1.ts - - - collide with tile.ts - - - collision.ts - - - - fill tiles.ts - - - get tile.ts - - - - - map draw.ts - - - put tile.ts - - - - - random tiles.ts - - - replace tiles.ts - - - small map.ts - - - - - sprite draw tiles.ts - - - swap tiles.ts - - - bounce.ts - - - elastic.ts - - - - - - - - - circle.ts - - - - - line.ts - - - point.ts - - - rect vs rect.ts - - - rectangle.ts - - - animate by framename.ts - - - dynamic texture 1.ts - - - dynamic texture 2.ts - - - rotation.ts - - - \ No newline at end of file diff --git a/Tests/camera fx/fade.js b/Tests/camera fx/fade.js deleted file mode 100644 index 2fe678bca..000000000 --- a/Tests/camera fx/fade.js +++ /dev/null @@ -1,46 +0,0 @@ -/// -/// -(function () { - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update); - function init() { - myGame.loader.addImageFile('background', 'assets/pics/large-color-wheel.png'); - myGame.loader.addImageFile('car', 'assets/sprites/car90.png'); - myGame.loader.load(); - } - var car; - var fade; - function create() { - myGame.add.sprite(0, 0, 'background'); - car = myGame.add.sprite(400, 300, 'car'); - // Add our effect to the camera - fade = myGame.camera.fx.add(Phaser.FX.Camera.Fade); - } - function update() { - car.velocity.x = 0; - car.velocity.y = 0; - car.angularVelocity = 0; - if(myGame.input.keyboard.isDown(Phaser.Keyboard.LEFT)) { - car.angularVelocity = -200; - } else if(myGame.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) { - car.angularVelocity = 200; - } - if(myGame.input.keyboard.isDown(Phaser.Keyboard.UP)) { - car.velocity.copyFrom(myGame.motion.velocityFromAngle(car.angle, 300)); - } - // Fade when the car hits the edges, a different colour per edge - if(car.x < 0) { - fade.start(0x330066, 3); - car.x = 0; - } else if(car.x > myGame.world.width) { - fade.start(0x000066, 3); - car.x = myGame.world.width - car.width; - } - if(car.y < 0) { - fade.start(0xffffff, 4); - car.y = 0; - } else if(car.y > myGame.world.height) { - fade.start(0x000000, 3); - car.y = myGame.world.height - car.height; - } - } -})(); diff --git a/Tests/camera fx/fade.ts b/Tests/camera fx/fade.ts deleted file mode 100644 index 4816b5d5f..000000000 --- a/Tests/camera fx/fade.ts +++ /dev/null @@ -1,77 +0,0 @@ -/// -/// - -(function () { - - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update); - - function init() { - - myGame.loader.addImageFile('background', 'assets/pics/large-color-wheel.png'); - myGame.loader.addImageFile('car', 'assets/sprites/car90.png'); - - myGame.loader.load(); - - } - - var car: Phaser.Sprite; - var fade: Phaser.FX.Camera.Fade; - - function create() { - - myGame.add.sprite(0, 0, 'background'); - - car = myGame.add.sprite(400, 300, 'car'); - - // Add our effect to the camera - fade = myGame.camera.fx.add(Phaser.FX.Camera.Fade); - - } - - function update() { - - car.velocity.x = 0; - car.velocity.y = 0; - car.angularVelocity = 0; - - if (myGame.input.keyboard.isDown(Phaser.Keyboard.LEFT)) - { - car.angularVelocity = -200; - } - else if (myGame.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) - { - car.angularVelocity = 200; - } - - if (myGame.input.keyboard.isDown(Phaser.Keyboard.UP)) - { - car.velocity.copyFrom(myGame.motion.velocityFromAngle(car.angle, 300)); - } - - // Fade when the car hits the edges, a different colour per edge - - if (car.x < 0) - { - fade.start(0x330066, 3); - car.x = 0; - } - else if (car.x > myGame.world.width) - { - fade.start(0x000066, 3); - car.x = myGame.world.width - car.width; - } - - if (car.y < 0) - { - fade.start(0xffffff, 4); - car.y = 0; - } - else if (car.y > myGame.world.height) - { - fade.start(0x000000, 3); - car.y = myGame.world.height - car.height; - } - - } - -})(); diff --git a/Tests/camera fx/flash.js b/Tests/camera fx/flash.js deleted file mode 100644 index 6c35dc002..000000000 --- a/Tests/camera fx/flash.js +++ /dev/null @@ -1,46 +0,0 @@ -/// -/// -(function () { - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update); - function init() { - myGame.loader.addImageFile('background', 'assets/pics/large-color-wheel.png'); - myGame.loader.addImageFile('car', 'assets/sprites/car90.png'); - myGame.loader.load(); - } - var car; - var flash; - function create() { - myGame.add.sprite(0, 0, 'background'); - car = myGame.add.sprite(400, 300, 'car'); - // Add our effect to the camera - flash = myGame.camera.fx.add(Phaser.FX.Camera.Flash); - } - function update() { - car.velocity.x = 0; - car.velocity.y = 0; - car.angularVelocity = 0; - if(myGame.input.keyboard.isDown(Phaser.Keyboard.LEFT)) { - car.angularVelocity = -200; - } else if(myGame.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) { - car.angularVelocity = 200; - } - if(myGame.input.keyboard.isDown(Phaser.Keyboard.UP)) { - car.velocity.copyFrom(myGame.motion.velocityFromAngle(car.angle, 300)); - } - // Flash when the car hits the edges, a different colour per edge - if(car.x < 0) { - flash.start(0xffffff, 1); - car.x = 0; - } else if(car.x > myGame.world.width) { - flash.start(0xff0000, 2); - car.x = myGame.world.width - car.width; - } - if(car.y < 0) { - flash.start(0xffff00, 2); - car.y = 0; - } else if(car.y > myGame.world.height) { - flash.start(0xff00ff, 3); - car.y = myGame.world.height - car.height; - } - } -})(); diff --git a/Tests/camera fx/flash.ts b/Tests/camera fx/flash.ts deleted file mode 100644 index f3a2e61a3..000000000 --- a/Tests/camera fx/flash.ts +++ /dev/null @@ -1,77 +0,0 @@ -/// -/// - -(function () { - - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update); - - function init() { - - myGame.loader.addImageFile('background', 'assets/pics/large-color-wheel.png'); - myGame.loader.addImageFile('car', 'assets/sprites/car90.png'); - - myGame.loader.load(); - - } - - var car: Phaser.Sprite; - var flash: Phaser.FX.Camera.Flash; - - function create() { - - myGame.add.sprite(0, 0, 'background'); - - car = myGame.add.sprite(400, 300, 'car'); - - // Add our effect to the camera - flash = myGame.camera.fx.add(Phaser.FX.Camera.Flash); - - } - - function update() { - - car.velocity.x = 0; - car.velocity.y = 0; - car.angularVelocity = 0; - - if (myGame.input.keyboard.isDown(Phaser.Keyboard.LEFT)) - { - car.angularVelocity = -200; - } - else if (myGame.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) - { - car.angularVelocity = 200; - } - - if (myGame.input.keyboard.isDown(Phaser.Keyboard.UP)) - { - car.velocity.copyFrom(myGame.motion.velocityFromAngle(car.angle, 300)); - } - - // Flash when the car hits the edges, a different colour per edge - - if (car.x < 0) - { - flash.start(0xffffff, 1); - car.x = 0; - } - else if (car.x > myGame.world.width) - { - flash.start(0xff0000, 2); - car.x = myGame.world.width - car.width; - } - - if (car.y < 0) - { - flash.start(0xffff00, 2); - car.y = 0; - } - else if (car.y > myGame.world.height) - { - flash.start(0xff00ff, 3); - car.y = myGame.world.height - car.height; - } - - } - -})(); diff --git a/Tests/camera fx/mirror.js b/Tests/camera fx/mirror.js deleted file mode 100644 index e9abc4c5b..000000000 --- a/Tests/camera fx/mirror.js +++ /dev/null @@ -1,41 +0,0 @@ -/// -/// -(function () { - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update); - function init() { - // Just set the world to be the size of the image we're loading in - myGame.world.setSize(1216, 896); - myGame.loader.addImageFile('backdrop', 'assets/pics/ninja-masters2.png'); - myGame.loader.load(); - } - var mirror; - function create() { - // What we need is a camera 800x400 pixels in size as the mirror effect will be 200px tall and sit below it. - // So we resize our default camera to 400px - myGame.camera.height = 400; - // Because it's our default camera we need to tell it to disable clipping, otherwise we'll never see the mirror effect render. - myGame.camera.disableClipping = true; - // Add our effect to the camera - mirror = myGame.camera.fx.add(Phaser.FX.Camera.Mirror); - // The first 2 parameters are the x and y coordinates of where to display the effect. They are in STAGE coordinates, not World. - // The next is a Quad making up the rectangular region of the Camera that we'll create the effect from (in this case the whole camera). - // Finally we set the fill color that is put over the top of the mirror effect. - mirror.start(0, 400, new Phaser.Quad(0, 0, 800, 400), 'rgba(0, 0, 100, 0.7)'); - // Experiment with variations on these to see the different mirror effects that can be achieved. - //mirror.flipX = true; - //mirror.flipY = true; - myGame.add.sprite(0, 0, 'backdrop'); - } - function update() { - if(myGame.input.keyboard.isDown(Phaser.Keyboard.LEFT)) { - myGame.camera.scroll.x -= 4; - } else if(myGame.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) { - myGame.camera.scroll.x += 4; - } - if(myGame.input.keyboard.isDown(Phaser.Keyboard.UP)) { - myGame.camera.scroll.y -= 4; - } else if(myGame.input.keyboard.isDown(Phaser.Keyboard.DOWN)) { - myGame.camera.scroll.y += 4; - } - } -})(); diff --git a/Tests/camera fx/mirror.ts b/Tests/camera fx/mirror.ts deleted file mode 100644 index 3a7cdc92a..000000000 --- a/Tests/camera fx/mirror.ts +++ /dev/null @@ -1,68 +0,0 @@ -/// -/// - -(function () { - - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update); - - function init() { - - // Just set the world to be the size of the image we're loading in - myGame.world.setSize(1216, 896); - - myGame.loader.addImageFile('backdrop', 'assets/pics/ninja-masters2.png'); - - myGame.loader.load(); - - } - - var mirror: Phaser.FX.Camera.Mirror; - - function create() { - - // What we need is a camera 800x400 pixels in size as the mirror effect will be 200px tall and sit below it. - // So we resize our default camera to 400px - myGame.camera.height = 400; - - // Because it's our default camera we need to tell it to disable clipping, otherwise we'll never see the mirror effect render. - myGame.camera.disableClipping = true; - - // Add our effect to the camera - mirror = myGame.camera.fx.add(Phaser.FX.Camera.Mirror); - - // The first 2 parameters are the x and y coordinates of where to display the effect. They are in STAGE coordinates, not World. - // The next is a Quad making up the rectangular region of the Camera that we'll create the effect from (in this case the whole camera). - // Finally we set the fill color that is put over the top of the mirror effect. - mirror.start(0, 400, new Phaser.Quad(0, 0, 800, 400), 'rgba(0, 0, 100, 0.7)'); - - // Experiment with variations on these to see the different mirror effects that can be achieved. - //mirror.flipX = true; - //mirror.flipY = true; - - myGame.add.sprite(0, 0, 'backdrop'); - - } - - function update() { - - if (myGame.input.keyboard.isDown(Phaser.Keyboard.LEFT)) - { - myGame.camera.scroll.x -= 4; - } - else if (myGame.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) - { - myGame.camera.scroll.x += 4; - } - - if (myGame.input.keyboard.isDown(Phaser.Keyboard.UP)) - { - myGame.camera.scroll.y -= 4; - } - else if (myGame.input.keyboard.isDown(Phaser.Keyboard.DOWN)) - { - myGame.camera.scroll.y += 4; - } - - } - -})(); diff --git a/Tests/camera fx/scanlines.js b/Tests/camera fx/scanlines.js deleted file mode 100644 index 71d9bab54..000000000 --- a/Tests/camera fx/scanlines.js +++ /dev/null @@ -1,32 +0,0 @@ -/// -/// -(function () { - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update); - function init() { - myGame.world.setSize(1216, 896); - myGame.loader.addImageFile('backdrop', 'assets/pics/ninja-masters2.png'); - myGame.loader.load(); - } - var scanlines; - function create() { - // Add our effect to the camera - scanlines = myGame.camera.fx.add(Phaser.FX.Camera.Scanlines); - // We'll have the scanlines spaced out every 2 pixels - scanlines.spacing = 2; - // This is the color the lines will be drawn in - scanlines.color = 'rgba(0, 0, 0, 0.8)'; - myGame.add.sprite(0, 0, 'backdrop'); - } - function update() { - if(myGame.input.keyboard.isDown(Phaser.Keyboard.LEFT)) { - myGame.camera.scroll.x -= 4; - } else if(myGame.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) { - myGame.camera.scroll.x += 4; - } - if(myGame.input.keyboard.isDown(Phaser.Keyboard.UP)) { - myGame.camera.scroll.y -= 4; - } else if(myGame.input.keyboard.isDown(Phaser.Keyboard.DOWN)) { - myGame.camera.scroll.y += 4; - } - } -})(); diff --git a/Tests/camera fx/scanlines.ts b/Tests/camera fx/scanlines.ts deleted file mode 100644 index 019f30249..000000000 --- a/Tests/camera fx/scanlines.ts +++ /dev/null @@ -1,57 +0,0 @@ -/// -/// - -(function () { - - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update); - - function init() { - - myGame.world.setSize(1216, 896); - - myGame.loader.addImageFile('backdrop', 'assets/pics/ninja-masters2.png'); - - myGame.loader.load(); - - } - - var scanlines: Phaser.FX.Camera.Scanlines; - - function create() { - - // Add our effect to the camera - scanlines = myGame.camera.fx.add(Phaser.FX.Camera.Scanlines); - - // We'll have the scanlines spaced out every 2 pixels - scanlines.spacing = 2; - - // This is the color the lines will be drawn in - scanlines.color = 'rgba(0, 0, 0, 0.8)'; - - myGame.add.sprite(0, 0, 'backdrop'); - - } - - function update() { - - if (myGame.input.keyboard.isDown(Phaser.Keyboard.LEFT)) - { - myGame.camera.scroll.x -= 4; - } - else if (myGame.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) - { - myGame.camera.scroll.x += 4; - } - - if (myGame.input.keyboard.isDown(Phaser.Keyboard.UP)) - { - myGame.camera.scroll.y -= 4; - } - else if (myGame.input.keyboard.isDown(Phaser.Keyboard.DOWN)) - { - myGame.camera.scroll.y += 4; - } - - } - -})(); diff --git a/Tests/camera fx/shake.js b/Tests/camera fx/shake.js deleted file mode 100644 index 6c78a0da3..000000000 --- a/Tests/camera fx/shake.js +++ /dev/null @@ -1,50 +0,0 @@ -/// -/// -(function () { - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update); - function init() { - myGame.loader.addImageFile('background', 'assets/pics/remember-me.jpg'); - myGame.loader.addImageFile('car', 'assets/sprites/car90.png'); - myGame.loader.load(); - } - var car; - var shake; - function create() { - myGame.add.sprite(0, 0, 'background'); - car = myGame.add.sprite(400, 300, 'car'); - // Add our effect to the camera - shake = myGame.camera.fx.add(Phaser.FX.Camera.Shake); - myGame.onRenderCallback = render; - } - function update() { - car.velocity.x = 0; - car.velocity.y = 0; - car.angularVelocity = 0; - if(myGame.input.keyboard.isDown(Phaser.Keyboard.LEFT)) { - car.angularVelocity = -200; - } else if(myGame.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) { - car.angularVelocity = 200; - } - if(myGame.input.keyboard.isDown(Phaser.Keyboard.UP)) { - car.velocity.copyFrom(myGame.motion.velocityFromAngle(car.angle, 300)); - } - // Shake the camera when the car hits the edges, a different intensity per edge - if(car.x < 0) { - shake.start(); - car.x = 0; - } else if(car.x > myGame.world.width) { - shake.start(0.02); - car.x = myGame.world.width - car.width; - } - if(car.y < 0) { - shake.start(0.07, 1); - car.y = 0; - } else if(car.y > myGame.world.height) { - shake.start(0.1); - car.y = myGame.world.height - car.height; - } - } - function render() { - myGame.camera.renderDebugInfo(32, 32); - } -})(); diff --git a/Tests/camera fx/shake.ts b/Tests/camera fx/shake.ts deleted file mode 100644 index eaa047a30..000000000 --- a/Tests/camera fx/shake.ts +++ /dev/null @@ -1,85 +0,0 @@ -/// -/// - -(function () { - - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update); - - function init() { - - myGame.loader.addImageFile('background', 'assets/pics/remember-me.jpg'); - myGame.loader.addImageFile('car', 'assets/sprites/car90.png'); - - myGame.loader.load(); - - } - - var car: Phaser.Sprite; - var shake: Phaser.FX.Camera.Shake; - - function create() { - - myGame.add.sprite(0, 0, 'background'); - - car = myGame.add.sprite(400, 300, 'car'); - - // Add our effect to the camera - shake = myGame.camera.fx.add(Phaser.FX.Camera.Shake); - - myGame.onRenderCallback = render; - - } - - function update() { - - car.velocity.x = 0; - car.velocity.y = 0; - car.angularVelocity = 0; - - if (myGame.input.keyboard.isDown(Phaser.Keyboard.LEFT)) - { - car.angularVelocity = -200; - } - else if (myGame.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) - { - car.angularVelocity = 200; - } - - if (myGame.input.keyboard.isDown(Phaser.Keyboard.UP)) - { - car.velocity.copyFrom(myGame.motion.velocityFromAngle(car.angle, 300)); - } - - // Shake the camera when the car hits the edges, a different intensity per edge - - if (car.x < 0) - { - shake.start(); - car.x = 0; - } - else if (car.x > myGame.world.width) - { - shake.start(0.02); - car.x = myGame.world.width - car.width; - } - - if (car.y < 0) - { - shake.start(0.07, 1); - car.y = 0; - } - else if (car.y > myGame.world.height) - { - shake.start(0.1); - car.y = myGame.world.height - car.height; - } - - } - - function render() { - - myGame.camera.renderDebugInfo(32, 32); - - } - -})(); diff --git a/Tests/cameras/camera alpha.js b/Tests/cameras/camera alpha.js deleted file mode 100644 index ff60bfe95..000000000 --- a/Tests/cameras/camera alpha.js +++ /dev/null @@ -1,38 +0,0 @@ -/// -(function () { - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update); - function init() { - myGame.world.setSize(2240, 2240); - myGame.loader.addImageFile('grid', 'assets/tests/debug-grid-1920x1920.png'); - myGame.loader.addImageFile('car', 'assets/sprites/car90.png'); - myGame.loader.load(); - } - var car; - var miniCam; - function create() { - myGame.add.sprite(0, 0, 'grid'); - car = myGame.add.sprite(400, 300, 'car'); - myGame.camera.follow(car, Phaser.Camera.STYLE_TOPDOWN); - myGame.camera.setBounds(0, 0, myGame.world.width, myGame.world.height); - miniCam = myGame.add.camera(0, 0, 300, 300); - miniCam.follow(car, Phaser.Camera.STYLE_TOPDOWN_TIGHT); - miniCam.setBounds(0, 0, myGame.world.width, myGame.world.height); - miniCam.showBorder = true; - miniCam.alpha = 0.7; - } - function update() { - car.velocity.x = 0; - car.velocity.y = 0; - car.angularVelocity = 0; - car.angularAcceleration = 0; - if(myGame.input.keyboard.isDown(Phaser.Keyboard.LEFT)) { - car.angularVelocity = -200; - } else if(myGame.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) { - car.angularVelocity = 200; - } - if(myGame.input.keyboard.isDown(Phaser.Keyboard.UP)) { - var motion = myGame.motion.velocityFromAngle(car.angle, 300); - car.velocity.copyFrom(motion); - } - } -})(); diff --git a/Tests/cameras/camera alpha.ts b/Tests/cameras/camera alpha.ts deleted file mode 100644 index abf81700f..000000000 --- a/Tests/cameras/camera alpha.ts +++ /dev/null @@ -1,63 +0,0 @@ -/// - -(function () { - - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update); - - function init() { - - myGame.world.setSize(2240, 2240); - - myGame.loader.addImageFile('grid', 'assets/tests/debug-grid-1920x1920.png'); - myGame.loader.addImageFile('car', 'assets/sprites/car90.png'); - - myGame.loader.load(); - - } - - var car: Phaser.Sprite; - var miniCam: Phaser.Camera; - - function create() { - - myGame.add.sprite(0, 0, 'grid'); - - car = myGame.add.sprite(400, 300, 'car'); - - myGame.camera.follow(car, Phaser.Camera.STYLE_TOPDOWN); - myGame.camera.setBounds(0, 0, myGame.world.width, myGame.world.height); - - miniCam = myGame.add.camera(0, 0, 300, 300); - miniCam.follow(car, Phaser.Camera.STYLE_TOPDOWN_TIGHT); - miniCam.setBounds(0, 0, myGame.world.width, myGame.world.height); - miniCam.showBorder = true; - miniCam.alpha = 0.7; - - } - - function update() { - - car.velocity.x = 0; - car.velocity.y = 0; - car.angularVelocity = 0; - car.angularAcceleration = 0; - - if (myGame.input.keyboard.isDown(Phaser.Keyboard.LEFT)) - { - car.angularVelocity = -200; - } - else if (myGame.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) - { - car.angularVelocity = 200; - } - - if (myGame.input.keyboard.isDown(Phaser.Keyboard.UP)) - { - var motion:Phaser.Point = myGame.motion.velocityFromAngle(car.angle, 300); - - car.velocity.copyFrom(motion); - } - - } - -})(); diff --git a/Tests/cameras/camera bounds.js b/Tests/cameras/camera bounds.js deleted file mode 100644 index 6c5f09176..000000000 --- a/Tests/cameras/camera bounds.js +++ /dev/null @@ -1,33 +0,0 @@ -/// -(function () { - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update); - function init() { - myGame.world.setSize(1920, 1200); - myGame.camera.setBounds(0, 0, 1920, 1200); - myGame.loader.addImageFile('backdrop', 'assets/pics/remember-me.jpg'); - myGame.loader.addImageFile('melon', 'assets/sprites/melon.png'); - myGame.loader.load(); - } - function create() { - myGame.add.sprite(0, 0, 'backdrop'); - for(var i = 0; i < 100; i++) { - myGame.add.sprite(Math.random() * myGame.world.width, Math.random() * myGame.world.height, 'melon'); - } - myGame.onRenderCallback = render; - } - function update() { - if(myGame.input.keyboard.isDown(Phaser.Keyboard.LEFT)) { - myGame.camera.scroll.x -= 4; - } else if(myGame.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) { - myGame.camera.scroll.x += 4; - } - if(myGame.input.keyboard.isDown(Phaser.Keyboard.UP)) { - myGame.camera.scroll.y -= 4; - } else if(myGame.input.keyboard.isDown(Phaser.Keyboard.DOWN)) { - myGame.camera.scroll.y += 4; - } - } - function render() { - myGame.camera.renderDebugInfo(32, 32); - } -})(); diff --git a/Tests/cameras/camera bounds.ts b/Tests/cameras/camera bounds.ts deleted file mode 100644 index 4c2c3a7bc..000000000 --- a/Tests/cameras/camera bounds.ts +++ /dev/null @@ -1,60 +0,0 @@ -/// - -(function () { - - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update); - - function init() { - - myGame.world.setSize(1920, 1200); - myGame.camera.setBounds(0, 0, 1920, 1200); - - myGame.loader.addImageFile('backdrop', 'assets/pics/remember-me.jpg'); - myGame.loader.addImageFile('melon', 'assets/sprites/melon.png'); - - myGame.loader.load(); - - } - - function create() { - - myGame.add.sprite(0, 0, 'backdrop'); - - for (var i = 0; i < 100; i++) - { - myGame.add.sprite(Math.random() * myGame.world.width, Math.random() * myGame.world.height, 'melon'); - } - - myGame.onRenderCallback = render; - - } - - function update() { - - if (myGame.input.keyboard.isDown(Phaser.Keyboard.LEFT)) - { - myGame.camera.scroll.x -= 4; - } - else if (myGame.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) - { - myGame.camera.scroll.x += 4; - } - - if (myGame.input.keyboard.isDown(Phaser.Keyboard.UP)) - { - myGame.camera.scroll.y -= 4; - } - else if (myGame.input.keyboard.isDown(Phaser.Keyboard.DOWN)) - { - myGame.camera.scroll.y += 4; - } - - } - - function render() { - - myGame.camera.renderDebugInfo(32, 32); - - } - -})(); diff --git a/Tests/cameras/camera position.js b/Tests/cameras/camera position.js deleted file mode 100644 index 295ac7651..000000000 --- a/Tests/cameras/camera position.js +++ /dev/null @@ -1,40 +0,0 @@ -/// -(function () { - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update); - function init() { - myGame.world.setSize(3000, 3000); - myGame.loader.addImageFile('melon', 'assets/sprites/melon.png'); - myGame.loader.load(); - } - var cam2; - function create() { - for(var i = 0; i < 1000; i++) { - myGame.add.sprite(Math.random() * 3000, Math.random() * 3000, 'melon'); - } - myGame.camera.setPosition(16, 80); - myGame.camera.setSize(320, 320); - myGame.camera.showBorder = true; - myGame.camera.borderColor = 'rgb(255,0,0)'; - cam2 = myGame.add.camera(380, 100, 400, 400); - cam2.showBorder = true; - cam2.borderColor = 'rgb(255,255,0)'; - } - function update() { - myGame.camera.renderDebugInfo(16, 16); - cam2.renderDebugInfo(200, 16); - if(myGame.input.keyboard.isDown(Phaser.Keyboard.LEFT)) { - myGame.camera.x -= 4; - cam2.x -= 2; - } else if(myGame.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) { - myGame.camera.x += 4; - cam2.x += 2; - } - if(myGame.input.keyboard.isDown(Phaser.Keyboard.UP)) { - myGame.camera.y -= 4; - cam2.y -= 2; - } else if(myGame.input.keyboard.isDown(Phaser.Keyboard.DOWN)) { - myGame.camera.y += 4; - cam2.y += 2; - } - } -})(); diff --git a/Tests/cameras/camera position.ts b/Tests/cameras/camera position.ts deleted file mode 100644 index d5f7384c0..000000000 --- a/Tests/cameras/camera position.ts +++ /dev/null @@ -1,66 +0,0 @@ -/// - -(function () { - - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update); - - function init() { - - myGame.world.setSize(3000, 3000); - - myGame.loader.addImageFile('melon', 'assets/sprites/melon.png'); - - myGame.loader.load(); - - } - - var cam2: Phaser.Camera; - - function create() { - - for (var i = 0; i < 1000; i++) - { - myGame.add.sprite(Math.random() * 3000, Math.random() * 3000, 'melon'); - } - - myGame.camera.setPosition(16, 80); - myGame.camera.setSize(320, 320); - myGame.camera.showBorder = true; - myGame.camera.borderColor = 'rgb(255,0,0)'; - - cam2 = myGame.add.camera(380, 100, 400, 400); - cam2.showBorder = true; - cam2.borderColor = 'rgb(255,255,0)'; - - } - - function update() { - - myGame.camera.renderDebugInfo(16, 16); - cam2.renderDebugInfo(200, 16); - - if (myGame.input.keyboard.isDown(Phaser.Keyboard.LEFT)) - { - myGame.camera.x -= 4; - cam2.x -= 2; - } - else if (myGame.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) - { - myGame.camera.x += 4; - cam2.x += 2; - } - - if (myGame.input.keyboard.isDown(Phaser.Keyboard.UP)) - { - myGame.camera.y -= 4; - cam2.y -= 2; - } - else if (myGame.input.keyboard.isDown(Phaser.Keyboard.DOWN)) - { - myGame.camera.y += 4; - cam2.y += 2; - } - - } - -})(); diff --git a/Tests/cameras/camera rotation.js b/Tests/cameras/camera rotation.js deleted file mode 100644 index d77157982..000000000 --- a/Tests/cameras/camera rotation.js +++ /dev/null @@ -1,34 +0,0 @@ -/// -(function () { - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update); - function init() { - myGame.world.setSize(3000, 3000); - myGame.loader.addImageFile('car', 'assets/sprites/car.png'); - myGame.loader.addImageFile('melon', 'assets/sprites/melon.png'); - myGame.loader.load(); - } - function create() { - for(var i = 0; i < 1000; i++) { - if(Math.random() > 0.5) { - myGame.add.sprite(Math.random() * 3000, Math.random() * 3000, 'car'); - } else { - myGame.add.sprite(Math.random() * 3000, Math.random() * 3000, 'melon'); - } - } - myGame.camera.setPosition(100, 100); - myGame.camera.setSize(320, 320); - } - function update() { - myGame.camera.renderDebugInfo(600, 32); - if(myGame.input.keyboard.isDown(Phaser.Keyboard.LEFT)) { - myGame.camera.rotation -= 2; - } else if(myGame.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) { - myGame.camera.rotation += 2; - } - if(myGame.input.keyboard.isDown(Phaser.Keyboard.UP)) { - myGame.camera.scroll.y -= 4; - } else if(myGame.input.keyboard.isDown(Phaser.Keyboard.DOWN)) { - myGame.camera.scroll.y += 4; - } - } -})(); diff --git a/Tests/cameras/camera rotation.ts b/Tests/cameras/camera rotation.ts deleted file mode 100644 index 92d41cc44..000000000 --- a/Tests/cameras/camera rotation.ts +++ /dev/null @@ -1,61 +0,0 @@ -/// - -(function () { - - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update); - - function init() { - - myGame.world.setSize(3000, 3000); - - myGame.loader.addImageFile('car', 'assets/sprites/car.png'); - myGame.loader.addImageFile('melon', 'assets/sprites/melon.png'); - - myGame.loader.load(); - - } - - function create() { - - for (var i = 0; i < 1000; i++) - { - if (Math.random() > 0.5) - { - myGame.add.sprite(Math.random() * 3000, Math.random() * 3000, 'car'); - } - else - { - myGame.add.sprite(Math.random() * 3000, Math.random() * 3000, 'melon'); - } - } - - myGame.camera.setPosition(100, 100); - myGame.camera.setSize(320, 320); - - } - - function update() { - - myGame.camera.renderDebugInfo(600, 32); - - if (myGame.input.keyboard.isDown(Phaser.Keyboard.LEFT)) - { - myGame.camera.rotation -= 2; - } - else if (myGame.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) - { - myGame.camera.rotation += 2; - } - - if (myGame.input.keyboard.isDown(Phaser.Keyboard.UP)) - { - myGame.camera.scroll.y -= 4; - } - else if (myGame.input.keyboard.isDown(Phaser.Keyboard.DOWN)) - { - myGame.camera.scroll.y += 4; - } - - } - -})(); diff --git a/Tests/cameras/camera scale.js b/Tests/cameras/camera scale.js deleted file mode 100644 index d33ad8f62..000000000 --- a/Tests/cameras/camera scale.js +++ /dev/null @@ -1,45 +0,0 @@ -/// -(function () { - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update); - function init() { - myGame.world.setSize(2240, 2240); - myGame.loader.addImageFile('grid', 'assets/tests/debug-grid-1920x1920.png'); - myGame.loader.addImageFile('car', 'assets/sprites/car90.png'); - myGame.loader.load(); - } - var car; - var miniCam; - var bigCam; - function create() { - myGame.add.sprite(0, 0, 'grid'); - car = myGame.add.sprite(400, 300, 'car'); - myGame.camera.follow(car); - myGame.camera.deadzone = new Phaser.Rectangle(64, 64, myGame.stage.width - 128, myGame.stage.height - 128); - myGame.camera.setBounds(0, 0, myGame.world.width, myGame.world.height); - miniCam = myGame.add.camera(600, 32, 200, 200); - miniCam.follow(car, Phaser.Camera.STYLE_LOCKON); - miniCam.setBounds(0, 0, myGame.world.width, myGame.world.height); - miniCam.showBorder = true; - miniCam.scale.setTo(0.5, 0.5); - bigCam = myGame.add.camera(32, 32, 200, 200); - bigCam.follow(car, Phaser.Camera.STYLE_LOCKON); - bigCam.setBounds(0, 0, myGame.world.width, myGame.world.height); - bigCam.showBorder = true; - bigCam.scale.setTo(2, 2); - } - function update() { - car.velocity.x = 0; - car.velocity.y = 0; - car.angularVelocity = 0; - car.angularAcceleration = 0; - if(myGame.input.keyboard.isDown(Phaser.Keyboard.LEFT)) { - car.angularVelocity = -200; - } else if(myGame.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) { - car.angularVelocity = 200; - } - if(myGame.input.keyboard.isDown(Phaser.Keyboard.UP)) { - var motion = myGame.motion.velocityFromAngle(car.angle, 300); - car.velocity.copyFrom(motion); - } - } -})(); diff --git a/Tests/cameras/camera scale.ts b/Tests/cameras/camera scale.ts deleted file mode 100644 index 254d0165d..000000000 --- a/Tests/cameras/camera scale.ts +++ /dev/null @@ -1,71 +0,0 @@ -/// - -(function () { - - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update); - - function init() { - - myGame.world.setSize(2240, 2240); - - myGame.loader.addImageFile('grid', 'assets/tests/debug-grid-1920x1920.png'); - myGame.loader.addImageFile('car', 'assets/sprites/car90.png'); - - myGame.loader.load(); - - } - - var car: Phaser.Sprite; - var miniCam: Phaser.Camera; - var bigCam: Phaser.Camera; - - function create() { - - myGame.add.sprite(0, 0, 'grid'); - - car = myGame.add.sprite(400, 300, 'car'); - - myGame.camera.follow(car); - myGame.camera.deadzone = new Phaser.Rectangle(64, 64, myGame.stage.width - 128, myGame.stage.height - 128); - myGame.camera.setBounds(0, 0, myGame.world.width, myGame.world.height); - - miniCam = myGame.add.camera(600, 32, 200, 200); - miniCam.follow(car, Phaser.Camera.STYLE_LOCKON); - miniCam.setBounds(0, 0, myGame.world.width, myGame.world.height); - miniCam.showBorder = true; - miniCam.scale.setTo(0.5, 0.5); - - bigCam = myGame.add.camera(32, 32, 200, 200); - bigCam.follow(car, Phaser.Camera.STYLE_LOCKON); - bigCam.setBounds(0, 0, myGame.world.width, myGame.world.height); - bigCam.showBorder = true; - bigCam.scale.setTo(2, 2); - - } - - function update() { - - car.velocity.x = 0; - car.velocity.y = 0; - car.angularVelocity = 0; - car.angularAcceleration = 0; - - if (myGame.input.keyboard.isDown(Phaser.Keyboard.LEFT)) - { - car.angularVelocity = -200; - } - else if (myGame.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) - { - car.angularVelocity = 200; - } - - if (myGame.input.keyboard.isDown(Phaser.Keyboard.UP)) - { - var motion:Phaser.Point = myGame.motion.velocityFromAngle(car.angle, 300); - - car.velocity.copyFrom(motion); - } - - } - -})(); diff --git a/Tests/cameras/camera shadow.js b/Tests/cameras/camera shadow.js deleted file mode 100644 index b66262d2f..000000000 --- a/Tests/cameras/camera shadow.js +++ /dev/null @@ -1,47 +0,0 @@ -/// -(function () { - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update); - function init() { - myGame.world.setSize(2240, 2240); - myGame.loader.addImageFile('grid', 'assets/tests/debug-grid-1920x1920.png'); - myGame.loader.addImageFile('car', 'assets/sprites/car90.png'); - myGame.loader.load(); - } - var car; - var miniCam; - var bigCam; - function create() { - myGame.add.sprite(0, 0, 'grid'); - car = myGame.add.sprite(400, 300, 'car'); - myGame.camera.follow(car); - myGame.camera.deadzone = new Phaser.Rectangle(64, 64, myGame.stage.width - 128, myGame.stage.height - 128); - myGame.camera.setBounds(0, 0, myGame.world.width, myGame.world.height); - miniCam = myGame.add.camera(600, 32, 200, 200); - miniCam.follow(car, Phaser.Camera.STYLE_LOCKON); - miniCam.setBounds(0, 0, myGame.world.width, myGame.world.height); - miniCam.showBorder = true; - miniCam.scale.setTo(0.5, 0.5); - miniCam.showShadow = true; - bigCam = myGame.add.camera(32, 32, 200, 200); - bigCam.follow(car, Phaser.Camera.STYLE_LOCKON); - bigCam.setBounds(0, 0, myGame.world.width, myGame.world.height); - bigCam.showBorder = true; - bigCam.scale.setTo(2, 2); - bigCam.showShadow = true; - } - function update() { - car.velocity.x = 0; - car.velocity.y = 0; - car.angularVelocity = 0; - car.angularAcceleration = 0; - if(myGame.input.keyboard.isDown(Phaser.Keyboard.LEFT)) { - car.angularVelocity = -200; - } else if(myGame.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) { - car.angularVelocity = 200; - } - if(myGame.input.keyboard.isDown(Phaser.Keyboard.UP)) { - var motion = myGame.motion.velocityFromAngle(car.angle, 300); - car.velocity.copyFrom(motion); - } - } -})(); diff --git a/Tests/cameras/camera shadow.ts b/Tests/cameras/camera shadow.ts deleted file mode 100644 index 195e52273..000000000 --- a/Tests/cameras/camera shadow.ts +++ /dev/null @@ -1,73 +0,0 @@ -/// - -(function () { - - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update); - - function init() { - - myGame.world.setSize(2240, 2240); - - myGame.loader.addImageFile('grid', 'assets/tests/debug-grid-1920x1920.png'); - myGame.loader.addImageFile('car', 'assets/sprites/car90.png'); - - myGame.loader.load(); - - } - - var car: Phaser.Sprite; - var miniCam: Phaser.Camera; - var bigCam: Phaser.Camera; - - function create() { - - myGame.add.sprite(0, 0, 'grid'); - - car = myGame.add.sprite(400, 300, 'car'); - - myGame.camera.follow(car); - myGame.camera.deadzone = new Phaser.Rectangle(64, 64, myGame.stage.width - 128, myGame.stage.height - 128); - myGame.camera.setBounds(0, 0, myGame.world.width, myGame.world.height); - - miniCam = myGame.add.camera(600, 32, 200, 200); - miniCam.follow(car, Phaser.Camera.STYLE_LOCKON); - miniCam.setBounds(0, 0, myGame.world.width, myGame.world.height); - miniCam.showBorder = true; - miniCam.scale.setTo(0.5, 0.5); - miniCam.showShadow = true; - - bigCam = myGame.add.camera(32, 32, 200, 200); - bigCam.follow(car, Phaser.Camera.STYLE_LOCKON); - bigCam.setBounds(0, 0, myGame.world.width, myGame.world.height); - bigCam.showBorder = true; - bigCam.scale.setTo(2, 2); - bigCam.showShadow = true; - - } - - function update() { - - car.velocity.x = 0; - car.velocity.y = 0; - car.angularVelocity = 0; - car.angularAcceleration = 0; - - if (myGame.input.keyboard.isDown(Phaser.Keyboard.LEFT)) - { - car.angularVelocity = -200; - } - else if (myGame.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) - { - car.angularVelocity = 200; - } - - if (myGame.input.keyboard.isDown(Phaser.Keyboard.UP)) - { - var motion:Phaser.Point = myGame.motion.velocityFromAngle(car.angle, 300); - - car.velocity.copyFrom(motion); - } - - } - -})(); diff --git a/Tests/cameras/camera texture.js b/Tests/cameras/camera texture.js deleted file mode 100644 index 4a9cf23cd..000000000 --- a/Tests/cameras/camera texture.js +++ /dev/null @@ -1,46 +0,0 @@ -/// -(function () { - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update); - function init() { - myGame.world.setSize(2240, 2240); - myGame.loader.addImageFile('balls', 'assets/sprites/balls.png'); - myGame.loader.addImageFile('car', 'assets/sprites/car90.png'); - myGame.loader.load(); - } - var car; - var miniCam; - var bigCam; - function create() { - //myGame.add.sprite('grid', 0, 0); - car = myGame.add.sprite(400, 300, 'car'); - myGame.camera.setTexture('balls'); - myGame.camera.follow(car); - myGame.camera.deadzone = new Phaser.Rectangle(64, 64, myGame.stage.width - 128, myGame.stage.height - 128); - myGame.camera.setBounds(0, 0, myGame.world.width, myGame.world.height); - //miniCam = myGame.add.camera(600, 32, 200, 200); - //miniCam.follow(car, Camera.STYLE_LOCKON); - //miniCam.setBounds(0, 0, myGame.world.width, myGame.world.height); - //miniCam.showBorder = true; - //miniCam.scale.setTo(0.5, 0.5); - //bigCam = myGame.add.camera(32, 32, 200, 200); - //bigCam.follow(car, Camera.STYLE_LOCKON); - //bigCam.setBounds(0, 0, myGame.world.width, myGame.world.height); - //bigCam.showBorder = true; - //bigCam.scale.setTo(2, 2); - } - function update() { - car.velocity.x = 0; - car.velocity.y = 0; - car.angularVelocity = 0; - car.angularAcceleration = 0; - if(myGame.input.keyboard.isDown(Phaser.Keyboard.LEFT)) { - car.angularVelocity = -200; - } else if(myGame.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) { - car.angularVelocity = 200; - } - if(myGame.input.keyboard.isDown(Phaser.Keyboard.UP)) { - var motion = myGame.motion.velocityFromAngle(car.angle, 300); - car.velocity.copyFrom(motion); - } - } -})(); diff --git a/Tests/cameras/camera texture.ts b/Tests/cameras/camera texture.ts deleted file mode 100644 index aa5ba0ed9..000000000 --- a/Tests/cameras/camera texture.ts +++ /dev/null @@ -1,72 +0,0 @@ -/// - -(function () { - - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update); - - function init() { - - myGame.world.setSize(2240, 2240); - - myGame.loader.addImageFile('balls', 'assets/sprites/balls.png'); - myGame.loader.addImageFile('car', 'assets/sprites/car90.png'); - - myGame.loader.load(); - - } - - var car: Phaser.Sprite; - var miniCam: Phaser.Camera; - var bigCam: Phaser.Camera; - - function create() { - - //myGame.add.sprite('grid', 0, 0); - - car = myGame.add.sprite(400, 300, 'car'); - - myGame.camera.setTexture('balls'); - myGame.camera.follow(car); - myGame.camera.deadzone = new Phaser.Rectangle(64, 64, myGame.stage.width - 128, myGame.stage.height - 128); - myGame.camera.setBounds(0, 0, myGame.world.width, myGame.world.height); - - //miniCam = myGame.add.camera(600, 32, 200, 200); - //miniCam.follow(car, Camera.STYLE_LOCKON); - //miniCam.setBounds(0, 0, myGame.world.width, myGame.world.height); - //miniCam.showBorder = true; - //miniCam.scale.setTo(0.5, 0.5); - - //bigCam = myGame.add.camera(32, 32, 200, 200); - //bigCam.follow(car, Camera.STYLE_LOCKON); - //bigCam.setBounds(0, 0, myGame.world.width, myGame.world.height); - //bigCam.showBorder = true; - //bigCam.scale.setTo(2, 2); - - } - - function update() { - - car.velocity.x = 0; - car.velocity.y = 0; - car.angularVelocity = 0; - car.angularAcceleration = 0; - - if (myGame.input.keyboard.isDown(Phaser.Keyboard.LEFT)) - { - car.angularVelocity = -200; - } - else if (myGame.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) - { - car.angularVelocity = 200; - } - - if (myGame.input.keyboard.isDown(Phaser.Keyboard.UP)) - { - var motion:Phaser.Point = myGame.motion.velocityFromAngle(car.angle, 300); - - car.velocity.copyFrom(motion); - } - - } - -})(); diff --git a/Tests/cameras/focus on.js b/Tests/cameras/focus on.js deleted file mode 100644 index e2aa58109..000000000 --- a/Tests/cameras/focus on.js +++ /dev/null @@ -1,36 +0,0 @@ -/// -(function () { - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update); - function init() { - myGame.world.setSize(1920, 1920); - myGame.loader.addImageFile('grid', 'assets/tests/debug-grid-1920x1920.png'); - myGame.loader.addImageFile('melon', 'assets/sprites/melon.png'); - myGame.loader.addImageFile('carrot', 'assets/sprites/carrot.png'); - myGame.loader.load(); - } - var melon; - function create() { - // locked to the camera - myGame.add.sprite(0, 0, 'grid'); - melon = myGame.add.sprite(600, 650, 'melon'); - melon.scrollFactor.setTo(1.5, 1.5); - // scrolls x2 camera speed - for(var i = 0; i < 100; i++) { - var tempSprite = myGame.add.sprite(Math.random() * myGame.world.width, Math.random() * myGame.world.height, 'carrot'); - tempSprite.scrollFactor.setTo(2, 2); - } - } - function update() { - myGame.camera.renderDebugInfo(32, 32); - melon.renderDebugInfo(200, 32); - if(myGame.input.keyboard.isDown(Phaser.Keyboard.LEFT)) { - myGame.camera.focusOnXY(640, 640); - } else if(myGame.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) { - myGame.camera.focusOnXY(1234, 800); - } else if(myGame.input.keyboard.isDown(Phaser.Keyboard.UP)) { - myGame.camera.focusOnXY(50, 200); - } else if(myGame.input.keyboard.isDown(Phaser.Keyboard.DOWN)) { - myGame.camera.focusOnXY(1700, 1700); - } - } -})(); diff --git a/Tests/cameras/focus on.ts b/Tests/cameras/focus on.ts deleted file mode 100644 index 6807a0b9d..000000000 --- a/Tests/cameras/focus on.ts +++ /dev/null @@ -1,62 +0,0 @@ -/// - -(function () { - - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update); - - function init() { - - myGame.world.setSize(1920, 1920); - - myGame.loader.addImageFile('grid', 'assets/tests/debug-grid-1920x1920.png'); - myGame.loader.addImageFile('melon', 'assets/sprites/melon.png'); - myGame.loader.addImageFile('carrot', 'assets/sprites/carrot.png'); - - myGame.loader.load(); - - } - - var melon: Phaser.Sprite; - - function create() { - - // locked to the camera - myGame.add.sprite(0, 0, 'grid'); - - melon = myGame.add.sprite(600, 650, 'melon'); - melon.scrollFactor.setTo(1.5, 1.5); - - // scrolls x2 camera speed - for (var i = 0; i < 100; i++) - { - var tempSprite = myGame.add.sprite(Math.random() * myGame.world.width, Math.random() * myGame.world.height, 'carrot'); - tempSprite.scrollFactor.setTo(2, 2); - } - - } - - function update() { - - myGame.camera.renderDebugInfo(32, 32); - melon.renderDebugInfo(200, 32); - - if (myGame.input.keyboard.isDown(Phaser.Keyboard.LEFT)) - { - myGame.camera.focusOnXY(640, 640); - } - else if (myGame.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) - { - myGame.camera.focusOnXY(1234, 800); - } - else if (myGame.input.keyboard.isDown(Phaser.Keyboard.UP)) - { - myGame.camera.focusOnXY(50, 200); - } - else if (myGame.input.keyboard.isDown(Phaser.Keyboard.DOWN)) - { - myGame.camera.focusOnXY(1700, 1700); - } - - } - -})(); diff --git a/Tests/cameras/follow deadzone.js b/Tests/cameras/follow deadzone.js deleted file mode 100644 index 3f748921e..000000000 --- a/Tests/cameras/follow deadzone.js +++ /dev/null @@ -1,36 +0,0 @@ -/// -(function () { - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update); - function init() { - myGame.world.setSize(2240, 2240); - myGame.loader.addImageFile('grid', 'assets/tests/debug-grid-1920x1920.png'); - myGame.loader.addImageFile('car', 'assets/sprites/car90.png'); - myGame.loader.load(); - } - var car; - function create() { - myGame.add.sprite(0, 0, 'grid'); - car = myGame.add.sprite(400, 300, 'car'); - myGame.camera.follow(car); - // Here we'll set our own custom deadzone which is 64px smaller than the stage size on all sides - myGame.camera.deadzone = new Phaser.Rectangle(64, 64, myGame.stage.width - 128, myGame.stage.height - 128); - myGame.camera.setBounds(0, 0, myGame.world.width, myGame.world.height); - } - function update() { - myGame.camera.renderDebugInfo(32, 32); - car.renderDebugInfo(200, 32); - car.velocity.x = 0; - car.velocity.y = 0; - car.angularVelocity = 0; - car.angularAcceleration = 0; - if(myGame.input.keyboard.isDown(Phaser.Keyboard.LEFT)) { - car.angularVelocity = -200; - } else if(myGame.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) { - car.angularVelocity = 200; - } - if(myGame.input.keyboard.isDown(Phaser.Keyboard.UP)) { - var motion = myGame.motion.velocityFromAngle(car.angle, 300); - car.velocity.copyFrom(motion); - } - } -})(); diff --git a/Tests/cameras/follow deadzone.ts b/Tests/cameras/follow deadzone.ts deleted file mode 100644 index 6dca503cb..000000000 --- a/Tests/cameras/follow deadzone.ts +++ /dev/null @@ -1,61 +0,0 @@ -/// - -(function () { - - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update); - - function init() { - - myGame.world.setSize(2240, 2240); - - myGame.loader.addImageFile('grid', 'assets/tests/debug-grid-1920x1920.png'); - myGame.loader.addImageFile('car', 'assets/sprites/car90.png'); - - myGame.loader.load(); - - } - - var car: Phaser.Sprite; - - function create() { - - myGame.add.sprite(0, 0, 'grid'); - - car = myGame.add.sprite(400, 300, 'car'); - - myGame.camera.follow(car); - // Here we'll set our own custom deadzone which is 64px smaller than the stage size on all sides - myGame.camera.deadzone = new Phaser.Rectangle(64, 64, myGame.stage.width - 128, myGame.stage.height - 128); - myGame.camera.setBounds(0, 0, myGame.world.width, myGame.world.height); - - } - - function update() { - - myGame.camera.renderDebugInfo(32, 32); - car.renderDebugInfo(200, 32); - - car.velocity.x = 0; - car.velocity.y = 0; - car.angularVelocity = 0; - car.angularAcceleration = 0; - - if (myGame.input.keyboard.isDown(Phaser.Keyboard.LEFT)) - { - car.angularVelocity = -200; - } - else if (myGame.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) - { - car.angularVelocity = 200; - } - - if (myGame.input.keyboard.isDown(Phaser.Keyboard.UP)) - { - var motion:Phaser.Point = myGame.motion.velocityFromAngle(car.angle, 300); - - car.velocity.copyFrom(motion); - } - - } - -})(); diff --git a/Tests/cameras/follow sprite.js b/Tests/cameras/follow sprite.js deleted file mode 100644 index e0a1eaaaa..000000000 --- a/Tests/cameras/follow sprite.js +++ /dev/null @@ -1,34 +0,0 @@ -/// -(function () { - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update); - function init() { - myGame.world.setSize(1920, 1920); - myGame.loader.addImageFile('grid', 'assets/tests/debug-grid-1920x1920.png'); - myGame.loader.addImageFile('car', 'assets/sprites/car90.png'); - myGame.loader.load(); - } - var car; - function create() { - myGame.add.sprite(0, 0, 'grid'); - car = myGame.add.sprite(400, 300, 'car'); - myGame.camera.follow(car); - myGame.onRenderCallback = render; - } - function update() { - car.velocity.x = 0; - car.velocity.y = 0; - car.angularVelocity = 0; - if(myGame.input.keyboard.isDown(Phaser.Keyboard.LEFT)) { - car.angularVelocity = -200; - } else if(myGame.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) { - car.angularVelocity = 200; - } - if(myGame.input.keyboard.isDown(Phaser.Keyboard.UP)) { - car.velocity.copyFrom(myGame.motion.velocityFromAngle(car.angle, 300)); - } - } - function render() { - myGame.camera.renderDebugInfo(32, 32); - car.renderDebugInfo(200, 32); - } -})(); diff --git a/Tests/cameras/follow sprite.ts b/Tests/cameras/follow sprite.ts deleted file mode 100644 index 3b3669c5a..000000000 --- a/Tests/cameras/follow sprite.ts +++ /dev/null @@ -1,62 +0,0 @@ -/// - -(function () { - - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update); - - function init() { - - myGame.world.setSize(1920, 1920); - - myGame.loader.addImageFile('grid', 'assets/tests/debug-grid-1920x1920.png'); - myGame.loader.addImageFile('car', 'assets/sprites/car90.png'); - - myGame.loader.load(); - - } - - var car; - - function create() { - - myGame.add.sprite(0, 0, 'grid'); - - car = myGame.add.sprite(400, 300, 'car'); - - myGame.camera.follow(car); - - myGame.onRenderCallback = render; - - } - - function update() { - - - car.velocity.x = 0; - car.velocity.y = 0; - car.angularVelocity = 0; - - if (myGame.input.keyboard.isDown(Phaser.Keyboard.LEFT)) - { - car.angularVelocity = -200; - } - else if (myGame.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) - { - car.angularVelocity = 200; - } - - if (myGame.input.keyboard.isDown(Phaser.Keyboard.UP)) - { - car.velocity.copyFrom(myGame.motion.velocityFromAngle(car.angle, 300)); - } - - } - - function render() { - - myGame.camera.renderDebugInfo(32, 32); - car.renderDebugInfo(200, 32); - - } - -})(); diff --git a/Tests/cameras/follow topdown.js b/Tests/cameras/follow topdown.js deleted file mode 100644 index e6cbe4590..000000000 --- a/Tests/cameras/follow topdown.js +++ /dev/null @@ -1,34 +0,0 @@ -/// -(function () { - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update); - function init() { - myGame.world.setSize(2240, 2240); - myGame.loader.addImageFile('grid', 'assets/tests/debug-grid-1920x1920.png'); - myGame.loader.addImageFile('car', 'assets/sprites/car90.png'); - myGame.loader.load(); - } - var car; - function create() { - myGame.add.sprite(0, 0, 'grid'); - car = myGame.add.sprite(400, 300, 'car'); - myGame.camera.follow(car, Phaser.Camera.STYLE_TOPDOWN); - myGame.camera.setBounds(0, 0, myGame.world.width, myGame.world.height); - } - function update() { - myGame.camera.renderDebugInfo(32, 32); - car.renderDebugInfo(200, 32); - car.velocity.x = 0; - car.velocity.y = 0; - car.angularVelocity = 0; - car.angularAcceleration = 0; - if(myGame.input.keyboard.isDown(Phaser.Keyboard.LEFT)) { - car.angularVelocity = -200; - } else if(myGame.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) { - car.angularVelocity = 200; - } - if(myGame.input.keyboard.isDown(Phaser.Keyboard.UP)) { - var motion = myGame.motion.velocityFromAngle(car.angle, 300); - car.velocity.copyFrom(motion); - } - } -})(); diff --git a/Tests/cameras/follow topdown.ts b/Tests/cameras/follow topdown.ts deleted file mode 100644 index 382187dee..000000000 --- a/Tests/cameras/follow topdown.ts +++ /dev/null @@ -1,59 +0,0 @@ -/// - -(function () { - - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update); - - function init() { - - myGame.world.setSize(2240, 2240); - - myGame.loader.addImageFile('grid', 'assets/tests/debug-grid-1920x1920.png'); - myGame.loader.addImageFile('car', 'assets/sprites/car90.png'); - - myGame.loader.load(); - - } - - var car: Phaser.Sprite; - - function create() { - - myGame.add.sprite(0, 0, 'grid'); - - car = myGame.add.sprite(400, 300, 'car'); - - myGame.camera.follow(car, Phaser.Camera.STYLE_TOPDOWN); - myGame.camera.setBounds(0, 0, myGame.world.width, myGame.world.height); - - } - - function update() { - - myGame.camera.renderDebugInfo(32, 32); - car.renderDebugInfo(200, 32); - - car.velocity.x = 0; - car.velocity.y = 0; - car.angularVelocity = 0; - car.angularAcceleration = 0; - - if (myGame.input.keyboard.isDown(Phaser.Keyboard.LEFT)) - { - car.angularVelocity = -200; - } - else if (myGame.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) - { - car.angularVelocity = 200; - } - - if (myGame.input.keyboard.isDown(Phaser.Keyboard.UP)) - { - var motion:Phaser.Point = myGame.motion.velocityFromAngle(car.angle, 300); - - car.velocity.copyFrom(motion); - } - - } - -})(); diff --git a/Tests/cameras/multicam1.js b/Tests/cameras/multicam1.js deleted file mode 100644 index 42bede024..000000000 --- a/Tests/cameras/multicam1.js +++ /dev/null @@ -1,44 +0,0 @@ -/// -(function () { - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update); - function init() { - myGame.world.setSize(3000, 3000); - myGame.loader.addImageFile('car', 'assets/sprites/car.png'); - myGame.loader.addImageFile('coin', 'assets/sprites/coin.png'); - myGame.loader.addImageFile('melon', 'assets/sprites/melon.png'); - myGame.loader.load(); - } - var cam2; - function create() { - for(var i = 0; i < 1000; i++) { - myGame.add.sprite(Math.random() * 3000, Math.random() * 3000, 'melon'); - } - myGame.camera.setPosition(16, 80); - myGame.camera.setSize(320, 320); - myGame.camera.showBorder = true; - myGame.camera.borderColor = 'rgb(255,0,0)'; - cam2 = myGame.add.camera(380, 100, 400, 400); - //cam2.transparent = false; - //cam2.backgroundColor = 'rgb(20,20,20)'; - cam2.showBorder = true; - cam2.borderColor = 'rgb(255,255,0)'; - } - function update() { - myGame.camera.renderDebugInfo(16, 16); - cam2.renderDebugInfo(200, 16); - if(myGame.input.keyboard.isDown(Phaser.Keyboard.LEFT)) { - myGame.camera.scroll.x -= 4; - cam2.scroll.x -= 2; - } else if(myGame.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) { - myGame.camera.scroll.x += 4; - cam2.scroll.x += 2; - } - if(myGame.input.keyboard.isDown(Phaser.Keyboard.UP)) { - myGame.camera.scroll.y -= 4; - cam2.scroll.y -= 2; - } else if(myGame.input.keyboard.isDown(Phaser.Keyboard.DOWN)) { - myGame.camera.scroll.y += 4; - cam2.scroll.y += 2; - } - } -})(); diff --git a/Tests/cameras/multicam1.ts b/Tests/cameras/multicam1.ts deleted file mode 100644 index b408b2244..000000000 --- a/Tests/cameras/multicam1.ts +++ /dev/null @@ -1,70 +0,0 @@ -/// - -(function () { - - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update); - - function init() { - - myGame.world.setSize(3000, 3000); - - myGame.loader.addImageFile('car', 'assets/sprites/car.png'); - myGame.loader.addImageFile('coin', 'assets/sprites/coin.png'); - myGame.loader.addImageFile('melon', 'assets/sprites/melon.png'); - - myGame.loader.load(); - - } - - var cam2: Phaser.Camera; - - function create() { - - for (var i = 0; i < 1000; i++) - { - myGame.add.sprite(Math.random() * 3000, Math.random() * 3000, 'melon'); - } - - myGame.camera.setPosition(16, 80); - myGame.camera.setSize(320, 320); - myGame.camera.showBorder = true; - myGame.camera.borderColor = 'rgb(255,0,0)'; - - cam2 = myGame.add.camera(380, 100, 400, 400); - //cam2.transparent = false; - //cam2.backgroundColor = 'rgb(20,20,20)'; - cam2.showBorder = true; - cam2.borderColor = 'rgb(255,255,0)'; - - } - - function update() { - - myGame.camera.renderDebugInfo(16, 16); - cam2.renderDebugInfo(200, 16); - - if (myGame.input.keyboard.isDown(Phaser.Keyboard.LEFT)) - { - myGame.camera.scroll.x -= 4; - cam2.scroll.x -= 2; - } - else if (myGame.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) - { - myGame.camera.scroll.x += 4; - cam2.scroll.x += 2; - } - - if (myGame.input.keyboard.isDown(Phaser.Keyboard.UP)) - { - myGame.camera.scroll.y -= 4; - cam2.scroll.y -= 2; - } - else if (myGame.input.keyboard.isDown(Phaser.Keyboard.DOWN)) - { - myGame.camera.scroll.y += 4; - cam2.scroll.y += 2; - } - - } - -})(); diff --git a/Tests/cameras/scroll factor.js b/Tests/cameras/scroll factor.js deleted file mode 100644 index 7dbc31dbb..000000000 --- a/Tests/cameras/scroll factor.js +++ /dev/null @@ -1,37 +0,0 @@ -/// -(function () { - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update); - function init() { - myGame.world.setSize(1920, 1200); - myGame.loader.addImageFile('backdrop', 'assets/pics/remember-me.jpg'); - myGame.loader.addImageFile('melon', 'assets/sprites/melon.png'); - myGame.loader.addImageFile('carrot', 'assets/sprites/carrot.png'); - myGame.loader.load(); - } - var melon; - function create() { - // scrolls in time with the camera - myGame.add.sprite(0, 0, 'backdrop'); - melon = myGame.add.sprite(600, 650, 'melon'); - melon.scrollFactor.setTo(1.5, 1.5); - // scrolls x2 camera speed - for(var i = 0; i < 100; i++) { - var tempSprite = myGame.add.sprite(Math.random() * myGame.world.width, Math.random() * myGame.world.height, 'carrot'); - tempSprite.scrollFactor.setTo(2, 2); - } - } - function update() { - myGame.camera.renderDebugInfo(32, 32); - melon.renderDebugInfo(200, 32); - if(myGame.input.keyboard.isDown(Phaser.Keyboard.LEFT)) { - myGame.camera.scroll.x -= 1; - } else if(myGame.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) { - myGame.camera.scroll.x += 1; - } - if(myGame.input.keyboard.isDown(Phaser.Keyboard.UP)) { - myGame.camera.scroll.y -= 1; - } else if(myGame.input.keyboard.isDown(Phaser.Keyboard.DOWN)) { - myGame.camera.scroll.y += 1; - } - } -})(); diff --git a/Tests/cameras/scroll factor.ts b/Tests/cameras/scroll factor.ts deleted file mode 100644 index df4fc3b6c..000000000 --- a/Tests/cameras/scroll factor.ts +++ /dev/null @@ -1,63 +0,0 @@ -/// - -(function () { - - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update); - - function init() { - - myGame.world.setSize(1920, 1200); - - myGame.loader.addImageFile('backdrop', 'assets/pics/remember-me.jpg'); - myGame.loader.addImageFile('melon', 'assets/sprites/melon.png'); - myGame.loader.addImageFile('carrot', 'assets/sprites/carrot.png'); - - myGame.loader.load(); - - } - - var melon: Phaser.Sprite; - - function create() { - - // scrolls in time with the camera - myGame.add.sprite(0, 0, 'backdrop'); - - melon = myGame.add.sprite(600, 650, 'melon'); - melon.scrollFactor.setTo(1.5, 1.5); - - // scrolls x2 camera speed - for (var i = 0; i < 100; i++) - { - var tempSprite = myGame.add.sprite(Math.random() * myGame.world.width, Math.random() * myGame.world.height, 'carrot'); - tempSprite.scrollFactor.setTo(2, 2); - } - - } - - function update() { - - myGame.camera.renderDebugInfo(32, 32); - melon.renderDebugInfo(200, 32); - - if (myGame.input.keyboard.isDown(Phaser.Keyboard.LEFT)) - { - myGame.camera.scroll.x -= 1; - } - else if (myGame.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) - { - myGame.camera.scroll.x += 1; - } - - if (myGame.input.keyboard.isDown(Phaser.Keyboard.UP)) - { - myGame.camera.scroll.y -= 1; - } - else if (myGame.input.keyboard.isDown(Phaser.Keyboard.DOWN)) - { - myGame.camera.scroll.y += 1; - } - - } - -})(); diff --git a/Tests/collision/collide sprites.js b/Tests/collision/collide sprites.js deleted file mode 100644 index fe82a9b65..000000000 --- a/Tests/collision/collide sprites.js +++ /dev/null @@ -1,35 +0,0 @@ -/// -(function () { - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update); - function init() { - myGame.loader.addImageFile('car', 'assets/sprites/car90.png'); - myGame.loader.addImageFile('melon', 'assets/sprites/melon.png'); - myGame.loader.load(); - } - var car; - var melon; - function create() { - car = myGame.add.sprite(100, 300, 'car'); - melon = myGame.add.sprite(200, 310, 'melon'); - car.name = 'car'; - melon.name = 'melon'; - } - function update() { - car.renderDebugInfo(16, 16); - car.velocity.x = 0; - car.velocity.y = 0; - car.angularVelocity = 0; - if(myGame.input.keyboard.isDown(Phaser.Keyboard.LEFT)) { - car.angularVelocity = -200; - } else if(myGame.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) { - car.angularVelocity = 200; - } - if(myGame.input.keyboard.isDown(Phaser.Keyboard.UP)) { - car.velocity.copyFrom(myGame.motion.velocityFromAngle(car.angle, 200)); - } - myGame.collide(car, melon, collides); - } - function collides(a, b) { - console.log('Collision!!!!!'); - } -})(); diff --git a/Tests/collision/collide sprites.ts b/Tests/collision/collide sprites.ts deleted file mode 100644 index 1bcf3622a..000000000 --- a/Tests/collision/collide sprites.ts +++ /dev/null @@ -1,61 +0,0 @@ -/// - -(function () { - - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update); - - function init() { - - myGame.loader.addImageFile('car', 'assets/sprites/car90.png'); - myGame.loader.addImageFile('melon', 'assets/sprites/melon.png'); - - myGame.loader.load(); - - } - - var car: Phaser.Sprite; - var melon: Phaser.Sprite; - - function create() { - - car = myGame.add.sprite(100, 300, 'car'); - melon = myGame.add.sprite(200, 310, 'melon'); - - car.name = 'car'; - melon.name = 'melon'; - - } - - function update() { - - car.renderDebugInfo(16, 16); - - car.velocity.x = 0; - car.velocity.y = 0; - car.angularVelocity = 0; - - if (myGame.input.keyboard.isDown(Phaser.Keyboard.LEFT)) - { - car.angularVelocity = -200; - } - else if (myGame.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) - { - car.angularVelocity = 200; - } - - if (myGame.input.keyboard.isDown(Phaser.Keyboard.UP)) - { - car.velocity.copyFrom(myGame.motion.velocityFromAngle(car.angle, 200)); - } - - myGame.collide(car, melon, collides); - - } - - function collides(a, b) { - - console.log('Collision!!!!!'); - - } - -})(); diff --git a/Tests/collision/falling balls.js b/Tests/collision/falling balls.js deleted file mode 100644 index 0f650c7ca..000000000 --- a/Tests/collision/falling balls.js +++ /dev/null @@ -1,45 +0,0 @@ -/// -(function () { - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update); - function init() { - myGame.loader.addImageFile('ball0', 'assets/sprites/yellow_ball.png'); - myGame.loader.addImageFile('ball1', 'assets/sprites/aqua_ball.png'); - myGame.loader.addImageFile('ball2', 'assets/sprites/blue_ball.png'); - myGame.loader.addImageFile('ball3', 'assets/sprites/green_ball.png'); - myGame.loader.addImageFile('ball4', 'assets/sprites/red_ball.png'); - myGame.loader.addImageFile('ball5', 'assets/sprites/purple_ball.png'); - myGame.loader.addImageFile('atari', 'assets/sprites/atari130xe.png'); - myGame.loader.load(); - } - var atari; - var balls; - function create() { - atari = myGame.add.sprite(300, 450, 'atari'); - atari.immovable = true; - balls = myGame.add.group(); - for(var i = 0; i < 100; i++) { - var tempBall = new Phaser.Sprite(myGame, Math.random() * myGame.stage.width, -32, 'ball' + Math.round(Math.random() * 5)); - tempBall.velocity.y = 100 + Math.random() * 150; - tempBall.elasticity = 0.9; - balls.add(tempBall); - } - } - function update() { - atari.velocity.x = 0; - if(myGame.input.keyboard.isDown(Phaser.Keyboard.LEFT)) { - atari.velocity.x = -400; - } else if(myGame.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) { - atari.velocity.x = 400; - } - balls.forEach(checkOffScreen, false); - myGame.collide(atari, balls); - } - function checkOffScreen(ball) { - if(ball.y < -32 || ball.y > myGame.stage.height || ball.x < 0 || ball.x > myGame.stage.width) { - ball.x = Math.random() * myGame.stage.width; - ball.y = -32; - ball.velocity.x = 0; - ball.velocity.y = 100 + Math.random() * 150; - } - } -})(); diff --git a/Tests/collision/falling balls.ts b/Tests/collision/falling balls.ts deleted file mode 100644 index 90033cb33..000000000 --- a/Tests/collision/falling balls.ts +++ /dev/null @@ -1,72 +0,0 @@ -/// - -(function () { - - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update); - - function init() { - - myGame.loader.addImageFile('ball0', 'assets/sprites/yellow_ball.png'); - myGame.loader.addImageFile('ball1', 'assets/sprites/aqua_ball.png'); - myGame.loader.addImageFile('ball2', 'assets/sprites/blue_ball.png'); - myGame.loader.addImageFile('ball3', 'assets/sprites/green_ball.png'); - myGame.loader.addImageFile('ball4', 'assets/sprites/red_ball.png'); - myGame.loader.addImageFile('ball5', 'assets/sprites/purple_ball.png'); - myGame.loader.addImageFile('atari', 'assets/sprites/atari130xe.png'); - - myGame.loader.load(); - - } - - var atari: Phaser.Sprite; - var balls: Phaser.Group; - - function create() { - - atari = myGame.add.sprite(300, 450, 'atari'); - atari.immovable = true; - - balls = myGame.add.group(); - - for (var i = 0; i < 100; i++) - { - var tempBall: Phaser.Sprite = new Phaser.Sprite(myGame, Math.random() * myGame.stage.width, -32, 'ball' + Math.round(Math.random() * 5)); - tempBall.velocity.y = 100 + Math.random() * 150; - tempBall.elasticity = 0.9; - balls.add(tempBall); - } - - } - - function update() { - - atari.velocity.x = 0; - - if (myGame.input.keyboard.isDown(Phaser.Keyboard.LEFT)) - { - atari.velocity.x = -400; - } - else if (myGame.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) - { - atari.velocity.x = 400; - } - - balls.forEach(checkOffScreen, false); - - myGame.collide(atari, balls); - - } - - function checkOffScreen(ball:Phaser.Sprite) { - - if (ball.y < -32 || ball.y > myGame.stage.height || ball.x < 0 || ball.x > myGame.stage.width) - { - ball.x = Math.random() * myGame.stage.width; - ball.y = -32; - ball.velocity.x = 0; - ball.velocity.y = 100 + Math.random() * 150; - } - - } - -})(); diff --git a/Tests/collision/mask animation 1.js b/Tests/collision/mask animation 1.js deleted file mode 100644 index d2643a361..000000000 --- a/Tests/collision/mask animation 1.js +++ /dev/null @@ -1,31 +0,0 @@ -/// -(function () { - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update); - function init() { - myGame.loader.addImageFile('card', 'assets/sprites/mana_card.png'); - myGame.loader.addTextureAtlas('bot', 'assets/sprites/running_bot.png', 'assets/sprites/running_bot.json'); - myGame.loader.load(); - } - var card; - var bot; - function create() { - card = myGame.add.sprite(200, 220, 'card'); - bot = myGame.add.sprite(myGame.stage.width - 100, 300, 'bot'); - // The collision mask is much thinner than the animated sprite - bot.collisionMask.offset.x = 16; - bot.collisionMask.width = 32; - bot.renderDebug = true; - bot.animations.add('run'); - bot.animations.play('run', 10, true); - bot.velocity.x = -150; - } - function update() { - if(bot.x < -bot.width) { - bot.x = myGame.stage.width; - bot.velocity.x = -150; - card.x = 200; - card.velocity.x = 0; - } - myGame.collide(card, bot); - } -})(); diff --git a/Tests/collision/mask animation 1.ts b/Tests/collision/mask animation 1.ts deleted file mode 100644 index 2a7ea22b9..000000000 --- a/Tests/collision/mask animation 1.ts +++ /dev/null @@ -1,50 +0,0 @@ -/// - -(function () { - - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update); - - function init() { - - myGame.loader.addImageFile('card', 'assets/sprites/mana_card.png'); - myGame.loader.addTextureAtlas('bot', 'assets/sprites/running_bot.png', 'assets/sprites/running_bot.json'); - myGame.loader.load(); - - } - - var card: Phaser.Sprite; - var bot: Phaser.Sprite; - - function create() { - - card = myGame.add.sprite(200, 220, 'card'); - - bot = myGame.add.sprite(myGame.stage.width - 100, 300, 'bot'); - - // The collision mask is much thinner than the animated sprite - bot.collisionMask.offset.x = 16; - bot.collisionMask.width = 32; - bot.renderDebug = true; - - bot.animations.add('run'); - bot.animations.play('run', 10, true); - - bot.velocity.x = -150; - - } - - function update() { - - if (bot.x < -bot.width) - { - bot.x = myGame.stage.width; - bot.velocity.x = -150; - card.x = 200; - card.velocity.x = 0; - } - - myGame.collide(card, bot); - - } - -})(); diff --git a/Tests/collision/mask test 1.js b/Tests/collision/mask test 1.js deleted file mode 100644 index 59b3738c6..000000000 --- a/Tests/collision/mask test 1.js +++ /dev/null @@ -1,38 +0,0 @@ -/// -(function () { - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update); - function init() { - myGame.loader.addImageFile('atari1', 'assets/sprites/atari130xe.png'); - myGame.loader.addImageFile('atari2', 'assets/sprites/atari800xl.png'); - myGame.loader.load(); - } - var atari1; - var atari2; - var atari3; - function create() { - atari1 = myGame.add.sprite(270, 100, 'atari1'); - atari2 = myGame.add.sprite(400, 400, 'atari2'); - atari3 = myGame.add.sprite(0, 440, 'atari1'); - atari1.collisionMask.height = 16; - atari3.collisionMask.width = 16; - atari1.elasticity = 0.5; - atari3.elasticity = 0.5; - atari2.immovable = true; - atari1.renderDebug = true; - atari2.renderDebug = true; - atari3.renderDebug = true; - myGame.input.onTap.addOnce(startDrop, this); - } - function startDrop() { - atari1.velocity.y = 100; - atari3.velocity.x = 100; - } - function update() { - myGame.collide(myGame.world.group); - } - function collides(a, b) { - console.log('Collision!!!!!'); - } - function render() { - } -})(); diff --git a/Tests/collision/mask test 1.ts b/Tests/collision/mask test 1.ts deleted file mode 100644 index 865c8a9de..000000000 --- a/Tests/collision/mask test 1.ts +++ /dev/null @@ -1,64 +0,0 @@ -/// - -(function () { - - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update); - - function init() { - - myGame.loader.addImageFile('atari1', 'assets/sprites/atari130xe.png'); - myGame.loader.addImageFile('atari2', 'assets/sprites/atari800xl.png'); - - myGame.loader.load(); - - } - - var atari1: Phaser.Sprite; - var atari2: Phaser.Sprite; - var atari3: Phaser.Sprite; - - function create() { - - atari1 = myGame.add.sprite(270, 100, 'atari1'); - atari2 = myGame.add.sprite(400, 400, 'atari2'); - atari3 = myGame.add.sprite(0, 440, 'atari1'); - - atari1.collisionMask.height = 16; - atari3.collisionMask.width = 16; - - atari1.elasticity = 0.5; - atari3.elasticity = 0.5; - - atari2.immovable = true; - - atari1.renderDebug = true; - atari2.renderDebug = true; - atari3.renderDebug = true; - - myGame.input.onTap.addOnce(startDrop, this); - - } - - function startDrop() { - - atari1.velocity.y = 100; - atari3.velocity.x = 100; - - } - - function update() { - - myGame.collide(myGame.world.group); - - } - - function collides(a, b) { - - console.log('Collision!!!!!'); - - } - - function render() { - } - -})(); diff --git a/Tests/collision/mask test 2.js b/Tests/collision/mask test 2.js deleted file mode 100644 index 5f7627ce4..000000000 --- a/Tests/collision/mask test 2.js +++ /dev/null @@ -1,35 +0,0 @@ -/// -(function () { - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update); - function init() { - myGame.loader.addImageFile('atari1', 'assets/sprites/atari130xe.png'); - myGame.loader.addImageFile('atari2', 'assets/sprites/atari800xl.png'); - myGame.loader.load(); - } - var atari1; - var atari2; - function create() { - atari1 = myGame.add.sprite(400, 100, 'atari1'); - atari2 = myGame.add.sprite(400, 400, 'atari2'); - //atari1.collisionMask.createCircle(64); - //atari1.rotation = 45; - atari1.elasticity = 0.5; - //atari2.collisionMask.createCircle(64); - atari2.immovable = true; - atari1.renderDebug = true; - atari2.renderDebug = true; - myGame.input.onTap.addOnce(startDrop, this); - } - function startDrop() { - atari1.velocity.y = 100; - } - function update() { - myGame.collide(myGame.world.group); - } - function collides(a, b) { - console.log('Collision!!!!!'); - } - function render() { - //atari1.ren - } -})(); diff --git a/Tests/collision/mask test 2.ts b/Tests/collision/mask test 2.ts deleted file mode 100644 index 44f0da2cc..000000000 --- a/Tests/collision/mask test 2.ts +++ /dev/null @@ -1,62 +0,0 @@ -/// - -(function () { - - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update); - - function init() { - - myGame.loader.addImageFile('atari1', 'assets/sprites/atari130xe.png'); - myGame.loader.addImageFile('atari2', 'assets/sprites/atari800xl.png'); - - myGame.loader.load(); - - } - - var atari1: Phaser.Sprite; - var atari2: Phaser.Sprite; - - function create() { - - atari1 = myGame.add.sprite(400, 100, 'atari1'); - atari2 = myGame.add.sprite(400, 400, 'atari2'); - - //atari1.collisionMask.createCircle(64); - //atari1.rotation = 45; - atari1.elasticity = 0.5; - - //atari2.collisionMask.createCircle(64); - atari2.immovable = true; - - atari1.renderDebug = true; - atari2.renderDebug = true; - - myGame.input.onTap.addOnce(startDrop, this); - - } - - function startDrop() { - - atari1.velocity.y = 100; - - } - - function update() { - - myGame.collide(myGame.world.group); - - } - - function collides(a, b) { - - console.log('Collision!!!!!'); - - } - - function render() { - - //atari1.ren - - } - -})(); diff --git a/Tests/geometry/circle.js b/Tests/geometry/circle.js deleted file mode 100644 index 752987a5f..000000000 --- a/Tests/geometry/circle.js +++ /dev/null @@ -1,19 +0,0 @@ -/// -(function () { - var myGame = new Phaser.Game(this, 'game', 800, 600, null, create, update); - var circle; - var floor; - function create() { - circle = myGame.add.geomSprite(200, 0); - circle.createCircle(64); - circle.acceleration.y = 100; - circle.elasticity = 0.8; - // A simple floor - floor = myGame.add.geomSprite(0, 550); - floor.createRectangle(800, 50); - floor.immovable = true; - } - function update() { - myGame.collide(circle, floor); - } -})(); diff --git a/Tests/geometry/circle.ts b/Tests/geometry/circle.ts deleted file mode 100644 index 9a23b64ac..000000000 --- a/Tests/geometry/circle.ts +++ /dev/null @@ -1,30 +0,0 @@ -/// - -(function () { - - var myGame = new Phaser.Game(this, 'game', 800, 600, null, create, update); - - var circle: Phaser.GeomSprite; - var floor: Phaser.GeomSprite; - - function create() { - - circle = myGame.add.geomSprite(200, 0); - circle.createCircle(64); - circle.acceleration.y = 100; - circle.elasticity = 0.8; - - // A simple floor - floor = myGame.add.geomSprite(0, 550); - floor.createRectangle(800, 50); - floor.immovable = true; - - } - - function update() { - - myGame.collide(circle, floor); - - } - -})(); diff --git a/Tests/geometry/line.js b/Tests/geometry/line.js deleted file mode 100644 index c879fd004..000000000 --- a/Tests/geometry/line.js +++ /dev/null @@ -1,27 +0,0 @@ -/// -(function () { - var myGame = new Phaser.Game(this, 'game', 800, 600, null, create, update); - var line; - function create() { - line = myGame.add.geomSprite(200, 200); - line.createLine(400, 400); - } - function update() { - //box.velocity.x = 0; - //box.velocity.y = 0; - //box.angularVelocity = 0; - //box.angularAcceleration = 0; - //if (myGame.input.keyboard.isDown(Phaser.Keyboard.LEFT)) - //{ - // box.angularVelocity = -200; - //} - //else if (myGame.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) - //{ - // box.angularVelocity = 200; - //} - //if (myGame.input.keyboard.isDown(Phaser.Keyboard.UP)) - //{ - // box.velocity.copyFrom(myGame.motion.velocityFromAngle(box.angle, 200)); - //} - } -})(); diff --git a/Tests/geometry/line.ts b/Tests/geometry/line.ts deleted file mode 100644 index cf69a9a86..000000000 --- a/Tests/geometry/line.ts +++ /dev/null @@ -1,40 +0,0 @@ -/// - -(function () { - - var myGame = new Phaser.Game(this, 'game', 800, 600, null, create, update); - - var line: Phaser.GeomSprite; - - function create() { - - line = myGame.add.geomSprite(200, 200); - - line.createLine(400, 400); - - } - - function update() { - - //box.velocity.x = 0; - //box.velocity.y = 0; - //box.angularVelocity = 0; - //box.angularAcceleration = 0; - - //if (myGame.input.keyboard.isDown(Phaser.Keyboard.LEFT)) - //{ - // box.angularVelocity = -200; - //} - //else if (myGame.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) - //{ - // box.angularVelocity = 200; - //} - - //if (myGame.input.keyboard.isDown(Phaser.Keyboard.UP)) - //{ - // box.velocity.copyFrom(myGame.motion.velocityFromAngle(box.angle, 200)); - //} - - } - -})(); diff --git a/Tests/geometry/multi rotate.js b/Tests/geometry/multi rotate.js deleted file mode 100644 index f00d76c42..000000000 --- a/Tests/geometry/multi rotate.js +++ /dev/null @@ -1,31 +0,0 @@ -/// -(function () { - var myGame = new Phaser.Game(this, 'game', 800, 600, null, create, update, render); - var p1; - var p2; - var p3; - var p4; - var d = 0; - function create() { - p1 = new Phaser.Point(myGame.stage.centerX, myGame.stage.centerY); - p2 = new Phaser.Point(p1.x - 50, p1.y - 50); - p3 = new Phaser.Point(p1.x - 100, p1.y - 100); - p4 = new Phaser.Point(p1.x - 150, p1.y - 150); - } - function update() { - p2.rotate(p1.x, p1.y, myGame.math.wrapAngle(d), true); - p3.rotate(p1.x, p1.y, myGame.math.wrapAngle(d), true); - p4.rotate(p1.x, p1.y, myGame.math.wrapAngle(d), true); - d++; - } - function render() { - myGame.stage.context.fillStyle = 'rgb(255,255,0)'; - myGame.stage.context.fillRect(p1.x, p1.y, 4, 4); - myGame.stage.context.fillStyle = 'rgb(255,0,0)'; - myGame.stage.context.fillRect(p2.x, p2.y, 4, 4); - myGame.stage.context.fillStyle = 'rgb(0,255,0)'; - myGame.stage.context.fillRect(p3.x, p3.y, 4, 4); - myGame.stage.context.fillStyle = 'rgb(255,0,255)'; - myGame.stage.context.fillRect(p4.x, p4.y, 4, 4); - } -})(); diff --git a/Tests/geometry/multi rotate.ts b/Tests/geometry/multi rotate.ts deleted file mode 100644 index 075f82cae..000000000 --- a/Tests/geometry/multi rotate.ts +++ /dev/null @@ -1,49 +0,0 @@ -/// - -(function () { - - var myGame = new Phaser.Game(this, 'game', 800, 600, null, create, update, render); - - var p1:Phaser.Point; - var p2:Phaser.Point; - var p3:Phaser.Point; - var p4:Phaser.Point; - - var d: number = 0; - - function create() { - - p1 = new Phaser.Point(myGame.stage.centerX, myGame.stage.centerY); - p2 = new Phaser.Point(p1.x - 50, p1.y - 50); - p3 = new Phaser.Point(p1.x - 100, p1.y - 100); - p4 = new Phaser.Point(p1.x - 150, p1.y - 150); - - } - - function update() { - - p2.rotate(p1.x, p1.y, myGame.math.wrapAngle(d), true); - p3.rotate(p1.x, p1.y, myGame.math.wrapAngle(d), true); - p4.rotate(p1.x, p1.y, myGame.math.wrapAngle(d), true); - - d++; - - } - - function render() { - - myGame.stage.context.fillStyle = 'rgb(255,255,0)'; - myGame.stage.context.fillRect(p1.x, p1.y, 4, 4); - - myGame.stage.context.fillStyle = 'rgb(255,0,0)'; - myGame.stage.context.fillRect(p2.x, p2.y, 4, 4); - - myGame.stage.context.fillStyle = 'rgb(0,255,0)'; - myGame.stage.context.fillRect(p3.x, p3.y, 4, 4); - - myGame.stage.context.fillStyle = 'rgb(255,0,255)'; - myGame.stage.context.fillRect(p4.x, p4.y, 4, 4); - - } - -})(); diff --git a/Tests/geometry/point.js b/Tests/geometry/point.js deleted file mode 100644 index 126f3f3b6..000000000 --- a/Tests/geometry/point.js +++ /dev/null @@ -1,21 +0,0 @@ -/// -(function () { - var myGame = new Phaser.Game(this, 'game', 800, 600, null, create, update); - var floor; - function create() { - for(var i = 0; i < 100; i++) { - var p = myGame.add.geomSprite(myGame.stage.randomX, Math.random() * 100); - p.createPoint(); - p.fillColor = 'rgb(255,255,255)'; - p.acceleration.y = 100 + Math.random() * 100; - p.elasticity = 0.8; - } - // A simple floor - floor = myGame.add.geomSprite(0, 550); - floor.createRectangle(800, 50); - floor.immovable = true; - } - function update() { - myGame.collide(myGame.world.group, floor); - } -})(); diff --git a/Tests/geometry/point.ts b/Tests/geometry/point.ts deleted file mode 100644 index 2ae39d039..000000000 --- a/Tests/geometry/point.ts +++ /dev/null @@ -1,33 +0,0 @@ -/// - -(function () { - - var myGame = new Phaser.Game(this, 'game', 800, 600, null, create, update); - - var floor: Phaser.GeomSprite; - - function create() { - - for (var i = 0; i < 100; i++) - { - var p:Phaser.GeomSprite = myGame.add.geomSprite(myGame.stage.randomX, Math.random() * 100); - p.createPoint(); - p.fillColor = 'rgb(255,255,255)'; - p.acceleration.y = 100 + Math.random() * 100; - p.elasticity = 0.8; - } - - // A simple floor - floor = myGame.add.geomSprite(0, 550); - floor.createRectangle(800, 50); - floor.immovable = true; - - } - - function update() { - - myGame.collide(myGame.world.group, floor); - - } - -})(); diff --git a/Tests/geometry/rect vs rect.js b/Tests/geometry/rect vs rect.js deleted file mode 100644 index b89c54e74..000000000 --- a/Tests/geometry/rect vs rect.js +++ /dev/null @@ -1,22 +0,0 @@ -/// -(function () { - var myGame = new Phaser.Game(this, 'game', 800, 600, null, create, update); - var box1; - var box2; - function create() { - box2 = myGame.add.geomSprite(300, 300).createRectangle(128, 128); - box1 = myGame.add.geomSprite(320, 100).createRectangle(64, 64); - box1.velocity.y = 50; - } - function update() { - if(box1.collide(box2) == true) { - box1.fillColor = 'rgb(255,0,0)'; - } else { - box1.fillColor = 'rgb(0,255,0)'; - } - } - function checkPoints() { - if(box2.rect.containsPoint(box1.rect.topLeft)) { - } - } -})(); diff --git a/Tests/geometry/rect vs rect.ts b/Tests/geometry/rect vs rect.ts deleted file mode 100644 index b527a9cf4..000000000 --- a/Tests/geometry/rect vs rect.ts +++ /dev/null @@ -1,41 +0,0 @@ -/// - -(function () { - - var myGame = new Phaser.Game(this, 'game', 800, 600, null, create, update); - - var box1: Phaser.GeomSprite; - var box2: Phaser.GeomSprite; - - function create() { - - box2 = myGame.add.geomSprite(300, 300).createRectangle(128, 128); - box1 = myGame.add.geomSprite(320, 100).createRectangle(64, 64); - - box1.velocity.y = 50; - - } - - function update() { - - if (box1.collide(box2) == true) - { - box1.fillColor = 'rgb(255,0,0)'; - } - else - { - box1.fillColor = 'rgb(0,255,0)'; - } - - } - - function checkPoints() { - - if (box2.rect.containsPoint(box1.rect.topLeft)) - { - - } - - } - -})(); diff --git a/Tests/geometry/rectangle.js b/Tests/geometry/rectangle.js deleted file mode 100644 index e6508013b..000000000 --- a/Tests/geometry/rectangle.js +++ /dev/null @@ -1,24 +0,0 @@ -/// -(function () { - var myGame = new Phaser.Game(this, 'game', 800, 600, null, create, update); - var box; - function create() { - box = myGame.add.geomSprite(0, 0); - box.createRectangle(64, 64); - box.renderOutline = false; - } - function update() { - box.velocity.x = 0; - box.velocity.y = 0; - if(myGame.input.keyboard.isDown(Phaser.Keyboard.LEFT)) { - box.velocity.x = -200; - } else if(myGame.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) { - box.velocity.x = 200; - } - if(myGame.input.keyboard.isDown(Phaser.Keyboard.UP)) { - box.velocity.y = -200; - } else if(myGame.input.keyboard.isDown(Phaser.Keyboard.DOWN)) { - box.velocity.y = 200; - } - } -})(); diff --git a/Tests/geometry/rectangle.ts b/Tests/geometry/rectangle.ts deleted file mode 100644 index 55bfc90d7..000000000 --- a/Tests/geometry/rectangle.ts +++ /dev/null @@ -1,43 +0,0 @@ -/// - -(function () { - - var myGame = new Phaser.Game(this, 'game', 800, 600, null, create, update); - - var box: Phaser.GeomSprite; - - function create() { - - box = myGame.add.geomSprite(0, 0); - - box.createRectangle(64, 64); - box.renderOutline = false; - - } - - function update() { - - box.velocity.x = 0; - box.velocity.y = 0; - - if (myGame.input.keyboard.isDown(Phaser.Keyboard.LEFT)) - { - box.velocity.x = -200; - } - else if (myGame.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) - { - box.velocity.x = 200; - } - - if (myGame.input.keyboard.isDown(Phaser.Keyboard.UP)) - { - box.velocity.y = -200; - } - else if (myGame.input.keyboard.isDown(Phaser.Keyboard.DOWN)) - { - box.velocity.y = 200; - } - - } - -})(); diff --git a/Tests/geometry/rope bridge.js b/Tests/geometry/rope bridge.js deleted file mode 100644 index 60a056d14..000000000 --- a/Tests/geometry/rope bridge.js +++ /dev/null @@ -1,34 +0,0 @@ -/// -(function () { - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update, render); - function init() { - myGame.loader.addImageFile('ball5', 'assets/sprites/purple_ball.png'); - myGame.loader.load(); - } - var segment; - function create() { - myGame.verlet.friction = 1; - myGame.verlet.hideNearestEntityCircle = true; - var points = []; - var startX = 100; - var startY = 200; - var spacing = 20; - for(var i = 0; i < 30; i++) { - points.push(new Phaser.Vector2(startX + (i * spacing), startY)); - } - segment = myGame.verlet.createLineSegments(points, 0.5); - segment.loadGraphic('ball5'); - segment.hideConstraints = false; - segment.pin(0); - segment.pin(points.length - 1); - } - function update() { - } - function render() { - myGame.verlet.render(); - //myGame.stage.context.fillStyle = 'rgb(255,255,0)'; - //myGame.stage.context.fillRect(p1.x, p1.y, 4, 4); - //myGame.stage.context.fillStyle = 'rgb(255,0,0)'; - //myGame.stage.context.fillRect(p2.x, p2.y, 4, 4); - } -})(); diff --git a/Tests/geometry/rope bridge.ts b/Tests/geometry/rope bridge.ts deleted file mode 100644 index 1d1a437f0..000000000 --- a/Tests/geometry/rope bridge.ts +++ /dev/null @@ -1,55 +0,0 @@ -/// - -(function () { - - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update, render); - - function init() { - - myGame.loader.addImageFile('ball5', 'assets/sprites/purple_ball.png'); - myGame.loader.load(); - - } - - var segment: Phaser.Verlet.Composite; - - function create() { - - myGame.verlet.friction = 1; - myGame.verlet.hideNearestEntityCircle = true; - - var points: Phaser.Vector2[] = []; - var startX: number = 100; - var startY: number = 200; - var spacing: number = 20; - - for (var i = 0; i < 30; i++) - { - points.push(new Phaser.Vector2(startX + (i * spacing), startY)); - } - - segment = myGame.verlet.createLineSegments(points, 0.5); - segment.loadGraphic('ball5'); - segment.hideConstraints = false; - - segment.pin(0); - segment.pin(points.length - 1); - - } - - function update() { - } - - function render() { - - myGame.verlet.render(); - - //myGame.stage.context.fillStyle = 'rgb(255,255,0)'; - //myGame.stage.context.fillRect(p1.x, p1.y, 4, 4); - - //myGame.stage.context.fillStyle = 'rgb(255,0,0)'; - //myGame.stage.context.fillRect(p2.x, p2.y, 4, 4); - - } - -})(); diff --git a/Tests/geometry/rotate point 1.js b/Tests/geometry/rotate point 1.js deleted file mode 100644 index 229ec21fb..000000000 --- a/Tests/geometry/rotate point 1.js +++ /dev/null @@ -1,21 +0,0 @@ -/// -(function () { - var myGame = new Phaser.Game(this, 'game', 800, 600, null, create, update, render); - var p1; - var p2; - var d = 0; - function create() { - p1 = new Phaser.Point(200, 300); - p2 = new Phaser.Point(300, 300); - } - function update() { - p1.rotate(p2.x, p2.y, myGame.math.wrapAngle(d), true); - d++; - } - function render() { - myGame.stage.context.fillStyle = 'rgb(255,255,0)'; - myGame.stage.context.fillRect(p1.x, p1.y, 4, 4); - myGame.stage.context.fillStyle = 'rgb(255,0,0)'; - myGame.stage.context.fillRect(p2.x, p2.y, 4, 4); - } -})(); diff --git a/Tests/geometry/rotate point 1.ts b/Tests/geometry/rotate point 1.ts deleted file mode 100644 index c97610f8e..000000000 --- a/Tests/geometry/rotate point 1.ts +++ /dev/null @@ -1,36 +0,0 @@ -/// - -(function () { - - var myGame = new Phaser.Game(this, 'game', 800, 600, null, create, update, render); - - var p1:Phaser.Point; - var p2:Phaser.Point; - var d: number = 0; - - function create() { - - p1 = new Phaser.Point(200, 300); - p2 = new Phaser.Point(300, 300); - - } - - function update() { - - p1.rotate(p2.x, p2.y, myGame.math.wrapAngle(d), true); - - d++; - - } - - function render() { - - myGame.stage.context.fillStyle = 'rgb(255,255,0)'; - myGame.stage.context.fillRect(p1.x, p1.y, 4, 4); - - myGame.stage.context.fillStyle = 'rgb(255,0,0)'; - myGame.stage.context.fillRect(p2.x, p2.y, 4, 4); - - } - -})(); diff --git a/Tests/geometry/rotate point 2.js b/Tests/geometry/rotate point 2.js deleted file mode 100644 index 7e1c16888..000000000 --- a/Tests/geometry/rotate point 2.js +++ /dev/null @@ -1,43 +0,0 @@ -/// -(function () { - var myGame = new Phaser.Game(this, 'game', 800, 600, null, create, update, render); - var p1; - var p2; - var p3; - var p4; - var d2 = 0; - var d3 = 0; - var d4 = 0; - function create() { - p1 = new Phaser.Point(myGame.stage.centerX, myGame.stage.centerY); - p2 = new Phaser.Point(p1.x - 50, p1.y - 50); - p3 = new Phaser.Point(p2.x - 50, p2.y - 50); - p4 = new Phaser.Point(p3.x - 50, p3.y - 50); - } - function update() { - p2.rotate(p1.x, p1.y, myGame.math.wrapAngle(d2), true, 150); - p3.rotate(p2.x, p2.y, myGame.math.wrapAngle(d3), true, 50); - p4.rotate(p3.x, p3.y, myGame.math.wrapAngle(d4), true, 100); - d2 += 1; - d3 += 4; - d4 += 6; - } - function render() { - myGame.stage.context.strokeStyle = 'rgb(0,255,255)'; - myGame.stage.context.beginPath(); - myGame.stage.context.moveTo(p1.x, p1.y); - myGame.stage.context.lineTo(p2.x, p2.y); - myGame.stage.context.lineTo(p3.x, p3.y); - myGame.stage.context.lineTo(p4.x, p4.y); - myGame.stage.context.stroke(); - myGame.stage.context.closePath(); - myGame.stage.context.fillStyle = 'rgb(255,255,0)'; - myGame.stage.context.fillRect(p1.x, p1.y, 4, 4); - myGame.stage.context.fillStyle = 'rgb(255,0,0)'; - myGame.stage.context.fillRect(p2.x, p2.y, 4, 4); - myGame.stage.context.fillStyle = 'rgb(0,255,0)'; - myGame.stage.context.fillRect(p3.x, p3.y, 4, 4); - myGame.stage.context.fillStyle = 'rgb(255,0,255)'; - myGame.stage.context.fillRect(p4.x, p4.y, 4, 4); - } -})(); diff --git a/Tests/geometry/rotate point 2.ts b/Tests/geometry/rotate point 2.ts deleted file mode 100644 index 92ce80349..000000000 --- a/Tests/geometry/rotate point 2.ts +++ /dev/null @@ -1,62 +0,0 @@ -/// - -(function () { - - var myGame = new Phaser.Game(this, 'game', 800, 600, null, create, update, render); - - var p1:Phaser.Point; - var p2:Phaser.Point; - var p3:Phaser.Point; - var p4:Phaser.Point; - - var d2: number = 0; - var d3: number = 0; - var d4: number = 0; - - function create() { - - p1 = new Phaser.Point(myGame.stage.centerX, myGame.stage.centerY); - p2 = new Phaser.Point(p1.x - 50, p1.y - 50); - p3 = new Phaser.Point(p2.x - 50, p2.y - 50); - p4 = new Phaser.Point(p3.x - 50, p3.y - 50); - - } - - function update() { - - p2.rotate(p1.x, p1.y, myGame.math.wrapAngle(d2), true, 150); - p3.rotate(p2.x, p2.y, myGame.math.wrapAngle(d3), true, 50); - p4.rotate(p3.x, p3.y, myGame.math.wrapAngle(d4), true, 100); - - d2 += 1; - d3 += 4; - d4 += 6; - - } - - function render() { - - myGame.stage.context.strokeStyle = 'rgb(0,255,255)'; - myGame.stage.context.beginPath(); - myGame.stage.context.moveTo(p1.x, p1.y); - myGame.stage.context.lineTo(p2.x, p2.y); - myGame.stage.context.lineTo(p3.x, p3.y); - myGame.stage.context.lineTo(p4.x, p4.y); - myGame.stage.context.stroke(); - myGame.stage.context.closePath(); - - myGame.stage.context.fillStyle = 'rgb(255,255,0)'; - myGame.stage.context.fillRect(p1.x, p1.y, 4, 4); - - myGame.stage.context.fillStyle = 'rgb(255,0,0)'; - myGame.stage.context.fillRect(p2.x, p2.y, 4, 4); - - myGame.stage.context.fillStyle = 'rgb(0,255,0)'; - myGame.stage.context.fillRect(p3.x, p3.y, 4, 4); - - myGame.stage.context.fillStyle = 'rgb(255,0,255)'; - myGame.stage.context.fillRect(p4.x, p4.y, 4, 4); - - } - -})(); diff --git a/Tests/geometry/rotate point 3.js b/Tests/geometry/rotate point 3.js deleted file mode 100644 index 13169cb26..000000000 --- a/Tests/geometry/rotate point 3.js +++ /dev/null @@ -1,71 +0,0 @@ -/// -(function () { - var myGame = new Phaser.Game(this, 'game', 800, 600, null, create, update, render); - var origin; - var p1; - var p2; - var p3; - var p4; - var d = 0; - function create() { - // This creates a box made up of 4 edge-points and rotates it around the origin - origin = new Phaser.Point(400, 300); - p1 = new Phaser.Point()// top left - ; - p2 = new Phaser.Point()// top right - ; - p3 = new Phaser.Point()// bottom right - ; - p4 = new Phaser.Point()// bottom left - ; - } - function update() { - // top left (red) - p1.rotate(origin.x, origin.y, myGame.math.wrapAngle(d), true, 200); - // top right (yellow) - p2.rotate(origin.x, origin.y, myGame.math.wrapAngle(d + 90), true, 200); - // bottom right (aqua) - p3.rotate(origin.x, origin.y, myGame.math.wrapAngle(d + 180), true, 200); - // bottom left (blue) - p4.rotate(origin.x, origin.y, myGame.math.wrapAngle(d + 270), true, 200); - d++; - } - function render() { - // Render the shape - myGame.stage.context.beginPath(); - myGame.stage.context.fillStyle = 'rgba(0,255,0,0.2)'; - myGame.stage.context.strokeStyle = 'rgb(0,255,0)'; - myGame.stage.context.lineWidth = 1; - myGame.stage.context.moveTo(p1.x, p1.y); - myGame.stage.context.lineTo(p2.x, p2.y); - myGame.stage.context.lineTo(p3.x, p3.y); - myGame.stage.context.lineTo(p4.x, p4.y); - myGame.stage.context.lineTo(p1.x, p1.y); - myGame.stage.context.fill(); - myGame.stage.context.stroke(); - myGame.stage.context.closePath(); - // Render the points - myGame.stage.context.fillStyle = 'rgb(255,255,255)'; - myGame.stage.context.fillRect(origin.x, origin.y, 4, 4); - myGame.stage.context.beginPath(); - myGame.stage.context.fillStyle = 'rgb(255,0,0)'; - myGame.stage.context.arc(p1.x, p1.y, 4, 0, Math.PI * 2); - myGame.stage.context.fill(); - myGame.stage.context.closePath(); - myGame.stage.context.beginPath(); - myGame.stage.context.fillStyle = 'rgb(255,255,0)'; - myGame.stage.context.arc(p2.x, p2.y, 4, 0, Math.PI * 2); - myGame.stage.context.fill(); - myGame.stage.context.closePath(); - myGame.stage.context.beginPath(); - myGame.stage.context.fillStyle = 'rgb(0,255,255)'; - myGame.stage.context.arc(p3.x, p3.y, 4, 0, Math.PI * 2); - myGame.stage.context.fill(); - myGame.stage.context.closePath(); - myGame.stage.context.beginPath(); - myGame.stage.context.fillStyle = 'rgb(0,0,255)'; - myGame.stage.context.arc(p4.x, p4.y, 4, 0, Math.PI * 2); - myGame.stage.context.fill(); - myGame.stage.context.closePath(); - } -})(); diff --git a/Tests/geometry/rotate point 3.ts b/Tests/geometry/rotate point 3.ts deleted file mode 100644 index ad0c8d763..000000000 --- a/Tests/geometry/rotate point 3.ts +++ /dev/null @@ -1,95 +0,0 @@ -/// - -(function () { - - var myGame = new Phaser.Game(this, 'game', 800, 600, null, create, update, render); - - var origin:Phaser.Point; - - var p1:Phaser.Point; - var p2:Phaser.Point; - var p3:Phaser.Point; - var p4:Phaser.Point; - - var d: number = 0; - - function create() { - - // This creates a box made up of 4 edge-points and rotates it around the origin - - origin = new Phaser.Point(400, 300); - - p1 = new Phaser.Point(); // top left - p2 = new Phaser.Point(); // top right - p3 = new Phaser.Point(); // bottom right - p4 = new Phaser.Point(); // bottom left - - } - - function update() { - - // top left (red) - p1.rotate(origin.x, origin.y, myGame.math.wrapAngle(d), true, 200); - - // top right (yellow) - p2.rotate(origin.x, origin.y, myGame.math.wrapAngle(d + 90), true, 200); - - // bottom right (aqua) - p3.rotate(origin.x, origin.y, myGame.math.wrapAngle(d + 180), true, 200); - - // bottom left (blue) - p4.rotate(origin.x, origin.y, myGame.math.wrapAngle(d + 270), true, 200); - - d++; - - } - - function render() { - - // Render the shape - - myGame.stage.context.beginPath(); - myGame.stage.context.fillStyle = 'rgba(0,255,0,0.2)'; - myGame.stage.context.strokeStyle = 'rgb(0,255,0)'; - myGame.stage.context.lineWidth = 1; - myGame.stage.context.moveTo(p1.x, p1.y); - myGame.stage.context.lineTo(p2.x, p2.y); - myGame.stage.context.lineTo(p3.x, p3.y); - myGame.stage.context.lineTo(p4.x, p4.y); - myGame.stage.context.lineTo(p1.x, p1.y); - myGame.stage.context.fill(); - myGame.stage.context.stroke(); - myGame.stage.context.closePath(); - - // Render the points - - myGame.stage.context.fillStyle = 'rgb(255,255,255)'; - myGame.stage.context.fillRect(origin.x, origin.y, 4, 4); - - myGame.stage.context.beginPath(); - myGame.stage.context.fillStyle = 'rgb(255,0,0)'; - myGame.stage.context.arc(p1.x, p1.y, 4, 0, Math.PI * 2); - myGame.stage.context.fill(); - myGame.stage.context.closePath(); - - myGame.stage.context.beginPath(); - myGame.stage.context.fillStyle = 'rgb(255,255,0)'; - myGame.stage.context.arc(p2.x, p2.y, 4, 0, Math.PI * 2); - myGame.stage.context.fill(); - myGame.stage.context.closePath(); - - myGame.stage.context.beginPath(); - myGame.stage.context.fillStyle = 'rgb(0,255,255)'; - myGame.stage.context.arc(p3.x, p3.y, 4, 0, Math.PI * 2); - myGame.stage.context.fill(); - myGame.stage.context.closePath(); - - myGame.stage.context.beginPath(); - myGame.stage.context.fillStyle = 'rgb(0,0,255)'; - myGame.stage.context.arc(p4.x, p4.y, 4, 0, Math.PI * 2); - myGame.stage.context.fill(); - myGame.stage.context.closePath(); - - } - -})(); diff --git a/Tests/geometry/rotate point 4.js b/Tests/geometry/rotate point 4.js deleted file mode 100644 index ea9ed35ce..000000000 --- a/Tests/geometry/rotate point 4.js +++ /dev/null @@ -1,54 +0,0 @@ -/// -(function () { - var myGame = new Phaser.Game(this, 'game', 800, 600, null, create, update, render); - var origin; - var origin2; - var points = []; - var points2 = []; - var d = 0; - var d2 = 0; - var m = 64; - function create() { - // Let's have some fun :) - origin = new Phaser.Point(300, 200); - origin2 = new Phaser.Point(600, 350); - for(var i = 0; i < m; i++) { - points.push(new Phaser.Point()); - points2.push(new Phaser.Point()); - } - } - function update() { - for(var i = 0; i < m; i++) { - points[i].rotate(origin.x, origin.y, myGame.math.wrapAngle(d + (i * (360 / m))), true, i * 5); - //points2[i].rotate(origin2.x, origin2.y, myGame.math.wrapAngle(d2 + (i * (360/m))), true, i * 10); - //points[i].rotate(origin.x, origin.y, myGame.math.wrapAngle(d + (i * (360/m))), true, 200); - points2[i].rotate(origin2.x, origin2.y, myGame.math.wrapAngle(d2 + (i * (360 / m))), true, 200); - } - d -= 2; - d2 += 2; - } - function render() { - // Render the shape - myGame.stage.context.save(); - //myGame.stage.context.globalCompositeOperation = 'xor'; - myGame.stage.context.globalCompositeOperation = 'lighter'; - myGame.stage.context.lineWidth = 20; - for(var i = 0; i < m; i++) { - myGame.stage.context.beginPath(); - myGame.stage.context.strokeStyle = 'rgba(255,' + Math.round(i * (255 / m)).toString() + ',0,1)'; - myGame.stage.context.moveTo(origin.x, origin.y); - myGame.stage.context.lineTo(points[i].x, points[i].y); - myGame.stage.context.stroke(); - myGame.stage.context.closePath(); - } - for(var i = 0; i < m; i++) { - myGame.stage.context.beginPath(); - myGame.stage.context.strokeStyle = 'rgba(0,' + Math.round(i * (255 / m)).toString() + ',255,1)'; - myGame.stage.context.moveTo(origin2.x, origin2.y); - myGame.stage.context.lineTo(points2[i].x, points2[i].y); - myGame.stage.context.stroke(); - myGame.stage.context.closePath(); - } - myGame.stage.context.restore(); - } -})(); diff --git a/Tests/geometry/rotate point 4.ts b/Tests/geometry/rotate point 4.ts deleted file mode 100644 index 020c268c8..000000000 --- a/Tests/geometry/rotate point 4.ts +++ /dev/null @@ -1,82 +0,0 @@ -/// - -(function () { - - var myGame = new Phaser.Game(this, 'game', 800, 600, null, create, update, render); - - var origin:Phaser.Point; - var origin2:Phaser.Point; - - var points:Phaser.Point[] = []; - var points2:Phaser.Point[] = []; - - var d: number = 0; - var d2: number = 0; - var m: number = 64; - - function create() { - - // Let's have some fun :) - - origin = new Phaser.Point(300, 200); - origin2 = new Phaser.Point(600, 350); - - for (var i = 0; i < m; i++) - { - points.push(new Phaser.Point()); - points2.push(new Phaser.Point()); - } - - } - - function update() { - - for (var i = 0; i < m; i++) - { - points[i].rotate(origin.x, origin.y, myGame.math.wrapAngle(d + (i * (360/m))), true, i * 5); - //points2[i].rotate(origin2.x, origin2.y, myGame.math.wrapAngle(d2 + (i * (360/m))), true, i * 10); - - //points[i].rotate(origin.x, origin.y, myGame.math.wrapAngle(d + (i * (360/m))), true, 200); - points2[i].rotate(origin2.x, origin2.y, myGame.math.wrapAngle(d2 + (i * (360/m))), true, 200); - } - - d -= 2; - d2 += 2; - - } - - function render() { - - // Render the shape - - myGame.stage.context.save(); - //myGame.stage.context.globalCompositeOperation = 'xor'; - myGame.stage.context.globalCompositeOperation = 'lighter'; - myGame.stage.context.lineWidth = 20; - - for (var i = 0; i < m; i++) - { - myGame.stage.context.beginPath(); - myGame.stage.context.strokeStyle = 'rgba(255,' + Math.round(i * (255/m)).toString() + ',0,1)'; - myGame.stage.context.moveTo(origin.x, origin.y); - myGame.stage.context.lineTo(points[i].x, points[i].y); - myGame.stage.context.stroke(); - myGame.stage.context.closePath(); - } - - - for (var i = 0; i < m; i++) - { - myGame.stage.context.beginPath(); - myGame.stage.context.strokeStyle = 'rgba(0,' + Math.round(i * (255/m)).toString() + ',255,1)'; - myGame.stage.context.moveTo(origin2.x, origin2.y); - myGame.stage.context.lineTo(points2[i].x, points2[i].y); - myGame.stage.context.stroke(); - myGame.stage.context.closePath(); - } - - myGame.stage.context.restore(); - - } - -})(); diff --git a/Tests/geometry/verlet 1.js b/Tests/geometry/verlet 1.js deleted file mode 100644 index ac4a38166..000000000 --- a/Tests/geometry/verlet 1.js +++ /dev/null @@ -1,26 +0,0 @@ -/// -(function () { - var myGame = new Phaser.Game(this, 'game', 800, 600, null, create, update, render); - var segment; - function create() { - myGame.verlet.friction = 1; - segment = myGame.verlet.createLineSegments([ - new Phaser.Vector2(20, 10), - new Phaser.Vector2(40, 10), - new Phaser.Vector2(60, 10), - new Phaser.Vector2(80, 10), - new Phaser.Vector2(100, 10) - ], 0.02); - segment.pin(0); - segment.pin(4); - var wheel = myGame.verlet.createTire(new Phaser.Vector2(200, 50), 100, 30, 0.3, 0.9); - var tire2 = myGame.verlet.createTire(new Phaser.Vector2(400, 50), 70, 7, 0.1, 0.2); - var cube = myGame.verlet.createTire(new Phaser.Vector2(600, 50), 70, 4, 1, 1); - var tri = myGame.verlet.createTire(new Phaser.Vector2(700, 50), 100, 3, 1, 1); - } - function update() { - } - function render() { - myGame.verlet.render(); - } -})(); diff --git a/Tests/geometry/verlet 1.ts b/Tests/geometry/verlet 1.ts deleted file mode 100644 index d6265c007..000000000 --- a/Tests/geometry/verlet 1.ts +++ /dev/null @@ -1,33 +0,0 @@ -/// - -(function () { - - var myGame = new Phaser.Game(this, 'game', 800, 600, null, create, update, render); - - var segment: Phaser.Verlet.Composite; - - function create() { - - myGame.verlet.friction = 1; - - segment = myGame.verlet.createLineSegments([new Phaser.Vector2(20, 10), new Phaser.Vector2(40, 10), new Phaser.Vector2(60, 10), new Phaser.Vector2(80, 10), new Phaser.Vector2(100, 10)], 0.02); - segment.pin(0); - segment.pin(4); - - var wheel = myGame.verlet.createTire(new Phaser.Vector2(200,50), 100, 30, 0.3, 0.9); - var tire2 = myGame.verlet.createTire(new Phaser.Vector2(400,50), 70, 7, 0.1, 0.2); - var cube = myGame.verlet.createTire(new Phaser.Vector2(600,50), 70, 4, 1, 1); - var tri = myGame.verlet.createTire(new Phaser.Vector2(700,50), 100, 3, 1, 1); - - } - - function update() { - } - - function render() { - - myGame.verlet.render(); - - } - -})(); diff --git a/Tests/geometry/verlet sprites.js b/Tests/geometry/verlet sprites.js deleted file mode 100644 index 52f41605a..000000000 --- a/Tests/geometry/verlet sprites.js +++ /dev/null @@ -1,34 +0,0 @@ -/// -(function () { - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update, render); - function init() { - myGame.loader.addImageFile('ball0', 'assets/sprites/yellow_ball.png'); - myGame.loader.addImageFile('ball1', 'assets/sprites/aqua_ball.png'); - myGame.loader.addImageFile('ball2', 'assets/sprites/blue_ball.png'); - myGame.loader.addImageFile('ball3', 'assets/sprites/green_ball.png'); - myGame.loader.addImageFile('ball4', 'assets/sprites/red_ball.png'); - myGame.loader.addImageFile('ball5', 'assets/sprites/purple_ball.png'); - myGame.loader.load(); - } - var wheel; - var diamond; - var triangle; - var cube; - function create() { - myGame.verlet.friction = 1; - myGame.verlet.step = 32; - wheel = myGame.verlet.createTire(new Phaser.Vector2(200, 50), 100, 30, 0.3, 0.9); - wheel.loadGraphic('ball0'); - diamond = myGame.verlet.createTire(new Phaser.Vector2(400, 50), 70, 7, 0.1, 0.2); - diamond.loadGraphic('ball1'); - triangle = myGame.verlet.createTire(new Phaser.Vector2(600, 50), 100, 3, 1, 1); - triangle.loadGraphic('ball2'); - cube = myGame.verlet.createTire(new Phaser.Vector2(300, 50), 100, 4, 0.3, 0.9); - cube.loadGraphic('ball3'); - } - function update() { - } - function render() { - myGame.verlet.render(); - } -})(); diff --git a/Tests/geometry/verlet sprites.ts b/Tests/geometry/verlet sprites.ts deleted file mode 100644 index 3432b36b7..000000000 --- a/Tests/geometry/verlet sprites.ts +++ /dev/null @@ -1,53 +0,0 @@ -/// - -(function () { - - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update, render); - - function init() { - - myGame.loader.addImageFile('ball0', 'assets/sprites/yellow_ball.png'); - myGame.loader.addImageFile('ball1', 'assets/sprites/aqua_ball.png'); - myGame.loader.addImageFile('ball2', 'assets/sprites/blue_ball.png'); - myGame.loader.addImageFile('ball3', 'assets/sprites/green_ball.png'); - myGame.loader.addImageFile('ball4', 'assets/sprites/red_ball.png'); - myGame.loader.addImageFile('ball5', 'assets/sprites/purple_ball.png'); - - myGame.loader.load(); - - } - - var wheel: Phaser.Verlet.Composite; - var diamond: Phaser.Verlet.Composite; - var triangle: Phaser.Verlet.Composite; - var cube: Phaser.Verlet.Composite; - - function create() { - - myGame.verlet.friction = 1; - myGame.verlet.step = 32; - - wheel = myGame.verlet.createTire(new Phaser.Vector2(200,50), 100, 30, 0.3, 0.9); - wheel.loadGraphic('ball0'); - - diamond = myGame.verlet.createTire(new Phaser.Vector2(400,50), 70, 7, 0.1, 0.2); - diamond.loadGraphic('ball1'); - - triangle = myGame.verlet.createTire(new Phaser.Vector2(600,50), 100, 3, 1, 1); - triangle.loadGraphic('ball2'); - - cube = myGame.verlet.createTire(new Phaser.Vector2(300, 50), 100, 4, 0.3, 0.9); - cube.loadGraphic('ball3'); - - } - - function update() { - } - - function render() { - - myGame.verlet.render(); - - } - -})(); diff --git a/Tests/groups/basic group.js b/Tests/groups/basic group.js deleted file mode 100644 index a0a1fae1a..000000000 --- a/Tests/groups/basic group.js +++ /dev/null @@ -1,39 +0,0 @@ -/// -(function () { - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update); - function init() { - myGame.world.setSize(1920, 1920); - myGame.loader.addImageFile('grid', 'assets/tests/debug-grid-1920x1920.png'); - myGame.loader.addImageFile('car', 'assets/sprites/car90.png'); - myGame.loader.addImageFile('melon', 'assets/sprites/melon.png'); - myGame.loader.load(); - } - var car; - var melons; - function create() { - myGame.add.sprite(0, 0, 'grid'); - melons = myGame.add.group(); - for(var i = 0; i < 100; i++) { - var tempSprite = myGame.add.sprite(Math.random() * myGame.world.width, Math.random() * myGame.world.height, 'melon'); - tempSprite.scrollFactor.setTo(1.2, 1.2); - melons.add(tempSprite); - } - car = myGame.add.sprite(400, 300, 'car'); - myGame.camera.follow(car); - } - function update() { - car.velocity.x = 0; - car.velocity.y = 0; - car.angularVelocity = 0; - car.angularAcceleration = 0; - if(myGame.input.keyboard.isDown(Phaser.Keyboard.LEFT)) { - car.angularVelocity = -200; - } else if(myGame.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) { - car.angularVelocity = 200; - } - if(myGame.input.keyboard.isDown(Phaser.Keyboard.UP)) { - var motion = myGame.motion.velocityFromAngle(car.angle, 300); - car.velocity.copyFrom(motion); - } - } -})(); diff --git a/Tests/groups/basic group.ts b/Tests/groups/basic group.ts deleted file mode 100644 index 344b68980..000000000 --- a/Tests/groups/basic group.ts +++ /dev/null @@ -1,66 +0,0 @@ -/// - -(function () { - - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update); - - function init() { - - myGame.world.setSize(1920, 1920); - - myGame.loader.addImageFile('grid', 'assets/tests/debug-grid-1920x1920.png'); - myGame.loader.addImageFile('car', 'assets/sprites/car90.png'); - myGame.loader.addImageFile('melon', 'assets/sprites/melon.png'); - - myGame.loader.load(); - - } - - var car: Phaser.Sprite; - var melons: Phaser.Group; - - function create() { - - myGame.add.sprite(0, 0, 'grid'); - - melons = myGame.add.group(); - - for (var i = 0; i < 100; i++) - { - var tempSprite = myGame.add.sprite(Math.random() * myGame.world.width, Math.random() * myGame.world.height, 'melon'); - tempSprite.scrollFactor.setTo(1.2, 1.2); - melons.add(tempSprite); - } - - car = myGame.add.sprite(400, 300, 'car'); - - myGame.camera.follow(car); - - } - - function update() { - - car.velocity.x = 0; - car.velocity.y = 0; - car.angularVelocity = 0; - car.angularAcceleration = 0; - - if (myGame.input.keyboard.isDown(Phaser.Keyboard.LEFT)) - { - car.angularVelocity = -200; - } - else if (myGame.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) - { - car.angularVelocity = 200; - } - - if (myGame.input.keyboard.isDown(Phaser.Keyboard.UP)) - { - var motion:Phaser.Point = myGame.motion.velocityFromAngle(car.angle, 300); - - car.velocity.copyFrom(motion); - } - - } - -})(); diff --git a/Tests/groups/display order.js b/Tests/groups/display order.js deleted file mode 100644 index 089983b0f..000000000 --- a/Tests/groups/display order.js +++ /dev/null @@ -1,32 +0,0 @@ -/// -(function () { - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update); - function init() { - myGame.loader.addImageFile('atari1', 'assets/sprites/atari130xe.png'); - myGame.loader.addImageFile('atari2', 'assets/sprites/atari800xl.png'); - myGame.loader.addImageFile('card', 'assets/sprites/mana_card.png'); - myGame.loader.load(); - } - var items; - var card; - function create() { - items = myGame.add.group(); - // Items are rendered in the depth order in which they are added to the Group - items.add(myGame.add.sprite(64, 100, 'atari1')); - card = items.add(myGame.add.sprite(240, 80, 'card')); - items.add(myGame.add.sprite(280, 100, 'atari2')); - myGame.input.onTap.addOnce(removeCard, this); - } - function removeCard() { - // Now let's kill the card sprite - card.kill(); - myGame.input.onTap.addOnce(replaceCard, this); - } - function replaceCard() { - // And bring it back to life again - I assume it will render in the same place as before? - var bob = items.getFirstDead(); - bob.revive(); - } - function update() { - } -})(); diff --git a/Tests/groups/display order.ts b/Tests/groups/display order.ts deleted file mode 100644 index 38a12f5aa..000000000 --- a/Tests/groups/display order.ts +++ /dev/null @@ -1,56 +0,0 @@ -/// - -(function () { - - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update); - - function init() { - - myGame.loader.addImageFile('atari1', 'assets/sprites/atari130xe.png'); - myGame.loader.addImageFile('atari2', 'assets/sprites/atari800xl.png'); - myGame.loader.addImageFile('card', 'assets/sprites/mana_card.png'); - - myGame.loader.load(); - - } - - var items: Phaser.Group; - var card: Phaser.Sprite; - - function create() { - - items = myGame.add.group(); - - // Items are rendered in the depth order in which they are added to the Group - - items.add(myGame.add.sprite(64, 100, 'atari1')); - card = items.add(myGame.add.sprite(240, 80, 'card')); - items.add(myGame.add.sprite(280, 100, 'atari2')); - - myGame.input.onTap.addOnce(removeCard, this); - - } - - function removeCard() { - - // Now let's kill the card sprite - card.kill(); - - myGame.input.onTap.addOnce(replaceCard, this); - - } - - function replaceCard() { - - // And bring it back to life again - I assume it will render in the same place as before? - var bob = items.getFirstDead(); - - bob.revive(); - - } - - function update() { - - } - -})(); diff --git a/Tests/input/mouse scale.js b/Tests/input/mouse scale.js deleted file mode 100644 index 9a4f2146d..000000000 --- a/Tests/input/mouse scale.js +++ /dev/null @@ -1,35 +0,0 @@ -/// -(function () { - // Here we create a quite tiny game (320x240 in size) - var myGame = new Phaser.Game(this, 'game', 320, 240, init, create, update, render); - function init() { - // This sets a limit on the up-scale - myGame.stage.scale.maxWidth = 640; - myGame.stage.scale.maxHeight = 480; - // Then we tell Phaser that we want it to scale up to whatever the browser can handle, but to do it proportionally - myGame.stage.scaleMode = Phaser.StageScaleMode.SHOW_ALL; - myGame.loader.addImageFile('melon', 'assets/sprites/melon.png'); - myGame.loader.load(); - } - function create() { - myGame.world.setSize(2000, 2000); - for(var i = 0; i < 1000; i++) { - myGame.add.sprite(myGame.world.randomX, myGame.world.randomY, 'melon'); - } - } - function update() { - if(myGame.input.keyboard.isDown(Phaser.Keyboard.LEFT)) { - myGame.camera.scroll.x -= 4; - } else if(myGame.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) { - myGame.camera.scroll.x += 4; - } - if(myGame.input.keyboard.isDown(Phaser.Keyboard.UP)) { - myGame.camera.scroll.y -= 4; - } else if(myGame.input.keyboard.isDown(Phaser.Keyboard.DOWN)) { - myGame.camera.scroll.y += 4; - } - } - function render() { - myGame.input.renderDebugInfo(16, 16); - } -})(); diff --git a/Tests/input/mouse scale.ts b/Tests/input/mouse scale.ts deleted file mode 100644 index 6c6997cf3..000000000 --- a/Tests/input/mouse scale.ts +++ /dev/null @@ -1,62 +0,0 @@ -/// - -(function () { - - // Here we create a quite tiny game (320x240 in size) - var myGame = new Phaser.Game(this, 'game', 320, 240, init, create, update, render); - - function init() { - - // This sets a limit on the up-scale - myGame.stage.scale.maxWidth = 640; - myGame.stage.scale.maxHeight = 480; - - // Then we tell Phaser that we want it to scale up to whatever the browser can handle, but to do it proportionally - myGame.stage.scaleMode = Phaser.StageScaleMode.SHOW_ALL; - - myGame.loader.addImageFile('melon', 'assets/sprites/melon.png'); - - myGame.loader.load(); - - } - - function create() { - - myGame.world.setSize(2000, 2000); - - for (var i = 0; i < 1000; i++) - { - myGame.add.sprite(myGame.world.randomX, myGame.world.randomY, 'melon'); - } - - } - - function update() { - - if (myGame.input.keyboard.isDown(Phaser.Keyboard.LEFT)) - { - myGame.camera.scroll.x -= 4; - } - else if (myGame.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) - { - myGame.camera.scroll.x += 4; - } - - if (myGame.input.keyboard.isDown(Phaser.Keyboard.UP)) - { - myGame.camera.scroll.y -= 4; - } - else if (myGame.input.keyboard.isDown(Phaser.Keyboard.DOWN)) - { - myGame.camera.scroll.y += 4; - } - - } - - function render() { - - myGame.input.renderDebugInfo(16, 16); - - } - -})(); diff --git a/Tests/input/multitouch.js b/Tests/input/multitouch.js deleted file mode 100644 index 02a627a82..000000000 --- a/Tests/input/multitouch.js +++ /dev/null @@ -1,23 +0,0 @@ -/// -(function () { - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update, render); - function init() { - myGame.loader.addImageFile('dragonsun', 'assets/pics/cougar_dragonsun.png'); - myGame.loader.load(); - } - function create() { - console.log('dragons 8'); - myGame.input.onDown.add(test1, this); - } - function test1() { - console.log('down'); - } - function update() { - } - function render() { - myGame.input.pointer1.renderDebug(); - myGame.input.pointer2.renderDebug(); - myGame.input.pointer3.renderDebug(); - myGame.input.pointer4.renderDebug(); - } -})(); diff --git a/Tests/input/multitouch.ts b/Tests/input/multitouch.ts deleted file mode 100644 index b75d747f4..000000000 --- a/Tests/input/multitouch.ts +++ /dev/null @@ -1,40 +0,0 @@ -/// - -(function () { - - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update, render); - - function init() { - - myGame.loader.addImageFile('dragonsun', 'assets/pics/cougar_dragonsun.png'); - - myGame.loader.load(); - - } - - function create() { - - console.log('dragons 8'); - - myGame.input.onDown.add(test1, this); - - } - - function test1() { - console.log('down'); - } - - function update() { - - } - - function render() { - - myGame.input.pointer1.renderDebug(); - myGame.input.pointer2.renderDebug(); - myGame.input.pointer3.renderDebug(); - myGame.input.pointer4.renderDebug(); - - } - -})(); diff --git a/Tests/input/single tap.js b/Tests/input/single tap.js deleted file mode 100644 index efbae5567..000000000 --- a/Tests/input/single tap.js +++ /dev/null @@ -1,39 +0,0 @@ -/// -(function () { - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update, render); - function init() { - myGame.loader.addImageFile('ball0', 'assets/sprites/yellow_ball.png'); - myGame.loader.addImageFile('ball1', 'assets/sprites/aqua_ball.png'); - myGame.loader.addImageFile('ball2', 'assets/sprites/blue_ball.png'); - myGame.loader.addImageFile('ball3', 'assets/sprites/green_ball.png'); - myGame.loader.addImageFile('ball4', 'assets/sprites/red_ball.png'); - myGame.loader.addImageFile('ball5', 'assets/sprites/purple_ball.png'); - myGame.loader.load(); - } - var balls; - function create() { - balls = myGame.add.group(); - myGame.input.onTap.add(tapped, this); - } - function tapped(pointer, doubleTap) { - if(balls.countDead() > 0) { - var tempBall = balls.getFirstDead(); - tempBall.revive(); - tempBall.x = pointer.x; - tempBall.y = pointer.y; - } else { - var tempBall = new Phaser.Sprite(myGame, pointer.x, pointer.y, 'ball' + Math.round(Math.random() * 5)); - tempBall.setBoundsFromWorld(Phaser.GameObject.OUT_OF_BOUNDS_KILL); - balls.add(tempBall); - } - tempBall.velocity.y = 150; - if(doubleTap) { - tempBall.scale.setTo(4, 4); - } - } - function update() { - } - function render() { - myGame.input.renderDebugInfo(16, 16); - } -})(); diff --git a/Tests/input/single tap.ts b/Tests/input/single tap.ts deleted file mode 100644 index db3e525a8..000000000 --- a/Tests/input/single tap.ts +++ /dev/null @@ -1,64 +0,0 @@ -/// - -(function () { - - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update, render); - - function init() { - - myGame.loader.addImageFile('ball0', 'assets/sprites/yellow_ball.png'); - myGame.loader.addImageFile('ball1', 'assets/sprites/aqua_ball.png'); - myGame.loader.addImageFile('ball2', 'assets/sprites/blue_ball.png'); - myGame.loader.addImageFile('ball3', 'assets/sprites/green_ball.png'); - myGame.loader.addImageFile('ball4', 'assets/sprites/red_ball.png'); - myGame.loader.addImageFile('ball5', 'assets/sprites/purple_ball.png'); - - myGame.loader.load(); - - } - - var balls: Phaser.Group; - - function create() { - - balls = myGame.add.group(); - - myGame.input.onTap.add(tapped, this); - - } - - function tapped(pointer: Phaser.Pointer, doubleTap: bool) { - - if (balls.countDead() > 0) - { - var tempBall: Phaser.Sprite = balls.getFirstDead(); - tempBall.revive(); - tempBall.x = pointer.x; - tempBall.y = pointer.y; - } - else - { - var tempBall: Phaser.Sprite = new Phaser.Sprite(myGame, pointer.x, pointer.y, 'ball' + Math.round(Math.random() * 5)); - tempBall.setBoundsFromWorld(Phaser.GameObject.OUT_OF_BOUNDS_KILL); - balls.add(tempBall); - } - - tempBall.velocity.y = 150; - - if (doubleTap) - { - tempBall.scale.setTo(4, 4); - } - - } - - function update() { - } - - function render() { - - myGame.input.renderDebugInfo(16, 16); - - } - -})(); diff --git a/Tests/input/single touch.js b/Tests/input/single touch.js deleted file mode 100644 index 3dc654d48..000000000 --- a/Tests/input/single touch.js +++ /dev/null @@ -1,19 +0,0 @@ -/// -(function () { - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update, render); - function init() { - } - function create() { - // We lock the game to allowing only 1 Pointer active - // This means on multi-touch systems it will ignore any extra fingers placed down beyond the first - myGame.input.maxPointers = 1; - } - function update() { - } - function render() { - myGame.input.renderDebugInfo(16, 16); - myGame.input.pointer1.renderDebug(true); - myGame.input.pointer2.renderDebug(true); - myGame.input.pointer3.renderDebug(true); - } -})(); diff --git a/Tests/input/single touch.ts b/Tests/input/single touch.ts deleted file mode 100644 index 57570ddfa..000000000 --- a/Tests/input/single touch.ts +++ /dev/null @@ -1,31 +0,0 @@ -/// - -(function () { - - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update, render); - - function init() { - } - - function create() { - - // We lock the game to allowing only 1 Pointer active - // This means on multi-touch systems it will ignore any extra fingers placed down beyond the first - myGame.input.maxPointers = 1; - - } - - function update() { - } - - function render() { - - myGame.input.renderDebugInfo(16, 16); - - myGame.input.pointer1.renderDebug(true); - myGame.input.pointer2.renderDebug(true); - myGame.input.pointer3.renderDebug(true); - - } - -})(); diff --git a/Tests/mini games/formula 1.js b/Tests/mini games/formula 1.js deleted file mode 100644 index f58f4ac93..000000000 --- a/Tests/mini games/formula 1.js +++ /dev/null @@ -1,36 +0,0 @@ -/// -(function () { - var myGame = new Phaser.Game(this, 'game', 840, 400, init, create, update); - function init() { - myGame.loader.addImageFile('track', 'assets/games/f1/track.png'); - myGame.loader.addImageFile('car', 'assets/games/f1/car1.png'); - myGame.loader.load(); - } - var car; - var bigCam; - function create() { - myGame.camera.setBounds(0, 0, myGame.stage.width, myGame.stage.height); - myGame.add.sprite(0, 0, 'track'); - car = myGame.add.sprite(180, 298, 'car'); - car.rotation = 180; - car.maxVelocity.setTo(150, 150); - bigCam = myGame.add.camera(640, 0, 100, 200); - bigCam.follow(car, Phaser.Camera.STYLE_LOCKON); - bigCam.setBounds(0, 0, myGame.stage.width, myGame.stage.height); - bigCam.showBorder = true; - bigCam.borderColor = 'rgb(0,0,0)'; - bigCam.scale.setTo(2, 2); - } - function update() { - if(myGame.input.keyboard.isDown(Phaser.Keyboard.LEFT)) { - car.rotation -= 4; - } else if(myGame.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) { - car.rotation += 4; - } - if(myGame.input.keyboard.isDown(Phaser.Keyboard.UP)) { - car.velocity.copyFrom(myGame.motion.velocityFromAngle(car.angle, 150)); - } else { - car.velocity.copyFrom(myGame.motion.velocityFromAngle(car.angle, 60)); - } - } -})(); diff --git a/Tests/mini games/formula 1.ts b/Tests/mini games/formula 1.ts deleted file mode 100644 index 035c7a34c..000000000 --- a/Tests/mini games/formula 1.ts +++ /dev/null @@ -1,59 +0,0 @@ -/// - -(function () { - - var myGame = new Phaser.Game(this, 'game', 840, 400, init, create, update); - - function init() { - - myGame.loader.addImageFile('track', 'assets/games/f1/track.png'); - myGame.loader.addImageFile('car', 'assets/games/f1/car1.png'); - - myGame.loader.load(); - - } - - var car: Phaser.Sprite; - var bigCam: Phaser.Camera; - - function create() { - - myGame.camera.setBounds(0, 0, myGame.stage.width, myGame.stage.height); - myGame.add.sprite(0, 0, 'track'); - - car = myGame.add.sprite(180, 298, 'car'); - car.rotation = 180; - car.maxVelocity.setTo(150, 150); - - bigCam = myGame.add.camera(640, 0, 100, 200); - bigCam.follow(car, Phaser.Camera.STYLE_LOCKON); - bigCam.setBounds(0, 0, myGame.stage.width, myGame.stage.height); - bigCam.showBorder = true; - bigCam.borderColor = 'rgb(0,0,0)'; - bigCam.scale.setTo(2, 2); - - } - - function update() { - - if (myGame.input.keyboard.isDown(Phaser.Keyboard.LEFT)) - { - car.rotation -= 4; - } - else if (myGame.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) - { - car.rotation += 4; - } - - if (myGame.input.keyboard.isDown(Phaser.Keyboard.UP)) - { - car.velocity.copyFrom(myGame.motion.velocityFromAngle(car.angle, 150)); - } - else - { - car.velocity.copyFrom(myGame.motion.velocityFromAngle(car.angle, 60)); - } - - } - -})(); diff --git a/Tests/misc/boot screen.js b/Tests/misc/boot screen.js new file mode 100644 index 000000000..70088c0d1 --- /dev/null +++ b/Tests/misc/boot screen.js @@ -0,0 +1,5 @@ +/// +(function () { + // If you don't give any parameters to Phaser beyond the defaults you'll see the standard Phaser boot screen appear. + var game = new Phaser.Game(this, 'game'); +})(); diff --git a/Tests/misc/boot screen.ts b/Tests/misc/boot screen.ts new file mode 100644 index 000000000..29b0043d7 --- /dev/null +++ b/Tests/misc/boot screen.ts @@ -0,0 +1,8 @@ +/// + +(function () { + + // If you don't give any parameters to Phaser beyond the defaults you'll see the standard Phaser boot screen appear. + var game = new Phaser.Game(this, 'game'); + +})(); diff --git a/Tests/misc/bootscreen.js b/Tests/misc/bootscreen.js deleted file mode 100644 index 57cb3bfae..000000000 --- a/Tests/misc/bootscreen.js +++ /dev/null @@ -1,4 +0,0 @@ -/// -(function () { - var myGame = new Phaser.Game(this, 'game', 800, 600); -})(); diff --git a/Tests/misc/bootscreen.ts b/Tests/misc/bootscreen.ts deleted file mode 100644 index f0a673436..000000000 --- a/Tests/misc/bootscreen.ts +++ /dev/null @@ -1,7 +0,0 @@ -/// - -(function () { - - var myGame = new Phaser.Game(this, 'game', 800, 600); - -})(); diff --git a/Tests/misc/multi game.js b/Tests/misc/multi game.js deleted file mode 100644 index 8e1944eda..000000000 --- a/Tests/misc/multi game.js +++ /dev/null @@ -1,58 +0,0 @@ -/// -(function () { - // Let's test having 2 totally separate games embedded on the same page - var myGame = new Phaser.Game(this, 'game', 400, 400, init, create, update); - // They can share the same parent div, they'll just butt-up next to each other - var myGame2 = new Phaser.Game(this, 'game', 400, 400, init2, create2, update2); - function init() { - myGame.world.setSize(3000, 3000); - myGame.loader.addImageFile('melon', 'assets/sprites/melon.png'); - myGame.loader.load(); - } - function create() { - myGame.camera.setBounds(0, 0, myGame.world.width, myGame.world.height); - for(var i = 0; i < 1000; i++) { - myGame.add.sprite(myGame.world.randomX, myGame.world.randomY, 'melon'); - } - } - function update() { - if(myGame.input.keyboard.isDown(Phaser.Keyboard.LEFT)) { - myGame.camera.scroll.x -= 4; - } else if(myGame.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) { - myGame.camera.scroll.x += 4; - } - if(myGame.input.keyboard.isDown(Phaser.Keyboard.UP)) { - myGame.camera.scroll.y += 4; - } else if(myGame.input.keyboard.isDown(Phaser.Keyboard.DOWN)) { - myGame.camera.scroll.y -= 4; - } - } - // And now for game 2, we're basically just duplicating the functions from above, but that's fine for this test - function init2() { - myGame2.world.setSize(1920, 1920); - myGame2.loader.addImageFile('grid', 'assets/tests/debug-grid-1920x1920.png'); - myGame2.loader.addImageFile('car', 'assets/sprites/car90.png'); - myGame2.loader.load(); - } - var car; - function create2() { - myGame2.camera.setBounds(0, 0, myGame.world.width, myGame.world.height); - myGame2.add.sprite(0, 0, 'grid'); - car = myGame2.add.sprite(400, 300, 'car'); - myGame2.camera.follow(car); - } - function update2() { - car.velocity.x = 0; - car.velocity.y = 0; - car.angularVelocity = 0; - car.angularAcceleration = 0; - if(myGame2.input.keyboard.isDown(Phaser.Keyboard.LEFT)) { - car.angularVelocity = -200; - } else if(myGame2.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) { - car.angularVelocity = 200; - } - if(myGame2.input.keyboard.isDown(Phaser.Keyboard.UP)) { - car.velocity.copyFrom(myGame.motion.velocityFromAngle(car.angle, 300)); - } - } -})(); diff --git a/Tests/misc/multi game.ts b/Tests/misc/multi game.ts deleted file mode 100644 index 2704c3ca1..000000000 --- a/Tests/misc/multi game.ts +++ /dev/null @@ -1,104 +0,0 @@ -/// - -(function () { - - // Let's test having 2 totally separate games embedded on the same page - var myGame = new Phaser.Game(this, 'game', 400, 400, init, create, update); - - // They can share the same parent div, they'll just butt-up next to each other - var myGame2 = new Phaser.Game(this, 'game', 400, 400, init2, create2, update2); - - function init() { - - myGame.world.setSize(3000, 3000); - - myGame.loader.addImageFile('melon', 'assets/sprites/melon.png'); - - myGame.loader.load(); - - } - - function create() { - - myGame.camera.setBounds(0, 0, myGame.world.width, myGame.world.height); - - for (var i = 0; i < 1000; i++) - { - myGame.add.sprite(myGame.world.randomX, myGame.world.randomY, 'melon'); - } - - } - - function update() { - - if (myGame.input.keyboard.isDown(Phaser.Keyboard.LEFT)) - { - myGame.camera.scroll.x -= 4; - } - else if (myGame.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) - { - myGame.camera.scroll.x += 4; - } - - if (myGame.input.keyboard.isDown(Phaser.Keyboard.UP)) - { - myGame.camera.scroll.y += 4; - } - else if (myGame.input.keyboard.isDown(Phaser.Keyboard.DOWN)) - { - myGame.camera.scroll.y -= 4; - } - - } - - // And now for game 2, we're basically just duplicating the functions from above, but that's fine for this test - - function init2() { - - myGame2.world.setSize(1920, 1920); - - myGame2.loader.addImageFile('grid', 'assets/tests/debug-grid-1920x1920.png'); - myGame2.loader.addImageFile('car', 'assets/sprites/car90.png'); - - myGame2.loader.load(); - - } - - var car; - - function create2() { - - myGame2.camera.setBounds(0, 0, myGame.world.width, myGame.world.height); - - myGame2.add.sprite(0, 0, 'grid'); - - car = myGame2.add.sprite(400, 300, 'car'); - - myGame2.camera.follow(car); - - } - - function update2() { - - car.velocity.x = 0; - car.velocity.y = 0; - car.angularVelocity = 0; - car.angularAcceleration = 0; - - if (myGame2.input.keyboard.isDown(Phaser.Keyboard.LEFT)) - { - car.angularVelocity = -200; - } - else if (myGame2.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) - { - car.angularVelocity = 200; - } - - if (myGame2.input.keyboard.isDown(Phaser.Keyboard.UP)) - { - car.velocity.copyFrom(myGame.motion.velocityFromAngle(car.angle, 300)); - } - - } - -})(); diff --git a/Tests/misc/starfield.js b/Tests/misc/starfield.js deleted file mode 100644 index 55f3e468b..000000000 --- a/Tests/misc/starfield.js +++ /dev/null @@ -1,46 +0,0 @@ -/// -(function () { - var myGame = new Phaser.Game(this, 'game', 800, 600, null, create, update, render); - var starfield; - var xx = []; - var yy = []; - var zz = []; - var xxx = 0; - var yyy = 0; - function create() { - // the width of the starfield - var star_w = 12000; - for(var i = 0; i < 800; i++) { - xx[i] = Math.floor(Math.random() * star_w * 2) - star_w; - yy[i] = Math.floor(Math.random() * star_w * 2) - star_w; - zz[i] = Math.floor(Math.random() * 160) + 1; - } - starfield = myGame.add.dynamicTexture(800, 600); - } - function update() { - starfield.clear(); - for(var i = 0; i < 800; i++) { - if(zz[i] == 1) { - zz[i] = 100; - } - xxx = (xx[i]) / (zz[i]); - yyy = (yy[i]) / (zz[i])--; - //var x: number = xxx + myGame.input.x; - //var y: number = yyy + myGame.input.y; - var x = xxx + 400; - var y = yyy + 300; - var c = '#ffffff'; - if(zz[i] > 80) { - c = '#666666'; - } else if(zz[i] > 60) { - c = '#888888'; - } else if(zz[i] > 40) { - c = '#aaaaaa'; - } - starfield.setPixel(x, y, c); - } - } - function render() { - starfield.render(); - } -})(); diff --git a/Tests/misc/starfield.ts b/Tests/misc/starfield.ts deleted file mode 100644 index ae5e08148..000000000 --- a/Tests/misc/starfield.ts +++ /dev/null @@ -1,61 +0,0 @@ -/// - -(function () { - - var myGame = new Phaser.Game(this, 'game', 800, 600, null, create, update, render); - - var starfield: Phaser.DynamicTexture; - - var xx = []; - var yy = []; - var zz = []; - var xxx = 0; - var yyy = 0; - - function create() { - - // the width of the starfield - var star_w: number = 12000; - - for (var i: number = 0; i < 800; i++) - { - xx[i] = Math.floor(Math.random() * star_w * 2) - star_w - yy[i] = Math.floor(Math.random() * star_w * 2) - star_w - zz[i] = Math.floor(Math.random() * 160) + 1; - } - - starfield = myGame.add.dynamicTexture(800, 600); - - } - - function update() { - - starfield.clear(); - - for (var i: number = 0; i < 800; i++) - { - if (zz[i] == 1) zz[i] = 100; - xxx = (xx[i]) / (zz[i]); - yyy = (yy[i]) / (zz[i])--; - //var x: number = xxx + myGame.input.x; - //var y: number = yyy + myGame.input.y; - var x: number = xxx + 400; - var y: number = yyy + 300; - var c: string = '#ffffff'; - - if (zz[i] > 80) c = '#666666'; - else if (zz[i] > 60) c = '#888888' - else if (zz[i] > 40) c = '#aaaaaa'; - - starfield.setPixel(x, y, c); - } - - } - - function render() { - - starfield.render(); - - } - -})(); diff --git a/Tests/misc/time.js b/Tests/misc/time.js deleted file mode 100644 index 75fe1bf8a..000000000 --- a/Tests/misc/time.js +++ /dev/null @@ -1,33 +0,0 @@ -/// -(function () { - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update); - function init() { - myGame.loader.addImageFile('car', 'assets/sprites/asteroids_ship.png'); - myGame.loader.load(); - } - var car; - function create() { - car = myGame.add.sprite(200, 300, 'car'); - myGame.onRenderCallback = render; - myGame.stage.context.font = '16px Arial'; - myGame.stage.context.fillStyle = 'rgb(255,255,255)'; - } - function update() { - car.velocity.x = 0; - car.velocity.y = 0; - car.angularVelocity = 0; - car.angularAcceleration = 0; - if(myGame.input.keyboard.isDown(Phaser.Keyboard.LEFT)) { - car.angularVelocity = -200; - } else if(myGame.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) { - car.angularVelocity = 200; - } - if(myGame.input.keyboard.isDown(Phaser.Keyboard.UP)) { - var motion = myGame.motion.velocityFromAngle(car.angle, 200); - car.velocity.copyFrom(motion); - } - } - function render() { - myGame.stage.context.fillText(myGame.time.time.toString(), 32, 32); - } -})(); diff --git a/Tests/misc/time.ts b/Tests/misc/time.ts deleted file mode 100644 index 95872f1bf..000000000 --- a/Tests/misc/time.ts +++ /dev/null @@ -1,58 +0,0 @@ -/// - -(function () { - - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update); - - function init() { - - myGame.loader.addImageFile('car', 'assets/sprites/asteroids_ship.png'); - - myGame.loader.load(); - - } - - var car: Phaser.Sprite; - - function create() { - - car = myGame.add.sprite(200, 300, 'car'); - - myGame.onRenderCallback = render; - - myGame.stage.context.font = '16px Arial'; - myGame.stage.context.fillStyle = 'rgb(255,255,255)'; - - } - - function update() { - - car.velocity.x = 0; - car.velocity.y = 0; - car.angularVelocity = 0; - car.angularAcceleration = 0; - - if (myGame.input.keyboard.isDown(Phaser.Keyboard.LEFT)) - { - car.angularVelocity = -200; - } - else if (myGame.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) - { - car.angularVelocity = 200; - } - - if (myGame.input.keyboard.isDown(Phaser.Keyboard.UP)) - { - var motion:Phaser.Point = myGame.motion.velocityFromAngle(car.angle, 200); - car.velocity.copyFrom(motion); - } - - } - - function render() { - - myGame.stage.context.fillText(myGame.time.time.toString(), 32, 32); - - } - -})(); diff --git a/Tests/mobile/bunny mobile.js b/Tests/mobile/bunny mobile.js deleted file mode 100644 index 767cf72cd..000000000 --- a/Tests/mobile/bunny mobile.js +++ /dev/null @@ -1,58 +0,0 @@ -/// -(function () { - var myGame = new Phaser.Game(this, 'game', 320, 460, init, create, update, render); - function init() { - myGame.loader.addImageFile('bunny', 'assets/sprites/wabbit.png'); - myGame.loader.load(); - myGame.stage.scaleMode = Phaser.StageScaleMode.SHOW_ALL; - } - var maxX; - var maxY; - var minX; - var minY; - function create() { - minX = 0; - minY = 0; - maxX = myGame.stage.width - 26; - maxY = myGame.stage.height - 37; - myGame.input.onDown.add(addBunnies, this); - // This will really help on slow Android phones - myGame.framerate = 30; - // Make sure the camera doesn't clip anything - myGame.camera.disableClipping = true; - myGame.stage.context.fillStyle = 'rgb(255,0,0)'; - myGame.stage.context.font = '20px Arial'; - addBunnies(); - } - function addBunnies() { - for(var i = 0; i < 10; i++) { - var tempSprite = myGame.add.sprite(myGame.stage.randomX, 0, 'bunny'); - tempSprite.velocity.x = -200 + (Math.random() * 400); - tempSprite.velocity.y = 100 + Math.random() * 200; - } - } - function update() { - myGame.world.group.forEach(checkWalls); - } - function render() { - // Note: Displaying canvas text causes a big performance hit on mobile - myGame.stage.context.fillText("fps: " + myGame.time.fps.toString(), 0, 32); - } - function checkWalls(bunny) { - if(bunny.x > maxX) { - bunny.velocity.x *= -1; - bunny.x = maxX; - } else if(bunny.x < minX) { - bunny.velocity.x *= -1; - bunny.x = minX; - } - if(bunny.y > maxY) { - bunny.velocity.y *= -0.8; - bunny.y = maxY; - } else if(bunny.y < minY) { - bunny.velocity.x = -200 + (Math.random() * 400); - bunny.velocity.y = 100 + Math.random() * 200; - bunny.y = minY; - } - } -})(); diff --git a/Tests/mobile/bunny mobile.ts b/Tests/mobile/bunny mobile.ts deleted file mode 100644 index 6cf9f9404..000000000 --- a/Tests/mobile/bunny mobile.ts +++ /dev/null @@ -1,94 +0,0 @@ -/// - -(function () { - - var myGame = new Phaser.Game(this, 'game', 320, 460, init, create, update, render); - - function init() { - - myGame.loader.addImageFile('bunny', 'assets/sprites/wabbit.png'); - - myGame.loader.load(); - - myGame.stage.scaleMode = Phaser.StageScaleMode.SHOW_ALL; - - } - - var maxX: number; - var maxY: number; - var minX: number; - var minY: number; - - function create() { - - minX = 0; - minY = 0; - maxX = myGame.stage.width - 26; - maxY = myGame.stage.height - 37; - - myGame.input.onDown.add(addBunnies, this); - - // This will really help on slow Android phones - myGame.framerate = 30; - // Make sure the camera doesn't clip anything - myGame.camera.disableClipping = true; - - myGame.stage.context.fillStyle = 'rgb(255,0,0)'; - myGame.stage.context.font = '20px Arial'; - - addBunnies(); - - } - - function addBunnies() { - - for (var i = 0; i < 10; i++) - { - var tempSprite = myGame.add.sprite(myGame.stage.randomX, 0, 'bunny'); - tempSprite.velocity.x = -200 + (Math.random() * 400); - tempSprite.velocity.y = 100 + Math.random() * 200; - } - - } - - function update() { - - myGame.world.group.forEach(checkWalls); - - } - - function render() { - - // Note: Displaying canvas text causes a big performance hit on mobile - myGame.stage.context.fillText("fps: " + myGame.time.fps.toString(), 0, 32); - - } - - function checkWalls(bunny:Phaser.Sprite) { - - if (bunny.x > maxX) - { - bunny.velocity.x *= -1; - bunny.x = maxX; - } - else if (bunny.x < minX) - { - bunny.velocity.x *= -1; - bunny.x = minX; - } - - if (bunny.y > maxY) - { - bunny.velocity.y *= -0.8; - bunny.y = maxY; - } - else if (bunny.y < minY) - { - bunny.velocity.x = -200 + (Math.random() * 400); - bunny.velocity.y = 100 + Math.random() * 200; - bunny.y = minY; - } - - } - -})(); diff --git a/Tests/mobile/fullscreen.html b/Tests/mobile/fullscreen.html deleted file mode 100644 index 0c6698986..000000000 --- a/Tests/mobile/fullscreen.html +++ /dev/null @@ -1,62 +0,0 @@ - - - - - - Phaser Mobile Fullscreen Test - - - - - -
- - - - - \ No newline at end of file diff --git a/Tests/mobile/sprite test 1.js b/Tests/mobile/sprite test 1.js deleted file mode 100644 index 717a958f4..000000000 --- a/Tests/mobile/sprite test 1.js +++ /dev/null @@ -1,46 +0,0 @@ -/// -(function () { - var myGame = new Phaser.Game(this, 'game', 320, 400, init, create); - var emitter; - function init() { - myGame.loader.addImageFile('backdrop1', 'assets/pics/atari_fujilogo.png'); - myGame.loader.addImageFile('backdrop2', 'assets/pics/acryl_bladerunner.png'); - myGame.loader.addImageFile('jet', 'assets/sprites/carrot.png'); - myGame.loader.load(); - // This can help a lot on crappy old Android phones :) - //myGame.framerate = 30; - myGame.stage.backgroundColor = 'rgb(50,50,50)'; - myGame.stage.scaleMode = Phaser.StageScaleMode.SHOW_ALL; - //myGame.stage.scaleMode = Phaser.StageScaleMode.EXACT_FIT; - //myGame.stage.scaleMode = Phaser.StageScaleMode.NO_SCALE; - } - var pic1; - var pic2; - function create() { - pic1 = myGame.add.sprite(0, 0, 'backdrop1'); - pic2 = myGame.add.sprite(0, 0, 'backdrop2'); - // Creates a basic emitter, bursting out 50 default sprites (i.e. 16x16 white boxes) - emitter = myGame.add.emitter(myGame.stage.centerX, myGame.stage.centerY); - emitter.makeParticles('jet', 50, false, 0); - emitter.setRotation(0, 0); - emitter.start(false, 10, 0.1); - // Make sure the camera doesn't clip anything - myGame.camera.disableClipping = true; - myGame.stage.scale.enterLandscape.add(goneLandscape, this); - myGame.stage.scale.enterPortrait.add(gonePortrait, this); - myGame.onRenderCallback = render; - } - function goneLandscape() { - pic1.visible = true; - pic2.visible = false; - } - function gonePortrait() { - pic1.visible = false; - pic2.visible = true; - } - function render() { - myGame.stage.context.fillStyle = 'rgb(255,0,0)'; - myGame.stage.context.font = '20px Arial'; - //myGame.stage.context.fillText("ttc: " + myGame._raf.timeToCall.toString(), 0, 64); - } -})(); diff --git a/Tests/mobile/sprite test 1.ts b/Tests/mobile/sprite test 1.ts deleted file mode 100644 index fac3d4403..000000000 --- a/Tests/mobile/sprite test 1.ts +++ /dev/null @@ -1,73 +0,0 @@ -/// - -(function () { - - var myGame = new Phaser.Game(this, 'game', 320, 400, init, create); - - var emitter: Phaser.Emitter; - - function init() { - - myGame.loader.addImageFile('backdrop1', 'assets/pics/atari_fujilogo.png'); - myGame.loader.addImageFile('backdrop2', 'assets/pics/acryl_bladerunner.png'); - myGame.loader.addImageFile('jet', 'assets/sprites/carrot.png'); - - myGame.loader.load(); - - // This can help a lot on crappy old Android phones :) - //myGame.framerate = 30; - - myGame.stage.backgroundColor = 'rgb(50,50,50)'; - myGame.stage.scaleMode = Phaser.StageScaleMode.SHOW_ALL; - //myGame.stage.scaleMode = Phaser.StageScaleMode.EXACT_FIT; - //myGame.stage.scaleMode = Phaser.StageScaleMode.NO_SCALE; - - } - - var pic1; - var pic2; - - function create() { - - pic1 = myGame.add.sprite(0, 0, 'backdrop1'); - pic2 = myGame.add.sprite(0, 0, 'backdrop2'); - - // Creates a basic emitter, bursting out 50 default sprites (i.e. 16x16 white boxes) - emitter = myGame.add.emitter(myGame.stage.centerX, myGame.stage.centerY); - emitter.makeParticles('jet', 50, false, 0); - emitter.setRotation(0, 0); - emitter.start(false, 10, 0.1); - - // Make sure the camera doesn't clip anything - myGame.camera.disableClipping = true; - - myGame.stage.scale.enterLandscape.add(goneLandscape, this); - myGame.stage.scale.enterPortrait.add(gonePortrait, this); - - myGame.onRenderCallback = render; - - } - - function goneLandscape() { - - pic1.visible = true; - pic2.visible = false; - - } - - function gonePortrait() { - - pic1.visible = false; - pic2.visible = true; - - } - - function render() { - - myGame.stage.context.fillStyle = 'rgb(255,0,0)'; - myGame.stage.context.font = '20px Arial'; - //myGame.stage.context.fillText("ttc: " + myGame._raf.timeToCall.toString(), 0, 64); - - } - -})(); diff --git a/Tests/particles/basic emitter.js b/Tests/particles/basic emitter.js deleted file mode 100644 index e5fa16505..000000000 --- a/Tests/particles/basic emitter.js +++ /dev/null @@ -1,11 +0,0 @@ -/// -(function () { - var myGame = new Phaser.Game(this, 'game', 800, 600, null, create); - var emitter; - function create() { - // Creates a basic emitter, bursting out 50 default sprites (i.e. 16x16 white boxes) - emitter = myGame.add.emitter(myGame.stage.centerX, myGame.stage.centerY); - emitter.makeParticles(null, 50, false, 0); - emitter.start(true); - } -})(); diff --git a/Tests/particles/basic emitter.ts b/Tests/particles/basic emitter.ts deleted file mode 100644 index 1dcc63676..000000000 --- a/Tests/particles/basic emitter.ts +++ /dev/null @@ -1,18 +0,0 @@ -/// - -(function () { - - var myGame = new Phaser.Game(this, 'game', 800, 600, null, create); - - var emitter: Phaser.Emitter; - - function create() { - - // Creates a basic emitter, bursting out 50 default sprites (i.e. 16x16 white boxes) - emitter = myGame.add.emitter(myGame.stage.centerX, myGame.stage.centerY); - emitter.makeParticles(null, 50, false, 0); - emitter.start(true); - - } - -})(); diff --git a/Tests/particles/graphic emitter.js b/Tests/particles/graphic emitter.js deleted file mode 100644 index eabb6d546..000000000 --- a/Tests/particles/graphic emitter.js +++ /dev/null @@ -1,14 +0,0 @@ -/// -(function () { - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create); - var emitter; - function init() { - myGame.loader.addImageFile('jet', 'assets/sprites/jets.png'); - myGame.loader.load(); - } - function create() { - emitter = myGame.add.emitter(myGame.stage.centerX, myGame.stage.centerY); - emitter.makeParticles('jet', 50, false, 0); - emitter.start(false, 10, 0.1); - } -})(); diff --git a/Tests/particles/graphic emitter.ts b/Tests/particles/graphic emitter.ts deleted file mode 100644 index eff00efdc..000000000 --- a/Tests/particles/graphic emitter.ts +++ /dev/null @@ -1,25 +0,0 @@ -/// - -(function () { - - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create); - - var emitter: Phaser.Emitter; - - function init() { - - myGame.loader.addImageFile('jet', 'assets/sprites/jets.png'); - - myGame.loader.load(); - - } - - function create() { - - emitter = myGame.add.emitter(myGame.stage.centerX, myGame.stage.centerY); - emitter.makeParticles('jet', 50, false, 0); - emitter.start(false, 10, 0.1); - - } - -})(); diff --git a/Tests/particles/mousetrail.js b/Tests/particles/mousetrail.js deleted file mode 100644 index 8b5ac2e8b..000000000 --- a/Tests/particles/mousetrail.js +++ /dev/null @@ -1,23 +0,0 @@ -/// -(function () { - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update); - var emitter; - function init() { - myGame.loader.addImageFile('jet', 'assets/sprites/particle1.png'); - myGame.loader.load(); - } - function create() { - emitter = myGame.add.emitter(myGame.stage.centerX, myGame.stage.centerY); - emitter.makeParticles('jet', 100); - emitter.gravity = 200; - emitter.setXSpeed(-50, 50); - emitter.setYSpeed(-50, -100); - emitter.setRotation(0, 0); - emitter.start(false, 10, 0.05); - } - function update() { - emitter.x = myGame.input.x; - emitter.y = myGame.input.y; - //emitter.em - } -})(); diff --git a/Tests/particles/mousetrail.ts b/Tests/particles/mousetrail.ts deleted file mode 100644 index b179dfb23..000000000 --- a/Tests/particles/mousetrail.ts +++ /dev/null @@ -1,38 +0,0 @@ -/// - -(function () { - - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update); - - var emitter: Phaser.Emitter; - - function init() { - - myGame.loader.addImageFile('jet', 'assets/sprites/particle1.png'); - - myGame.loader.load(); - - } - - function create() { - - emitter = myGame.add.emitter(myGame.stage.centerX, myGame.stage.centerY); - emitter.makeParticles('jet', 100); - - emitter.gravity = 200; - emitter.setXSpeed(-50, 50); - emitter.setYSpeed(-50, -100); - emitter.setRotation(0, 0); - emitter.start(false, 10, 0.05); - - } - - function update() { - - emitter.x = myGame.input.x; - emitter.y = myGame.input.y; - //emitter.em - - } - -})(); diff --git a/Tests/particles/multiple streams.js b/Tests/particles/multiple streams.js deleted file mode 100644 index ee0454efb..000000000 --- a/Tests/particles/multiple streams.js +++ /dev/null @@ -1,49 +0,0 @@ -/// -(function () { - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update); - var emitter1; - var emitter2; - var emitter3; - var emitter4; - var emitter5; - var emitter6; - function init() { - myGame.loader.addImageFile('ball1', 'assets/sprites/aqua_ball.png'); - myGame.loader.addImageFile('ball2', 'assets/sprites/yellow_ball.png'); - myGame.loader.addImageFile('ball3', 'assets/sprites/red_ball.png'); - myGame.loader.addImageFile('ball4', 'assets/sprites/purple_ball.png'); - myGame.loader.addImageFile('ball5', 'assets/sprites/blue_ball.png'); - myGame.loader.addImageFile('ball6', 'assets/sprites/green_ball.png'); - myGame.loader.load(); - } - function makeEmitter(emitter, x, y, graphic) { - emitter = myGame.add.emitter(x, y); - emitter.gravity = 100; - emitter.bounce = 0.5; - if(x == 0) { - emitter.setXSpeed(200, 250); - } else { - emitter.setXSpeed(-200, -250); - } - emitter.setYSpeed(-50, -10); - emitter.makeParticles(graphic, 250, false, 0); - return emitter; - } - function create() { - emitter1 = makeEmitter(emitter1, 0, 50, 'ball1'); - emitter2 = makeEmitter(emitter2, 0, 250, 'ball2'); - emitter3 = makeEmitter(emitter3, 0, 450, 'ball3'); - emitter4 = makeEmitter(emitter4, myGame.stage.width, 50, 'ball4'); - emitter5 = makeEmitter(emitter5, myGame.stage.width, 250, 'ball5'); - emitter6 = makeEmitter(emitter6, myGame.stage.width, 450, 'ball6'); - emitter1.start(false, 50, 0.05); - emitter2.start(false, 50, 0.05); - emitter3.start(false, 50, 0.05); - emitter4.start(false, 50, 0.05); - emitter5.start(false, 50, 0.05); - emitter6.start(false, 50, 0.05); - } - function update() { - //myGame.collide(leftEmitter, rightEmitter); - } -})(); diff --git a/Tests/particles/multiple streams.ts b/Tests/particles/multiple streams.ts deleted file mode 100644 index 129e1d981..000000000 --- a/Tests/particles/multiple streams.ts +++ /dev/null @@ -1,73 +0,0 @@ -/// - -(function () { - - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update); - - var emitter1: Phaser.Emitter; - var emitter2: Phaser.Emitter; - var emitter3: Phaser.Emitter; - var emitter4: Phaser.Emitter; - var emitter5: Phaser.Emitter; - var emitter6: Phaser.Emitter; - - function init() { - - myGame.loader.addImageFile('ball1', 'assets/sprites/aqua_ball.png'); - myGame.loader.addImageFile('ball2', 'assets/sprites/yellow_ball.png'); - myGame.loader.addImageFile('ball3', 'assets/sprites/red_ball.png'); - myGame.loader.addImageFile('ball4', 'assets/sprites/purple_ball.png'); - myGame.loader.addImageFile('ball5', 'assets/sprites/blue_ball.png'); - myGame.loader.addImageFile('ball6', 'assets/sprites/green_ball.png'); - - myGame.loader.load(); - - } - - function makeEmitter(emitter, x, y, graphic) { - - emitter = myGame.add.emitter(x, y); - emitter.gravity = 100; - emitter.bounce = 0.5; - - if (x == 0) - { - emitter.setXSpeed(200, 250); - } - else - { - emitter.setXSpeed(-200, -250); - } - - emitter.setYSpeed(-50, -10); - emitter.makeParticles(graphic, 250, false, 0); - - return emitter; - - } - - function create() { - - emitter1 = makeEmitter(emitter1, 0, 50, 'ball1'); - emitter2 = makeEmitter(emitter2, 0, 250, 'ball2'); - emitter3 = makeEmitter(emitter3, 0, 450, 'ball3'); - emitter4 = makeEmitter(emitter4, myGame.stage.width, 50, 'ball4'); - emitter5 = makeEmitter(emitter5, myGame.stage.width, 250, 'ball5'); - emitter6 = makeEmitter(emitter6, myGame.stage.width, 450, 'ball6'); - - emitter1.start(false, 50, 0.05); - emitter2.start(false, 50, 0.05); - emitter3.start(false, 50, 0.05); - emitter4.start(false, 50, 0.05); - emitter5.start(false, 50, 0.05); - emitter6.start(false, 50, 0.05); - - } - - function update() { - - //myGame.collide(leftEmitter, rightEmitter); - - } - -})(); diff --git a/Tests/particles/sprite emitter.js b/Tests/particles/sprite emitter.js deleted file mode 100644 index c06c225cf..000000000 --- a/Tests/particles/sprite emitter.js +++ /dev/null @@ -1,46 +0,0 @@ -var __extends = this.__extends || function (d, b) { - function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); -}; -/// -/// -/// -// Actually we could achieve the same result as this by using a sprite sheet and basic Particle -// but it still shows you how to use it properly from TypeScript, so it was worth making -var customParticle = (function (_super) { - __extends(customParticle, _super); - function customParticle(game) { - _super.call(this, game); - var s = [ - 'carrot', - 'melon', - 'eggplant', - 'mushroom', - 'pineapple' - ]; - this.loadGraphic(game.math.getRandom(s)); - } - return customParticle; -})(Phaser.Particle); -(function () { - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create); - var emitter; - function init() { - myGame.loader.addImageFile('carrot', 'assets/sprites/carrot.png'); - myGame.loader.addImageFile('melon', 'assets/sprites/melon.png'); - myGame.loader.addImageFile('eggplant', 'assets/sprites/eggplant.png'); - myGame.loader.addImageFile('mushroom', 'assets/sprites/mushroom.png'); - myGame.loader.addImageFile('pineapple', 'assets/sprites/pineapple.png'); - myGame.loader.load(); - } - function create() { - emitter = myGame.add.emitter(myGame.stage.centerX, 50); - emitter.gravity = 100; - // Here we tell the emitter to use our customParticle class - // The customParticle needs to extend Particle and must take game:Game as the first constructor parameter, otherwise it's free as a bird - emitter.particleClass = customParticle; - emitter.makeParticles(null, 500, false, 0); - emitter.start(false, 10, 0.05); - } -})(); diff --git a/Tests/particles/sprite emitter.ts b/Tests/particles/sprite emitter.ts deleted file mode 100644 index 7a4b4014b..000000000 --- a/Tests/particles/sprite emitter.ts +++ /dev/null @@ -1,52 +0,0 @@ -/// -/// -/// - -// Actually we could achieve the same result as this by using a sprite sheet and basic Particle -// but it still shows you how to use it properly from TypeScript, so it was worth making -class customParticle extends Phaser.Particle { - - constructor(game:Phaser.Game) { - - super(game); - - var s = ['carrot', 'melon', 'eggplant', 'mushroom', 'pineapple']; - - this.loadGraphic(game.math.getRandom(s)); - } - -} - -(function () { - - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create); - - var emitter: Phaser.Emitter; - - function init() { - - myGame.loader.addImageFile('carrot', 'assets/sprites/carrot.png'); - myGame.loader.addImageFile('melon', 'assets/sprites/melon.png'); - myGame.loader.addImageFile('eggplant', 'assets/sprites/eggplant.png'); - myGame.loader.addImageFile('mushroom', 'assets/sprites/mushroom.png'); - myGame.loader.addImageFile('pineapple', 'assets/sprites/pineapple.png'); - - myGame.loader.load(); - - } - - function create() { - - emitter = myGame.add.emitter(myGame.stage.centerX, 50); - emitter.gravity = 100; - - // Here we tell the emitter to use our customParticle class - // The customParticle needs to extend Particle and must take game:Game as the first constructor parameter, otherwise it's free as a bird - emitter.particleClass = customParticle; - - emitter.makeParticles(null, 500, false, 0); - emitter.start(false, 10, 0.05); - - } - -})(); diff --git a/Tests/particles/when particles collide.js b/Tests/particles/when particles collide.js deleted file mode 100644 index 921c42bce..000000000 --- a/Tests/particles/when particles collide.js +++ /dev/null @@ -1,30 +0,0 @@ -/// -(function () { - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update); - var leftEmitter; - var rightEmitter; - function init() { - myGame.loader.addImageFile('ball1', 'assets/sprites/aqua_ball.png'); - myGame.loader.addImageFile('ball2', 'assets/sprites/yellow_ball.png'); - myGame.loader.load(); - } - function create() { - leftEmitter = myGame.add.emitter(0, myGame.stage.centerY - 200); - leftEmitter.gravity = 100; - leftEmitter.bounce = 0.5; - leftEmitter.setXSpeed(100, 200); - leftEmitter.setYSpeed(-50, 50); - leftEmitter.makeParticles('ball1', 250, false, 1); - rightEmitter = myGame.add.emitter(myGame.stage.width, myGame.stage.centerY - 200); - rightEmitter.gravity = 100; - rightEmitter.bounce = 0.5; - rightEmitter.setXSpeed(-100, -200); - rightEmitter.setYSpeed(-50, 50); - rightEmitter.makeParticles('ball2', 250, false, 1); - leftEmitter.start(false, 50, 0.05); - rightEmitter.start(false, 50, 0.05); - } - function update() { - myGame.collide(leftEmitter, rightEmitter); - } -})(); diff --git a/Tests/particles/when particles collide.ts b/Tests/particles/when particles collide.ts deleted file mode 100644 index 7b4eca6cd..000000000 --- a/Tests/particles/when particles collide.ts +++ /dev/null @@ -1,47 +0,0 @@ -/// - -(function () { - - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update); - - var leftEmitter: Phaser.Emitter; - var rightEmitter: Phaser.Emitter; - - function init() { - - myGame.loader.addImageFile('ball1', 'assets/sprites/aqua_ball.png'); - myGame.loader.addImageFile('ball2', 'assets/sprites/yellow_ball.png'); - - myGame.loader.load(); - - } - - function create() { - - leftEmitter = myGame.add.emitter(0, myGame.stage.centerY - 200); - leftEmitter.gravity = 100; - leftEmitter.bounce = 0.5; - leftEmitter.setXSpeed(100, 200); - leftEmitter.setYSpeed(-50, 50); - leftEmitter.makeParticles('ball1', 250, false, 1); - - - rightEmitter = myGame.add.emitter(myGame.stage.width, myGame.stage.centerY - 200); - rightEmitter.gravity = 100; - rightEmitter.bounce = 0.5; - rightEmitter.setXSpeed(-100, -200); - rightEmitter.setYSpeed(-50, 50); - rightEmitter.makeParticles('ball2', 250, false, 1); - - leftEmitter.start(false, 50, 0.05); - rightEmitter.start(false, 50, 0.05); - - } - - function update() { - - myGame.collide(leftEmitter, rightEmitter); - - } - -})(); diff --git a/Tests/phaser-fx.js b/Tests/phaser-fx.js index c784aa725..6499d8dac 100644 --- a/Tests/phaser-fx.js +++ b/Tests/phaser-fx.js @@ -1,8 +1,7 @@ var Phaser; (function (Phaser) { (function (FX) { - /// - /// + /// /** * Phaser - FX - Camera - Flash * @@ -73,9 +72,57 @@ var Phaser; var Phaser; (function (Phaser) { (function (FX) { - /// - /// - /// + /// + /** + * Phaser - FX - Camera - Border + * + * Creates a border around a camera. + */ + (function (Camera) { + var Border = (function () { + function Border(game, parent) { + /** + * Whether render border of this camera or not. (default is false) + * @type {boolean} + */ + this.showBorder = false; + /** + * Color of border of this camera. (in css color string) + * @type {string} + */ + this.borderColor = 'rgb(255,255,255)'; + this._game = game; + this._parent = parent; + } + Border.prototype.start = /** + * You can name the function that starts the effect whatever you like, but we used 'start' in our effects. + */ + function () { + }; + Border.prototype.postRender = /** + * Post-render is called during the objects render cycle, after the children/image data has been rendered. + * It happens directly BEFORE a canvas context.restore has happened if added to a Camera. + */ + function (camera, cameraX, cameraY, cameraWidth, cameraHeight) { + if(this.showBorder == true) { + this._game.stage.context.strokeStyle = this.borderColor; + this._game.stage.context.lineWidth = 1; + this._game.stage.context.rect(camera.scaledX, camera.scaledY, camera.worldView.width, camera.worldView.height); + this._game.stage.context.stroke(); + } + }; + return Border; + })(); + Camera.Border = Border; + })(FX.Camera || (FX.Camera = {})); + var Camera = FX.Camera; + })(Phaser.FX || (Phaser.FX = {})); + var FX = Phaser.FX; +})(Phaser || (Phaser = {})); +var Phaser; +(function (Phaser) { + (function (FX) { + /// /** * Phaser - FX - Camera - Template * @@ -131,9 +178,7 @@ var Phaser; var Phaser; (function (Phaser) { (function (FX) { - /// - /// - /// + /// /** * Phaser - FX - Camera - Mirror * @@ -176,9 +221,10 @@ var Phaser; * It happens directly BEFORE a canvas context.restore has happened if added to a Camera. */ function (camera, cameraX, cameraY, cameraWidth, cameraHeight) { - if(this.cls) { - this._context.clearRect(0, 0, this._mirrorWidth, this._mirrorHeight); - } + //if (this.cls) + //{ + // this._context.clearRect(0, 0, this._mirrorWidth, this._mirrorHeight); + //} this._sx = cameraX + this._mirrorX; this._sy = cameraY + this._mirrorY; if(this.flipX == true && this.flipY == false) { @@ -221,9 +267,79 @@ var Phaser; var Phaser; (function (Phaser) { (function (FX) { - /// - /// - /// + /// + /** + * Phaser - FX - Camera - Shadow + * + * Creates a drop-shadow effect on the camera window. + */ + (function (Camera) { + var Shadow = (function () { + function Shadow(game, parent) { + /** + * Render camera shadow or not. (default is false) + * @type {boolean} + */ + this.showShadow = false; + /** + * Color of shadow, in css color string. + * @type {string} + */ + this.shadowColor = 'rgb(0,0,0)'; + /** + * Blur factor of shadow. + * @type {number} + */ + this.shadowBlur = 10; + /** + * Offset of the shadow from camera's position. + * @type {Point} + */ + this.shadowOffset = new Phaser.Point(4, 4); + this._game = game; + this._parent = parent; + } + Shadow.prototype.start = /** + * You can name the function that starts the effect whatever you like, but we used 'start' in our effects. + */ + function () { + }; + Shadow.prototype.preRender = /** + * Pre-render is called at the start of the object render cycle, before any transforms have taken place. + * It happens directly AFTER a canvas context.save has happened if added to a Camera. + */ + function (camera, cameraX, cameraY, cameraWidth, cameraHeight) { + // Shadow + if(this.showShadow == true) { + this._game.stage.context.shadowColor = this.shadowColor; + this._game.stage.context.shadowBlur = this.shadowBlur; + this._game.stage.context.shadowOffsetX = this.shadowOffset.x; + this._game.stage.context.shadowOffsetY = this.shadowOffset.y; + } + }; + Shadow.prototype.render = /** + * render is called during the objects render cycle, right after all transforms have finished, but before any children/image data is rendered. + */ + function (camera, cameraX, cameraY, cameraWidth, cameraHeight) { + // Shadow off + if(this.showShadow == true) { + this._game.stage.context.shadowBlur = 0; + this._game.stage.context.shadowOffsetX = 0; + this._game.stage.context.shadowOffsetY = 0; + } + }; + return Shadow; + })(); + Camera.Shadow = Shadow; + })(FX.Camera || (FX.Camera = {})); + var Camera = FX.Camera; + })(Phaser.FX || (Phaser.FX = {})); + var FX = Phaser.FX; +})(Phaser || (Phaser = {})); +var Phaser; +(function (Phaser) { + (function (FX) { + /// /** * Phaser - FX - Camera - Scanlines * @@ -254,8 +370,7 @@ var Phaser; var Phaser; (function (Phaser) { (function (FX) { - /// - /// + /// /** * Phaser - FX - Camera - Shake * @@ -267,7 +382,7 @@ var Phaser; this._fxShakeIntensity = 0; this._fxShakeDuration = 0; this._fxShakeComplete = null; - this._fxShakeOffset = new Phaser.MicroPoint(0, 0); + this._fxShakeOffset = new Phaser.Point(0, 0); this._fxShakeDirection = 0; this._fxShakePrevX = 0; this._fxShakePrevY = 0; @@ -347,8 +462,7 @@ var Phaser; var Phaser; (function (Phaser) { (function (FX) { - /// - /// + /// /** * Phaser - FX - Camera - Fade * diff --git a/Tests/phaser.js b/Tests/phaser.js index 37c35bb80..9fcb30c69 100644 --- a/Tests/phaser.js +++ b/Tests/phaser.js @@ -1,2805 +1,448 @@ -/// -/** -* Phaser - Basic -* -* A useful "generic" object on which all GameObjects and Groups are based. -* It has no size, position or graphical data. -*/ -var Phaser; -(function (Phaser) { - var Basic = (function () { - /** - * Instantiate the basic object. - */ - function Basic(game) { - /** - * Allows you to give this object a name. Useful for debugging, but not actually used internally. - */ - this.name = ''; - this._game = game; - this.ID = -1; - this.exists = true; - this.active = true; - this.visible = true; - this.alive = true; - this.isGroup = false; - this.ignoreGlobalUpdate = false; - this.ignoreGlobalRender = false; - this.ignoreDrawDebug = false; - } - Basic.prototype.destroy = /** - * Override this to null out iables or manually call - * destroy() on class members if necessary. - * Don't forget to call super.destroy()! - */ - function () { - }; - Basic.prototype.preUpdate = /** - * Pre-update is called right before update() on each object in the game loop. - */ - function () { - }; - Basic.prototype.update = /** - * Override this to update your class's position and appearance. - * This is where most of your game rules and behavioral code will go. - */ - function (forceUpdate) { - if (typeof forceUpdate === "undefined") { forceUpdate = false; } - }; - Basic.prototype.postUpdate = /** - * Post-update is called right after update() on each object in the game loop. - */ - function () { - }; - Basic.prototype.render = function (camera, cameraOffsetX, cameraOffsetY, forceRender) { - if (typeof forceRender === "undefined") { forceRender = false; } - }; - Basic.prototype.kill = /** - * Handy for "killing" game objects. - * Default behavior is to flag them as nonexistent AND dead. - * However, if you want the "corpse" to remain in the game, - * like to animate an effect or whatever, you should override this, - * setting only alive to false, and leaving exists true. - */ - function () { - this.alive = false; - this.exists = false; - }; - Basic.prototype.revive = /** - * Handy for bringing game objects "back to life". Just sets alive and exists back to true. - * In practice, this is most often called by Object.reset(). - */ - function () { - this.alive = true; - this.exists = true; - }; - Basic.prototype.toString = /** - * Convert object to readable string name. Useful for debugging, save games, etc. - */ - function () { - return ""; - }; - return Basic; - })(); - Phaser.Basic = Basic; -})(Phaser || (Phaser = {})); -/// -/** -* Phaser - SignalBinding -* -* An object that represents a binding between a Signal and a listener function. -* Based on JS Signals by Miller Medeiros. Converted by TypeScript by Richard Davey. -* Released under the MIT license -* http://millermedeiros.github.com/js-signals/ -*/ -var Phaser; -(function (Phaser) { - var SignalBinding = (function () { - /** - * Object that represents a binding between a Signal and a listener function. - *
- This is an internal constructor and shouldn't be called by regular users. - *
- inspired by Joa Ebert AS3 SignalBinding and Robert Penner's Slot classes. - * @author Miller Medeiros - * @constructor - * @internal - * @name SignalBinding - * @param {Signal} signal Reference to Signal object that listener is currently bound to. - * @param {Function} listener Handler function bound to the signal. - * @param {boolean} isOnce If binding should be executed just once. - * @param {Object} [listenerContext] Context on which listener will be executed (object that should represent the `this` variable inside listener function). - * @param {Number} [priority] The priority level of the event listener. (default = 0). - */ - function SignalBinding(signal, listener, isOnce, listenerContext, priority) { - if (typeof priority === "undefined") { priority = 0; } - /** - * If binding is active and should be executed. - * @type boolean - */ - this.active = true; - /** - * Default parameters passed to listener during `Signal.dispatch` and `SignalBinding.execute`. (curried parameters) - * @type Array|null - */ - this.params = null; - this._listener = listener; - this._isOnce = isOnce; - this.context = listenerContext; - this._signal = signal; - this.priority = priority || 0; - } - SignalBinding.prototype.execute = /** - * Call listener passing arbitrary parameters. - *

If binding was added using `Signal.addOnce()` it will be automatically removed from signal dispatch queue, this method is used internally for the signal dispatch.

- * @param {Array} [paramsArr] Array of parameters that should be passed to the listener - * @return {*} Value returned by the listener. - */ - function (paramsArr) { - var handlerReturn; - var params; - if(this.active && !!this._listener) { - params = this.params ? this.params.concat(paramsArr) : paramsArr; - handlerReturn = this._listener.apply(this.context, params); - if(this._isOnce) { - this.detach(); - } - } - return handlerReturn; - }; - SignalBinding.prototype.detach = /** - * Detach binding from signal. - * - alias to: mySignal.remove(myBinding.getListener()); - * @return {Function|null} Handler function bound to the signal or `null` if binding was previously detached. - */ - function () { - return this.isBound() ? this._signal.remove(this._listener, this.context) : null; - }; - SignalBinding.prototype.isBound = /** - * @return {Boolean} `true` if binding is still bound to the signal and have a listener. - */ - function () { - return (!!this._signal && !!this._listener); - }; - SignalBinding.prototype.isOnce = /** - * @return {boolean} If SignalBinding will only be executed once. - */ - function () { - return this._isOnce; - }; - SignalBinding.prototype.getListener = /** - * @return {Function} Handler function bound to the signal. - */ - function () { - return this._listener; - }; - SignalBinding.prototype.getSignal = /** - * @return {Signal} Signal that listener is currently bound to. - */ - function () { - return this._signal; - }; - SignalBinding.prototype._destroy = /** - * Delete instance properties - * @private - */ - function () { - delete this._signal; - delete this._listener; - delete this.context; - }; - SignalBinding.prototype.toString = /** - * @return {string} String representation of the object. - */ - function () { - return '[SignalBinding isOnce:' + this._isOnce + ', isBound:' + this.isBound() + ', active:' + this.active + ']'; - }; - return SignalBinding; - })(); - Phaser.SignalBinding = SignalBinding; -})(Phaser || (Phaser = {})); -/// -/** -* Phaser - Signal -* -* A Signal is used for object communication via a custom broadcaster instead of Events. -* Based on JS Signals by Miller Medeiros. Converted by TypeScript by Richard Davey. -* Released under the MIT license -* http://millermedeiros.github.com/js-signals/ -*/ -var Phaser; -(function (Phaser) { - var Signal = (function () { - function Signal() { - /** - * - * @property _bindings - * @type Array - * @private - */ - this._bindings = []; - /** - * - * @property _prevParams - * @type Any - * @private - */ - this._prevParams = null; - /** - * If Signal should keep record of previously dispatched parameters and - * automatically execute listener during `add()`/`addOnce()` if Signal was - * already dispatched before. - * @type boolean - */ - this.memorize = false; - /** - * @type boolean - * @private - */ - this._shouldPropagate = true; - /** - * If Signal is active and should broadcast events. - *

IMPORTANT: Setting this property during a dispatch will only affect the next dispatch, if you want to stop the propagation of a signal use `halt()` instead.

- * @type boolean - */ - this.active = true; - } - Signal.VERSION = '1.0.0'; - Signal.prototype.validateListener = /** - * - * @method validateListener - * @param {Any} listener - * @param {Any} fnName - */ - function (listener, fnName) { - if(typeof listener !== 'function') { - throw new Error('listener is a required param of {fn}() and should be a Function.'.replace('{fn}', fnName)); - } - }; - Signal.prototype._registerListener = /** - * @param {Function} listener - * @param {boolean} isOnce - * @param {Object} [listenerContext] - * @param {Number} [priority] - * @return {SignalBinding} - * @private - */ - function (listener, isOnce, listenerContext, priority) { - var prevIndex = this._indexOfListener(listener, listenerContext); - var binding; - if(prevIndex !== -1) { - binding = this._bindings[prevIndex]; - if(binding.isOnce() !== isOnce) { - throw new Error('You cannot add' + (isOnce ? '' : 'Once') + '() then add' + (!isOnce ? '' : 'Once') + '() the same listener without removing the relationship first.'); - } - } else { - binding = new Phaser.SignalBinding(this, listener, isOnce, listenerContext, priority); - this._addBinding(binding); - } - if(this.memorize && this._prevParams) { - binding.execute(this._prevParams); - } - return binding; - }; - Signal.prototype._addBinding = /** - * - * @method _addBinding - * @param {SignalBinding} binding - * @private - */ - function (binding) { - //simplified insertion sort - var n = this._bindings.length; - do { - --n; - }while(this._bindings[n] && binding.priority <= this._bindings[n].priority); - this._bindings.splice(n + 1, 0, binding); - }; - Signal.prototype._indexOfListener = /** - * - * @method _indexOfListener - * @param {Function} listener - * @return {number} - * @private - */ - function (listener, context) { - var n = this._bindings.length; - var cur; - while(n--) { - cur = this._bindings[n]; - if(cur.getListener() === listener && cur.context === context) { - return n; - } - } - return -1; - }; - Signal.prototype.has = /** - * Check if listener was attached to Signal. - * @param {Function} listener - * @param {Object} [context] - * @return {boolean} if Signal has the specified listener. - */ - function (listener, context) { - if (typeof context === "undefined") { context = null; } - return this._indexOfListener(listener, context) !== -1; - }; - Signal.prototype.add = /** - * Add a listener to the signal. - * @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 {SignalBinding} An Object representing the binding between the Signal and listener. - */ - function (listener, listenerContext, priority) { - if (typeof listenerContext === "undefined") { listenerContext = null; } - if (typeof priority === "undefined") { priority = 0; } - this.validateListener(listener, 'add'); - return this._registerListener(listener, false, listenerContext, priority); - }; - Signal.prototype.addOnce = /** - * Add listener to the signal that should be removed after first execution (will be executed only once). - * @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 {SignalBinding} An Object representing the binding between the Signal and listener. - */ - function (listener, listenerContext, priority) { - if (typeof listenerContext === "undefined") { listenerContext = null; } - if (typeof priority === "undefined") { priority = 0; } - this.validateListener(listener, 'addOnce'); - return this._registerListener(listener, true, listenerContext, priority); - }; - Signal.prototype.remove = /** - * Remove a single listener from the dispatch queue. - * @param {Function} listener Handler function that should be removed. - * @param {Object} [context] Execution context (since you can add the same handler multiple times if executing in a different context). - * @return {Function} Listener handler function. - */ - function (listener, context) { - if (typeof context === "undefined") { context = null; } - this.validateListener(listener, 'remove'); - var i = this._indexOfListener(listener, context); - if(i !== -1) { - this._bindings[i]._destroy(); - this._bindings.splice(i, 1); - } - return listener; - }; - Signal.prototype.removeAll = /** - * Remove all listeners from the Signal. - */ - function () { - if(this._bindings) { - var n = this._bindings.length; - while(n--) { - this._bindings[n]._destroy(); - } - this._bindings.length = 0; - } - }; - Signal.prototype.getNumListeners = /** - * @return {number} Number of listeners attached to the Signal. - */ - function () { - return this._bindings.length; - }; - Signal.prototype.halt = /** - * Stop propagation of the event, blocking the dispatch to next listeners on the queue. - *

IMPORTANT: should be called only during signal dispatch, calling it before/after dispatch won't affect signal broadcast.

- * @see Signal.prototype.disable - */ - function () { - this._shouldPropagate = false; - }; - Signal.prototype.dispatch = /** - * Dispatch/Broadcast Signal to all listeners added to the queue. - * @param {...*} [params] Parameters that should be passed to each handler. - */ - function () { - var paramsArr = []; - for (var _i = 0; _i < (arguments.length - 0); _i++) { - paramsArr[_i] = arguments[_i + 0]; - } - if(!this.active) { - return; - } - var n = this._bindings.length; - var bindings; - if(this.memorize) { - this._prevParams = paramsArr; - } - if(!n) { - //should come after memorize - return; - } - bindings = this._bindings.slice(0)//clone array in case add/remove items during dispatch - ; - this._shouldPropagate = true//in case `halt` was called before dispatch or during the previous dispatch. - ; - //execute all callbacks until end of the list or until a callback returns `false` or stops propagation - //reverse loop since listeners with higher priority will be added at the end of the list - do { - n--; - }while(bindings[n] && this._shouldPropagate && bindings[n].execute(paramsArr) !== false); - }; - Signal.prototype.forget = /** - * Forget memorized arguments. - * @see Signal.memorize - */ - function () { - this._prevParams = null; - }; - Signal.prototype.dispose = /** - * Remove all bindings from signal and destroy any reference to external objects (destroy Signal object). - *

IMPORTANT: calling any method on the signal instance after calling dispose will throw errors.

- */ - function () { - this.removeAll(); - delete this._bindings; - delete this._prevParams; - }; - Signal.prototype.toString = /** - * @return {string} String representation of the object. - */ - function () { - return '[Signal active:' + this.active + ' numListeners:' + this.getNumListeners() + ']'; - }; - return Signal; - })(); - Phaser.Signal = Signal; -})(Phaser || (Phaser = {})); /// /** -* Phaser - CollisionMask +* Phaser - Loader +* +* The Loader handles loading all external content such as Images, Sounds, Texture Atlases and data files. +* It uses a combination of Image() loading and xhr and provides for progress and completion callbacks. */ var Phaser; (function (Phaser) { - var CollisionMask = (function () { + var Loader = (function () { /** - * CollisionMask constructor. Creates a new CollisionMask for the given GameObject. + * Loader constructor * * @param game {Phaser.Game} Current game instance. - * @param parent {Phaser.GameObject} The GameObject this CollisionMask belongs to. - * @param x {number} The initial x position of the CollisionMask. - * @param y {number} The initial y position of the CollisionMask. - * @param width {number} The width of the CollisionMask. - * @param height {number} The height of the CollisionMask. + * @param callback {function} This will be called when assets completely loaded. */ - function CollisionMask(game, parent, x, y, width, height) { + function Loader(game, callback) { /** - * Geom type of this sprite. (available: QUAD, POINT, CIRCLE, LINE, RECTANGLE, POLYGON) - * @type {number} + * The crossOrigin value applied to loaded images + * @type {string} */ - this.type = 0; + this.crossOrigin = ''; this._game = game; - this._parent = parent; - // By default the CollisionMask is a quad - this.type = CollisionMask.QUAD; - this.quad = new Phaser.Quad(this._parent.x, this._parent.y, this._parent.width, this._parent.height); - this.offset = new Phaser.MicroPoint(0, 0); - this.last = new Phaser.MicroPoint(0, 0); - this._ref = this.quad; - return this; + this._gameCreateComplete = callback; + this._keys = []; + this._fileList = { + }; + this._xhr = new XMLHttpRequest(); + this._queueSize = 0; } - CollisionMask.QUAD = 0; - CollisionMask.POINT = 1; - CollisionMask.CIRCLE = 2; - CollisionMask.LINE = 3; - CollisionMask.RECTANGLE = 4; - CollisionMask.POLYGON = 5; - CollisionMask.prototype.createCircle = /** - * Create a circle shape with specific diameter. - * @param diameter {number} Diameter of the circle. - * @return {CollisionMask} This - */ - function (diameter) { - this.type = CollisionMask.CIRCLE; - this.circle = new Phaser.Circle(this.last.x, this.last.y, diameter); - this._ref = this.circle; - return this; - }; - CollisionMask.prototype.preUpdate = /** - * Pre-update is called right before update() on each object in the game loop. + Loader.TEXTURE_ATLAS_JSON_ARRAY = 0; + Loader.TEXTURE_ATLAS_JSON_HASH = 1; + Loader.TEXTURE_ATLAS_XML_STARLING = 2; + Loader.prototype.reset = /** + * Reset loader, this will remove all loaded assets. */ function () { - this.last.x = this.x; - this.last.y = this.y; + this._queueSize = 0; }; - CollisionMask.prototype.update = function () { - this._ref.x = this._parent.x + this.offset.x; - this._ref.y = this._parent.y + this.offset.y; - }; - CollisionMask.prototype.render = /** - * Renders the bounding box around this Sprite and the contact points. Useful for visually debugging. - * @param camera {Camera} Camera the bound will be rendered to. - * @param cameraOffsetX {number} X offset of bound to the camera. - * @param cameraOffsetY {number} Y offset of bound to the camera. - */ - function (camera, cameraOffsetX, cameraOffsetY) { - var _dx = cameraOffsetX + (this.x - camera.worldView.x); - var _dy = cameraOffsetY + (this.y - camera.worldView.y); - this._parent.context.fillStyle = this._parent.renderDebugColor; - if(this.type == CollisionMask.QUAD) { - this._parent.context.fillRect(_dx, _dy, this.width, this.height); - } else if(this.type == CollisionMask.CIRCLE) { - this._parent.context.beginPath(); - this._parent.context.arc(_dx, _dy, this.circle.radius, 0, Math.PI * 2); - this._parent.context.fill(); - this._parent.context.closePath(); - } - }; - CollisionMask.prototype.destroy = /** - * Destroy all objects and references belonging to this CollisionMask - */ - function () { - this._game = null; - this._parent = null; - this._ref = null; - this.quad = null; - this.point = null; - this.circle = null; - this.rect = null; - this.line = null; - this.offset = null; - }; - CollisionMask.prototype.intersectsRaw = function (left, right, top, bottom) { - //if ((objBounds.x + objBounds.width > x) && (objBounds.x < x + width) && (objBounds.y + objBounds.height > y) && (objBounds.y < y + height)) - return true; - }; - CollisionMask.prototype.intersectsVector = function (vector) { - if(this.type == CollisionMask.QUAD) { - return this.quad.contains(vector.x, vector.y); - } - }; - CollisionMask.prototype.intersects = /** - * Gives a basic boolean response to a geometric collision. - * If you need the details of the collision use the Collision functions instead and inspect the IntersectResult object. - * @param source {GeomSprite} Sprite you want to check. - * @return {boolean} Whether they overlaps or not. - */ - function (source) { - // Quad vs. Quad - if(this.type == CollisionMask.QUAD && source.type == CollisionMask.QUAD) { - return this.quad.intersects(source.quad); - } - // Circle vs. Circle - if(this.type == CollisionMask.CIRCLE && source.type == CollisionMask.CIRCLE) { - return Phaser.Collision.circleToCircle(this.circle, source.circle).result; - } - // Circle vs. Rect - if(this.type == CollisionMask.CIRCLE && source.type == CollisionMask.RECTANGLE) { - return Phaser.Collision.circleToRectangle(this.circle, source.rect).result; - } - // Circle vs. Point - if(this.type == CollisionMask.CIRCLE && source.type == CollisionMask.POINT) { - return Phaser.Collision.circleContainsPoint(this.circle, source.point).result; - } - // Circle vs. Line - if(this.type == CollisionMask.CIRCLE && source.type == CollisionMask.LINE) { - return Phaser.Collision.lineToCircle(source.line, this.circle).result; - } - // Rect vs. Rect - if(this.type == CollisionMask.RECTANGLE && source.type == CollisionMask.RECTANGLE) { - return Phaser.Collision.rectangleToRectangle(this.rect, source.rect).result; - } - // Rect vs. Circle - if(this.type == CollisionMask.RECTANGLE && source.type == CollisionMask.CIRCLE) { - return Phaser.Collision.circleToRectangle(source.circle, this.rect).result; - } - // Rect vs. Point - if(this.type == CollisionMask.RECTANGLE && source.type == CollisionMask.POINT) { - return Phaser.Collision.pointToRectangle(source.point, this.rect).result; - } - // Rect vs. Line - if(this.type == CollisionMask.RECTANGLE && source.type == CollisionMask.LINE) { - return Phaser.Collision.lineToRectangle(source.line, this.rect).result; - } - // Point vs. Point - if(this.type == CollisionMask.POINT && source.type == CollisionMask.POINT) { - return this.point.equals(source.point); - } - // Point vs. Circle - if(this.type == CollisionMask.POINT && source.type == CollisionMask.CIRCLE) { - return Phaser.Collision.circleContainsPoint(source.circle, this.point).result; - } - // Point vs. Rect - if(this.type == CollisionMask.POINT && source.type == CollisionMask.RECTANGLE) { - return Phaser.Collision.pointToRectangle(this.point, source.rect).result; - } - // Point vs. Line - if(this.type == CollisionMask.POINT && source.type == CollisionMask.LINE) { - return source.line.isPointOnLine(this.point.x, this.point.y); - } - // Line vs. Line - if(this.type == CollisionMask.LINE && source.type == CollisionMask.LINE) { - return Phaser.Collision.lineSegmentToLineSegment(this.line, source.line).result; - } - // Line vs. Circle - if(this.type == CollisionMask.LINE && source.type == CollisionMask.CIRCLE) { - return Phaser.Collision.lineToCircle(this.line, source.circle).result; - } - // Line vs. Rect - if(this.type == CollisionMask.LINE && source.type == CollisionMask.RECTANGLE) { - return Phaser.Collision.lineSegmentToRectangle(this.line, source.rect).result; - } - // Line vs. Point - if(this.type == CollisionMask.LINE && source.type == CollisionMask.POINT) { - return this.line.isPointOnLine(source.point.x, source.point.y); - } - return false; - }; - CollisionMask.prototype.checkHullIntersection = function (mask) { - if((this.hullX + this.hullWidth > mask.hullX) && (this.hullX < mask.hullX + mask.width) && (this.hullY + this.hullHeight > mask.hullY) && (this.hullY < mask.hullY + mask.hullHeight)) { - return true; - } else { - return false; - } - }; - Object.defineProperty(CollisionMask.prototype, "hullWidth", { + Object.defineProperty(Loader.prototype, "queueSize", { get: function () { - if(this.deltaX > 0) { - return this.width + this.deltaX; - } else { - return this.width - this.deltaX; - } + return this._queueSize; }, enumerable: true, configurable: true }); - Object.defineProperty(CollisionMask.prototype, "hullHeight", { - get: function () { - if(this.deltaY > 0) { - return this.height + this.deltaY; - } else { - return this.height - this.deltaY; - } - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(CollisionMask.prototype, "hullX", { - get: function () { - if(this.x < this.last.x) { - return this.x; - } else { - return this.last.x; - } - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(CollisionMask.prototype, "hullY", { - get: function () { - if(this.y < this.last.y) { - return this.y; - } else { - return this.last.y; - } - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(CollisionMask.prototype, "deltaXAbs", { - get: function () { - return (this.deltaX > 0 ? this.deltaX : -this.deltaX); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(CollisionMask.prototype, "deltaYAbs", { - get: function () { - return (this.deltaY > 0 ? this.deltaY : -this.deltaY); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(CollisionMask.prototype, "deltaX", { - get: function () { - return this.x - this.last.x; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(CollisionMask.prototype, "deltaY", { - get: function () { - return this.y - this.last.y; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(CollisionMask.prototype, "x", { - get: function () { - return this._ref.x; - //return this.quad.x; - }, - set: function (value) { - this._ref.x = value; - //this.quad.x = value; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(CollisionMask.prototype, "y", { - get: function () { - return this._ref.y; - //return this.quad.y; - }, - set: function (value) { - this._ref.y = value; - //this.quad.y = value; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(CollisionMask.prototype, "width", { - get: function () { - //return this.quad.width; - return this._ref.width; - }, - set: //public get rotation(): number { - // return this._angle; - //} - //public set rotation(value: number) { - // this._angle = this._game.math.wrap(value, 360, 0); - //} - //public get angle(): number { - // return this._angle; - //} - //public set angle(value: number) { - // this._angle = this._game.math.wrap(value, 360, 0); - //} - function (value) { - //this.quad.width = value; - this._ref.width = value; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(CollisionMask.prototype, "height", { - get: function () { - //return this.quad.height; - return this._ref.height; - }, - set: function (value) { - //this.quad.height = value; - this._ref.height = value; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(CollisionMask.prototype, "left", { - get: function () { - return this.x; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(CollisionMask.prototype, "right", { - get: function () { - return this.x + this.width; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(CollisionMask.prototype, "top", { - get: function () { - return this.y; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(CollisionMask.prototype, "bottom", { - get: function () { - return this.y + this.height; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(CollisionMask.prototype, "halfWidth", { - get: function () { - return this.width / 2; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(CollisionMask.prototype, "halfHeight", { - get: function () { - return this.height / 2; - }, - enumerable: true, - configurable: true - }); - return CollisionMask; - })(); - Phaser.CollisionMask = CollisionMask; -})(Phaser || (Phaser = {})); -var __extends = this.__extends || function (d, b) { - function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); -}; -/// -/// -/// -/// -/** -* Phaser - GameObject -* -* This is the base GameObject on which all other game objects are derived. It contains all the logic required for position, -* motion, size, collision and input. -*/ -var Phaser; -(function (Phaser) { - var GameObject = (function (_super) { - __extends(GameObject, _super); - /** - * GameObject constructor - * - * Create a new GameObject object at specific position with specific width and height. - * - * @param [x] {number} The x position of the object. - * @param [y] {number} The y position of the object. - * @param [width] {number} The width of the object. - * @param [height] {number} The height of the object. + Loader.prototype.addImageFile = /** + * Add a new image asset loading request with key and url. + * @param key {string} Unique asset key of this image file. + * @param url {string} URL of image file. */ - function GameObject(game, x, y, width, height) { - if (typeof x === "undefined") { x = 0; } - if (typeof y === "undefined") { y = 0; } - if (typeof width === "undefined") { width = 16; } - if (typeof height === "undefined") { height = 16; } - _super.call(this, game); - /** - * Angle of this object. - * @type {number} - */ - this._angle = 0; - /** - * What action will be performed when object is out of the worldBounds. - * This will default to GameObject.OUT_OF_BOUNDS_STOP. - * @type {number} - */ - this.outOfBoundsAction = 0; - /** - * Z-order value of the object. - */ - this.z = 0; - /** - * This value is added to the angle of the GameObject. - * For example if you had a sprite drawn facing straight up then you could set - * rotationOffset to 90 and it would correspond correctly with Phasers rotation system - * @type {number} - */ - this.rotationOffset = 0; - /** - * Controls if the GameObject is rendered rotated or not. - * If renderRotation is false then the object can still rotate but it will never be rendered rotated. - * @type {boolean} - */ - this.renderRotation = true; - /** - * Set this to false if you want to skip the automatic motion/movement stuff - * (see updateMotion()). - * @type {boolean} - */ - this.moves = true; - // Input - this.inputEnabled = false; - this._inputOver = false; - this.canvas = game.stage.canvas; - this.context = game.stage.context; - this.frameBounds = new Phaser.Rectangle(x, y, width, height); - this.exists = true; - this.active = true; - this.visible = true; - this.alive = true; - this.isGroup = false; - this.alpha = 1; - this.scale = new Phaser.MicroPoint(1, 1); - this.last = new Phaser.MicroPoint(x, y); - this.align = GameObject.ALIGN_TOP_LEFT; - this.mass = 1; - this.elasticity = 0; - this.health = 1; - this.immovable = false; - this.moves = true; - this.worldBounds = null; - this.touching = Phaser.Collision.NONE; - this.wasTouching = Phaser.Collision.NONE; - this.allowCollisions = Phaser.Collision.ANY; - this.velocity = new Phaser.MicroPoint(); - this.acceleration = new Phaser.MicroPoint(); - this.drag = new Phaser.MicroPoint(); - this.maxVelocity = new Phaser.MicroPoint(10000, 10000); - this.angle = 0; - this.angularVelocity = 0; - this.angularAcceleration = 0; - this.angularDrag = 0; - this.maxAngular = 10000; - this.cameraBlacklist = []; - this.scrollFactor = new Phaser.MicroPoint(1, 1); - this.collisionMask = new Phaser.CollisionMask(game, this, x, y, width, height); - } - GameObject.ALIGN_TOP_LEFT = 0; - GameObject.ALIGN_TOP_CENTER = 1; - GameObject.ALIGN_TOP_RIGHT = 2; - GameObject.ALIGN_CENTER_LEFT = 3; - GameObject.ALIGN_CENTER = 4; - GameObject.ALIGN_CENTER_RIGHT = 5; - GameObject.ALIGN_BOTTOM_LEFT = 6; - GameObject.ALIGN_BOTTOM_CENTER = 7; - GameObject.ALIGN_BOTTOM_RIGHT = 8; - GameObject.OUT_OF_BOUNDS_STOP = 0; - GameObject.OUT_OF_BOUNDS_KILL = 1; - GameObject.prototype.preUpdate = /** - * Pre-update is called right before update() on each object in the game loop. - */ - function () { - this.last.x = this.frameBounds.x; - this.last.y = this.frameBounds.y; - this.collisionMask.preUpdate(); - }; - GameObject.prototype.update = /** - * Override this function to update your class's position and appearance. - */ - function () { - }; - GameObject.prototype.postUpdate = /** - * Automatically called after update() by the game loop. - */ - function () { - if(this.moves) { - this.updateMotion(); - } - if(this.worldBounds != null) { - if(this.outOfBoundsAction == GameObject.OUT_OF_BOUNDS_KILL) { - if(this.x < this.worldBounds.x || this.x > this.worldBounds.right || this.y < this.worldBounds.y || this.y > this.worldBounds.bottom) { - this.kill(); - } - } else { - if(this.x < this.worldBounds.x) { - this.x = this.worldBounds.x; - } else if(this.x > this.worldBounds.right) { - this.x = this.worldBounds.right; - } - if(this.y < this.worldBounds.y) { - this.y = this.worldBounds.y; - } else if(this.y > this.worldBounds.bottom) { - this.y = this.worldBounds.bottom; - } - } - } - this.collisionMask.update(); - if(this.inputEnabled) { - this.updateInput(); - } - this.wasTouching = this.touching; - this.touching = Phaser.Collision.NONE; - }; - GameObject.prototype.updateInput = /** - * Update input. - */ - function () { - }; - GameObject.prototype.updateMotion = /** - * Internal function for updating the position and speed of this object. - */ - function () { - var delta; - var velocityDelta; - velocityDelta = (this._game.motion.computeVelocity(this.angularVelocity, this.angularAcceleration, this.angularDrag, this.maxAngular) - this.angularVelocity) / 2; - this.angularVelocity += velocityDelta; - this._angle += this.angularVelocity * this._game.time.elapsed; - this.angularVelocity += velocityDelta; - velocityDelta = (this._game.motion.computeVelocity(this.velocity.x, this.acceleration.x, this.drag.x, this.maxVelocity.x) - this.velocity.x) / 2; - this.velocity.x += velocityDelta; - delta = this.velocity.x * this._game.time.elapsed; - this.velocity.x += velocityDelta; - this.frameBounds.x += delta; - velocityDelta = (this._game.motion.computeVelocity(this.velocity.y, this.acceleration.y, this.drag.y, this.maxVelocity.y) - this.velocity.y) / 2; - this.velocity.y += velocityDelta; - delta = this.velocity.y * this._game.time.elapsed; - this.velocity.y += velocityDelta; - this.frameBounds.y += delta; - }; - GameObject.prototype.overlaps = /** - * Checks to see if some GameObject overlaps this GameObject or Group. - * If the group has a LOT of things in it, it might be faster to use Collision.overlaps(). - * WARNING: Currently tilemaps do NOT support screen space overlap checks! - * - * @param objectOrGroup {object} The object or group being tested. - * @param inScreenSpace {boolean} Whether to take scroll factors numbero account when checking for overlap. Default is false, or "only compare in world space." - * @param camera {Camera} Specify which game camera you want. If null getScreenXY() will just grab the first global camera. - * - * @return {boolean} Whether or not the objects overlap this. - */ - function (objectOrGroup, inScreenSpace, camera) { - if (typeof inScreenSpace === "undefined") { inScreenSpace = false; } - if (typeof camera === "undefined") { camera = null; } - if(objectOrGroup.isGroup) { - var results = false; - var i = 0; - var members = objectOrGroup.members; - while(i < length) { - if(this.overlaps(members[i++], inScreenSpace, camera)) { - results = true; - } - } - return results; - } - if(!inScreenSpace) { - return (objectOrGroup.x + objectOrGroup.width > this.x) && (objectOrGroup.x < this.x + this.width) && (objectOrGroup.y + objectOrGroup.height > this.y) && (objectOrGroup.y < this.y + this.height); - } - if(camera == null) { - camera = this._game.camera; - } - var objectScreenPos = objectOrGroup.getScreenXY(null, camera); - this.getScreenXY(this._point, camera); - return (objectScreenPos.x + objectOrGroup.width > this._point.x) && (objectScreenPos.x < this._point.x + this.width) && (objectScreenPos.y + objectOrGroup.height > this._point.y) && (objectScreenPos.y < this._point.y + this.height); - }; - GameObject.prototype.overlapsAt = /** - * Checks to see if this GameObject were located at the given position, would it overlap the GameObject or Group? - * This is distinct from overlapsPoint(), which just checks that point, rather than taking the object's size numbero account. - * WARNING: Currently tilemaps do NOT support screen space overlap checks! - * - * @param X {number} The X position you want to check. Pretends this object (the caller, not the parameter) is located here. - * @param Y {number} The Y position you want to check. Pretends this object (the caller, not the parameter) is located here. - * @param objectOrGroup {object} The object or group being tested. - * @param inScreenSpace {boolean} Whether to take scroll factors numbero account when checking for overlap. Default is false, or "only compare in world space." - * @param camera {Camera} Specify which game camera you want. If null getScreenXY() will just grab the first global camera. - * - * @return {boolean} Whether or not the two objects overlap. - */ - function (X, Y, objectOrGroup, inScreenSpace, camera) { - if (typeof inScreenSpace === "undefined") { inScreenSpace = false; } - if (typeof camera === "undefined") { camera = null; } - if(objectOrGroup.isGroup) { - var results = false; - var basic; - var i = 0; - var members = objectOrGroup.members; - while(i < length) { - if(this.overlapsAt(X, Y, members[i++], inScreenSpace, camera)) { - results = true; - } - } - return results; - } - if(!inScreenSpace) { - return (objectOrGroup.x + objectOrGroup.width > X) && (objectOrGroup.x < X + this.width) && (objectOrGroup.y + objectOrGroup.height > Y) && (objectOrGroup.y < Y + this.height); - } - if(camera == null) { - camera = this._game.camera; - } - var objectScreenPos = objectOrGroup.getScreenXY(null, Phaser.Camera); - this._point.x = X - camera.scroll.x * this.scrollFactor.x//copied from getScreenXY() - ; - this._point.y = Y - camera.scroll.y * this.scrollFactor.y; - this._point.x += (this._point.x > 0) ? 0.0000001 : -0.0000001; - this._point.y += (this._point.y > 0) ? 0.0000001 : -0.0000001; - return (objectScreenPos.x + objectOrGroup.width > this._point.x) && (objectScreenPos.x < this._point.x + this.width) && (objectScreenPos.y + objectOrGroup.height > this._point.y) && (objectScreenPos.y < this._point.y + this.height); - }; - GameObject.prototype.overlapsPoint = /** - * Checks to see if a point in 2D world space overlaps this GameObject. - * - * @param point {Point} The point in world space you want to check. - * @param inScreenSpace {boolean} Whether to take scroll factors into account when checking for overlap. - * @param camera {Camera} Specify which game camera you want. If null getScreenXY() will just grab the first global camera. - * - * @return Whether or not the point overlaps this object. - */ - function (point, inScreenSpace, camera) { - if (typeof inScreenSpace === "undefined") { inScreenSpace = false; } - if (typeof camera === "undefined") { camera = null; } - if(!inScreenSpace) { - return (point.x > this.x) && (point.x < this.x + this.width) && (point.y > this.y) && (point.y < this.y + this.height); - } - if(camera == null) { - camera = this._game.camera; - } - var X = point.x - camera.scroll.x; - var Y = point.y - camera.scroll.y; - this.getScreenXY(this._point, camera); - return (X > this._point.x) && (X < this._point.x + this.width) && (Y > this._point.y) && (Y < this._point.y + this.height); - }; - GameObject.prototype.onScreen = /** - * Check and see if this object is currently on screen. - * - * @param camera {Camera} Specify which game camera you want. If null getScreenXY() will just grab the first global camera. - * - * @return {boolean} Whether the object is on screen or not. - */ - function (camera) { - if (typeof camera === "undefined") { camera = null; } - if(camera == null) { - camera = this._game.camera; - } - this.getScreenXY(this._point, camera); - return (this._point.x + this.width > 0) && (this._point.x < camera.width) && (this._point.y + this.height > 0) && (this._point.y < camera.height); - }; - GameObject.prototype.getScreenXY = /** - * Call this to figure out the on-screen position of the object. - * - * @param point {Point} Takes a MicroPoint object and assigns the post-scrolled X and Y values of this object to it. - * @param camera {Camera} Specify which game camera you want. If null getScreenXY() will just grab the first global camera. - * - * @return {MicroPoint} The MicroPoint you passed in, or a new Point if you didn't pass one, containing the screen X and Y position of this object. - */ - function (point, camera) { - if (typeof point === "undefined") { point = null; } - if (typeof camera === "undefined") { camera = null; } - if(point == null) { - point = new Phaser.MicroPoint(); - } - if(camera == null) { - camera = this._game.camera; - } - point.x = this.x - camera.scroll.x * this.scrollFactor.x; - point.y = this.y - camera.scroll.y * this.scrollFactor.y; - point.x += (point.x > 0) ? 0.0000001 : -0.0000001; - point.y += (point.y > 0) ? 0.0000001 : -0.0000001; - return point; - }; - Object.defineProperty(GameObject.prototype, "solid", { - get: /** - * Whether the object collides or not. For more control over what directions - * the object will collide from, use collision constants (like LEFT, FLOOR, etc) - * to set the value of allowCollisions directly. - */ - function () { - return (this.allowCollisions & Phaser.Collision.ANY) > Phaser.Collision.NONE; - }, - set: function (value) { - if(value) { - this.allowCollisions = Phaser.Collision.ANY; - } else { - this.allowCollisions = Phaser.Collision.NONE; - } - }, - enumerable: true, - configurable: true - }); - GameObject.prototype.getMidpoint = /** - * Retrieve the midpoint of this object in world coordinates. - * - * @param point {Point} Allows you to pass in an existing Point object if you're so inclined. Otherwise a new one is created. - * - * @return {MicroPoint} A Point object containing the midpoint of this object in world coordinates. - */ - function (point) { - if (typeof point === "undefined") { point = null; } - if(point == null) { - point = new Phaser.MicroPoint(); - } - point.copyFrom(this.frameBounds.center); - return point; - }; - GameObject.prototype.reset = /** - * Handy for reviving game objects. - * Resets their existence flags and position. - * - * @param x {number} The new X position of this object. - * @param y {number} The new Y position of this object. - */ - function (x, y) { - this.revive(); - this.touching = Phaser.Collision.NONE; - this.wasTouching = Phaser.Collision.NONE; - this.x = x; - this.y = y; - this.last.x = x; - this.last.y = y; - this.velocity.x = 0; - this.velocity.y = 0; - }; - GameObject.prototype.isTouching = /** - * Handy for checking if this object is touching a particular surface. - * For slightly better performance you can just & the value directly into touching. - * However, this method is good for readability and accessibility. - * - * @param Direction {number} Any of the collision flags (e.g. LEFT, FLOOR, etc). - * - * @return {boolean} Whether the object is touching an object in (any of) the specified direction(s) this frame. - */ - function (direction) { - return (this.touching & direction) > Phaser.Collision.NONE; - }; - GameObject.prototype.justTouched = /** - * Handy function for checking if this object just landed on a particular surface. - * - * @param Direction {number} Any of the collision flags (e.g. LEFT, FLOOR, etc). - * - * @returns {boolean} Whether the object just landed on any specicied surfaces. - */ - function (direction) { - return ((this.touching & direction) > Phaser.Collision.NONE) && ((this.wasTouching & direction) <= Phaser.Collision.NONE); - }; - GameObject.prototype.hurt = /** - * Reduces the "health" variable of this sprite by the amount specified in Damage. - * Calls kill() if health drops to or below zero. - * - * @param Damage {number} How much health to take away (use a negative number to give a health bonus). - */ - function (damage) { - this.health = this.health - damage; - if(this.health <= 0) { - this.kill(); + function (key, url) { + if(this.checkKeyExists(key) === false) { + this._queueSize++; + this._fileList[key] = { + type: 'image', + key: key, + url: url, + data: null, + error: false, + loaded: false + }; + this._keys.push(key); } }; - GameObject.prototype.setBounds = /** - * Set the world bounds that this GameObject can exist within. By default a GameObject can exist anywhere - * in the world. But by setting the bounds (which are given in world dimensions, not screen dimensions) - * it can be stopped from leaving the world, or a section of it. - * - * @param x {number} x position of the bound - * @param y {number} y position of the bound - * @param width {number} width of its bound - * @param height {number} height of its bound + Loader.prototype.addSpriteSheet = /** + * Add a new sprite sheet loading request. + * @param key {string} Unique asset key of the sheet file. + * @param url {string} URL of sheet file. + * @param frameWidth {number} Width of each single frame. + * @param frameHeight {number} Height of each single frame. + * @param frameMax {number} How many frames in this sprite sheet. */ - function (x, y, width, height) { - this.worldBounds = new Phaser.Quad(x, y, width, height); - }; - GameObject.prototype.setBoundsFromWorld = /** - * Set the world bounds that this GameObject can exist within based on the size of the current game world. - * - * @param action {number} The action to take if the object hits the world bounds, either OUT_OF_BOUNDS_KILL or OUT_OF_BOUNDS_STOP - */ - function (action) { - if (typeof action === "undefined") { action = GameObject.OUT_OF_BOUNDS_STOP; } - this.setBounds(this._game.world.bounds.x, this._game.world.bounds.y, this._game.world.bounds.width, this._game.world.bounds.height); - this.outOfBoundsAction = action; - }; - GameObject.prototype.hideFromCamera = /** - * If you do not wish this object to be visible to a specific camera, pass the camera here. - * - * @param camera {Camera} The specific camera. - */ - function (camera) { - if(this.cameraBlacklist.indexOf(camera.ID) == -1) { - this.cameraBlacklist.push(camera.ID); + function (key, url, frameWidth, frameHeight, frameMax) { + if (typeof frameMax === "undefined") { frameMax = -1; } + if(this.checkKeyExists(key) === false) { + this._queueSize++; + this._fileList[key] = { + type: 'spritesheet', + key: key, + url: url, + data: null, + frameWidth: frameWidth, + frameHeight: frameHeight, + frameMax: frameMax, + error: false, + loaded: false + }; + this._keys.push(key); } }; - GameObject.prototype.showToCamera = /** - * Make this object only visible to a specific camera. - * - * @param camera {Camera} The camera you wish it to be visible. + Loader.prototype.addTextureAtlas = /** + * Add a new texture atlas loading request. + * @param key {string} Unique asset key of the texture atlas file. + * @param textureURL {string} The url of the texture atlas image file. + * @param [atlasURL] {string} The url of the texture atlas data file (json/xml) + * @param [atlasData] {object} A JSON or XML data object. + * @param [format] {number} A value describing the format of the data. */ - function (camera) { - if(this.cameraBlacklist.indexOf(camera.ID) !== -1) { - this.cameraBlacklist.slice(this.cameraBlacklist.indexOf(camera.ID), 1); - } - }; - GameObject.prototype.clearCameraList = /** - * This clears the camera black list, making the GameObject visible to all cameras. - */ - function () { - this.cameraBlacklist.length = 0; - }; - GameObject.prototype.destroy = /** - * Clean up memory. - */ - function () { - }; - GameObject.prototype.setPosition = function (x, y) { - this.x = x; - this.y = y; - }; - Object.defineProperty(GameObject.prototype, "x", { - get: function () { - return this.frameBounds.x; - }, - set: function (value) { - this.frameBounds.x = value; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(GameObject.prototype, "y", { - get: function () { - return this.frameBounds.y; - }, - set: function (value) { - this.frameBounds.y = value; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(GameObject.prototype, "rotation", { - get: function () { - return this._angle; - }, - set: function (value) { - this._angle = this._game.math.wrap(value, 360, 0); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(GameObject.prototype, "angle", { - get: function () { - return this._angle; - }, - set: function (value) { - this._angle = this._game.math.wrap(value, 360, 0); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(GameObject.prototype, "width", { - get: function () { - return this.frameBounds.width; - }, - set: function (value) { - this.frameBounds.width = value; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(GameObject.prototype, "height", { - get: function () { - return this.frameBounds.height; - }, - set: function (value) { - this.frameBounds.height = value; - }, - enumerable: true, - configurable: true - }); - return GameObject; - })(Phaser.Basic); - Phaser.GameObject = GameObject; -})(Phaser || (Phaser = {})); -/// -/// -/** -* Phaser - Camera -* -* A Camera is your view into the game world. It has a position, size, scale and rotation and renders only those objects -* within its field of view. The game automatically creates a single Stage sized camera on boot, but it can be changed and -* additional cameras created via the CameraManager. -*/ -var Phaser; -(function (Phaser) { - var Camera = (function () { - /** - *Sprite constructor - * Instantiates a new camera at the specified location, with the specified size and zoom level. - * - * @param game {Phaser.Game} Current game instance. - * @param id {number} Unique identity. - * @param x {number} X location of the camera's display in pixels. Uses native, 1:1 resolution, ignores zoom. - * @param y {number} Y location of the camera's display in pixels. Uses native, 1:1 resolution, ignores zoom. - * @param width {number} The width of the camera display in pixels. - * @param height {number} The height of the camera display in pixels. - */ - function Camera(game, id, x, y, width, height) { - this._clip = false; - this._rotation = 0; - this._target = null; - this._sx = 0; - this._sy = 0; - /** - * Scale factor of the camera. - * @type {MicroPoint} - */ - this.scale = new Phaser.MicroPoint(1, 1); - /** - * Scrolling factor. - * @type {MicroPoint} - */ - this.scroll = new Phaser.MicroPoint(0, 0); - /** - * Camera bounds. - * @type {Rectangle} - */ - this.bounds = null; - /** - * Sprite moving inside this rectangle will not cause camera moving. - * @type {Rectangle} - */ - this.deadzone = null; - // Camera Border - this.disableClipping = false; - /** - * Whether render border of this camera or not. (default is false) - * @type {boolean} - */ - this.showBorder = false; - /** - * Color of border of this camera. (in css color string) - * @type {string} - */ - this.borderColor = 'rgb(255,255,255)'; - /** - * Whether the camera background is opaque or not. If set to true the Camera is filled with - * the value of Camera.backgroundColor every frame. - * @type {boolean} - */ - this.opaque = false; - /** - * Clears the camera every frame using a canvas clearRect call (default to true). - * Note that this erases anything below the camera as well, so do not use it in conjuction with a camera - * that uses alpha or that needs to be able to manage opacity. Equally if Camera.opaque is set to true - * then set Camera.clear to false to save rendering time. - * By default the Stage will clear itself every frame, so be sure not to double-up clear calls. - * @type {boolean} - */ - this.clear = false; - /** - * Background color in css color string. - * @type {string} - */ - this._bgColor = 'rgb(0,0,0)'; - /** - * Background texture repeat style. (default is 'repeat') - * @type {string} - */ - this._bgTextureRepeat = 'repeat'; - // Camera Shadow - /** - * Render camera shadow or not. (default is false) - * @type {boolean} - */ - this.showShadow = false; - /** - * Color of shadow, in css color string. - * @type {string} - */ - this.shadowColor = 'rgb(0,0,0)'; - /** - * Blur factor of shadow. - * @type {number} - */ - this.shadowBlur = 10; - /** - * Offset of the shadow from camera's position. - * @type {MicroPoint} - */ - this.shadowOffset = new Phaser.MicroPoint(4, 4); - /** - * Whether this camera visible or not. (default is true) - * @type {boolean} - */ - this.visible = true; - /** - * Alpha of the camera. (everything rendered to this camera will be affected) - * @type {number} - */ - this.alpha = 1; - /** - * The x position of the current input event in world coordinates. - * @type {number} - */ - this.inputX = 0; - /** - * The y position of the current input event in world coordinates. - * @type {number} - */ - this.inputY = 0; - this._game = game; - this.ID = id; - this._stageX = x; - this._stageY = y; - this.fx = new Phaser.FXManager(this._game, this); - // The view into the world canvas we wish to render - this.worldView = new Phaser.Rectangle(0, 0, width, height); - this.checkClip(); - } - Camera.STYLE_LOCKON = 0; - Camera.STYLE_PLATFORMER = 1; - Camera.STYLE_TOPDOWN = 2; - Camera.STYLE_TOPDOWN_TIGHT = 3; - Camera.prototype.follow = /** - * Tells this camera object what sprite to track. - * @param target {Sprite} The object you want the camera to track. Set to null to not follow anything. - * @param [style] {number} Leverage one of the existing "deadzone" presets. If you use a custom deadzone, ignore this parameter and manually specify the deadzone after calling follow(). - */ - function (target, style) { - if (typeof style === "undefined") { style = Camera.STYLE_LOCKON; } - this._target = target; - var helper; - switch(style) { - case Camera.STYLE_PLATFORMER: - var w = this.width / 8; - var h = this.height / 3; - this.deadzone = new Phaser.Rectangle((this.width - w) / 2, (this.height - h) / 2 - h * 0.25, w, h); - break; - case Camera.STYLE_TOPDOWN: - helper = Math.max(this.width, this.height) / 4; - this.deadzone = new Phaser.Rectangle((this.width - helper) / 2, (this.height - helper) / 2, helper, helper); - break; - case Camera.STYLE_TOPDOWN_TIGHT: - helper = Math.max(this.width, this.height) / 8; - this.deadzone = new Phaser.Rectangle((this.width - helper) / 2, (this.height - helper) / 2, helper, helper); - break; - case Camera.STYLE_LOCKON: - default: - this.deadzone = null; - break; - } - }; - Camera.prototype.focusOnXY = /** - * Move the camera focus to this location instantly. - * @param x {number} X position. - * @param y {number} Y position. - */ - function (x, y) { - x += (x > 0) ? 0.0000001 : -0.0000001; - y += (y > 0) ? 0.0000001 : -0.0000001; - this.scroll.x = Math.round(x - this.worldView.halfWidth); - this.scroll.y = Math.round(y - this.worldView.halfHeight); - }; - Camera.prototype.focusOn = /** - * Move the camera focus to this location instantly. - * @param point {any} Point you want to focus. - */ - function (point) { - point.x += (point.x > 0) ? 0.0000001 : -0.0000001; - point.y += (point.y > 0) ? 0.0000001 : -0.0000001; - this.scroll.x = Math.round(point.x - this.worldView.halfWidth); - this.scroll.y = Math.round(point.y - this.worldView.halfHeight); - }; - Camera.prototype.setBounds = /** - * Specify the boundaries of the world or where the camera is allowed to move. - * - * @param x {number} The smallest X value of your world (usually 0). - * @param y {number} The smallest Y value of your world (usually 0). - * @param width {number} The largest X value of your world (usually the world width). - * @param height {number} The largest Y value of your world (usually the world height). - */ - function (x, y, width, height) { - if (typeof x === "undefined") { x = 0; } - if (typeof y === "undefined") { y = 0; } - if (typeof width === "undefined") { width = 0; } - if (typeof height === "undefined") { height = 0; } - if(this.bounds == null) { - this.bounds = new Phaser.Rectangle(); - } - this.bounds.setTo(x, y, width, height); - this.scroll.setTo(0, 0); - this.update(); - }; - Camera.prototype.update = /** - * Update focusing and scrolling. - */ - function () { - this.fx.preUpdate(); - if(this._target !== null) { - if(this.deadzone == null) { - this.focusOnXY(this._target.x, this._target.y); - } else { - var edge; - var targetX = this._target.x + ((this._target.x > 0) ? 0.0000001 : -0.0000001); - var targetY = this._target.y + ((this._target.y > 0) ? 0.0000001 : -0.0000001); - edge = targetX - this.deadzone.x; - if(this.scroll.x > edge) { - this.scroll.x = edge; - } - edge = targetX + this._target.width - this.deadzone.x - this.deadzone.width; - if(this.scroll.x < edge) { - this.scroll.x = edge; - } - edge = targetY - this.deadzone.y; - if(this.scroll.y > edge) { - this.scroll.y = edge; - } - edge = targetY + this._target.height - this.deadzone.y - this.deadzone.height; - if(this.scroll.y < edge) { - this.scroll.y = edge; - } - } - } - // Make sure we didn't go outside the cameras bounds - if(this.bounds !== null) { - if(this.scroll.x < this.bounds.left) { - this.scroll.x = this.bounds.left; - } - if(this.scroll.x > this.bounds.right - this.width) { - this.scroll.x = (this.bounds.right - this.width) + 1; - } - if(this.scroll.y < this.bounds.top) { - this.scroll.y = this.bounds.top; - } - if(this.scroll.y > this.bounds.bottom - this.height) { - this.scroll.y = (this.bounds.bottom - this.height) + 1; - } - } - this.worldView.x = this.scroll.x; - this.worldView.y = this.scroll.y; - // Input values - this.inputX = this.worldView.x + this._game.input.x; - this.inputY = this.worldView.y + this._game.input.y; - this.fx.postUpdate(); - }; - Camera.prototype.render = /** - * Draw background, shadow, effects, and objects if this is visible. - */ - function () { - if(this.visible === false || this.alpha < 0.1) { - return; - } - if(this._rotation !== 0 || this._clip || this.scale.x !== 1 || this.scale.y !== 1) { - this._game.stage.context.save(); - } - // It may be safer/quicker to just save the context every frame regardless (needs testing on mobile - sucked on Android 2.x) - //this._game.stage.context.save(); - this.fx.preRender(this, this._stageX, this._stageY, this.worldView.width, this.worldView.height); - if(this.alpha !== 1) { - this._game.stage.context.globalAlpha = this.alpha; - } - this._sx = this._stageX; - this._sy = this._stageY; - // Shadow - if(this.showShadow == true) { - this._game.stage.context.shadowColor = this.shadowColor; - this._game.stage.context.shadowBlur = this.shadowBlur; - this._game.stage.context.shadowOffsetX = this.shadowOffset.x; - this._game.stage.context.shadowOffsetY = this.shadowOffset.y; - } - // Scale on - if(this.scale.x !== 1 || this.scale.y !== 1) { - this._game.stage.context.scale(this.scale.x, this.scale.y); - this._sx = this._sx / this.scale.x; - this._sy = this._sy / this.scale.y; - } - // Rotation - translate to the mid-point of the camera - if(this._rotation !== 0) { - this._game.stage.context.translate(this._sx + this.worldView.halfWidth, this._sy + this.worldView.halfHeight); - this._game.stage.context.rotate(this._rotation * (Math.PI / 180)); - // now shift back to where that should actually render - this._game.stage.context.translate(-(this._sx + this.worldView.halfWidth), -(this._sy + this.worldView.halfHeight)); - } - if(this.clear == true) { - this._game.stage.context.clearRect(this._sx, this._sy, this.worldView.width, this.worldView.height); - } - // Background - if(this.opaque == true) { - if(this._bgTexture) { - this._game.stage.context.fillStyle = this._bgTexture; - this._game.stage.context.fillRect(this._sx, this._sy, this.worldView.width, this.worldView.height); - } else { - this._game.stage.context.fillStyle = this._bgColor; - this._game.stage.context.fillRect(this._sx, this._sy, this.worldView.width, this.worldView.height); - } - } - // Shadow off - if(this.showShadow == true) { - this._game.stage.context.shadowBlur = 0; - this._game.stage.context.shadowOffsetX = 0; - this._game.stage.context.shadowOffsetY = 0; - } - this.fx.render(this, this._stageX, this._stageY, this.worldView.width, this.worldView.height); - // Clip the camera so we don't get sprites appearing outside the edges - if(this._clip == true && this.disableClipping == false) { - this._game.stage.context.beginPath(); - this._game.stage.context.rect(this._sx, this._sy, this.worldView.width, this.worldView.height); - this._game.stage.context.closePath(); - this._game.stage.context.clip(); - } - this._game.world.group.render(this, this._sx, this._sy); - if(this.showBorder == true) { - this._game.stage.context.strokeStyle = this.borderColor; - this._game.stage.context.lineWidth = 1; - this._game.stage.context.rect(this._sx, this._sy, this.worldView.width, this.worldView.height); - this._game.stage.context.stroke(); - } - // Scale off - if(this.scale.x !== 1 || this.scale.y !== 1) { - this._game.stage.context.scale(1, 1); - } - this.fx.postRender(this, this._sx, this._sy, this.worldView.width, this.worldView.height); - if(this._rotation !== 0 || (this._clip && this.disableClipping == false)) { - this._game.stage.context.translate(0, 0); - } - if(this._rotation !== 0 || this._clip || this.scale.x !== 1 || this.scale.y !== 1) { - this._game.stage.context.restore(); - } - if(this.alpha !== 1) { - this._game.stage.context.globalAlpha = 1; - } - }; - Object.defineProperty(Camera.prototype, "backgroundColor", { - get: function () { - return this._bgColor; - }, - set: function (color) { - this._bgColor = color; - }, - enumerable: true, - configurable: true - }); - Camera.prototype.setTexture = /** - * Set camera background texture. - * @param key {string} Asset key of the texture. - * @param [repeat] {string} what kind of repeat will this texture used for background. - */ - function (key, repeat) { - if (typeof repeat === "undefined") { repeat = 'repeat'; } - this._bgTexture = this._game.stage.context.createPattern(this._game.cache.getImage(key), repeat); - this._bgTextureRepeat = repeat; - }; - Camera.prototype.setPosition = /** - * Set position of this camera. - * @param x {number} X position. - * @param y {number} Y position. - */ - function (x, y) { - this._stageX = x; - this._stageY = y; - this.checkClip(); - }; - Camera.prototype.setSize = /** - * Give this camera a new size. - * @param width {number} Width of new size. - * @param height {number} Height of new size. - */ - function (width, height) { - this.worldView.width = width; - this.worldView.height = height; - this.checkClip(); - }; - Camera.prototype.renderDebugInfo = /** - * Render debug infos. (including id, position, rotation, scrolling factor, bounds and some other properties) - * @param x {number} X position of the debug info to be rendered. - * @param y {number} Y position of the debug info to be rendered. - * @param [color] {number} color of the debug info to be rendered. (format is css color string) - */ - function (x, y, color) { - if (typeof color === "undefined") { color = 'rgb(255,255,255)'; } - this._game.stage.context.fillStyle = color; - this._game.stage.context.fillText('Camera ID: ' + this.ID + ' (' + this.worldView.width + ' x ' + this.worldView.height + ')', x, y); - this._game.stage.context.fillText('X: ' + this._stageX + ' Y: ' + this._stageY + ' Rotation: ' + this._rotation, x, y + 14); - this._game.stage.context.fillText('World X: ' + this.scroll.x.toFixed(1) + ' World Y: ' + this.scroll.y.toFixed(1), x, y + 28); - if(this.bounds) { - this._game.stage.context.fillText('Bounds: ' + this.bounds.width + ' x ' + this.bounds.height, x, y + 56); - } - }; - Object.defineProperty(Camera.prototype, "x", { - get: function () { - return this._stageX; - }, - set: function (value) { - this._stageX = value; - this.checkClip(); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Camera.prototype, "y", { - get: function () { - return this._stageY; - }, - set: function (value) { - this._stageY = value; - this.checkClip(); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Camera.prototype, "width", { - get: function () { - return this.worldView.width; - }, - set: function (value) { - if(value > this._game.stage.width) { - value = this._game.stage.width; - } - this.worldView.width = value; - this.checkClip(); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Camera.prototype, "height", { - get: function () { - return this.worldView.height; - }, - set: function (value) { - if(value > this._game.stage.height) { - value = this._game.stage.height; - } - this.worldView.height = value; - this.checkClip(); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Camera.prototype, "rotation", { - get: function () { - return this._rotation; - }, - set: function (value) { - this._rotation = this._game.math.wrap(value, 360, 0); - }, - enumerable: true, - configurable: true - }); - Camera.prototype.checkClip = function () { - if(this._stageX !== 0 || this._stageY !== 0 || this.worldView.width < this._game.stage.width || this.worldView.height < this._game.stage.height) { - this._clip = true; - } else { - this._clip = false; - } - }; - return Camera; - })(); - Phaser.Camera = Camera; -})(Phaser || (Phaser = {})); -/// -/// -/// -/// -/** -* Phaser - Sprite -* -* The Sprite GameObject is an extension of the core GameObject that includes support for animation and dynamic textures. -* It's probably the most used GameObject of all. -*/ -var Phaser; -(function (Phaser) { - var Sprite = (function (_super) { - __extends(Sprite, _super); - /** - * Sprite constructor - * Create a new Sprite. - * - * @param game {Phaser.Game} Current game instance. - * @param [x] {number} the initial x position of the sprite. - * @param [y] {number} the initial y position of the sprite. - * @param [key] {string} Key of the graphic you want to load for this sprite. - */ - function Sprite(game, x, y, key) { - if (typeof x === "undefined") { x = 0; } - if (typeof y === "undefined") { y = 0; } - if (typeof key === "undefined") { key = null; } - _super.call(this, game, x, y); - /** - * Texture of this sprite is DynamicTexture? (default to false) - * @type {boolean} - */ - this._dynamicTexture = false; - // local rendering related temp vars to help avoid gc spikes - this._sx = 0; - this._sy = 0; - this._sw = 0; - this._sh = 0; - this._dx = 0; - this._dy = 0; - this._dw = 0; - this._dh = 0; - /** - * Render bound of this sprite for debugging? (default to false) - * @type {boolean} - */ - this.renderDebug = false; - /** - * Color of the Sprite when no image is present. Format is a css color string. - * @type {string} - */ - this.fillColor = 'rgb(255,255,255)'; - /** - * Color of bound when render debug. (see renderDebug) Format is a css color string. - * @type {string} - */ - this.renderDebugColor = 'rgba(0,255,0,0.5)'; - /** - * Color of points when render debug. (see renderDebug) Format is a css color string. - * @type {string} - */ - this.renderDebugPointColor = 'rgba(255,255,255,1)'; - /** - * Flip the graphic horizontally? (defaults to false) - * @type {boolean} - */ - this.flipped = false; - this._texture = null; - this.animations = new Phaser.AnimationManager(this._game, this); - if(key !== null) { - this.cacheKey = key; - this.loadGraphic(key); - } else { - this.frameBounds.width = 16; - this.frameBounds.height = 16; - } - } - Sprite.prototype.loadGraphic = /** - * Load graphic for this sprite. (graphic can be SpriteSheet or Texture) - * @param key {string} Key of the graphic you want to load for this sprite. - * @param clearAnimations {boolean} If this Sprite has a set of animation data already loaded you can choose to keep or clear it with this boolean - * @return {Sprite} Sprite instance itself. - */ - function (key, clearAnimations) { - if (typeof clearAnimations === "undefined") { clearAnimations = true; } - if(clearAnimations && this.animations.frameData !== null) { - this.animations.destroy(); - } - if(this._game.cache.getImage(key) !== null) { - if(this._game.cache.isSpriteSheet(key) == false) { - this._texture = this._game.cache.getImage(key); - this.frameBounds.width = this._texture.width; - this.frameBounds.height = this._texture.height; - this.collisionMask.width = this._texture.width; - this.collisionMask.height = this._texture.height; - } else { - this._texture = this._game.cache.getImage(key); - this.animations.loadFrameData(this._game.cache.getFrameData(key)); - this.collisionMask.width = this.animations.currentFrame.width; - this.collisionMask.height = this.animations.currentFrame.height; - } - this._dynamicTexture = false; - } - return this; - }; - Sprite.prototype.loadDynamicTexture = /** - * Load a DynamicTexture as its texture. - * @param texture {DynamicTexture} The texture object to be used by this sprite. - * @return {Sprite} Sprite instance itself. - */ - function (texture) { - this._texture = texture; - this.frameBounds.width = this._texture.width; - this.frameBounds.height = this._texture.height; - this._dynamicTexture = true; - return this; - }; - Sprite.prototype.makeGraphic = /** - * This function creates a flat colored square image dynamically. - * @param width {number} The width of the sprite you want to generate. - * @param height {number} The height of the sprite you want to generate. - * @param [color] {number} specifies the color of the generated block. (format is 0xAARRGGBB) - * @return {Sprite} Sprite instance itself. - */ - function (width, height, color) { - if (typeof color === "undefined") { color = 'rgb(255,255,255)'; } - this._texture = null; - this.width = width; - this.height = height; - this.fillColor = color; - this._dynamicTexture = false; - return this; - }; - Sprite.prototype.inCamera = /** - * Check whether this object is visible in a specific camera rectangle. - * @param camera {Rectangle} The rectangle you want to check. - * @return {boolean} Return true if bounds of this sprite intersects the given rectangle, otherwise return false. - */ - function (camera, cameraOffsetX, cameraOffsetY) { - // Object fixed in place regardless of the camera scrolling? Then it's always visible - if(this.scrollFactor.x == 0 && this.scrollFactor.y == 0) { - return true; - } - this._dx = (this.frameBounds.x - camera.x); - this._dy = (this.frameBounds.y - camera.y); - this._dw = this.frameBounds.width * this.scale.x; - this._dh = this.frameBounds.height * this.scale.y; - return (camera.right > this._dx) && (camera.x < this._dx + this._dw) && (camera.bottom > this._dy) && (camera.y < this._dy + this._dh); - }; - Sprite.prototype.postUpdate = /** - * Automatically called after update() by the game loop, this function just updates animations. - */ - function () { - this.animations.update(); - _super.prototype.postUpdate.call(this); - }; - Object.defineProperty(Sprite.prototype, "frame", { - get: function () { - return this.animations.frame; - }, - set: function (value) { - this.animations.frame = value; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Sprite.prototype, "frameName", { - get: function () { - return this.animations.frameName; - }, - set: function (value) { - this.animations.frameName = value; - }, - enumerable: true, - configurable: true - }); - Sprite.prototype.render = /** - * Render this sprite to specific camera. Called by game loop after update(). - * @param camera {Camera} Camera this sprite will be rendered to. - * @cameraOffsetX {number} X offset to the camera. - * @cameraOffsetY {number} Y offset to the camera. - * @return {boolean} Return false if not rendered, otherwise return true. - */ - function (camera, cameraOffsetX, cameraOffsetY) { - // Render checks - if(this.visible == false || this.scale.x == 0 || this.scale.y == 0 || this.alpha < 0.1 || this.cameraBlacklist.indexOf(camera.ID) !== -1 || this.inCamera(camera.worldView, cameraOffsetX, cameraOffsetY) == false) { - return false; - } - // Alpha - if(this.alpha !== 1) { - var globalAlpha = this.context.globalAlpha; - this.context.globalAlpha = this.alpha; - } - this._sx = 0; - this._sy = 0; - this._sw = this.frameBounds.width; - this._sh = this.frameBounds.height; - this._dx = (cameraOffsetX * this.scrollFactor.x) + this.frameBounds.topLeft.x - (camera.worldView.x * this.scrollFactor.x); - this._dy = (cameraOffsetY * this.scrollFactor.y) + this.frameBounds.topLeft.y - (camera.worldView.y * this.scrollFactor.y); - this._dw = this.frameBounds.width * this.scale.x; - this._dh = this.frameBounds.height * this.scale.y; - if(this.align == Phaser.GameObject.ALIGN_TOP_CENTER) { - this._dx -= this.frameBounds.halfWidth * this.scale.x; - } else if(this.align == Phaser.GameObject.ALIGN_TOP_RIGHT) { - this._dx -= this.frameBounds.width * this.scale.x; - } else if(this.align == Phaser.GameObject.ALIGN_CENTER_LEFT) { - this._dy -= this.frameBounds.halfHeight * this.scale.y; - } else if(this.align == Phaser.GameObject.ALIGN_CENTER) { - this._dx -= this.frameBounds.halfWidth * this.scale.x; - this._dy -= this.frameBounds.halfHeight * this.scale.y; - } else if(this.align == Phaser.GameObject.ALIGN_CENTER_RIGHT) { - this._dx -= this.frameBounds.width * this.scale.x; - this._dy -= this.frameBounds.halfHeight * this.scale.y; - } else if(this.align == Phaser.GameObject.ALIGN_BOTTOM_LEFT) { - this._dy -= this.frameBounds.height * this.scale.y; - } else if(this.align == Phaser.GameObject.ALIGN_BOTTOM_CENTER) { - this._dx -= this.frameBounds.halfWidth * this.scale.x; - this._dy -= this.frameBounds.height * this.scale.y; - } else if(this.align == Phaser.GameObject.ALIGN_BOTTOM_RIGHT) { - this._dx -= this.frameBounds.width * this.scale.x; - this._dy -= this.frameBounds.height * this.scale.y; - } - if(this._dynamicTexture == false && this.animations.currentFrame !== null) { - this._sx = this.animations.currentFrame.x; - this._sy = this.animations.currentFrame.y; - if(this.animations.currentFrame.trimmed) { - this._dx += this.animations.currentFrame.spriteSourceSizeX; - this._dy += this.animations.currentFrame.spriteSourceSizeY; - } - } - // Apply camera difference - if(this.scrollFactor.x !== 1 || this.scrollFactor.y !== 1) { - //this._dx -= (camera.worldView.x * this.scrollFactor.x); - //this._dy -= (camera.worldView.y * this.scrollFactor.y); - } - // Rotation - needs to work from origin point really, but for now from center - if(this.angle !== 0 || this.rotationOffset !== 0 || this.flipped == true) { - this.context.save(); - this.context.translate(this._dx + (this._dw / 2), this._dy + (this._dh / 2)); - if(this.renderRotation == true && (this.angle !== 0 || this.rotationOffset !== 0)) { - this.context.rotate((this.rotationOffset + this.angle) * (Math.PI / 180)); - } - this._dx = -(this._dw / 2); - this._dy = -(this._dh / 2); - if(this.flipped == true) { - this.context.scale(-1, 1); - } - } - this._sx = Math.round(this._sx); - this._sy = Math.round(this._sy); - this._sw = Math.round(this._sw); - this._sh = Math.round(this._sh); - this._dx = Math.round(this._dx); - this._dy = Math.round(this._dy); - this._dw = Math.round(this._dw); - this._dh = Math.round(this._dh); - if(this._texture != null) { - if(this._dynamicTexture) { - this.context.drawImage(this._texture.canvas, // Source Image - this._sx, // Source X (location within the source image) - this._sy, // Source Y - this._sw, // Source Width - this._sh, // Source Height - this._dx, // Destination X (where on the canvas it'll be drawn) - this._dy, // Destination Y - this._dw, // Destination Width (always same as Source Width unless scaled) - this._dh); - // Destination Height (always same as Source Height unless scaled) - } else { - this.context.drawImage(this._texture, // Source Image - this._sx, // Source X (location within the source image) - this._sy, // Source Y - this._sw, // Source Width - this._sh, // Source Height - this._dx, // Destination X (where on the canvas it'll be drawn) - this._dy, // Destination Y - this._dw, // Destination Width (always same as Source Width unless scaled) - this._dh); - // Destination Height (always same as Source Height unless scaled) - } - } else { - this.context.fillStyle = this.fillColor; - this.context.fillRect(this._dx, this._dy, this._dw, this._dh); - } - if(this.flipped === true || this.rotation !== 0 || this.rotationOffset !== 0) { - //this.context.translate(0, 0); - this.context.restore(); - } - if(this.renderDebug) { - this.renderBounds(camera, cameraOffsetX, cameraOffsetY); - //this.collisionMask.render(camera, cameraOffsetX, cameraOffsetY); - } - if(globalAlpha > -1) { - this.context.globalAlpha = globalAlpha; - } - return true; - }; - Sprite.prototype.renderBounds = /** - * Renders the bounding box around this Sprite and the contact points. Useful for visually debugging. - * @param camera {Camera} Camera the bound will be rendered to. - * @param cameraOffsetX {number} X offset of bound to the camera. - * @param cameraOffsetY {number} Y offset of bound to the camera. - */ - function (camera, cameraOffsetX, cameraOffsetY) { - this._dx = cameraOffsetX + (this.frameBounds.topLeft.x - camera.worldView.x); - this._dy = cameraOffsetY + (this.frameBounds.topLeft.y - camera.worldView.y); - this.context.fillStyle = this.renderDebugColor; - this.context.fillRect(this._dx, this._dy, this.frameBounds.width, this.frameBounds.height); - //this.context.fillStyle = this.renderDebugPointColor; - //var hw = this.frameBounds.halfWidth * this.scale.x; - //var hh = this.frameBounds.halfHeight * this.scale.y; - //var sw = (this.frameBounds.width * this.scale.x) - 1; - //var sh = (this.frameBounds.height * this.scale.y) - 1; - //this.context.fillRect(this._dx, this._dy, 1, 1); // top left - //this.context.fillRect(this._dx + hw, this._dy, 1, 1); // top center - //this.context.fillRect(this._dx + sw, this._dy, 1, 1); // top right - //this.context.fillRect(this._dx, this._dy + hh, 1, 1); // left center - //this.context.fillRect(this._dx + hw, this._dy + hh, 1, 1); // center - //this.context.fillRect(this._dx + sw, this._dy + hh, 1, 1); // right center - //this.context.fillRect(this._dx, this._dy + sh, 1, 1); // bottom left - //this.context.fillRect(this._dx + hw, this._dy + sh, 1, 1); // bottom center - //this.context.fillRect(this._dx + sw, this._dy + sh, 1, 1); // bottom right + function (key, textureURL, atlasURL, atlasData, format) { + if (typeof atlasURL === "undefined") { atlasURL = null; } + if (typeof atlasData === "undefined") { atlasData = null; } + if (typeof format === "undefined") { format = Loader.TEXTURE_ATLAS_JSON_ARRAY; } + if(this.checkKeyExists(key) === false) { + if(atlasURL !== null) { + // A URL to a json/xml file has been given + this._queueSize++; + this._fileList[key] = { + type: 'textureatlas', + key: key, + url: textureURL, + atlasURL: atlasURL, + data: null, + format: format, + error: false, + loaded: false }; - Sprite.prototype.renderDebugInfo = /** - * Render debug infos. (including name, bounds info, position and some other properties) - * @param x {number} X position of the debug info to be rendered. - * @param y {number} Y position of the debug info to be rendered. - * @param [color] {number} color of the debug info to be rendered. (format is css color string) - */ - function (x, y, color) { - if (typeof color === "undefined") { color = 'rgb(255,255,255)'; } - this.context.fillStyle = color; - this.context.fillText('Sprite: ' + this.name + ' (' + this.frameBounds.width + ' x ' + this.frameBounds.height + ')', x, y); - this.context.fillText('x: ' + this.frameBounds.x.toFixed(1) + ' y: ' + this.frameBounds.y.toFixed(1) + ' rotation: ' + this.angle.toFixed(1), x, y + 14); - this.context.fillText('dx: ' + this._dx.toFixed(1) + ' dy: ' + this._dy.toFixed(1) + ' dw: ' + this._dw.toFixed(1) + ' dh: ' + this._dh.toFixed(1), x, y + 28); - this.context.fillText('sx: ' + this._sx.toFixed(1) + ' sy: ' + this._sy.toFixed(1) + ' sw: ' + this._sw.toFixed(1) + ' sh: ' + this._sh.toFixed(1), x, y + 42); - }; - return Sprite; - })(Phaser.GameObject); - Phaser.Sprite = Sprite; -})(Phaser || (Phaser = {})); -/// -/** -* Phaser - Animation -* -* An Animation is a single animation. It is created by the AnimationManager and belongs to Sprite objects. -*/ -var Phaser; -(function (Phaser) { - var Animation = (function () { - /** - * Animation constructor - * Create a new Animation. - * - * @param parent {Sprite} Owner sprite of this animation. - * @param frameData {FrameData} The FrameData object contains animation data. - * @param name {string} Unique name of this animation. - * @param frames {number[]/string[]} An array of numbers or strings indicating what frames to play in what order. - * @param delay {number} Time between frames in ms. - * @param looped {boolean} Whether or not the animation is looped or just plays once. - */ - function Animation(game, parent, frameData, name, frames, delay, looped) { - this._game = game; - this._parent = parent; - this._frames = frames; - this._frameData = frameData; - this.name = name; - this.delay = 1000 / delay; - this.looped = looped; - this.isFinished = false; - this.isPlaying = false; - this._frameIndex = 0; - this.currentFrame = this._frameData.getFrame(this._frames[this._frameIndex]); - } - Object.defineProperty(Animation.prototype, "frameTotal", { - get: function () { - return this._frames.length; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Animation.prototype, "frame", { - get: function () { - if(this.currentFrame !== null) { - return this.currentFrame.index; + this._keys.push(key); } else { - return this._frameIndex; + if(format == Loader.TEXTURE_ATLAS_JSON_ARRAY) { + // A json string or object has been given + if(typeof atlasData === 'string') { + atlasData = JSON.parse(atlasData); + } + this._queueSize++; + this._fileList[key] = { + type: 'textureatlas', + key: key, + url: textureURL, + data: null, + atlasURL: null, + atlasData: atlasData['frames'], + format: format, + error: false, + loaded: false + }; + this._keys.push(key); + } else if(format == Loader.TEXTURE_ATLAS_XML_STARLING) { + // An xml string or object has been given + 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; + } + } + this._queueSize++; + this._fileList[key] = { + type: 'textureatlas', + key: key, + url: textureURL, + data: null, + atlasURL: null, + atlasData: atlasData, + format: format, + error: false, + loaded: false + }; + this._keys.push(key); + } } - }, - set: function (value) { - this.currentFrame = this._frameData.getFrame(value); - if(this.currentFrame !== null) { - this._parent.frameBounds.width = this.currentFrame.width; - this._parent.frameBounds.height = this.currentFrame.height; - this._frameIndex = value; + } + }; + Loader.prototype.addAudioFile = /** + * Add a new audio file loading request. + * @param key {string} Unique asset key of the audio file. + * @param url {string} URL of audio file. + */ + function (key, url) { + if(this.checkKeyExists(key) === false) { + this._queueSize++; + this._fileList[key] = { + type: 'audio', + key: key, + url: url, + data: null, + buffer: null, + error: false, + loaded: false + }; + this._keys.push(key); + } + }; + Loader.prototype.addTextFile = /** + * Add a new text file loading request. + * @param key {string} Unique asset key of the text file. + * @param url {string} URL of text file. + */ + function (key, url) { + if(this.checkKeyExists(key) === false) { + this._queueSize++; + this._fileList[key] = { + type: 'text', + key: key, + url: url, + data: null, + error: false, + loaded: false + }; + this._keys.push(key); + } + }; + Loader.prototype.removeFile = /** + * Remove loading request of a file. + * @param key {string} Key of the file you want to remove. + */ + function (key) { + delete this._fileList[key]; + }; + Loader.prototype.removeAll = /** + * Remove all file loading requests. + */ + function () { + this._fileList = { + }; + }; + Loader.prototype.load = /** + * Load assets. + * @param onFileLoadCallback {function} Called when each file loaded successfully. + * @param onCompleteCallback {function} Called when all assets completely loaded. + */ + function (onFileLoadCallback, onCompleteCallback) { + if (typeof onFileLoadCallback === "undefined") { onFileLoadCallback = null; } + if (typeof onCompleteCallback === "undefined") { onCompleteCallback = null; } + this.progress = 0; + this.hasLoaded = false; + this._onComplete = onCompleteCallback; + if(onCompleteCallback == null) { + this._onComplete = this._game.onCreateCallback; + } + this._onFileLoad = onFileLoadCallback; + if(this._keys.length > 0) { + this._progressChunk = 100 / this._keys.length; + this.loadFile(); + } else { + this.progress = 1; + this.hasLoaded = true; + this._gameCreateComplete.call(this._game); + if(this._onComplete !== null) { + this._onComplete.call(this._game.callbackContext); } - }, - enumerable: true, - configurable: true - }); - Animation.prototype.play = /** - * Play this animation. - * @param frameRate {number} FrameRate you want to specify instead of using default. - * @param loop {boolean} Whether or not the animation is looped or just plays once. - */ - function (frameRate, loop) { - if (typeof frameRate === "undefined") { frameRate = null; } - if(frameRate !== null) { - this.delay = 1000 / frameRate; } - if(loop !== undefined) { - this.looped = loop; + }; + Loader.prototype.loadFile = /** + * Load files. Private method ONLY used by loader. + */ + function () { + var _this = this; + var file = this._fileList[this._keys.pop()]; + // Image or Data? + switch(file.type) { + case 'image': + case 'spritesheet': + case 'textureatlas': + 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 = file.url; + break; + case 'audio': + this._xhr.open("GET", 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(); + break; + case 'text': + this._xhr.open("GET", 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; } - this.isPlaying = true; - this.isFinished = false; - this._timeLastFrame = this._game.time.now; - this._timeNextFrame = this._game.time.now + this.delay; - this._frameIndex = 0; - this.currentFrame = this._frameData.getFrame(this._frames[this._frameIndex]); }; - Animation.prototype.restart = /** - * Play this animation from the first frame. + Loader.prototype.fileError = /** + * Error occured when load a file. + * @param key {string} Key of the error loading file. */ - function () { - this.isPlaying = true; - this.isFinished = false; - this._timeLastFrame = this._game.time.now; - this._timeNextFrame = this._game.time.now + this.delay; - this._frameIndex = 0; - this.currentFrame = this._frameData.getFrame(this._frames[this._frameIndex]); + function (key) { + this._fileList[key].loaded = true; + this._fileList[key].error = true; + this.nextFile(key, false); }; - Animation.prototype.stop = /** - * Stop playing animation and set it finished. + Loader.prototype.fileComplete = /** + * Called when a file is successfully loaded. + * @param key {string} Key of the successfully loaded file. */ - function () { - this.isPlaying = false; - this.isFinished = true; - }; - Animation.prototype.update = /** - * Update animation frames. - */ - function () { - if(this.isPlaying == true && this._game.time.now >= this._timeNextFrame) { - this._frameIndex++; - if(this._frameIndex == this._frames.length) { - if(this.looped) { - this._frameIndex = 0; - this.currentFrame = this._frameData.getFrame(this._frames[this._frameIndex]); + function (key) { + var _this = this; + this._fileList[key].loaded = true; + var file = this._fileList[key]; + var loadNext = true; + 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 'textureatlas': + if(file.atlasURL == null) { + this._game.cache.addTextureAtlas(file.key, file.url, file.data, file.atlasData, file.format); } else { - this.onComplete(); + // Load the JSON or XML before carrying on with the next file + loadNext = false; + this._xhr.open("GET", file.atlasURL, true); + this._xhr.responseType = "text"; + if(file.format == Loader.TEXTURE_ATLAS_JSON_ARRAY) { + this._xhr.onload = function () { + return _this.jsonLoadComplete(file.key); + }; + } else if(file.format == Loader.TEXTURE_ATLAS_XML_STARLING) { + this._xhr.onload = function () { + return _this.xmlLoadComplete(file.key); + }; + } + this._xhr.onerror = function () { + return _this.dataLoadError(file.key); + }; + this._xhr.send(); } + break; + case 'audio': + file.data = this._xhr.response; + this._game.cache.addSound(file.key, file.url, file.data); + break; + case 'text': + file.data = this._xhr.response; + this._game.cache.addText(file.key, file.url, file.data); + break; + } + if(loadNext) { + this.nextFile(key, true); + } + }; + Loader.prototype.jsonLoadComplete = /** + * Successfully loaded a JSON file. + * @param key {string} Key of the loaded JSON file. + */ + function (key) { + var data = JSON.parse(this._xhr.response); + var file = this._fileList[key]; + this._game.cache.addTextureAtlas(file.key, file.url, file.data, data['frames'], file.format); + this.nextFile(key, true); + }; + Loader.prototype.dataLoadError = /** + * Error occured when load a JSON. + * @param key {string} Key of the error loading JSON file. + */ + function (key) { + var file = this._fileList[key]; + file.error = true; + this.nextFile(key, true); + }; + Loader.prototype.xmlLoadComplete = function (key) { + var atlasData = this._xhr.response; + var xml; + try { + if(window['DOMParser']) { + var domparser = new DOMParser(); + xml = domparser.parseFromString(atlasData, "text/xml"); } else { - this.currentFrame = this._frameData.getFrame(this._frames[this._frameIndex]); + xml = new ActiveXObject("Microsoft.XMLDOM"); + xml.async = 'false'; + xml.loadXML(atlasData); } - this._timeLastFrame = this._game.time.now; - this._timeNextFrame = this._game.time.now + this.delay; - return true; + } catch (e) { + xml = undefined; } - return false; + if(!xml || !xml.documentElement || xml.getElementsByTagName("parsererror").length) { + throw new Error("Phaser.Loader. Invalid XML given"); + } + var file = this._fileList[key]; + this._game.cache.addTextureAtlas(file.key, file.url, file.data, xml, file.format); + this.nextFile(key, true); }; - Animation.prototype.destroy = /** - * Clean up animation memory. + Loader.prototype.nextFile = /** + * Handle loading next file. + * @param previousKey {string} Key of previous loaded asset. + * @param success {boolean} Whether the previous asset loaded successfully or not. */ - function () { - this._game = null; - this._parent = null; - this._frames = null; - this._frameData = null; - this.currentFrame = null; - this.isPlaying = false; - }; - Animation.prototype.onComplete = /** - * Animation complete callback method. - */ - function () { - this.isPlaying = false; - this.isFinished = true; - // callback - }; - return Animation; - })(); - Phaser.Animation = Animation; -})(Phaser || (Phaser = {})); -/// -/** -* Phaser - AnimationLoader -* -* Responsible for parsing sprite sheet and JSON data into the internal FrameData format that Phaser uses for animations. -*/ -var Phaser; -(function (Phaser) { - var AnimationLoader = (function () { - function AnimationLoader() { } - AnimationLoader.parseSpriteSheet = /** - * Parse a sprite sheet from asset data. - * @param key {string} Asset key for the sprite sheet data. - * @param frameWidth {number} Width of animation frame. - * @param frameHeight {number} Height of animation frame. - * @param frameMax {number} Number of animation frames. - * @return {FrameData} Generated FrameData object. - */ - function parseSpriteSheet(game, key, frameWidth, frameHeight, frameMax) { - // How big is our image? - var img = game.cache.getImage(key); - if(img == null) { - return null; + function (previousKey, success) { + this.progress = Math.round(this.progress + this._progressChunk); + if(this.progress > 100) { + this.progress = 100; } - var width = img.width; - var height = img.height; - var row = Math.round(width / frameWidth); - var column = Math.round(height / frameHeight); - var total = row * column; - if(frameMax !== -1) { - total = frameMax; + if(this._onFileLoad) { + this._onFileLoad.call(this._game.callbackContext, this.progress, previousKey, success); } - // Zero or smaller than frame sizes? - if(width == 0 || height == 0 || width < frameWidth || height < frameHeight || total === 0) { - return null; - } - // Let's create some frames then - var data = new Phaser.FrameData(); - var x = 0; - var y = 0; - for(var i = 0; i < total; i++) { - data.addFrame(new Phaser.Frame(x, y, frameWidth, frameHeight, '')); - x += frameWidth; - if(x === width) { - x = 0; - y += frameHeight; - } - } - return data; - }; - AnimationLoader.parseJSONData = /** - * Parse frame datas from json. - * @param json {object} Json data you want to parse. - * @return {FrameData} Generated FrameData object. - */ - function parseJSONData(game, json) { - // Malformed? - if(!json['frames']) { - throw new Error("Phaser.AnimationLoader.parseJSONData: Invalid Texture Atlas JSON given, missing 'frames' array"); - } - // Let's create some frames then - var data = new Phaser.FrameData(); - // By this stage frames is a fully parsed array - var frames = json; - var newFrame; - for(var i = 0; i < frames.length; i++) { - newFrame = data.addFrame(new Phaser.Frame(frames[i].frame.x, frames[i].frame.y, frames[i].frame.w, frames[i].frame.h, frames[i].filename)); - newFrame.setTrim(frames[i].trimmed, frames[i].sourceSize.w, frames[i].sourceSize.h, frames[i].spriteSourceSize.x, frames[i].spriteSourceSize.y, frames[i].spriteSourceSize.w, frames[i].spriteSourceSize.h); - } - return data; - }; - AnimationLoader.parseXMLData = function parseXMLData(game, xml, format) { - // Malformed? - if(!xml.getElementsByTagName('TextureAtlas')) { - throw new Error("Phaser.AnimationLoader.parseXMLData: Invalid Texture Atlas XML given, missing tag"); - } - // Let's create some frames then - var data = new Phaser.FrameData(); - var frames = xml.getElementsByTagName('SubTexture'); - var newFrame; - for(var i = 0; i < frames.length; i++) { - var frame = frames[i].attributes; - newFrame = data.addFrame(new Phaser.Frame(frame.x.nodeValue, frame.y.nodeValue, frame.width.nodeValue, frame.height.nodeValue, frame.name.nodeValue)); - // Trimmed? - if(frame.frameX.nodeValue != '-0' || frame.frameY.nodeValue != '-0') { - newFrame.setTrim(true, frame.width.nodeValue, frame.height.nodeValue, Math.abs(frame.frameX.nodeValue), Math.abs(frame.frameY.nodeValue), frame.frameWidth.nodeValue, frame.frameHeight.nodeValue); - } - } - return data; - }; - return AnimationLoader; - })(); - Phaser.AnimationLoader = AnimationLoader; -})(Phaser || (Phaser = {})); -/// -/** -* Phaser - Frame -* -* A Frame is a single frame of an animation and is part of a FrameData collection. -*/ -var Phaser; -(function (Phaser) { - var Frame = (function () { - /** - * Frame constructor - * Create a new Frame with specific position, size and name. - * - * @param x {number} X position within the image to cut from. - * @param y {number} Y position within the image to cut from. - * @param width {number} Width of the frame. - * @param height {number} Height of the frame. - * @param name {string} Name of this frame. - */ - function Frame(x, y, width, height, name) { - /** - * Useful for Texture Atlas files. (is set to the filename value) - */ - this.name = ''; - /** - * Rotated? (not yet implemented) - */ - this.rotated = false; - /** - * Either cw or ccw, rotation is always 90 degrees. - */ - this.rotationDirection = 'cw'; - this.x = x; - this.y = y; - this.width = width; - this.height = height; - this.name = name; - this.rotated = false; - this.trimmed = false; - } - Frame.prototype.setRotation = /** - * Set rotation of this frame. (Not yet supported!) - */ - function (rotated, rotationDirection) { - // Not yet supported - }; - Frame.prototype.setTrim = /** - * Set trim of the frame. - * @param trimmed {boolean} Whether this frame trimmed or not. - * @param actualWidth {number} Actual width of this frame. - * @param actualHeight {number} Actual height of this frame. - * @param destX {number} Destiny x position. - * @param destY {number} Destiny y position. - * @param destWidth {number} Destiny draw width. - * @param destHeight {number} Destiny draw height. - */ - function (trimmed, actualWidth, actualHeight, destX, destY, destWidth, destHeight) { - this.trimmed = trimmed; - this.sourceSizeW = actualWidth; - this.sourceSizeH = actualHeight; - this.spriteSourceSizeX = destX; - this.spriteSourceSizeY = destY; - this.spriteSourceSizeW = destWidth; - this.spriteSourceSizeH = destHeight; - }; - return Frame; - })(); - Phaser.Frame = Frame; -})(Phaser || (Phaser = {})); -/// -/** -* Phaser - FrameData -* -* FrameData is a container for Frame objects, the internal representation of animation data in Phaser. -*/ -var Phaser; -(function (Phaser) { - var FrameData = (function () { - /** - * FrameData constructor - */ - function FrameData() { - this._frames = []; - this._frameNames = []; - } - Object.defineProperty(FrameData.prototype, "total", { - get: function () { - return this._frames.length; - }, - enumerable: true, - configurable: true - }); - FrameData.prototype.addFrame = /** - * Add a new frame. - * @param frame {Frame} The frame you want to add. - * @return {Frame} The frame you just added. - */ - function (frame) { - frame.index = this._frames.length; - this._frames.push(frame); - if(frame.name !== '') { - this._frameNames[frame.name] = frame.index; - } - return frame; - }; - FrameData.prototype.getFrame = /** - * Get a frame by its index. - * @param index {number} Index of the frame you want to get. - * @return {Frame} The frame you want. - */ - function (index) { - if(this._frames[index]) { - return this._frames[index]; - } - return null; - }; - FrameData.prototype.getFrameByName = /** - * Get a frame by its name. - * @param name {string} Name of the frame you want to get. - * @return {Frame} The frame you want. - */ - function (name) { - if(this._frameNames[name] >= 0) { - return this._frames[this._frameNames[name]]; - } - return null; - }; - FrameData.prototype.checkFrameName = /** - * Check whether there's a frame with given name. - * @param name {string} Name of the frame you want to check. - * @return {boolean} True if frame with given name found, otherwise return false. - */ - function (name) { - if(this._frameNames[name] >= 0) { - return true; - } - return false; - }; - FrameData.prototype.getFrameRange = /** - * Get ranges of frames in an array. - * @param start {number} Start index of frames you want. - * @param end {number} End index of frames you want. - * @param [output] {Frame[]} result will be added into this array. - * @return {Frame[]} Ranges of specific frames in an array. - */ - function (start, end, output) { - if (typeof output === "undefined") { output = []; } - for(var i = start; i <= end; i++) { - output.push(this._frames[i]); - } - return output; - }; - FrameData.prototype.getFrameIndexes = /** - * Get all indexes of frames by giving their name. - * @param [output] {number[]} result will be added into this array. - * @return {number[]} Indexes of specific frames in an array. - */ - function (output) { - if (typeof output === "undefined") { output = []; } - output.length = 0; - for(var i = 0; i < this._frames.length; i++) { - output.push(i); - } - return output; - }; - FrameData.prototype.getFrameIndexesByName = /** - * Get all names of frames by giving their indexes. - * @param [output] {number[]} result will be added into this array. - * @return {number[]} Names of specific frames in an array. - */ - function (input) { - var output = []; - for(var i = 0; i < input.length; i++) { - if(this.getFrameByName(input[i])) { - output.push(this.getFrameByName(input[i]).index); - } - } - return output; - }; - FrameData.prototype.getAllFrames = /** - * Get all frames in this frame data. - * @return {Frame[]} All the frames in an array. - */ - function () { - return this._frames; - }; - FrameData.prototype.getFrames = /** - * Get All frames with specific ranges. - * @param range {number[]} Ranges in an array. - * @return {Frame[]} All frames in an array. - */ - function (range) { - var output = []; - for(var i = 0; i < range.length; i++) { - output.push(this._frames[i]); - } - return output; - }; - return FrameData; - })(); - Phaser.FrameData = FrameData; -})(Phaser || (Phaser = {})); -/// -/// -/// -/// -/// -/// -/** -* Phaser - AnimationManager -* -* Any Sprite that has animation contains an instance of the AnimationManager, which is used to add, play and update -* sprite specific animations. -*/ -var Phaser; -(function (Phaser) { - var AnimationManager = (function () { - /** - * AnimationManager constructor - * Create a new AnimationManager. - * - * @param parent {Sprite} Owner sprite of this manager. - */ - function AnimationManager(game, parent) { - /** - * Data contains animation frames. - * @type {FrameData} - */ - this._frameData = null; - /** - * Keeps track of the current frame of animation. - */ - this.currentFrame = null; - this._game = game; - this._parent = parent; - this._anims = { - }; - } - AnimationManager.prototype.loadFrameData = /** - * Load animation frame data. - * @param frameData Data to be loaded. - */ - function (frameData) { - this._frameData = frameData; - this.frame = 0; - }; - AnimationManager.prototype.add = /** - * Add a new animation. - * @param name {string} What this animation should be called (e.g. "run"). - * @param frames {any[]} An array of numbers/strings indicating what frames to play in what order (e.g. [1, 2, 3] or ['run0', 'run1', run2]). - * @param frameRate {number} The speed in frames per second that the animation should play at (e.g. 60 fps). - * @param loop {boolean} Whether or not the animation is looped or just plays once. - * @param useNumericIndex {boolean} Use number indexes instead of string indexes? - * @return {Animation} The Animation that was created - */ - function (name, frames, frameRate, loop, useNumericIndex) { - if (typeof frames === "undefined") { frames = null; } - if (typeof frameRate === "undefined") { frameRate = 60; } - if (typeof loop === "undefined") { loop = false; } - if (typeof useNumericIndex === "undefined") { useNumericIndex = true; } - if(this._frameData == null) { - return; - } - if(frames == null) { - frames = this._frameData.getFrameIndexes(); + if(this._keys.length > 0) { + this.loadFile(); } else { - if(this.validateFrames(frames, useNumericIndex) == false) { - throw Error('Invalid frames given to Animation ' + name); - return; + this.hasLoaded = true; + this.removeAll(); + this._gameCreateComplete.call(this._game); + if(this._onComplete !== null) { + this._onComplete.call(this._game.callbackContext); } } - if(useNumericIndex == false) { - frames = this._frameData.getFrameIndexesByName(frames); - } - this._anims[name] = new Phaser.Animation(this._game, this._parent, this._frameData, name, frames, frameRate, loop); - this.currentAnim = this._anims[name]; - this.currentFrame = this.currentAnim.currentFrame; - return this._anims[name]; }; - AnimationManager.prototype.validateFrames = /** - * Check whether the frames is valid. - * @param frames {any[]} Frames to be validated. - * @param useNumericIndex {boolean} Does these frames use number indexes or string indexes? - * @return {boolean} True if they're valid, otherwise return false. + Loader.prototype.checkKeyExists = /** + * Check whether asset exists with a specific key. + * @param key {string} Key of the asset you want to check. + * @return {boolean} Return true if exists, otherwise return false. */ - function (frames, useNumericIndex) { - for(var i = 0; i < frames.length; i++) { - if(useNumericIndex == true) { - if(frames[i] > this._frameData.total) { - return false; - } - } else { - if(this._frameData.checkFrameName(frames[i]) == false) { - return false; - } - } - } - return true; - }; - AnimationManager.prototype.play = /** - * Play animation with specific name. - * @param name {string} The string name of the animation you want to play. - * @param frameRate {number} FrameRate you want to specify instead of using default. - * @param loop {boolean} Whether or not the animation is looped or just plays once. - */ - function (name, frameRate, loop) { - if (typeof frameRate === "undefined") { frameRate = null; } - if(this._anims[name]) { - if(this.currentAnim == this._anims[name]) { - if(this.currentAnim.isPlaying == false) { - this.currentAnim.play(frameRate, loop); - } - } else { - this.currentAnim = this._anims[name]; - this.currentAnim.play(frameRate, loop); - } + function (key) { + if(this._fileList[key]) { + return true; + } else { + return false; } }; - AnimationManager.prototype.stop = /** - * Stop animation by name. - * Current animation will be automatically set to the stopped one. - */ - function (name) { - if(this._anims[name]) { - this.currentAnim = this._anims[name]; - this.currentAnim.stop(); - } - }; - AnimationManager.prototype.update = /** - * Update animation and parent sprite's bounds. - */ - function () { - if(this.currentAnim && this.currentAnim.update() == true) { - this.currentFrame = this.currentAnim.currentFrame; - this._parent.frameBounds.width = this.currentFrame.width; - this._parent.frameBounds.height = this.currentFrame.height; - } - }; - Object.defineProperty(AnimationManager.prototype, "frameData", { - get: function () { - return this._frameData; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(AnimationManager.prototype, "frameTotal", { - get: function () { - if(this._frameData) { - return this._frameData.total; - } else { - return -1; - } - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(AnimationManager.prototype, "frame", { - get: function () { - return this._frameIndex; - }, - set: function (value) { - if(this._frameData.getFrame(value) !== null) { - this.currentFrame = this._frameData.getFrame(value); - this._parent.frameBounds.width = this.currentFrame.width; - this._parent.frameBounds.height = this.currentFrame.height; - this._frameIndex = value; - } - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(AnimationManager.prototype, "frameName", { - get: function () { - return this.currentFrame.name; - }, - set: function (value) { - if(this._frameData.getFrameByName(value) !== null) { - this.currentFrame = this._frameData.getFrameByName(value); - this._parent.frameBounds.width = this.currentFrame.width; - this._parent.frameBounds.height = this.currentFrame.height; - this._frameIndex = this.currentFrame.index; - } - }, - enumerable: true, - configurable: true - }); - AnimationManager.prototype.destroy = /** - * Removes all related references - */ - function () { - this._anims = { - }; - this._frameData = null; - this._frameIndex = 0; - this.currentAnim = null; - this.currentFrame = null; - }; - return AnimationManager; + return Loader; })(); - Phaser.AnimationManager = AnimationManager; + Phaser.Loader = Loader; })(Phaser || (Phaser = {})); -/// +/// /** * Phaser - Cache * @@ -3017,4304 +660,8 @@ var Phaser; })(); Phaser.Cache = Cache; })(Phaser || (Phaser = {})); -/// -/// -/** -* Phaser - CameraManager -* -* Your game only has one CameraManager instance and it's responsible for looking after, creating and destroying -* all of the cameras in the world. -*/ -var Phaser; -(function (Phaser) { - var CameraManager = (function () { - /** - * CameraManager constructor - * This will create a new Camera with position and size. - * - * @param x {number} X Position of the created camera. - * @param y {number} y Position of the created camera. - * @param width {number} Width of the created camera. - * @param height {number} Height of the created camera. - */ - function CameraManager(game, x, y, width, height) { - /** - * Local helper stores index of next created camera. - */ - this._cameraInstance = 0; - this._game = game; - this._cameras = []; - this.current = this.addCamera(x, y, width, height); - } - CameraManager.prototype.getAll = /** - * Get all the cameras. - * - * @returns {Camera[]} An array contains all the cameras. - */ - function () { - return this._cameras; - }; - CameraManager.prototype.update = /** - * Update cameras. - */ - function () { - this._cameras.forEach(function (camera) { - return camera.update(); - }); - }; - CameraManager.prototype.render = /** - * Render cameras. - */ - function () { - this._cameras.forEach(function (camera) { - return camera.render(); - }); - }; - CameraManager.prototype.addCamera = /** - * Create a new camera with specific position and size. - * - * @param x {number} X position of the new camera. - * @param y {number} Y position of the new camera. - * @param width {number} Width of the new camera. - * @param height {number} Height of the new camera. - * @returns {Camera} The newly created camera object. - */ - function (x, y, width, height) { - var newCam = new Phaser.Camera(this._game, this._cameraInstance, x, y, width, height); - this._cameras.push(newCam); - this._cameraInstance++; - return newCam; - }; - CameraManager.prototype.removeCamera = /** - * Remove a new camera with its id. - * - * @param id {number} ID of the camera you want to remove. - * @returns {boolean} True if successfully removed the camera, otherwise return false. - */ - function (id) { - for(var c = 0; c < this._cameras.length; c++) { - if(this._cameras[c].ID == id) { - if(this.current.ID === this._cameras[c].ID) { - this.current = null; - } - this._cameras.splice(c, 1); - return true; - } - } - return false; - }; - CameraManager.prototype.destroy = /** - * Clean up memory. - */ - function () { - this._cameras.length = 0; - this.current = this.addCamera(0, 0, this._game.stage.width, this._game.stage.height); - }; - return CameraManager; - })(); - Phaser.CameraManager = CameraManager; -})(Phaser || (Phaser = {})); /// /** -* Phaser - Point -* -* The Point object represents a location in a two-dimensional coordinate system, where x represents the horizontal axis and y represents the vertical axis. -*/ -var Phaser; -(function (Phaser) { - var Point = (function () { - /** - * Creates a new point. If you pass no parameters to this method, a point is created at (0,0). - * @class Point - * @constructor - * @param {Number} x The horizontal position of this point (default 0) - * @param {Number} y The vertical position of this point (default 0) - **/ - function Point(x, y) { - if (typeof x === "undefined") { x = 0; } - if (typeof y === "undefined") { y = 0; } - this.setTo(x, y); - } - Point.prototype.add = /** - * Adds the coordinates of another point to the coordinates of this point to create a new point. - * @method add - * @param {Point} point - The point to be added. - * @return {Point} The new Point object. - **/ - function (toAdd, output) { - if (typeof output === "undefined") { output = new Point(); } - return output.setTo(this.x + toAdd.x, this.y + toAdd.y); - }; - Point.prototype.addTo = /** - * Adds the given values to the coordinates of this point and returns it - * @method addTo - * @param {Number} x - The amount to add to the x value of the point - * @param {Number} y - The amount to add to the x value of the point - * @return {Point} This Point object. - **/ - function (x, y) { - if (typeof x === "undefined") { x = 0; } - if (typeof y === "undefined") { y = 0; } - return this.setTo(this.x + x, this.y + y); - }; - Point.prototype.subtractFrom = /** - * Adds the given values to the coordinates of this point and returns it - * @method addTo - * @param {Number} x - The amount to add to the x value of the point - * @param {Number} y - The amount to add to the x value of the point - * @return {Point} This Point object. - **/ - function (x, y) { - if (typeof x === "undefined") { x = 0; } - if (typeof y === "undefined") { y = 0; } - return this.setTo(this.x - x, this.y - y); - }; - Point.prototype.invert = /** - * Inverts the x and y values of this point - * @method invert - * @return {Point} This Point object. - **/ - function () { - return this.setTo(this.y, this.x); - }; - Point.prototype.clamp = /** - * Clamps this Point object to be between the given min and max - * @method clamp - * @param {number} The minimum value to clamp this Point to - * @param {number} The maximum value to clamp this Point to - * @return {Point} This Point object. - **/ - function (min, max) { - this.clampX(min, max); - this.clampY(min, max); - return this; - }; - Point.prototype.clampX = /** - * Clamps the x value of this Point object to be between the given min and max - * @method clampX - * @param {number} The minimum value to clamp this Point to - * @param {number} The maximum value to clamp this Point to - * @return {Point} This Point object. - **/ - function (min, max) { - this.x = Math.max(Math.min(this.x, max), min); - return this; - }; - Point.prototype.clampY = /** - * Clamps the y value of this Point object to be between the given min and max - * @method clampY - * @param {number} The minimum value to clamp this Point to - * @param {number} The maximum value to clamp this Point to - * @return {Point} This Point object. - **/ - function (min, max) { - this.x = Math.max(Math.min(this.x, max), min); - this.y = Math.max(Math.min(this.y, max), min); - return this; - }; - Point.prototype.clone = /** - * Creates a copy of this Point. - * @method clone - * @param {Point} output Optional Point object. If given the values will be set into this object, otherwise a brand new Point object will be created and returned. - * @return {Point} The new Point object. - **/ - function (output) { - if (typeof output === "undefined") { output = new Point(); } - return output.setTo(this.x, this.y); - }; - Point.prototype.copyFrom = /** - * Copies the point data from the source Point object into this Point object. - * @method copyFrom - * @param {Point} source - The point to copy from. - * @return {Point} This Point object. Useful for chaining method calls. - **/ - function (source) { - return this.setTo(source.x, source.y); - }; - Point.prototype.copyTo = /** - * Copies the point data from this Point object to the given target Point object. - * @method copyTo - * @param {Point} target - The point to copy to. - * @return {Point} The target Point object. - **/ - function (target) { - return target.setTo(this.x, this.y); - }; - Point.prototype.distanceTo = /** - * Returns the distance from this Point object to the given Point object. - * @method distanceFrom - * @param {Point} target - The destination Point object. - * @param {Boolean} round - Round the distance to the nearest integer (default false) - * @return {Number} The distance between this Point object and the destination Point object. - **/ - function (target, round) { - if (typeof round === "undefined") { round = false; } - var dx = this.x - target.x; - var dy = this.y - target.y; - if(round === true) { - return Math.round(Math.sqrt(dx * dx + dy * dy)); - } else { - return Math.sqrt(dx * dx + dy * dy); - } - }; - Point.distanceBetween = /** - * Returns the distance between the two Point objects. - * @method distanceBetween - * @param {Point} pointA - The first Point object. - * @param {Point} pointB - The second Point object. - * @param {Boolean} round - Round the distance to the nearest integer (default false) - * @return {Number} The distance between the two Point objects. - **/ - function distanceBetween(pointA, pointB, round) { - if (typeof round === "undefined") { round = false; } - var dx = pointA.x - pointB.x; - var dy = pointA.y - pointB.y; - if(round === true) { - return Math.round(Math.sqrt(dx * dx + dy * dy)); - } else { - return Math.sqrt(dx * dx + dy * dy); - } - }; - Point.prototype.distanceCompare = /** - * Returns true if the distance between this point and a target point is greater than or equal a specified distance. - * This avoids using a costly square root operation - * @method distanceCompare - * @param {Point} target - The Point object to use for comparison. - * @param {Number} distance - The distance to use for comparison. - * @return {Boolena} True if distance is >= specified distance. - **/ - function (target, distance) { - if(this.distanceTo(target) >= distance) { - return true; - } else { - return false; - } - }; - Point.prototype.equals = /** - * Determines whether this Point object and the given point object are equal. They are equal if they have the same x and y values. - * @method equals - * @param {Point} point - The point to compare against. - * @return {Boolean} A value of true if the object is equal to this Point object; false if it is not equal. - **/ - function (toCompare) { - if(this.x === toCompare.x && this.y === toCompare.y) { - return true; - } else { - return false; - } - }; - Point.prototype.interpolate = /** - * Determines a point between two specified points. The parameter f determines where the new interpolated point is located relative to the two end points specified by parameters pt1 and pt2. - * The closer the value of the parameter f is to 1.0, the closer the interpolated point is to the first point (parameter pt1). The closer the value of the parameter f is to 0, the closer the interpolated point is to the second point (parameter pt2). - * @method interpolate - * @param {Point} pointA - The first Point object. - * @param {Point} pointB - The second Point object. - * @param {Number} f - The level of interpolation between the two points. Indicates where the new point will be, along the line between pt1 and pt2. If f=1, pt1 is returned; if f=0, pt2 is returned. - * @return {Point} The new interpolated Point object. - **/ - function (pointA, pointB, f) { - }; - Point.prototype.offset = /** - * Offsets the Point object by the specified amount. The value of dx is added to the original value of x to create the new x value. - * The value of dy is added to the original value of y to create the new y value. - * @method offset - * @param {Number} dx - The amount by which to offset the horizontal coordinate, x. - * @param {Number} dy - The amount by which to offset the vertical coordinate, y. - * @return {Point} This Point object. Useful for chaining method calls. - **/ - function (dx, dy) { - this.x += dx; - this.y += dy; - return this; - }; - Point.prototype.polar = /** - * Converts a pair of polar coordinates to a Cartesian point coordinate. - * @method polar - * @param {Number} length - The length coordinate of the polar pair. - * @param {Number} angle - The angle, in radians, of the polar pair. - * @return {Point} The new Cartesian Point object. - **/ - function (length, angle) { - }; - Point.prototype.rotate = /** - * Rotates the point around the x/y coordinates given to the desired angle - * @param x {number} The x coordinate of the anchor point - * @param y {number} The y coordinate of the anchor point - * @param {Number} angle The angle in radians (unless asDegrees is true) to return the point from. - * @param {Boolean} asDegrees Is the given angle in radians (false) or degrees (true)? - * @param {Number} distance An optional distance constraint between the point and the anchor - * @return The modified point object - */ - function (cx, cy, angle, asDegrees, distance) { - if (typeof asDegrees === "undefined") { asDegrees = false; } - if (typeof distance === "undefined") { distance = null; } - if(asDegrees) { - angle = angle * Phaser.GameMath.DEG_TO_RAD; - } - // Get distance from origin (cx/cy) to this point - if(distance === null) { - distance = Math.sqrt(((cx - this.x) * (cx - this.x)) + ((cy - this.y) * (cy - this.y))); - } - return this.setTo(cx + distance * Math.cos(angle), cy + distance * Math.sin(angle)); - }; - Point.prototype.setTo = /** - * Sets the x and y values of this Point object to the given coordinates. - * @method setTo - * @param {Number} x - The horizontal position of this point. - * @param {Number} y - The vertical position of this point. - * @return {Point} This Point object. Useful for chaining method calls. - **/ - function (x, y) { - this.x = x; - this.y = y; - return this; - }; - Point.prototype.subtract = /** - * Subtracts the coordinates of another point from the coordinates of this point to create a new point. - * @method subtract - * @param {Point} point - The point to be subtracted. - * @param {Point} output Optional Point object. If given the values will be set into this object, otherwise a brand new Point object will be created and returned. - * @return {Point} The new Point object. - **/ - function (point, output) { - if (typeof output === "undefined") { output = new Point(); } - return output.setTo(this.x - point.x, this.y - point.y); - }; - Point.prototype.toString = /** - * Returns a string representation of this object. - * @method toString - * @return {string} a string representation of the instance. - **/ - function () { - return '[{Point (x=' + this.x + ' y=' + this.y + ')}]'; - }; - return Point; - })(); - Phaser.Point = Point; -})(Phaser || (Phaser = {})); -/// -/** -* Phaser - MicroPoint -* -* The MicroPoint object represents a location in a two-dimensional coordinate system, -* where x represents the horizontal axis and y represents the vertical axis. -* It is different to the Point class in that it doesn't contain any of the help methods like add/substract/distanceTo, etc. -* Use a MicroPoint when all you literally need is a solid container for x and y (such as in the Rectangle class). -*/ -var Phaser; -(function (Phaser) { - var MicroPoint = (function () { - /** - * Creates a new point. If you pass no parameters to this method, a point is created at (0,0). - * @class MicroPoint - * @constructor - * @param {Number} x The horizontal position of this point (default 0) - * @param {Number} y The vertical position of this point (default 0) - **/ - function MicroPoint(x, y, parent) { - if (typeof x === "undefined") { x = 0; } - if (typeof y === "undefined") { y = 0; } - if (typeof parent === "undefined") { parent = null; } - this._x = x; - this._y = y; - this.parent = parent; - } - Object.defineProperty(MicroPoint.prototype, "x", { - get: /** - * The x coordinate of the top-left corner of the rectangle - * @property x - * @type {Number} - **/ - function () { - return this._x; - }, - set: /** - * The x coordinate of the top-left corner of the rectangle - * @property x - * @type {Number} - **/ - function (value) { - this._x = value; - if(this.parent) { - this.parent.updateBounds(); - } - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(MicroPoint.prototype, "y", { - get: /** - * The y coordinate of the top-left corner of the rectangle - * @property y - * @type {Number} - **/ - function () { - return this._y; - }, - set: /** - * The y coordinate of the top-left corner of the rectangle - * @property y - * @type {Number} - **/ - function (value) { - this._y = value; - if(this.parent) { - this.parent.updateBounds(); - } - }, - enumerable: true, - configurable: true - }); - MicroPoint.prototype.copyFrom = /** - * Copies the x and y values from any given object to this MicroPoint. - * @method copyFrom - * @param {any} source - The object to copy from. - * @return {MicroPoint} This MicroPoint object. Useful for chaining method calls. - **/ - function (source) { - return this.setTo(source.x, source.y); - }; - MicroPoint.prototype.copyTo = /** - * Copies the x and y values from this MicroPoint to any given object. - * @method copyTo - * @param {any} target - The object to copy to. - * @return {any} The target object. - **/ - function (target) { - target.x = this._x; - target.y = this._y; - return target; - }; - MicroPoint.prototype.setTo = /** - * Sets the x and y values of this MicroPoint object to the given coordinates. - * @method setTo - * @param {Number} x - The horizontal position of this point. - * @param {Number} y - The vertical position of this point. - * @return {MicroPoint} This MicroPoint object. Useful for chaining method calls. - **/ - function (x, y, callParent) { - if (typeof callParent === "undefined") { callParent = true; } - this._x = x; - this._y = y; - if(this.parent != null && callParent == true) { - this.parent.updateBounds(); - } - return this; - }; - MicroPoint.prototype.equals = /** - * Determines whether this MicroPoint object and the given object are equal. They are equal if they have the same x and y values. - * @method equals - * @param {any} point - The object to compare against. Must have x and y properties. - * @return {Boolean} A value of true if the object is equal to this MicroPoin object; false if it is not equal. - **/ - function (toCompare) { - if(this._x === toCompare.x && this._y === toCompare.y) { - return true; - } else { - return false; - } - }; - MicroPoint.prototype.toString = /** - * Returns a string representation of this object. - * @method toString - * @return {string} a string representation of the instance. - **/ - function () { - return '[{MicroPoint (x=' + this._x + ' y=' + this._y + ')}]'; - }; - return MicroPoint; - })(); - Phaser.MicroPoint = MicroPoint; -})(Phaser || (Phaser = {})); -/// -/// -/** -* Phaser - Rectangle -* -* A Rectangle object is an area defined by its position, as indicated by its top-left corner (x,y) and width and height. -*/ -var Phaser; -(function (Phaser) { - var Rectangle = (function () { - /** - * Creates a new Rectangle object with the top-left corner specified by the x and y parameters and with the specified width and height parameters. - * If you call this function without parameters, a rectangle with x, y, width, and height properties set to 0 is created. - * @class Rectangle - * @constructor - * @param {Number} x The x coordinate of the top-left corner of the rectangle. - * @param {Number} y The y coordinate of the top-left corner of the rectangle. - * @param {Number} width The width of the rectangle. - * @param {Number} height The height of the rectangle. - * @return {Rectangle} This rectangle object - **/ - function Rectangle(x, y, width, height) { - if (typeof x === "undefined") { x = 0; } - if (typeof y === "undefined") { y = 0; } - if (typeof width === "undefined") { width = 0; } - if (typeof height === "undefined") { height = 0; } - this._tempX = null; - this._tempY = null; - this._tempWidth = null; - this._tempHeight = null; - /** - * The width of the rectangle - * @property width - * @type {Number} - **/ - this._width = 0; - /** - * The height of the rectangle - * @property height - * @type {Number} - **/ - this._height = 0; - /** - * Half of the width of the rectangle - * @property halfWidth - * @type {Number} - **/ - this._halfWidth = 0; - /** - * Half of the height of the rectangle - * @property halfHeight - * @type {Number} - **/ - this._halfHeight = 0; - /** - * The size of the longest side (width or height) - * @property length - * @type {Number} - **/ - this.length = 0; - this._width = width; - if(width > 0) { - this._halfWidth = Math.round(width / 2); - } - this._height = height; - if(height > 0) { - this._halfHeight = Math.round(height / 2); - } - this.length = Math.max(this._width, this._height); - this.topLeft = new Phaser.MicroPoint(x, y, this); - this.topCenter = new Phaser.MicroPoint(x + this._halfWidth, y, this); - this.topRight = new Phaser.MicroPoint(x + this._width - 1, y, this); - this.leftCenter = new Phaser.MicroPoint(x, y + this._halfHeight, this); - this.center = new Phaser.MicroPoint(x + this._halfWidth, y + this._halfHeight, this); - this.rightCenter = new Phaser.MicroPoint(x + this._width - 1, y + this._halfHeight, this); - this.bottomLeft = new Phaser.MicroPoint(x, y + this._height - 1, this); - this.bottomCenter = new Phaser.MicroPoint(x + this._halfWidth, y + this._height - 1, this); - this.bottomRight = new Phaser.MicroPoint(x + this._width - 1, y + this._height - 1, this); - } - Object.defineProperty(Rectangle.prototype, "x", { - get: /** - * The x coordinate of the top-left corner of the rectangle - * @property x - * @type {Number} - **/ - function () { - return this.topLeft.x; - }, - set: /** - * The x coordinate of the top-left corner of the rectangle - * @property x - * @type {Number} - **/ - function (value) { - this.topLeft.x = value; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Rectangle.prototype, "y", { - get: /** - * The y coordinate of the top-left corner of the rectangle - * @property y - * @type {Number} - **/ - function () { - return this.topLeft.y; - }, - set: /** - * The y coordinate of the top-left corner of the rectangle - * @property y - * @type {Number} - **/ - function (value) { - this.topLeft.y = value; - }, - enumerable: true, - configurable: true - }); - Rectangle.prototype.updateBounds = /** - * Updates all of the MicroPoints based on the values of width and height. - * You should not normally call this directly. - **/ - function () { - if(this._tempWidth !== null) { - this._width = this._tempWidth; - this._halfWidth = 0; - if(this._width > 0) { - this._halfWidth = Math.round(this._width / 2); - } - } - if(this._tempHeight !== null) { - this._height = this._tempHeight; - this._halfHeight = 0; - if(this._height > 0) { - this._halfHeight = Math.round(this._height / 2); - } - } - this.length = Math.max(this._width, this._height); - if(this._tempX !== null && this._tempY !== null) { - this.topLeft.setTo(this._tempX, this._tempY, false); - } else if(this._tempX !== null && this._tempY == null) { - this.topLeft.setTo(this._tempX, this.topLeft.y, false); - } else if(this._tempX == null && this._tempY !== null) { - this.topLeft.setTo(this.topLeft.x, this._tempY, false); - } else { - this.topLeft.setTo(this.x, this.y, false); - } - this.topCenter.setTo(this.x + this._halfWidth, this.y, false); - this.topRight.setTo(this.x + this._width - 1, this.y, false); - this.leftCenter.setTo(this.x, this.y + this._halfHeight, false); - this.center.setTo(this.x + this._halfWidth, this.y + this._halfHeight, false); - this.rightCenter.setTo(this.x + this._width - 1, this.y + this._halfHeight, false); - this.bottomLeft.setTo(this.x, this.y + this._height - 1, false); - this.bottomCenter.setTo(this.x + this._halfWidth, this.y + this._height - 1, false); - this.bottomRight.setTo(this.x + this._width - 1, this.y + this._height - 1, false); - this._tempX = null; - this._tempY = null; - this._tempWidth = null; - this._tempHeight = null; - }; - Object.defineProperty(Rectangle.prototype, "width", { - get: /** - * The width of the rectangle - * @property width - * @type {Number} - **/ - function () { - return this._width; - }, - set: /** - * The width of the rectangle - * @property width - * @type {Number} - **/ - function (value) { - this._width = value; - this._halfWidth = Math.round(value / 2); - this.updateBounds(); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Rectangle.prototype, "height", { - get: /** - * The height of the rectangle - * @property height - * @type {Number} - **/ - function () { - return this._height; - }, - set: /** - * The height of the rectangle - * @property height - * @type {Number} - **/ - function (value) { - this._height = value; - this._halfHeight = Math.round(value / 2); - this.updateBounds(); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Rectangle.prototype, "halfWidth", { - get: /** - * Half of the width of the rectangle - * @property halfWidth - * @type {Number} - **/ - function () { - return this._halfWidth; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Rectangle.prototype, "halfHeight", { - get: /** - * Half of the height of the rectangle - * @property halfHeight - * @type {Number} - **/ - function () { - return this._halfHeight; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Rectangle.prototype, "bottom", { - get: /** - * 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 - * @return {Number} - **/ - function () { - return this.bottomCenter.y; - }, - set: /** - * 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 - **/ - function (value) { - if(value < this.y) { - this._tempHeight = 0; - } else { - this._tempHeight = this.y + value; - } - this.updateBounds(); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Rectangle.prototype, "left", { - get: /** - * The x coordinate of the top-left corner of the rectangle. - * Changing the left property of a Rectangle object has no effect on the y and height properties. - * However it does affect the width property, whereas changing the x value does not affect the width property. - * @method left - * @ return {Number} - **/ - function () { - return this.x; - }, - set: /** - * The x coordinate of the top-left corner of the rectangle. - * Changing the left property of a Rectangle object has no effect on the y and height properties. - * However it does affect the width property, whereas changing the x value does not affect the width property. - * @method left - * @param {Number} value - **/ - function (value) { - var diff = this.x - value; - if(this._width + diff < 0) { - this._tempWidth = 0; - this._tempX = value; - } else { - this._tempWidth = this._width + diff; - this._tempX = value; - } - this.updateBounds(); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Rectangle.prototype, "right", { - get: /** - * The sum of the x and width properties. - * Changing the right property of a Rectangle object has no effect on the x, y and height properties. - * However it does affect the width property. - * @method right - * @return {Number} - **/ - function () { - return this.rightCenter.x; - }, - set: /** - * The sum of the x and width properties. - * Changing the right property of a Rectangle object has no effect on the x, y and height properties. - * However it does affect the width property. - * @method right - * @param {Number} value - **/ - function (value) { - if(value < this.topLeft.x) { - this._tempWidth = 0; - } else { - this._tempWidth = (value - this.topLeft.x); - } - this.updateBounds(); - }, - enumerable: true, - configurable: true - }); - Rectangle.prototype.size = /** - * The size of the Rectangle object, expressed as a Point object with the values of the width and height properties. - * @method size - * @param {Point} output Optional Point object. If given the values will be set into the object, otherwise a brand new Point object will be created and returned. - * @return {Point} The size of the Rectangle object - **/ - function (output) { - if (typeof output === "undefined") { output = new Phaser.Point(); } - return output.setTo(this._width, this._height); - }; - Object.defineProperty(Rectangle.prototype, "volume", { - get: /** - * The volume of the Rectangle object in pixels, derived from width * height - * @method volume - * @return {Number} - **/ - function () { - return this._width * this._height; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Rectangle.prototype, "perimeter", { - get: /** - * The perimeter size of the Rectangle object in pixels. This is the sum of all 4 sides. - * @method perimeter - * @return {Number} - **/ - function () { - return (this._width * 2) + (this._height * 2); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Rectangle.prototype, "top", { - get: /** - * The y coordinate of the top-left corner of the rectangle. - * Changing the top property of a Rectangle object has no effect on the x and width properties. - * However it does affect the height property, whereas changing the y value does not affect the height property. - * @method top - * @return {Number} - **/ - function () { - return this.topCenter.y; - }, - set: /** - * The y coordinate of the top-left corner of the rectangle. - * Changing the top property of a Rectangle object has no effect on the x and width properties. - * However it does affect the height property, whereas changing the y value does not affect the height property. - * @method top - * @param {Number} value - **/ - function (value) { - var diff = this.topCenter.y - value; - if(this._height + diff < 0) { - this._tempHeight = 0; - this._tempY = value; - } else { - this._tempHeight = this._height + diff; - this._tempY = value; - } - this.updateBounds(); - }, - enumerable: true, - configurable: true - }); - Rectangle.prototype.clone = /** - * Returns a new Rectangle object with the same values for the x, y, width, and height properties as the original Rectangle object. - * @method clone - * @param {Rectangle} output Optional Rectangle object. If given the values will be set into the object, otherwise a brand new Rectangle object will be created and returned. - * @return {Rectangle} - **/ - function (output) { - if (typeof output === "undefined") { output = new Rectangle(); } - return output.setTo(this.x, this.y, this.width, this.height); - }; - Rectangle.prototype.contains = /** - * Determines whether the specified coordinates are contained within the region defined by this Rectangle object. - * @method contains - * @param {Number} x The x coordinate of the point to test. - * @param {Number} y The y coordinate of the point to test. - * @return {Boolean} A value of true if the Rectangle object contains the specified point; otherwise false. - **/ - function (x, y) { - if(x >= this.topLeft.x && x <= this.topRight.x && y >= this.topLeft.y && y <= this.bottomRight.y) { - return true; - } - return false; - }; - Rectangle.prototype.containsPoint = /** - * Determines whether the specified point is contained within the rectangular region defined by this Rectangle object. - * This method is similar to the Rectangle.contains() method, except that it takes a Point object as a parameter. - * @method containsPoint - * @param {Point} point The point object being checked. Can be Point or any object with .x and .y values. - * @return {Boolean} A value of true if the Rectangle object contains the specified point; otherwise false. - **/ - function (point) { - return this.contains(point.x, point.y); - }; - Rectangle.prototype.containsRect = /** - * Determines whether the Rectangle object specified by the rect parameter is contained within this Rectangle object. - * A Rectangle object is said to contain another if the second Rectangle object falls entirely within the boundaries of the first. - * @method containsRect - * @param {Rectangle} rect The rectangle object being checked. - * @return {Boolean} A value of true if the Rectangle object contains the specified point; otherwise false. - **/ - function (rect) { - // If the given rect has a larger volume than this one then it can never contain it - if(rect.volume > this.volume) { - return false; - } - if(rect.x >= this.topLeft.x && rect.y >= this.topLeft.y && rect.rightCenter.x <= this.rightCenter.x && rect.bottomCenter.y <= this.bottomCenter.y) { - return true; - } - return false; - }; - Rectangle.prototype.copyFrom = /** - * Copies all of rectangle data from the source Rectangle object into the calling Rectangle object. - * @method copyFrom - * @param {Rectangle} rect The source rectangle object to copy from - * @return {Rectangle} This rectangle object - **/ - function (source) { - return this.setTo(source.x, source.y, source.width, source.height); - }; - Rectangle.prototype.copyTo = /** - * Copies all the rectangle data from this Rectangle object into the destination Rectangle object. - * @method copyTo - * @param {Rectangle} rect The destination rectangle object to copy in to - * @return {Rectangle} The destination rectangle object - **/ - function (target) { - return target.copyFrom(this); - }; - Rectangle.prototype.equals = /** - * Determines whether the object specified in the toCompare parameter is equal to this Rectangle object. - * This method compares the x, y, width, and height properties of an object against the same properties of this Rectangle object. - * @method equals - * @param {Rectangle} toCompare The rectangle to compare to this Rectangle object. - * @return {Boolean} A value of true if the object has exactly the same values for the x, y, width, and height properties as this Rectangle object; otherwise false. - **/ - function (toCompare) { - if(this.topLeft.equals(toCompare.topLeft) && this.bottomRight.equals(toCompare.bottomRight)) { - return true; - } - return false; - }; - Rectangle.prototype.inflate = /** - * Increases the size of the Rectangle object by the specified amounts. - * The center point of the Rectangle object stays the same, and its size increases to the left and right by the dx value, - * and to the top and the bottom by the dy value. - * @method inflate - * @param {Number} dx The amount to be added to the left side of this Rectangle. - * @param {Number} dy The amount to be added to the bottom side of this Rectangle. - * @return {Rectangle} This Rectangle object. - **/ - function (dx, dy) { - this._tempX = this.topLeft.x - dx; - this._tempWidth = this._width + (2 * dx); - this._tempY = this.topLeft.y - dy; - this._tempHeight = this._height + (2 * dy); - this.updateBounds(); - return this; - }; - Rectangle.prototype.inflatePoint = /** - * Increases the size of the Rectangle object. - * This method is similar to the Rectangle.inflate() method except it takes a Point object as a parameter. - * @method inflatePoint - * @param {Point} point The x property of this Point object is used to increase the horizontal dimension of the Rectangle object. The y property is used to increase the vertical dimension of the Rectangle object. - * @return {Rectangle} This Rectangle object. - **/ - function (point) { - return this.inflate(point.x, point.y); - }; - Rectangle.prototype.intersection = /** - * If the Rectangle object specified in the toIntersect parameter intersects with this Rectangle object, - * returns the area of intersection as a Rectangle object. If the rectangles do not intersect, this method - * returns an empty Rectangle object with its properties set to 0. - * @method intersection - * @param {Rectangle} toIntersect The Rectangle object to compare against to see if it intersects with this Rectangle object. - * @param {Rectangle} output Optional Rectangle object. If given the intersection values will be set into this object, otherwise a brand new Rectangle object will be created and returned. - * @return {Rectangle} A Rectangle object that equals the area of intersection. If the rectangles do not intersect, this method returns an empty Rectangle object; that is, a rectangle with its x, y, width, and height properties set to 0. - **/ - function (toIntersect, output) { - if (typeof output === "undefined") { output = new Rectangle(); } - if(this.intersects(toIntersect) === true) { - output.x = Math.max(toIntersect.topLeft.x, this.topLeft.x); - output.y = Math.max(toIntersect.topLeft.y, this.topLeft.y); - output.width = Math.min(toIntersect.rightCenter.x, this.rightCenter.x) - output.x; - output.height = Math.min(toIntersect.bottomCenter.y, this.bottomCenter.y) - output.y; - } - return output; - }; - Rectangle.prototype.intersects = /** - * Determines whether the object specified intersects (overlaps) with this Rectangle object. - * This method checks the x, y, width, and height properties of the specified Rectangle object to see if it intersects with this Rectangle object. - * @method intersects - * @param {Rectangle} r2 The Rectangle object to compare against to see if it intersects with this Rectangle object. - * @param {Number} t A tolerance value to allow for an intersection test with padding, default to 0 - * @return {Boolean} A value of true if the specified object intersects with this Rectangle object; otherwise false. - **/ - function (r2, t) { - if (typeof t === "undefined") { t = 0; } - return !(r2.left > this.right + t || r2.right < this.left - t || r2.top > this.bottom + t || r2.bottom < this.top - t); - }; - Object.defineProperty(Rectangle.prototype, "isEmpty", { - get: /** - * Determines whether or not this Rectangle object is empty. - * @method isEmpty - * @return {Boolean} A value of true if the Rectangle object's width or height is less than or equal to 0; otherwise false. - **/ - function () { - if(this.width < 1 || this.height < 1) { - return true; - } - return false; - }, - enumerable: true, - configurable: true - }); - Rectangle.prototype.offset = /** - * Adjusts the location of the Rectangle object, as determined by its top-left corner, by the specified amounts. - * @method offset - * @param {Number} dx Moves the x value of the Rectangle object by this amount. - * @param {Number} dy Moves the y value of the Rectangle object by this amount. - * @return {Rectangle} This Rectangle object. - **/ - function (dx, dy) { - if(!isNaN(dx) && !isNaN(dy)) { - this.x += dx; - this.y += dy; - } - return this; - }; - Rectangle.prototype.offsetPoint = /** - * Adjusts the location of the Rectangle object using a Point object as a parameter. This method is similar to the Rectangle.offset() method, except that it takes a Point object as a parameter. - * @method offsetPoint - * @param {Point} point A Point object to use to offset this Rectangle object. - * @return {Rectangle} This Rectangle object. - **/ - function (point) { - return this.offset(point.x, point.y); - }; - Rectangle.prototype.setEmpty = /** - * Sets all of the Rectangle object's properties to 0. A Rectangle object is empty if its width or height is less than or equal to 0. - * @method setEmpty - * @return {Rectangle} This rectangle object - **/ - function () { - return this.setTo(0, 0, 0, 0); - }; - Rectangle.prototype.setTo = /** - * Sets the members of Rectangle to the specified values. - * @method setTo - * @param {Number} x The x coordinate of the top-left corner of the rectangle. - * @param {Number} y The y coordinate of the top-left corner of the rectangle. - * @param {Number} width The width of the rectangle in pixels. - * @param {Number} height The height of the rectangle in pixels. - * @return {Rectangle} This rectangle object - **/ - function (x, y, width, height) { - this._tempX = x; - this._tempY = y; - this._tempWidth = width; - this._tempHeight = height; - this.updateBounds(); - return this; - }; - Rectangle.prototype.union = /** - * Adds two rectangles together to create a new Rectangle object, by filling in the horizontal and vertical space between the two rectangles. - * @method union - * @param {Rectangle} toUnion A Rectangle object to add to this Rectangle object. - * @param {Rectangle} output Optional Rectangle object. If given the new values will be set into this object, otherwise a brand new Rectangle object will be created and returned. - * @return {Rectangle} A Rectangle object that is the union of the two rectangles. - **/ - function (toUnion, output) { - if (typeof output === "undefined") { output = new Rectangle(); } - return output.setTo(Math.min(toUnion.x, this.x), Math.min(toUnion.y, this.y), Math.max(toUnion.right, this.right), Math.max(toUnion.bottom, this.bottom)); - }; - Rectangle.prototype.toString = /** - * Returns a string representation of this object. - * @method toString - * @return {String} a string representation of the instance. - **/ - function () { - return "[{Rectangle (x=" + this.x + " y=" + this.y + " width=" + this.width + " height=" + this.height + " empty=" + this.isEmpty + ")}]"; - }; - return Rectangle; - })(); - Phaser.Rectangle = Rectangle; -})(Phaser || (Phaser = {})); -/// -/** -* Phaser - Polygon -* -*/ -var Phaser; -(function (Phaser) { - var Polygon = (function () { - /** - * A *convex* clockwise polygon - * @class Polygon - * @constructor - * @param {Vector2} pos A vector representing the origin of the polygon (all other points are relative to this one) - * @param {Array.} points An Array of vectors representing the points in the polygon, in clockwise order. - **/ - function Polygon(pos, points, parent) { - if (typeof pos === "undefined") { pos = new Phaser.Vector2(); } - if (typeof points === "undefined") { points = []; } - if (typeof parent === "undefined") { parent = null; } - this.pos = pos; - this.points = points; - this.parent = parent; - this.recalc(); - } - Polygon.prototype.recalc = /** - * Recalculate the edges and normals of the polygon. This - * MUST be called if the points array is modified at all and - * the edges or normals are to be accessed. - */ - function () { - var points = this.points; - var len = points.length; - this.edges = []; - this.normals = []; - for(var i = 0; i < len; i++) { - var p1 = points[i]; - var p2 = i < len - 1 ? points[i + 1] : points[0]; - var e = new Phaser.Vector2().copyFrom(p2).sub(p1); - var n = new Phaser.Vector2().copyFrom(e).perp().normalize(); - this.edges.push(e); - this.normals.push(n); - } - }; - return Polygon; - })(); - Phaser.Polygon = Polygon; -})(Phaser || (Phaser = {})); -/// -/// -/** -* Phaser - Quad -* -* A Quad object is an area defined by its position, as indicated by its top-left corner (x,y) and width and height. -* Very much like a Rectangle only without all of the additional methods and properties of that class. -*/ -var Phaser; -(function (Phaser) { - var Quad = (function () { - /** - * Creates a new Quad object with the top-left corner specified by the x and y parameters and with the specified width and height parameters. If you call this function without parameters, a rectangle with x, y, width, and height properties set to 0 is created. - * @class Quad - * @constructor - * @param {Number} x The x coordinate of the top-left corner of the quad. - * @param {Number} y The y coordinate of the top-left corner of the quad. - * @param {Number} width The width of the quad. - * @param {Number} height The height of the quad. - * @return {Quad} This object - **/ - function Quad(x, y, width, height) { - if (typeof x === "undefined") { x = 0; } - if (typeof y === "undefined") { y = 0; } - if (typeof width === "undefined") { width = 0; } - if (typeof height === "undefined") { height = 0; } - this.setTo(x, y, width, height); - } - Quad.prototype.setTo = /** - * Sets the Quad to the specified size. - * @method setTo - * @param {Number} x The x coordinate of the top-left corner of the quad. - * @param {Number} y The y coordinate of the top-left corner of the quad. - * @param {Number} width The width of the quad. - * @param {Number} height The height of the quad. - * @return {Quad} This object - **/ - function (x, y, width, height) { - this.x = x; - this.y = y; - this.width = width; - this.height = height; - return this; - }; - Object.defineProperty(Quad.prototype, "left", { - get: function () { - return this.x; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Quad.prototype, "right", { - get: function () { - return this.x + this.width; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Quad.prototype, "top", { - get: function () { - return this.y; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Quad.prototype, "bottom", { - get: function () { - return this.y + this.height; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Quad.prototype, "halfWidth", { - get: function () { - return this.width / 2; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Quad.prototype, "halfHeight", { - get: function () { - return this.height / 2; - }, - enumerable: true, - configurable: true - }); - Quad.prototype.intersects = /** - * Determines whether the object specified intersects (overlaps) with this Quad object. - * This method checks the x, y, width, and height properties of the specified Quad object to see if it intersects with this Quad object. - * @method intersects - * @param {Object} quad The object to check for intersection with this Quad. Must have left/right/top/bottom properties (Rectangle, Quad). - * @param {Number} tolerance A tolerance value to allow for an intersection test with padding, default to 0 - * @return {Boolean} A value of true if the specified object intersects with this Quad; otherwise false. - **/ - function (quad, tolerance) { - if (typeof tolerance === "undefined") { tolerance = 0; } - return !(quad.left > this.right + tolerance || quad.right < this.left - tolerance || quad.top > this.bottom + tolerance || quad.bottom < this.top - tolerance); - }; - Quad.prototype.intersectsRaw = /** - * Determines whether the object specified intersects (overlaps) with the given values. - * @method intersectsProps - * @param {Number} left - * @param {Number} right - * @param {Number} top - * @param {Number} bottomt - * @param {Number} tolerance A tolerance value to allow for an intersection test with padding, default to 0 - * @return {Boolean} A value of true if the specified object intersects with this Quad; otherwise false. - **/ - function (left, right, top, bottom, tolerance) { - if (typeof tolerance === "undefined") { tolerance = 0; } - return !(left > this.right + tolerance || right < this.left - tolerance || top > this.bottom + tolerance || bottom < this.top - tolerance); - }; - Quad.prototype.contains = /** - * Determines whether the specified coordinates are contained within the region defined by this Quad object. - * @method contains - * @param {Number} x The x coordinate of the point to test. - * @param {Number} y The y coordinate of the point to test. - * @return {Boolean} A value of true if the Rectangle object contains the specified point; otherwise false. - **/ - function (x, y) { - if(x >= this.x && x <= this.right && y >= this.y && y <= this.bottom) { - return true; - } - return false; - }; - Quad.prototype.copyFrom = /** - * Copies the x/y/width/height values from the source object into this Quad - * @method copyFrom - * @param {Any} source The source object to copy from. Can be a Quad, Rectangle or any object with exposed x/y/width/height properties - * @return {Quad} This object - **/ - function (source) { - return this.setTo(source.x, source.y, source.width, source.height); - }; - Quad.prototype.copyTo = /** - * Copies the x/y/width/height values from this Quad into the given target object - * @method copyTo - * @param {Any} target The object to copy this quads values in to. Can be a Quad, Rectangle or any object with exposed x/y/width/height properties - * @return {Any} The target object - **/ - function (target) { - return target.copyFrom(this); - }; - Quad.prototype.toPolygon = /** - * Creates and returns a Polygon that is the same as this Quad. - * @method toPolygon - * @return {Polygon} A new Polygon that represents this quad. - **/ - function () { - return new Phaser.Polygon(new Phaser.Vector2(this.x, this.y), [ - new Phaser.Vector2(), - new Phaser.Vector2(this.width, 0), - new Phaser.Vector2(this.width, this.height), - new Phaser.Vector2(0, this.height) - ]); - }; - Quad.prototype.toString = /** - * Returns a string representation of this object. - * @method toString - * @return {string} a string representation of the object. - **/ - function () { - return "[{Quad (x=" + this.x + " y=" + this.y + " width=" + this.width + " height=" + this.height + ")}]"; - }; - return Quad; - })(); - Phaser.Quad = Quad; -})(Phaser || (Phaser = {})); -/// -/** -* Phaser - Circle -* -* A Circle object is an area defined by its position, as indicated by its center point (x,y) and diameter. -*/ -var Phaser; -(function (Phaser) { - var Circle = (function () { - /** - * Creates a new Circle object with the center coordinate specified by the x and y parameters and the diameter specified by the diameter parameter. If you call this function without parameters, a circle with x, y, diameter and radius properties set to 0 is created. - * @class Circle - * @constructor - * @param {Number} [x] The x coordinate of the center of the circle. - * @param {Number} [y] The y coordinate of the center of the circle. - * @param {Number} [diameter] The diameter of the circle. - * @return {Circle} This circle object - **/ - function Circle(x, y, diameter) { - if (typeof x === "undefined") { x = 0; } - if (typeof y === "undefined") { y = 0; } - if (typeof diameter === "undefined") { diameter = 0; } - this._diameter = 0; - this._radius = 0; - /** - * The x coordinate of the center of the circle - * @property x - * @type Number - **/ - this.x = 0; - /** - * The y coordinate of the center of the circle - * @property y - * @type Number - **/ - this.y = 0; - this._pos = new Phaser.Vector2(); - this.setTo(x, y, diameter); - } - Object.defineProperty(Circle.prototype, "pos", { - get: /** - * The position of this Circle object represented by a Vector2 - * @property pos - * @type Vector2 - **/ - function () { - return this._pos.setTo(this.x, this.y); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Circle.prototype, "diameter", { - get: /** - * The diameter of the circle. The largest distance between any two points on the circle. The same as the radius * 2. - * @method diameter - * @return {Number} - **/ - function () { - return this._diameter; - }, - set: /** - * The diameter of the circle. The largest distance between any two points on the circle. The same as the radius * 2. - * @method diameter - * @param {Number} The diameter of the circle. - **/ - function (value) { - if(value > 0) { - this._diameter = value; - this._radius = value * 0.5; - } - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Circle.prototype, "radius", { - get: /** - * The radius of the circle. The length of a line extending from the center of the circle to any point on the circle itself. The same as half the diameter. - * @method radius - * @return {Number} - **/ - function () { - return this._radius; - }, - set: /** - * The radius of the circle. The length of a line extending from the center of the circle to any point on the circle itself. The same as half the diameter. - * @method radius - * @param {Number} The radius of the circle. - **/ - function (value) { - if(value > 0) { - this._radius = value; - this._diameter = value * 2; - } - }, - enumerable: true, - configurable: true - }); - Circle.prototype.circumference = /** - * The circumference of the circle. - * @method circumference - * @return {Number} - **/ - function () { - return 2 * (Math.PI * this._radius); - }; - Object.defineProperty(Circle.prototype, "bottom", { - get: /** - * The sum of the y and radius properties. Changing the bottom property of a Circle object has no effect on the x and y properties, but does change the diameter. - * @method bottom - * @return {Number} - **/ - function () { - return this.y + this._radius; - }, - set: /** - * The sum of the y and radius properties. Changing the bottom property of a Circle object has no effect on the x and y properties, but does change the diameter. - * @method bottom - * @param {Number} The value to adjust the height of the circle by. - **/ - function (value) { - if(!isNaN(value)) { - if(value < this.y) { - this._radius = 0; - this._diameter = 0; - } else { - this.radius = value - this.y; - } - } - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Circle.prototype, "left", { - get: /** - * The x coordinate of the leftmost point of the circle. Changing the left property of a Circle object has no effect on the x and y properties. However it does affect the diameter, whereas changing the x value does not affect the diameter property. - * @method left - * @return {Number} The x coordinate of the leftmost point of the circle. - **/ - function () { - return this.x - this._radius; - }, - set: /** - * The x coordinate of the leftmost point of the circle. Changing the left property of a Circle object has no effect on the x and y properties. However it does affect the diameter, whereas changing the x value does not affect the diameter property. - * @method left - * @param {Number} The value to adjust the position of the leftmost point of the circle by. - **/ - function (value) { - if(!isNaN(value)) { - if(value < this.x) { - this.radius = this.x - value; - } else { - this._radius = 0; - this._diameter = 0; - } - } - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Circle.prototype, "right", { - get: /** - * The x coordinate of the rightmost point of the circle. Changing the right property of a Circle object has no effect on the x and y properties. However it does affect the diameter, whereas changing the x value does not affect the diameter property. - * @method right - * @return {Number} - **/ - function () { - return this.x + this._radius; - }, - set: /** - * The x coordinate of the rightmost point of the circle. Changing the right property of a Circle object has no effect on the x and y properties. However it does affect the diameter, whereas changing the x value does not affect the diameter property. - * @method right - * @param {Number} The amount to adjust the diameter of the circle by. - **/ - function (value) { - if(!isNaN(value)) { - if(value > this.x) { - this.radius = value - this.x; - } else { - this._radius = 0; - this._diameter = 0; - } - } - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Circle.prototype, "top", { - get: /** - * The sum of the y minus the radius property. Changing the top property of a Circle object has no effect on the x and y properties, but does change the diameter. - * @method bottom - * @return {Number} - **/ - function () { - return this.y - this._radius; - }, - set: /** - * The sum of the y minus the radius property. Changing the top property of a Circle object has no effect on the x and y properties, but does change the diameter. - * @method bottom - * @param {Number} The amount to adjust the height of the circle by. - **/ - function (value) { - if(!isNaN(value)) { - if(value > this.y) { - this._radius = 0; - this._diameter = 0; - } else { - this.radius = this.y - value; - } - } - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Circle.prototype, "area", { - get: /** - * Gets the area of this Circle. - * @method area - * @return {Number} This area of this circle. - **/ - function () { - if(this._radius > 0) { - return Math.PI * this._radius * this._radius; - } else { - return 0; - } - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Circle.prototype, "isEmpty", { - get: /** - * Determines whether or not this Circle object is empty. - * @method isEmpty - * @return {Boolean} A value of true if the Circle objects diameter is less than or equal to 0; otherwise false. - **/ - function () { - if(this._diameter <= 0) { - return true; - } - return false; - }, - enumerable: true, - configurable: true - }); - Circle.prototype.intersectCircleLine = /** - * Whether the circle intersects with a line. Checks against infinite line defined by the two points on the line, not the line segment. - * If you need details about the intersection then use Collision.lineToCircle instead. - * @method intersectCircleLine - * @param {Object} the line object to check. - * @return {Boolean} - **/ - function (line) { - return Phaser.Collision.lineToCircle(line, this).result; - }; - Circle.prototype.clone = /** - * Returns a new Circle object with the same values for the x, y, width, and height properties as the original Circle object. - * @method clone - * @param {Circle} [optional] output Optional Circle object. If given the values will be set into the object, otherwise a brand new Circle object will be created and returned. - * @return {Phaser.Circle} - **/ - function (output) { - if (typeof output === "undefined") { output = new Circle(); } - return output.setTo(this.x, this.y, this._diameter); - }; - Circle.prototype.contains = /** - * Return true if the given x/y coordinates are within this Circle object. - * If you need details about the intersection then use Phaser.Intersect.circleContainsPoint instead. - * @method contains - * @param {Number} The X value of the coordinate to test. - * @param {Number} The Y value of the coordinate to test. - * @return {Boolean} True if the coordinates are within this circle, otherwise false. - **/ - function (x, y) { - return Phaser.Collision.circleContainsPoint(this, { - x: x, - y: y - }).result; - }; - Circle.prototype.containsPoint = /** - * Return true if the coordinates of the given Point object are within this Circle object. - * If you need details about the intersection then use Phaser.Intersect.circleContainsPoint instead. - * @method containsPoint - * @param {Phaser.Point} The Point object to test. - * @return {Boolean} True if the coordinates are within this circle, otherwise false. - **/ - function (point) { - return Phaser.Collision.circleContainsPoint(this, point).result; - }; - Circle.prototype.containsCircle = /** - * Return true if the given Circle is contained entirely within this Circle object. - * If you need details about the intersection then use Phaser.Intersect.circleToCircle instead. - * @method containsCircle - * @param {Phaser.Circle} The Circle object to test. - * @return {Boolean} True if the coordinates are within this circle, otherwise false. - **/ - function (circle) { - return Phaser.Collision.circleToCircle(this, circle).result; - }; - Circle.prototype.copyFrom = /** - * Copies all of circle data from the source Circle object into the calling Circle object. - * @method copyFrom - * @param {Circle} rect The source circle object to copy from - * @return {Circle} This circle object - **/ - function (source) { - return this.setTo(source.x, source.y, source.diameter); - }; - Circle.prototype.copyTo = /** - * Copies all of circle data from this Circle object into the destination Circle object. - * @method copyTo - * @param {Circle} circle The destination circle object to copy in to - * @return {Circle} The destination circle object - **/ - function (target) { - return target.copyFrom(this); - }; - Circle.prototype.distanceTo = /** - * Returns the distance from the center of this Circle object to the given object (can be Circle, Point or anything with x/y values) - * @method distanceFrom - * @param {Circle/Point} target - The destination Point object. - * @param {Boolean} [optional] round - Round the distance to the nearest integer (default false) - * @return {Number} The distance between this Point object and the destination Point object. - **/ - function (target, round) { - if (typeof round === "undefined") { round = false; } - var dx = this.x - target.x; - var dy = this.y - target.y; - if(round === true) { - return Math.round(Math.sqrt(dx * dx + dy * dy)); - } else { - return Math.sqrt(dx * dx + dy * dy); - } - }; - Circle.prototype.equals = /** - * Determines whether the object specified in the toCompare parameter is equal to this Circle object. This method compares the x, y and diameter properties of an object against the same properties of this Circle object. - * @method equals - * @param {Circle} toCompare The circle to compare to this Circle object. - * @return {Boolean} A value of true if the object has exactly the same values for the x, y and diameter properties as this Circle object; otherwise false. - **/ - function (toCompare) { - if(this.x === toCompare.x && this.y === toCompare.y && this.diameter === toCompare.diameter) { - return true; - } - return false; - }; - Circle.prototype.intersects = /** - * Determines whether the Circle object specified in the toIntersect parameter intersects with this Circle object. This method checks the radius distances between the two Circle objects to see if they intersect. - * @method intersects - * @param {Circle} toIntersect The Circle object to compare against to see if it intersects with this Circle object. - * @return {Boolean} A value of true if the specified object intersects with this Circle object; otherwise false. - **/ - function (toIntersect) { - if(this.distanceTo(toIntersect, false) < (this._radius + toIntersect._radius)) { - return true; - } - return false; - }; - Circle.prototype.circumferencePoint = /** - * Returns a Point object containing the coordinates of a point on the circumference of this Circle based on the given angle. - * @method circumferencePoint - * @param {Number} angle The angle in radians (unless asDegrees is true) to return the point from. - * @param {Boolean} asDegrees Is the given angle in radians (false) or degrees (true)? - * @param {Phaser.Point} [optional] output An optional Point object to put the result in to. If none specified a new Point object will be created. - * @return {Phaser.Point} The Point object holding the result. - **/ - function (angle, asDegrees, output) { - if (typeof asDegrees === "undefined") { asDegrees = false; } - if (typeof output === "undefined") { output = new Phaser.Point(); } - if(asDegrees === true) { - angle = angle * Phaser.GameMath.DEG_TO_RAD; - } - output.x = this.x + this._radius * Math.cos(angle); - output.y = this.y + this._radius * Math.sin(angle); - return output; - }; - Circle.prototype.offset = /** - * Adjusts the location of the Circle object, as determined by its center coordinate, by the specified amounts. - * @method offset - * @param {Number} dx Moves the x value of the Circle object by this amount. - * @param {Number} dy Moves the y value of the Circle object by this amount. - * @return {Circle} This Circle object. - **/ - function (dx, dy) { - if(!isNaN(dx) && !isNaN(dy)) { - this.x += dx; - this.y += dy; - } - return this; - }; - Circle.prototype.offsetPoint = /** - * Adjusts the location of the Circle object using a Point object as a parameter. This method is similar to the Circle.offset() method, except that it takes a Point object as a parameter. - * @method offsetPoint - * @param {Point} point A Point object to use to offset this Circle object. - * @return {Circle} This Circle object. - **/ - function (point) { - return this.offset(point.x, point.y); - }; - Circle.prototype.setTo = /** - * Sets the members of Circle to the specified values. - * @method setTo - * @param {Number} x The x coordinate of the center of the circle. - * @param {Number} y The y coordinate of the center of the circle. - * @param {Number} diameter The diameter of the circle in pixels. - * @return {Circle} This circle object - **/ - function (x, y, diameter) { - this.x = x; - this.y = y; - this._diameter = diameter; - this._radius = diameter * 0.5; - return this; - }; - Circle.prototype.toString = /** - * Returns a string representation of this object. - * @method toString - * @return {string} a string representation of the instance. - **/ - function () { - return "[{Circle (x=" + this.x + " y=" + this.y + " diameter=" + this.diameter + " radius=" + this.radius + ")}]"; - }; - return Circle; - })(); - Phaser.Circle = Circle; -})(Phaser || (Phaser = {})); -/// -/** -* Phaser - Line -* -* A Line object is an infinte line through space. The two sets of x/y coordinates define the Line Segment. -*/ -var Phaser; -(function (Phaser) { - var Line = (function () { - /** - * - * @constructor - * @param {Number} x1 - * @param {Number} y1 - * @param {Number} x2 - * @param {Number} y2 - * @return {Phaser.Line} This Object - */ - function Line(x1, y1, x2, y2) { - if (typeof x1 === "undefined") { x1 = 0; } - if (typeof y1 === "undefined") { y1 = 0; } - if (typeof x2 === "undefined") { x2 = 0; } - if (typeof y2 === "undefined") { y2 = 0; } - /** - * - * @property x1 - * @type {Number} - */ - this.x1 = 0; - /** - * - * @property y1 - * @type {Number} - */ - this.y1 = 0; - /** - * - * @property x2 - * @type {Number} - */ - this.x2 = 0; - /** - * - * @property y2 - * @type {Number} - */ - this.y2 = 0; - this.setTo(x1, y1, x2, y2); - } - Line.prototype.clone = /** - * - * @method clone - * @param {Phaser.Line} [output] - * @return {Phaser.Line} - */ - function (output) { - if (typeof output === "undefined") { output = new Line(); } - return output.setTo(this.x1, this.y1, this.x2, this.y2); - }; - Line.prototype.copyFrom = /** - * - * @method copyFrom - * @param {Phaser.Line} source - * @return {Phaser.Line} - */ - function (source) { - return this.setTo(source.x1, source.y1, source.x2, source.y2); - }; - Line.prototype.copyTo = /** - * - * @method copyTo - * @param {Phaser.Line} target - * @return {Phaser.Line} - */ - function (target) { - return target.copyFrom(this); - }; - Line.prototype.setTo = /** - * - * @method setTo - * @param {Number} x1 - * @param {Number} y1 - * @param {Number} x2 - * @param {Number} y2 - * @return {Phaser.Line} - */ - function (x1, y1, x2, y2) { - if (typeof x1 === "undefined") { x1 = 0; } - if (typeof y1 === "undefined") { y1 = 0; } - if (typeof x2 === "undefined") { x2 = 0; } - if (typeof y2 === "undefined") { y2 = 0; } - this.x1 = x1; - this.y1 = y1; - this.x2 = x2; - this.y2 = y2; - return this; - }; - Object.defineProperty(Line.prototype, "width", { - get: function () { - return Math.max(this.x1, this.x2) - Math.min(this.x1, this.x2); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Line.prototype, "height", { - get: function () { - return Math.max(this.y1, this.y2) - Math.min(this.y1, this.y2); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Line.prototype, "length", { - get: /** - * - * @method length - * @return {Number} - */ - function () { - return Math.sqrt((this.x2 - this.x1) * (this.x2 - this.x1) + (this.y2 - this.y1) * (this.y2 - this.y1)); - }, - enumerable: true, - configurable: true - }); - Line.prototype.getY = /** - * - * @method getY - * @param {Number} x - * @return {Number} - */ - function (x) { - return this.slope * x + this.yIntercept; - }; - Object.defineProperty(Line.prototype, "angle", { - get: /** - * - * @method angle - * @return {Number} - */ - function () { - return Math.atan2(this.x2 - this.x1, this.y2 - this.y1); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Line.prototype, "slope", { - get: /** - * - * @method slope - * @return {Number} - */ - function () { - return (this.y2 - this.y1) / (this.x2 - this.x1); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Line.prototype, "perpSlope", { - get: /** - * - * @method perpSlope - * @return {Number} - */ - function () { - return -((this.x2 - this.x1) / (this.y2 - this.y1)); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Line.prototype, "yIntercept", { - get: /** - * - * @method yIntercept - * @return {Number} - */ - function () { - return (this.y1 - this.slope * this.x1); - }, - enumerable: true, - configurable: true - }); - Line.prototype.isPointOnLine = /** - * - * @method isPointOnLine - * @param {Number} x - * @param {Number} y - * @return {Boolean} - */ - function (x, y) { - if((x - this.x1) * (this.y2 - this.y1) === (this.x2 - this.x1) * (y - this.y1)) { - return true; - } else { - return false; - } - }; - Line.prototype.isPointOnLineSegment = /** - * - * @method isPointOnLineSegment - * @param {Number} x - * @param {Number} y - * @return {Boolean} - */ - function (x, y) { - var xMin = Math.min(this.x1, this.x2); - var xMax = Math.max(this.x1, this.x2); - var yMin = Math.min(this.y1, this.y2); - var yMax = Math.max(this.y1, this.y2); - if(this.isPointOnLine(x, y) && (x >= xMin && x <= xMax) && (y >= yMin && y <= yMax)) { - return true; - } else { - return false; - } - }; - Line.prototype.intersectLineLine = /** - * - * @method intersectLineLine - * @param {Any} line - * @return {Any} - */ - function (line) { - //return Phaser.intersectLineLine(this,line); - }; - Line.prototype.perp = /** - * - * @method perp - * @param {Number} x - * @param {Number} y - * @param {Phaser.Line} [output] - * @return {Phaser.Line} - */ - function (x, y, output) { - if(this.y1 === this.y2) { - if(output) { - output.setTo(x, y, x, this.y1); - } else { - return new Line(x, y, x, this.y1); - } - } - var yInt = (y - this.perpSlope * x); - var pt = this.intersectLineLine({ - x1: x, - y1: y, - x2: 0, - y2: yInt - }); - if(output) { - output.setTo(x, y, pt.x, pt.y); - } else { - return new Line(x, y, pt.x, pt.y); - } - }; - Line.prototype.toString = /* - intersectLineCircle (circle:Circle) - { - var perp = this.perp() - return Phaser.intersectLineCircle(this,circle); - - } - */ - /** - * - * @method toString - * @return {String} - */ - function () { - return "[{Line (x1=" + this.x1 + " y1=" + this.y1 + " x2=" + this.x2 + " y2=" + this.y2 + ")}]"; - }; - return Line; - })(); - Phaser.Line = Line; -})(Phaser || (Phaser = {})); -/// -/** -* Phaser - IntersectResult -* -* A light-weight result object to hold the results of an intersection. For when you need more than just true/false. -*/ -var Phaser; -(function (Phaser) { - var IntersectResult = (function () { - function IntersectResult() { - /** - * Did they intersect or not? - * @property result - * @type {Boolean} - */ - this.result = false; - } - IntersectResult.prototype.setTo = /** - * - * @method setTo - * @param {Number} x1 - * @param {Number} y1 - * @param {Number} [x2] - * @param {Number} [y2] - * @param {Number} [width] - * @param {Number} [height] - */ - function (x1, y1, x2, y2, width, height) { - if (typeof x2 === "undefined") { x2 = 0; } - if (typeof y2 === "undefined") { y2 = 0; } - if (typeof width === "undefined") { width = 0; } - if (typeof height === "undefined") { height = 0; } - this.x = x1; - this.y = y1; - this.x1 = x1; - this.y1 = y1; - this.x2 = x2; - this.y2 = y2; - this.width = width; - this.height = height; - }; - return IntersectResult; - })(); - Phaser.IntersectResult = IntersectResult; -})(Phaser || (Phaser = {})); -/// -/// -/** -* Phaser - Response -* -*/ -var Phaser; -(function (Phaser) { - var Response = (function () { - /** - * An object representing the result of an intersection. Contain information about: - * - The two objects participating in the intersection - * - The vector representing the minimum change necessary to extract the first object - * from the second one. - * - Whether the first object is entirely inside the second, or vice versa. - * - * @constructor - */ - function Response() { - this.a = null; - this.b = null; - this.overlapN = new Phaser.Vector2(); - this.overlapV = new Phaser.Vector2(); - this.clear(); - } - Response.prototype.clear = /** - * Set some values of the response back to their defaults. Call this between tests if - * you are going to reuse a single Response object for multiple intersection tests (recommented) - * - * @return {Response} This for chaining - */ - function () { - this.aInB = true; - this.bInA = true; - this.overlap = Number.MAX_VALUE; - return this; - }; - return Response; - })(); - Phaser.Response = Response; -})(Phaser || (Phaser = {})); -/// -/** -* Phaser - Vector2 -* -* A two dimensional vector. -* Contains methods and ideas from verlet-js by Sub Protocol, SAT.js by Jim Riecken and N by Metanet Software. -*/ -var Phaser; -(function (Phaser) { - var Vector2 = (function () { - /** - * Creates a new Vector2 object. - * @class Vector2 - * @constructor - * @param {Number} x The x position of the vector - * @param {Number} y The y position of the vector - * @return {Vector2} This object - **/ - function Vector2(x, y) { - if (typeof x === "undefined") { x = 0; } - if (typeof y === "undefined") { y = 0; } - this.x = x; - this.y = y; - } - Vector2.prototype.setTo = function (x, y) { - this.x = x; - this.y = y; - return this; - }; - Vector2.prototype.add = /** - * Add this vector to the given one and return the result. - * - * @param {Vector2} v The other Vector. - * @param {Vector2} The output Vector. - * @return {Vector2} The new Vector - */ - function (v, output) { - if (typeof output === "undefined") { output = new Vector2(); } - return output.setTo(this.x + v.x, this.y + v.y); - }; - Vector2.prototype.sub = /** - * Subtract this vector to the given one and return the result. - * - * @param {Vector2} v The other Vector. - * @param {Vector2} The output Vector. - * @return {Vector2} The new Vector - */ - function (v, output) { - if (typeof output === "undefined") { output = new Vector2(); } - return output.setTo(this.x - v.x, this.y - v.y); - }; - Vector2.prototype.mul = /** - * Multiply this vector with the given one and return the result. - * - * @param {Vector2} v The other Vector. - * @param {Vector2} The output Vector. - * @return {Vector2} The new Vector - */ - function (v, output) { - if (typeof output === "undefined") { output = new Vector2(); } - return output.setTo(this.x * v.x, this.y * v.y); - }; - Vector2.prototype.div = /** - * Divide this vector by the given one and return the result. - * - * @param {Vector2} v The other Vector. - * @param {Vector2} The output Vector. - * @return {Vector2} The new Vector - */ - function (v, output) { - if (typeof output === "undefined") { output = new Vector2(); } - return output.setTo(this.x / v.x, this.y / v.y); - }; - Vector2.prototype.scale = /** - * Scale this vector by the given values and return the result. - * - * @param {number} x The scaling factor in the x direction. - * @param {?number=} y The scaling factor in the y direction. If this - * is not specified, the x scaling factor will be used. - * @return {Vector} The new Vector - */ - function (x, y, output) { - if (typeof y === "undefined") { y = null; } - if (typeof output === "undefined") { output = new Vector2(); } - if(y === null) { - y = x; - } - return output.setTo(this.x * x, this.y * y); - }; - Vector2.prototype.perp = /** - * Rotate this vector by 90 degrees - * - * @return {Vector} This for chaining. - */ - function (output) { - if (typeof output === "undefined") { output = this; } - var x = this.x; - return output.setTo(this.y, -x); - }; - Vector2.prototype.mutableSet = // Same as copyFrom, used by VerletManager - function (v) { - this.x = v.x; - this.y = v.y; - return this; - }; - Vector2.prototype.mutableAdd = /** - * Add another vector to this one. - * - * @param {Vector} other The other Vector. - * @return {Vector} This for chaining. - */ - function (v) { - this.x += v.x; - this.y += v.y; - return this; - }; - Vector2.prototype.mutableSub = /** - * Subtract another vector from this one. - * - * @param {Vector} other The other Vector. - * @return {Vector} This for chaining. - */ - function (v) { - this.x -= v.x; - this.y -= v.y; - return this; - }; - Vector2.prototype.mutableMul = /** - * Multiply another vector with this one. - * - * @param {Vector} other The other Vector. - * @return {Vector} This for chaining. - */ - function (v) { - this.x *= v.x; - this.y *= v.y; - return this; - }; - Vector2.prototype.mutableDiv = /** - * Divide this vector by another one. - * - * @param {Vector} other The other Vector. - * @return {Vector} This for chaining. - */ - function (v) { - this.x /= v.x; - this.y /= v.y; - return this; - }; - Vector2.prototype.mutableScale = /** - * Scale this vector. - * - * @param {number} x The scaling factor in the x direction. - * @param {?number=} y The scaling factor in the y direction. If this - * is not specified, the x scaling factor will be used. - * @return {Vector} This for chaining. - */ - function (x, y) { - this.x *= x; - this.y *= y || x; - return this; - }; - Vector2.prototype.reverse = /** - * Reverse this vector. - * - * @return {Vector} This for chaining. - */ - function () { - this.x = -this.x; - this.y = -this.y; - return this; - }; - Vector2.prototype.edge = function (v, output) { - if (typeof output === "undefined") { output = new Vector2(); } - return this.sub(v, output); - }; - Vector2.prototype.equals = function (v) { - return this.x == v.x && this.y == v.y; - }; - Vector2.prototype.epsilonEquals = function (v, epsilon) { - return Math.abs(this.x - v.x) <= epsilon && Math.abs(this.y - v.y) <= epsilon; - }; - Vector2.prototype.length = /** - * Get the length of this vector. - * - * @return {number} The length of this vector. - */ - function () { - return Math.sqrt((this.x * this.x) + (this.y * this.y)); - }; - Vector2.prototype.length2 = /** - * Get the length^2 of this vector. - * - * @return {number} The length^2 of this vector. - */ - function () { - return (this.x * this.x) + (this.y * this.y); - }; - Vector2.prototype.distance = /** - * Get the distance between this vector and the given vector. - * - * @return {Vector2} v The vector to check - */ - function (v) { - return Math.sqrt(this.distance2(v)); - }; - Vector2.prototype.distance2 = /** - * Get the distance^2 between this vector and the given vector. - * - * @return {Vector2} v The vector to check - */ - function (v) { - return ((v.x - this.x) * (v.x - this.x)) + ((v.y - this.y) * (v.y - this.y)); - }; - Vector2.prototype.project = /** - * Project this vector on to another vector. - * - * @param {Vector} other The vector to project onto. - * @return {Vector} This for chaining. - */ - function (other) { - var amt = this.dot(other) / other.length2(); - if(amt != 0) { - this.x = amt * other.x; - this.y = amt * other.y; - } - return this; - }; - Vector2.prototype.projectN = /** - * Project this vector onto a vector of unit length. - * - * @param {Vector} other The unit vector to project onto. - * @return {Vector} This for chaining. - */ - function (other) { - var amt = this.dot(other); - if(amt != 0) { - this.x = amt * other.x; - this.y = amt * other.y; - } - return this; - }; - Vector2.prototype.reflect = /** - * Reflect this vector on an arbitrary axis. - * - * @param {Vector} axis The vector representing the axis. - * @return {Vector} This for chaining. - */ - function (axis) { - var x = this.x; - var y = this.y; - this.project(axis).scale(2); - this.x -= x; - this.y -= y; - return this; - }; - Vector2.prototype.reflectN = /** - * Reflect this vector on an arbitrary axis (represented by a unit vector) - * - * @param {Vector} axis The unit vector representing the axis. - * @return {Vector} This for chaining. - */ - function (axis) { - var x = this.x; - var y = this.y; - this.projectN(axis).scale(2); - this.x -= x; - this.y -= y; - return this; - }; - Vector2.prototype.getProjectionMagnitude = function (v) { - var den = v.dot(v); - if(den == 0) { - return 0; - } else { - return Math.abs(this.dot(v) / den); - } - }; - Vector2.prototype.direction = function (output) { - if (typeof output === "undefined") { output = new Vector2(); } - output.copyFrom(this); - return this.normalize(output); - }; - Vector2.prototype.normalRightHand = function (output) { - if (typeof output === "undefined") { output = this; } - return output.setTo(this.y * -1, this.x); - }; - Vector2.prototype.normalize = /** - * Normalize (make unit length) this vector. - * - * @return {Vector} This for chaining. - */ - function (output) { - if (typeof output === "undefined") { output = this; } - var m = this.length(); - if(m != 0) { - output.setTo(this.x / m, this.y / m); - } - return output; - }; - Vector2.prototype.getMagnitude = function () { - return Math.sqrt(Math.pow(this.x, 2) + Math.pow(this.y, 2)); - }; - Vector2.prototype.dot = /** - * Get the dot product of this vector against another. - * - * @param {Vector} other The vector to dot this one against. - * @return {number} The dot product. - */ - function (v) { - return ((this.x * v.x) + (this.y * v.y)); - }; - Vector2.prototype.cross = /** - * Get the cross product of this vector against another. - * - * @param {Vector} other The vector to cross this one against. - * @return {number} The cross product. - */ - function (v) { - return ((this.x * v.y) - (this.y * v.x)); - }; - Vector2.prototype.angle = /** - * Get the angle between this vector and the given vector. - * - * @return {Vector2} v The vector to check - */ - function (v) { - return Math.atan2(this.x * v.y - this.y * v.x, this.x * v.x + this.y * v.y); - }; - Vector2.prototype.angle2 = function (vLeft, vRight) { - return vLeft.sub(this).angle(vRight.sub(this)); - }; - Vector2.prototype.rotate = /** - * Rotate this vector around the origin to the given angle (theta) and return the result in a new Vector - * - * @return {Vector2} v The vector to check - */ - function (origin, theta, output) { - if (typeof output === "undefined") { output = new Vector2(); } - var x = this.x - origin.x; - var y = this.y - origin.y; - return output.setTo(x * Math.cos(theta) - y * Math.sin(theta) + origin.x, x * Math.sin(theta) + y * Math.cos(theta) + origin.y); - }; - Vector2.prototype.clone = function (output) { - if (typeof output === "undefined") { output = new Vector2(); } - return output.setTo(this.x, this.y); - }; - Vector2.prototype.copyFrom = function (v) { - this.x = v.x; - this.y = v.y; - return this; - }; - Vector2.prototype.copyTo = function (v) { - return v.setTo(this.x, this.y); - }; - Vector2.prototype.toString = /** - * Returns a string representation of this object. - * @method toString - * @return {string} a string representation of the object. - **/ - function () { - return "[{Vector2 (x=" + this.x + " y=" + this.y + ")}]"; - }; - return Vector2; - })(); - Phaser.Vector2 = Vector2; -})(Phaser || (Phaser = {})); -/// -/** -* Phaser - LinkedList -* -* A miniature linked list class. Useful for optimizing time-critical or highly repetitive tasks! -*/ -var Phaser; -(function (Phaser) { - var LinkedList = (function () { - /** - * Creates a new link, and sets object and next to null. - */ - function LinkedList() { - this.object = null; - this.next = null; - } - LinkedList.prototype.destroy = /** - * Clean up memory. - */ - function () { - this.object = null; - if(this.next != null) { - this.next.destroy(); - } - this.next = null; - }; - return LinkedList; - })(); - Phaser.LinkedList = LinkedList; -})(Phaser || (Phaser = {})); -/// -/// -/** -* Phaser - QuadTree -* -* A fairly generic quad tree structure for rapid overlap checks. QuadTree is also configured for single or dual list operation. -* You can add items either to its A list or its B list. When you do an overlap check, you can compare the A list to itself, -* or the A list against the B list. Handy for different things! -*/ -var Phaser; -(function (Phaser) { - var QuadTree = (function (_super) { - __extends(QuadTree, _super); - /** - * Instantiate a new Quad Tree node. - * - * @param {Number} x The X-coordinate of the point in space. - * @param {Number} y The Y-coordinate of the point in space. - * @param {Number} width Desired width of this node. - * @param {Number} height Desired height of this node. - * @param {Number} parent The parent branch or node. Pass null to create a root. - */ - function QuadTree(x, y, width, height, parent) { - if (typeof parent === "undefined") { parent = null; } - _super.call(this, x, y, width, height); - this._headA = this._tailA = new Phaser.LinkedList(); - this._headB = this._tailB = new Phaser.LinkedList(); - //Copy the parent's children (if there are any) - if(parent != null) { - var iterator; - var ot; - if(parent._headA.object != null) { - iterator = parent._headA; - while(iterator != null) { - if(this._tailA.object != null) { - ot = this._tailA; - this._tailA = new Phaser.LinkedList(); - ot.next = this._tailA; - } - this._tailA.object = iterator.object; - iterator = iterator.next; - } - } - if(parent._headB.object != null) { - iterator = parent._headB; - while(iterator != null) { - if(this._tailB.object != null) { - ot = this._tailB; - this._tailB = new Phaser.LinkedList(); - ot.next = this._tailB; - } - this._tailB.object = iterator.object; - iterator = iterator.next; - } - } - } else { - QuadTree._min = (this.width + this.height) / (2 * QuadTree.divisions); - } - this._canSubdivide = (this.width > QuadTree._min) || (this.height > QuadTree._min); - //Set up comparison/sort helpers - this._northWestTree = null; - this._northEastTree = null; - this._southEastTree = null; - this._southWestTree = null; - this._leftEdge = this.x; - this._rightEdge = this.x + this.width; - this._halfWidth = this.width / 2; - this._midpointX = this._leftEdge + this._halfWidth; - this._topEdge = this.y; - this._bottomEdge = this.y + this.height; - this._halfHeight = this.height / 2; - this._midpointY = this._topEdge + this._halfHeight; - } - QuadTree.A_LIST = 0; - QuadTree.B_LIST = 1; - QuadTree.prototype.destroy = /** - * Clean up memory. - */ - function () { - this._tailA.destroy(); - this._tailB.destroy(); - this._headA.destroy(); - this._headB.destroy(); - this._tailA = null; - this._tailB = null; - this._headA = null; - this._headB = null; - if(this._northWestTree != null) { - this._northWestTree.destroy(); - } - if(this._northEastTree != null) { - this._northEastTree.destroy(); - } - if(this._southEastTree != null) { - this._southEastTree.destroy(); - } - if(this._southWestTree != null) { - this._southWestTree.destroy(); - } - this._northWestTree = null; - this._northEastTree = null; - this._southEastTree = null; - this._southWestTree = null; - QuadTree._object = null; - QuadTree._processingCallback = null; - QuadTree._notifyCallback = null; - }; - QuadTree.prototype.load = /** - * Load objects and/or groups into the quad tree, and register notify and processing callbacks. - * - * @param {Basic} objectOrGroup1 Any object that is or extends GameObject or Group. - * @param {Basic} objectOrGroup2 Any object that is or extends GameObject or Group. If null, the first parameter will be checked against itself. - * @param {Function} notifyCallback A function with the form myFunction(Object1:GameObject,Object2:GameObject) that is called whenever two objects are found to overlap in world space, and either no processCallback is specified, or the processCallback returns true. - * @param {Function} processCallback A function with the form myFunction(Object1:GameObject,Object2:GameObject):bool that is called whenever two objects are found to overlap in world space. The notifyCallback is only called if this function returns true. See GameObject.separate(). - * @param context The context in which the callbacks will be called - */ - function (objectOrGroup1, objectOrGroup2, notifyCallback, processCallback, context) { - if (typeof objectOrGroup2 === "undefined") { objectOrGroup2 = null; } - if (typeof notifyCallback === "undefined") { notifyCallback = null; } - if (typeof processCallback === "undefined") { processCallback = null; } - if (typeof context === "undefined") { context = null; } - this.add(objectOrGroup1, QuadTree.A_LIST); - if(objectOrGroup2 != null) { - this.add(objectOrGroup2, QuadTree.B_LIST); - QuadTree._useBothLists = true; - } else { - QuadTree._useBothLists = false; - } - QuadTree._notifyCallback = notifyCallback; - QuadTree._processingCallback = processCallback; - QuadTree._callbackContext = context; - }; - QuadTree.prototype.add = /** - * Call this function to add an object to the root of the tree. - * This function will recursively add all group members, but - * not the groups themselves. - * - * @param {Basic} objectOrGroup GameObjects are just added, Groups are recursed and their applicable members added accordingly. - * @param {Number} list A uint flag indicating the list to which you want to add the objects. Options are QuadTree.A_LIST and QuadTree.B_LIST. - */ - function (objectOrGroup, list) { - QuadTree._list = list; - if(objectOrGroup.isGroup == true) { - var i = 0; - var basic; - var members = objectOrGroup['members']; - var l = objectOrGroup['length']; - while(i < l) { - basic = members[i++]; - if((basic != null) && basic.exists) { - if(basic.isGroup) { - this.add(basic, list); - } else { - QuadTree._object = basic; - if(QuadTree._object.exists && QuadTree._object.allowCollisions) { - this.addObject(); - } - } - } - } - } else { - QuadTree._object = objectOrGroup; - if(QuadTree._object.exists && QuadTree._object.allowCollisions) { - this.addObject(); - } - } - }; - QuadTree.prototype.addObject = /** - * Internal function for recursively navigating and creating the tree - * while adding objects to the appropriate nodes. - */ - function () { - //If this quad (not its children) lies entirely inside this object, add it here - if(!this._canSubdivide || ((this._leftEdge >= QuadTree._object.collisionMask.x) && (this._rightEdge <= QuadTree._object.collisionMask.right) && (this._topEdge >= QuadTree._object.collisionMask.y) && (this._bottomEdge <= QuadTree._object.collisionMask.bottom))) { - this.addToList(); - return; - } - //See if the selected object fits completely inside any of the quadrants - if((QuadTree._object.collisionMask.x > this._leftEdge) && (QuadTree._object.collisionMask.right < this._midpointX)) { - if((QuadTree._object.collisionMask.y > this._topEdge) && (QuadTree._object.collisionMask.bottom < this._midpointY)) { - if(this._northWestTree == null) { - this._northWestTree = new QuadTree(this._leftEdge, this._topEdge, this._halfWidth, this._halfHeight, this); - } - this._northWestTree.addObject(); - return; - } - if((QuadTree._object.collisionMask.y > this._midpointY) && (QuadTree._object.collisionMask.bottom < this._bottomEdge)) { - if(this._southWestTree == null) { - this._southWestTree = new QuadTree(this._leftEdge, this._midpointY, this._halfWidth, this._halfHeight, this); - } - this._southWestTree.addObject(); - return; - } - } - if((QuadTree._object.collisionMask.x > this._midpointX) && (QuadTree._object.collisionMask.right < this._rightEdge)) { - if((QuadTree._object.collisionMask.y > this._topEdge) && (QuadTree._object.collisionMask.bottom < this._midpointY)) { - if(this._northEastTree == null) { - this._northEastTree = new QuadTree(this._midpointX, this._topEdge, this._halfWidth, this._halfHeight, this); - } - this._northEastTree.addObject(); - return; - } - if((QuadTree._object.collisionMask.y > this._midpointY) && (QuadTree._object.collisionMask.bottom < this._bottomEdge)) { - if(this._southEastTree == null) { - this._southEastTree = new QuadTree(this._midpointX, this._midpointY, this._halfWidth, this._halfHeight, this); - } - this._southEastTree.addObject(); - return; - } - } - //If it wasn't completely contained we have to check out the partial overlaps - if((QuadTree._object.collisionMask.right > this._leftEdge) && (QuadTree._object.collisionMask.x < this._midpointX) && (QuadTree._object.collisionMask.bottom > this._topEdge) && (QuadTree._object.collisionMask.y < this._midpointY)) { - if(this._northWestTree == null) { - this._northWestTree = new QuadTree(this._leftEdge, this._topEdge, this._halfWidth, this._halfHeight, this); - } - this._northWestTree.addObject(); - } - if((QuadTree._object.collisionMask.right > this._midpointX) && (QuadTree._object.collisionMask.x < this._rightEdge) && (QuadTree._object.collisionMask.bottom > this._topEdge) && (QuadTree._object.collisionMask.y < this._midpointY)) { - if(this._northEastTree == null) { - this._northEastTree = new QuadTree(this._midpointX, this._topEdge, this._halfWidth, this._halfHeight, this); - } - this._northEastTree.addObject(); - } - if((QuadTree._object.collisionMask.right > this._midpointX) && (QuadTree._object.collisionMask.x < this._rightEdge) && (QuadTree._object.collisionMask.bottom > this._midpointY) && (QuadTree._object.collisionMask.y < this._bottomEdge)) { - if(this._southEastTree == null) { - this._southEastTree = new QuadTree(this._midpointX, this._midpointY, this._halfWidth, this._halfHeight, this); - } - this._southEastTree.addObject(); - } - if((QuadTree._object.collisionMask.right > this._leftEdge) && (QuadTree._object.collisionMask.x < this._midpointX) && (QuadTree._object.collisionMask.bottom > this._midpointY) && (QuadTree._object.collisionMask.y < this._bottomEdge)) { - if(this._southWestTree == null) { - this._southWestTree = new QuadTree(this._leftEdge, this._midpointY, this._halfWidth, this._halfHeight, this); - } - this._southWestTree.addObject(); - } - }; - QuadTree.prototype.addToList = /** - * Internal function for recursively adding objects to leaf lists. - */ - function () { - var ot; - if(QuadTree._list == QuadTree.A_LIST) { - if(this._tailA.object != null) { - ot = this._tailA; - this._tailA = new Phaser.LinkedList(); - ot.next = this._tailA; - } - this._tailA.object = QuadTree._object; - } else { - if(this._tailB.object != null) { - ot = this._tailB; - this._tailB = new Phaser.LinkedList(); - ot.next = this._tailB; - } - this._tailB.object = QuadTree._object; - } - if(!this._canSubdivide) { - return; - } - if(this._northWestTree != null) { - this._northWestTree.addToList(); - } - if(this._northEastTree != null) { - this._northEastTree.addToList(); - } - if(this._southEastTree != null) { - this._southEastTree.addToList(); - } - if(this._southWestTree != null) { - this._southWestTree.addToList(); - } - }; - QuadTree.prototype.execute = /** - * QuadTree's other main function. Call this after adding objects - * using QuadTree.load() to compare the objects that you loaded. - * - * @return {Boolean} Whether or not any overlaps were found. - */ - function () { - var overlapProcessed = false; - var iterator; - if(this._headA.object != null) { - iterator = this._headA; - while(iterator != null) { - QuadTree._object = iterator.object; - if(QuadTree._useBothLists) { - QuadTree._iterator = this._headB; - } else { - QuadTree._iterator = iterator.next; - } - if(QuadTree._object.exists && (QuadTree._object.allowCollisions > 0) && (QuadTree._iterator != null) && (QuadTree._iterator.object != null) && QuadTree._iterator.object.exists && this.overlapNode()) { - overlapProcessed = true; - } - iterator = iterator.next; - } - } - //Advance through the tree by calling overlap on each child - if((this._northWestTree != null) && this._northWestTree.execute()) { - overlapProcessed = true; - } - if((this._northEastTree != null) && this._northEastTree.execute()) { - overlapProcessed = true; - } - if((this._southEastTree != null) && this._southEastTree.execute()) { - overlapProcessed = true; - } - if((this._southWestTree != null) && this._southWestTree.execute()) { - overlapProcessed = true; - } - return overlapProcessed; - }; - QuadTree.prototype.overlapNode = /** - * A private for comparing an object against the contents of a node. - * - * @return {Boolean} Whether or not any overlaps were found. - */ - function () { - //Walk the list and check for overlaps - var overlapProcessed = false; - var checkObject; - while(QuadTree._iterator != null) { - if(!QuadTree._object.exists || (QuadTree._object.allowCollisions <= 0)) { - break; - } - checkObject = QuadTree._iterator.object; - if((QuadTree._object === checkObject) || !checkObject.exists || (checkObject.allowCollisions <= 0)) { - QuadTree._iterator = QuadTree._iterator.next; - continue; - } - if(QuadTree._object.collisionMask.checkHullIntersection(checkObject.collisionMask)) { - //Execute callback functions if they exist - if((QuadTree._processingCallback == null) || QuadTree._processingCallback(QuadTree._object, checkObject)) { - overlapProcessed = true; - } - if(overlapProcessed && (QuadTree._notifyCallback != null)) { - if(QuadTree._callbackContext !== null) { - QuadTree._notifyCallback.call(QuadTree._callbackContext, QuadTree._object, checkObject); - } else { - QuadTree._notifyCallback(QuadTree._object, checkObject); - } - } - } - QuadTree._iterator = QuadTree._iterator.next; - } - return overlapProcessed; - }; - return QuadTree; - })(Phaser.Rectangle); - Phaser.QuadTree = QuadTree; -})(Phaser || (Phaser = {})); -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/** -* Phaser - Collision -* -* A set of extremely useful collision and geometry intersection functions. -*/ -var Phaser; -(function (Phaser) { - var Collision = (function () { - /** - * Collision constructor - * @param game A reference to the current Game - */ - function Collision(game) { - this._game = game; - Collision.T_VECTORS = []; - for(var i = 0; i < 10; i++) { - Collision.T_VECTORS.push(new Phaser.Vector2()); - } - Collision.T_ARRAYS = []; - for(var i = 0; i < 5; i++) { - Collision.T_ARRAYS.push([]); - } - } - Collision.LEFT = 0x0001; - Collision.RIGHT = 0x0010; - Collision.UP = 0x0100; - Collision.DOWN = 0x1000; - Collision.NONE = 0; - Collision.CEILING = Collision.UP; - Collision.FLOOR = Collision.DOWN; - Collision.WALL = Collision.LEFT | Collision.RIGHT; - Collision.ANY = Collision.LEFT | Collision.RIGHT | Collision.UP | Collision.DOWN; - Collision.OVERLAP_BIAS = 4; - Collision.TILE_OVERLAP = false; - Collision.lineToLine = /** - * Checks for Line to Line intersection and returns an IntersectResult object containing the results of the intersection. - * @param line1 The first Line object to check - * @param line2 The second Line object to check - * @param [output] An optional IntersectResult object to store the intersection values in. One is created if none given. - * @returns {IntersectResult=} An IntersectResult object containing the results of the intersection - */ - function lineToLine(line1, line2, output) { - if (typeof output === "undefined") { output = new Phaser.IntersectResult(); } - var denominator = (line1.x1 - line1.x2) * (line2.y1 - line2.y2) - (line1.y1 - line1.y2) * (line2.x1 - line2.x2); - if(denominator !== 0) { - output.result = true; - output.x = ((line1.x1 * line1.y2 - line1.y1 * line1.x2) * (line2.x1 - line2.x2) - (line1.x1 - line1.x2) * (line2.x1 * line2.y2 - line2.y1 * line2.x2)) / denominator; - output.y = ((line1.x1 * line1.y2 - line1.y1 * line1.x2) * (line2.y1 - line2.y2) - (line1.y1 - line1.y2) * (line2.x1 * line2.y2 - line2.y1 * line2.x2)) / denominator; - } - return output; - }; - Collision.lineToLineSegment = /** - * Checks for Line to Line Segment intersection and returns an IntersectResult object containing the results of the intersection. - * @param line The Line object to check - * @param seg The Line segment object to check - * @param [output] An optional IntersectResult object to store the intersection values in. One is created if none given. - * @returns {IntersectResult=} An IntersectResult object containing the results of the intersection - */ - function lineToLineSegment(line, seg, output) { - if (typeof output === "undefined") { output = new Phaser.IntersectResult(); } - var denominator = (line.x1 - line.x2) * (seg.y1 - seg.y2) - (line.y1 - line.y2) * (seg.x1 - seg.x2); - if(denominator !== 0) { - output.x = ((line.x1 * line.y2 - line.y1 * line.x2) * (seg.x1 - seg.x2) - (line.x1 - line.x2) * (seg.x1 * seg.y2 - seg.y1 * seg.x2)) / denominator; - output.y = ((line.x1 * line.y2 - line.y1 * line.x2) * (seg.y1 - seg.y2) - (line.y1 - line.y2) * (seg.x1 * seg.y2 - seg.y1 * seg.x2)) / denominator; - var maxX = Math.max(seg.x1, seg.x2); - var minX = Math.min(seg.x1, seg.x2); - var maxY = Math.max(seg.y1, seg.y2); - var minY = Math.min(seg.y1, seg.y2); - if((output.x <= maxX && output.x >= minX) === true || (output.y <= maxY && output.y >= minY) === true) { - output.result = true; - } - } - return output; - }; - Collision.lineToRawSegment = /** - * Checks for Line to Raw Line Segment intersection and returns the result in the IntersectResult object. - * @param line The Line object to check - * @param x1 The start x coordinate of the raw segment - * @param y1 The start y coordinate of the raw segment - * @param x2 The end x coordinate of the raw segment - * @param y2 The end y coordinate of the raw segment - * @param [output] An optional IntersectResult object to store the intersection values in. One is created if none given. - * @returns {IntersectResult=} An IntersectResult object containing the results of the intersection - */ - function lineToRawSegment(line, x1, y1, x2, y2, output) { - if (typeof output === "undefined") { output = new Phaser.IntersectResult(); } - var denominator = (line.x1 - line.x2) * (y1 - y2) - (line.y1 - line.y2) * (x1 - x2); - if(denominator !== 0) { - output.x = ((line.x1 * line.y2 - line.y1 * line.x2) * (x1 - x2) - (line.x1 - line.x2) * (x1 * y2 - y1 * x2)) / denominator; - output.y = ((line.x1 * line.y2 - line.y1 * line.x2) * (y1 - y2) - (line.y1 - line.y2) * (x1 * y2 - y1 * x2)) / denominator; - var maxX = Math.max(x1, x2); - var minX = Math.min(x1, x2); - var maxY = Math.max(y1, y2); - var minY = Math.min(y1, y2); - if((output.x <= maxX && output.x >= minX) === true || (output.y <= maxY && output.y >= minY) === true) { - output.result = true; - } - } - return output; - }; - Collision.lineToRay = /** - * Checks for Line to Ray intersection and returns the result in an IntersectResult object. - * @param line1 The Line object to check - * @param ray The Ray object to check - * @param [output] An optional IntersectResult object to store the intersection values in. One is created if none given. - * @returns {IntersectResult=} An IntersectResult object containing the results of the intersection - */ - function lineToRay(line1, ray, output) { - if (typeof output === "undefined") { output = new Phaser.IntersectResult(); } - var denominator = (line1.x1 - line1.x2) * (ray.y1 - ray.y2) - (line1.y1 - line1.y2) * (ray.x1 - ray.x2); - if(denominator !== 0) { - output.x = ((line1.x1 * line1.y2 - line1.y1 * line1.x2) * (ray.x1 - ray.x2) - (line1.x1 - line1.x2) * (ray.x1 * ray.y2 - ray.y1 * ray.x2)) / denominator; - output.y = ((line1.x1 * line1.y2 - line1.y1 * line1.x2) * (ray.y1 - ray.y2) - (line1.y1 - line1.y2) * (ray.x1 * ray.y2 - ray.y1 * ray.x2)) / denominator; - output.result = true// true unless either of the 2 following conditions are met - ; - if(!(ray.x1 >= ray.x2) && output.x < ray.x1) { - output.result = false; - } - if(!(ray.y1 >= ray.y2) && output.y < ray.y1) { - output.result = false; - } - } - return output; - }; - Collision.lineToCircle = /** - * Check if the Line and Circle objects intersect - * @param line The Line object to check - * @param circle The Circle object to check - * @param [output] An optional IntersectResult object to store the intersection values in. One is created if none given. - * @returns {IntersectResult=} An IntersectResult object containing the results of the intersection - */ - function lineToCircle(line, circle, output) { - if (typeof output === "undefined") { output = new Phaser.IntersectResult(); } - // Get a perpendicular line running to the center of the circle - if(line.perp(circle.x, circle.y).length <= circle.radius) { - output.result = true; - } - return output; - }; - Collision.lineToRectangle = /** - * Check if the Line intersects each side of the Rectangle - * @param line The Line object to check - * @param rect The Rectangle object to check - * @param [output] An optional IntersectResult object to store the intersection values in. One is created if none given. - * @returns {IntersectResult=} An IntersectResult object containing the results of the intersection - */ - function lineToRectangle(line, rect, output) { - if (typeof output === "undefined") { output = new Phaser.IntersectResult(); } - // Top of the Rectangle vs the Line - Collision.lineToRawSegment(line, rect.x, rect.y, rect.right, rect.y, output); - if(output.result === true) { - return output; - } - // Left of the Rectangle vs the Line - Collision.lineToRawSegment(line, rect.x, rect.y, rect.x, rect.bottom, output); - if(output.result === true) { - return output; - } - // Bottom of the Rectangle vs the Line - Collision.lineToRawSegment(line, rect.x, rect.bottom, rect.right, rect.bottom, output); - if(output.result === true) { - return output; - } - // Right of the Rectangle vs the Line - Collision.lineToRawSegment(line, rect.right, rect.y, rect.right, rect.bottom, output); - return output; - }; - Collision.lineSegmentToLineSegment = /** - * Check if the two Line Segments intersect and returns the result in an IntersectResult object. - * @param line1 The first Line Segment to check - * @param line2 The second Line Segment to check - * @param [output] An optional IntersectResult object to store the intersection values in. One is created if none given. - * @returns {IntersectResult=} An IntersectResult object containing the results of the intersection - */ - function lineSegmentToLineSegment(line1, line2, output) { - if (typeof output === "undefined") { output = new Phaser.IntersectResult(); } - Collision.lineToLineSegment(line1, line2); - if(output.result === true) { - if(!(output.x >= Math.min(line1.x1, line1.x2) && output.x <= Math.max(line1.x1, line1.x2) && output.y >= Math.min(line1.y1, line1.y2) && output.y <= Math.max(line1.y1, line1.y2))) { - output.result = false; - } - } - return output; - }; - Collision.lineSegmentToRay = /** - * Check if the Line Segment intersects with the Ray and returns the result in an IntersectResult object. - * @param line The Line Segment to check. - * @param ray The Ray to check. - * @param [output] An optional IntersectResult object to store the intersection values in. One is created if none given. - * @returns {IntersectResult=} An IntersectResult object containing the results of the intersection - */ - function lineSegmentToRay(line, ray, output) { - if (typeof output === "undefined") { output = new Phaser.IntersectResult(); } - Collision.lineToRay(line, ray, output); - if(output.result === true) { - if(!(output.x >= Math.min(line.x1, line.x2) && output.x <= Math.max(line.x1, line.x2) && output.y >= Math.min(line.y1, line.y2) && output.y <= Math.max(line.y1, line.y2))) { - output.result = false; - } - } - return output; - }; - Collision.lineSegmentToCircle = /** - * Check if the Line Segment intersects with the Circle and returns the result in an IntersectResult object. - * @param seg The Line Segment to check. - * @param circle The Circle to check - * @param [output] An optional IntersectResult object to store the intersection values in. One is created if none given. - * @returns {IntersectResult=} An IntersectResult object containing the results of the intersection - */ - function lineSegmentToCircle(seg, circle, output) { - if (typeof output === "undefined") { output = new Phaser.IntersectResult(); } - var perp = seg.perp(circle.x, circle.y); - if(perp.length <= circle.radius) { - // Line intersects circle - check if segment does - var maxX = Math.max(seg.x1, seg.x2); - var minX = Math.min(seg.x1, seg.x2); - var maxY = Math.max(seg.y1, seg.y2); - var minY = Math.min(seg.y1, seg.y2); - if((perp.x2 <= maxX && perp.x2 >= minX) && (perp.y2 <= maxY && perp.y2 >= minY)) { - output.result = true; - } else { - // Worst case - segment doesn't traverse center, so no perpendicular connection. - if(Collision.circleContainsPoint(circle, { - x: seg.x1, - y: seg.y1 - }) || Collision.circleContainsPoint(circle, { - x: seg.x2, - y: seg.y2 - })) { - output.result = true; - } - } - } - return output; - }; - Collision.lineSegmentToRectangle = /** - * Check if the Line Segment intersects with the Rectangle and returns the result in an IntersectResult object. - * @param seg The Line Segment to check. - * @param rect The Rectangle to check. - * @param [output] An optional IntersectResult object to store the intersection values in. One is created if none given. - * @returns {IntersectResult=} An IntersectResult object containing the results of the intersection - */ - function lineSegmentToRectangle(seg, rect, output) { - if (typeof output === "undefined") { output = new Phaser.IntersectResult(); } - if(rect.contains(seg.x1, seg.y1) && rect.contains(seg.x2, seg.y2)) { - output.result = true; - } else { - // Top of the Rectangle vs the Line - Collision.lineToRawSegment(seg, rect.x, rect.y, rect.right, rect.bottom, output); - if(output.result === true) { - return output; - } - // Left of the Rectangle vs the Line - Collision.lineToRawSegment(seg, rect.x, rect.y, rect.x, rect.bottom, output); - if(output.result === true) { - return output; - } - // Bottom of the Rectangle vs the Line - Collision.lineToRawSegment(seg, rect.x, rect.bottom, rect.right, rect.bottom, output); - if(output.result === true) { - return output; - } - // Right of the Rectangle vs the Line - Collision.lineToRawSegment(seg, rect.right, rect.y, rect.right, rect.bottom, output); - return output; - } - return output; - }; - Collision.rayToRectangle = /** - * Check for Ray to Rectangle intersection and returns the result in an IntersectResult object. - * @param ray The Ray to check. - * @param rect The Rectangle to check. - * @param [output] An optional IntersectResult object to store the intersection values in. One is created if none given. - * @returns {IntersectResult=} An IntersectResult object containing the results of the intersection - */ - function rayToRectangle(ray, rect, output) { - if (typeof output === "undefined") { output = new Phaser.IntersectResult(); } - // Currently just finds first intersection - might not be closest to ray pt1 - Collision.lineToRectangle(ray, rect, output); - return output; - }; - Collision.rayToLineSegment = /** - * Check whether a Ray intersects a Line segment and returns the parametric value where the intersection occurs in an IntersectResult object. - * @param rayX1 - * @param rayY1 - * @param rayX2 - * @param rayY2 - * @param lineX1 - * @param lineY1 - * @param lineX2 - * @param lineY2 - * @param [output] An optional IntersectResult object to store the intersection values in. One is created if none given. - * @returns {IntersectResult=} An IntersectResult object containing the results of the intersection - */ - function rayToLineSegment(rayX1, rayY1, rayX2, rayY2, lineX1, lineY1, lineX2, lineY2, output) { - if (typeof output === "undefined") { output = new Phaser.IntersectResult(); } - var r; - var s; - var d; - // Check lines are not parallel - if((rayY2 - rayY1) / (rayX2 - rayX1) != (lineY2 - lineY1) / (lineX2 - lineX1)) { - d = (((rayX2 - rayX1) * (lineY2 - lineY1)) - (rayY2 - rayY1) * (lineX2 - lineX1)); - if(d != 0) { - r = (((rayY1 - lineY1) * (lineX2 - lineX1)) - (rayX1 - lineX1) * (lineY2 - lineY1)) / d; - s = (((rayY1 - lineY1) * (rayX2 - rayX1)) - (rayX1 - lineX1) * (rayY2 - rayY1)) / d; - if(r >= 0) { - if(s >= 0 && s <= 1) { - output.result = true; - output.x = rayX1 + r * (rayX2 - rayX1); - output.y = rayY1 + r * (rayY2 - rayY1); - } - } - } - } - return output; - }; - Collision.pointToRectangle = /** - * Determines whether the specified point is contained within the rectangular region defined by the Rectangle object and returns the result in an IntersectResult object. - * @param point The Point or MicroPoint object to check, or any object with x and y properties. - * @param rect The Rectangle object to check the point against - * @param [output] An optional IntersectResult object to store the intersection values in. One is created if none given. - * @returns {IntersectResult=} An IntersectResult object containing the results of the intersection - */ - function pointToRectangle(point, rect, output) { - if (typeof output === "undefined") { output = new Phaser.IntersectResult(); } - output.setTo(point.x, point.y); - output.result = rect.containsPoint(point); - return output; - }; - Collision.rectangleToRectangle = /** - * Check whether two axis aligned Rectangles intersect and returns the intersecting rectangle dimensions in an IntersectResult object if they do. - * @param rect1 The first Rectangle object. - * @param rect2 The second Rectangle object. - * @param [output] An optional IntersectResult object to store the intersection values in. One is created if none given. - * @returns {IntersectResult=} An IntersectResult object containing the results of the intersection - */ - function rectangleToRectangle(rect1, rect2, output) { - if (typeof output === "undefined") { output = new Phaser.IntersectResult(); } - var leftX = Math.max(rect1.x, rect2.x); - var rightX = Math.min(rect1.right, rect2.right); - var topY = Math.max(rect1.y, rect2.y); - var bottomY = Math.min(rect1.bottom, rect2.bottom); - output.setTo(leftX, topY, rightX - leftX, bottomY - topY, rightX - leftX, bottomY - topY); - var cx = output.x + output.width * .5; - var cy = output.y + output.height * .5; - if((cx > rect1.x && cx < rect1.right) && (cy > rect1.y && cy < rect1.bottom)) { - output.result = true; - } - return output; - }; - Collision.rectangleToCircle = /** - * Checks if the Rectangle and Circle objects intersect and returns the result in an IntersectResult object. - * @param rect The Rectangle object to check - * @param circle The Circle object to check - * @param [output] An optional IntersectResult object to store the intersection values in. One is created if none given. - * @returns {IntersectResult=} An IntersectResult object containing the results of the intersection - */ - function rectangleToCircle(rect, circle, output) { - if (typeof output === "undefined") { output = new Phaser.IntersectResult(); } - return Collision.circleToRectangle(circle, rect, output); - }; - Collision.circleToCircle = /** - * Checks if the two Circle objects intersect and returns the result in an IntersectResult object. - * @param circle1 The first Circle object to check - * @param circle2 The second Circle object to check - * @param [output] An optional IntersectResult object to store the intersection values in. One is created if none given. - * @returns {IntersectResult=} An IntersectResult object containing the results of the intersection - */ - function circleToCircle(circle1, circle2, output) { - if (typeof output === "undefined") { output = new Phaser.IntersectResult(); } - output.result = ((circle1.radius + circle2.radius) * (circle1.radius + circle2.radius)) >= Collision.distanceSquared(circle1.x, circle1.y, circle2.x, circle2.y); - return output; - }; - Collision.circleToRectangle = /** - * Checks if the Circle object intersects with the Rectangle and returns the result in an IntersectResult object. - * @param circle The Circle object to check - * @param rect The Rectangle object to check - * @param [output] An optional IntersectResult object to store the intersection values in. One is created if none given. - * @returns {IntersectResult=} An IntersectResult object containing the results of the intersection - */ - function circleToRectangle(circle, rect, output) { - if (typeof output === "undefined") { output = new Phaser.IntersectResult(); } - var inflatedRect = rect.clone(); - inflatedRect.inflate(circle.radius, circle.radius); - output.result = inflatedRect.contains(circle.x, circle.y); - return output; - }; - Collision.circleContainsPoint = /** - * Checks if the Point object is contained within the Circle and returns the result in an IntersectResult object. - * @param circle The Circle object to check - * @param point A Point or MicroPoint object to check, or any object with x and y properties - * @param [output] An optional IntersectResult object to store the intersection values in. One is created if none given. - * @returns {IntersectResult=} An IntersectResult object containing the results of the intersection - */ - function circleContainsPoint(circle, point, output) { - if (typeof output === "undefined") { output = new Phaser.IntersectResult(); } - output.result = circle.radius * circle.radius >= Collision.distanceSquared(circle.x, circle.y, point.x, point.y); - return output; - }; - Collision.prototype.overlap = /** - * Checks for overlaps between two objects using the world QuadTree. Can be GameObject vs. GameObject, GameObject vs. Group or Group vs. Group. - * Note: Does not take the objects scrollFactor into account. All overlaps are check in world space. - * @param object1 The first GameObject or Group to check. If null the world.group is used. - * @param object2 The second GameObject or Group to check. - * @param notifyCallback A callback function that is called if the objects overlap. The two objects will be passed to this function in the same order in which you passed them to Collision.overlap. - * @param processCallback A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then notifyCallback will only be called if processCallback returns true. - * @param context The context in which the callbacks will be called - * @returns {boolean} true if the objects overlap, otherwise false. - */ - function (object1, object2, notifyCallback, processCallback, context) { - if (typeof object1 === "undefined") { object1 = null; } - if (typeof object2 === "undefined") { object2 = null; } - if (typeof notifyCallback === "undefined") { notifyCallback = null; } - if (typeof processCallback === "undefined") { processCallback = null; } - if (typeof context === "undefined") { context = null; } - if(object1 == null) { - object1 = this._game.world.group; - } - if(object2 == object1) { - object2 = null; - } - Phaser.QuadTree.divisions = this._game.world.worldDivisions; - var quadTree = new Phaser.QuadTree(this._game.world.bounds.x, this._game.world.bounds.y, this._game.world.bounds.width, this._game.world.bounds.height); - quadTree.load(object1, object2, notifyCallback, processCallback, context); - var result = quadTree.execute(); - quadTree.destroy(); - quadTree = null; - return result; - }; - Collision.separate = /** - * The core Collision separation function used by Collision.overlap. - * @param object1 The first GameObject to separate - * @param object2 The second GameObject to separate - * @returns {boolean} Returns true if the objects were separated, otherwise false. - */ - function separate(object1, object2) { - object1.collisionMask.update(); - object2.collisionMask.update(); - var separatedX = Collision.separateX(object1, object2); - var separatedY = Collision.separateY(object1, object2); - return separatedX || separatedY; - }; - Collision.separateTile = /** - * Collision resolution specifically for GameObjects vs. Tiles. - * @param object The GameObject to separate - * @param tile The Tile to separate - * @returns {boolean} Whether the objects in fact touched and were separated - */ - function separateTile(object, x, y, width, height, mass, collideLeft, collideRight, collideUp, collideDown, separateX, separateY) { - object.collisionMask.update(); - var separatedX = Collision.separateTileX(object, x, y, width, height, mass, collideLeft, collideRight, separateX); - var separatedY = Collision.separateTileY(object, x, y, width, height, mass, collideUp, collideDown, separateY); - return separatedX || separatedY; - }; - Collision.separateTileX = /** - * Separates the two objects on their x axis - * @param object The GameObject to separate - * @param tile The Tile to separate - * @returns {boolean} Whether the objects in fact touched and were separated along the X axis. - */ - function separateTileX(object, x, y, width, height, mass, collideLeft, collideRight, separate) { - // Can't separate two immovable objects (tiles are always immovable) - if(object.immovable) { - return false; - } - // First, get the object delta - var overlap = 0; - var objDelta = object.x - object.last.x; - //var objDelta: number = object.collisionMask.deltaX; - if(objDelta != 0) { - // Check if the X hulls actually overlap - var objDeltaAbs = (objDelta > 0) ? objDelta : -objDelta; - //var objDeltaAbs: number = object.collisionMask.deltaXAbs; - var objBounds = new Phaser.Quad(object.x - ((objDelta > 0) ? objDelta : 0), object.last.y, object.width + ((objDelta > 0) ? objDelta : -objDelta), object.height); - if((objBounds.x + objBounds.width > x) && (objBounds.x < x + width) && (objBounds.y + objBounds.height > y) && (objBounds.y < y + height)) { - var maxOverlap = objDeltaAbs + Collision.OVERLAP_BIAS; - // If they did overlap (and can), figure out by how much and flip the corresponding flags - if(objDelta > 0) { - overlap = object.x + object.width - x; - if((overlap > maxOverlap) || !(object.allowCollisions & Collision.RIGHT) || collideLeft == false) { - overlap = 0; - } else { - object.touching |= Collision.RIGHT; - } - } else if(objDelta < 0) { - overlap = object.x - width - x; - if((-overlap > maxOverlap) || !(object.allowCollisions & Collision.LEFT) || collideRight == false) { - overlap = 0; - } else { - object.touching |= Collision.LEFT; - } - } - } - } - // Then adjust their positions and velocities accordingly (if there was any overlap) - if(overlap != 0) { - if(separate == true) { - //console.log(' - object.x = object.x - overlap; - object.velocity.x = -(object.velocity.x * object.elasticity); - } - Collision.TILE_OVERLAP = true; - return true; - } else { - return false; - } - }; - Collision.separateTileY = /** - * Separates the two objects on their y axis - * @param object The first GameObject to separate - * @param tile The second GameObject to separate - * @returns {boolean} Whether the objects in fact touched and were separated along the Y axis. - */ - function separateTileY(object, x, y, width, height, mass, collideUp, collideDown, separate) { - // Can't separate two immovable objects (tiles are always immovable) - if(object.immovable) { - return false; - } - // First, get the two object deltas - var overlap = 0; - var objDelta = object.y - object.last.y; - if(objDelta != 0) { - // Check if the Y hulls actually overlap - var objDeltaAbs = (objDelta > 0) ? objDelta : -objDelta; - var objBounds = new Phaser.Quad(object.x, object.y - ((objDelta > 0) ? objDelta : 0), object.width, object.height + objDeltaAbs); - if((objBounds.x + objBounds.width > x) && (objBounds.x < x + width) && (objBounds.y + objBounds.height > y) && (objBounds.y < y + height)) { - var maxOverlap = objDeltaAbs + Collision.OVERLAP_BIAS; - // If they did overlap (and can), figure out by how much and flip the corresponding flags - if(objDelta > 0) { - overlap = object.y + object.height - y; - if((overlap > maxOverlap) || !(object.allowCollisions & Collision.DOWN) || collideUp == false) { - overlap = 0; - } else { - object.touching |= Collision.DOWN; - } - } else if(objDelta < 0) { - overlap = object.y - height - y; - if((-overlap > maxOverlap) || !(object.allowCollisions & Collision.UP) || collideDown == false) { - overlap = 0; - } else { - object.touching |= Collision.UP; - } - } - } - } - // TODO - with super low velocities you get lots of stuttering, set some kind of base minimum here - // Then adjust their positions and velocities accordingly (if there was any overlap) - if(overlap != 0) { - if(separate == true) { - object.y = object.y - overlap; - object.velocity.y = -(object.velocity.y * object.elasticity); - } - Collision.TILE_OVERLAP = true; - return true; - } else { - return false; - } - }; - Collision.NEWseparateTileX = /** - * Separates the two objects on their x axis - * @param object The GameObject to separate - * @param tile The Tile to separate - * @returns {boolean} Whether the objects in fact touched and were separated along the X axis. - */ - function NEWseparateTileX(object, x, y, width, height, mass, collideLeft, collideRight, separate) { - // Can't separate two immovable objects (tiles are always immovable) - if(object.immovable) { - return false; - } - // First, get the object delta - var overlap = 0; - if(object.collisionMask.deltaX != 0) { - // Check if the X hulls actually overlap - //var objDeltaAbs: number = (objDelta > 0) ? objDelta : -objDelta; - //var objBounds: Quad = new Quad(object.x - ((objDelta > 0) ? objDelta : 0), object.last.y, object.width + ((objDelta > 0) ? objDelta : -objDelta), object.height); - //if ((objBounds.x + objBounds.width > x) && (objBounds.x < x + width) && (objBounds.y + objBounds.height > y) && (objBounds.y < y + height)) - if(object.collisionMask.intersectsRaw(x, x + width, y, y + height)) { - var maxOverlap = object.collisionMask.deltaXAbs + Collision.OVERLAP_BIAS; - // If they did overlap (and can), figure out by how much and flip the corresponding flags - if(object.collisionMask.deltaX > 0) { - //overlap = object.x + object.width - x; - overlap = object.collisionMask.right - x; - if((overlap > maxOverlap) || !(object.allowCollisions & Collision.RIGHT) || collideLeft == false) { - overlap = 0; - } else { - object.touching |= Collision.RIGHT; - } - } else if(object.collisionMask.deltaX < 0) { - //overlap = object.x - width - x; - overlap = object.collisionMask.x - width - x; - if((-overlap > maxOverlap) || !(object.allowCollisions & Collision.LEFT) || collideRight == false) { - overlap = 0; - } else { - object.touching |= Collision.LEFT; - } - } - } - } - // Then adjust their positions and velocities accordingly (if there was any overlap) - if(overlap != 0) { - if(separate == true) { - object.x = object.x - overlap; - object.velocity.x = -(object.velocity.x * object.elasticity); - } - Collision.TILE_OVERLAP = true; - return true; - } else { - return false; - } - }; - Collision.NEWseparateTileY = /** - * Separates the two objects on their y axis - * @param object The first GameObject to separate - * @param tile The second GameObject to separate - * @returns {boolean} Whether the objects in fact touched and were separated along the Y axis. - */ - function NEWseparateTileY(object, x, y, width, height, mass, collideUp, collideDown, separate) { - // Can't separate two immovable objects (tiles are always immovable) - if(object.immovable) { - return false; - } - // First, get the two object deltas - var overlap = 0; - //var objDelta: number = object.y - object.last.y; - if(object.collisionMask.deltaY != 0) { - // Check if the Y hulls actually overlap - //var objDeltaAbs: number = (objDelta > 0) ? objDelta : -objDelta; - //var objBounds: Quad = new Quad(object.x, object.y - ((objDelta > 0) ? objDelta : 0), object.width, object.height + objDeltaAbs); - //if ((objBounds.x + objBounds.width > x) && (objBounds.x < x + width) && (objBounds.y + objBounds.height > y) && (objBounds.y < y + height)) - if(object.collisionMask.intersectsRaw(x, x + width, y, y + height)) { - //var maxOverlap: number = objDeltaAbs + Collision.OVERLAP_BIAS; - var maxOverlap = object.collisionMask.deltaYAbs + Collision.OVERLAP_BIAS; - // If they did overlap (and can), figure out by how much and flip the corresponding flags - if(object.collisionMask.deltaY > 0) { - //overlap = object.y + object.height - y; - overlap = object.collisionMask.bottom - y; - if((overlap > maxOverlap) || !(object.allowCollisions & Collision.DOWN) || collideUp == false) { - overlap = 0; - } else { - object.touching |= Collision.DOWN; - } - } else if(object.collisionMask.deltaY < 0) { - //overlap = object.y - height - y; - overlap = object.collisionMask.y - height - y; - if((-overlap > maxOverlap) || !(object.allowCollisions & Collision.UP) || collideDown == false) { - overlap = 0; - } else { - object.touching |= Collision.UP; - } - } - } - } - // TODO - with super low velocities you get lots of stuttering, set some kind of base minimum here - // Then adjust their positions and velocities accordingly (if there was any overlap) - if(overlap != 0) { - if(separate == true) { - object.y = object.y - overlap; - object.velocity.y = -(object.velocity.y * object.elasticity); - } - Collision.TILE_OVERLAP = true; - return true; - } else { - return false; - } - }; - Collision.separateX = /** - * Separates the two objects on their x axis - * @param object1 The first GameObject to separate - * @param object2 The second GameObject to separate - * @returns {boolean} Whether the objects in fact touched and were separated along the X axis. - */ - function separateX(object1, object2) { - // Can't separate two immovable objects - if(object1.immovable && object2.immovable) { - return false; - } - // First, get the two object deltas - var overlap = 0; - if(object1.collisionMask.deltaX != object2.collisionMask.deltaX) { - if(object1.collisionMask.intersects(object2.collisionMask)) { - var maxOverlap = object1.collisionMask.deltaXAbs + object2.collisionMask.deltaXAbs + Collision.OVERLAP_BIAS; - // If they did overlap (and can), figure out by how much and flip the corresponding flags - if(object1.collisionMask.deltaX > object2.collisionMask.deltaX) { - overlap = object1.collisionMask.right - object2.collisionMask.x; - if((overlap > maxOverlap) || !(object1.allowCollisions & Collision.RIGHT) || !(object2.allowCollisions & Collision.LEFT)) { - overlap = 0; - } else { - object1.touching |= Collision.RIGHT; - object2.touching |= Collision.LEFT; - } - } else if(object1.collisionMask.deltaX < object2.collisionMask.deltaX) { - overlap = object1.collisionMask.x - object2.collisionMask.width - object2.collisionMask.x; - if((-overlap > maxOverlap) || !(object1.allowCollisions & Collision.LEFT) || !(object2.allowCollisions & Collision.RIGHT)) { - overlap = 0; - } else { - object1.touching |= Collision.LEFT; - object2.touching |= Collision.RIGHT; - } - } - } - } - // Then adjust their positions and velocities accordingly (if there was any overlap) - if(overlap != 0) { - var obj1Velocity = object1.velocity.x; - var obj2Velocity = object2.velocity.x; - if(!object1.immovable && !object2.immovable) { - overlap *= 0.5; - object1.x = object1.x - overlap; - object2.x += overlap; - var obj1NewVelocity = Math.sqrt((obj2Velocity * obj2Velocity * object2.mass) / object1.mass) * ((obj2Velocity > 0) ? 1 : -1); - var obj2NewVelocity = Math.sqrt((obj1Velocity * obj1Velocity * object1.mass) / object2.mass) * ((obj1Velocity > 0) ? 1 : -1); - var average = (obj1NewVelocity + obj2NewVelocity) * 0.5; - obj1NewVelocity -= average; - obj2NewVelocity -= average; - object1.velocity.x = average + obj1NewVelocity * object1.elasticity; - object2.velocity.x = average + obj2NewVelocity * object2.elasticity; - } else if(!object1.immovable) { - object1.x = object1.x - overlap; - object1.velocity.x = obj2Velocity - obj1Velocity * object1.elasticity; - } else if(!object2.immovable) { - object2.x += overlap; - object2.velocity.x = obj1Velocity - obj2Velocity * object2.elasticity; - } - return true; - } else { - return false; - } - }; - Collision.separateY = /** - * Separates the two objects on their y axis - * @param object1 The first GameObject to separate - * @param object2 The second GameObject to separate - * @returns {boolean} Whether the objects in fact touched and were separated along the Y axis. - */ - function separateY(object1, object2) { - // Can't separate two immovable objects - if(object1.immovable && object2.immovable) { - return false; - } - // First, get the two object deltas - var overlap = 0; - if(object1.collisionMask.deltaY != object2.collisionMask.deltaY) { - if(object1.collisionMask.intersects(object2.collisionMask)) { - // This is the only place to use the DeltaAbs values - var maxOverlap = object1.collisionMask.deltaYAbs + object2.collisionMask.deltaYAbs + Collision.OVERLAP_BIAS; - // If they did overlap (and can), figure out by how much and flip the corresponding flags - if(object1.collisionMask.deltaY > object2.collisionMask.deltaY) { - overlap = object1.collisionMask.bottom - object2.collisionMask.y; - if((overlap > maxOverlap) || !(object1.allowCollisions & Collision.DOWN) || !(object2.allowCollisions & Collision.UP)) { - overlap = 0; - } else { - object1.touching |= Collision.DOWN; - object2.touching |= Collision.UP; - } - } else if(object1.collisionMask.deltaY < object2.collisionMask.deltaY) { - overlap = object1.collisionMask.y - object2.collisionMask.height - object2.collisionMask.y; - if((-overlap > maxOverlap) || !(object1.allowCollisions & Collision.UP) || !(object2.allowCollisions & Collision.DOWN)) { - overlap = 0; - } else { - object1.touching |= Collision.UP; - object2.touching |= Collision.DOWN; - } - } - } - } - // Then adjust their positions and velocities accordingly (if there was any overlap) - if(overlap != 0) { - var obj1Velocity = object1.velocity.y; - var obj2Velocity = object2.velocity.y; - if(!object1.immovable && !object2.immovable) { - overlap *= 0.5; - object1.y = object1.y - overlap; - object2.y += overlap; - var obj1NewVelocity = Math.sqrt((obj2Velocity * obj2Velocity * object2.mass) / object1.mass) * ((obj2Velocity > 0) ? 1 : -1); - var obj2NewVelocity = Math.sqrt((obj1Velocity * obj1Velocity * object1.mass) / object2.mass) * ((obj1Velocity > 0) ? 1 : -1); - var average = (obj1NewVelocity + obj2NewVelocity) * 0.5; - obj1NewVelocity -= average; - obj2NewVelocity -= average; - object1.velocity.y = average + obj1NewVelocity * object1.elasticity; - object2.velocity.y = average + obj2NewVelocity * object2.elasticity; - } else if(!object1.immovable) { - object1.y = object1.y - overlap; - object1.velocity.y = obj2Velocity - obj1Velocity * object1.elasticity; - // This is special case code that handles things like horizontal moving platforms you can ride - if(object2.active && object2.moves && (object1.collisionMask.deltaY > object2.collisionMask.deltaY)) { - object1.x += object2.x - object2.last.x; - } - } else if(!object2.immovable) { - object2.y += overlap; - object2.velocity.y = obj1Velocity - obj2Velocity * object2.elasticity; - // This is special case code that handles things like horizontal moving platforms you can ride - if(object1.active && object1.moves && (object1.collisionMask.deltaY < object2.collisionMask.deltaY)) { - object2.x += object1.x - object1.last.x; - } - } - return true; - } else { - return false; - } - }; - Collision.distance = /** - * Returns the distance between the two given coordinates. - * @param x1 The X value of the first coordinate - * @param y1 The Y value of the first coordinate - * @param x2 The X value of the second coordinate - * @param y2 The Y value of the second coordinate - * @returns {number} The distance between the two coordinates - */ - function distance(x1, y1, x2, y2) { - return Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1)); - }; - Collision.distanceSquared = /** - * Returns the distanced squared between the two given coordinates. - * @param x1 The X value of the first coordinate - * @param y1 The Y value of the first coordinate - * @param x2 The X value of the second coordinate - * @param y2 The Y value of the second coordinate - * @returns {number} The distance between the two coordinates - */ - function distanceSquared(x1, y1, x2, y2) { - return (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1); - }; - Collision.flattenPointsOn = // SAT - /** - * Flattens the specified array of points onto a unit vector axis, - * resulting in a one dimensional range of the minimum and - * maximum value on that axis. - * - * @param {Array.} points The points to flatten. - * @param {Vector} normal The unit vector axis to flatten on. - * @param {Array.} result An array. After calling this function, - * result[0] will be the minimum value, - * result[1] will be the maximum value. - */ - function flattenPointsOn(points, normal, result) { - var min = Number.MAX_VALUE; - var max = -Number.MAX_VALUE; - var len = points.length; - for(var i = 0; i < len; i++) { - // Get the magnitude of the projection of the point onto the normal - var dot = points[i].dot(normal); - if(dot < min) { - min = dot; - } - if(dot > max) { - max = dot; - } - } - result[0] = min; - result[1] = max; - }; - Collision.isSeparatingAxis = /** - * Check whether two convex clockwise polygons are separated by the specified - * axis (must be a unit vector). - * - * @param {Vector} aPos The position of the first polygon. - * @param {Vector} bPos The position of the second polygon. - * @param {Array.} aPoints The points in the first polygon. - * @param {Array.} bPoints The points in the second polygon. - * @param {Vector} axis The axis (unit sized) to test against. The points of both polygons - * will be projected onto this axis. - * @param {Response=} response A Response object (optional) which will be populated - * if the axis is not a separating axis. - * @return {boolean} true if it is a separating axis, false otherwise. If false, - * and a response is passed in, information about how much overlap and - * the direction of the overlap will be populated. - */ - function isSeparatingAxis(aPos, bPos, aPoints, bPoints, axis, response) { - if (typeof response === "undefined") { response = null; } - var rangeA = Collision.T_ARRAYS.pop(); - var rangeB = Collision.T_ARRAYS.pop(); - // Get the magnitude of the offset between the two polygons - var offsetV = Collision.T_VECTORS.pop().copyFrom(bPos).sub(aPos); - var projectedOffset = offsetV.dot(axis); - // Project the polygons onto the axis. - Collision.flattenPointsOn(aPoints, axis, rangeA); - Collision.flattenPointsOn(bPoints, axis, rangeB); - // Move B's range to its position relative to A. - rangeB[0] += projectedOffset; - rangeB[1] += projectedOffset; - // Check if there is a gap. If there is, this is a separating axis and we can stop - if(rangeA[0] > rangeB[1] || rangeB[0] > rangeA[1]) { - Collision.T_VECTORS.push(offsetV); - Collision.T_ARRAYS.push(rangeA); - Collision.T_ARRAYS.push(rangeB); - return true; - } - // If we're calculating a response, calculate the overlap. - if(response) { - var overlap = 0; - // A starts further left than B - if(rangeA[0] < rangeB[0]) { - response.aInB = false; - // A ends before B does. We have to pull A out of B - if(rangeA[1] < rangeB[1]) { - overlap = rangeA[1] - rangeB[0]; - response.bInA = false; - // B is fully inside A. Pick the shortest way out. - } else { - var option1 = rangeA[1] - rangeB[0]; - var option2 = rangeB[1] - rangeA[0]; - overlap = option1 < option2 ? option1 : -option2; - } - // B starts further left than A - } else { - response.bInA = false; - // B ends before A ends. We have to push A out of B - if(rangeA[1] > rangeB[1]) { - overlap = rangeA[0] - rangeB[1]; - response.aInB = false; - // A is fully inside B. Pick the shortest way out. - } else { - var option1 = rangeA[1] - rangeB[0]; - var option2 = rangeB[1] - rangeA[0]; - overlap = option1 < option2 ? option1 : -option2; - } - } - // If this is the smallest amount of overlap we've seen so far, set it as the minimum overlap. - var absOverlap = Math.abs(overlap); - if(absOverlap < response.overlap) { - response.overlap = absOverlap; - response.overlapN.copyFrom(axis); - if(overlap < 0) { - response.overlapN.reverse(); - } - } - } - Collision.T_VECTORS.push(offsetV); - Collision.T_ARRAYS.push(rangeA); - Collision.T_ARRAYS.push(rangeB); - return false; - }; - Collision.LEFT_VORNOI_REGION = -1; - Collision.MIDDLE_VORNOI_REGION = 0; - Collision.RIGHT_VORNOI_REGION = 1; - Collision.vornoiRegion = /** - * Calculates which Vornoi region a point is on a line segment. - * It is assumed that both the line and the point are relative to (0, 0) - * - * | (0) | - * (-1) [0]--------------[1] (1) - * | (0) | - * - * @param {Vector} line The line segment. - * @param {Vector} point The point. - * @return {number} LEFT_VORNOI_REGION (-1) if it is the left region, - * MIDDLE_VORNOI_REGION (0) if it is the middle region, - * RIGHT_VORNOI_REGION (1) if it is the right region. - */ - function vornoiRegion(line, point) { - var len2 = line.length2(); - var dp = point.dot(line); - if(dp < 0) { - return Collision.LEFT_VORNOI_REGION; - } else if(dp > len2) { - return Collision.RIGHT_VORNOI_REGION; - } else { - return Collision.MIDDLE_VORNOI_REGION; - } - }; - Collision.testCircleCircle = /** - * Check if two circles intersect. - * - * @param {Circle} a The first circle. - * @param {Circle} b The second circle. - * @param {Response=} response Response object (optional) that will be populated if - * the circles intersect. - * @return {boolean} true if the circles intersect, false if they don't. - */ - function testCircleCircle(a, b, response) { - if (typeof response === "undefined") { response = null; } - var differenceV = Collision.T_VECTORS.pop().copyFrom(b.pos).sub(a.pos); - var totalRadius = a.radius + b.radius; - var totalRadiusSq = totalRadius * totalRadius; - var distanceSq = differenceV.length2(); - if(distanceSq > totalRadiusSq) { - // They do not intersect - Collision.T_VECTORS.push(differenceV); - return false; - } - // They intersect. If we're calculating a response, calculate the overlap. - if(response) { - var dist = Math.sqrt(distanceSq); - response.a = a; - response.b = b; - response.overlap = totalRadius - dist; - response.overlapN.copyFrom(differenceV.normalize()); - response.overlapV.copyFrom(differenceV).scale(response.overlap); - response.aInB = a.radius <= b.radius && dist <= b.radius - a.radius; - response.bInA = b.radius <= a.radius && dist <= a.radius - b.radius; - } - Collision.T_VECTORS.push(differenceV); - return true; - }; - Collision.testPolygonCircle = /** - * Check if a polygon and a circle intersect. - * - * @param {Polygon} polygon The polygon. - * @param {Circle} circle The circle. - * @param {Response=} response Response object (optional) that will be populated if - * they interset. - * @return {boolean} true if they intersect, false if they don't. - */ - function testPolygonCircle(polygon, circle, response) { - if (typeof response === "undefined") { response = null; } - var circlePos = Collision.T_VECTORS.pop().copyFrom(circle.pos).sub(polygon.pos); - var radius = circle.radius; - var radius2 = radius * radius; - var points = polygon.points; - var len = points.length; - var edge = Collision.T_VECTORS.pop(); - var point = Collision.T_VECTORS.pop(); - // For each edge in the polygon - for(var i = 0; i < len; i++) { - var next = i === len - 1 ? 0 : i + 1; - var prev = i === 0 ? len - 1 : i - 1; - var overlap = 0; - var overlapN = null; - // Get the edge - edge.copyFrom(polygon.edges[i]); - // Calculate the center of the cirble relative to the starting point of the edge - point.copyFrom(circlePos).sub(points[i]); - // If the distance between the center of the circle and the point - // is bigger than the radius, the polygon is definitely not fully in - // the circle. - if(response && point.length2() > radius2) { - response.aInB = false; - } - // Calculate which Vornoi region the center of the circle is in. - var region = Collision.vornoiRegion(edge, point); - if(region === Collision.LEFT_VORNOI_REGION) { - // Need to make sure we're in the RIGHT_VORNOI_REGION of the previous edge. - edge.copyFrom(polygon.edges[prev]); - // Calculate the center of the circle relative the starting point of the previous edge - var point2 = Collision.T_VECTORS.pop().copyFrom(circlePos).sub(points[prev]); - region = Collision.vornoiRegion(edge, point2); - if(region === Collision.RIGHT_VORNOI_REGION) { - // It's in the region we want. Check if the circle intersects the point. - var dist = point.length2(); - if(dist > radius) { - // No intersection - Collision.T_VECTORS.push(circlePos); - Collision.T_VECTORS.push(edge); - Collision.T_VECTORS.push(point); - Collision.T_VECTORS.push(point2); - return false; - } else if(response) { - // It intersects, calculate the overlap - response.bInA = false; - overlapN = point.normalize(); - overlap = radius - dist; - } - } - Collision.T_VECTORS.push(point2); - } else if(region === Collision.RIGHT_VORNOI_REGION) { - // Need to make sure we're in the left region on the next edge - edge.copyFrom(polygon.edges[next]); - // Calculate the center of the circle relative to the starting point of the next edge - point.copyFrom(circlePos).sub(points[next]); - region = Collision.vornoiRegion(edge, point); - if(region === Collision.LEFT_VORNOI_REGION) { - // It's in the region we want. Check if the circle intersects the point. - var dist = point.length2(); - if(dist > radius) { - // No intersection - Collision.T_VECTORS.push(circlePos); - Collision.T_VECTORS.push(edge); - Collision.T_VECTORS.push(point); - return false; - } else if(response) { - // It intersects, calculate the overlap - response.bInA = false; - overlapN = point.normalize(); - overlap = radius - dist; - } - } - // MIDDLE_VORNOI_REGION - } else { - // Need to check if the circle is intersecting the edge, - // Change the edge into its "edge normal". - var normal = edge.perp().normalize(); - // Find the perpendicular distance between the center of the - // circle and the edge. - var dist = point.dot(normal); - var distAbs = Math.abs(dist); - // If the circle is on the outside of the edge, there is no intersection - if(dist > 0 && distAbs > radius) { - Collision.T_VECTORS.push(circlePos); - Collision.T_VECTORS.push(normal); - Collision.T_VECTORS.push(point); - return false; - } else if(response) { - // It intersects, calculate the overlap. - overlapN = normal; - overlap = radius - dist; - // If the center of the circle is on the outside of the edge, or part of the - // circle is on the outside, the circle is not fully inside the polygon. - if(dist >= 0 || overlap < 2 * radius) { - response.bInA = false; - } - } - } - // If this is the smallest overlap we've seen, keep it. - // (overlapN may be null if the circle was in the wrong Vornoi region) - if(overlapN && response && Math.abs(overlap) < Math.abs(response.overlap)) { - response.overlap = overlap; - response.overlapN.copyFrom(overlapN); - } - } - // Calculate the final overlap vector - based on the smallest overlap. - if(response) { - response.a = polygon; - response.b = circle; - response.overlapV.copyFrom(response.overlapN).scale(response.overlap); - } - Collision.T_VECTORS.push(circlePos); - Collision.T_VECTORS.push(edge); - Collision.T_VECTORS.push(point); - return true; - }; - Collision.testCirclePolygon = /** - * Check if a circle and a polygon intersect. - * - * NOTE: This runs slightly slower than polygonCircle as it just - * runs polygonCircle and reverses everything at the end. - * - * @param {Circle} circle The circle. - * @param {Polygon} polygon The polygon. - * @param {Response=} response Response object (optional) that will be populated if - * they interset. - * @return {boolean} true if they intersect, false if they don't. - */ - function testCirclePolygon(circle, polygon, response) { - if (typeof response === "undefined") { response = null; } - var result = Collision.testPolygonCircle(polygon, circle, response); - if(result && response) { - // Swap A and B in the response. - var a = response.a; - var aInB = response.aInB; - response.overlapN.reverse(); - response.overlapV.reverse(); - response.a = response.b; - response.b = a; - response.aInB = response.bInA; - response.bInA = aInB; - } - return result; - }; - Collision.testPolygonPolygon = /** - * Checks whether two convex, clockwise polygons intersect. - * - * @param {Polygon} a The first polygon. - * @param {Polygon} b The second polygon. - * @param {Response=} response Response object (optional) that will be populated if - * they interset. - * @return {boolean} true if they intersect, false if they don't. - */ - function testPolygonPolygon(a, b, response) { - if (typeof response === "undefined") { response = null; } - var aPoints = a.points; - var aLen = aPoints.length; - var bPoints = b.points; - var bLen = bPoints.length; - // If any of the edge normals of A is a separating axis, no intersection. - for(var i = 0; i < aLen; i++) { - if(Collision.isSeparatingAxis(a.pos, b.pos, aPoints, bPoints, a.normals[i], response)) { - return false; - } - } - // If any of the edge normals of B is a separating axis, no intersection. - for(var i = 0; i < bLen; i++) { - if(Collision.isSeparatingAxis(a.pos, b.pos, aPoints, bPoints, b.normals[i], response)) { - return false; - } - } - // Since none of the edge normals of A or B are a separating axis, there is an intersection - // and we've already calculated the smallest overlap (in isSeparatingAxis). Calculate the - // final overlap vector. - if(response) { - response.a = a; - response.b = b; - response.overlapV.copyFrom(response.overlapN).scale(response.overlap); - } - return true; - }; - return Collision; - })(); - Phaser.Collision = Collision; -})(Phaser || (Phaser = {})); -/// -/** -* Phaser - DynamicTexture -* -* A DynamicTexture can be thought of as a mini canvas into which you can draw anything. -* Game Objects can be assigned a DynamicTexture, so when they render in the world they do so -* based on the contents of the texture at the time. This allows you to create powerful effects -* once and have them replicated across as many game objects as you like. -*/ -var Phaser; -(function (Phaser) { - var DynamicTexture = (function () { - /** - * DynamicTexture constructor - * Create a new DynamicTexture. - * - * @param game {Phaser.Game} Current game instance. - * @param width {number} Init width of this texture. - * @param height {number} Init height of this texture. - */ - function DynamicTexture(game, width, height) { - this._sx = 0; - this._sy = 0; - this._sw = 0; - this._sh = 0; - this._dx = 0; - this._dy = 0; - this._dw = 0; - this._dh = 0; - this._game = game; - this.canvas = document.createElement('canvas'); - this.canvas.width = width; - this.canvas.height = height; - this.context = this.canvas.getContext('2d'); - this.bounds = new Phaser.Rectangle(0, 0, width, height); - } - DynamicTexture.prototype.getPixel = /** - * Get a color of a specific pixel. - * @param x {number} X position of the pixel in this texture. - * @param y {number} Y position of the pixel in this texture. - * @return {number} A native color value integer (format: 0xRRGGBB) - */ - function (x, y) { - //r = imageData.data[0]; - //g = imageData.data[1]; - //b = imageData.data[2]; - //a = imageData.data[3]; - var imageData = this.context.getImageData(x, y, 1, 1); - return this.getColor(imageData.data[0], imageData.data[1], imageData.data[2]); - }; - DynamicTexture.prototype.getPixel32 = /** - * Get a color of a specific pixel (including alpha value). - * @param x {number} X position of the pixel in this texture. - * @param y {number} Y position of the pixel in this texture. - * @return A native color value integer (format: 0xAARRGGBB) - */ - function (x, y) { - var imageData = this.context.getImageData(x, y, 1, 1); - return this.getColor32(imageData.data[3], imageData.data[0], imageData.data[1], imageData.data[2]); - }; - DynamicTexture.prototype.getPixels = /** - * Get pixels in array in a specific rectangle. - * @param rect {Rectangle} The specific rectangle. - * @returns {array} CanvasPixelArray. - */ - function (rect) { - return this.context.getImageData(rect.x, rect.y, rect.width, rect.height); - }; - DynamicTexture.prototype.setPixel = /** - * Set color of a specific pixel. - * @param x {number} X position of the target pixel. - * @param y {number} Y position of the target pixel. - * @param color {number} Native integer with color value. (format: 0xRRGGBB) - */ - function (x, y, color) { - this.context.fillStyle = color; - this.context.fillRect(x, y, 1, 1); - }; - DynamicTexture.prototype.setPixel32 = /** - * Set color (with alpha) of a specific pixel. - * @param x {number} X position of the target pixel. - * @param y {number} Y position of the target pixel. - * @param color {number} Native integer with color value. (format: 0xAARRGGBB) - */ - function (x, y, color) { - this.context.fillStyle = color; - this.context.fillRect(x, y, 1, 1); - }; - DynamicTexture.prototype.setPixels = /** - * Set image data to a specific rectangle. - * @param rect {Rectangle} Target rectangle. - * @param input {object} Source image data. - */ - function (rect, input) { - this.context.putImageData(input, rect.x, rect.y); - }; - DynamicTexture.prototype.fillRect = /** - * Fill a given rectangle with specific color. - * @param rect {Rectangle} Target rectangle you want to fill. - * @param color {number} A native number with color value. (format: 0xRRGGBB) - */ - function (rect, color) { - this.context.fillStyle = color; - this.context.fillRect(rect.x, rect.y, rect.width, rect.height); - }; - DynamicTexture.prototype.pasteImage = /** - * - */ - function (key, frame, destX, destY, destWidth, destHeight) { - if (typeof frame === "undefined") { frame = -1; } - if (typeof destX === "undefined") { destX = 0; } - if (typeof destY === "undefined") { destY = 0; } - if (typeof destWidth === "undefined") { destWidth = null; } - if (typeof destHeight === "undefined") { destHeight = null; } - var texture = null; - var frameData; - this._sx = 0; - this._sy = 0; - this._dx = destX; - this._dy = destY; - // TODO - Load a frame from a sprite sheet, otherwise we'll draw the whole lot - if(frame > -1) { - //if (this._game.cache.isSpriteSheet(key)) - //{ - // texture = this._game.cache.getImage(key); - //this.animations.loadFrameData(this._game.cache.getFrameData(key)); - //} - } else { - texture = this._game.cache.getImage(key); - this._sw = texture.width; - this._sh = texture.height; - this._dw = texture.width; - this._dh = texture.height; - } - if(destWidth !== null) { - this._dw = destWidth; - } - if(destHeight !== null) { - this._dh = destHeight; - } - if(texture != null) { - this.context.drawImage(texture, // Source Image - this._sx, // Source X (location within the source image) - this._sy, // Source Y - this._sw, // Source Width - this._sh, // Source Height - this._dx, // Destination X (where on the canvas it'll be drawn) - this._dy, // Destination Y - this._dw, // Destination Width (always same as Source Width unless scaled) - this._dh); - // Destination Height (always same as Source Height unless scaled) - } - }; - DynamicTexture.prototype.copyPixels = // TODO - Add in support for: alphaBitmapData: BitmapData = null, alphaPoint: Point = null, mergeAlpha: bool = false - /** - * Copy pixel from another DynamicTexture to this texture. - * @param sourceTexture {DynamicTexture} Source texture object. - * @param sourceRect {Rectangle} The specific region rectangle to be copied to this in the source. - * @param destPoint {Point} Top-left point the target image data will be paste at. - */ - function (sourceTexture, sourceRect, destPoint) { - // Swap for drawImage if the sourceRect is the same size as the sourceTexture to avoid a costly getImageData call - if(sourceRect.equals(this.bounds) == true) { - this.context.drawImage(sourceTexture.canvas, destPoint.x, destPoint.y); - } else { - this.context.putImageData(sourceTexture.getPixels(sourceRect), destPoint.x, destPoint.y); - } - }; - DynamicTexture.prototype.assignCanvasToGameObjects = /** - * Given an array of GameObjects it will update each of them so that their canvas/contexts reference this DynamicTexture - * @param objects {Array} An array of GameObjects, or objects that inherit from it such as Sprites - */ - function (objects) { - for(var i = 0; i < objects.length; i++) { - objects[i].canvas = this.canvas; - objects[i].context = this.context; - } - }; - DynamicTexture.prototype.clear = /** - * Clear the whole canvas. - */ - function () { - this.context.clearRect(0, 0, this.bounds.width, this.bounds.height); - }; - DynamicTexture.prototype.render = /** - * Renders this DynamicTexture to the Stage at the given x/y coordinates - * - * @param x {number} The X coordinate to render on the stage to (given in screen coordinates, not world) - * @param y {number} The Y coordinate to render on the stage to (given in screen coordinates, not world) - */ - function (x, y) { - if (typeof x === "undefined") { x = 0; } - if (typeof y === "undefined") { y = 0; } - this._game.stage.context.drawImage(this.canvas, x, y); - }; - Object.defineProperty(DynamicTexture.prototype, "width", { - get: function () { - return this.bounds.width; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(DynamicTexture.prototype, "height", { - get: function () { - return this.bounds.height; - }, - enumerable: true, - configurable: true - }); - DynamicTexture.prototype.getColor32 = /** - * Given an alpha and 3 color values this will return an integer representation of it - * - * @param alpha {number} The Alpha value (between 0 and 255) - * @param red {number} The Red channel value (between 0 and 255) - * @param green {number} The Green channel value (between 0 and 255) - * @param blue {number} The Blue channel value (between 0 and 255) - * - * @return A native color value integer (format: 0xAARRGGBB) - */ - function (alpha, red, green, blue) { - return alpha << 24 | red << 16 | green << 8 | blue; - }; - DynamicTexture.prototype.getColor = /** - * Given 3 color values this will return an integer representation of it - * - * @param red {number} The Red channel value (between 0 and 255) - * @param green {number} The Green channel value (between 0 and 255) - * @param blue {number} The Blue channel value (between 0 and 255) - * - * @return A native color value integer (format: 0xRRGGBB) - */ - function (red, green, blue) { - return red << 16 | green << 8 | blue; - }; - return DynamicTexture; - })(); - Phaser.DynamicTexture = DynamicTexture; -})(Phaser || (Phaser = {})); -/// -/** * Phaser - GameMath * * Adds a set of extra Math functions used through-out Phaser. @@ -8235,7 +1582,3739 @@ var Phaser; })(); Phaser.GameMath = GameMath; })(Phaser || (Phaser = {})); -/// +/// +/** +* Phaser - RandomDataGenerator +* +* An extremely useful repeatable random data generator. Access it via Game.rnd +* Based on Nonsense by Josh Faul https://github.com/jocafa/Nonsense +* Random number generator from http://baagoe.org/en/wiki/Better_random_numbers_for_javascript +*/ +var Phaser; +(function (Phaser) { + var RandomDataGenerator = (function () { + /** + * @constructor + * @param {Array} seeds + * @return {Phaser.RandomDataGenerator} + */ + function RandomDataGenerator(seeds) { + if (typeof seeds === "undefined") { seeds = []; } + /** + * @property c + * @type Number + * @private + */ + this.c = 1; + this.sow(seeds); + } + RandomDataGenerator.prototype.uint32 = /** + * @method uint32 + * @private + */ + function () { + return this.rnd.apply(this) * 0x100000000;// 2^32 + + }; + RandomDataGenerator.prototype.fract32 = /** + * @method fract32 + * @private + */ + function () { + return this.rnd.apply(this) + (this.rnd.apply(this) * 0x200000 | 0) * 1.1102230246251565e-16;// 2^-53 + + }; + RandomDataGenerator.prototype.rnd = // private random helper + /** + * @method rnd + * @private + */ + function () { + var t = 2091639 * this.s0 + this.c * 2.3283064365386963e-10;// 2^-32 + + this.c = t | 0; + this.s0 = this.s1; + this.s1 = this.s2; + this.s2 = t - this.c; + return this.s2; + }; + RandomDataGenerator.prototype.hash = /** + * @method hash + * @param {Any} data + * @private + */ + function (data) { + var h, i, n; + n = 0xefc8249d; + data = data.toString(); + for(i = 0; i < data.length; i++) { + n += data.charCodeAt(i); + h = 0.02519603282416938 * n; + n = h >>> 0; + h -= n; + h *= n; + n = h >>> 0; + h -= n; + n += h * 0x100000000// 2^32 + ; + } + return (n >>> 0) * 2.3283064365386963e-10;// 2^-32 + + }; + RandomDataGenerator.prototype.sow = /** + * Reset the seed of the random data generator + * @method sow + * @param {Array} seeds + */ + function (seeds) { + if (typeof seeds === "undefined") { seeds = []; } + this.s0 = this.hash(' '); + this.s1 = this.hash(this.s0); + this.s2 = this.hash(this.s1); + var seed; + for(var i = 0; seed = seeds[i++]; ) { + this.s0 -= this.hash(seed); + this.s0 += ~~(this.s0 < 0); + this.s1 -= this.hash(seed); + this.s1 += ~~(this.s1 < 0); + this.s2 -= this.hash(seed); + this.s2 += ~~(this.s2 < 0); + } + }; + Object.defineProperty(RandomDataGenerator.prototype, "integer", { + get: /** + * Returns a random integer between 0 and 2^32 + * @method integer + * @return {Number} + */ + function () { + return this.uint32(); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(RandomDataGenerator.prototype, "frac", { + get: /** + * Returns a random real number between 0 and 1 + * @method frac + * @return {Number} + */ + function () { + return this.fract32(); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(RandomDataGenerator.prototype, "real", { + get: /** + * Returns a random real number between 0 and 2^32 + * @method real + * @return {Number} + */ + function () { + return this.uint32() + this.fract32(); + }, + enumerable: true, + configurable: true + }); + RandomDataGenerator.prototype.integerInRange = /** + * Returns a random integer between min and max + * @method integerInRange + * @param {Number} min + * @param {Number} max + * @return {Number} + */ + function (min, max) { + return Math.floor(this.realInRange(min, max)); + }; + RandomDataGenerator.prototype.realInRange = /** + * Returns a random real number between min and max + * @method realInRange + * @param {Number} min + * @param {Number} max + * @return {Number} + */ + function (min, max) { + min = min || 0; + max = max || 0; + return this.frac * (max - min) + min; + }; + Object.defineProperty(RandomDataGenerator.prototype, "normal", { + get: /** + * Returns a random real number between -1 and 1 + * @method normal + * @return {Number} + */ + function () { + return 1 - 2 * this.frac; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(RandomDataGenerator.prototype, "uuid", { + get: /** + * Returns a valid v4 UUID hex string (from https://gist.github.com/1308368) + * @method uuid + * @return {String} + */ + function () { + var a, b; + for(b = a = ''; a++ < 36; b += ~a % 5 | a * 3 & 4 ? (a ^ 15 ? 8 ^ this.frac * (a ^ 20 ? 16 : 4) : 4).toString(16) : '-') { + ; + } + return b; + }, + enumerable: true, + configurable: true + }); + RandomDataGenerator.prototype.pick = /** + * Returns a random member of `array` + * @method pick + * @param {Any} array + */ + function (array) { + return array[this.integerInRange(0, array.length)]; + }; + RandomDataGenerator.prototype.weightedPick = /** + * Returns a random member of `array`, favoring the earlier entries + * @method weightedPick + * @param {Any} array + */ + function (array) { + return array[~~(Math.pow(this.frac, 2) * array.length)]; + }; + RandomDataGenerator.prototype.timestamp = /** + * 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 timestamp + * @param {Number} min + * @param {Number} max + */ + function (min, max) { + if (typeof min === "undefined") { min = 946684800000; } + if (typeof max === "undefined") { max = 1577862000000; } + return this.realInRange(min, max); + }; + Object.defineProperty(RandomDataGenerator.prototype, "angle", { + get: /** + * Returns a random angle between -180 and 180 + * @method angle + */ + function () { + return this.integerInRange(-180, 180); + }, + enumerable: true, + configurable: true + }); + return RandomDataGenerator; + })(); + Phaser.RandomDataGenerator = RandomDataGenerator; +})(Phaser || (Phaser = {})); +/// +/** +* Phaser - Vec2 +* +* A Circle object is an area defined by its position, as indicated by its center point (x,y) and diameter. +*/ +var Phaser; +(function (Phaser) { + var Vec2 = (function () { + /** + * Creates a new Vec2 object. + * @class Vec2 + * @constructor + * @param {Number} x The x position of the vector + * @param {Number} y The y position of the vector + * @return {Vec2} This object + **/ + function Vec2(x, y) { + if (typeof x === "undefined") { x = 0; } + if (typeof y === "undefined") { y = 0; } + this.x = x; + this.y = y; + } + Vec2.prototype.copyFrom = /** + * Copies the x and y properties from any given object to this Vec2. + * @method copyFrom + * @param {any} source - The object to copy from. + * @return {Vec2} This Vec2 object. + **/ + function (source) { + return this.setTo(source.x, source.y); + }; + Vec2.prototype.setTo = /** + * Sets the x and y properties of the Vector. + * @param {Number} x The x position of the vector + * @param {Number} y The y position of the vector + * @return {Vec2} This object + **/ + function (x, y) { + this.x = x; + this.y = y; + return this; + }; + Vec2.prototype.add = /** + * Add another vector to this one. + * + * @param {Vec2} other The other Vector. + * @return {Vec2} This for chaining. + */ + function (a) { + this.x += a.x; + this.y += a.y; + return this; + }; + Vec2.prototype.subtract = /** + * Subtract another vector from this one. + * + * @param {Vec2} other The other Vector. + * @return {Vec2} This for chaining. + */ + function (v) { + this.x -= v.x; + this.y -= v.y; + return this; + }; + Vec2.prototype.multiply = /** + * Multiply another vector with this one. + * + * @param {Vec2} other The other Vector. + * @return {Vec2} This for chaining. + */ + function (v) { + this.x *= v.x; + this.y *= v.y; + return this; + }; + Vec2.prototype.divide = /** + * Divide this vector by another one. + * + * @param {Vec2} other The other Vector. + * @return {Vec2} This for chaining. + */ + function (v) { + this.x /= v.x; + this.y /= v.y; + return this; + }; + Vec2.prototype.length = /** + * Get the length of this vector. + * + * @return {number} The length of this vector. + */ + function () { + return Math.sqrt((this.x * this.x) + (this.y * this.y)); + }; + Vec2.prototype.lengthSq = /** + * Get the length squared of this vector. + * + * @return {number} The length^2 of this vector. + */ + function () { + return (this.x * this.x) + (this.y * this.y); + }; + Vec2.prototype.dot = /** + * The dot product of two 2D vectors. + * + * @param {Vec2} a Reference to a source Vec2 object. + * @return {Number} + */ + function (a) { + return ((this.x * a.x) + (this.y * a.y)); + }; + Vec2.prototype.cross = /** + * The cross product of two 2D vectors. + * + * @param {Vec2} a Reference to a source Vec2 object. + * @return {Number} + */ + function (a) { + return ((this.x * a.y) - (this.y * a.x)); + }; + Vec2.prototype.projectionLength = /** + * The projection magnitude of two 2D vectors. + * + * @param {Vec2} a Reference to a source Vec2 object. + * @return {Number} + */ + function (a) { + var den = a.dot(a); + if(den == 0) { + return 0; + } else { + return Math.abs(this.dot(a) / den); + } + }; + Vec2.prototype.angle = /** + * The angle between two 2D vectors. + * + * @param {Vec2} a Reference to a source Vec2 object. + * @return {Number} + */ + function (a) { + return Math.atan2(a.x * this.y - a.y * this.x, a.x * this.x + a.y * this.y); + }; + Vec2.prototype.scale = /** + * Scale this vector. + * + * @param {number} x The scaling factor in the x direction. + * @param {?number=} y The scaling factor in the y direction. If this is not specified, the x scaling factor will be used. + * @return {Vec2} This for chaining. + */ + function (x, y) { + this.x *= x; + this.y *= y || x; + return this; + }; + Vec2.prototype.divideByScalar = /** + * Divide this vector by the given scalar. + * + * @param {number} scalar + * @return {Vec2} This for chaining. + */ + function (scalar) { + this.x /= scalar; + this.y /= scalar; + return this; + }; + Vec2.prototype.reverse = /** + * Reverse this vector. + * + * @return {Vec2} This for chaining. + */ + function () { + this.x = -this.x; + this.y = -this.y; + return this; + }; + Vec2.prototype.toString = /** + * Returns a string representation of this object. + * @method toString + * @return {string} a string representation of the object. + **/ + function () { + return "[{Vec2 (x=" + this.x + " y=" + this.y + ")}]"; + }; + return Vec2; + })(); + Phaser.Vec2 = Vec2; +})(Phaser || (Phaser = {})); +/// +/** +* Phaser - AnimationLoader +* +* Responsible for parsing sprite sheet and JSON data into the internal FrameData format that Phaser uses for animations. +*/ +var Phaser; +(function (Phaser) { + var AnimationLoader = (function () { + function AnimationLoader() { } + AnimationLoader.parseSpriteSheet = /** + * Parse a sprite sheet from asset data. + * @param key {string} Asset key for the sprite sheet data. + * @param frameWidth {number} Width of animation frame. + * @param frameHeight {number} Height of animation frame. + * @param frameMax {number} Number of animation frames. + * @return {FrameData} Generated FrameData object. + */ + function parseSpriteSheet(game, key, frameWidth, frameHeight, frameMax) { + // How big is our image? + var img = game.cache.getImage(key); + if(img == null) { + return null; + } + var width = img.width; + var height = img.height; + var row = Math.round(width / frameWidth); + var column = Math.round(height / frameHeight); + var total = row * column; + if(frameMax !== -1) { + total = frameMax; + } + // Zero or smaller than frame sizes? + if(width == 0 || height == 0 || width < frameWidth || height < frameHeight || total === 0) { + return null; + } + // Let's create some frames then + var data = new Phaser.FrameData(); + var x = 0; + var y = 0; + for(var i = 0; i < total; i++) { + data.addFrame(new Phaser.Frame(x, y, frameWidth, frameHeight, '')); + x += frameWidth; + if(x === width) { + x = 0; + y += frameHeight; + } + } + return data; + }; + AnimationLoader.parseJSONData = /** + * Parse frame datas from json. + * @param json {object} Json data you want to parse. + * @return {FrameData} Generated FrameData object. + */ + function parseJSONData(game, json) { + // Malformed? + if(!json['frames']) { + throw new Error("Phaser.AnimationLoader.parseJSONData: Invalid Texture Atlas JSON given, missing 'frames' array"); + } + // Let's create some frames then + var data = new Phaser.FrameData(); + // By this stage frames is a fully parsed array + var frames = json; + var newFrame; + for(var i = 0; i < frames.length; i++) { + newFrame = data.addFrame(new Phaser.Frame(frames[i].frame.x, frames[i].frame.y, frames[i].frame.w, frames[i].frame.h, frames[i].filename)); + newFrame.setTrim(frames[i].trimmed, frames[i].sourceSize.w, frames[i].sourceSize.h, frames[i].spriteSourceSize.x, frames[i].spriteSourceSize.y, frames[i].spriteSourceSize.w, frames[i].spriteSourceSize.h); + } + return data; + }; + AnimationLoader.parseXMLData = function parseXMLData(game, xml, format) { + // Malformed? + if(!xml.getElementsByTagName('TextureAtlas')) { + throw new Error("Phaser.AnimationLoader.parseXMLData: Invalid Texture Atlas XML given, missing tag"); + } + // Let's create some frames then + var data = new Phaser.FrameData(); + var frames = xml.getElementsByTagName('SubTexture'); + var newFrame; + for(var i = 0; i < frames.length; i++) { + var frame = frames[i].attributes; + newFrame = data.addFrame(new Phaser.Frame(frame.x.nodeValue, frame.y.nodeValue, frame.width.nodeValue, frame.height.nodeValue, frame.name.nodeValue)); + // Trimmed? + if(frame.frameX.nodeValue != '-0' || frame.frameY.nodeValue != '-0') { + newFrame.setTrim(true, frame.width.nodeValue, frame.height.nodeValue, Math.abs(frame.frameX.nodeValue), Math.abs(frame.frameY.nodeValue), frame.frameWidth.nodeValue, frame.frameHeight.nodeValue); + } + } + return data; + }; + return AnimationLoader; + })(); + Phaser.AnimationLoader = AnimationLoader; +})(Phaser || (Phaser = {})); +/// +/** +* Phaser - Animation +* +* An Animation is a single animation. It is created by the AnimationManager and belongs to Sprite objects. +*/ +var Phaser; +(function (Phaser) { + var Animation = (function () { + /** + * Animation constructor + * Create a new Animation. + * + * @param parent {Sprite} Owner sprite of this animation. + * @param frameData {FrameData} The FrameData object contains animation data. + * @param name {string} Unique name of this animation. + * @param frames {number[]/string[]} An array of numbers or strings indicating what frames to play in what order. + * @param delay {number} Time between frames in ms. + * @param looped {boolean} Whether or not the animation is looped or just plays once. + */ + function Animation(game, parent, frameData, name, frames, delay, looped) { + this._game = game; + this._parent = parent; + this._frames = frames; + this._frameData = frameData; + this.name = name; + this.delay = 1000 / delay; + this.looped = looped; + this.isFinished = false; + this.isPlaying = false; + this._frameIndex = 0; + this.currentFrame = this._frameData.getFrame(this._frames[this._frameIndex]); + } + Object.defineProperty(Animation.prototype, "frameTotal", { + get: function () { + return this._frames.length; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Animation.prototype, "frame", { + get: function () { + if(this.currentFrame !== null) { + return this.currentFrame.index; + } else { + return this._frameIndex; + } + }, + set: function (value) { + this.currentFrame = this._frameData.getFrame(value); + if(this.currentFrame !== null) { + this._parent.frameBounds.width = this.currentFrame.width; + this._parent.frameBounds.height = this.currentFrame.height; + this._frameIndex = value; + } + }, + enumerable: true, + configurable: true + }); + Animation.prototype.play = /** + * Play this animation. + * @param frameRate {number} FrameRate you want to specify instead of using default. + * @param loop {boolean} Whether or not the animation is looped or just plays once. + */ + function (frameRate, loop) { + if (typeof frameRate === "undefined") { frameRate = null; } + if(frameRate !== null) { + this.delay = 1000 / frameRate; + } + if(loop !== undefined) { + this.looped = loop; + } + this.isPlaying = true; + this.isFinished = false; + this._timeLastFrame = this._game.time.now; + this._timeNextFrame = this._game.time.now + this.delay; + this._frameIndex = 0; + this.currentFrame = this._frameData.getFrame(this._frames[this._frameIndex]); + }; + Animation.prototype.restart = /** + * Play this animation from the first frame. + */ + function () { + this.isPlaying = true; + this.isFinished = false; + this._timeLastFrame = this._game.time.now; + this._timeNextFrame = this._game.time.now + this.delay; + this._frameIndex = 0; + this.currentFrame = this._frameData.getFrame(this._frames[this._frameIndex]); + }; + Animation.prototype.stop = /** + * Stop playing animation and set it finished. + */ + function () { + this.isPlaying = false; + this.isFinished = true; + }; + Animation.prototype.update = /** + * Update animation frames. + */ + function () { + if(this.isPlaying == true && this._game.time.now >= this._timeNextFrame) { + this._frameIndex++; + if(this._frameIndex == this._frames.length) { + if(this.looped) { + this._frameIndex = 0; + this.currentFrame = this._frameData.getFrame(this._frames[this._frameIndex]); + } else { + this.onComplete(); + } + } else { + this.currentFrame = this._frameData.getFrame(this._frames[this._frameIndex]); + } + this._timeLastFrame = this._game.time.now; + this._timeNextFrame = this._game.time.now + this.delay; + return true; + } + return false; + }; + Animation.prototype.destroy = /** + * Clean up animation memory. + */ + function () { + this._game = null; + this._parent = null; + this._frames = null; + this._frameData = null; + this.currentFrame = null; + this.isPlaying = false; + }; + Animation.prototype.onComplete = /** + * Animation complete callback method. + */ + function () { + this.isPlaying = false; + this.isFinished = true; + // callback goes here + }; + return Animation; + })(); + Phaser.Animation = Animation; +})(Phaser || (Phaser = {})); +/// +/** +* Phaser - Frame +* +* A Frame is a single frame of an animation and is part of a FrameData collection. +*/ +var Phaser; +(function (Phaser) { + var Frame = (function () { + /** + * Frame constructor + * Create a new Frame with specific position, size and name. + * + * @param x {number} X position within the image to cut from. + * @param y {number} Y position within the image to cut from. + * @param width {number} Width of the frame. + * @param height {number} Height of the frame. + * @param name {string} Name of this frame. + */ + function Frame(x, y, width, height, name) { + /** + * Useful for Texture Atlas files. (is set to the filename value) + */ + this.name = ''; + /** + * Rotated? (not yet implemented) + */ + this.rotated = false; + /** + * Either cw or ccw, rotation is always 90 degrees. + */ + this.rotationDirection = 'cw'; + this.x = x; + this.y = y; + this.width = width; + this.height = height; + this.name = name; + this.rotated = false; + this.trimmed = false; + } + Frame.prototype.setRotation = /** + * Set rotation of this frame. (Not yet supported!) + */ + function (rotated, rotationDirection) { + // Not yet supported + }; + Frame.prototype.setTrim = /** + * Set trim of the frame. + * @param trimmed {boolean} Whether this frame trimmed or not. + * @param actualWidth {number} Actual width of this frame. + * @param actualHeight {number} Actual height of this frame. + * @param destX {number} Destiny x position. + * @param destY {number} Destiny y position. + * @param destWidth {number} Destiny draw width. + * @param destHeight {number} Destiny draw height. + */ + function (trimmed, actualWidth, actualHeight, destX, destY, destWidth, destHeight) { + this.trimmed = trimmed; + this.sourceSizeW = actualWidth; + this.sourceSizeH = actualHeight; + this.spriteSourceSizeX = destX; + this.spriteSourceSizeY = destY; + this.spriteSourceSizeW = destWidth; + this.spriteSourceSizeH = destHeight; + }; + return Frame; + })(); + Phaser.Frame = Frame; +})(Phaser || (Phaser = {})); +/// +/** +* Phaser - FrameData +* +* FrameData is a container for Frame objects, the internal representation of animation data in Phaser. +*/ +var Phaser; +(function (Phaser) { + var FrameData = (function () { + /** + * FrameData constructor + */ + function FrameData() { + this._frames = []; + this._frameNames = []; + } + Object.defineProperty(FrameData.prototype, "total", { + get: function () { + return this._frames.length; + }, + enumerable: true, + configurable: true + }); + FrameData.prototype.addFrame = /** + * Add a new frame. + * @param frame {Frame} The frame you want to add. + * @return {Frame} The frame you just added. + */ + function (frame) { + frame.index = this._frames.length; + this._frames.push(frame); + if(frame.name !== '') { + this._frameNames[frame.name] = frame.index; + } + return frame; + }; + FrameData.prototype.getFrame = /** + * Get a frame by its index. + * @param index {number} Index of the frame you want to get. + * @return {Frame} The frame you want. + */ + function (index) { + if(this._frames[index]) { + return this._frames[index]; + } + return null; + }; + FrameData.prototype.getFrameByName = /** + * Get a frame by its name. + * @param name {string} Name of the frame you want to get. + * @return {Frame} The frame you want. + */ + function (name) { + if(this._frameNames[name] >= 0) { + return this._frames[this._frameNames[name]]; + } + return null; + }; + FrameData.prototype.checkFrameName = /** + * Check whether there's a frame with given name. + * @param name {string} Name of the frame you want to check. + * @return {boolean} True if frame with given name found, otherwise return false. + */ + function (name) { + if(this._frameNames[name] >= 0) { + return true; + } + return false; + }; + FrameData.prototype.getFrameRange = /** + * Get ranges of frames in an array. + * @param start {number} Start index of frames you want. + * @param end {number} End index of frames you want. + * @param [output] {Frame[]} result will be added into this array. + * @return {Frame[]} Ranges of specific frames in an array. + */ + function (start, end, output) { + if (typeof output === "undefined") { output = []; } + for(var i = start; i <= end; i++) { + output.push(this._frames[i]); + } + return output; + }; + FrameData.prototype.getFrameIndexes = /** + * Get all indexes of frames by giving their name. + * @param [output] {number[]} result will be added into this array. + * @return {number[]} Indexes of specific frames in an array. + */ + function (output) { + if (typeof output === "undefined") { output = []; } + output.length = 0; + for(var i = 0; i < this._frames.length; i++) { + output.push(i); + } + return output; + }; + FrameData.prototype.getFrameIndexesByName = /** + * Get all names of frames by giving their indexes. + * @param [output] {number[]} result will be added into this array. + * @return {number[]} Names of specific frames in an array. + */ + function (input) { + var output = []; + for(var i = 0; i < input.length; i++) { + if(this.getFrameByName(input[i])) { + output.push(this.getFrameByName(input[i]).index); + } + } + return output; + }; + FrameData.prototype.getAllFrames = /** + * Get all frames in this frame data. + * @return {Frame[]} All the frames in an array. + */ + function () { + return this._frames; + }; + FrameData.prototype.getFrames = /** + * Get All frames with specific ranges. + * @param range {number[]} Ranges in an array. + * @return {Frame[]} All frames in an array. + */ + function (range) { + var output = []; + for(var i = 0; i < range.length; i++) { + output.push(this._frames[i]); + } + return output; + }; + return FrameData; + })(); + Phaser.FrameData = FrameData; +})(Phaser || (Phaser = {})); +/// +/// +/// +/// +/// +/// +/** +* Phaser - AnimationManager +* +* Any Sprite that has animation contains an instance of the AnimationManager, which is used to add, play and update +* sprite specific animations. +*/ +var Phaser; +(function (Phaser) { + var AnimationManager = (function () { + /** + * AnimationManager constructor + * Create a new AnimationManager. + * + * @param parent {Sprite} Owner sprite of this manager. + */ + function AnimationManager(game, parent) { + /** + * Data contains animation frames. + * @type {FrameData} + */ + this._frameData = null; + /** + * Keeps track of the current frame of animation. + */ + this.currentFrame = null; + this._game = game; + this._parent = parent; + this._anims = { + }; + } + AnimationManager.prototype.loadFrameData = /** + * Load animation frame data. + * @param frameData Data to be loaded. + */ + function (frameData) { + this._frameData = frameData; + this.frame = 0; + }; + AnimationManager.prototype.add = /** + * Add a new animation. + * @param name {string} What this animation should be called (e.g. "run"). + * @param frames {any[]} An array of numbers/strings indicating what frames to play in what order (e.g. [1, 2, 3] or ['run0', 'run1', run2]). + * @param frameRate {number} The speed in frames per second that the animation should play at (e.g. 60 fps). + * @param loop {boolean} Whether or not the animation is looped or just plays once. + * @param useNumericIndex {boolean} Use number indexes instead of string indexes? + * @return {Animation} The Animation that was created + */ + function (name, frames, frameRate, loop, useNumericIndex) { + if (typeof frames === "undefined") { frames = null; } + if (typeof frameRate === "undefined") { frameRate = 60; } + if (typeof loop === "undefined") { loop = false; } + if (typeof useNumericIndex === "undefined") { useNumericIndex = true; } + if(this._frameData == null) { + return; + } + if(frames == null) { + frames = this._frameData.getFrameIndexes(); + } else { + if(this.validateFrames(frames, useNumericIndex) == false) { + throw Error('Invalid frames given to Animation ' + name); + return; + } + } + if(useNumericIndex == false) { + frames = this._frameData.getFrameIndexesByName(frames); + } + this._anims[name] = new Phaser.Animation(this._game, this._parent, this._frameData, name, frames, frameRate, loop); + this.currentAnim = this._anims[name]; + this.currentFrame = this.currentAnim.currentFrame; + return this._anims[name]; + }; + AnimationManager.prototype.validateFrames = /** + * Check whether the frames is valid. + * @param frames {any[]} Frames to be validated. + * @param useNumericIndex {boolean} Does these frames use number indexes or string indexes? + * @return {boolean} True if they're valid, otherwise return false. + */ + function (frames, useNumericIndex) { + for(var i = 0; i < frames.length; i++) { + if(useNumericIndex == true) { + if(frames[i] > this._frameData.total) { + return false; + } + } else { + if(this._frameData.checkFrameName(frames[i]) == false) { + return false; + } + } + } + return true; + }; + AnimationManager.prototype.play = /** + * Play animation with specific name. + * @param name {string} The string name of the animation you want to play. + * @param frameRate {number} FrameRate you want to specify instead of using default. + * @param loop {boolean} Whether or not the animation is looped or just plays once. + */ + function (name, frameRate, loop) { + if (typeof frameRate === "undefined") { frameRate = null; } + if(this._anims[name]) { + if(this.currentAnim == this._anims[name]) { + if(this.currentAnim.isPlaying == false) { + this.currentAnim.play(frameRate, loop); + } + } else { + this.currentAnim = this._anims[name]; + this.currentAnim.play(frameRate, loop); + } + } + }; + AnimationManager.prototype.stop = /** + * Stop animation by name. + * Current animation will be automatically set to the stopped one. + */ + function (name) { + if(this._anims[name]) { + this.currentAnim = this._anims[name]; + this.currentAnim.stop(); + } + }; + AnimationManager.prototype.update = /** + * Update animation and parent sprite's bounds. + */ + function () { + if(this.currentAnim && this.currentAnim.update() == true) { + this.currentFrame = this.currentAnim.currentFrame; + this._parent.frameBounds.width = this.currentFrame.width; + this._parent.frameBounds.height = this.currentFrame.height; + } + }; + Object.defineProperty(AnimationManager.prototype, "frameData", { + get: function () { + return this._frameData; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(AnimationManager.prototype, "frameTotal", { + get: function () { + if(this._frameData) { + return this._frameData.total; + } else { + return -1; + } + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(AnimationManager.prototype, "frame", { + get: function () { + return this._frameIndex; + }, + set: function (value) { + if(this._frameData.getFrame(value) !== null) { + this.currentFrame = this._frameData.getFrame(value); + this._parent.frameBounds.width = this.currentFrame.width; + this._parent.frameBounds.height = this.currentFrame.height; + this._frameIndex = value; + } + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(AnimationManager.prototype, "frameName", { + get: function () { + return this.currentFrame.name; + }, + set: function (value) { + if(this._frameData.getFrameByName(value) !== null) { + this.currentFrame = this._frameData.getFrameByName(value); + this._parent.frameBounds.width = this.currentFrame.width; + this._parent.frameBounds.height = this.currentFrame.height; + this._frameIndex = this.currentFrame.index; + } + }, + enumerable: true, + configurable: true + }); + AnimationManager.prototype.destroy = /** + * Removes all related references + */ + function () { + this._anims = { + }; + this._frameData = null; + this._frameIndex = 0; + this.currentAnim = null; + this.currentFrame = null; + }; + return AnimationManager; + })(); + Phaser.AnimationManager = AnimationManager; +})(Phaser || (Phaser = {})); +var Phaser; +(function (Phaser) { + /// + /** + * Phaser - Components - Position + * + * Sprite position, both world and screen, and rotation values and methods. + */ + (function (Components) { + var Position = (function () { + function Position(parent, x, y) { + /** + * Rotation angle of this object. + * @type {number} + */ + this._rotation = 0; + /** + * Z-order value of the object. + */ + this.z = 0; + /** + * This value is added to the rotation of the Sprite. + * For example if you had a sprite graphic drawn facing straight up then you could set + * rotationOffset to 90 and it would correspond correctly with Phasers right-handed coordinate system. + * @type {number} + */ + this.rotationOffset = 0; + this._sprite = parent; + this.world = new Phaser.Vec2(x, y); + this.screen = new Phaser.Vec2(x, y); + this.offset = new Phaser.Vec2(0, 0); + this.midpoint = new Phaser.Vec2(0, 0); + } + Object.defineProperty(Position.prototype, "rotation", { + get: function () { + return this._rotation; + }, + set: function (value) { + this._rotation = this._sprite.game.math.wrap(value, 360, 0); + }, + enumerable: true, + configurable: true + }); + return Position; + })(); + Components.Position = Position; + })(Phaser.Components || (Phaser.Components = {})); + var Components = Phaser.Components; +})(Phaser || (Phaser = {})); +/// +/// +/// +/** +* Phaser - RectangleUtils +* +* A collection of methods useful for manipulating and comparing Rectangle objects. +* +* TODO: Check docs + overlap + intersect + toPolygon? +*/ +var Phaser; +(function (Phaser) { + var RectangleUtils = (function () { + function RectangleUtils() { } + RectangleUtils.getTopLeftAsPoint = /** + * Get the location of the Rectangles top-left corner as a Point object. + * @method getTopLeftAsPoint + * @param {Rectangle} a - The Rectangle object. + * @param {Point} out - Optional Point to store the value in, if not supplied a new Point object will be created. + * @return {Point} The new Point object. + **/ + function getTopLeftAsPoint(a, out) { + if (typeof out === "undefined") { out = new Phaser.Point(); } + return out.setTo(a.x, a.y); + }; + RectangleUtils.getBottomRightAsPoint = /** + * Get the location of the Rectangles bottom-right corner as a Point object. + * @method getTopLeftAsPoint + * @param {Rectangle} a - The Rectangle object. + * @param {Point} out - Optional Point to store the value in, if not supplied a new Point object will be created. + * @return {Point} The new Point object. + **/ + function getBottomRightAsPoint(a, out) { + if (typeof out === "undefined") { out = new Phaser.Point(); } + return out.setTo(a.right, a.bottom); + }; + RectangleUtils.inflate = /** + * Increases the size of the Rectangle object by the specified amounts. The center point of the Rectangle object stays the same, and its size increases to the left and right by the dx value, and to the top and the bottom by the dy value. + * @method inflate + * @param {Rectangle} a - The Rectangle object. + * @param {Number} dx The amount to be added to the left side of the Rectangle. + * @param {Number} dy The amount to be added to the bottom side of the Rectangle. + * @return {Rectangle} This Rectangle object. + **/ + function inflate(a, dx, dy) { + a.x -= dx; + a.width += 2 * dx; + a.y -= dy; + a.height += 2 * dy; + return a; + }; + RectangleUtils.inflatePoint = /** + * Increases the size of the Rectangle object. This method is similar to the Rectangle.inflate() method except it takes a Point object as a parameter. + * @method inflatePoint + * @param {Rectangle} a - The Rectangle object. + * @param {Point} point The x property of this Point object is used to increase the horizontal dimension of the Rectangle object. The y property is used to increase the vertical dimension of the Rectangle object. + * @return {Rectangle} The Rectangle object. + **/ + function inflatePoint(a, point) { + return RectangleUtils.inflate(a, point.x, point.y); + }; + RectangleUtils.size = /** + * The size of the Rectangle object, expressed as a Point object with the values of the width and height properties. + * @method size + * @param {Rectangle} a - The Rectangle object. + * @param {Point} output Optional Point object. If given the values will be set into the object, otherwise a brand new Point object will be created and returned. + * @return {Point} The size of the Rectangle object + **/ + function size(a, output) { + if (typeof output === "undefined") { output = new Phaser.Point(); } + return output.setTo(a.width, a.height); + }; + RectangleUtils.clone = /** + * Returns a new Rectangle object with the same values for the x, y, width, and height properties as the original Rectangle object. + * @method clone + * @param {Rectangle} a - The Rectangle object. + * @param {Rectangle} output Optional Rectangle object. If given the values will be set into the object, otherwise a brand new Rectangle object will be created and returned. + * @return {Rectangle} + **/ + function clone(a, output) { + if (typeof output === "undefined") { output = new Phaser.Rectangle(); } + return output.setTo(a.x, a.y, a.width, a.height); + }; + RectangleUtils.contains = /** + * Determines whether the specified coordinates are contained within the region defined by this Rectangle object. + * @method contains + * @param {Rectangle} a - The Rectangle object. + * @param {Number} x The x coordinate of the point to test. + * @param {Number} y The y coordinate of the point to test. + * @return {Boolean} A value of true if the Rectangle object contains the specified point; otherwise false. + **/ + function contains(a, x, y) { + return (x >= a.x && x <= a.right && y >= a.y && y <= a.bottom); + }; + RectangleUtils.containsPoint = /** + * Determines whether the specified point is contained within the rectangular region defined by this Rectangle object. This method is similar to the Rectangle.contains() method, except that it takes a Point object as a parameter. + * @method containsPoint + * @param {Rectangle} a - The Rectangle object. + * @param {Point} point The point object being checked. Can be Point or any object with .x and .y values. + * @return {Boolean} A value of true if the Rectangle object contains the specified point; otherwise false. + **/ + function containsPoint(a, point) { + return RectangleUtils.contains(a, point.x, point.y); + }; + RectangleUtils.containsRect = /** + * Determines whether the first Rectangle object is fully contained within the second Rectangle object. + * A Rectangle object is said to contain another if the second Rectangle object falls entirely within the boundaries of the first. + * @method containsRect + * @param {Rectangle} a - The first Rectangle object. + * @param {Rectangle} b - The second Rectangle object. + * @return {Boolean} A value of true if the Rectangle object contains the specified point; otherwise false. + **/ + function containsRect(a, b) { + // If the given rect has a larger volume than this one then it can never contain it + if(a.volume > b.volume) { + return false; + } + return (a.x >= b.x && a.y >= b.y && a.right <= b.right && a.bottom <= b.bottom); + }; + RectangleUtils.equals = /** + * Determines whether the two Rectangles are equal. + * This method compares the x, y, width and height properties of each Rectangle. + * @method equals + * @param {Rectangle} a - The first Rectangle object. + * @param {Rectangle} b - The second Rectangle object. + * @return {Boolean} A value of true if the two Rectangles have exactly the same values for the x, y, width and height properties; otherwise false. + **/ + function equals(a, b) { + return (a.x == b.x && a.y == b.y && a.width == b.width && a.height == b.height); + }; + RectangleUtils.intersection = /** + * If the Rectangle object specified in the toIntersect parameter intersects with this Rectangle object, returns the area of intersection as a Rectangle object. If the rectangles do not intersect, this method returns an empty Rectangle object with its properties set to 0. + * @method intersection + * @param {Rectangle} a - The first Rectangle object. + * @param {Rectangle} b - The second Rectangle object. + * @param {Rectangle} output Optional Rectangle object. If given the intersection values will be set into this object, otherwise a brand new Rectangle object will be created and returned. + * @return {Rectangle} A Rectangle object that equals the area of intersection. If the rectangles do not intersect, this method returns an empty Rectangle object; that is, a rectangle with its x, y, width, and height properties set to 0. + **/ + function intersection(a, b, out) { + if (typeof out === "undefined") { out = new Phaser.Rectangle(); } + if(RectangleUtils.intersects(a, b)) { + out.x = Math.max(a.x, b.x); + out.y = Math.max(a.y, b.y); + out.width = Math.min(a.right, b.right) - out.x; + out.height = Math.min(a.bottom, b.bottom) - out.y; + } + return out; + }; + RectangleUtils.intersects = /** + * Determines whether the two Rectangles intersect with each other. + * This method checks the x, y, width, and height properties of the Rectangles. + * @method intersects + * @param {Rectangle} a - The first Rectangle object. + * @param {Rectangle} b - The second Rectangle object. + * @param {Number} tolerance A tolerance value to allow for an intersection test with padding, default to 0 + * @return {Boolean} A value of true if the specified object intersects with this Rectangle object; otherwise false. + **/ + function intersects(a, b, tolerance) { + if (typeof tolerance === "undefined") { tolerance = 0; } + // ? + //return (a.right > b.x) && (a.x < b.right) && (a.bottom > b.y) && (a.y < b.bottom); + return !(a.left > b.right + tolerance || a.right < b.left - tolerance || a.top > b.bottom + tolerance || a.bottom < b.top - tolerance); + //if (a.x >= b.right || a.right <= b.x || a.bottom <= b.y || a.y >= b.bottom) + //{ + // return false; + //} + //return true; + }; + RectangleUtils.intersectsRaw = /** + * Determines whether the object specified intersects (overlaps) with the given values. + * @method intersectsRaw + * @param {Number} left + * @param {Number} right + * @param {Number} top + * @param {Number} bottomt + * @param {Number} tolerance A tolerance value to allow for an intersection test with padding, default to 0 + * @return {Boolean} A value of true if the specified object intersects with the Rectangle; otherwise false. + **/ + function intersectsRaw(a, left, right, top, bottom, tolerance) { + if (typeof tolerance === "undefined") { tolerance = 0; } + return !(left > a.right + tolerance || right < a.left - tolerance || top > a.bottom + tolerance || bottom < a.top - tolerance); + }; + RectangleUtils.union = /** + * Adds two rectangles together to create a new Rectangle object, by filling in the horizontal and vertical space between the two rectangles. + * @method union + * @param {Rectangle} a - The first Rectangle object. + * @param {Rectangle} b - The second Rectangle object. + * @param {Rectangle} output Optional Rectangle object. If given the new values will be set into this object, otherwise a brand new Rectangle object will be created and returned. + * @return {Rectangle} A Rectangle object that is the union of the two rectangles. + **/ + function union(a, b, out) { + if (typeof out === "undefined") { out = new Phaser.Rectangle(); } + return out.setTo(Math.min(a.x, b.x), Math.min(a.y, b.y), Math.max(a.right, b.right), Math.max(a.bottom, b.bottom)); + }; + return RectangleUtils; + })(); + Phaser.RectangleUtils = RectangleUtils; +})(Phaser || (Phaser = {})); +/// +/// +/// +/** +* Phaser - DynamicTexture +* +* A DynamicTexture can be thought of as a mini canvas into which you can draw anything. +* Game Objects can be assigned a DynamicTexture, so when they render in the world they do so +* based on the contents of the texture at the time. This allows you to create powerful effects +* once and have them replicated across as many game objects as you like. +*/ +var Phaser; +(function (Phaser) { + var DynamicTexture = (function () { + /** + * DynamicTexture constructor + * Create a new DynamicTexture. + * + * @param game {Phaser.Game} Current game instance. + * @param width {number} Init width of this texture. + * @param height {number} Init height of this texture. + */ + function DynamicTexture(game, width, height) { + this._sx = 0; + this._sy = 0; + this._sw = 0; + this._sh = 0; + this._dx = 0; + this._dy = 0; + this._dw = 0; + this._dh = 0; + this.game = game; + this.type = Phaser.Types.GEOMSPRITE; + this.canvas = document.createElement('canvas'); + this.canvas.width = width; + this.canvas.height = height; + this.context = this.canvas.getContext('2d'); + this.bounds = new Phaser.Rectangle(0, 0, width, height); + } + DynamicTexture.prototype.getPixel = /** + * Get a color of a specific pixel. + * @param x {number} X position of the pixel in this texture. + * @param y {number} Y position of the pixel in this texture. + * @return {number} A native color value integer (format: 0xRRGGBB) + */ + function (x, y) { + //r = imageData.data[0]; + //g = imageData.data[1]; + //b = imageData.data[2]; + //a = imageData.data[3]; + var imageData = this.context.getImageData(x, y, 1, 1); + return this.getColor(imageData.data[0], imageData.data[1], imageData.data[2]); + }; + DynamicTexture.prototype.getPixel32 = /** + * Get a color of a specific pixel (including alpha value). + * @param x {number} X position of the pixel in this texture. + * @param y {number} Y position of the pixel in this texture. + * @return A native color value integer (format: 0xAARRGGBB) + */ + function (x, y) { + var imageData = this.context.getImageData(x, y, 1, 1); + return this.getColor32(imageData.data[3], imageData.data[0], imageData.data[1], imageData.data[2]); + }; + DynamicTexture.prototype.getPixels = /** + * Get pixels in array in a specific rectangle. + * @param rect {Rectangle} The specific rectangle. + * @returns {array} CanvasPixelArray. + */ + function (rect) { + return this.context.getImageData(rect.x, rect.y, rect.width, rect.height); + }; + DynamicTexture.prototype.setPixel = /** + * Set color of a specific pixel. + * @param x {number} X position of the target pixel. + * @param y {number} Y position of the target pixel. + * @param color {number} Native integer with color value. (format: 0xRRGGBB) + */ + function (x, y, color) { + this.context.fillStyle = color; + this.context.fillRect(x, y, 1, 1); + }; + DynamicTexture.prototype.setPixel32 = /** + * Set color (with alpha) of a specific pixel. + * @param x {number} X position of the target pixel. + * @param y {number} Y position of the target pixel. + * @param color {number} Native integer with color value. (format: 0xAARRGGBB) + */ + function (x, y, color) { + this.context.fillStyle = color; + this.context.fillRect(x, y, 1, 1); + }; + DynamicTexture.prototype.setPixels = /** + * Set image data to a specific rectangle. + * @param rect {Rectangle} Target rectangle. + * @param input {object} Source image data. + */ + function (rect, input) { + this.context.putImageData(input, rect.x, rect.y); + }; + DynamicTexture.prototype.fillRect = /** + * Fill a given rectangle with specific color. + * @param rect {Rectangle} Target rectangle you want to fill. + * @param color {number} A native number with color value. (format: 0xRRGGBB) + */ + function (rect, color) { + this.context.fillStyle = color; + this.context.fillRect(rect.x, rect.y, rect.width, rect.height); + }; + DynamicTexture.prototype.pasteImage = /** + * + */ + function (key, frame, destX, destY, destWidth, destHeight) { + if (typeof frame === "undefined") { frame = -1; } + if (typeof destX === "undefined") { destX = 0; } + if (typeof destY === "undefined") { destY = 0; } + if (typeof destWidth === "undefined") { destWidth = null; } + if (typeof destHeight === "undefined") { destHeight = null; } + var texture = null; + var frameData; + this._sx = 0; + this._sy = 0; + this._dx = destX; + this._dy = destY; + // TODO - Load a frame from a sprite sheet, otherwise we'll draw the whole lot + if(frame > -1) { + //if (this.game.cache.isSpriteSheet(key)) + //{ + // texture = this.game.cache.getImage(key); + //this.animations.loadFrameData(this.game.cache.getFrameData(key)); + //} + } else { + texture = this.game.cache.getImage(key); + this._sw = texture.width; + this._sh = texture.height; + this._dw = texture.width; + this._dh = texture.height; + } + if(destWidth !== null) { + this._dw = destWidth; + } + if(destHeight !== null) { + this._dh = destHeight; + } + if(texture != null) { + this.context.drawImage(texture, // Source Image + this._sx, // Source X (location within the source image) + this._sy, // Source Y + this._sw, // Source Width + this._sh, // Source Height + this._dx, // Destination X (where on the canvas it'll be drawn) + this._dy, // Destination Y + this._dw, // Destination Width (always same as Source Width unless scaled) + this._dh); + // Destination Height (always same as Source Height unless scaled) + } + }; + DynamicTexture.prototype.copyPixels = // TODO - Add in support for: alphaBitmapData: BitmapData = null, alphaPoint: Point = null, mergeAlpha: bool = false + /** + * Copy pixel from another DynamicTexture to this texture. + * @param sourceTexture {DynamicTexture} Source texture object. + * @param sourceRect {Rectangle} The specific region rectangle to be copied to this in the source. + * @param destPoint {Point} Top-left point the target image data will be paste at. + */ + function (sourceTexture, sourceRect, destPoint) { + // Swap for drawImage if the sourceRect is the same size as the sourceTexture to avoid a costly getImageData call + if(Phaser.RectangleUtils.equals(sourceRect, this.bounds) == true) { + this.context.drawImage(sourceTexture.canvas, destPoint.x, destPoint.y); + } else { + this.context.putImageData(sourceTexture.getPixels(sourceRect), destPoint.x, destPoint.y); + } + }; + DynamicTexture.prototype.assignCanvasToGameObjects = /** + * Given an array of Sprites it will update each of them so that their canvas/contexts reference this DynamicTexture + * @param objects {Array} An array of GameObjects, or objects that inherit from it such as Sprites + */ + function (objects) { + for(var i = 0; i < objects.length; i++) { + objects[i].texture.canvas = this.canvas; + objects[i].texture.context = this.context; + } + }; + DynamicTexture.prototype.clear = /** + * Clear the whole canvas. + */ + function () { + this.context.clearRect(0, 0, this.bounds.width, this.bounds.height); + }; + DynamicTexture.prototype.render = /** + * Renders this DynamicTexture to the Stage at the given x/y coordinates + * + * @param x {number} The X coordinate to render on the stage to (given in screen coordinates, not world) + * @param y {number} The Y coordinate to render on the stage to (given in screen coordinates, not world) + */ + function (x, y) { + if (typeof x === "undefined") { x = 0; } + if (typeof y === "undefined") { y = 0; } + this.game.stage.context.drawImage(this.canvas, x, y); + }; + Object.defineProperty(DynamicTexture.prototype, "width", { + get: function () { + return this.bounds.width; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(DynamicTexture.prototype, "height", { + get: function () { + return this.bounds.height; + }, + enumerable: true, + configurable: true + }); + DynamicTexture.prototype.getColor32 = /** + * Given an alpha and 3 color values this will return an integer representation of it + * + * @param alpha {number} The Alpha value (between 0 and 255) + * @param red {number} The Red channel value (between 0 and 255) + * @param green {number} The Green channel value (between 0 and 255) + * @param blue {number} The Blue channel value (between 0 and 255) + * + * @return A native color value integer (format: 0xAARRGGBB) + */ + function (alpha, red, green, blue) { + return alpha << 24 | red << 16 | green << 8 | blue; + }; + DynamicTexture.prototype.getColor = /** + * Given 3 color values this will return an integer representation of it + * + * @param red {number} The Red channel value (between 0 and 255) + * @param green {number} The Green channel value (between 0 and 255) + * @param blue {number} The Blue channel value (between 0 and 255) + * + * @return A native color value integer (format: 0xRRGGBB) + */ + function (red, green, blue) { + return red << 16 | green << 8 | blue; + }; + return DynamicTexture; + })(); + Phaser.DynamicTexture = DynamicTexture; +})(Phaser || (Phaser = {})); +/// +/** +* Phaser - Circle +* +* A Circle object is an area defined by its position, as indicated by its center point (x,y) and diameter. +*/ +var Phaser; +(function (Phaser) { + var Circle = (function () { + /** + * Creates a new Circle object with the center coordinate specified by the x and y parameters and the diameter specified by the diameter parameter. If you call this function without parameters, a circle with x, y, diameter and radius properties set to 0 is created. + * @class Circle + * @constructor + * @param {Number} [x] The x coordinate of the center of the circle. + * @param {Number} [y] The y coordinate of the center of the circle. + * @param {Number} [diameter] The diameter of the circle. + * @return {Circle} This circle object + **/ + function Circle(x, y, diameter) { + if (typeof x === "undefined") { x = 0; } + if (typeof y === "undefined") { y = 0; } + if (typeof diameter === "undefined") { diameter = 0; } + this._diameter = 0; + this._radius = 0; + //private _pos: Vec2; + /** + * The x coordinate of the center of the circle + * @property x + * @type Number + **/ + this.x = 0; + /** + * The y coordinate of the center of the circle + * @property y + * @type Number + **/ + this.y = 0; + this.setTo(x, y, diameter); + } + Object.defineProperty(Circle.prototype, "diameter", { + get: /** + * The diameter of the circle. The largest distance between any two points on the circle. The same as the radius * 2. + * @method diameter + * @return {Number} + **/ + function () { + return this._diameter; + }, + set: /** + * The diameter of the circle. The largest distance between any two points on the circle. The same as the radius * 2. + * @method diameter + * @param {Number} The diameter of the circle. + **/ + function (value) { + if(value > 0) { + this._diameter = value; + this._radius = value * 0.5; + } + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Circle.prototype, "radius", { + get: /** + * The radius of the circle. The length of a line extending from the center of the circle to any point on the circle itself. The same as half the diameter. + * @method radius + * @return {Number} + **/ + function () { + return this._radius; + }, + set: /** + * The radius of the circle. The length of a line extending from the center of the circle to any point on the circle itself. The same as half the diameter. + * @method radius + * @param {Number} The radius of the circle. + **/ + function (value) { + if(value > 0) { + this._radius = value; + this._diameter = value * 2; + } + }, + enumerable: true, + configurable: true + }); + Circle.prototype.circumference = /** + * The circumference of the circle. + * @method circumference + * @return {Number} + **/ + function () { + return 2 * (Math.PI * this._radius); + }; + Object.defineProperty(Circle.prototype, "bottom", { + get: /** + * The sum of the y and radius properties. Changing the bottom property of a Circle object has no effect on the x and y properties, but does change the diameter. + * @method bottom + * @return {Number} + **/ + function () { + return this.y + this._radius; + }, + set: /** + * The sum of the y and radius properties. Changing the bottom property of a Circle object has no effect on the x and y properties, but does change the diameter. + * @method bottom + * @param {Number} The value to adjust the height of the circle by. + **/ + function (value) { + if(value < this.y) { + this._radius = 0; + this._diameter = 0; + } else { + this.radius = value - this.y; + } + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Circle.prototype, "left", { + get: /** + * The x coordinate of the leftmost point of the circle. Changing the left property of a Circle object has no effect on the x and y properties. However it does affect the diameter, whereas changing the x value does not affect the diameter property. + * @method left + * @return {Number} The x coordinate of the leftmost point of the circle. + **/ + function () { + return this.x - this._radius; + }, + set: /** + * The x coordinate of the leftmost point of the circle. Changing the left property of a Circle object has no effect on the x and y properties. However it does affect the diameter, whereas changing the x value does not affect the diameter property. + * @method left + * @param {Number} The value to adjust the position of the leftmost point of the circle by. + **/ + function (value) { + if(value > this.x) { + this._radius = 0; + this._diameter = 0; + } else { + this.radius = this.x - value; + } + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Circle.prototype, "right", { + get: /** + * The x coordinate of the rightmost point of the circle. Changing the right property of a Circle object has no effect on the x and y properties. However it does affect the diameter, whereas changing the x value does not affect the diameter property. + * @method right + * @return {Number} + **/ + function () { + return this.x + this._radius; + }, + set: /** + * The x coordinate of the rightmost point of the circle. Changing the right property of a Circle object has no effect on the x and y properties. However it does affect the diameter, whereas changing the x value does not affect the diameter property. + * @method right + * @param {Number} The amount to adjust the diameter of the circle by. + **/ + function (value) { + if(value < this.x) { + this._radius = 0; + this._diameter = 0; + } else { + this.radius = value - this.x; + } + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Circle.prototype, "top", { + get: /** + * The sum of the y minus the radius property. Changing the top property of a Circle object has no effect on the x and y properties, but does change the diameter. + * @method bottom + * @return {Number} + **/ + function () { + return this.y - this._radius; + }, + set: /** + * The sum of the y minus the radius property. Changing the top property of a Circle object has no effect on the x and y properties, but does change the diameter. + * @method bottom + * @param {Number} The amount to adjust the height of the circle by. + **/ + function (value) { + if(value > this.y) { + this._radius = 0; + this._diameter = 0; + } else { + this.radius = this.y - value; + } + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Circle.prototype, "area", { + get: /** + * Gets the area of this Circle. + * @method area + * @return {Number} This area of this circle. + **/ + function () { + if(this._radius > 0) { + return Math.PI * this._radius * this._radius; + } else { + return 0; + } + }, + enumerable: true, + configurable: true + }); + Circle.prototype.setTo = /** + * Sets the members of Circle to the specified values. + * @method setTo + * @param {Number} x The x coordinate of the center of the circle. + * @param {Number} y The y coordinate of the center of the circle. + * @param {Number} diameter The diameter of the circle in pixels. + * @return {Circle} This circle object + **/ + function (x, y, diameter) { + this.x = x; + this.y = y; + this._diameter = diameter; + this._radius = diameter * 0.5; + return this; + }; + Circle.prototype.copyFrom = /** + * Copies the x, y and diameter properties from any given object to this Circle. + * @method copyFrom + * @param {any} source - The object to copy from. + * @return {Circle} This Circle object. + **/ + function (source) { + return this.setTo(source.x, source.y, source.diameter); + }; + Object.defineProperty(Circle.prototype, "empty", { + get: /** + * Determines whether or not this Circle object is empty. + * @method empty + * @return {Boolean} A value of true if the Circle objects diameter is less than or equal to 0; otherwise false. + **/ + function () { + return (this._diameter == 0); + }, + set: /** + * Sets all of the Circle objects properties to 0. A Circle object is empty if its diameter is less than or equal to 0. + * @method setEmpty + * @return {Circle} This Circle object + **/ + function (value) { + return this.setTo(0, 0, 0); + }, + enumerable: true, + configurable: true + }); + Circle.prototype.offset = /** + * Adjusts the location of the Circle object, as determined by its center coordinate, by the specified amounts. + * @method offset + * @param {Number} dx Moves the x value of the Circle object by this amount. + * @param {Number} dy Moves the y value of the Circle object by this amount. + * @return {Circle} This Circle object. + **/ + function (dx, dy) { + this.x += dx; + this.y += dy; + return this; + }; + Circle.prototype.offsetPoint = /** + * Adjusts the location of the Circle object using a Point object as a parameter. This method is similar to the Circle.offset() method, except that it takes a Point object as a parameter. + * @method offsetPoint + * @param {Point} point A Point object to use to offset this Circle object. + * @return {Circle} This Circle object. + **/ + function (point) { + return this.offset(point.x, point.y); + }; + Circle.prototype.toString = /** + * Returns a string representation of this object. + * @method toString + * @return {string} a string representation of the instance. + **/ + function () { + return "[{Circle (x=" + this.x + " y=" + this.y + " diameter=" + this.diameter + " radius=" + this.radius + ")}]"; + }; + return Circle; + })(); + Phaser.Circle = Circle; +})(Phaser || (Phaser = {})); +/// +/// +/// +/// +/// +/** +* Phaser - SpriteUtils +* +* A collection of methods useful for manipulating and checking Sprites. +* +* TODO: +*/ +var Phaser; +(function (Phaser) { + var SpriteUtils = (function () { + function SpriteUtils() { } + SpriteUtils.ALIGN_TOP_LEFT = 0; + SpriteUtils.ALIGN_TOP_CENTER = 1; + SpriteUtils.ALIGN_TOP_RIGHT = 2; + SpriteUtils.ALIGN_CENTER_LEFT = 3; + SpriteUtils.ALIGN_CENTER = 4; + SpriteUtils.ALIGN_CENTER_RIGHT = 5; + SpriteUtils.ALIGN_BOTTOM_LEFT = 6; + SpriteUtils.ALIGN_BOTTOM_CENTER = 7; + SpriteUtils.ALIGN_BOTTOM_RIGHT = 8; + SpriteUtils.setBounds = /** + * Checks to see if some GameObject overlaps this GameObject or Group. + * If the group has a LOT of things in it, it might be faster to use Collision.overlaps(). + * WARNING: Currently tilemaps do NOT support screen space overlap checks! + * + * @param objectOrGroup {object} The object or group being tested. + * @param inScreenSpace {boolean} Whether to take scroll factors numbero account when checking for overlap. Default is false, or "only compare in world space." + * @param camera {Camera} Specify which game camera you want. If null getScreenXY() will just grab the first global camera. + * + * @return {boolean} Whether or not the objects overlap this. + */ + /* + static overlaps(objectOrGroup, inScreenSpace: bool = false, camera: Camera = null): bool { + + if (objectOrGroup.isGroup) + { + var results: bool = false; + var i: number = 0; + var members = objectOrGroup.members; + + while (i < length) + { + if (this.overlaps(members[i++], inScreenSpace, camera)) + { + results = true; + } + } + + return results; + + } + + if (!inScreenSpace) + { + return (objectOrGroup.x + objectOrGroup.width > this.x) && (objectOrGroup.x < this.x + this.width) && + (objectOrGroup.y + objectOrGroup.height > this.y) && (objectOrGroup.y < this.y + this.height); + } + + if (camera == null) + { + camera = this._game.camera; + } + + var objectScreenPos: Point = objectOrGroup.getScreenXY(null, camera); + + this.getScreenXY(this._point, camera); + + return (objectScreenPos.x + objectOrGroup.width > this._point.x) && (objectScreenPos.x < this._point.x + this.width) && + (objectScreenPos.y + objectOrGroup.height > this._point.y) && (objectScreenPos.y < this._point.y + this.height); + } + */ + /** + * Checks to see if this GameObject were located at the given position, would it overlap the GameObject or Group? + * This is distinct from overlapsPoint(), which just checks that point, rather than taking the object's size numbero account. + * WARNING: Currently tilemaps do NOT support screen space overlap checks! + * + * @param X {number} The X position you want to check. Pretends this object (the caller, not the parameter) is located here. + * @param Y {number} The Y position you want to check. Pretends this object (the caller, not the parameter) is located here. + * @param objectOrGroup {object} The object or group being tested. + * @param inScreenSpace {boolean} Whether to take scroll factors numbero account when checking for overlap. Default is false, or "only compare in world space." + * @param camera {Camera} Specify which game camera you want. If null getScreenXY() will just grab the first global camera. + * + * @return {boolean} Whether or not the two objects overlap. + */ + /* + static overlapsAt(X: number, Y: number, objectOrGroup, inScreenSpace: bool = false, camera: Camera = null): bool { + + if (objectOrGroup.isGroup) + { + var results: bool = false; + var basic; + var i: number = 0; + var members = objectOrGroup.members; + + while (i < length) + { + if (this.overlapsAt(X, Y, members[i++], inScreenSpace, camera)) + { + results = true; + } + } + + return results; + } + + if (!inScreenSpace) + { + return (objectOrGroup.x + objectOrGroup.width > X) && (objectOrGroup.x < X + this.width) && + (objectOrGroup.y + objectOrGroup.height > Y) && (objectOrGroup.y < Y + this.height); + } + + if (camera == null) + { + camera = this._game.camera; + } + + var objectScreenPos: Point = objectOrGroup.getScreenXY(null, Camera); + + this._point.x = X - camera.scroll.x * this.scrollFactor.x; //copied from getScreenXY() + this._point.y = Y - camera.scroll.y * this.scrollFactor.y; + this._point.x += (this._point.x > 0) ? 0.0000001 : -0.0000001; + this._point.y += (this._point.y > 0) ? 0.0000001 : -0.0000001; + + return (objectScreenPos.x + objectOrGroup.width > this._point.x) && (objectScreenPos.x < this._point.x + this.width) && + (objectScreenPos.y + objectOrGroup.height > this._point.y) && (objectScreenPos.y < this._point.y + this.height); + } + */ + /** + * Checks to see if a point in 2D world space overlaps this GameObject. + * + * @param point {Point} The point in world space you want to check. + * @param inScreenSpace {boolean} Whether to take scroll factors into account when checking for overlap. + * @param camera {Camera} Specify which game camera you want. If null getScreenXY() will just grab the first global camera. + * + * @return Whether or not the point overlaps this object. + */ + /* + static overlapsPoint(point: Point, inScreenSpace: bool = false, camera: Camera = null): bool { + + if (!inScreenSpace) + { + return (point.x > this.x) && (point.x < this.x + this.width) && (point.y > this.y) && (point.y < this.y + this.height); + } + + if (camera == null) + { + camera = this._game.camera; + } + + var X: number = point.x - camera.scroll.x; + var Y: number = point.y - camera.scroll.y; + + this.getScreenXY(this._point, camera); + + return (X > this._point.x) && (X < this._point.x + this.width) && (Y > this._point.y) && (Y < this._point.y + this.height); + + } + */ + /** + * Check and see if this object is currently on screen. + * + * @param camera {Camera} Specify which game camera you want. If null getScreenXY() will just grab the first global camera. + * + * @return {boolean} Whether the object is on screen or not. + */ + /* + static onScreen(camera: Camera = null): bool { + + if (camera == null) + { + camera = this._game.camera; + } + + this.getScreenXY(this._point, camera); + + return (this._point.x + this.width > 0) && (this._point.x < camera.width) && (this._point.y + this.height > 0) && (this._point.y < camera.height); + + } + */ + /** + * Call this to figure out the on-screen position of the object. + * + * @param point {Point} Takes a MicroPoint object and assigns the post-scrolled X and Y values of this object to it. + * @param camera {Camera} Specify which game camera you want. If null getScreenXY() will just grab the first global camera. + * + * @return {MicroPoint} The MicroPoint you passed in, or a new Point if you didn't pass one, containing the screen X and Y position of this object. + */ + /* + static getScreenXY(point: MicroPoint = null, camera: Camera = null): MicroPoint { + + if (point == null) + { + point = new MicroPoint(); + } + + if (camera == null) + { + camera = this._game.camera; + } + + point.x = this.x - camera.scroll.x * this.scrollFactor.x; + point.y = this.y - camera.scroll.y * this.scrollFactor.y; + point.x += (point.x > 0) ? 0.0000001 : -0.0000001; + point.y += (point.y > 0) ? 0.0000001 : -0.0000001; + + return point; + + } + */ + /** + * Set the world bounds that this GameObject can exist within based on the size of the current game world. + * + * @param action {number} The action to take if the object hits the world bounds, either OUT_OF_BOUNDS_KILL or OUT_OF_BOUNDS_STOP + */ + /* + static setBoundsFromWorld(action?: number = GameObject.OUT_OF_BOUNDS_STOP) { + + this.setBounds(this._game.world.bounds.x, this._game.world.bounds.y, this._game.world.bounds.width, this._game.world.bounds.height); + this.outOfBoundsAction = action; + + } + */ + /** + * Check whether this object is visible in a specific camera rectangle. + * @param camera {Rectangle} The rectangle you want to check. + * @return {boolean} Return true if bounds of this sprite intersects the given rectangle, otherwise return false. + */ + /* + static inCamera(camera: Rectangle, cameraOffsetX: number, cameraOffsetY: number): bool { + + // Object fixed in place regardless of the camera scrolling? Then it's always visible + if (this.scrollFactor.x == 0 && this.scrollFactor.y == 0) + { + return true; + } + + this._dx = (this.frameBounds.x - camera.x); + this._dy = (this.frameBounds.y - camera.y); + this._dw = this.frameBounds.width * this.scale.x; + this._dh = this.frameBounds.height * this.scale.y; + + return (camera.right > this._dx) && (camera.x < this._dx + this._dw) && (camera.bottom > this._dy) && (camera.y < this._dy + this._dh); + + } + */ + /** + * Handy for reviving game objects. + * Resets their existence flags and position. + * + * @param x {number} The new X position of this object. + * @param y {number} The new Y position of this object. + */ + /* + static reset(x: number, y: number) { + + this.revive(); + this.touching = Collision.NONE; + this.wasTouching = Collision.NONE; + this.x = x; + this.y = y; + this.last.x = x; + this.last.y = y; + this.velocity.x = 0; + this.velocity.y = 0; + + } + */ + /** + * Set the world bounds that this GameObject can exist within. By default a GameObject can exist anywhere + * in the world. But by setting the bounds (which are given in world dimensions, not screen dimensions) + * it can be stopped from leaving the world, or a section of it. + * + * @param x {number} x position of the bound + * @param y {number} y position of the bound + * @param width {number} width of its bound + * @param height {number} height of its bound + */ + function setBounds(x, y, width, height) { + //this.worldBounds = new Quad(x, y, width, height); + }; + return SpriteUtils; + })(); + Phaser.SpriteUtils = SpriteUtils; + /** + * This function creates a flat colored square image dynamically. + * @param width {number} The width of the sprite you want to generate. + * @param height {number} The height of the sprite you want to generate. + * @param [color] {number} specifies the color of the generated block. (format is 0xAARRGGBB) + * @return {Sprite} Sprite instance itself. + */ + /* + static makeGraphic(width: number, height: number, color: string = 'rgb(255,255,255)'): Sprite { + + this._texture = null; + this.width = width; + this.height = height; + this.fillColor = color; + this._dynamicTexture = false; + + return this; + } + */ + })(Phaser || (Phaser = {})); +var Phaser; +(function (Phaser) { + /// + /// + /// + /** + * Phaser - Components - Texture + * + * The Texture being used to render the Sprite. Either Image based on a DynamicTexture. + */ + (function (Components) { + var Texture = (function () { + function Texture(parent, key, canvas, context) { + if (typeof key === "undefined") { key = ''; } + if (typeof canvas === "undefined") { canvas = null; } + if (typeof context === "undefined") { context = null; } + /** + * Reference to the Image stored in the Game.Cache that is used as the texture for the Sprite. + */ + this._imageTexture = null; + /** + * Reference to the DynamicTexture that is used as the texture for the Sprite. + * @type {DynamicTexture} + */ + this._dynamicTexture = null; + /** + * Controls if the Sprite is rendered rotated or not. + * If renderRotation is false then the object can still rotate but it will never be rendered rotated. + * @type {boolean} + */ + this.renderRotation = true; + /** + * Flip the graphic horizontally (defaults to false) + * @type {boolean} + */ + this.flippedX = false; + /** + * Flip the graphic vertically (defaults to false) + * @type {boolean} + */ + this.flippedY = false; + this._game = parent.game; + this._sprite = parent; + this.canvas = canvas; + this.context = context; + this.alpha = 1; + this.flippedX = false; + this.flippedY = false; + if(key !== null) { + this.cacheKey = key; + this.loadImage(key); + } + } + Texture.prototype.setTo = /** + * Updates the texture being used to render the Sprite. + * Called automatically by SpriteUtils.loadTexture and SpriteUtils.loadDynamicTexture. + */ + function (image, dynamic) { + if (typeof image === "undefined") { image = null; } + if (typeof dynamic === "undefined") { dynamic = null; } + if(dynamic) { + this._dynamicTexture = dynamic; + this.texture = this._dynamicTexture.canvas; + } else { + this._imageTexture = image; + this.texture = this._imageTexture; + } + return this._sprite; + }; + Texture.prototype.loadImage = /** + * Sets a new graphic from the game cache to use as the texture for this Sprite. + * The graphic can be SpriteSheet or Texture Atlas. If you need to use a DynamicTexture see loadDynamicTexture. + * @param key {string} Key of the graphic you want to load for this sprite. + * @param clearAnimations {boolean} If this Sprite has a set of animation data already loaded you can choose to keep or clear it with this boolean + * @return {Sprite} Sprite instance itself. + */ + function (key, clearAnimations) { + if (typeof clearAnimations === "undefined") { clearAnimations = true; } + //if (clearAnimations && sprite.animations.frameData !== null) + //{ + // sprite.animations.destroy(); + //} + if(this._game.cache.getImage(key) !== null) { + this.setTo(this._game.cache.getImage(key), null); + if(this._game.cache.isSpriteSheet(key)) { + //sprite.animations.loadFrameData(sprite._game.cache.getFrameData(key)); + //sprite.collisionMask.width = sprite.animations.currentFrame.width; + //sprite.collisionMask.height = sprite.animations.currentFrame.height; + } else { + this._sprite.frameBounds.width = this.width; + this._sprite.frameBounds.height = this.height; + //sprite.collisionMask.width = sprite._texture.width; + //sprite.collisionMask.height = sprite._texture.height; + } + } + }; + Texture.prototype.loadDynamicTexture = /** + * Load a DynamicTexture as its texture. + * @param texture {DynamicTexture} The texture object to be used by this sprite. + * @return {Sprite} Sprite instance itself. + */ + function (texture) { + //if (sprite.animations.frameData !== null) + //{ + // sprite.animations.destroy(); + //} + this.setTo(null, texture); + this._sprite.frameBounds.width = this.width; + this._sprite.frameBounds.height = this.height; + }; + Object.defineProperty(Texture.prototype, "width", { + get: /** + * Getter only. The width of the texture. + * @type {number} + */ + function () { + if(this._dynamicTexture) { + return this._dynamicTexture.width; + } else { + return this._imageTexture.width; + } + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Texture.prototype, "height", { + get: /** + * Getter only. The height of the texture. + * @type {number} + */ + function () { + if(this._dynamicTexture) { + return this._dynamicTexture.height; + } else { + return this._imageTexture.height; + } + }, + enumerable: true, + configurable: true + }); + return Texture; + })(); + Components.Texture = Texture; + })(Phaser.Components || (Phaser.Components = {})); + var Components = Phaser.Components; +})(Phaser || (Phaser = {})); +/// +/// +/// +/// +/// +/** +* Phaser - Sprite +* +*/ +var Phaser; +(function (Phaser) { + var Sprite = (function () { + /** + * Create a new Sprite. + * + * @param game {Phaser.Game} Current game instance. + * @param [x] {number} the initial x position of the sprite. + * @param [y] {number} the initial y position of the sprite. + * @param [key] {string} Key of the graphic you want to load for this sprite. + * @param [width] {number} The width of the object. + * @param [height] {number} The height of the object. + */ + function Sprite(game, x, y, key, width, height) { + if (typeof x === "undefined") { x = 0; } + if (typeof y === "undefined") { y = 0; } + if (typeof key === "undefined") { key = null; } + if (typeof width === "undefined") { width = 16; } + if (typeof height === "undefined") { height = 16; } + this.game = game; + this.type = Phaser.Types.SPRITE; + this.render = game.renderer.renderSprite; + this.exists = true; + this.active = true; + this.visible = true; + this.alive = true; + this.frameBounds = new Phaser.Rectangle(x, y, width, height); + this.origin = new Phaser.Vec2(0, 0); + this.scrollFactor = new Phaser.Vec2(1, 1); + this.scale = new Phaser.Vec2(1, 1); + this.position = new Phaser.Components.Position(this, x, y); + this.texture = new Phaser.Components.Texture(this, key, game.stage.canvas, game.stage.context); + this.width = this.frameBounds.width; + this.height = this.frameBounds.height; + this.rotation = this.position.rotation; + } + Sprite.prototype.preUpdate = /** + * Pre-update is called right before update() on each object in the game loop. + */ + function () { + //this.last.x = this.frameBounds.x; + //this.last.y = this.frameBounds.y; + //this.collisionMask.preUpdate(); + }; + Sprite.prototype.update = /** + * Override this function to update your class's position and appearance. + */ + function () { + }; + Sprite.prototype.postUpdate = /** + * Automatically called after update() by the game loop. + */ + function () { + /* + this.animations.update(); + + if (this.moves) + { + this.updateMotion(); + } + + if (this.worldBounds != null) + { + if (this.outOfBoundsAction == GameObject.OUT_OF_BOUNDS_KILL) + { + if (this.x < this.worldBounds.x || this.x > this.worldBounds.right || this.y < this.worldBounds.y || this.y > this.worldBounds.bottom) + { + this.kill(); + } + } + else + { + if (this.x < this.worldBounds.x) + { + this.x = this.worldBounds.x; + } + else if (this.x > this.worldBounds.right) + { + this.x = this.worldBounds.right; + } + + if (this.y < this.worldBounds.y) + { + this.y = this.worldBounds.y; + } + else if (this.y > this.worldBounds.bottom) + { + this.y = this.worldBounds.bottom; + } + } + } + + this.collisionMask.update(); + + if (this.inputEnabled) + { + this.updateInput(); + } + + this.wasTouching = this.touching; + this.touching = Collision.NONE; + */ + }; + Sprite.prototype.destroy = /** + * Clean up memory. + */ + function () { + }; + Object.defineProperty(Sprite.prototype, "x", { + get: /** + * x value of the object. + */ + function () { + return this.position.world.x; + }, + set: function (value) { + this.position.world.x = value; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Sprite.prototype, "y", { + get: /** + * y value of the object. + */ + function () { + return this.position.world.y; + }, + set: function (value) { + this.position.world.y = value; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Sprite.prototype, "z", { + get: /** + * z value of the object. + */ + function () { + return this.position.z; + }, + set: function (value) { + this.position.z = value; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Sprite.prototype, "rotation", { + get: /** + * rotation value of the object. + */ + function () { + return this.position.rotation; + }, + set: function (value) { + this.position.rotation = value; + }, + enumerable: true, + configurable: true + }); + return Sprite; + })(); + Phaser.Sprite = Sprite; +})(Phaser || (Phaser = {})); +/// +/// +/** +* Phaser - CameraFX +* +* CameraFX controls all special effects applied to game Cameras. +*/ +var Phaser; +(function (Phaser) { + var CameraFX = (function () { + function CameraFX(game, parent) { + this._game = game; + this._parent = parent; + this._fx = []; + this.active = true; + this.visible = true; + } + CameraFX.prototype.add = /** + * Adds a new FX to the FXManager. + * The effect must be an object with at least one of the following methods: preUpdate, postUpdate, preRender, render or postRender. + * A new instance of the effect will be created and a reference to Game will be passed to the object constructor. + * @param {object} effect + * @return {any} + */ + function (effect) { + var result = false; + var newEffect = { + effect: { + }, + preUpdate: false, + postUpdate: false, + preRender: false, + render: false, + postRender: false + }; + if(typeof effect === 'function') { + newEffect.effect = new effect(this._game, this._parent); + } else { + throw new Error("Invalid object given to Phaser.CameraFX.add"); + } + // Check for methods now to avoid having to do this every loop + if(typeof newEffect.effect['preUpdate'] === 'function') { + newEffect.preUpdate = true; + result = true; + } + if(typeof newEffect.effect['postUpdate'] === 'function') { + newEffect.postUpdate = true; + result = true; + } + if(typeof newEffect.effect['preRender'] === 'function') { + newEffect.preRender = true; + result = true; + } + if(typeof newEffect.effect['render'] === 'function') { + newEffect.render = true; + result = true; + } + if(typeof newEffect.effect['postRender'] === 'function') { + newEffect.postRender = true; + result = true; + } + if(result == true) { + this._length = this._fx.push(newEffect); + return newEffect.effect; + } else { + return result; + } + }; + CameraFX.prototype.preUpdate = /** + * Pre-update is called at the start of the objects update cycle, before any other updates have taken place. + */ + function () { + if(this.active) { + for(var i = 0; i < this._length; i++) { + if(this._fx[i].preUpdate) { + this._fx[i].effect.preUpdate(); + } + } + } + }; + CameraFX.prototype.postUpdate = /** + * Post-update is called at the end of the objects update cycle, after other update logic has taken place. + */ + function () { + if(this.active) { + for(var i = 0; i < this._length; i++) { + if(this._fx[i].postUpdate) { + this._fx[i].effect.postUpdate(); + } + } + } + }; + CameraFX.prototype.preRender = /** + * Pre-render is called at the start of the object render cycle, before any transforms have taken place. + * It happens directly AFTER a canvas context.save has happened if added to a Camera. + * @param {Camera} camera + * @param {number} cameraX + * @param {number} cameraY + * @param {number} cameraWidth + * @param {number} cameraHeight + */ + function (camera, cameraX, cameraY, cameraWidth, cameraHeight) { + if(this.visible) { + for(var i = 0; i < this._length; i++) { + if(this._fx[i].preRender) { + this._fx[i].effect.preRender(camera, cameraX, cameraY, cameraWidth, cameraHeight); + } + } + } + }; + CameraFX.prototype.render = /** + * render is called during the objects render cycle, right after all transforms have finished, but before any children/image data is rendered. + * @param {Camera} camera + * @param {number} cameraX + * @param {number} cameraY + * @param {number} cameraWidth + * @param {number} cameraHeight + */ + function (camera, cameraX, cameraY, cameraWidth, cameraHeight) { + if(this.visible) { + for(var i = 0; i < this._length; i++) { + if(this._fx[i].preRender) { + this._fx[i].effect.preRender(camera, cameraX, cameraY, cameraWidth, cameraHeight); + } + } + } + }; + CameraFX.prototype.postRender = /** + * Post-render is called during the objects render cycle, after the children/image data has been rendered. + * It happens directly BEFORE a canvas context.restore has happened if added to a Camera. + */ + function (camera, cameraX, cameraY, cameraWidth, cameraHeight) { + if(this.visible) { + for(var i = 0; i < this._length; i++) { + if(this._fx[i].postRender) { + this._fx[i].effect.postRender(camera, cameraX, cameraY, cameraWidth, cameraHeight); + } + } + } + }; + CameraFX.prototype.destroy = /** + * Clear down this FXManager and null out references + */ + function () { + this._game = null; + this._fx = null; + }; + return CameraFX; + })(); + Phaser.CameraFX = CameraFX; +})(Phaser || (Phaser = {})); +/// +/// +/// +/// +/// +/// +/** +* Phaser - Camera +* +* A Camera is your view into the game world. It has a position, size, scale and rotation and renders only those objects +* within its field of view. The game automatically creates a single Stage sized camera on boot, but it can be changed and +* additional cameras created via the CameraManager. +*/ +var Phaser; +(function (Phaser) { + var Camera = (function () { + /** + * Instantiates a new camera at the specified location, with the specified size and zoom level. + * + * @param game {Phaser.Game} Current game instance. + * @param id {number} Unique identity. + * @param x {number} X location of the camera's display in pixels. Uses native, 1:1 resolution, ignores zoom. + * @param y {number} Y location of the camera's display in pixels. Uses native, 1:1 resolution, ignores zoom. + * @param width {number} The width of the camera display in pixels. + * @param height {number} The height of the camera display in pixels. + */ + function Camera(game, id, x, y, width, height) { + this._clip = false; + this._rotation = 0; + this._target = null; + /** + * Scale factor of the camera. + * @type {Vec2} + */ + this.scale = new Phaser.Vec2(1, 1); + /** + * Scrolling factor. + * @type {MicroPoint} + */ + this.scroll = new Phaser.Vec2(0, 0); + /** + * Camera bounds. + * @type {Rectangle} + */ + this.bounds = null; + /** + * Sprite moving inside this rectangle will not cause camera moving. + * @type {Rectangle} + */ + this.deadzone = null; + /** + * Disable the automatic camera canvas clipping when Camera is non-Stage sized. + * @type {Boolean} + */ + this.disableClipping = false; + /** + * Whether the camera background is opaque or not. If set to true the Camera is filled with + * the value of Camera.backgroundColor every frame. Normally you wouldn't enable this if the + * Camera is the full Stage size, as the Stage.backgroundColor has the same effect. But for + * multiple or mini cameras it can be very useful. + * @type {boolean} + */ + this.opaque = false; + /** + * The Background Color of the camera in css color string format, i.e. 'rgb(0,0,0)' or '#ff0000'. + * Not used if the Camera.opaque property is false. + * @type {string} + */ + this.backgroundColor = 'rgb(0,0,0)'; + /** + * Whether this camera visible or not. (default is true) + * @type {boolean} + */ + this.visible = true; + /** + * Alpha of the camera. (everything rendered to this camera will be affected) + * @type {number} + */ + this.alpha = 1; + /** + * The x position of the current input event in world coordinates. + * @type {number} + */ + this.inputX = 0; + /** + * The y position of the current input event in world coordinates. + * @type {number} + */ + this.inputY = 0; + this._game = game; + this.ID = id; + this._stageX = x; + this._stageY = y; + this.scaledX = x; + this.scaledY = x; + this.fx = new Phaser.CameraFX(this._game, this); + // The view into the world canvas we wish to render + this.worldView = new Phaser.Rectangle(0, 0, width, height); + this.checkClip(); + } + Camera.STYLE_LOCKON = 0; + Camera.STYLE_PLATFORMER = 1; + Camera.STYLE_TOPDOWN = 2; + Camera.STYLE_TOPDOWN_TIGHT = 3; + Camera.prototype.hide = /** + * Hides an object from this Camera. Hidden objects are not rendered. + * The object must implement a public cameraBlacklist property. + * + * @param object {Sprite/Group} The object this camera should ignore. + */ + function (object) { + if(this.isHidden(object) == false) { + object['cameraBlacklist'].push(this.ID); + } + }; + Camera.prototype.isHidden = /** + * Returns true if the object is hidden from this Camera. + * + * @param object {Sprite/Group} The object to check. + */ + function (object) { + if(object['cameraBlacklist'] && object['cameraBlacklist'].length > 0 && object['cameraBlacklist'].indexOf(this.ID) == -1) { + return true; + } + return false; + }; + Camera.prototype.show = /** + * Un-hides an object previously hidden to this Camera. + * The object must implement a public cameraBlacklist property. + * + * @param object {Sprite/Group} The object this camera should display. + */ + function (object) { + if(this.isHidden(object) == true) { + object['cameraBlacklist'].slice(object['cameraBlacklist'].indexOf(this.ID), 1); + } + }; + Camera.prototype.follow = /** + * Tells this camera object what sprite to track. + * @param target {Sprite} The object you want the camera to track. Set to null to not follow anything. + * @param [style] {number} Leverage one of the existing "deadzone" presets. If you use a custom deadzone, ignore this parameter and manually specify the deadzone after calling follow(). + */ + function (target, style) { + if (typeof style === "undefined") { style = Camera.STYLE_LOCKON; } + this._target = target; + var helper; + switch(style) { + case Camera.STYLE_PLATFORMER: + var w = this.width / 8; + var h = this.height / 3; + this.deadzone = new Phaser.Rectangle((this.width - w) / 2, (this.height - h) / 2 - h * 0.25, w, h); + break; + case Camera.STYLE_TOPDOWN: + helper = Math.max(this.width, this.height) / 4; + this.deadzone = new Phaser.Rectangle((this.width - helper) / 2, (this.height - helper) / 2, helper, helper); + break; + case Camera.STYLE_TOPDOWN_TIGHT: + helper = Math.max(this.width, this.height) / 8; + this.deadzone = new Phaser.Rectangle((this.width - helper) / 2, (this.height - helper) / 2, helper, helper); + break; + case Camera.STYLE_LOCKON: + default: + this.deadzone = null; + break; + } + }; + Camera.prototype.focusOnXY = /** + * Move the camera focus to this location instantly. + * @param x {number} X position. + * @param y {number} Y position. + */ + function (x, y) { + x += (x > 0) ? 0.0000001 : -0.0000001; + y += (y > 0) ? 0.0000001 : -0.0000001; + this.scroll.x = Math.round(x - this.worldView.halfWidth); + this.scroll.y = Math.round(y - this.worldView.halfHeight); + }; + Camera.prototype.focusOn = /** + * Move the camera focus to this location instantly. + * @param point {any} Point you want to focus. + */ + function (point) { + point.x += (point.x > 0) ? 0.0000001 : -0.0000001; + point.y += (point.y > 0) ? 0.0000001 : -0.0000001; + this.scroll.x = Math.round(point.x - this.worldView.halfWidth); + this.scroll.y = Math.round(point.y - this.worldView.halfHeight); + }; + Camera.prototype.setBounds = /** + * Specify the boundaries of the world or where the camera is allowed to move. + * + * @param x {number} The smallest X value of your world (usually 0). + * @param y {number} The smallest Y value of your world (usually 0). + * @param width {number} The largest X value of your world (usually the world width). + * @param height {number} The largest Y value of your world (usually the world height). + */ + function (x, y, width, height) { + if (typeof x === "undefined") { x = 0; } + if (typeof y === "undefined") { y = 0; } + if (typeof width === "undefined") { width = 0; } + if (typeof height === "undefined") { height = 0; } + if(this.bounds == null) { + this.bounds = new Phaser.Rectangle(); + } + this.bounds.setTo(x, y, width, height); + this.scroll.setTo(0, 0); + this.update(); + }; + Camera.prototype.update = /** + * Update focusing and scrolling. + */ + function () { + this.fx.preUpdate(); + if(this._target !== null) { + if(this.deadzone == null) { + this.focusOnXY(this._target.x, this._target.y); + } else { + var edge; + var targetX = this._target.x + ((this._target.x > 0) ? 0.0000001 : -0.0000001); + var targetY = this._target.y + ((this._target.y > 0) ? 0.0000001 : -0.0000001); + edge = targetX - this.deadzone.x; + if(this.scroll.x > edge) { + this.scroll.x = edge; + } + edge = targetX + this._target.width - this.deadzone.x - this.deadzone.width; + if(this.scroll.x < edge) { + this.scroll.x = edge; + } + edge = targetY - this.deadzone.y; + if(this.scroll.y > edge) { + this.scroll.y = edge; + } + edge = targetY + this._target.height - this.deadzone.y - this.deadzone.height; + if(this.scroll.y < edge) { + this.scroll.y = edge; + } + } + } + // Make sure we didn't go outside the cameras bounds + if(this.bounds !== null) { + if(this.scroll.x < this.bounds.left) { + this.scroll.x = this.bounds.left; + } + if(this.scroll.x > this.bounds.right - this.width) { + this.scroll.x = (this.bounds.right - this.width) + 1; + } + if(this.scroll.y < this.bounds.top) { + this.scroll.y = this.bounds.top; + } + if(this.scroll.y > this.bounds.bottom - this.height) { + this.scroll.y = (this.bounds.bottom - this.height) + 1; + } + } + this.worldView.x = this.scroll.x; + this.worldView.y = this.scroll.y; + // Input values + this.inputX = this.worldView.x + this._game.input.x; + this.inputY = this.worldView.y + this._game.input.y; + this.fx.postUpdate(); + }; + Camera.prototype.preRender = /** + * Camera preRender + */ + function () { + if(this.visible === false || this.alpha < 0.1) { + return; + } + if(this._rotation !== 0 || this._clip || this.scale.x !== 1 || this.scale.y !== 1) { + this._game.stage.context.save(); + } + this.fx.preRender(this, this._stageX, this._stageY, this.worldView.width, this.worldView.height); + if(this.alpha !== 1) { + this._game.stage.context.globalAlpha = this.alpha; + } + this.scaledX = this._stageX; + this.scaledY = this._stageY; + // Scale on + if(this.scale.x !== 1 || this.scale.y !== 1) { + this._game.stage.context.scale(this.scale.x, this.scale.y); + this.scaledX = this.scaledX / this.scale.x; + this.scaledY = this.scaledY / this.scale.y; + } + // Rotation - translate to the mid-point of the camera + if(this._rotation !== 0) { + this._game.stage.context.translate(this.scaledX + this.worldView.halfWidth, this.scaledY + this.worldView.halfHeight); + this._game.stage.context.rotate(this._rotation * (Math.PI / 180)); + // now shift back to where that should actually render + this._game.stage.context.translate(-(this.scaledX + this.worldView.halfWidth), -(this.scaledY + this.worldView.halfHeight)); + } + // Background + if(this.opaque) { + this._game.stage.context.fillStyle = this.backgroundColor; + this._game.stage.context.fillRect(this.scaledX, this.scaledY, this.worldView.width, this.worldView.height); + } + this.fx.render(this, this._stageX, this._stageY, this.worldView.width, this.worldView.height); + // Clip the camera so we don't get sprites appearing outside the edges + if(this._clip == true && this.disableClipping == false) { + this._game.stage.context.beginPath(); + this._game.stage.context.rect(this.scaledX, this.scaledY, this.worldView.width, this.worldView.height); + this._game.stage.context.closePath(); + this._game.stage.context.clip(); + } + }; + Camera.prototype.postRender = /** + * Camera postRender + */ + function () { + // Scale off + if(this.scale.x !== 1 || this.scale.y !== 1) { + this._game.stage.context.scale(1, 1); + } + this.fx.postRender(this, this.scaledX, this.scaledY, this.worldView.width, this.worldView.height); + if(this._rotation !== 0 || (this._clip && this.disableClipping == false)) { + this._game.stage.context.translate(0, 0); + } + if(this._rotation !== 0 || this._clip || this.scale.x !== 1 || this.scale.y !== 1) { + this._game.stage.context.restore(); + } + if(this.alpha !== 1) { + this._game.stage.context.globalAlpha = 1; + } + }; + Camera.prototype.setPosition = /** + * Set position of this camera. + * @param x {number} X position. + * @param y {number} Y position. + */ + function (x, y) { + this._stageX = x; + this._stageY = y; + this.checkClip(); + }; + Camera.prototype.setSize = /** + * Give this camera a new size. + * @param width {number} Width of new size. + * @param height {number} Height of new size. + */ + function (width, height) { + this.worldView.width = width; + this.worldView.height = height; + this.checkClip(); + }; + Camera.prototype.renderDebugInfo = /** + * Render debug infos. (including id, position, rotation, scrolling factor, bounds and some other properties) + * @param x {number} X position of the debug info to be rendered. + * @param y {number} Y position of the debug info to be rendered. + * @param [color] {number} color of the debug info to be rendered. (format is css color string) + */ + function (x, y, color) { + if (typeof color === "undefined") { color = 'rgb(255,255,255)'; } + this._game.stage.context.fillStyle = color; + this._game.stage.context.fillText('Camera ID: ' + this.ID + ' (' + this.worldView.width + ' x ' + this.worldView.height + ')', x, y); + this._game.stage.context.fillText('X: ' + this._stageX + ' Y: ' + this._stageY + ' Rotation: ' + this._rotation, x, y + 14); + this._game.stage.context.fillText('World X: ' + this.scroll.x.toFixed(1) + ' World Y: ' + this.scroll.y.toFixed(1), x, y + 28); + if(this.bounds) { + this._game.stage.context.fillText('Bounds: ' + this.bounds.width + ' x ' + this.bounds.height, x, y + 56); + } + }; + Camera.prototype.destroy = /** + * Destroys this camera, associated FX and removes itself from the CameraManager. + */ + function () { + this._game.world.cameras.removeCamera(this.ID); + this.fx.destroy(); + }; + Object.defineProperty(Camera.prototype, "x", { + get: function () { + return this._stageX; + }, + set: function (value) { + this._stageX = value; + this.checkClip(); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Camera.prototype, "y", { + get: function () { + return this._stageY; + }, + set: function (value) { + this._stageY = value; + this.checkClip(); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Camera.prototype, "width", { + get: function () { + return this.worldView.width; + }, + set: function (value) { + if(value > this._game.stage.width) { + value = this._game.stage.width; + } + this.worldView.width = value; + this.checkClip(); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Camera.prototype, "height", { + get: function () { + return this.worldView.height; + }, + set: function (value) { + if(value > this._game.stage.height) { + value = this._game.stage.height; + } + this.worldView.height = value; + this.checkClip(); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Camera.prototype, "rotation", { + get: function () { + return this._rotation; + }, + set: function (value) { + this._rotation = this._game.math.wrap(value, 360, 0); + }, + enumerable: true, + configurable: true + }); + Camera.prototype.checkClip = function () { + if(this._stageX !== 0 || this._stageY !== 0 || this.worldView.width < this._game.stage.width || this.worldView.height < this._game.stage.height) { + this._clip = true; + } else { + this._clip = false; + } + }; + return Camera; + })(); + Phaser.Camera = Camera; +})(Phaser || (Phaser = {})); +/// +/// +/** +* Phaser - CameraManager +* +* Your game only has one CameraManager instance and it's responsible for looking after, creating and destroying +* all of the cameras in the world. +*/ +var Phaser; +(function (Phaser) { + var CameraManager = (function () { + /** + * CameraManager constructor + * This will create a new Camera with position and size. + * + * @param x {number} X Position of the created camera. + * @param y {number} y Position of the created camera. + * @param width {number} Width of the created camera. + * @param height {number} Height of the created camera. + */ + function CameraManager(game, x, y, width, height) { + /** + * Local helper stores index of next created camera. + */ + this._cameraInstance = 0; + this._game = game; + this._cameras = []; + this.current = this.addCamera(x, y, width, height); + } + CameraManager.CAMERA_TYPE_ORTHOGRAPHIC = 0; + CameraManager.CAMERA_TYPE_ISOMETRIC = 1; + CameraManager.prototype.getAll = /** + * Get all the cameras. + * + * @returns {Camera[]} An array contains all the cameras. + */ + function () { + return this._cameras; + }; + CameraManager.prototype.update = /** + * Update cameras. + */ + function () { + this._cameras.forEach(function (camera) { + return camera.update(); + }); + }; + CameraManager.prototype.addCamera = /** + * Create a new camera with specific position and size. + * + * @param x {number} X position of the new camera. + * @param y {number} Y position of the new camera. + * @param width {number} Width of the new camera. + * @param height {number} Height of the new camera. + * @returns {Camera} The newly created camera object. + */ + function (x, y, width, height, type) { + if (typeof type === "undefined") { type = CameraManager.CAMERA_TYPE_ORTHOGRAPHIC; } + var newCam = new Phaser.Camera(this._game, this._cameraInstance, x, y, width, height); + this._cameras.push(newCam); + this._cameraInstance++; + return newCam; + }; + CameraManager.prototype.removeCamera = /** + * Remove a new camera with its id. + * + * @param id {number} ID of the camera you want to remove. + * @returns {boolean} True if successfully removed the camera, otherwise return false. + */ + function (id) { + for(var c = 0; c < this._cameras.length; c++) { + if(this._cameras[c].ID == id) { + if(this.current.ID === this._cameras[c].ID) { + this.current = null; + } + this._cameras.splice(c, 1); + return true; + } + } + return false; + }; + CameraManager.prototype.destroy = /** + * Clean up memory. + */ + function () { + this._cameras.length = 0; + this.current = this.addCamera(0, 0, this._game.stage.width, this._game.stage.height); + }; + return CameraManager; + })(); + Phaser.CameraManager = CameraManager; +})(Phaser || (Phaser = {})); +var Phaser; +(function (Phaser) { + /// + /** + * Phaser - Easing - Back + * + * For use with Phaser.Tween + */ + (function (Easing) { + var Back = (function () { + function Back() { } + Back.In = function In(k) { + var s = 1.70158; + return k * k * ((s + 1) * k - s); + }; + Back.Out = function Out(k) { + var s = 1.70158; + return --k * k * ((s + 1) * k + s) + 1; + }; + Back.InOut = function InOut(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); + }; + return Back; + })(); + Easing.Back = Back; + })(Phaser.Easing || (Phaser.Easing = {})); + var Easing = Phaser.Easing; +})(Phaser || (Phaser = {})); +var Phaser; +(function (Phaser) { + /// + /** + * Phaser - Easing - Bounce + * + * For use with Phaser.Tween + */ + (function (Easing) { + var Bounce = (function () { + function Bounce() { } + Bounce.In = function In(k) { + return 1 - Phaser.Easing.Bounce.Out(1 - k); + }; + Bounce.Out = function Out(k) { + if(k < (1 / 2.75)) { + return 7.5625 * k * k; + } else if(k < (2 / 2.75)) { + return 7.5625 * (k -= (1.5 / 2.75)) * k + 0.75; + } else if(k < (2.5 / 2.75)) { + return 7.5625 * (k -= (2.25 / 2.75)) * k + 0.9375; + } else { + return 7.5625 * (k -= (2.625 / 2.75)) * k + 0.984375; + } + }; + Bounce.InOut = function InOut(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; + }; + return Bounce; + })(); + Easing.Bounce = Bounce; + })(Phaser.Easing || (Phaser.Easing = {})); + var Easing = Phaser.Easing; +})(Phaser || (Phaser = {})); +var Phaser; +(function (Phaser) { + /// + /** + * Phaser - Easing - Circular + * + * For use with Phaser.Tween + */ + (function (Easing) { + var Circular = (function () { + function Circular() { } + Circular.In = function In(k) { + return 1 - Math.sqrt(1 - k * k); + }; + Circular.Out = function Out(k) { + return Math.sqrt(1 - (--k * k)); + }; + Circular.InOut = function InOut(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 Circular; + })(); + Easing.Circular = Circular; + })(Phaser.Easing || (Phaser.Easing = {})); + var Easing = Phaser.Easing; +})(Phaser || (Phaser = {})); +var Phaser; +(function (Phaser) { + /// + /** + * Phaser - Easing - Cubic + * + * For use with Phaser.Tween + */ + (function (Easing) { + var Cubic = (function () { + function Cubic() { } + Cubic.In = function In(k) { + return k * k * k; + }; + Cubic.Out = function Out(k) { + return --k * k * k + 1; + }; + Cubic.InOut = function InOut(k) { + if((k *= 2) < 1) { + return 0.5 * k * k * k; + } + return 0.5 * ((k -= 2) * k * k + 2); + }; + return Cubic; + })(); + Easing.Cubic = Cubic; + })(Phaser.Easing || (Phaser.Easing = {})); + var Easing = Phaser.Easing; +})(Phaser || (Phaser = {})); +var Phaser; +(function (Phaser) { + /// + /** + * Phaser - Easing - Elastic + * + * For use with Phaser.Tween + */ + (function (Easing) { + var Elastic = (function () { + function Elastic() { } + Elastic.In = function In(k) { + var s, a = 0.1, p = 0.4; + if(k === 0) { + return 0; + } + if(k === 1) { + return 1; + } + if(!a || a < 1) { + a = 1; + s = p / 4; + } else { + s = p * Math.asin(1 / a) / (2 * Math.PI); + } + return -(a * Math.pow(2, 10 * (k -= 1)) * Math.sin((k - s) * (2 * Math.PI) / p)); + }; + Elastic.Out = function Out(k) { + var s, a = 0.1, p = 0.4; + if(k === 0) { + return 0; + } + if(k === 1) { + return 1; + } + if(!a || a < 1) { + a = 1; + s = p / 4; + } else { + s = p * Math.asin(1 / a) / (2 * Math.PI); + } + return (a * Math.pow(2, -10 * k) * Math.sin((k - s) * (2 * Math.PI) / p) + 1); + }; + Elastic.InOut = function InOut(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; + }; + return Elastic; + })(); + Easing.Elastic = Elastic; + })(Phaser.Easing || (Phaser.Easing = {})); + var Easing = Phaser.Easing; +})(Phaser || (Phaser = {})); +var Phaser; +(function (Phaser) { + /// + /** + * Phaser - Easing - Exponential + * + * For use with Phaser.Tween + */ + (function (Easing) { + var Exponential = (function () { + function Exponential() { } + Exponential.In = function In(k) { + return k === 0 ? 0 : Math.pow(1024, k - 1); + }; + Exponential.Out = function Out(k) { + return k === 1 ? 1 : 1 - Math.pow(2, -10 * k); + }; + Exponential.InOut = function InOut(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); + }; + return Exponential; + })(); + Easing.Exponential = Exponential; + })(Phaser.Easing || (Phaser.Easing = {})); + var Easing = Phaser.Easing; +})(Phaser || (Phaser = {})); +var Phaser; +(function (Phaser) { + /// + /** + * Phaser - Easing - Linear + * + * For use with Phaser.Tween + */ + (function (Easing) { + var Linear = (function () { + function Linear() { } + Linear.None = function None(k) { + return k; + }; + return Linear; + })(); + Easing.Linear = Linear; + })(Phaser.Easing || (Phaser.Easing = {})); + var Easing = Phaser.Easing; +})(Phaser || (Phaser = {})); +var Phaser; +(function (Phaser) { + /// + /** + * Phaser - Easing - Quadratic + * + * For use with Phaser.Tween + */ + (function (Easing) { + var Quadratic = (function () { + function Quadratic() { } + Quadratic.In = function In(k) { + return k * k; + }; + Quadratic.Out = function Out(k) { + return k * (2 - k); + }; + Quadratic.InOut = function InOut(k) { + if((k *= 2) < 1) { + return 0.5 * k * k; + } + return -0.5 * (--k * (k - 2) - 1); + }; + return Quadratic; + })(); + Easing.Quadratic = Quadratic; + })(Phaser.Easing || (Phaser.Easing = {})); + var Easing = Phaser.Easing; +})(Phaser || (Phaser = {})); +var Phaser; +(function (Phaser) { + /// + /** + * Phaser - Easing - Quartic + * + * For use with Phaser.Tween + */ + (function (Easing) { + var Quartic = (function () { + function Quartic() { } + Quartic.In = function In(k) { + return k * k * k * k; + }; + Quartic.Out = function Out(k) { + return 1 - (--k * k * k * k); + }; + Quartic.InOut = function InOut(k) { + if((k *= 2) < 1) { + return 0.5 * k * k * k * k; + } + return -0.5 * ((k -= 2) * k * k * k - 2); + }; + return Quartic; + })(); + Easing.Quartic = Quartic; + })(Phaser.Easing || (Phaser.Easing = {})); + var Easing = Phaser.Easing; +})(Phaser || (Phaser = {})); +var Phaser; +(function (Phaser) { + /// + /** + * Phaser - Easing - Quintic + * + * For use with Phaser.Tween + */ + (function (Easing) { + var Quintic = (function () { + function Quintic() { } + Quintic.In = function In(k) { + return k * k * k * k * k; + }; + Quintic.Out = function Out(k) { + return --k * k * k * k * k + 1; + }; + Quintic.InOut = function InOut(k) { + if((k *= 2) < 1) { + return 0.5 * k * k * k * k * k; + } + return 0.5 * ((k -= 2) * k * k * k * k + 2); + }; + return Quintic; + })(); + Easing.Quintic = Quintic; + })(Phaser.Easing || (Phaser.Easing = {})); + var Easing = Phaser.Easing; +})(Phaser || (Phaser = {})); +var Phaser; +(function (Phaser) { + /// + /** + * Phaser - Easing - Sinusoidal + * + * For use with Phaser.Tween + */ + (function (Easing) { + var Sinusoidal = (function () { + function Sinusoidal() { } + Sinusoidal.In = function In(k) { + return 1 - Math.cos(k * Math.PI / 2); + }; + Sinusoidal.Out = function Out(k) { + return Math.sin(k * Math.PI / 2); + }; + Sinusoidal.InOut = function InOut(k) { + return 0.5 * (1 - Math.cos(Math.PI * k)); + }; + return Sinusoidal; + })(); + Easing.Sinusoidal = Sinusoidal; + })(Phaser.Easing || (Phaser.Easing = {})); + var Easing = Phaser.Easing; +})(Phaser || (Phaser = {})); +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/** +* Phaser - Tween +* +* Based heavily on tween.js by sole (https://github.com/sole/tween.js) converted to TypeScript and integrated into Phaser +*/ +var Phaser; +(function (Phaser) { + var Tween = (function () { + /** + * Tween constructor + * Create a new Tween. + * + * @param object {object} Target object will be affected by this tween. + * @param game {Phaser.Game} Current game instance. + */ + function Tween(object, game) { + /** + * Reference to the target object. + * @type {object} + */ + this._object = null; + this._pausedTime = 0; + /** + * Start values container. + * @type {object} + */ + this._valuesStart = { + }; + /** + * End values container. + * @type {object} + */ + this._valuesEnd = { + }; + /** + * How long this tween will perform. + * @type {number} + */ + this._duration = 1000; + this._delayTime = 0; + this._startTime = null; + /** + * Contains chained tweens. + * @type {Tweens[]} + */ + this._chainedTweens = []; + this._object = object; + this._game = game; + this._manager = this._game.tweens; + this._interpolationFunction = this._game.math.linearInterpolation; + this._easingFunction = Phaser.Easing.Linear.None; + this._chainedTweens = []; + this.onStart = new Phaser.Signal(); + this.onUpdate = new Phaser.Signal(); + this.onComplete = new Phaser.Signal(); + } + Tween.prototype.to = /** + * Configure the Tween + * @param properties {object} Propertis you want to tween. + * @param [duration] {number} duration of this tween. + * @param [ease] {any} Easing function. + * @param [autoStart] {boolean} Whether this tween will start automatically or not. + * @param [delay] {number} delay before this tween will start, defaults to 0 (no delay) + * @return {Tween} Itself. + */ + function (properties, duration, ease, autoStart, delay) { + if (typeof duration === "undefined") { duration = 1000; } + if (typeof ease === "undefined") { ease = null; } + if (typeof autoStart === "undefined") { autoStart = false; } + if (typeof delay === "undefined") { delay = 0; } + this._duration = duration; + // If properties isn't an object this will fail, sanity check it here somehow? + this._valuesEnd = properties; + if(ease !== null) { + this._easingFunction = ease; + } + if(delay > 0) { + this._delayTime = delay; + } + if(autoStart === true) { + return this.start(); + } else { + return this; + } + }; + Tween.prototype.start = /** + * Start to tween. + */ + function () { + if(this._game === null || this._object === null) { + return; + } + this._manager.add(this); + this.onStart.dispatch(this._object); + this._startTime = this._game.time.now + this._delayTime; + for(var property in this._valuesEnd) { + // This prevents the interpolation of null values or of non-existing properties + if(this._object[property] === null || !(property in this._object)) { + throw Error('Phaser.Tween interpolation of null value of non-existing property'); + continue; + } + // check if an Array was provided as property value + if(this._valuesEnd[property] instanceof Array) { + if(this._valuesEnd[property].length === 0) { + continue; + } + // create a local copy of the Array with the start value at the front + this._valuesEnd[property] = [ + this._object[property] + ].concat(this._valuesEnd[property]); + } + this._valuesStart[property] = this._object[property]; + } + return this; + }; + Tween.prototype.clear = function () { + this._chainedTweens = []; + this.onStart.removeAll(); + this.onUpdate.removeAll(); + this.onComplete.removeAll(); + return this; + }; + Tween.prototype.stop = /** + * Stop tweening. + */ + function () { + if(this._manager !== null) { + this._manager.remove(this); + } + this.onComplete.dispose(); + return this; + }; + Object.defineProperty(Tween.prototype, "parent", { + set: function (value) { + this._game = value; + this._manager = this._game.tweens; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Tween.prototype, "delay", { + get: function () { + return this._delayTime; + }, + set: function (amount) { + this._delayTime = amount; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Tween.prototype, "easing", { + get: function () { + return this._easingFunction; + }, + set: function (easing) { + this._easingFunction = easing; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Tween.prototype, "interpolation", { + get: function () { + return this._interpolationFunction; + }, + set: function (interpolation) { + this._interpolationFunction = interpolation; + }, + enumerable: true, + configurable: true + }); + Tween.prototype.chain = /** + * Add another chained tween, which will start automatically when the one before it completes. + * @param tween {Phaser.Tween} Tween object you want to chain with this. + * @return {Phaser.Tween} Itselfe. + */ + function (tween) { + this._chainedTweens.push(tween); + return this; + }; + Tween.prototype.update = /** + * Update tweening. + * @param time {number} Current time from game clock. + * @return {boolean} Return false if this completed and no need to update, otherwise return true. + */ + function (time) { + if(this._game.paused == true) { + if(this._pausedTime == 0) { + this._pausedTime = time; + } + } else { + // Ok we aren't paused, but was there some time gained? + if(this._pausedTime > 0) { + this._startTime += (time - this._pausedTime); + this._pausedTime = 0; + } + } + if(time < this._startTime) { + return true; + } + var elapsed = (time - this._startTime) / this._duration; + elapsed = elapsed > 1 ? 1 : elapsed; + var value = this._easingFunction(elapsed); + for(var property in this._valuesStart) { + // Add checks for object, array, numeric up front + if(this._valuesEnd[property] instanceof Array) { + this._object[property] = this._interpolationFunction(this._valuesEnd[property], value); + } else { + this._object[property] = this._valuesStart[property] + (this._valuesEnd[property] - this._valuesStart[property]) * value; + } + } + this.onUpdate.dispatch(this._object, value); + if(elapsed == 1) { + this.onComplete.dispatch(this._object); + for(var i = 0; i < this._chainedTweens.length; i++) { + this._chainedTweens[i].start(); + } + return false; + } + return true; + }; + return Tween; + })(); + Phaser.Tween = Tween; +})(Phaser || (Phaser = {})); +/// +/// /** * Phaser - GameObjectFactory * @@ -8262,19 +5341,19 @@ var Phaser; * @returns {Camera} The newly created camera object. */ function (x, y, width, height) { - return this._world.createCamera(x, y, width, height); + return this._world.cameras.addCamera(x, y, width, height); }; - GameObjectFactory.prototype.geomSprite = /** + GameObjectFactory.prototype.sprite = /** * Create a new GeomSprite with specific position. * * @param x {number} X position of the new geom sprite. * @param y {number} Y position of the new geom sprite. * @returns {GeomSprite} The newly created geom sprite object. */ - function (x, y) { - return this._world.createGeomSprite(x, y); - }; - GameObjectFactory.prototype.sprite = /** + //public geomSprite(x: number, y: number): GeomSprite { + // return this._world.group.add(new GeomSprite(this._game, x, y)); + //} + /** * Create a new Sprite with specific position and sprite sheet key. * * @param x {number} X position of the new sprite. @@ -8284,7 +5363,7 @@ var Phaser; */ function (x, y, key) { if (typeof key === "undefined") { key = ''; } - return this._world.createSprite(x, y, key); + return this._world.group.add(new Phaser.Sprite(this._game, x, y, key)); }; GameObjectFactory.prototype.dynamicTexture = /** * Create a new DynamicTexture with specific size. @@ -8294,7 +5373,7 @@ var Phaser; * @returns {DynamicTexture} The newly created dynamic texture object. */ function (width, height) { - return this._world.createDynamicTexture(width, height); + return new Phaser.DynamicTexture(this._game, width, height); }; GameObjectFactory.prototype.group = /** * Create a new object container. @@ -8304,17 +5383,17 @@ var Phaser; */ function (maxSize) { if (typeof maxSize === "undefined") { maxSize = 0; } - return this._world.createGroup(maxSize); + return this._world.group.add(new Phaser.Group(this._game, maxSize)); }; - GameObjectFactory.prototype.particle = /** + GameObjectFactory.prototype.tween = /** * Create a new Particle. * * @return {Particle} The newly created particle object. */ - function () { - return this._world.createParticle(); - }; - GameObjectFactory.prototype.emitter = /** + //public particle(): Particle { + // return new Particle(this._game); + //} + /** * Create a new Emitter. * * @param x {number} Optional, x position of the emitter. @@ -8322,13 +5401,10 @@ var Phaser; * @param size {number} Optional, size of this emitter. * @return {Emitter} The newly created emitter object. */ - function (x, y, size) { - if (typeof x === "undefined") { x = 0; } - if (typeof y === "undefined") { y = 0; } - if (typeof size === "undefined") { size = 0; } - return this._world.createEmitter(x, y, size); - }; - GameObjectFactory.prototype.scrollZone = /** + //public emitter(x?: number = 0, y?: number = 0, size?: number = 0): Emitter { + // return this._world.group.add(new Emitter(this._game, x, y, size)); + //} + /** * Create a new ScrollZone object with image key, position and size. * * @param key {string} Key to a image you wish this object to use. @@ -8338,14 +5414,10 @@ var Phaser; * @param height {number} Height of this object. * @returns {ScrollZone} The newly created scroll zone object. */ - function (key, x, y, width, height) { - if (typeof x === "undefined") { x = 0; } - if (typeof y === "undefined") { y = 0; } - if (typeof width === "undefined") { width = 0; } - if (typeof height === "undefined") { height = 0; } - return this._world.createScrollZone(key, x, y, width, height); - }; - GameObjectFactory.prototype.tilemap = /** + //public scrollZone(key: string, x?: number = 0, y?: number = 0, width?: number = 0, height?: number = 0): ScrollZone { + // return this._world.group.add(new ScrollZone(this._game, key, x, y, width, height)); + //} + /** * Create a new Tilemap. * * @param key {string} Key for tileset image. @@ -8356,13 +5428,10 @@ var Phaser; * @param [tileHeight] {number} height of each tile. * @return {Tilemap} The newly created tilemap object. */ - function (key, mapData, format, resizeWorld, tileWidth, tileHeight) { - if (typeof resizeWorld === "undefined") { resizeWorld = true; } - if (typeof tileWidth === "undefined") { tileWidth = 0; } - if (typeof tileHeight === "undefined") { tileHeight = 0; } - return this._world.createTilemap(key, mapData, format, resizeWorld, tileWidth, tileHeight); - }; - GameObjectFactory.prototype.tween = /** + //public tilemap(key: string, mapData: string, format: number, resizeWorld: bool = true, tileWidth?: number = 0, tileHeight?: number = 0): Tilemap { + // return this._world.group.add(new Tilemap(this._game, key, mapData, format, resizeWorld, tileWidth, tileHeight)); + //} + /** * Create a tween object for a specific object. * * @param obj Object you wish the tween will affect. @@ -8381,47 +5450,47 @@ var Phaser; function (sprite) { return this._world.group.add(sprite); }; - GameObjectFactory.prototype.existingGeomSprite = /** + GameObjectFactory.prototype.existingTween = /** * Add an existing GeomSprite to the current world. * Note: This doesn't check or update the objects reference to Game. If that is wrong, all kinds of things will break. * * @param sprite The GeomSprite to add to the Game World * @return {Phaser.GeomSprite} The GeomSprite object */ - function (sprite) { - return this._world.group.add(sprite); - }; - GameObjectFactory.prototype.existingEmitter = /** + //public existingGeomSprite(sprite: GeomSprite): GeomSprite { + // return this._world.group.add(sprite); + //} + /** * Add an existing Emitter to the current world. * Note: This doesn't check or update the objects reference to Game. If that is wrong, all kinds of things will break. * * @param emitter The Emitter to add to the Game World * @return {Phaser.Emitter} The Emitter object */ - function (emitter) { - return this._world.group.add(emitter); - }; - GameObjectFactory.prototype.existingScrollZone = /** + //public existingEmitter(emitter: Emitter): Emitter { + // return this._world.group.add(emitter); + //} + /** * Add an existing ScrollZone to the current world. * Note: This doesn't check or update the objects reference to Game. If that is wrong, all kinds of things will break. * * @param scrollZone The ScrollZone to add to the Game World * @return {Phaser.ScrollZone} The ScrollZone object */ - function (scrollZone) { - return this._world.group.add(scrollZone); - }; - GameObjectFactory.prototype.existingTilemap = /** + //public existingScrollZone(scrollZone: ScrollZone): ScrollZone { + // return this._world.group.add(scrollZone); + //} + /** * Add an existing Tilemap to the current world. * Note: This doesn't check or update the objects reference to Game. If that is wrong, all kinds of things will break. * * @param tilemap The Tilemap to add to the Game World * @return {Phaser.Tilemap} The Tilemap object */ - function (tilemap) { - return this._world.group.add(tilemap); - }; - GameObjectFactory.prototype.existingTween = /** + //public existingTilemap(tilemap: Tilemap): Tilemap { + // return this._world.group.add(tilemap); + //} + /** * Add an existing Tween to the current world. * Note: This doesn't check or update the objects reference to Game. If that is wrong, all kinds of things will break. * @@ -8435,8 +5504,35 @@ var Phaser; })(); Phaser.GameObjectFactory = GameObjectFactory; })(Phaser || (Phaser = {})); -/// -/// +var Phaser; +(function (Phaser) { + /** + * Constants used to define game object types (faster than doing typeof object checks in core loops) + */ + var Types = (function () { + function Types() { } + Types.RENDERER_AUTO_DETECT = 0; + Types.RENDERER_HEADLESS = 1; + Types.RENDERER_CANVAS = 2; + Types.RENDERER_WEBGL = 3; + Types.GROUP = 0; + Types.SPRITE = 1; + Types.GEOMSPRITE = 2; + Types.PARTICLE = 3; + Types.EMITTER = 4; + Types.TILEMAP = 5; + Types.SCROLLZONE = 6; + Types.GEOM_POINT = 0; + Types.GEOM_CIRCLE = 1; + Types.GEOM_RECTANGLE = 2; + Types.GEOM_LINE = 3; + Types.GEOM_POLYGON = 4; + return Types; + })(); + Phaser.Types = Types; +})(Phaser || (Phaser = {})); +/// +/// /** * Phaser - Group * @@ -8444,11 +5540,9 @@ var Phaser; */ var Phaser; (function (Phaser) { - var Group = (function (_super) { - __extends(Group, _super); - function Group(game, MaxSize) { - if (typeof MaxSize === "undefined") { MaxSize = 0; } - _super.call(this, game); + var Group = (function () { + function Group(game, maxSize) { + if (typeof maxSize === "undefined") { maxSize = 0; } /** * You can set a globalCompositeOperation that will be applied before the render method is called on this Groups children. * This is useful if you wish to apply an effect like 'lighten' to a whole group of children as it saves doing it one-by-one. @@ -8462,54 +5556,30 @@ var Phaser; * Set to 0 to disable. */ this.alpha = 0; - this.isGroup = true; + this.game = game; + this.type = Phaser.Types.GROUP; + this.exists = true; + this.visible = true; this.members = []; this.length = 0; - this._maxSize = MaxSize; + this._maxSize = maxSize; this._marker = 0; this._sortIndex = null; this.cameraBlacklist = []; } Group.ASCENDING = -1; Group.DESCENDING = 1; - Group.prototype.hideFromCamera = /** - * If you do not wish this object to be visible to a specific camera, pass the camera here. - * - * @param camera {Camera} The specific camera. - */ - function (camera) { - if(this.cameraBlacklist.indexOf(camera.ID) == -1) { - this.cameraBlacklist.push(camera.ID); - } - }; - Group.prototype.showToCamera = /** - * Make this object only visible to a specific camera. - * - * @param camera {Camera} The camera you wish it to be visible. - */ - function (camera) { - if(this.cameraBlacklist.indexOf(camera.ID) !== -1) { - this.cameraBlacklist.slice(this.cameraBlacklist.indexOf(camera.ID), 1); - } - }; - Group.prototype.clearCameraList = /** - * This clears the camera black list, making the GameObject visible to all cameras. - */ - function () { - this.cameraBlacklist.length = 0; - }; Group.prototype.destroy = /** * Override this function to handle any deleting or "shutdown" type operations you might need, * such as removing traditional Flash children like Basic objects. */ function () { if(this.members != null) { - var basic; - var i = 0; - while(i < this.length) { - basic = this.members[i++]; - if(basic != null) { - basic.destroy(); + this._i = 0; + while(this._i < this.length) { + this._member = this.members[this._i++]; + if(this._member != null) { + this._member.destroy(); } } this.members.length = 0; @@ -8517,56 +5587,49 @@ var Phaser; this._sortIndex = null; }; Group.prototype.update = /** - * Automatically goes through and calls update on everything you added. + * Calls update on all members of this Group who have a status of active=true and exists=true + * You can also call Object.update directly, which will bypass the active/exists check. */ function (forceUpdate) { if (typeof forceUpdate === "undefined") { forceUpdate = false; } - if(this.ignoreGlobalUpdate && forceUpdate == false) { - return; - } - var basic; - var i = 0; - while(i < this.length) { - basic = this.members[i++]; - if((basic != null) && basic.exists && basic.active && basic.ignoreGlobalUpdate == false) { - basic.preUpdate(); - basic.update(forceUpdate); - basic.postUpdate(); + this._i = 0; + while(this._i < this.length) { + this._member = this.members[this._i++]; + if(this._member != null && this._member.exists && this._member.active) { + this._member.preUpdate(); + this._member.update(forceUpdate); + this._member.postUpdate(); } } }; Group.prototype.render = /** - * Automatically goes through and calls render on everything you added. + * Calls render on all members of this Group who have a status of visible=true and exists=true + * You can also call Object.render directly, which will bypass the visible/exists check. */ - function (camera, cameraOffsetX, cameraOffsetY, forceRender) { - if (typeof forceRender === "undefined") { forceRender = false; } - if(this.cameraBlacklist.indexOf(camera.ID) !== -1) { - return; - } - if(this.ignoreGlobalRender && forceRender == false) { + function (camera) { + if(camera.isHidden(this) == true) { return; } if(this.globalCompositeOperation) { - this._game.stage.context.save(); - this._game.stage.context.globalCompositeOperation = this.globalCompositeOperation; + this.game.stage.context.save(); + this.game.stage.context.globalCompositeOperation = this.globalCompositeOperation; } if(this.alpha > 0) { - var prevAlpha = this._game.stage.context.globalAlpha; - this._game.stage.context.globalAlpha = this.alpha; + this._prevAlpha = this.game.stage.context.globalAlpha; + this.game.stage.context.globalAlpha = this.alpha; } - var basic; - var i = 0; - while(i < this.length) { - basic = this.members[i++]; - if((basic != null) && basic.exists && basic.visible && basic.ignoreGlobalRender == false) { - basic.render(camera, cameraOffsetX, cameraOffsetY, forceRender); + this._i = 0; + while(this._i < this.length) { + this._member = this.members[this._i++]; + if(this._member != null && this._member.exists && this._member.visible && camera.isHidden(this._member) == false) { + this._member.render(camera, this._member); } } if(this.alpha > 0) { - this._game.stage.context.globalAlpha = prevAlpha; + this.game.stage.context.globalAlpha = this._prevAlpha; } if(this.globalCompositeOperation) { - this._game.stage.context.restore(); + this.game.stage.context.restore(); } }; Object.defineProperty(Group.prototype, "maxSize", { @@ -8584,17 +5647,16 @@ var Phaser; if(this._marker >= this._maxSize) { this._marker = 0; } - if((this._maxSize == 0) || (this.members == null) || (this._maxSize >= this.members.length)) { + if(this._maxSize == 0 || this.members == null || (this._maxSize >= this.members.length)) { return; } //If the max size has shrunk, we need to get rid of some objects - var basic; - var i = this._maxSize; - var l = this.members.length; - while(i < l) { - basic = this.members[i++]; - if(basic != null) { - basic.destroy(); + this._i = this._maxSize; + this._length = this.members.length; + while(this._i < this._length) { + this._member = this.members[this._i++]; + if(this._member != null) { + this._member.destroy(); } } this.length = this.members.length = this._maxSize; @@ -8614,28 +5676,28 @@ var Phaser; * @param {Basic} Object The object you want to add to the group. * @return {Basic} The same Basic object that was passed in. */ - function (Object) { + function (object) { //Don't bother adding an object twice. if(this.members.indexOf(Object) >= 0) { - return Object; + return object; } //First, look for a null entry where we can add the object. - var i = 0; - var l = this.members.length; - while(i < l) { - if(this.members[i] == null) { - this.members[i] = Object; - if(i >= this.length) { - this.length = i + 1; + this._i = 0; + this._length = this.members.length; + while(this._i < this._length) { + if(this.members[this._i] == null) { + this.members[this._i] = object; + if(this._i >= this.length) { + this.length = this._i + 1; } - return Object; + return object; } - i++; + this._i++; } //Failing that, expand the array (if we can) and add the object. if(this._maxSize > 0) { if(this.members.length >= this._maxSize) { - return Object; + return object; } else if(this.members.length * 2 <= this._maxSize) { this.members.length *= 2; } else { @@ -8646,9 +5708,9 @@ var Phaser; } //If we made it this far, then we successfully grew the group, //and we can go ahead and add the object at the first open slot. - this.members[i] = Object; - this.length = i + 1; - return Object; + this.members[this._i] = object; + this.length = this._i + 1; + return object; }; Group.prototype.recycle = /** * Recycling is designed to help you reuse game objects without always re-allocating or "newing" them. @@ -8673,31 +5735,30 @@ var Phaser; * * @return {any} A reference to the object that was created. Don't forget to cast it back to the Class you want (e.g. myObject = myGroup.recycle(myObjectClass) as myObjectClass;). */ - function (ObjectClass) { - if (typeof ObjectClass === "undefined") { ObjectClass = null; } - var basic; + function (objectClass) { + if (typeof objectClass === "undefined") { objectClass = null; } if(this._maxSize > 0) { if(this.length < this._maxSize) { - if(ObjectClass == null) { + if(objectClass == null) { return null; } - return this.add(new ObjectClass(this._game)); + return this.add(new objectClass(this.game)); } else { - basic = this.members[this._marker++]; + this._member = this.members[this._marker++]; if(this._marker >= this._maxSize) { this._marker = 0; } - return basic; + return this._member; } } else { - basic = this.getFirstAvailable(ObjectClass); - if(basic != null) { - return basic; + this._member = this.getFirstAvailable(objectClass); + if(this._member != null) { + return this._member; } - if(ObjectClass == null) { + if(objectClass == null) { return null; } - return this.add(new ObjectClass(this._game)); + return this.add(new objectClass(this.game)); } }; Group.prototype.remove = /** @@ -8710,15 +5771,15 @@ var Phaser; */ function (object, splice) { if (typeof splice === "undefined") { splice = false; } - var index = this.members.indexOf(object); - if((index < 0) || (index >= this.members.length)) { + this._i = this.members.indexOf(object); + if(this._i < 0 || (this._i >= this.members.length)) { return null; } if(splice) { - this.members.splice(index, 1); + this.members.splice(this._i, 1); this.length--; } else { - this.members[index] = null; + this.members[this._i] = null; } return object; }; @@ -8731,11 +5792,11 @@ var Phaser; * @return {Basic} The new object. */ function (oldObject, newObject) { - var index = this.members.indexOf(oldObject); - if((index < 0) || (index >= this.members.length)) { + this._i = this.members.indexOf(oldObject); + if(this._i < 0 || (this._i >= this.members.length)) { return null; } - this.members[index] = newObject; + this.members[this._i] = newObject; return newObject; }; Group.prototype.sort = /** @@ -8762,17 +5823,16 @@ var Phaser; * @param {Object} Value The value you want to assign to that variable. * @param {boolean} Recurse Default value is true, meaning if setAll() encounters a member that is a group, it will call setAll() on that group rather than modifying its variable. */ - function (VariableName, Value, Recurse) { - if (typeof Recurse === "undefined") { Recurse = true; } - var basic; - var i = 0; - while(i < length) { - basic = this.members[i++]; - if(basic != null) { - if(Recurse && (basic.isGroup == true)) { - basic['setAll'](VariableName, Value, Recurse); + function (variableName, value, recurse) { + if (typeof recurse === "undefined") { recurse = true; } + this._i = 0; + while(this._i < this.length) { + this._member = this.members[this._i++]; + if(this._member != null) { + if(recurse && this._member.type == Phaser.Types.GROUP) { + this._member.setAll(variableName, value, recurse); } else { - basic[VariableName] = Value; + this._member[variableName] = value; } } } @@ -8784,17 +5844,16 @@ var Phaser; * @param {string} FunctionName The string representation of the function you want to call on each object, for example "kill()" or "init()". * @param {boolean} Recurse Default value is true, meaning if callAll() encounters a member that is a group, it will call callAll() on that group rather than calling the group's function. */ - function (FunctionName, Recurse) { - if (typeof Recurse === "undefined") { Recurse = true; } - var basic; - var i = 0; - while(i < this.length) { - basic = this.members[i++]; - if(basic != null) { - if(Recurse && (basic.isGroup == true)) { - basic['callAll'](FunctionName, Recurse); + function (functionName, recurse) { + if (typeof recurse === "undefined") { recurse = true; } + this._i = 0; + while(this._i < this.length) { + this._member = this.members[this._i++]; + if(this._member != null) { + if(recurse && this._member.type == Phaser.Types.GROUP) { + this._member.callAll(functionName, recurse); } else { - basic[FunctionName](); + this._member[functionName](); } } } @@ -8805,15 +5864,14 @@ var Phaser; */ function (callback, recursive) { if (typeof recursive === "undefined") { recursive = false; } - var basic; - var i = 0; - while(i < this.length) { - basic = this.members[i++]; - if(basic != null) { - if(recursive && (basic.isGroup == true)) { - basic.forEach(callback, true); + this._i = 0; + while(this._i < this.length) { + this._member = this.members[this._i++]; + if(this._member != null) { + if(recursive && this._member.type == Phaser.Types.GROUP) { + this._member.forEach(callback, true); } else { - callback.call(this, basic); + callback.call(this, this._member); } } } @@ -8825,15 +5883,14 @@ var Phaser; */ function (context, callback, recursive) { if (typeof recursive === "undefined") { recursive = false; } - var basic; - var i = 0; - while(i < this.length) { - basic = this.members[i++]; - if(basic != null && basic.alive) { - if(recursive && (basic.isGroup == true)) { - basic.forEachAlive(context, callback, true); + this._i = 0; + while(this._i < this.length) { + this._member = this.members[this._i++]; + if(this._member != null && this._member.alive) { + if(recursive && this._member.type == Phaser.Types.GROUP) { + this._member.forEachAlive(context, callback, true); } else { - callback.call(context, basic); + callback.call(context, this._member); } } } @@ -8846,14 +5903,13 @@ var Phaser; * * @return {any} A Basic currently flagged as not existing. */ - function (ObjectClass) { - if (typeof ObjectClass === "undefined") { ObjectClass = null; } - var basic; - var i = 0; - while(i < this.length) { - basic = this.members[i++]; - if((basic != null) && !basic.exists && ((ObjectClass == null) || (typeof basic === ObjectClass))) { - return basic; + function (objectClass) { + if (typeof objectClass === "undefined") { objectClass = null; } + this._i = 0; + while(this._i < this.length) { + this._member = this.members[this._i++]; + if((this._member != null) && !this._member.exists && ((objectClass == null) || (typeof this._member === objectClass))) { + return this._member; } } return null; @@ -8865,14 +5921,12 @@ var Phaser; * @return {number} An int indicating the first null slot in the group. */ function () { - var basic; - var i = 0; - var l = this.members.length; - while(i < l) { - if(this.members[i] == null) { - return i; + this._i = 0; + while(this._i < this.length) { + if(this.members[this._i] == null) { + return this._i; } else { - i++; + this._i++; } } return -1; @@ -8884,12 +5938,11 @@ var Phaser; * @return {Basic} A Basic currently flagged as existing. */ function () { - var basic; - var i = 0; - while(i < length) { - basic = this.members[i++]; - if((basic != null) && basic.exists) { - return basic; + this._i = 0; + while(this._i < this.length) { + this._member = this.members[this._i++]; + if(this._member != null && this._member.exists) { + return this._member; } } return null; @@ -8901,12 +5954,11 @@ var Phaser; * @return {Basic} A Basic currently flagged as not dead. */ function () { - var basic; - var i = 0; - while(i < this.length) { - basic = this.members[i++]; - if((basic != null) && basic.exists && basic.alive) { - return basic; + this._i = 0; + while(this._i < this.length) { + this._member = this.members[this._i++]; + if((this._member != null) && this._member.exists && this._member.alive) { + return this._member; } } return null; @@ -8918,12 +5970,11 @@ var Phaser; * @return {Basic} A Basic currently flagged as dead. */ function () { - var basic; - var i = 0; - while(i < this.length) { - basic = this.members[i++]; - if((basic != null) && !basic.alive) { - return basic; + this._i = 0; + while(this._i < this.length) { + this._member = this.members[this._i++]; + if((this._member != null) && !this._member.alive) { + return this._member; } } return null; @@ -8934,21 +5985,20 @@ var Phaser; * @return {number} The number of Basics flagged as not dead. Returns -1 if group is empty. */ function () { - var count = -1; - var basic; - var i = 0; - while(i < this.length) { - basic = this.members[i++]; - if(basic != null) { - if(count < 0) { - count = 0; + this._count = -1; + this._i = 0; + while(this._i < this.length) { + this._member = this.members[this._i++]; + if(this._member != null) { + if(this._count < 0) { + this._count = 0; } - if(basic.exists && basic.alive) { - count++; + if(this._member.exists && this._member.alive) { + this._count++; } } } - return count; + return this._count; }; Group.prototype.countDead = /** * Call this function to find out how many members of the group are dead. @@ -8956,21 +6006,20 @@ var Phaser; * @return {number} The number of Basics flagged as dead. Returns -1 if group is empty. */ function () { - var count = -1; - var basic; - var i = 0; - while(i < this.length) { - basic = this.members[i++]; - if(basic != null) { - if(count < 0) { - count = 0; + this._count = -1; + this._i = 0; + while(this._i < this.length) { + this._member = this.members[this._i++]; + if(this._member != null) { + if(this._count < 0) { + this._count = 0; } - if(!basic.alive) { - count++; + if(!this._member.alive) { + this._count++; } } } - return count; + return this._count; }; Group.prototype.getRandom = /** * Returns a member at random from the group. @@ -8980,13 +6029,13 @@ var Phaser; * * @return {Basic} A Basic from the members list. */ - function (StartIndex, Length) { - if (typeof StartIndex === "undefined") { StartIndex = 0; } - if (typeof Length === "undefined") { Length = 0; } - if(Length == 0) { - Length = this.length; + function (startIndex, length) { + if (typeof startIndex === "undefined") { startIndex = 0; } + if (typeof length === "undefined") { length = 0; } + if(length == 0) { + length = this.length; } - return this._game.math.getRandom(this.members, StartIndex, Length); + return this.game.math.getRandom(this.members, startIndex, length); }; Group.prototype.clear = /** * Remove all instances of Basic subclass (Basic, Block, etc) from the list. @@ -8999,12 +6048,11 @@ var Phaser; * Calls kill on the group's members and then on the group itself. */ function () { - var basic; - var i = 0; - while(i < this.length) { - basic = this.members[i++]; - if((basic != null) && basic.exists) { - basic.kill(); + this._i = 0; + while(this._i < this.length) { + this._member = this.members[this._i++]; + if((this._member != null) && this._member.exists) { + this._member.kill(); } } }; @@ -9016,777 +6064,383 @@ var Phaser; * * @return {number} An integer value: -1 (Obj1 before Obj2), 0 (same), or 1 (Obj1 after Obj2). */ - function (Obj1, Obj2) { - if(Obj1[this._sortIndex] < Obj2[this._sortIndex]) { + function (obj1, obj2) { + if(obj1[this._sortIndex] < obj2[this._sortIndex]) { return this._sortOrder; - } else if(Obj1[this._sortIndex] > Obj2[this._sortIndex]) { + } else if(obj1[this._sortIndex] > obj2[this._sortIndex]) { return -this._sortOrder; } return 0; }; return Group; - })(Phaser.Basic); + })(); Phaser.Group = Group; })(Phaser || (Phaser = {})); -/// +/// /** -* Phaser - Loader +* Phaser - SignalBinding * -* The Loader handles loading all external content such as Images, Sounds, Texture Atlases and data files. -* It uses a combination of Image() loading and xhr and provides for progress and completion callbacks. +* An object that represents a binding between a Signal and a listener function. +* Based on JS Signals by Miller Medeiros. Converted by TypeScript by Richard Davey. +* Released under the MIT license +* http://millermedeiros.github.com/js-signals/ */ var Phaser; (function (Phaser) { - var Loader = (function () { + var SignalBinding = (function () { /** - * Loader constructor - * - * @param game {Phaser.Game} Current game instance. - * @param callback {function} This will be called when assets completely loaded. + * Object that represents a binding between a Signal and a listener function. + *
- This is an internal constructor and shouldn't be called by regular users. + *
- inspired by Joa Ebert AS3 SignalBinding and Robert Penner's Slot classes. + * @author Miller Medeiros + * @constructor + * @internal + * @name SignalBinding + * @param {Signal} signal Reference to Signal object that listener is currently bound to. + * @param {Function} listener Handler function bound to the signal. + * @param {boolean} isOnce If binding should be executed just once. + * @param {Object} [listenerContext] Context on which listener will be executed (object that should represent the `this` variable inside listener function). + * @param {Number} [priority] The priority level of the event listener. (default = 0). */ - function Loader(game, callback) { + function SignalBinding(signal, listener, isOnce, listenerContext, priority) { + if (typeof priority === "undefined") { priority = 0; } /** - * The crossOrigin value applied to loaded images - * @type {string} + * If binding is active and should be executed. + * @type boolean */ - this.crossOrigin = ''; - this._game = game; - this._gameCreateComplete = callback; - this._keys = []; - this._fileList = { - }; - this._xhr = new XMLHttpRequest(); - this._queueSize = 0; + this.active = true; + /** + * Default parameters passed to listener during `Signal.dispatch` and `SignalBinding.execute`. (curried parameters) + * @type Array|null + */ + this.params = null; + this._listener = listener; + this._isOnce = isOnce; + this.context = listenerContext; + this._signal = signal; + this.priority = priority || 0; } - Loader.TEXTURE_ATLAS_JSON_ARRAY = 0; - Loader.TEXTURE_ATLAS_JSON_HASH = 1; - Loader.TEXTURE_ATLAS_XML_STARLING = 2; - Loader.prototype.reset = /** - * Reset loader, this will remove all loaded assets. + SignalBinding.prototype.execute = /** + * Call listener passing arbitrary parameters. + *

If binding was added using `Signal.addOnce()` it will be automatically removed from signal dispatch queue, this method is used internally for the signal dispatch.

+ * @param {Array} [paramsArr] Array of parameters that should be passed to the listener + * @return {*} Value returned by the listener. + */ + function (paramsArr) { + var handlerReturn; + var params; + if(this.active && !!this._listener) { + params = this.params ? this.params.concat(paramsArr) : paramsArr; + handlerReturn = this._listener.apply(this.context, params); + if(this._isOnce) { + this.detach(); + } + } + return handlerReturn; + }; + SignalBinding.prototype.detach = /** + * Detach binding from signal. + * - alias to: mySignal.remove(myBinding.getListener()); + * @return {Function|null} Handler function bound to the signal or `null` if binding was previously detached. */ function () { - this._queueSize = 0; + return this.isBound() ? this._signal.remove(this._listener, this.context) : null; }; - Object.defineProperty(Loader.prototype, "queueSize", { - get: function () { - return this._queueSize; - }, - enumerable: true, - configurable: true - }); - Loader.prototype.addImageFile = /** - * Add a new image asset loading request with key and url. - * @param key {string} Unique asset key of this image file. - * @param url {string} URL of image file. - */ - function (key, url) { - if(this.checkKeyExists(key) === false) { - this._queueSize++; - this._fileList[key] = { - type: 'image', - key: key, - url: url, - data: null, - error: false, - loaded: false - }; - this._keys.push(key); - } - }; - Loader.prototype.addSpriteSheet = /** - * Add a new sprite sheet loading request. - * @param key {string} Unique asset key of the sheet file. - * @param url {string} URL of sheet file. - * @param frameWidth {number} Width of each single frame. - * @param frameHeight {number} Height of each single frame. - * @param frameMax {number} How many frames in this sprite sheet. - */ - function (key, url, frameWidth, frameHeight, frameMax) { - if (typeof frameMax === "undefined") { frameMax = -1; } - if(this.checkKeyExists(key) === false) { - this._queueSize++; - this._fileList[key] = { - type: 'spritesheet', - key: key, - url: url, - data: null, - frameWidth: frameWidth, - frameHeight: frameHeight, - frameMax: frameMax, - error: false, - loaded: false - }; - this._keys.push(key); - } - }; - Loader.prototype.addTextureAtlas = /** - * Add a new texture atlas loading request. - * @param key {string} Unique asset key of the texture atlas file. - * @param textureURL {string} The url of the texture atlas image file. - * @param [atlasURL] {string} The url of the texture atlas data file (json/xml) - * @param [atlasData] {object} A JSON or XML data object. - * @param [format] {number} A value describing the format of the data. - */ - function (key, textureURL, atlasURL, atlasData, format) { - if (typeof atlasURL === "undefined") { atlasURL = null; } - if (typeof atlasData === "undefined") { atlasData = null; } - if (typeof format === "undefined") { format = Loader.TEXTURE_ATLAS_JSON_ARRAY; } - if(this.checkKeyExists(key) === false) { - if(atlasURL !== null) { - // A URL to a json/xml file has been given - this._queueSize++; - this._fileList[key] = { - type: 'textureatlas', - key: key, - url: textureURL, - atlasURL: atlasURL, - data: null, - format: format, - error: false, - loaded: false - }; - this._keys.push(key); - } else { - if(format == Loader.TEXTURE_ATLAS_JSON_ARRAY) { - // A json string or object has been given - if(typeof atlasData === 'string') { - atlasData = JSON.parse(atlasData); - } - this._queueSize++; - this._fileList[key] = { - type: 'textureatlas', - key: key, - url: textureURL, - data: null, - atlasURL: null, - atlasData: atlasData['frames'], - format: format, - error: false, - loaded: false - }; - this._keys.push(key); - } else if(format == Loader.TEXTURE_ATLAS_XML_STARLING) { - // An xml string or object has been given - 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; - } - } - this._queueSize++; - this._fileList[key] = { - type: 'textureatlas', - key: key, - url: textureURL, - data: null, - atlasURL: null, - atlasData: atlasData, - format: format, - error: false, - loaded: false - }; - this._keys.push(key); - } - } - } - }; - Loader.prototype.addAudioFile = /** - * Add a new audio file loading request. - * @param key {string} Unique asset key of the audio file. - * @param url {string} URL of audio file. - */ - function (key, url) { - if(this.checkKeyExists(key) === false) { - this._queueSize++; - this._fileList[key] = { - type: 'audio', - key: key, - url: url, - data: null, - buffer: null, - error: false, - loaded: false - }; - this._keys.push(key); - } - }; - Loader.prototype.addTextFile = /** - * Add a new text file loading request. - * @param key {string} Unique asset key of the text file. - * @param url {string} URL of text file. - */ - function (key, url) { - if(this.checkKeyExists(key) === false) { - this._queueSize++; - this._fileList[key] = { - type: 'text', - key: key, - url: url, - data: null, - error: false, - loaded: false - }; - this._keys.push(key); - } - }; - Loader.prototype.removeFile = /** - * Remove loading request of a file. - * @param key {string} Key of the file you want to remove. - */ - function (key) { - delete this._fileList[key]; - }; - Loader.prototype.removeAll = /** - * Remove all file loading requests. + SignalBinding.prototype.isBound = /** + * @return {Boolean} `true` if binding is still bound to the signal and have a listener. */ function () { - this._fileList = { - }; + return (!!this._signal && !!this._listener); }; - Loader.prototype.load = /** - * Load assets. - * @param onFileLoadCallback {function} Called when each file loaded successfully. - * @param onCompleteCallback {function} Called when all assets completely loaded. - */ - function (onFileLoadCallback, onCompleteCallback) { - if (typeof onFileLoadCallback === "undefined") { onFileLoadCallback = null; } - if (typeof onCompleteCallback === "undefined") { onCompleteCallback = null; } - this.progress = 0; - this.hasLoaded = false; - this._onComplete = onCompleteCallback; - if(onCompleteCallback == null) { - this._onComplete = this._game.onCreateCallback; - } - this._onFileLoad = onFileLoadCallback; - if(this._keys.length > 0) { - this._progressChunk = 100 / this._keys.length; - this.loadFile(); - } else { - this.progress = 1; - this.hasLoaded = true; - this._gameCreateComplete.call(this._game); - if(this._onComplete !== null) { - this._onComplete.call(this._game.callbackContext); - } - } - }; - Loader.prototype.loadFile = /** - * Load files. Private method ONLY used by loader. + SignalBinding.prototype.isOnce = /** + * @return {boolean} If SignalBinding will only be executed once. */ function () { - var _this = this; - var file = this._fileList[this._keys.pop()]; - // Image or Data? - switch(file.type) { - case 'image': - case 'spritesheet': - case 'textureatlas': - 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 = file.url; - break; - case 'audio': - this._xhr.open("GET", 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(); - break; - case 'text': - this._xhr.open("GET", 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; - } + return this._isOnce; }; - Loader.prototype.fileError = /** - * Error occured when load a file. - * @param key {string} Key of the error loading file. + SignalBinding.prototype.getListener = /** + * @return {Function} Handler function bound to the signal. */ - function (key) { - this._fileList[key].loaded = true; - this._fileList[key].error = true; - this.nextFile(key, false); + function () { + return this._listener; }; - Loader.prototype.fileComplete = /** - * Called when a file is successfully loaded. - * @param key {string} Key of the successfully loaded file. + SignalBinding.prototype.getSignal = /** + * @return {Signal} Signal that listener is currently bound to. */ - function (key) { - var _this = this; - this._fileList[key].loaded = true; - var file = this._fileList[key]; - var loadNext = true; - 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 '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", file.atlasURL, true); - this._xhr.responseType = "text"; - if(file.format == Loader.TEXTURE_ATLAS_JSON_ARRAY) { - this._xhr.onload = function () { - return _this.jsonLoadComplete(file.key); - }; - } else if(file.format == Loader.TEXTURE_ATLAS_XML_STARLING) { - this._xhr.onload = function () { - return _this.xmlLoadComplete(file.key); - }; - } - this._xhr.onerror = function () { - return _this.dataLoadError(file.key); - }; - this._xhr.send(); - } - break; - case 'audio': - file.data = this._xhr.response; - this._game.cache.addSound(file.key, file.url, file.data); - break; - case 'text': - file.data = this._xhr.response; - this._game.cache.addText(file.key, file.url, file.data); - break; - } - if(loadNext) { - this.nextFile(key, true); - } + function () { + return this._signal; }; - Loader.prototype.jsonLoadComplete = /** - * Successfully loaded a JSON file. - * @param key {string} Key of the loaded JSON file. + SignalBinding.prototype._destroy = /** + * Delete instance properties + * @private */ - function (key) { - var data = JSON.parse(this._xhr.response); - var file = this._fileList[key]; - this._game.cache.addTextureAtlas(file.key, file.url, file.data, data['frames'], file.format); - this.nextFile(key, true); + function () { + delete this._signal; + delete this._listener; + delete this.context; }; - Loader.prototype.dataLoadError = /** - * Error occured when load a JSON. - * @param key {string} Key of the error loading JSON file. + SignalBinding.prototype.toString = /** + * @return {string} String representation of the object. */ - function (key) { - var file = this._fileList[key]; - file.error = true; - this.nextFile(key, true); + function () { + return '[SignalBinding isOnce:' + this._isOnce + ', isBound:' + this.isBound() + ', active:' + this.active + ']'; }; - Loader.prototype.xmlLoadComplete = function (key) { - var atlasData = this._xhr.response; - 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"); - } - var file = this._fileList[key]; - this._game.cache.addTextureAtlas(file.key, file.url, file.data, xml, file.format); - this.nextFile(key, true); - }; - Loader.prototype.nextFile = /** - * Handle loading next file. - * @param previousKey {string} Key of previous loaded asset. - * @param success {boolean} Whether the previous asset loaded successfully or not. - */ - function (previousKey, success) { - this.progress = Math.round(this.progress + this._progressChunk); - if(this.progress > 100) { - this.progress = 100; - } - if(this._onFileLoad) { - this._onFileLoad.call(this._game.callbackContext, this.progress, previousKey, success); - } - if(this._keys.length > 0) { - this.loadFile(); - } else { - this.hasLoaded = true; - this.removeAll(); - this._gameCreateComplete.call(this._game); - if(this._onComplete !== null) { - this._onComplete.call(this._game.callbackContext); - } - } - }; - Loader.prototype.checkKeyExists = /** - * Check whether asset exists with a specific key. - * @param key {string} Key of the asset you want to check. - * @return {boolean} Return true if exists, otherwise return false. - */ - function (key) { - if(this._fileList[key]) { - return true; - } else { - return false; - } - }; - return Loader; + return SignalBinding; })(); - Phaser.Loader = Loader; + Phaser.SignalBinding = SignalBinding; })(Phaser || (Phaser = {})); -/// -/// +/// /** -* Phaser - Motion +* Phaser - Signal * -* The Motion class contains lots of useful functions for moving game objects around in world space. +* A Signal is used for object communication via a custom broadcaster instead of Events. +* Based on JS Signals by Miller Medeiros. Converted by TypeScript by Richard Davey. +* Released under the MIT license +* http://millermedeiros.github.com/js-signals/ */ var Phaser; (function (Phaser) { - var Motion = (function () { - function Motion(game) { - this._game = game; + var Signal = (function () { + function Signal() { + /** + * + * @property _bindings + * @type Array + * @private + */ + this._bindings = []; + /** + * + * @property _prevParams + * @type Any + * @private + */ + this._prevParams = null; + /** + * If Signal should keep record of previously dispatched parameters and + * automatically execute listener during `add()`/`addOnce()` if Signal was + * already dispatched before. + * @type boolean + */ + this.memorize = false; + /** + * @type boolean + * @private + */ + this._shouldPropagate = true; + /** + * If Signal is active and should broadcast events. + *

IMPORTANT: Setting this property during a dispatch will only affect the next dispatch, if you want to stop the propagation of a signal use `halt()` instead.

+ * @type boolean + */ + this.active = true; } - Motion.prototype.computeVelocity = /** - * A tween-like function that takes a starting velocity and some other factors and returns an altered velocity. + Signal.VERSION = '1.0.0'; + Signal.prototype.validateListener = /** * - * @param {number} Velocity Any component of velocity (e.g. 20). - * @param {number} Acceleration Rate at which the velocity is changing. - * @param {number} Drag Really kind of a deceleration, this is how much the velocity changes if Acceleration is not set. - * @param {number} Max An absolute value cap for the velocity. - * - * @return {number} The altered Velocity value. + * @method validateListener + * @param {Any} listener + * @param {Any} fnName */ - function (Velocity, Acceleration, Drag, Max) { - if (typeof Acceleration === "undefined") { Acceleration = 0; } - if (typeof Drag === "undefined") { Drag = 0; } - if (typeof Max === "undefined") { Max = 10000; } - if(Acceleration !== 0) { - Velocity += Acceleration * this._game.time.elapsed; - } else if(Drag !== 0) { - var drag = Drag * this._game.time.elapsed; - if(Velocity - drag > 0) { - Velocity = Velocity - drag; - } else if(Velocity + drag < 0) { - Velocity += drag; - } else { - Velocity = 0; + function (listener, fnName) { + if(typeof listener !== 'function') { + throw new Error('listener is a required param of {fn}() and should be a Function.'.replace('{fn}', fnName)); + } + }; + Signal.prototype._registerListener = /** + * @param {Function} listener + * @param {boolean} isOnce + * @param {Object} [listenerContext] + * @param {Number} [priority] + * @return {SignalBinding} + * @private + */ + function (listener, isOnce, listenerContext, priority) { + var prevIndex = this._indexOfListener(listener, listenerContext); + var binding; + if(prevIndex !== -1) { + binding = this._bindings[prevIndex]; + if(binding.isOnce() !== isOnce) { + throw new Error('You cannot add' + (isOnce ? '' : 'Once') + '() then add' + (!isOnce ? '' : 'Once') + '() the same listener without removing the relationship first.'); + } + } else { + binding = new Phaser.SignalBinding(this, listener, isOnce, listenerContext, priority); + this._addBinding(binding); + } + if(this.memorize && this._prevParams) { + binding.execute(this._prevParams); + } + return binding; + }; + Signal.prototype._addBinding = /** + * + * @method _addBinding + * @param {SignalBinding} binding + * @private + */ + function (binding) { + //simplified insertion sort + var n = this._bindings.length; + do { + --n; + }while(this._bindings[n] && binding.priority <= this._bindings[n].priority); + this._bindings.splice(n + 1, 0, binding); + }; + Signal.prototype._indexOfListener = /** + * + * @method _indexOfListener + * @param {Function} listener + * @return {number} + * @private + */ + function (listener, context) { + var n = this._bindings.length; + var cur; + while(n--) { + cur = this._bindings[n]; + if(cur.getListener() === listener && cur.context === context) { + return n; } } - if((Velocity != 0) && (Max != 10000)) { - if(Velocity > Max) { - Velocity = Max; - } else if(Velocity < -Max) { - Velocity = -Max; + return -1; + }; + Signal.prototype.has = /** + * Check if listener was attached to Signal. + * @param {Function} listener + * @param {Object} [context] + * @return {boolean} if Signal has the specified listener. + */ + function (listener, context) { + if (typeof context === "undefined") { context = null; } + return this._indexOfListener(listener, context) !== -1; + }; + Signal.prototype.add = /** + * Add a listener to the signal. + * @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 {SignalBinding} An Object representing the binding between the Signal and listener. + */ + function (listener, listenerContext, priority) { + if (typeof listenerContext === "undefined") { listenerContext = null; } + if (typeof priority === "undefined") { priority = 0; } + this.validateListener(listener, 'add'); + return this._registerListener(listener, false, listenerContext, priority); + }; + Signal.prototype.addOnce = /** + * Add listener to the signal that should be removed after first execution (will be executed only once). + * @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 {SignalBinding} An Object representing the binding between the Signal and listener. + */ + function (listener, listenerContext, priority) { + if (typeof listenerContext === "undefined") { listenerContext = null; } + if (typeof priority === "undefined") { priority = 0; } + this.validateListener(listener, 'addOnce'); + return this._registerListener(listener, true, listenerContext, priority); + }; + Signal.prototype.remove = /** + * Remove a single listener from the dispatch queue. + * @param {Function} listener Handler function that should be removed. + * @param {Object} [context] Execution context (since you can add the same handler multiple times if executing in a different context). + * @return {Function} Listener handler function. + */ + function (listener, context) { + if (typeof context === "undefined") { context = null; } + this.validateListener(listener, 'remove'); + var i = this._indexOfListener(listener, context); + if(i !== -1) { + this._bindings[i]._destroy(); + this._bindings.splice(i, 1); + } + return listener; + }; + Signal.prototype.removeAll = /** + * Remove all listeners from the Signal. + */ + function () { + if(this._bindings) { + var n = this._bindings.length; + while(n--) { + this._bindings[n]._destroy(); } - } - return Velocity; - }; - Motion.prototype.velocityFromAngle = /** - * Given the angle and speed calculate the velocity and return it as a Point - * - * @param {number} angle The angle (in degrees) calculated in clockwise positive direction (down = 90 degrees positive, right = 0 degrees positive, up = 90 degrees negative) - * @param {number} speed The speed it will move, in pixels per second sq - * - * @return {Point} A Point where Point.x contains the velocity x value and Point.y contains the velocity y value - */ - function (angle, speed) { - if(isNaN(speed)) { - speed = 0; - } - var a = this._game.math.degreesToRadians(angle); - return new Phaser.Point((Math.cos(a) * speed), (Math.sin(a) * speed)); - }; - Motion.prototype.moveTowardsObject = /** - * Sets the source Sprite x/y velocity so it will move directly towards the destination Sprite at the speed given (in pixels per second)
- * If you specify a maxTime then it will adjust the speed (over-writing what you set) so it arrives at the destination in that number of seconds.
- * Timings are approximate due to the way Flash timers work, and irrespective of SWF frame rate. Allow for a variance of +- 50ms.
- * The source object doesn't stop moving automatically should it ever reach the destination coordinates.
- * If you need the object to accelerate, see accelerateTowardsObject() instead - * Note: Doesn't take into account acceleration, maxVelocity or drag (if you set drag or acceleration too high this object may not move at all) - * - * @param {GameObject} source The Sprite on which the velocity will be set - * @param {GameObject} dest The Sprite where the source object will move to - * @param {number} speed The speed it will move, in pixels per second (default is 60 pixels/sec) - * @param {number} maxTime Time given in milliseconds (1000 = 1 sec). If set the speed is adjusted so the source will arrive at destination in the given number of ms - */ - function (source, dest, speed, maxTime) { - if (typeof speed === "undefined") { speed = 60; } - if (typeof maxTime === "undefined") { maxTime = 0; } - var a = this.angleBetween(source, dest); - if(maxTime > 0) { - var d = this.distanceBetween(source, dest); - // We know how many pixels we need to move, but how fast? - speed = d / (maxTime / 1000); - } - source.velocity.x = Math.cos(a) * speed; - source.velocity.y = Math.sin(a) * speed; - }; - Motion.prototype.accelerateTowardsObject = /** - * Sets the x/y acceleration on the source Sprite so it will move towards the destination Sprite at the speed given (in pixels per second)
- * You must give a maximum speed value, beyond which the Sprite won't go any faster.
- * If you don't need acceleration look at moveTowardsObject() instead. - * - * @param {GameObject} source The Sprite on which the acceleration will be set - * @param {GameObject} dest The Sprite where the source object will move towards - * @param {number} speed The speed it will accelerate in pixels per second - * @param {number} xSpeedMax The maximum speed in pixels per second in which the sprite can move horizontally - * @param {number} ySpeedMax The maximum speed in pixels per second in which the sprite can move vertically - */ - function (source, dest, speed, xSpeedMax, ySpeedMax) { - var a = this.angleBetween(source, dest); - source.velocity.x = 0; - source.velocity.y = 0; - source.acceleration.x = Math.cos(a) * speed; - source.acceleration.y = Math.sin(a) * speed; - source.maxVelocity.x = xSpeedMax; - source.maxVelocity.y = ySpeedMax; - }; - Motion.prototype.moveTowardsMouse = /** - * Move the given Sprite towards the mouse pointer coordinates at a steady velocity - * If you specify a maxTime then it will adjust the speed (over-writing what you set) so it arrives at the destination in that number of seconds.
- * Timings are approximate due to the way Flash timers work, and irrespective of SWF frame rate. Allow for a variance of +- 50ms.
- * The source object doesn't stop moving automatically should it ever reach the destination coordinates.
- * - * @param {GameObject} source The Sprite to move - * @param {number} speed The speed it will move, in pixels per second (default is 60 pixels/sec) - * @param {number} maxTime Time given in milliseconds (1000 = 1 sec). If set the speed is adjusted so the source will arrive at destination in the given number of ms - */ - function (source, speed, maxTime) { - if (typeof speed === "undefined") { speed = 60; } - if (typeof maxTime === "undefined") { maxTime = 0; } - var a = this.angleBetweenMouse(source); - if(maxTime > 0) { - var d = this.distanceToMouse(source); - // We know how many pixels we need to move, but how fast? - speed = d / (maxTime / 1000); - } - source.velocity.x = Math.cos(a) * speed; - source.velocity.y = Math.sin(a) * speed; - }; - Motion.prototype.accelerateTowardsMouse = /** - * Sets the x/y acceleration on the source Sprite so it will move towards the mouse coordinates at the speed given (in pixels per second)
- * You must give a maximum speed value, beyond which the Sprite won't go any faster.
- * If you don't need acceleration look at moveTowardsMouse() instead. - * - * @param {GameObject} source The Sprite on which the acceleration will be set - * @param {number} speed The speed it will accelerate in pixels per second - * @param {number} xSpeedMax The maximum speed in pixels per second in which the sprite can move horizontally - * @param {number} ySpeedMax The maximum speed in pixels per second in which the sprite can move vertically - */ - function (source, speed, xSpeedMax, ySpeedMax) { - var a = this.angleBetweenMouse(source); - source.velocity.x = 0; - source.velocity.y = 0; - source.acceleration.x = Math.cos(a) * speed; - source.acceleration.y = Math.sin(a) * speed; - source.maxVelocity.x = xSpeedMax; - source.maxVelocity.y = ySpeedMax; - }; - Motion.prototype.moveTowardsPoint = /** - * Sets the x/y velocity on the source Sprite so it will move towards the target coordinates at the speed given (in pixels per second)
- * If you specify a maxTime then it will adjust the speed (over-writing what you set) so it arrives at the destination in that number of seconds.
- * Timings are approximate due to the way Flash timers work, and irrespective of SWF frame rate. Allow for a variance of +- 50ms.
- * The source object doesn't stop moving automatically should it ever reach the destination coordinates.
- * - * @param {GameObject} source The Sprite to move - * @param {Point} target The Point coordinates to move the source Sprite towards - * @param {number} speed The speed it will move, in pixels per second (default is 60 pixels/sec) - * @param {number} maxTime Time given in milliseconds (1000 = 1 sec). If set the speed is adjusted so the source will arrive at destination in the given number of ms - */ - function (source, target, speed, maxTime) { - if (typeof speed === "undefined") { speed = 60; } - if (typeof maxTime === "undefined") { maxTime = 0; } - var a = this.angleBetweenPoint(source, target); - if(maxTime > 0) { - var d = this.distanceToPoint(source, target); - // We know how many pixels we need to move, but how fast? - speed = d / (maxTime / 1000); - } - source.velocity.x = Math.cos(a) * speed; - source.velocity.y = Math.sin(a) * speed; - }; - Motion.prototype.accelerateTowardsPoint = /** - * Sets the x/y acceleration on the source Sprite so it will move towards the target coordinates at the speed given (in pixels per second)
- * You must give a maximum speed value, beyond which the Sprite won't go any faster.
- * If you don't need acceleration look at moveTowardsPoint() instead. - * - * @param {GameObject} source The Sprite on which the acceleration will be set - * @param {Point} target The Point coordinates to move the source Sprite towards - * @param {number} speed The speed it will accelerate in pixels per second - * @param {number} xSpeedMax The maximum speed in pixels per second in which the sprite can move horizontally - * @param {number} ySpeedMax The maximum speed in pixels per second in which the sprite can move vertically - */ - function (source, target, speed, xSpeedMax, ySpeedMax) { - var a = this.angleBetweenPoint(source, target); - source.velocity.x = 0; - source.velocity.y = 0; - source.acceleration.x = Math.cos(a) * speed; - source.acceleration.y = Math.sin(a) * speed; - source.maxVelocity.x = xSpeedMax; - source.maxVelocity.y = ySpeedMax; - }; - Motion.prototype.distanceBetween = /** - * Find the distance (in pixels, rounded) between two Sprites, taking their origin into account - * - * @param {GameObject} a The first Sprite - * @param {GameObject} b The second Sprite - * @return {number} int Distance (in pixels) - */ - function (a, b) { - var dx = (a.x + a.origin.x) - (b.x + b.origin.x); - var dy = (a.y + a.origin.y) - (b.y + b.origin.y); - return this._game.math.vectorLength(dx, dy); - }; - Motion.prototype.distanceToPoint = /** - * Find the distance (in pixels, rounded) from an Sprite to the given Point, taking the source origin into account - * - * @param {GameObject} a The Sprite - * @param {Point} target The Point - * @return {number} Distance (in pixels) - */ - function (a, target) { - var dx = (a.x + a.origin.x) - (target.x); - var dy = (a.y + a.origin.y) - (target.y); - return this._game.math.vectorLength(dx, dy); - }; - Motion.prototype.distanceToMouse = /** - * Find the distance (in pixels, rounded) from the object x/y and the mouse x/y - * - * @param {GameObject} a Sprite to test against - * @return {number} The distance between the given sprite and the mouse coordinates - */ - function (a) { - var dx = (a.x + a.origin.x) - this._game.input.x; - var dy = (a.y + a.origin.y) - this._game.input.y; - return this._game.math.vectorLength(dx, dy); - }; - Motion.prototype.angleBetweenPoint = /** - * Find the angle (in radians) between an Sprite and an Point. The source sprite takes its x/y and origin into account. - * The angle is calculated in clockwise positive direction (down = 90 degrees positive, right = 0 degrees positive, up = 90 degrees negative) - * - * @param {GameObject} a The Sprite to test from - * @param {Point} target The Point to angle the Sprite towards - * @param {boolean} asDegrees If you need the value in degrees instead of radians, set to true - * - * @return {number} The angle (in radians unless asDegrees is true) - */ - function (a, target, asDegrees) { - if (typeof asDegrees === "undefined") { asDegrees = false; } - var dx = (target.x) - (a.x + a.origin.x); - var dy = (target.y) - (a.y + a.origin.y); - if(asDegrees) { - return this._game.math.radiansToDegrees(Math.atan2(dy, dx)); - } else { - return Math.atan2(dy, dx); + this._bindings.length = 0; } }; - Motion.prototype.angleBetween = /** - * Find the angle (in radians) between the two Sprite, taking their x/y and origin into account. - * The angle is calculated in clockwise positive direction (down = 90 degrees positive, right = 0 degrees positive, up = 90 degrees negative) - * - * @param {GameObject} a The Sprite to test from - * @param {GameObject} b The Sprite to test to - * @param {boolean} asDegrees If you need the value in degrees instead of radians, set to true - * - * @return {number} The angle (in radians unless asDegrees is true) + Signal.prototype.getNumListeners = /** + * @return {number} Number of listeners attached to the Signal. */ - function (a, b, asDegrees) { - if (typeof asDegrees === "undefined") { asDegrees = false; } - var dx = (b.x + b.origin.x) - (a.x + a.origin.x); - var dy = (b.y + b.origin.y) - (a.y + a.origin.y); - if(asDegrees) { - return this._game.math.radiansToDegrees(Math.atan2(dy, dx)); - } else { - return Math.atan2(dy, dx); - } + function () { + return this._bindings.length; }; - Motion.prototype.velocityFromFacing = /** - * Given the GameObject and speed calculate the velocity and return it as an Point based on the direction the sprite is facing - * - * @param {GameObject} parent The Sprite to get the facing value from - * @param {number} speed The speed it will move, in pixels per second sq - * - * @return {Point} An Point where Point.x contains the velocity x value and Point.y contains the velocity y value + Signal.prototype.halt = /** + * Stop propagation of the event, blocking the dispatch to next listeners on the queue. + *

IMPORTANT: should be called only during signal dispatch, calling it before/after dispatch won't affect signal broadcast.

+ * @see Signal.prototype.disable */ - function (parent, speed) { - var a; - if(parent.facing == Phaser.Collision.LEFT) { - a = this._game.math.degreesToRadians(180); - } else if(parent.facing == Phaser.Collision.RIGHT) { - a = this._game.math.degreesToRadians(0); - } else if(parent.facing == Phaser.Collision.UP) { - a = this._game.math.degreesToRadians(-90); - } else if(parent.facing == Phaser.Collision.DOWN) { - a = this._game.math.degreesToRadians(90); - } - return new Phaser.Point(Math.cos(a) * speed, Math.sin(a) * speed); + function () { + this._shouldPropagate = false; }; - Motion.prototype.angleBetweenMouse = /** - * Find the angle (in radians) between an Sprite and the mouse, taking their x/y and origin into account. - * The angle is calculated in clockwise positive direction (down = 90 degrees positive, right = 0 degrees positive, up = 90 degrees negative) - * - * @param {GameObject} a The Object to test from - * @param {boolean} asDegrees If you need the value in degrees instead of radians, set to true - * - * @return {number} The angle (in radians unless asDegrees is true) + Signal.prototype.dispatch = /** + * Dispatch/Broadcast Signal to all listeners added to the queue. + * @param {...*} [params] Parameters that should be passed to each handler. */ - function (a, asDegrees) { - if (typeof asDegrees === "undefined") { asDegrees = false; } - // In order to get the angle between the object and mouse, we need the objects screen coordinates (rather than world coordinates) - var p = a.getScreenXY(); - var dx = a._game.input.x - p.x; - var dy = a._game.input.y - p.y; - if(asDegrees) { - return this._game.math.radiansToDegrees(Math.atan2(dy, dx)); - } else { - return Math.atan2(dy, dx); + function () { + var paramsArr = []; + for (var _i = 0; _i < (arguments.length - 0); _i++) { + paramsArr[_i] = arguments[_i + 0]; } + if(!this.active) { + return; + } + var n = this._bindings.length; + var bindings; + if(this.memorize) { + this._prevParams = paramsArr; + } + if(!n) { + //should come after memorize + return; + } + bindings = this._bindings.slice(0)//clone array in case add/remove items during dispatch + ; + this._shouldPropagate = true//in case `halt` was called before dispatch or during the previous dispatch. + ; + //execute all callbacks until end of the list or until a callback returns `false` or stops propagation + //reverse loop since listeners with higher priority will be added at the end of the list + do { + n--; + }while(bindings[n] && this._shouldPropagate && bindings[n].execute(paramsArr) !== false); }; - return Motion; + Signal.prototype.forget = /** + * Forget memorized arguments. + * @see Signal.memorize + */ + function () { + this._prevParams = null; + }; + Signal.prototype.dispose = /** + * Remove all bindings from signal and destroy any reference to external objects (destroy Signal object). + *

IMPORTANT: calling any method on the signal instance after calling dispose will throw errors.

+ */ + function () { + this.removeAll(); + delete this._bindings; + delete this._prevParams; + }; + Signal.prototype.toString = /** + * @return {string} String representation of the object. + */ + function () { + return '[Signal active:' + this.active + ' numListeners:' + this.getNumListeners() + ']'; + }; + return Signal; })(); - Phaser.Motion = Motion; + Phaser.Signal = Signal; })(Phaser || (Phaser = {})); /// -/// +/// /** * Phaser - Sound * @@ -9885,8 +6539,8 @@ var Phaser; })(); Phaser.Sound = Sound; })(Phaser || (Phaser = {})); -/// -/// +/// +/// /** * Phaser - SoundManager * @@ -9999,13 +6653,14 @@ var Phaser; /** * Phaser * -* v0.9.6 - May 21st 2013 +* v1.0.0 - June XX 2013 * * A small and feature-packed 2D canvas game framework born from the firey pits of Flixel and Kiwi. * * Richard Davey (@photonstorm) * -* Many thanks to Adam Saltsman (@ADAMATOMIC) for releasing Flixel on which Phaser took a lot of inspiration. +* Many thanks to Adam Saltsman (@ADAMATOMIC) for releasing Flixel, from both which Phaser +* and my love of game development took a lot of inspiration. * * "If you want your children to be intelligent, read them fairy tales." * "If you want them to be more intelligent, read them more fairy tales." @@ -10013,7 +6668,7 @@ var Phaser; */ var Phaser; (function (Phaser) { - Phaser.VERSION = 'Phaser version 0.9.6'; + Phaser.VERSION = 'Phaser version 1.0.0'; })(Phaser || (Phaser = {})); /// /** @@ -10522,7 +7177,7 @@ var Phaser; }; this.context = this.canvas.getContext('2d'); this.offset = this.getOffset(this.canvas); - this.bounds = new Phaser.Quad(this.offset.x, this.offset.y, width, height); + this.bounds = new Phaser.Rectangle(this.offset.x, this.offset.y, width, height); this.aspectRatio = width / height; this.scaleMode = Phaser.StageScaleMode.NO_SCALE; this.scale = new Phaser.StageScaleMode(this._game); @@ -10596,7 +7251,7 @@ var Phaser; var clientLeft = element.clientLeft || document.body.clientLeft || 0; var scrollTop = window.pageYOffset || element.scrollTop || document.body.scrollTop; var scrollLeft = window.pageXOffset || element.scrollLeft || document.body.scrollLeft; - return new Phaser.MicroPoint(box.left + scrollLeft - clientLeft, box.top + scrollTop - clientTop); + return new Phaser.Point(box.left + scrollLeft - clientLeft, box.top + scrollTop - clientTop); }; Stage.prototype.saveCanvasValues = /** * Save current canvas properties (strokeStyle, lineWidth and fillStyle) for later using. @@ -10835,600 +7490,8 @@ var Phaser; })(); Phaser.Time = Time; })(Phaser || (Phaser = {})); -var Phaser; -(function (Phaser) { - /// - /** - * Phaser - Easing - Back - * - * For use with Phaser.Tween - */ - (function (Easing) { - var Back = (function () { - function Back() { } - Back.In = function In(k) { - var s = 1.70158; - return k * k * ((s + 1) * k - s); - }; - Back.Out = function Out(k) { - var s = 1.70158; - return --k * k * ((s + 1) * k + s) + 1; - }; - Back.InOut = function InOut(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); - }; - return Back; - })(); - Easing.Back = Back; - })(Phaser.Easing || (Phaser.Easing = {})); - var Easing = Phaser.Easing; -})(Phaser || (Phaser = {})); -var Phaser; -(function (Phaser) { - /// - /** - * Phaser - Easing - Bounce - * - * For use with Phaser.Tween - */ - (function (Easing) { - var Bounce = (function () { - function Bounce() { } - Bounce.In = function In(k) { - return 1 - Phaser.Easing.Bounce.Out(1 - k); - }; - Bounce.Out = function Out(k) { - if(k < (1 / 2.75)) { - return 7.5625 * k * k; - } else if(k < (2 / 2.75)) { - return 7.5625 * (k -= (1.5 / 2.75)) * k + 0.75; - } else if(k < (2.5 / 2.75)) { - return 7.5625 * (k -= (2.25 / 2.75)) * k + 0.9375; - } else { - return 7.5625 * (k -= (2.625 / 2.75)) * k + 0.984375; - } - }; - Bounce.InOut = function InOut(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; - }; - return Bounce; - })(); - Easing.Bounce = Bounce; - })(Phaser.Easing || (Phaser.Easing = {})); - var Easing = Phaser.Easing; -})(Phaser || (Phaser = {})); -var Phaser; -(function (Phaser) { - /// - /** - * Phaser - Easing - Circular - * - * For use with Phaser.Tween - */ - (function (Easing) { - var Circular = (function () { - function Circular() { } - Circular.In = function In(k) { - return 1 - Math.sqrt(1 - k * k); - }; - Circular.Out = function Out(k) { - return Math.sqrt(1 - (--k * k)); - }; - Circular.InOut = function InOut(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 Circular; - })(); - Easing.Circular = Circular; - })(Phaser.Easing || (Phaser.Easing = {})); - var Easing = Phaser.Easing; -})(Phaser || (Phaser = {})); -var Phaser; -(function (Phaser) { - /// - /** - * Phaser - Easing - Cubic - * - * For use with Phaser.Tween - */ - (function (Easing) { - var Cubic = (function () { - function Cubic() { } - Cubic.In = function In(k) { - return k * k * k; - }; - Cubic.Out = function Out(k) { - return --k * k * k + 1; - }; - Cubic.InOut = function InOut(k) { - if((k *= 2) < 1) { - return 0.5 * k * k * k; - } - return 0.5 * ((k -= 2) * k * k + 2); - }; - return Cubic; - })(); - Easing.Cubic = Cubic; - })(Phaser.Easing || (Phaser.Easing = {})); - var Easing = Phaser.Easing; -})(Phaser || (Phaser = {})); -var Phaser; -(function (Phaser) { - /// - /** - * Phaser - Easing - Elastic - * - * For use with Phaser.Tween - */ - (function (Easing) { - var Elastic = (function () { - function Elastic() { } - Elastic.In = function In(k) { - var s, a = 0.1, p = 0.4; - if(k === 0) { - return 0; - } - if(k === 1) { - return 1; - } - if(!a || a < 1) { - a = 1; - s = p / 4; - } else { - s = p * Math.asin(1 / a) / (2 * Math.PI); - } - return -(a * Math.pow(2, 10 * (k -= 1)) * Math.sin((k - s) * (2 * Math.PI) / p)); - }; - Elastic.Out = function Out(k) { - var s, a = 0.1, p = 0.4; - if(k === 0) { - return 0; - } - if(k === 1) { - return 1; - } - if(!a || a < 1) { - a = 1; - s = p / 4; - } else { - s = p * Math.asin(1 / a) / (2 * Math.PI); - } - return (a * Math.pow(2, -10 * k) * Math.sin((k - s) * (2 * Math.PI) / p) + 1); - }; - Elastic.InOut = function InOut(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; - }; - return Elastic; - })(); - Easing.Elastic = Elastic; - })(Phaser.Easing || (Phaser.Easing = {})); - var Easing = Phaser.Easing; -})(Phaser || (Phaser = {})); -var Phaser; -(function (Phaser) { - /// - /** - * Phaser - Easing - Exponential - * - * For use with Phaser.Tween - */ - (function (Easing) { - var Exponential = (function () { - function Exponential() { } - Exponential.In = function In(k) { - return k === 0 ? 0 : Math.pow(1024, k - 1); - }; - Exponential.Out = function Out(k) { - return k === 1 ? 1 : 1 - Math.pow(2, -10 * k); - }; - Exponential.InOut = function InOut(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); - }; - return Exponential; - })(); - Easing.Exponential = Exponential; - })(Phaser.Easing || (Phaser.Easing = {})); - var Easing = Phaser.Easing; -})(Phaser || (Phaser = {})); -var Phaser; -(function (Phaser) { - /// - /** - * Phaser - Easing - Linear - * - * For use with Phaser.Tween - */ - (function (Easing) { - var Linear = (function () { - function Linear() { } - Linear.None = function None(k) { - return k; - }; - return Linear; - })(); - Easing.Linear = Linear; - })(Phaser.Easing || (Phaser.Easing = {})); - var Easing = Phaser.Easing; -})(Phaser || (Phaser = {})); -var Phaser; -(function (Phaser) { - /// - /** - * Phaser - Easing - Quadratic - * - * For use with Phaser.Tween - */ - (function (Easing) { - var Quadratic = (function () { - function Quadratic() { } - Quadratic.In = function In(k) { - return k * k; - }; - Quadratic.Out = function Out(k) { - return k * (2 - k); - }; - Quadratic.InOut = function InOut(k) { - if((k *= 2) < 1) { - return 0.5 * k * k; - } - return -0.5 * (--k * (k - 2) - 1); - }; - return Quadratic; - })(); - Easing.Quadratic = Quadratic; - })(Phaser.Easing || (Phaser.Easing = {})); - var Easing = Phaser.Easing; -})(Phaser || (Phaser = {})); -var Phaser; -(function (Phaser) { - /// - /** - * Phaser - Easing - Quartic - * - * For use with Phaser.Tween - */ - (function (Easing) { - var Quartic = (function () { - function Quartic() { } - Quartic.In = function In(k) { - return k * k * k * k; - }; - Quartic.Out = function Out(k) { - return 1 - (--k * k * k * k); - }; - Quartic.InOut = function InOut(k) { - if((k *= 2) < 1) { - return 0.5 * k * k * k * k; - } - return -0.5 * ((k -= 2) * k * k * k - 2); - }; - return Quartic; - })(); - Easing.Quartic = Quartic; - })(Phaser.Easing || (Phaser.Easing = {})); - var Easing = Phaser.Easing; -})(Phaser || (Phaser = {})); -var Phaser; -(function (Phaser) { - /// - /** - * Phaser - Easing - Quintic - * - * For use with Phaser.Tween - */ - (function (Easing) { - var Quintic = (function () { - function Quintic() { } - Quintic.In = function In(k) { - return k * k * k * k * k; - }; - Quintic.Out = function Out(k) { - return --k * k * k * k * k + 1; - }; - Quintic.InOut = function InOut(k) { - if((k *= 2) < 1) { - return 0.5 * k * k * k * k * k; - } - return 0.5 * ((k -= 2) * k * k * k * k + 2); - }; - return Quintic; - })(); - Easing.Quintic = Quintic; - })(Phaser.Easing || (Phaser.Easing = {})); - var Easing = Phaser.Easing; -})(Phaser || (Phaser = {})); -var Phaser; -(function (Phaser) { - /// - /** - * Phaser - Easing - Sinusoidal - * - * For use with Phaser.Tween - */ - (function (Easing) { - var Sinusoidal = (function () { - function Sinusoidal() { } - Sinusoidal.In = function In(k) { - return 1 - Math.cos(k * Math.PI / 2); - }; - Sinusoidal.Out = function Out(k) { - return Math.sin(k * Math.PI / 2); - }; - Sinusoidal.InOut = function InOut(k) { - return 0.5 * (1 - Math.cos(Math.PI * k)); - }; - return Sinusoidal; - })(); - Easing.Sinusoidal = Sinusoidal; - })(Phaser.Easing || (Phaser.Easing = {})); - var Easing = Phaser.Easing; -})(Phaser || (Phaser = {})); /// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/** -* Phaser - Tween -* -* Based heavily on tween.js by sole (https://github.com/sole/tween.js) converted to TypeScript and integrated into Phaser -*/ -var Phaser; -(function (Phaser) { - var Tween = (function () { - /** - * Tween constructor - * Create a new Tween. - * - * @param object {object} Target object will be affected by this tween. - * @param game {Phaser.Game} Current game instance. - */ - function Tween(object, game) { - /** - * Reference to the target object. - * @type {object} - */ - this._object = null; - this._pausedTime = 0; - /** - * Start values container. - * @type {object} - */ - this._valuesStart = { - }; - /** - * End values container. - * @type {object} - */ - this._valuesEnd = { - }; - /** - * How long this tween will perform. - * @type {number} - */ - this._duration = 1000; - this._delayTime = 0; - this._startTime = null; - /** - * Contains chained tweens. - * @type {Tweens[]} - */ - this._chainedTweens = []; - this._object = object; - this._game = game; - this._manager = this._game.tweens; - this._interpolationFunction = this._game.math.linearInterpolation; - this._easingFunction = Phaser.Easing.Linear.None; - this._chainedTweens = []; - this.onStart = new Phaser.Signal(); - this.onUpdate = new Phaser.Signal(); - this.onComplete = new Phaser.Signal(); - } - Tween.prototype.to = /** - * Configure the Tween - * @param properties {object} Propertis you want to tween. - * @param [duration] {number} duration of this tween. - * @param [ease] {any} Easing function. - * @param [autoStart] {boolean} Whether this tween will start automatically or not. - * @param [delay] {number} delay before this tween will start, defaults to 0 (no delay) - * @return {Tween} Itself. - */ - function (properties, duration, ease, autoStart, delay) { - if (typeof duration === "undefined") { duration = 1000; } - if (typeof ease === "undefined") { ease = null; } - if (typeof autoStart === "undefined") { autoStart = false; } - if (typeof delay === "undefined") { delay = 0; } - this._duration = duration; - // If properties isn't an object this will fail, sanity check it here somehow? - this._valuesEnd = properties; - if(ease !== null) { - this._easingFunction = ease; - } - if(delay > 0) { - this._delayTime = delay; - } - if(autoStart === true) { - return this.start(); - } else { - return this; - } - }; - Tween.prototype.start = /** - * Start to tween. - */ - function () { - if(this._game === null || this._object === null) { - return; - } - this._manager.add(this); - this.onStart.dispatch(this._object); - this._startTime = this._game.time.now + this._delayTime; - for(var property in this._valuesEnd) { - // This prevents the interpolation of null values or of non-existing properties - if(this._object[property] === null || !(property in this._object)) { - throw Error('Phaser.Tween interpolation of null value of non-existing property'); - continue; - } - // check if an Array was provided as property value - if(this._valuesEnd[property] instanceof Array) { - if(this._valuesEnd[property].length === 0) { - continue; - } - // create a local copy of the Array with the start value at the front - this._valuesEnd[property] = [ - this._object[property] - ].concat(this._valuesEnd[property]); - } - this._valuesStart[property] = this._object[property]; - } - return this; - }; - Tween.prototype.stop = /** - * Stop tweening. - */ - function () { - if(this._manager !== null) { - this._manager.remove(this); - } - this.onComplete.dispose(); - return this; - }; - Object.defineProperty(Tween.prototype, "parent", { - set: function (value) { - this._game = value; - this._manager = this._game.tweens; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Tween.prototype, "delay", { - get: function () { - return this._delayTime; - }, - set: function (amount) { - this._delayTime = amount; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Tween.prototype, "easing", { - get: function () { - return this._easingFunction; - }, - set: function (easing) { - this._easingFunction = easing; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Tween.prototype, "interpolation", { - get: function () { - return this._interpolationFunction; - }, - set: function (interpolation) { - this._interpolationFunction = interpolation; - }, - enumerable: true, - configurable: true - }); - Tween.prototype.chain = /** - * Add another chained tween, which will start automatically when the one before it completes. - * @param tween {Phaser.Tween} Tween object you want to chain with this. - * @return {Phaser.Tween} Itselfe. - */ - function (tween) { - this._chainedTweens.push(tween); - return this; - }; - Tween.prototype.update = /** - * Update tweening. - * @param time {number} Current time from game clock. - * @return {boolean} Return false if this completed and no need to update, otherwise return true. - */ - function (time) { - if(this._game.paused == true) { - if(this._pausedTime == 0) { - this._pausedTime = time; - } - } else { - // Ok we aren't paused, but was there some time gained? - if(this._pausedTime > 0) { - this._startTime += (time - this._pausedTime); - this._pausedTime = 0; - } - } - if(time < this._startTime) { - return true; - } - var elapsed = (time - this._startTime) / this._duration; - elapsed = elapsed > 1 ? 1 : elapsed; - var value = this._easingFunction(elapsed); - for(var property in this._valuesStart) { - // Add checks for object, array, numeric up front - if(this._valuesEnd[property] instanceof Array) { - this._object[property] = this._interpolationFunction(this._valuesEnd[property], value); - } else { - this._object[property] = this._valuesStart[property] + (this._valuesEnd[property] - this._valuesStart[property]) * value; - } - } - this.onUpdate.dispatch(this._object, value); - if(elapsed == 1) { - this.onComplete.dispatch(this._object); - for(var i = 0; i < this._chainedTweens.length; i++) { - this._chainedTweens[i].start(); - } - return false; - } - return true; - }; - return Tween; - })(); - Phaser.Tween = Tween; -})(Phaser || (Phaser = {})); -/// -/// +/// /** * Phaser - TweenManager * @@ -11518,606 +7581,10 @@ var Phaser; })(); Phaser.TweenManager = TweenManager; })(Phaser || (Phaser = {})); -var Phaser; -(function (Phaser) { - /// - /// - /** - * Phaser - Verlet - Particle - * - * - */ - (function (Verlet) { - var Particle = (function () { - /** - * Creates a new Particle object. - * @class Particle - * @constructor - * @param {Number} x The x coordinate of vector2 - * @param {Number} y The y coordinate of vector2 - * @return {Particle} This object - **/ - function Particle(pos) { - this.pos = (new Phaser.Vector2()).mutableSet(pos); - this.lastPos = (new Phaser.Vector2()).mutableSet(pos); - } - Particle.prototype.render = function (ctx) { - ctx.beginPath(); - ctx.arc(this.pos.x, this.pos.y, 2, 0, 2 * Math.PI); - ctx.fillStyle = "#2dad8f"; - ctx.fill(); - }; - return Particle; - })(); - Verlet.Particle = Particle; - })(Phaser.Verlet || (Phaser.Verlet = {})); - var Verlet = Phaser.Verlet; -})(Phaser || (Phaser = {})); -var Phaser; -(function (Phaser) { - /// - /// - /// - /** - * Phaser - PinConstraint - * - * Constrains to static / fixed point - */ - (function (Verlet) { - var PinConstraint = (function () { - /** - * Creates a new PinConstraint object. - * @class PinConstraint - * @constructor - * @param {Number} x The x coordinate of vector2 - * @param {Number} y The y coordinate of vector2 - * @return {PinConstraint} This object - **/ - function PinConstraint(a, pos) { - this.a = a; - this.pos = (new Phaser.Vector2()).mutableSet(pos); - } - PinConstraint.prototype.relax = function () { - this.a.pos.mutableSet(this.pos); - }; - PinConstraint.prototype.render = function (ctx) { - ctx.beginPath(); - ctx.arc(this.pos.x, this.pos.y, 6, 0, 2 * Math.PI); - ctx.fillStyle = "rgba(0,153,255,0.1)"; - ctx.fill(); - }; - return PinConstraint; - })(); - Verlet.PinConstraint = PinConstraint; - })(Phaser.Verlet || (Phaser.Verlet = {})); - var Verlet = Phaser.Verlet; -})(Phaser || (Phaser = {})); -var Phaser; -(function (Phaser) { - /// - /// - /// - /// - /** - * Phaser - Verlet - Composite - * - * - */ - (function (Verlet) { - var Composite = (function () { - /** - * Creates a new Composite object. - * @class Composite - * @constructor - * @param {Number} x The x coordinate of vector2 - * @param {Number} y The y coordinate of vector2 - * @return {Composite} This object - **/ - function Composite(game) { - /** - * Texture of the particles to be rendered. - */ - this._texture = null; - // local rendering related temp vars to help avoid gc spikes - this._sx = 0; - this._sy = 0; - this._sw = 0; - this._sh = 0; - this._dx = 0; - this._dy = 0; - this._dw = 0; - this._dh = 0; - this._hw = 0; - this._hh = 0; - this.drawParticles = null; - this.drawConstraints = null; - this.hideConstraints = true; - this.constraintLineColor = 'rgba(200,200,200,1)'; - this._game = game; - this.sprites = []; - this.particles = []; - this.constraints = []; - this.frameBounds = new Phaser.Quad(); - } - Composite.prototype.createDistanceConstraint = // Create Constraints - function (a, b, stiffness, distance) { - if (typeof distance === "undefined") { distance = null; } - this.constraints.push(new Phaser.Verlet.DistanceConstraint(a, b, stiffness, distance)); - return this.constraints[this.constraints.length - 1]; - }; - Composite.prototype.createAngleConstraint = function (a, b, c, stiffness) { - this.constraints.push(new Phaser.Verlet.AngleConstraint(a, b, c, stiffness)); - return this.constraints[this.constraints.length - 1]; - }; - Composite.prototype.createPinConstraint = function (a, pos) { - this.constraints.push(new Phaser.Verlet.PinConstraint(a, pos)); - return this.constraints[this.constraints.length - 1]; - }; - Composite.prototype.loadGraphic = /** - * Load a graphic for this Composite. The graphic cannot be a SpriteSheet yet. - * @param key {string} Key of the graphic you want to load for this sprite. - * @return {Composite} This object - */ - function (key) { - if(this._game.cache.getImage(key) !== null) { - if(this._game.cache.isSpriteSheet(key) == false) { - this._texture = this._game.cache.getImage(key); - this.frameBounds.width = this._texture.width; - this.frameBounds.height = this._texture.height; - this._hw = Math.floor(this.frameBounds.width / 2); - this._hh = Math.floor(this.frameBounds.width / 2); - this.drawParticles = this.render; - this.drawConstraints = this.renderConstraints; - } - } - return this; - }; - Composite.prototype.renderConstraints = function (context) { - if(this.hideConstraints == true || this.constraints.length == 0) { - return; - } - var i; - context.beginPath(); - for(i in this.constraints) { - if(this.constraints[i].b) { - context.moveTo(this.constraints[i].a.pos.x, this.constraints[i].a.pos.y); - context.lineTo(this.constraints[i].b.pos.x, this.constraints[i].b.pos.y); - } - } - context.strokeStyle = this.constraintLineColor; - context.stroke(); - context.closePath(); - }; - Composite.prototype.render = function (context) { - this._sx = 0; - this._sy = 0; - this._sw = this.frameBounds.width; - this._sh = this.frameBounds.height; - this._dw = this.frameBounds.width; - this._dh = this.frameBounds.height; - this._sx = Math.round(this._sx); - this._sy = Math.round(this._sy); - this._sw = Math.round(this._sw); - this._sh = Math.round(this._sh); - this._dw = Math.round(this._dw); - this._dh = Math.round(this._dh); - var i; - for(i in this.particles) { - //this._dx = cameraOffsetX + (this.frameBounds.topLeft.x - camera.worldView.x); - //this._dy = cameraOffsetY + (this.frameBounds.topLeft.y - camera.worldView.y); - this._dx = this.particles[i].pos.x - this._hw; - this._dy = this.particles[i].pos.y - this._hh; - this._dx = Math.round(this._dx); - this._dy = Math.round(this._dy); - context.drawImage(this._texture, // Source Image - this._sx, // Source X (location within the source image) - this._sy, // Source Y - this._sw, // Source Width - this._sh, // Source Height - this._dx, // Destination X (where on the canvas it'll be drawn) - this._dy, // Destination Y - this._dw, // Destination Width (always same as Source Width unless scaled) - this._dh); - // Destination Height (always same as Source Height unless scaled) - } - }; - Composite.prototype.pin = function (index, pos) { - if (typeof pos === "undefined") { pos = null; } - if(pos == null) { - pos = this.particles[index].pos; - } - var pc = new Phaser.Verlet.PinConstraint(this.particles[index], pos); - this.constraints.push(pc); - return pc; - }; - return Composite; - })(); - Verlet.Composite = Composite; - })(Phaser.Verlet || (Phaser.Verlet = {})); - var Verlet = Phaser.Verlet; -})(Phaser || (Phaser = {})); -var Phaser; -(function (Phaser) { - /// - /// - /// - /** - * Phaser - DistanceConstraint - * - * Constrains to initial distance - */ - (function (Verlet) { - var DistanceConstraint = (function () { - /** - * Creates a new DistanceConstraint object. - * @class DistanceConstraint - * @constructor - * @param {Number} x The x coordinate of vector2 - * @param {Number} y The y coordinate of vector2 - * @return {DistanceConstraint} This object - **/ - function DistanceConstraint(a, b, stiffness, distance) { - if (typeof distance === "undefined") { distance = null; } - this.a = a; - this.b = b; - if(distance === null) { - this.distance = a.pos.sub(b.pos).length(); - } else { - this.distance = distance; - } - this.stiffness = stiffness; - } - DistanceConstraint.prototype.relax = function (stepCoef) { - var normal = this.a.pos.sub(this.b.pos); - var m = normal.length2(); - normal.mutableScale(((this.distance * this.distance - m) / m) * this.stiffness * stepCoef); - this.a.pos.mutableAdd(normal); - this.b.pos.mutableSub(normal); - }; - DistanceConstraint.prototype.render = function (ctx) { - ctx.beginPath(); - ctx.moveTo(this.a.pos.x, this.a.pos.y); - ctx.lineTo(this.b.pos.x, this.b.pos.y); - ctx.strokeStyle = "#d8dde2"; - ctx.stroke(); - ctx.closePath(); - }; - return DistanceConstraint; - })(); - Verlet.DistanceConstraint = DistanceConstraint; - })(Phaser.Verlet || (Phaser.Verlet = {})); - var Verlet = Phaser.Verlet; -})(Phaser || (Phaser = {})); -var Phaser; -(function (Phaser) { - /// - /// - /// - /** - * Phaser - AngleConstraint - * - * constrains 3 particles to an angle - */ - (function (Verlet) { - var AngleConstraint = (function () { - /** - * Creates a new AngleConstraint object. - * @class AngleConstraint - * @constructor - * @param {Number} x The x coordinate of vector2 - * @param {Number} y The y coordinate of vector2 - * @return {AngleConstraint} This object - **/ - function AngleConstraint(a, b, c, stiffness) { - this.a = a; - this.b = b; - this.c = c; - this.angle = this.b.pos.angle2(this.a.pos, this.c.pos); - this.stiffness = stiffness; - } - AngleConstraint.prototype.relax = function (stepCoef) { - var angle = this.b.pos.angle2(this.a.pos, this.c.pos); - var diff = angle - this.angle; - if(diff <= -Math.PI) { - diff += 2 * Math.PI; - } else if(diff >= Math.PI) { - diff -= 2 * Math.PI; - } - diff *= stepCoef * this.stiffness; - this.a.pos = this.a.pos.rotate(this.b.pos, diff); - this.c.pos = this.c.pos.rotate(this.b.pos, -diff); - this.b.pos = this.b.pos.rotate(this.a.pos, diff); - this.b.pos = this.b.pos.rotate(this.c.pos, -diff); - }; - AngleConstraint.prototype.render = function (ctx) { - ctx.beginPath(); - ctx.moveTo(this.a.pos.x, this.a.pos.y); - ctx.lineTo(this.b.pos.x, this.b.pos.y); - ctx.lineTo(this.c.pos.x, this.c.pos.y); - var tmp = ctx.lineWidth; - ctx.lineWidth = 5; - ctx.strokeStyle = "rgba(255,255,0,0.2)"; - ctx.stroke(); - ctx.lineWidth = tmp; - }; - return AngleConstraint; - })(); - Verlet.AngleConstraint = AngleConstraint; - })(Phaser.Verlet || (Phaser.Verlet = {})); - var Verlet = Phaser.Verlet; -})(Phaser || (Phaser = {})); -var Phaser; -(function (Phaser) { - /// - /// - /// - /// - /// - /// - /// - /** - * Phaser - Verlet - * - * Based on verlet-js by Sub Protocol released under MIT - */ - (function (Verlet) { - var VerletManager = (function () { - /** - * Creates a new Vector2 object. - * @class Vector2 - * @constructor - * @param {Number} x The x coordinate of vector2 - * @param {Number} y The y coordinate of vector2 - * @return {Vector2} This object - **/ - function VerletManager(game, width, height) { - this._v = new Phaser.Vector2(); - this.composites = []; - this.step = 16; - this.selectionRadius = 20; - this.draggedEntity = null; - this.highlightColor = '#4f545c'; - this.hideNearestEntityCircle = false; - this._game = game; - this.width = width; - this.height = height; - this.gravity = new Phaser.Vector2(0, 0.2); - this.friction = 0.99; - this.groundFriction = 0.8; - this.canvas = game.stage.canvas; - this.context = game.stage.context; - this._game.input.onDown.add(this.mouseDownHandler, this); - this._game.input.onUp.add(this.mouseUpHandler, this); - } - VerletManager.prototype.intersectionTime = /** - * Computes time of intersection of a particle with a wall - * - * @param {Vec2} line walls root position - * @param {Vec2} p particle position - * @param {Vec2} dir walls direction - * @param {Vec2} v particles velocity - */ - function (wall, p, dir, v) { - if(dir.x != 0) { - var denominator = v.y - dir.y * v.x / dir.x; - if(denominator == 0) { - return undefined; - }// Movement is parallel to wall - - var numerator = wall.y + dir.y * (p.x - wall.x) / dir.x - p.y; - return numerator / denominator; - } else { - if(v.x == 0) { - return undefined; - }// parallel again - - var denominator = v.x; - var numerator = wall.x - p.x; - return numerator / denominator; - } - }; - VerletManager.prototype.intersectionPoint = function (wall, p, dir, v) { - var t = this.intersectionTime(wall, p, dir, v); - return new Phaser.Vector2(p.x + v.x * t, p.y + v.y * t); - }; - VerletManager.prototype.bounds = function (particle) { - this._v.mutableSet(particle.pos); - this._v.mutableSub(particle.lastPos); - if(particle.pos.y > this.height - 1) { - particle.pos.mutableSet(this.intersectionPoint(new Phaser.Vector2(0, this.height - 1), particle.lastPos, new Phaser.Vector2(1, 0), this._v)); - } - if(particle.pos.x < 0) { - particle.pos.mutableSet(this.intersectionPoint(new Phaser.Vector2(0, 0), particle.pos, new Phaser.Vector2(0, 1), this._v)); - } - if(particle.pos.x > this.width - 1) { - particle.pos.mutableSet(this.intersectionPoint(new Phaser.Vector2(this.width - 1, 0), particle.pos, new Phaser.Vector2(0, 1), this._v)); - } - }; - VerletManager.prototype.createPoint = function (pos) { - var composite = new Phaser.Verlet.Composite(this._game); - composite.particles.push(new Phaser.Verlet.Particle(pos)); - this.composites.push(composite); - return composite; - }; - VerletManager.prototype.createLineSegments = function (vertices, stiffness) { - var composite = new Phaser.Verlet.Composite(this._game); - var i; - for(i in vertices) { - composite.particles.push(new Phaser.Verlet.Particle(vertices[i])); - if(i > 0) { - composite.constraints.push(new Phaser.Verlet.DistanceConstraint(composite.particles[i], composite.particles[i - 1], stiffness)); - } - } - this.composites.push(composite); - return composite; - }; - VerletManager.prototype.createCloth = function (origin, width, height, segments, pinMod, stiffness) { - var composite = new Phaser.Verlet.Composite(this._game); - var xStride = width / segments; - var yStride = height / segments; - var x; - var y; - for(y = 0; y < segments; ++y) { - for(x = 0; x < segments; ++x) { - var px = origin.x + x * xStride - width / 2 + xStride / 2; - var py = origin.y + y * yStride - height / 2 + yStride / 2; - composite.particles.push(new Phaser.Verlet.Particle(new Phaser.Vector2(px, py))); - if(x > 0) { - composite.constraints.push(new Phaser.Verlet.DistanceConstraint(composite.particles[y * segments + x], composite.particles[y * segments + x - 1], stiffness)); - } - if(y > 0) { - composite.constraints.push(new Phaser.Verlet.DistanceConstraint(composite.particles[y * segments + x], composite.particles[(y - 1) * segments + x], stiffness)); - } - } - } - for(x = 0; x < segments; ++x) { - if(x % pinMod == 0) { - composite.pin(x); - } - } - this.composites.push(composite); - return composite; - }; - VerletManager.prototype.createTire = function (origin, radius, segments, spokeStiffness, treadStiffness) { - var stride = (2 * Math.PI) / segments; - var i; - var composite = new Phaser.Verlet.Composite(this._game); - // particles - for(i = 0; i < segments; ++i) { - var theta = i * stride; - composite.particles.push(new Verlet.Particle(new Phaser.Vector2(origin.x + Math.cos(theta) * radius, origin.y + Math.sin(theta) * radius))); - } - var center = new Verlet.Particle(origin); - composite.particles.push(center); - // constraints - for(i = 0; i < segments; ++i) { - composite.constraints.push(new Verlet.DistanceConstraint(composite.particles[i], composite.particles[(i + 1) % segments], treadStiffness)); - composite.constraints.push(new Verlet.DistanceConstraint(composite.particles[i], center, spokeStiffness)); - composite.constraints.push(new Verlet.DistanceConstraint(composite.particles[i], composite.particles[(i + 5) % segments], treadStiffness)); - } - this.composites.push(composite); - return composite; - }; - VerletManager.prototype.update = function () { - if(this.composites.length == 0) { - return; - } - var i, j, c; - for(c in this.composites) { - for(i in this.composites[c].particles) { - var particles = this.composites[c].particles; - // calculate velocity - var velocity = particles[i].pos.sub(particles[i].lastPos).scale(this.friction); - // ground friction - if(particles[i].pos.y >= this.height - 1 && velocity.length2() > 0.000001) { - var m = velocity.length(); - velocity.x /= m; - velocity.y /= m; - velocity.mutableScale(m * this.groundFriction); - } - // save last good state - particles[i].lastPos.mutableSet(particles[i].pos); - // gravity - particles[i].pos.mutableAdd(this.gravity); - // inertia - particles[i].pos.mutableAdd(velocity); - } - } - // handle dragging of entities - if(this.draggedEntity) { - this.draggedEntity.pos.mutableSet(this._game.input.position); - } - // relax - var stepCoef = 1 / this.step; - for(c in this.composites) { - var constraints = this.composites[c].constraints; - for(i = 0; i < this.step; ++i) { - for(j in constraints) { - constraints[j].relax(stepCoef); - } - } - } - // bounds checking - for(c in this.composites) { - var particles = this.composites[c].particles; - for(i in particles) { - this.bounds(particles[i]); - } - } - }; - VerletManager.prototype.mouseDownHandler = function () { - var nearest = this.nearestEntity(); - if(nearest) { - this.draggedEntity = nearest; - } - }; - VerletManager.prototype.mouseUpHandler = function () { - this.draggedEntity = null; - }; - VerletManager.prototype.nearestEntity = function () { - var c, i; - var d2Nearest = 0; - var entity = null; - var constraintsNearest = null; - // find nearest point - for(c in this.composites) { - var particles = this.composites[c].particles; - for(i in particles) { - var d2 = particles[i].pos.distance2(this._game.input.position); - if(d2 <= this.selectionRadius * this.selectionRadius && (entity == null || d2 < d2Nearest)) { - entity = particles[i]; - constraintsNearest = this.composites[c].constraints; - d2Nearest = d2; - } - } - } - // search for pinned constraints for this entity - for(i in constraintsNearest) { - if(constraintsNearest[i] instanceof Verlet.PinConstraint && constraintsNearest[i].a == entity) { - entity = constraintsNearest[i]; - } - } - return entity; - }; - VerletManager.prototype.render = function () { - var i, c; - for(c in this.composites) { - // draw constraints - if(this.composites[c].drawConstraints) { - this.composites[c].drawConstraints(this.context, this.composites[c]); - } else { - var constraints = this.composites[c].constraints; - for(i in constraints) { - constraints[i].render(this.context); - } - } - // draw particles - if(this.composites[c].drawParticles) { - this.composites[c].drawParticles(this.context, this.composites[c]); - } else { - var particles = this.composites[c].particles; - for(i in particles) { - particles[i].render(this.context); - } - } - } - // highlight nearest / dragged entity - var nearest = this.draggedEntity || this.nearestEntity(); - if(nearest && this.hideNearestEntityCircle == false) { - this.context.beginPath(); - this.context.arc(nearest.pos.x, nearest.pos.y, 8, 0, 2 * Math.PI); - this.context.strokeStyle = this.highlightColor; - this.context.stroke(); - this.context.closePath(); - } - }; - return VerletManager; - })(); - Verlet.VerletManager = VerletManager; - })(Phaser.Verlet || (Phaser.Verlet = {})); - var Verlet = Phaser.Verlet; -})(Phaser || (Phaser = {})); /// +/// +/// +/// /** * Phaser - World * @@ -12145,21 +7612,12 @@ var Phaser; this.worldDivisions = 6; } World.prototype.update = /** - * This is called automatically every frame, and is where main logic performs. + * This is called automatically every frame, and is where main logic happens. */ function () { - this.group.preUpdate(); this.group.update(); - this.group.postUpdate(); this.cameras.update(); }; - World.prototype.render = /** - * Render every thing to the screen, automatically called after update(). - */ - function () { - // Unlike in flixel our render process is camera driven, not group driven - this.cameras.render(); - }; World.prototype.destroy = /** * Clean up memory. */ @@ -12167,29 +7625,22 @@ var Phaser; this.group.destroy(); this.cameras.destroy(); }; - World.prototype.setSize = // World methods - /** - * Update size of this world with specific width and height. - * You can choose update camera bounds and verlet manager automatically or not. + World.prototype.setSize = /** + * Updates the size of this world. * * @param width {number} New width of the world. * @param height {number} New height of the world. - * @param [updateCameraBounds] {boolean} update camera bounds automatically or not. Default to true. - * @param [updateVerletBounds] {boolean} update verlet bounds automatically or not. Default to true. + * @param [updateCameraBounds] {boolean} Update camera bounds automatically or not. Default to true. */ - function (width, height, updateCameraBounds, updateVerletBounds) { + function (width, height, updateCameraBounds) { if (typeof updateCameraBounds === "undefined") { updateCameraBounds = true; } - if (typeof updateVerletBounds === "undefined") { updateVerletBounds = true; } this.bounds.width = width; this.bounds.height = height; if(updateCameraBounds == true) { this._game.camera.setBounds(0, 0, width, height); } - if(updateVerletBounds == true) { - this._game.verlet.width = width; - this._game.verlet.height = height; - } - }; + // dispatch world resize event + }; Object.defineProperty(World.prototype, "width", { get: function () { return this.bounds.width; @@ -12238,28 +7689,6 @@ var Phaser; enumerable: true, configurable: true }); - World.prototype.createCamera = // Cameras - /** - * Create a new camera with specific position and size. - * - * @param x {number} X position of the new camera. - * @param y {number} Y position of the new camera. - * @param width {number} Width of the new camera. - * @param height {number} Height of the new camera. - * @returns {Camera} The newly created camera object. - */ - function (x, y, width, height) { - return this.cameras.addCamera(x, y, width, height); - }; - World.prototype.removeCamera = /** - * Remove a new camera with its id. - * - * @param id {number} ID of the camera you want to remove. - * @returns {boolean} True if successfully removed the camera, otherwise return false. - */ - function (id) { - return this.cameras.removeCamera(id); - }; World.prototype.getAllCameras = /** * Get all the cameras. * @@ -12268,105 +7697,6 @@ var Phaser; function () { return this.cameras.getAll(); }; - World.prototype.createSprite = // Game Objects - /** - * Create a new Sprite with specific position and sprite sheet key. - * - * @param x {number} X position of the new sprite. - * @param y {number} Y position of the new sprite. - * @param [key] {string} key for the sprite sheet you want it to use. - * @returns {Sprite} The newly created sprite object. - */ - function (x, y, key) { - if (typeof key === "undefined") { key = ''; } - return this.group.add(new Phaser.Sprite(this._game, x, y, key)); - }; - World.prototype.createGeomSprite = /** - * Create a new GeomSprite with specific position. - * - * @param x {number} X position of the new geom sprite. - * @param y {number} Y position of the new geom sprite. - * @returns {GeomSprite} The newly created geom sprite object. - */ - function (x, y) { - return this.group.add(new Phaser.GeomSprite(this._game, x, y)); - }; - World.prototype.createDynamicTexture = /** - * Create a new DynamicTexture with specific size. - * - * @param width {number} Width of the texture. - * @param height {number} Height of the texture. - * @returns {DynamicTexture} The newly created dynamic texture object. - */ - function (width, height) { - return new Phaser.DynamicTexture(this._game, width, height); - }; - World.prototype.createGroup = /** - * Create a new object container. - * - * @param [maxSize] {number} capacity of this group. - * @returns {Group} The newly created group. - */ - function (maxSize) { - if (typeof maxSize === "undefined") { maxSize = 0; } - return this.group.add(new Phaser.Group(this._game, maxSize)); - }; - World.prototype.createScrollZone = /** - * Create a new ScrollZone object with image key, position and size. - * - * @param key {number} Key to a image you wish this object to use. - * @param x {number} X position of this object. - * @param y {number} Y position of this object. - * @param width {number} Width of this object. - * @param height {number} Height of this object. - * @returns {ScrollZone} The newly created scroll zone object. - */ - function (key, x, y, width, height) { - if (typeof x === "undefined") { x = 0; } - if (typeof y === "undefined") { y = 0; } - if (typeof width === "undefined") { width = 0; } - if (typeof height === "undefined") { height = 0; } - return this.group.add(new Phaser.ScrollZone(this._game, key, x, y, width, height)); - }; - World.prototype.createTilemap = /** - * Create a new Tilemap. - * - * @param key {string} Key for tileset image. - * @param mapData {string} Data of this tilemap. - * @param format {number} Format of map data. (Tilemap.FORMAT_CSV or Tilemap.FORMAT_TILED_JSON) - * @param [resizeWorld] {boolean} resize the world to make same as tilemap? - * @param [tileWidth] {number} width of each tile. - * @param [tileHeight] {number} height of each tile. - * @return {Tilemap} The newly created tilemap object. - */ - function (key, mapData, format, resizeWorld, tileWidth, tileHeight) { - if (typeof resizeWorld === "undefined") { resizeWorld = true; } - if (typeof tileWidth === "undefined") { tileWidth = 0; } - if (typeof tileHeight === "undefined") { tileHeight = 0; } - return this.group.add(new Phaser.Tilemap(this._game, key, mapData, format, resizeWorld, tileWidth, tileHeight)); - }; - World.prototype.createParticle = /** - * Create a new Particle. - * - * @return {Particle} The newly created particle object. - */ - function () { - return new Phaser.Particle(this._game); - }; - World.prototype.createEmitter = /** - * Create a new Emitter. - * - * @param [x] {number} x position of the emitter. - * @param [y] {number} y position of the emitter. - * @param [size] {number} size of this emitter. - * @return {Emitter} The newly created emitter object. - */ - function (x, y, size) { - if (typeof x === "undefined") { x = 0; } - if (typeof y === "undefined") { y = 0; } - if (typeof size === "undefined") { size = 0; } - return this.group.add(new Phaser.Emitter(this._game, x, y, size)); - }; return World; })(); Phaser.World = World; @@ -12789,233 +8119,6 @@ var Phaser; })(Phaser || (Phaser = {})); /// /** -* Phaser - RandomDataGenerator -* -* An extremely useful repeatable random data generator. Access it via Game.rnd -* Based on Nonsense by Josh Faul https://github.com/jocafa/Nonsense -* Random number generator from http://baagoe.org/en/wiki/Better_random_numbers_for_javascript -*/ -var Phaser; -(function (Phaser) { - var RandomDataGenerator = (function () { - /** - * @constructor - * @param {Array} seeds - * @return {Phaser.RandomDataGenerator} - */ - function RandomDataGenerator(seeds) { - if (typeof seeds === "undefined") { seeds = []; } - /** - * @property c - * @type Number - * @private - */ - this.c = 1; - this.sow(seeds); - } - RandomDataGenerator.prototype.uint32 = /** - * @method uint32 - * @private - */ - function () { - return this.rnd.apply(this) * 0x100000000;// 2^32 - - }; - RandomDataGenerator.prototype.fract32 = /** - * @method fract32 - * @private - */ - function () { - return this.rnd.apply(this) + (this.rnd.apply(this) * 0x200000 | 0) * 1.1102230246251565e-16;// 2^-53 - - }; - RandomDataGenerator.prototype.rnd = // private random helper - /** - * @method rnd - * @private - */ - function () { - var t = 2091639 * this.s0 + this.c * 2.3283064365386963e-10;// 2^-32 - - this.c = t | 0; - this.s0 = this.s1; - this.s1 = this.s2; - this.s2 = t - this.c; - return this.s2; - }; - RandomDataGenerator.prototype.hash = /** - * @method hash - * @param {Any} data - * @private - */ - function (data) { - var h, i, n; - n = 0xefc8249d; - data = data.toString(); - for(i = 0; i < data.length; i++) { - n += data.charCodeAt(i); - h = 0.02519603282416938 * n; - n = h >>> 0; - h -= n; - h *= n; - n = h >>> 0; - h -= n; - n += h * 0x100000000// 2^32 - ; - } - return (n >>> 0) * 2.3283064365386963e-10;// 2^-32 - - }; - RandomDataGenerator.prototype.sow = /** - * Reset the seed of the random data generator - * @method sow - * @param {Array} seeds - */ - function (seeds) { - if (typeof seeds === "undefined") { seeds = []; } - this.s0 = this.hash(' '); - this.s1 = this.hash(this.s0); - this.s2 = this.hash(this.s1); - var seed; - for(var i = 0; seed = seeds[i++]; ) { - this.s0 -= this.hash(seed); - this.s0 += ~~(this.s0 < 0); - this.s1 -= this.hash(seed); - this.s1 += ~~(this.s1 < 0); - this.s2 -= this.hash(seed); - this.s2 += ~~(this.s2 < 0); - } - }; - Object.defineProperty(RandomDataGenerator.prototype, "integer", { - get: /** - * Returns a random integer between 0 and 2^32 - * @method integer - * @return {Number} - */ - function () { - return this.uint32(); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(RandomDataGenerator.prototype, "frac", { - get: /** - * Returns a random real number between 0 and 1 - * @method frac - * @return {Number} - */ - function () { - return this.fract32(); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(RandomDataGenerator.prototype, "real", { - get: /** - * Returns a random real number between 0 and 2^32 - * @method real - * @return {Number} - */ - function () { - return this.uint32() + this.fract32(); - }, - enumerable: true, - configurable: true - }); - RandomDataGenerator.prototype.integerInRange = /** - * Returns a random integer between min and max - * @method integerInRange - * @param {Number} min - * @param {Number} max - * @return {Number} - */ - function (min, max) { - return Math.floor(this.realInRange(min, max)); - }; - RandomDataGenerator.prototype.realInRange = /** - * Returns a random real number between min and max - * @method realInRange - * @param {Number} min - * @param {Number} max - * @return {Number} - */ - function (min, max) { - min = min || 0; - max = max || 0; - return this.frac * (max - min) + min; - }; - Object.defineProperty(RandomDataGenerator.prototype, "normal", { - get: /** - * Returns a random real number between -1 and 1 - * @method normal - * @return {Number} - */ - function () { - return 1 - 2 * this.frac; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(RandomDataGenerator.prototype, "uuid", { - get: /** - * Returns a valid v4 UUID hex string (from https://gist.github.com/1308368) - * @method uuid - * @return {String} - */ - function () { - var a, b; - for(b = a = ''; a++ < 36; b += ~a % 5 | a * 3 & 4 ? (a ^ 15 ? 8 ^ this.frac * (a ^ 20 ? 16 : 4) : 4).toString(16) : '-') { - ; - } - return b; - }, - enumerable: true, - configurable: true - }); - RandomDataGenerator.prototype.pick = /** - * Returns a random member of `array` - * @method pick - * @param {Any} array - */ - function (array) { - return array[this.integerInRange(0, array.length)]; - }; - RandomDataGenerator.prototype.weightedPick = /** - * Returns a random member of `array`, favoring the earlier entries - * @method weightedPick - * @param {Any} array - */ - function (array) { - return array[~~(Math.pow(this.frac, 2) * array.length)]; - }; - RandomDataGenerator.prototype.timestamp = /** - * 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 timestamp - * @param {Number} min - * @param {Number} max - */ - function (min, max) { - if (typeof min === "undefined") { min = 946684800000; } - if (typeof max === "undefined") { max = 1577862000000; } - return this.realInRange(min, max); - }; - Object.defineProperty(RandomDataGenerator.prototype, "angle", { - get: /** - * Returns a random angle between -180 and 180 - * @method angle - */ - function () { - return this.integerInRange(-180, 180); - }, - enumerable: true, - configurable: true - }); - return RandomDataGenerator; - })(); - Phaser.RandomDataGenerator = RandomDataGenerator; -})(Phaser || (Phaser = {})); -/// -/** * Phaser - RequestAnimationFrame * * Abstracts away the use of RAF or setTimeOut for the core game update loop. The callback can be re-mapped on the fly. @@ -13140,8 +8243,499 @@ var Phaser; })(); Phaser.RequestAnimationFrame = RequestAnimationFrame; })(Phaser || (Phaser = {})); -/// -/// +/// +/// +/** +* Phaser - PointUtils +* +* A collection of methods useful for manipulating and comparing Point objects. +* +* TODO: interpolate & polar +*/ +var Phaser; +(function (Phaser) { + var PointUtils = (function () { + function PointUtils() { } + PointUtils.add = /** + * Adds the coordinates of two points together to create a new point. + * @method add + * @param {Point} a - The first Point object. + * @param {Point} b - The second Point object. + * @param {Point} out - Optional Point to store the value in, if not supplied a new Point object will be created. + * @return {Point} The new Point object. + **/ + function add(a, b, out) { + if (typeof out === "undefined") { out = new Phaser.Point(); } + return out.setTo(a.x + b.x, a.y + b.y); + }; + PointUtils.subtract = /** + * Subtracts the coordinates of two points to create a new point. + * @method subtract + * @param {Point} a - The first Point object. + * @param {Point} b - The second Point object. + * @param {Point} out - Optional Point to store the value in, if not supplied a new Point object will be created. + * @return {Point} The new Point object. + **/ + function subtract(a, b, out) { + if (typeof out === "undefined") { out = new Phaser.Point(); } + return out.setTo(a.x - b.x, a.y - b.y); + }; + PointUtils.multiply = /** + * Multiplies the coordinates of two points to create a new point. + * @method subtract + * @param {Point} a - The first Point object. + * @param {Point} b - The second Point object. + * @param {Point} out - Optional Point to store the value in, if not supplied a new Point object will be created. + * @return {Point} The new Point object. + **/ + function multiply(a, b, out) { + if (typeof out === "undefined") { out = new Phaser.Point(); } + return out.setTo(a.x * b.x, a.y * b.y); + }; + PointUtils.divide = /** + * Divides the coordinates of two points to create a new point. + * @method subtract + * @param {Point} a - The first Point object. + * @param {Point} b - The second Point object. + * @param {Point} out - Optional Point to store the value in, if not supplied a new Point object will be created. + * @return {Point} The new Point object. + **/ + function divide(a, b, out) { + if (typeof out === "undefined") { out = new Phaser.Point(); } + return out.setTo(a.x / b.x, a.y / b.y); + }; + PointUtils.clamp = /** + * Clamps the Point object values to be between the given min and max + * @method clamp + * @param {Point} a - The point. + * @param {number} The minimum value to clamp this Point to + * @param {number} The maximum value to clamp this Point to + * @return {Point} This Point object. + **/ + function clamp(a, min, max) { + PointUtils.clampX(a, min, max); + PointUtils.clampY(a, min, max); + return a; + }; + PointUtils.clampX = /** + * Clamps the x value of the given Point object to be between the min and max values. + * @method clampX + * @param {Point} a - The point. + * @param {number} The minimum value to clamp this Point to + * @param {number} The maximum value to clamp this Point to + * @return {Point} This Point object. + **/ + function clampX(a, min, max) { + a.x = Math.max(Math.min(a.x, max), min); + return a; + }; + PointUtils.clampY = /** + * Clamps the y value of the given Point object to be between the min and max values. + * @method clampY + * @param {Point} a - The point. + * @param {number} The minimum value to clamp this Point to + * @param {number} The maximum value to clamp this Point to + * @return {Point} This Point object. + **/ + function clampY(a, min, max) { + a.y = Math.max(Math.min(a.y, max), min); + return a; + }; + PointUtils.clone = /** + * Creates a copy of the given Point. + * @method clone + * @param {Point} output Optional Point object. If given the values will be set into this object, otherwise a brand new Point object will be created and returned. + * @return {Point} The new Point object. + **/ + function clone(a, output) { + if (typeof output === "undefined") { output = new Phaser.Point(); } + return output.setTo(a.x, a.y); + }; + PointUtils.distanceBetween = /** + * Returns the distance between the two given Point objects. + * @method distanceBetween + * @param {Point} a - The first Point object. + * @param {Point} b - The second Point object. + * @param {Boolean} round - Round the distance to the nearest integer (default false) + * @return {Number} The distance between the two Point objects. + **/ + function distanceBetween(a, b, round) { + if (typeof round === "undefined") { round = false; } + var dx = a.x - b.x; + var dy = a.y - b.y; + if(round === true) { + return Math.round(Math.sqrt(dx * dx + dy * dy)); + } else { + return Math.sqrt(dx * dx + dy * dy); + } + }; + PointUtils.equals = /** + * Determines whether the two given Point objects are equal. They are considered equal if they have the same x and y values. + * @method equals + * @param {Point} a - The first Point object. + * @param {Point} b - The second Point object. + * @return {Boolean} A value of true if the Points are equal, otherwise false. + **/ + function equals(a, b) { + return (a.x == b.x && a.y == b.y); + }; + PointUtils.rotate = /** + * Determines a point between two specified points. The parameter f determines where the new interpolated point is located relative to the two end points specified by parameters pt1 and pt2. + * The closer the value of the parameter f is to 1.0, the closer the interpolated point is to the first point (parameter pt1). The closer the value of the parameter f is to 0, the closer the interpolated point is to the second point (parameter pt2). + * @method interpolate + * @param {Point} pointA - The first Point object. + * @param {Point} pointB - The second Point object. + * @param {Number} f - The level of interpolation between the two points. Indicates where the new point will be, along the line between pt1 and pt2. If f=1, pt1 is returned; if f=0, pt2 is returned. + * @return {Point} The new interpolated Point object. + **/ + //static interpolate(pointA, pointB, f) { + //} + /** + * Converts a pair of polar coordinates to a Cartesian point coordinate. + * @method polar + * @param {Number} length - The length coordinate of the polar pair. + * @param {Number} angle - The angle, in radians, of the polar pair. + * @return {Point} The new Cartesian Point object. + **/ + //static polar(length, angle) { + //} + /** + * Rotates a Point around the x/y coordinates given to the desired angle. + * @param a {Point} The Point object to rotate. + * @param x {number} The x coordinate of the anchor point + * @param y {number} The y coordinate of the anchor point + * @param {Number} angle The angle in radians (unless asDegrees is true) to rotate the Point to. + * @param {Boolean} asDegrees Is the given angle in radians (false) or degrees (true)? + * @param {Number} distance An optional distance constraint between the Point and the anchor. + * @return The modified point object + */ + function rotate(a, x, y, angle, asDegrees, distance) { + if (typeof asDegrees === "undefined") { asDegrees = false; } + if (typeof distance === "undefined") { distance = null; } + if(asDegrees) { + angle = angle * Phaser.GameMath.DEG_TO_RAD; + } + // Get distance from origin (cx/cy) to this point + if(distance === null) { + distance = Math.sqrt(((x - a.x) * (x - a.x)) + ((y - a.y) * (y - a.y))); + } + return a.setTo(x + distance * Math.cos(angle), y + distance * Math.sin(angle)); + }; + PointUtils.rotateAroundPoint = /** + * Rotates a Point around the given Point to the desired angle. + * @param a {Point} The Point object to rotate. + * @param b {Point} The Point object to serve as point of rotation. + * @param x {number} The x coordinate of the anchor point + * @param y {number} The y coordinate of the anchor point + * @param {Number} angle The angle in radians (unless asDegrees is true) to rotate the Point to. + * @param {Boolean} asDegrees Is the given angle in radians (false) or degrees (true)? + * @param {Number} distance An optional distance constraint between the Point and the anchor. + * @return The modified point object + */ + function rotateAroundPoint(a, b, angle, asDegrees, distance) { + if (typeof asDegrees === "undefined") { asDegrees = false; } + if (typeof distance === "undefined") { distance = null; } + return PointUtils.rotate(a, b.x, b.y, angle, asDegrees, distance); + }; + return PointUtils; + })(); +})(Phaser || (Phaser = {})); +/// +/// +/** +* Phaser - Vec2Utils +* +* A collection of methods useful for manipulating and performing operations on 2D vectors. +* +*/ +var Phaser; +(function (Phaser) { + var Vec2Utils = (function () { + function Vec2Utils() { } + Vec2Utils.add = /** + * Adds two 2D vectors. + * + * @param {Vec2} a Reference to a source Vec2 object. + * @param {Vec2} b Reference to a source Vec2 object. + * @param {Vec2} out The output Vec2 that is the result of the operation. + * @return {Vec2} A Vec2 that is the sum of the two vectors. + */ + function add(a, b, out) { + if (typeof out === "undefined") { out = new Phaser.Vec2(); } + return out.setTo(a.x + b.x, a.y + b.y); + }; + Vec2Utils.subtract = /** + * Subtracts two 2D vectors. + * + * @param {Vec2} a Reference to a source Vec2 object. + * @param {Vec2} b Reference to a source Vec2 object. + * @param {Vec2} out The output Vec2 that is the result of the operation. + * @return {Vec2} A Vec2 that is the difference of the two vectors. + */ + function subtract(a, b, out) { + if (typeof out === "undefined") { out = new Phaser.Vec2(); } + return out.setTo(a.x - b.x, a.y - b.y); + }; + Vec2Utils.multiply = /** + * Multiplies two 2D vectors. + * + * @param {Vec2} a Reference to a source Vec2 object. + * @param {Vec2} b Reference to a source Vec2 object. + * @param {Vec2} out The output Vec2 that is the result of the operation. + * @return {Vec2} A Vec2 that is the sum of the two vectors multiplied. + */ + function multiply(a, b, out) { + if (typeof out === "undefined") { out = new Phaser.Vec2(); } + return out.setTo(a.x * b.x, a.y * b.y); + }; + Vec2Utils.divide = /** + * Divides two 2D vectors. + * + * @param {Vec2} a Reference to a source Vec2 object. + * @param {Vec2} b Reference to a source Vec2 object. + * @param {Vec2} out The output Vec2 that is the result of the operation. + * @return {Vec2} A Vec2 that is the sum of the two vectors divided. + */ + function divide(a, b, out) { + if (typeof out === "undefined") { out = new Phaser.Vec2(); } + return out.setTo(a.x / b.x, a.y / b.y); + }; + Vec2Utils.scale = /** + * Scales a 2D vector. + * + * @param {Vec2} a Reference to a source Vec2 object. + * @param {number} s Scaling value. + * @param {Vec2} out The output Vec2 that is the result of the operation. + * @return {Vec2} A Vec2 that is the scaled vector. + */ + function scale(a, s, out) { + if (typeof out === "undefined") { out = new Phaser.Vec2(); } + return out.setTo(a.x * s, a.y * s); + }; + Vec2Utils.perp = /** + * Rotate a 2D vector by 90 degrees. + * + * @param {Vec2} a Reference to a source Vec2 object. + * @param {Vec2} out The output Vec2 that is the result of the operation. + * @return {Vec2} A Vec2 that is the scaled vector. + */ + function perp(a, out) { + if (typeof out === "undefined") { out = new Phaser.Vec2(); } + return out.setTo(a.y, -a.x); + }; + Vec2Utils.equals = /** + * Checks if two 2D vectors are equal. + * + * @param {Vec2} a Reference to a source Vec2 object. + * @param {Vec2} b Reference to a source Vec2 object. + * @return {Boolean} + */ + function equals(a, b) { + return a.x == b.x && a.y == b.y; + }; + Vec2Utils.epsilonEquals = /** + * + * + * @param {Vec2} a Reference to a source Vec2 object. + * @param {Vec2} b Reference to a source Vec2 object. + * @param {Vec2} epsilon + * @return {Boolean} + */ + function epsilonEquals(a, b, epsilon) { + return Math.abs(a.x - b.x) <= epsilon && Math.abs(a.y - b.y) <= epsilon; + }; + Vec2Utils.distance = /** + * Get the distance between two 2D vectors. + * + * @param {Vec2} a Reference to a source Vec2 object. + * @param {Vec2} b Reference to a source Vec2 object. + * @return {Number} + */ + function distance(a, b) { + return Math.sqrt(Vec2Utils.distanceSq(a, b)); + }; + Vec2Utils.distanceSq = /** + * Get the distance squared between two 2D vectors. + * + * @param {Vec2} a Reference to a source Vec2 object. + * @param {Vec2} b Reference to a source Vec2 object. + * @return {Number} + */ + function distanceSq(a, b) { + return ((a.x - b.x) * (a.x - b.x)) + ((a.y - b.y) * (a.y - b.y)); + }; + Vec2Utils.project = /** + * Project two 2D vectors onto another vector. + * + * @param {Vec2} a Reference to a source Vec2 object. + * @param {Vec2} b Reference to a source Vec2 object. + * @param {Vec2} out The output Vec2 that is the result of the operation. + * @return {Vec2} A Vec2. + */ + function project(a, b, out) { + if (typeof out === "undefined") { out = new Phaser.Vec2(); } + var amt = a.dot(b) / b.lengthSq(); + if(amt != 0) { + out.setTo(amt * b.x, amt * b.y); + } + return out; + }; + Vec2Utils.projectUnit = /** + * Project this vector onto a vector of unit length. + * + * @param {Vec2} a Reference to a source Vec2 object. + * @param {Vec2} b Reference to a source Vec2 object. + * @param {Vec2} out The output Vec2 that is the result of the operation. + * @return {Vec2} A Vec2. + */ + function projectUnit(a, b, out) { + if (typeof out === "undefined") { out = new Phaser.Vec2(); } + var amt = a.dot(b); + if(amt != 0) { + out.setTo(amt * b.x, amt * b.y); + } + return out; + }; + Vec2Utils.normalRightHand = /** + * Right-hand normalize (make unit length) a 2D vector. + * + * @param {Vec2} a Reference to a source Vec2 object. + * @param {Vec2} out The output Vec2 that is the result of the operation. + * @return {Vec2} A Vec2. + */ + function normalRightHand(a, out) { + if (typeof out === "undefined") { out = this; } + return out.setTo(a.y * -1, a.x); + }; + Vec2Utils.normalize = /** + * Normalize (make unit length) a 2D vector. + * + * @param {Vec2} a Reference to a source Vec2 object. + * @param {Vec2} out The output Vec2 that is the result of the operation. + * @return {Vec2} A Vec2. + */ + function normalize(a, out) { + if (typeof out === "undefined") { out = new Phaser.Vec2(); } + var m = a.length(); + if(m != 0) { + out.setTo(a.x / m, a.y / m); + } + return out; + }; + Vec2Utils.dot = /** + * The dot product of two 2D vectors. + * + * @param {Vec2} a Reference to a source Vec2 object. + * @param {Vec2} b Reference to a source Vec2 object. + * @return {Number} + */ + function dot(a, b) { + return ((a.x * b.x) + (a.y * b.y)); + }; + Vec2Utils.cross = /** + * The cross product of two 2D vectors. + * + * @param {Vec2} a Reference to a source Vec2 object. + * @param {Vec2} b Reference to a source Vec2 object. + * @return {Number} + */ + function cross(a, b) { + return ((a.x * b.y) - (a.y * b.x)); + }; + Vec2Utils.angle = /** + * The angle between two 2D vectors. + * + * @param {Vec2} a Reference to a source Vec2 object. + * @param {Vec2} b Reference to a source Vec2 object. + * @return {Number} + */ + function angle(a, b) { + return Math.atan2(a.x * b.y - a.y * b.x, a.x * b.x + a.y * b.y); + }; + Vec2Utils.angleSq = /** + * The angle squared between two 2D vectors. + * + * @param {Vec2} a Reference to a source Vec2 object. + * @param {Vec2} b Reference to a source Vec2 object. + * @return {Number} + */ + function angleSq(a, b) { + return a.subtract(b).angle(b.subtract(a)); + }; + Vec2Utils.rotate = /** + * Rotate a 2D vector around the origin to the given angle (theta). + * + * @param {Vec2} a Reference to a source Vec2 object. + * @param {Vec2} b Reference to a source Vec2 object. + * @param {Number} theta The angle of rotation in radians. + * @param {Vec2} out The output Vec2 that is the result of the operation. + * @return {Vec2} A Vec2. + */ + function rotate(a, b, theta, out) { + if (typeof out === "undefined") { out = new Phaser.Vec2(); } + var x = a.x - b.x; + var y = a.y - b.y; + return out.setTo(x * Math.cos(theta) - y * Math.sin(theta) + b.x, x * Math.sin(theta) + y * Math.cos(theta) + b.y); + }; + Vec2Utils.clone = /** + * Clone a 2D vector. + * + * @param {Vec2} a Reference to a source Vec2 object. + * @param {Vec2} out The output Vec2 that is the result of the operation. + * @return {Vec2} A Vec2 that is a copy of the source Vec2. + */ + function clone(a, out) { + if (typeof out === "undefined") { out = new Phaser.Vec2(); } + return out.setTo(a.x, a.y); + }; + return Vec2Utils; + })(); + Phaser.Vec2Utils = Vec2Utils; + /** + * Reflect this vector on an arbitrary axis. + * + * @param {Vec2} axis The vector representing the axis. + * @return {Vec2} This for chaining. + */ + /* + static reflect(axis): Vec2 { + + var x = this.x; + var y = this.y; + this.project(axis).scale(2); + this.x -= x; + this.y -= y; + + return this; + + } + */ + /** + * Reflect this vector on an arbitrary axis (represented by a unit vector) + * + * @param {Vec2} axis The unit vector representing the axis. + * @return {Vec2} This for chaining. + */ + /* + static reflectN(axis): Vec2 { + + var x = this.x; + var y = this.y; + this.projectN(axis).scale(2); + this.x -= x; + this.y -= y; + + return this; + + } + + static getMagnitude(): number { + return Math.sqrt(Math.pow(this.x, 2) + Math.pow(this.y, 2)); + } + */ + })(Phaser || (Phaser = {})); +/// +/// /** * Phaser - Pointer * @@ -13180,13 +8774,13 @@ var Phaser; /** * A Vector object containing the initial position when the Pointer was engaged with the screen. * @property positionDown - * @type {Vector2} + * @type {Vec2} **/ this.positionDown = null; /** * A Vector object containing the current position of the Pointer on the screen. * @property position - * @type {Vector2} + * @type {Vec2} **/ this.position = null; /** @@ -13295,8 +8889,8 @@ var Phaser; this._game = game; this.id = id; this.active = false; - this.position = new Phaser.Vector2(); - this.positionDown = new Phaser.Vector2(); + this.position = new Phaser.Vec2(); + this.positionDown = new Phaser.Vec2(); this.circle = new Phaser.Circle(0, 0, 44); if(id == 0) { this.isMouse = true; @@ -13546,7 +9140,7 @@ var Phaser; })(); Phaser.Pointer = Pointer; })(Phaser || (Phaser = {})); -/// +/// /// /** * Phaser - MSPointer @@ -13643,7 +9237,7 @@ var Phaser; })(); Phaser.MSPointer = MSPointer; })(Phaser || (Phaser = {})); -/// +/// /// /** * Phaser - Gestures @@ -13679,11 +9273,508 @@ var Phaser; })(); Phaser.Gestures = Gestures; })(Phaser || (Phaser = {})); -/// -/// +/// +/** +* Phaser - Mouse +* +* The Mouse class handles mouse interactions with the game and the resulting events. +*/ +var Phaser; +(function (Phaser) { + var Mouse = (function () { + function Mouse(game) { + /** + * You can disable all Input by setting disabled = true. While set all new input related events will be ignored. + * @type {Boolean} + */ + this.disabled = false; + this._game = game; + } + Mouse.LEFT_BUTTON = 0; + Mouse.MIDDLE_BUTTON = 1; + Mouse.RIGHT_BUTTON = 2; + Mouse.prototype.start = /** + * Starts the event listeners running + * @method start + */ + function () { + var _this = this; + this._game.stage.canvas.addEventListener('mousedown', function (event) { + return _this.onMouseDown(event); + }, true); + this._game.stage.canvas.addEventListener('mousemove', function (event) { + return _this.onMouseMove(event); + }, true); + this._game.stage.canvas.addEventListener('mouseup', function (event) { + return _this.onMouseUp(event); + }, true); + }; + Mouse.prototype.onMouseDown = /** + * @param {MouseEvent} event + */ + function (event) { + if(this._game.input.disabled || this.disabled) { + return; + } + event['identifier'] = 0; + this._game.input.mousePointer.start(event); + }; + Mouse.prototype.onMouseMove = /** + * @param {MouseEvent} event + */ + function (event) { + if(this._game.input.disabled || this.disabled) { + return; + } + event['identifier'] = 0; + this._game.input.mousePointer.move(event); + }; + Mouse.prototype.onMouseUp = /** + * @param {MouseEvent} event + */ + function (event) { + if(this._game.input.disabled || this.disabled) { + return; + } + event['identifier'] = 0; + this._game.input.mousePointer.stop(event); + }; + Mouse.prototype.stop = /** + * Stop the event listeners + * @method stop + */ + function () { + //this._game.stage.canvas.addEventListener('mousedown', (event: MouseEvent) => this.onMouseDown(event), true); + //this._game.stage.canvas.addEventListener('mousemove', (event: MouseEvent) => this.onMouseMove(event), true); + //this._game.stage.canvas.addEventListener('mouseup', (event: MouseEvent) => this.onMouseUp(event), true); + }; + return Mouse; + })(); + Phaser.Mouse = Mouse; +})(Phaser || (Phaser = {})); +/// +/** +* Phaser - Keyboard +* +* The Keyboard class handles keyboard interactions with the game and the resulting events. +* The avoid stealing all browser input we don't use event.preventDefault. If you would like to trap a specific key however +* then use the addKeyCapture() method. +*/ +var Phaser; +(function (Phaser) { + var Keyboard = (function () { + function Keyboard(game) { + this._keys = { + }; + this._capture = { + }; + /** + * You can disable all Input by setting disabled = true. While set all new input related events will be ignored. + * @type {Boolean} + */ + this.disabled = false; + this._game = game; + } + Keyboard.prototype.start = function () { + var _this = this; + document.body.addEventListener('keydown', function (event) { + return _this.onKeyDown(event); + }, false); + document.body.addEventListener('keyup', function (event) { + return _this.onKeyUp(event); + }, false); + }; + Keyboard.prototype.addKeyCapture = /** + * By default when a key is pressed Phaser will not stop the event from propagating up to the browser. + * There are some keys this can be annoying for, like the arrow keys or space bar, which make the browser window scroll. + * You can use addKeyCapture to consume the keyboard event for specific keys so it doesn't bubble up to the the browser. + * Pass in either a single keycode or an array of keycodes. + * @param {Any} keycode + */ + function (keycode) { + if(typeof keycode === 'object') { + for(var i = 0; i < keycode.length; i++) { + this._capture[keycode[i]] = true; + } + } else { + this._capture[keycode] = true; + } + }; + Keyboard.prototype.removeKeyCapture = /** + * @param {Number} keycode + */ + function (keycode) { + delete this._capture[keycode]; + }; + Keyboard.prototype.clearCaptures = function () { + this._capture = { + }; + }; + Keyboard.prototype.onKeyDown = /** + * @param {KeyboardEvent} event + */ + function (event) { + if(this._game.input.disabled || this.disabled) { + return; + } + if(this._capture[event.keyCode]) { + event.preventDefault(); + } + if(!this._keys[event.keyCode]) { + this._keys[event.keyCode] = { + isDown: true, + timeDown: this._game.time.now, + timeUp: 0 + }; + } else { + this._keys[event.keyCode].isDown = true; + this._keys[event.keyCode].timeDown = this._game.time.now; + } + }; + Keyboard.prototype.onKeyUp = /** + * @param {KeyboardEvent} event + */ + function (event) { + if(this._game.input.disabled || this.disabled) { + return; + } + if(this._capture[event.keyCode]) { + event.preventDefault(); + } + if(!this._keys[event.keyCode]) { + this._keys[event.keyCode] = { + isDown: false, + timeDown: 0, + timeUp: this._game.time.now + }; + } else { + this._keys[event.keyCode].isDown = false; + this._keys[event.keyCode].timeUp = this._game.time.now; + } + }; + Keyboard.prototype.reset = function () { + for(var key in this._keys) { + this._keys[key].isDown = false; + } + }; + Keyboard.prototype.justPressed = /** + * @param {Number} keycode + * @param {Number} [duration] + * @return {Boolean} + */ + function (keycode, duration) { + if (typeof duration === "undefined") { duration = 250; } + if(this._keys[keycode] && this._keys[keycode].isDown === true && (this._game.time.now - this._keys[keycode].timeDown < duration)) { + return true; + } else { + return false; + } + }; + Keyboard.prototype.justReleased = /** + * @param {Number} keycode + * @param {Number} [duration] + * @return {Boolean} + */ + function (keycode, duration) { + if (typeof duration === "undefined") { duration = 250; } + if(this._keys[keycode] && this._keys[keycode].isDown === false && (this._game.time.now - this._keys[keycode].timeUp < duration)) { + return true; + } else { + return false; + } + }; + Keyboard.prototype.isDown = /** + * @param {Number} keycode + * @return {Boolean} + */ + function (keycode) { + if(this._keys[keycode]) { + return this._keys[keycode].isDown; + } else { + return false; + } + }; + Keyboard.A = "A".charCodeAt(0); + Keyboard.B = "B".charCodeAt(0); + Keyboard.C = "C".charCodeAt(0); + Keyboard.D = "D".charCodeAt(0); + Keyboard.E = "E".charCodeAt(0); + Keyboard.F = "F".charCodeAt(0); + Keyboard.G = "G".charCodeAt(0); + Keyboard.H = "H".charCodeAt(0); + Keyboard.I = "I".charCodeAt(0); + Keyboard.J = "J".charCodeAt(0); + Keyboard.K = "K".charCodeAt(0); + Keyboard.L = "L".charCodeAt(0); + Keyboard.M = "M".charCodeAt(0); + Keyboard.N = "N".charCodeAt(0); + Keyboard.O = "O".charCodeAt(0); + Keyboard.P = "P".charCodeAt(0); + Keyboard.Q = "Q".charCodeAt(0); + Keyboard.R = "R".charCodeAt(0); + Keyboard.S = "S".charCodeAt(0); + Keyboard.T = "T".charCodeAt(0); + Keyboard.U = "U".charCodeAt(0); + Keyboard.V = "V".charCodeAt(0); + Keyboard.W = "W".charCodeAt(0); + Keyboard.X = "X".charCodeAt(0); + Keyboard.Y = "Y".charCodeAt(0); + Keyboard.Z = "Z".charCodeAt(0); + Keyboard.ZERO = "0".charCodeAt(0); + Keyboard.ONE = "1".charCodeAt(0); + Keyboard.TWO = "2".charCodeAt(0); + Keyboard.THREE = "3".charCodeAt(0); + Keyboard.FOUR = "4".charCodeAt(0); + Keyboard.FIVE = "5".charCodeAt(0); + Keyboard.SIX = "6".charCodeAt(0); + Keyboard.SEVEN = "7".charCodeAt(0); + Keyboard.EIGHT = "8".charCodeAt(0); + Keyboard.NINE = "9".charCodeAt(0); + Keyboard.NUMPAD_0 = 96; + Keyboard.NUMPAD_1 = 97; + Keyboard.NUMPAD_2 = 98; + Keyboard.NUMPAD_3 = 99; + Keyboard.NUMPAD_4 = 100; + Keyboard.NUMPAD_5 = 101; + Keyboard.NUMPAD_6 = 102; + Keyboard.NUMPAD_7 = 103; + Keyboard.NUMPAD_8 = 104; + Keyboard.NUMPAD_9 = 105; + Keyboard.NUMPAD_MULTIPLY = 106; + Keyboard.NUMPAD_ADD = 107; + Keyboard.NUMPAD_ENTER = 108; + Keyboard.NUMPAD_SUBTRACT = 109; + Keyboard.NUMPAD_DECIMAL = 110; + Keyboard.NUMPAD_DIVIDE = 111; + Keyboard.F1 = 112; + Keyboard.F2 = 113; + Keyboard.F3 = 114; + Keyboard.F4 = 115; + Keyboard.F5 = 116; + Keyboard.F6 = 117; + Keyboard.F7 = 118; + Keyboard.F8 = 119; + Keyboard.F9 = 120; + Keyboard.F10 = 121; + Keyboard.F11 = 122; + Keyboard.F12 = 123; + Keyboard.F13 = 124; + Keyboard.F14 = 125; + Keyboard.F15 = 126; + Keyboard.COLON = 186; + Keyboard.EQUALS = 187; + Keyboard.UNDERSCORE = 189; + Keyboard.QUESTION_MARK = 191; + Keyboard.TILDE = 192; + Keyboard.OPEN_BRACKET = 219; + Keyboard.BACKWARD_SLASH = 220; + Keyboard.CLOSED_BRACKET = 221; + Keyboard.QUOTES = 222; + Keyboard.BACKSPACE = 8; + Keyboard.TAB = 9; + Keyboard.CLEAR = 12; + Keyboard.ENTER = 13; + Keyboard.SHIFT = 16; + Keyboard.CONTROL = 17; + Keyboard.ALT = 18; + Keyboard.CAPS_LOCK = 20; + Keyboard.ESC = 27; + Keyboard.SPACEBAR = 32; + Keyboard.PAGE_UP = 33; + Keyboard.PAGE_DOWN = 34; + Keyboard.END = 35; + Keyboard.HOME = 36; + Keyboard.LEFT = 37; + Keyboard.UP = 38; + Keyboard.RIGHT = 39; + Keyboard.DOWN = 40; + Keyboard.INSERT = 45; + Keyboard.DELETE = 46; + Keyboard.HELP = 47; + Keyboard.NUM_LOCK = 144; + return Keyboard; + })(); + Phaser.Keyboard = Keyboard; +})(Phaser || (Phaser = {})); +/// +/// +/** +* Phaser - Touch +* +* The Touch class handles touch interactions with the game and the resulting Pointer objects. +* http://www.w3.org/TR/touch-events/ +* https://developer.mozilla.org/en-US/docs/DOM/TouchList +* http://www.html5rocks.com/en/mobile/touchandmouse/ +* Note: Android 2.x only supports 1 touch event at once, no multi-touch +*/ +var Phaser; +(function (Phaser) { + var Touch = (function () { + /** + * Constructor + * @param {Game} game. + * @return {Touch} This object. + */ + function Touch(game) { + /** + * You can disable all Input by setting disabled = true. While set all new input related events will be ignored. + * @type {Boolean} + */ + this.disabled = false; + this._game = game; + } + Touch.prototype.start = /** + * Starts the event listeners running + * @method start + */ + function () { + var _this = this; + if(this._game.device.touch) { + this._game.stage.canvas.addEventListener('touchstart', function (event) { + return _this.onTouchStart(event); + }, false); + this._game.stage.canvas.addEventListener('touchmove', function (event) { + return _this.onTouchMove(event); + }, false); + this._game.stage.canvas.addEventListener('touchend', function (event) { + return _this.onTouchEnd(event); + }, false); + this._game.stage.canvas.addEventListener('touchenter', function (event) { + return _this.onTouchEnter(event); + }, false); + this._game.stage.canvas.addEventListener('touchleave', function (event) { + return _this.onTouchLeave(event); + }, false); + this._game.stage.canvas.addEventListener('touchcancel', function (event) { + return _this.onTouchCancel(event); + }, false); + document.addEventListener('touchmove', function (event) { + return _this.consumeTouchMove(event); + }, false); + } + }; + Touch.prototype.consumeTouchMove = /** + * Prevent iOS bounce-back (doesn't work?) + * @method consumeTouchMove + * @param {Any} event + **/ + function (event) { + event.preventDefault(); + }; + Touch.prototype.onTouchStart = /** + * + * @method onTouchStart + * @param {Any} event + **/ + function (event) { + if(this._game.input.disabled || this.disabled) { + return; + } + event.preventDefault(); + // event.targetTouches = list of all touches on the TARGET ELEMENT (i.e. game dom element) + // event.touches = list of all touches on the ENTIRE DOCUMENT, not just the target element + // event.changedTouches = the touches that CHANGED in this event, not the total number of them + for(var i = 0; i < event.changedTouches.length; i++) { + this._game.input.startPointer(event.changedTouches[i]); + } + }; + Touch.prototype.onTouchCancel = /** + * Touch cancel - touches that were disrupted (perhaps by moving into a plugin or browser chrome) + * Occurs for example on iOS when you put down 4 fingers and the app selector UI appears + * @method onTouchCancel + * @param {Any} event + **/ + function (event) { + if(this._game.input.disabled || this.disabled) { + return; + } + event.preventDefault(); + // Touch cancel - touches that were disrupted (perhaps by moving into a plugin or browser chrome) + // http://www.w3.org/TR/touch-events/#dfn-touchcancel + for(var i = 0; i < event.changedTouches.length; i++) { + this._game.input.stopPointer(event.changedTouches[i]); + } + }; + Touch.prototype.onTouchEnter = /** + * For touch enter and leave its a list of the touch points that have entered or left the target + * Doesn't appear to be supported by most browsers yet + * @method onTouchEnter + * @param {Any} event + **/ + function (event) { + if(this._game.input.disabled || this.disabled) { + return; + } + event.preventDefault(); + for(var i = 0; i < event.changedTouches.length; i++) { + console.log('touch enter'); + } + }; + Touch.prototype.onTouchLeave = /** + * For touch enter and leave its a list of the touch points that have entered or left the target + * Doesn't appear to be supported by most browsers yet + * @method onTouchLeave + * @param {Any} event + **/ + function (event) { + event.preventDefault(); + for(var i = 0; i < event.changedTouches.length; i++) { + console.log('touch leave'); + } + }; + Touch.prototype.onTouchMove = /** + * + * @method onTouchMove + * @param {Any} event + **/ + function (event) { + event.preventDefault(); + for(var i = 0; i < event.changedTouches.length; i++) { + this._game.input.updatePointer(event.changedTouches[i]); + } + }; + Touch.prototype.onTouchEnd = /** + * + * @method onTouchEnd + * @param {Any} event + **/ + function (event) { + event.preventDefault(); + // For touch end its a list of the touch points that have been removed from the surface + // https://developer.mozilla.org/en-US/docs/DOM/TouchList + // event.changedTouches = the touches that CHANGED in this event, not the total number of them + for(var i = 0; i < event.changedTouches.length; i++) { + this._game.input.stopPointer(event.changedTouches[i]); + } + }; + Touch.prototype.stop = /** + * Stop the event listeners + * @method stop + */ + function () { + if(this._game.device.touch) { + //this._domElement.addEventListener('touchstart', (event) => this.onTouchStart(event), false); + //this._domElement.addEventListener('touchmove', (event) => this.onTouchMove(event), false); + //this._domElement.addEventListener('touchend', (event) => this.onTouchEnd(event), false); + //this._domElement.addEventListener('touchenter', (event) => this.onTouchEnter(event), false); + //this._domElement.addEventListener('touchleave', (event) => this.onTouchLeave(event), false); + //this._domElement.addEventListener('touchcancel', (event) => this.onTouchCancel(event), false); + } + }; + return Touch; + })(); + Phaser.Touch = Touch; +})(Phaser || (Phaser = {})); +/// +/// +/// +/// /// /// /// +/// +/// +/// /** * Phaser - Input * @@ -13707,7 +9798,7 @@ var Phaser; /** * A vector object representing the current position of the Pointer. * @property vector - * @type {Vector2} + * @type {Vec2} **/ this.position = null; /** @@ -13847,7 +9938,7 @@ var Phaser; this.onUp = new Phaser.Signal(); this.onTap = new Phaser.Signal(); this.onHold = new Phaser.Signal(); - this.position = new Phaser.Vector2(); + this.position = new Phaser.Vec2(); this.circle = new Phaser.Circle(0, 0, 44); this.currentPointers = 0; } @@ -14229,7 +10320,7 @@ var Phaser; * @param {Pointer} pointer2 **/ function (pointer1, pointer2) { - return pointer1.position.distance(pointer2.position); + return Phaser.Vec2Utils.distance(pointer1.position, pointer2.position); }; Input.prototype.getAngle = /** * Get the angle between two Pointer objects @@ -14238,2579 +10329,236 @@ var Phaser; * @param {Pointer} pointer2 **/ function (pointer1, pointer2) { - return pointer1.position.angle(pointer2.position); + return Phaser.Vec2Utils.angle(pointer1.position, pointer2.position); }; return Input; })(); Phaser.Input = Input; })(Phaser || (Phaser = {})); -/// -/** -* Phaser - Keyboard -* -* The Keyboard class handles keyboard interactions with the game and the resulting events. -* The avoid stealing all browser input we don't use event.preventDefault. If you would like to trap a specific key however -* then use the addKeyCapture() method. -*/ -var Phaser; -(function (Phaser) { - var Keyboard = (function () { - function Keyboard(game) { - this._keys = { - }; - this._capture = { - }; - /** - * You can disable all Input by setting disabled = true. While set all new input related events will be ignored. - * @type {Boolean} - */ - this.disabled = false; - this._game = game; - } - Keyboard.prototype.start = function () { - var _this = this; - document.body.addEventListener('keydown', function (event) { - return _this.onKeyDown(event); - }, false); - document.body.addEventListener('keyup', function (event) { - return _this.onKeyUp(event); - }, false); - }; - Keyboard.prototype.addKeyCapture = /** - * By default when a key is pressed Phaser will not stop the event from propagating up to the browser. - * There are some keys this can be annoying for, like the arrow keys or space bar, which make the browser window scroll. - * You can use addKeyCapture to consume the keyboard event for specific keys so it doesn't bubble up to the the browser. - * Pass in either a single keycode or an array of keycodes. - * @param {Any} keycode - */ - function (keycode) { - if(typeof keycode === 'object') { - for(var i = 0; i < keycode.length; i++) { - this._capture[keycode[i]] = true; - } - } else { - this._capture[keycode] = true; - } - }; - Keyboard.prototype.removeKeyCapture = /** - * @param {Number} keycode - */ - function (keycode) { - delete this._capture[keycode]; - }; - Keyboard.prototype.clearCaptures = function () { - this._capture = { - }; - }; - Keyboard.prototype.onKeyDown = /** - * @param {KeyboardEvent} event - */ - function (event) { - if(this._game.input.disabled || this.disabled) { - return; - } - if(this._capture[event.keyCode]) { - event.preventDefault(); - } - if(!this._keys[event.keyCode]) { - this._keys[event.keyCode] = { - isDown: true, - timeDown: this._game.time.now, - timeUp: 0 - }; - } else { - this._keys[event.keyCode].isDown = true; - this._keys[event.keyCode].timeDown = this._game.time.now; - } - }; - Keyboard.prototype.onKeyUp = /** - * @param {KeyboardEvent} event - */ - function (event) { - if(this._game.input.disabled || this.disabled) { - return; - } - if(this._capture[event.keyCode]) { - event.preventDefault(); - } - if(!this._keys[event.keyCode]) { - this._keys[event.keyCode] = { - isDown: false, - timeDown: 0, - timeUp: this._game.time.now - }; - } else { - this._keys[event.keyCode].isDown = false; - this._keys[event.keyCode].timeUp = this._game.time.now; - } - }; - Keyboard.prototype.reset = function () { - for(var key in this._keys) { - this._keys[key].isDown = false; - } - }; - Keyboard.prototype.justPressed = /** - * @param {Number} keycode - * @param {Number} [duration] - * @return {Boolean} - */ - function (keycode, duration) { - if (typeof duration === "undefined") { duration = 250; } - if(this._keys[keycode] && this._keys[keycode].isDown === true && (this._game.time.now - this._keys[keycode].timeDown < duration)) { - return true; - } else { - return false; - } - }; - Keyboard.prototype.justReleased = /** - * @param {Number} keycode - * @param {Number} [duration] - * @return {Boolean} - */ - function (keycode, duration) { - if (typeof duration === "undefined") { duration = 250; } - if(this._keys[keycode] && this._keys[keycode].isDown === false && (this._game.time.now - this._keys[keycode].timeUp < duration)) { - return true; - } else { - return false; - } - }; - Keyboard.prototype.isDown = /** - * @param {Number} keycode - * @return {Boolean} - */ - function (keycode) { - if(this._keys[keycode]) { - return this._keys[keycode].isDown; - } else { - return false; - } - }; - Keyboard.A = "A".charCodeAt(0); - Keyboard.B = "B".charCodeAt(0); - Keyboard.C = "C".charCodeAt(0); - Keyboard.D = "D".charCodeAt(0); - Keyboard.E = "E".charCodeAt(0); - Keyboard.F = "F".charCodeAt(0); - Keyboard.G = "G".charCodeAt(0); - Keyboard.H = "H".charCodeAt(0); - Keyboard.I = "I".charCodeAt(0); - Keyboard.J = "J".charCodeAt(0); - Keyboard.K = "K".charCodeAt(0); - Keyboard.L = "L".charCodeAt(0); - Keyboard.M = "M".charCodeAt(0); - Keyboard.N = "N".charCodeAt(0); - Keyboard.O = "O".charCodeAt(0); - Keyboard.P = "P".charCodeAt(0); - Keyboard.Q = "Q".charCodeAt(0); - Keyboard.R = "R".charCodeAt(0); - Keyboard.S = "S".charCodeAt(0); - Keyboard.T = "T".charCodeAt(0); - Keyboard.U = "U".charCodeAt(0); - Keyboard.V = "V".charCodeAt(0); - Keyboard.W = "W".charCodeAt(0); - Keyboard.X = "X".charCodeAt(0); - Keyboard.Y = "Y".charCodeAt(0); - Keyboard.Z = "Z".charCodeAt(0); - Keyboard.ZERO = "0".charCodeAt(0); - Keyboard.ONE = "1".charCodeAt(0); - Keyboard.TWO = "2".charCodeAt(0); - Keyboard.THREE = "3".charCodeAt(0); - Keyboard.FOUR = "4".charCodeAt(0); - Keyboard.FIVE = "5".charCodeAt(0); - Keyboard.SIX = "6".charCodeAt(0); - Keyboard.SEVEN = "7".charCodeAt(0); - Keyboard.EIGHT = "8".charCodeAt(0); - Keyboard.NINE = "9".charCodeAt(0); - Keyboard.NUMPAD_0 = 96; - Keyboard.NUMPAD_1 = 97; - Keyboard.NUMPAD_2 = 98; - Keyboard.NUMPAD_3 = 99; - Keyboard.NUMPAD_4 = 100; - Keyboard.NUMPAD_5 = 101; - Keyboard.NUMPAD_6 = 102; - Keyboard.NUMPAD_7 = 103; - Keyboard.NUMPAD_8 = 104; - Keyboard.NUMPAD_9 = 105; - Keyboard.NUMPAD_MULTIPLY = 106; - Keyboard.NUMPAD_ADD = 107; - Keyboard.NUMPAD_ENTER = 108; - Keyboard.NUMPAD_SUBTRACT = 109; - Keyboard.NUMPAD_DECIMAL = 110; - Keyboard.NUMPAD_DIVIDE = 111; - Keyboard.F1 = 112; - Keyboard.F2 = 113; - Keyboard.F3 = 114; - Keyboard.F4 = 115; - Keyboard.F5 = 116; - Keyboard.F6 = 117; - Keyboard.F7 = 118; - Keyboard.F8 = 119; - Keyboard.F9 = 120; - Keyboard.F10 = 121; - Keyboard.F11 = 122; - Keyboard.F12 = 123; - Keyboard.F13 = 124; - Keyboard.F14 = 125; - Keyboard.F15 = 126; - Keyboard.COLON = 186; - Keyboard.EQUALS = 187; - Keyboard.UNDERSCORE = 189; - Keyboard.QUESTION_MARK = 191; - Keyboard.TILDE = 192; - Keyboard.OPEN_BRACKET = 219; - Keyboard.BACKWARD_SLASH = 220; - Keyboard.CLOSED_BRACKET = 221; - Keyboard.QUOTES = 222; - Keyboard.BACKSPACE = 8; - Keyboard.TAB = 9; - Keyboard.CLEAR = 12; - Keyboard.ENTER = 13; - Keyboard.SHIFT = 16; - Keyboard.CONTROL = 17; - Keyboard.ALT = 18; - Keyboard.CAPS_LOCK = 20; - Keyboard.ESC = 27; - Keyboard.SPACEBAR = 32; - Keyboard.PAGE_UP = 33; - Keyboard.PAGE_DOWN = 34; - Keyboard.END = 35; - Keyboard.HOME = 36; - Keyboard.LEFT = 37; - Keyboard.UP = 38; - Keyboard.RIGHT = 39; - Keyboard.DOWN = 40; - Keyboard.INSERT = 45; - Keyboard.DELETE = 46; - Keyboard.HELP = 47; - Keyboard.NUM_LOCK = 144; - return Keyboard; - })(); - Phaser.Keyboard = Keyboard; -})(Phaser || (Phaser = {})); -/// -/** -* Phaser - Mouse -* -* The Mouse class handles mouse interactions with the game and the resulting events. -*/ -var Phaser; -(function (Phaser) { - var Mouse = (function () { - function Mouse(game) { - /** - * You can disable all Input by setting disabled = true. While set all new input related events will be ignored. - * @type {Boolean} - */ - this.disabled = false; - this._game = game; - } - Mouse.LEFT_BUTTON = 0; - Mouse.MIDDLE_BUTTON = 1; - Mouse.RIGHT_BUTTON = 2; - Mouse.prototype.start = /** - * Starts the event listeners running - * @method start - */ - function () { - var _this = this; - this._game.stage.canvas.addEventListener('mousedown', function (event) { - return _this.onMouseDown(event); - }, true); - this._game.stage.canvas.addEventListener('mousemove', function (event) { - return _this.onMouseMove(event); - }, true); - this._game.stage.canvas.addEventListener('mouseup', function (event) { - return _this.onMouseUp(event); - }, true); - }; - Mouse.prototype.onMouseDown = /** - * @param {MouseEvent} event - */ - function (event) { - if(this._game.input.disabled || this.disabled) { - return; - } - event['identifier'] = 0; - this._game.input.mousePointer.start(event); - }; - Mouse.prototype.onMouseMove = /** - * @param {MouseEvent} event - */ - function (event) { - if(this._game.input.disabled || this.disabled) { - return; - } - event['identifier'] = 0; - this._game.input.mousePointer.move(event); - }; - Mouse.prototype.onMouseUp = /** - * @param {MouseEvent} event - */ - function (event) { - if(this._game.input.disabled || this.disabled) { - return; - } - event['identifier'] = 0; - this._game.input.mousePointer.stop(event); - }; - Mouse.prototype.stop = /** - * Stop the event listeners - * @method stop - */ - function () { - //this._game.stage.canvas.addEventListener('mousedown', (event: MouseEvent) => this.onMouseDown(event), true); - //this._game.stage.canvas.addEventListener('mousemove', (event: MouseEvent) => this.onMouseMove(event), true); - //this._game.stage.canvas.addEventListener('mouseup', (event: MouseEvent) => this.onMouseUp(event), true); - }; - return Mouse; - })(); - Phaser.Mouse = Mouse; -})(Phaser || (Phaser = {})); -/// -/// -/** -* Phaser - Touch -* -* The Touch class handles touch interactions with the game and the resulting Pointer objects. -* http://www.w3.org/TR/touch-events/ -* https://developer.mozilla.org/en-US/docs/DOM/TouchList -* http://www.html5rocks.com/en/mobile/touchandmouse/ -* Note: Android 2.x only supports 1 touch event at once, no multi-touch -*/ -var Phaser; -(function (Phaser) { - var Touch = (function () { - /** - * Constructor - * @param {Game} game. - * @return {Touch} This object. - */ - function Touch(game) { - /** - * You can disable all Input by setting disabled = true. While set all new input related events will be ignored. - * @type {Boolean} - */ - this.disabled = false; - this._game = game; - } - Touch.prototype.start = /** - * Starts the event listeners running - * @method start - */ - function () { - var _this = this; - if(this._game.device.touch) { - this._game.stage.canvas.addEventListener('touchstart', function (event) { - return _this.onTouchStart(event); - }, false); - this._game.stage.canvas.addEventListener('touchmove', function (event) { - return _this.onTouchMove(event); - }, false); - this._game.stage.canvas.addEventListener('touchend', function (event) { - return _this.onTouchEnd(event); - }, false); - this._game.stage.canvas.addEventListener('touchenter', function (event) { - return _this.onTouchEnter(event); - }, false); - this._game.stage.canvas.addEventListener('touchleave', function (event) { - return _this.onTouchLeave(event); - }, false); - this._game.stage.canvas.addEventListener('touchcancel', function (event) { - return _this.onTouchCancel(event); - }, false); - document.addEventListener('touchmove', function (event) { - return _this.consumeTouchMove(event); - }, false); - } - }; - Touch.prototype.consumeTouchMove = /** - * Prevent iOS bounce-back (doesn't work?) - * @method consumeTouchMove - * @param {Any} event - **/ - function (event) { - event.preventDefault(); - }; - Touch.prototype.onTouchStart = /** - * - * @method onTouchStart - * @param {Any} event - **/ - function (event) { - if(this._game.input.disabled || this.disabled) { - return; - } - event.preventDefault(); - // event.targetTouches = list of all touches on the TARGET ELEMENT (i.e. game dom element) - // event.touches = list of all touches on the ENTIRE DOCUMENT, not just the target element - // event.changedTouches = the touches that CHANGED in this event, not the total number of them - for(var i = 0; i < event.changedTouches.length; i++) { - this._game.input.startPointer(event.changedTouches[i]); - } - }; - Touch.prototype.onTouchCancel = /** - * Touch cancel - touches that were disrupted (perhaps by moving into a plugin or browser chrome) - * Occurs for example on iOS when you put down 4 fingers and the app selector UI appears - * @method onTouchCancel - * @param {Any} event - **/ - function (event) { - if(this._game.input.disabled || this.disabled) { - return; - } - event.preventDefault(); - // Touch cancel - touches that were disrupted (perhaps by moving into a plugin or browser chrome) - // http://www.w3.org/TR/touch-events/#dfn-touchcancel - for(var i = 0; i < event.changedTouches.length; i++) { - this._game.input.stopPointer(event.changedTouches[i]); - } - }; - Touch.prototype.onTouchEnter = /** - * For touch enter and leave its a list of the touch points that have entered or left the target - * Doesn't appear to be supported by most browsers yet - * @method onTouchEnter - * @param {Any} event - **/ - function (event) { - if(this._game.input.disabled || this.disabled) { - return; - } - event.preventDefault(); - for(var i = 0; i < event.changedTouches.length; i++) { - console.log('touch enter'); - } - }; - Touch.prototype.onTouchLeave = /** - * For touch enter and leave its a list of the touch points that have entered or left the target - * Doesn't appear to be supported by most browsers yet - * @method onTouchLeave - * @param {Any} event - **/ - function (event) { - event.preventDefault(); - for(var i = 0; i < event.changedTouches.length; i++) { - console.log('touch leave'); - } - }; - Touch.prototype.onTouchMove = /** - * - * @method onTouchMove - * @param {Any} event - **/ - function (event) { - event.preventDefault(); - for(var i = 0; i < event.changedTouches.length; i++) { - this._game.input.updatePointer(event.changedTouches[i]); - } - }; - Touch.prototype.onTouchEnd = /** - * - * @method onTouchEnd - * @param {Any} event - **/ - function (event) { - event.preventDefault(); - // For touch end its a list of the touch points that have been removed from the surface - // https://developer.mozilla.org/en-US/docs/DOM/TouchList - // event.changedTouches = the touches that CHANGED in this event, not the total number of them - for(var i = 0; i < event.changedTouches.length; i++) { - this._game.input.stopPointer(event.changedTouches[i]); - } - }; - Touch.prototype.stop = /** - * Stop the event listeners - * @method stop - */ - function () { - if(this._game.device.touch) { - //this._domElement.addEventListener('touchstart', (event) => this.onTouchStart(event), false); - //this._domElement.addEventListener('touchmove', (event) => this.onTouchMove(event), false); - //this._domElement.addEventListener('touchend', (event) => this.onTouchEnd(event), false); - //this._domElement.addEventListener('touchenter', (event) => this.onTouchEnter(event), false); - //this._domElement.addEventListener('touchleave', (event) => this.onTouchLeave(event), false); - //this._domElement.addEventListener('touchcancel', (event) => this.onTouchCancel(event), false); - } - }; - return Touch; - })(); - Phaser.Touch = Touch; -})(Phaser || (Phaser = {})); /// -/// -/** -* Phaser - Emitter -* -* Emitter is a lightweight particle emitter. It can be used for one-time explosions or for -* continuous effects like rain and fire. All it really does is launch Particle objects out -* at set intervals, and fixes their positions and velocities accorindgly. -*/ +/// +/// var Phaser; (function (Phaser) { - var Emitter = (function (_super) { - __extends(Emitter, _super); - /** - * Creates a new Emitter object at a specific position. - * Does NOT automatically generate or attach particles! - * - * @param x {number} The X position of the emitter. - * @param y {number} The Y position of the emitter. - * @param [size] {number} Specifies a maximum capacity for this emitter. - */ - function Emitter(game, x, y, size) { - if (typeof x === "undefined") { x = 0; } - if (typeof y === "undefined") { y = 0; } - if (typeof size === "undefined") { size = 0; } - _super.call(this, game, size); - this.x = x; - this.y = y; - this.width = 0; - this.height = 0; - this.minParticleSpeed = new Phaser.MicroPoint(-100, -100); - this.maxParticleSpeed = new Phaser.MicroPoint(100, 100); - this.minRotation = -360; - this.maxRotation = 360; - this.gravity = 0; - this.particleClass = null; - this.particleDrag = new Phaser.MicroPoint(); - this.frequency = 0.1; - this.lifespan = 3; - this.bounce = 0; - this._quantity = 0; - this._counter = 0; - this._explode = true; - this.on = false; - this._point = new Phaser.MicroPoint(); + var HeadlessRenderer = (function () { + function HeadlessRenderer(game) { + this._game = game; } - Emitter.prototype.destroy = /** - * Clean up memory. - */ - function () { - this.minParticleSpeed = null; - this.maxParticleSpeed = null; - this.particleDrag = null; - this.particleClass = null; - this._point = null; - _super.prototype.destroy.call(this); + HeadlessRenderer.prototype.render = function () { }; - Emitter.prototype.makeParticles = /** - * This function generates a new array of particle sprites to attach to the emitter. - * - * @param graphics If you opted to not pre-configure an array of Sprite objects, you can simply pass in a particle image or sprite sheet. - * @param quantity {number} The number of particles to generate when using the "create from image" option. - * @param multiple {boolean} Whether the image in the Graphics param is a single particle or a bunch of particles (if it's a bunch, they need to be square!). - * @param collide {number} Whether the particles should be flagged as not 'dead' (non-colliding particles are higher performance). 0 means no collisions, 0-1 controls scale of particle's bounding box. - * - * @return This Emitter instance (nice for chaining stuff together, if you're into that). - */ - function (graphics, quantity, multiple, collide) { - if (typeof quantity === "undefined") { quantity = 50; } - if (typeof multiple === "undefined") { multiple = false; } - if (typeof collide === "undefined") { collide = 0; } - this.maxSize = quantity; - var totalFrames = 1; - /* - if(Multiple) - { - var sprite:Sprite = new Sprite(this._game); - sprite.loadGraphic(Graphics,true); - totalFrames = sprite.frames; - sprite.destroy(); - } - */ - var randomFrame; - var particle; - var i = 0; - while(i < quantity) { - if(this.particleClass == null) { - particle = new Phaser.Particle(this._game); - } else { - particle = new this.particleClass(this._game); - } - if(multiple) { - /* - randomFrame = this._game.math.random()*totalFrames; - if(BakedRotations > 0) - particle.loadRotatedGraphic(Graphics,BakedRotations,randomFrame); - else - { - particle.loadGraphic(Graphics,true); - particle.frame = randomFrame; - } - */ - } else { - /* - if (BakedRotations > 0) - particle.loadRotatedGraphic(Graphics,BakedRotations); - else - particle.loadGraphic(Graphics); - */ - if(graphics) { - particle.loadGraphic(graphics); - } - } - if(collide > 0) { - particle.allowCollisions = Phaser.Collision.ANY; - particle.width *= collide; - particle.height *= collide; - //particle.centerOffsets(); - } else { - particle.allowCollisions = Phaser.Collision.NONE; - } - particle.exists = false; - this.add(particle); - i++; - } - return this; - }; - Emitter.prototype.update = /** - * Called automatically by the game loop, decides when to launch particles and when to "die". - */ - function () { - if(this.on) { - if(this._explode) { - this.on = false; - var i = 0; - var l = this._quantity; - if((l <= 0) || (l > this.length)) { - l = this.length; - } - while(i < l) { - this.emitParticle(); - i++; - } - this._quantity = 0; - } else { - this._timer += this._game.time.elapsed; - while((this.frequency > 0) && (this._timer > this.frequency) && this.on) { - this._timer -= this.frequency; - this.emitParticle(); - if((this._quantity > 0) && (++this._counter >= this._quantity)) { - this.on = false; - this._quantity = 0; - } - } - } - } - _super.prototype.update.call(this); - }; - Emitter.prototype.kill = /** - * Call this function to turn off all the particles and the emitter. - */ - function () { - this.on = false; - _super.prototype.kill.call(this); - }; - Emitter.prototype.start = /** - * Call this function to start emitting particles. - * - * @param explode {boolean} Whether the particles should all burst out at once. - * @param lifespan {number} How long each particle lives once emitted. 0 = forever. - * @param frequency {number} Ignored if Explode is set to true. Frequency is how often to emit a particle. 0 = never emit, 0.1 = 1 particle every 0.1 seconds, 5 = 1 particle every 5 seconds. - * @param quantity {number} How many particles to launch. 0 = "all of the particles". - */ - function (explode, lifespan, frequency, quantity) { - if (typeof explode === "undefined") { explode = true; } - if (typeof lifespan === "undefined") { lifespan = 0; } - if (typeof frequency === "undefined") { frequency = 0.1; } - if (typeof quantity === "undefined") { quantity = 0; } - this.revive(); - this.visible = true; - this.on = true; - this._explode = explode; - this.lifespan = lifespan; - this.frequency = frequency; - this._quantity += quantity; - this._counter = 0; - this._timer = 0; - }; - Emitter.prototype.emitParticle = /** - * This function can be used both internally and externally to emit the next particle. - */ - function () { - var particle = this.recycle(Phaser.Particle); - particle.lifespan = this.lifespan; - particle.elasticity = this.bounce; - particle.reset(this.x - (particle.width >> 1) + this._game.math.random() * this.width, this.y - (particle.height >> 1) + this._game.math.random() * this.height); - particle.visible = true; - if(this.minParticleSpeed.x != this.maxParticleSpeed.x) { - particle.velocity.x = this.minParticleSpeed.x + this._game.math.random() * (this.maxParticleSpeed.x - this.minParticleSpeed.x); - } else { - particle.velocity.x = this.minParticleSpeed.x; - } - if(this.minParticleSpeed.y != this.maxParticleSpeed.y) { - particle.velocity.y = this.minParticleSpeed.y + this._game.math.random() * (this.maxParticleSpeed.y - this.minParticleSpeed.y); - } else { - particle.velocity.y = this.minParticleSpeed.y; - } - particle.acceleration.y = this.gravity; - if(this.minRotation != this.maxRotation && this.minRotation !== 0 && this.maxRotation !== 0) { - particle.angularVelocity = this.minRotation + this._game.math.random() * (this.maxRotation - this.minRotation); - } else { - particle.angularVelocity = this.minRotation; - } - if(particle.angularVelocity != 0) { - particle.angle = this._game.math.random() * 360 - 180; - } - particle.drag.x = this.particleDrag.x; - particle.drag.y = this.particleDrag.y; - particle.onEmit(); - }; - Emitter.prototype.setSize = /** - * A more compact way of setting the width and height of the emitter. - * - * @param width {number} The desired width of the emitter (particles are spawned randomly within these dimensions). - * @param height {number} The desired height of the emitter. - */ - function (width, height) { - this.width = width; - this.height = height; - }; - Emitter.prototype.setXSpeed = /** - * A more compact way of setting the X velocity range of the emitter. - * - * @param Min {number} The minimum value for this range. - * @param Max {number} The maximum value for this range. - */ - function (min, max) { - if (typeof min === "undefined") { min = 0; } - if (typeof max === "undefined") { max = 0; } - this.minParticleSpeed.x = min; - this.maxParticleSpeed.x = max; - }; - Emitter.prototype.setYSpeed = /** - * A more compact way of setting the Y velocity range of the emitter. - * - * @param Min {number} The minimum value for this range. - * @param Max {number} The maximum value for this range. - */ - function (min, max) { - if (typeof min === "undefined") { min = 0; } - if (typeof max === "undefined") { max = 0; } - this.minParticleSpeed.y = min; - this.maxParticleSpeed.y = max; - }; - Emitter.prototype.setRotation = /** - * A more compact way of setting the angular velocity constraints of the emitter. - * - * @param Min {number} The minimum value for this range. - * @param Max {number} The maximum value for this range. - */ - function (min, max) { - if (typeof min === "undefined") { min = 0; } - if (typeof max === "undefined") { max = 0; } - this.minRotation = min; - this.maxRotation = max; - }; - Emitter.prototype.at = /** - * Change the emitter's midpoint to match the midpoint of a Object. - * - * @param Object {object} The Object that you want to sync up with. - */ - function (object) { - object.getMidpoint(this._point); - this.x = this._point.x - (this.width >> 1); - this.y = this._point.y - (this.height >> 1); - }; - return Emitter; - })(Phaser.Group); - Phaser.Emitter = Emitter; -})(Phaser || (Phaser = {})); -/// -/// -/** -* Phaser - GeomSprite -* -* A GeomSprite is a special kind of GameObject that contains a base geometry class (Circle, Line, Point, Rectangle). -* They can be rendered in the game and used for collision just like any other game object. Display of them is controlled -* via the lineWidth / lineColor / fillColor and renderOutline / renderFill properties. -*/ -var Phaser; -(function (Phaser) { - var GeomSprite = (function (_super) { - __extends(GeomSprite, _super); - /** - * GeomSprite constructor - * Create a new GeomSprite. - * - * @param game {Phaser.Game} Current game instance. - * @param [x] {number} the initial x position of the sprite. - * @param [y] {number} the initial y position of the sprite. - */ - function GeomSprite(game, x, y) { - if (typeof x === "undefined") { x = 0; } - if (typeof y === "undefined") { y = 0; } - _super.call(this, game, x, y); - // local rendering related temp vars to help avoid gc spikes - this._dx = 0; - this._dy = 0; - this._dw = 0; - this._dh = 0; - /** - * Geom type of this sprite. (available: UNASSIGNED, CIRCLE, LINE, POINT, RECTANGLE) - * @type {number} - */ - this.type = 0; - /** - * Render outline of this sprite or not. (default is true) - * @type {boolean} - */ - this.renderOutline = true; - /** - * Fill the shape or not. (default is true) - * @type {boolean} - */ - this.renderFill = true; - /** - * Width of outline. (default is 1) - * @type {number} - */ - this.lineWidth = 1; - /** - * Width of outline. (default is 1) - * @type {number} - */ - this.lineColor = 'rgb(0,255,0)'; - /** - * The color of the filled area in rgb or rgba string format - * @type {string} Defaults to rgb(0,100,0) - a green color - */ - this.fillColor = 'rgb(0,100,0)'; - this.type = GeomSprite.UNASSIGNED; - return this; - } - GeomSprite.UNASSIGNED = 0; - GeomSprite.CIRCLE = 1; - GeomSprite.LINE = 2; - GeomSprite.POINT = 3; - GeomSprite.RECTANGLE = 4; - GeomSprite.POLYGON = 5; - GeomSprite.prototype.loadCircle = /** - * Just like Sprite.loadGraphic(), this will load a circle and set its shape to Circle. - * @param circle {Circle} Circle geometry define. - * @return {GeomSprite} GeomSprite instance itself. - */ - function (circle) { - this.refresh(); - this.circle = circle; - this.type = GeomSprite.CIRCLE; - return this; - }; - GeomSprite.prototype.loadLine = /** - * Just like Sprite.loadGraphic(), this will load a line and set its shape to Line. - * @param line {Line} Line geometry define. - * @return {GeomSprite} GeomSprite instance itself. - */ - function (line) { - this.refresh(); - this.line = line; - this.type = GeomSprite.LINE; - return this; - }; - GeomSprite.prototype.loadPoint = /** - * Just like Sprite.loadGraphic(), this will load a point and set its shape to Point. - * @param point {Point} Point geometry define. - * @return {GeomSprite} GeomSprite instance itself. - */ - function (point) { - this.refresh(); - this.point = point; - this.type = GeomSprite.POINT; - return this; - }; - GeomSprite.prototype.loadRectangle = /** - * Just like Sprite.loadGraphic(), this will load a rect and set its shape to Rectangle. - * @param rect {Rectangle} Rectangle geometry define. - * @return {GeomSprite} GeomSprite instance itself. - */ - function (rect) { - this.refresh(); - this.rect = rect; - this.type = GeomSprite.RECTANGLE; - return this; - }; - GeomSprite.prototype.createCircle = /** - * Create a circle shape with specific diameter. - * @param diameter {number} Diameter of the circle. - * @return {GeomSprite} GeomSprite instance itself. - */ - function (diameter) { - this.refresh(); - this.circle = new Phaser.Circle(this.x, this.y, diameter); - this.type = GeomSprite.CIRCLE; - this.frameBounds.setTo(this.circle.x - this.circle.radius, this.circle.y - this.circle.radius, this.circle.diameter, this.circle.diameter); - return this; - }; - GeomSprite.prototype.createLine = /** - * Create a line shape with specific end point. - * @param x {number} X position of the end point. - * @param y {number} Y position of the end point. - * @return {GeomSprite} GeomSprite instance itself. - */ - function (x, y) { - this.refresh(); - this.line = new Phaser.Line(this.x, this.y, x, y); - this.type = GeomSprite.LINE; - this.frameBounds.setTo(this.x, this.y, this.line.width, this.line.height); - return this; - }; - GeomSprite.prototype.createPoint = /** - * Create a point shape at spriter's position. - * @return {GeomSprite} GeomSprite instance itself. - */ - function () { - this.refresh(); - this.point = new Phaser.Point(this.x, this.y); - this.type = GeomSprite.POINT; - this.frameBounds.width = 1; - this.frameBounds.height = 1; - return this; - }; - GeomSprite.prototype.createRectangle = /** - * Create a rectangle shape of the given width and height size - * @param width {Number} Width of the rectangle - * @param height {Number} Height of the rectangle - * @return {GeomSprite} GeomSprite instance. - */ - function (width, height) { - this.refresh(); - this.rect = new Phaser.Rectangle(this.x, this.y, width, height); - this.type = GeomSprite.RECTANGLE; - this.frameBounds.copyFrom(this.rect); - return this; - }; - GeomSprite.prototype.createPolygon = /** - * Create a polygon object - * @param width {Number} Width of the rectangle - * @param height {Number} Height of the rectangle - * @return {GeomSprite} GeomSprite instance. - */ - function (points) { - if (typeof points === "undefined") { points = []; } - this.refresh(); - this.polygon = new Phaser.Polygon(new Phaser.Vector2(this.x, this.y), points); - this.type = GeomSprite.POLYGON; - //this.frameBounds.copyFrom(this.rect); - return this; - }; - GeomSprite.prototype.refresh = /** - * Destroy all geom shapes of this sprite. - */ - function () { - this.circle = null; - this.line = null; - this.point = null; - this.rect = null; - }; - GeomSprite.prototype.update = /** - * Update bounds. - */ - function () { - // Update bounds and position? - if(this.type == GeomSprite.UNASSIGNED) { - return; - } else if(this.type == GeomSprite.CIRCLE) { - this.circle.x = this.x; - this.circle.y = this.y; - this.frameBounds.width = this.circle.diameter; - this.frameBounds.height = this.circle.diameter; - } else if(this.type == GeomSprite.LINE) { - this.line.x1 = this.x; - this.line.y1 = this.y; - this.frameBounds.setTo(this.x, this.y, this.line.width, this.line.height); - } else if(this.type == GeomSprite.POINT) { - this.point.x = this.x; - this.point.y = this.y; - } else if(this.type == GeomSprite.RECTANGLE) { - this.rect.x = this.x; - this.rect.y = this.y; - this.frameBounds.copyFrom(this.rect); - } - }; - GeomSprite.prototype.inCamera = /** - * Check whether this object is visible in a specific camera rectangle. - * @param camera {Rectangle} The rectangle you want to check. - * @return {boolean} Return true if bounds of this sprite intersects the given rectangle, otherwise return false. - */ - function (camera) { - if(this.scrollFactor.x !== 1.0 || this.scrollFactor.y !== 1.0) { - this._dx = this.frameBounds.x - (camera.x * this.scrollFactor.x); - this._dy = this.frameBounds.y - (camera.y * this.scrollFactor.x); - this._dw = this.frameBounds.width * this.scale.x; - this._dh = this.frameBounds.height * this.scale.y; - return (camera.right > this._dx) && (camera.x < this._dx + this._dw) && (camera.bottom > this._dy) && (camera.y < this._dy + this._dh); - } else { - return camera.intersects(this.frameBounds); - } - }; - GeomSprite.prototype.render = /** - * Render this sprite to specific camera. Called by game loop after update(). - * @param camera {Camera} Camera this sprite will be rendered to. - * @cameraOffsetX {number} X offset to the camera. - * @cameraOffsetY {number} Y offset to the camera. - * @return {boolean} Return false if not rendered, otherwise return true. - */ - function (camera, cameraOffsetX, cameraOffsetY) { - // Render checks - if(this.type == GeomSprite.UNASSIGNED || this.visible === false || this.scale.x == 0 || this.scale.y == 0 || this.alpha < 0.1 || this.cameraBlacklist.indexOf(camera.ID) !== -1 || this.inCamera(camera.worldView) == false) { + HeadlessRenderer.prototype.renderSprite = function (camera, sprite) { + // Render checks (needs inCamera check added) + if(sprite.scale.x == 0 || sprite.scale.y == 0 || sprite.texture.alpha < 0.1) { return false; } - // Alpha - if(this.alpha !== 1) { - var globalAlpha = this.context.globalAlpha; - this.context.globalAlpha = this.alpha; - } - this._dx = cameraOffsetX + (this.frameBounds.x - camera.worldView.x); - this._dy = cameraOffsetY + (this.frameBounds.y - camera.worldView.y); - this._dw = this.frameBounds.width * this.scale.x; - this._dh = this.frameBounds.height * this.scale.y; - // Apply camera difference - if(this.scrollFactor.x !== 1.0 || this.scrollFactor.y !== 1.0) { - this._dx -= (camera.worldView.x * this.scrollFactor.x); - this._dy -= (camera.worldView.y * this.scrollFactor.y); - } - // Rotation is disabled for now as I don't want it to be misleading re: collision - /* - if (this.angle !== 0) - { - this.context.save(); - this.context.translate(this._dx + (this._dw / 2) - this.origin.x, this._dy + (this._dh / 2) - this.origin.y); - this.context.rotate(this.angle * (Math.PI / 180)); - this._dx = -(this._dw / 2); - this._dy = -(this._dh / 2); - } - */ - this._dx = Math.round(this._dx); - this._dy = Math.round(this._dy); - this._dw = Math.round(this._dw); - this._dh = Math.round(this._dh); - this._game.stage.saveCanvasValues(); - // Debug - //this.context.fillStyle = 'rgba(255,0,0,0.5)'; - //this.context.fillRect(this.frameBounds.x, this.frameBounds.y, this.frameBounds.width, this.frameBounds.height); - this.context.lineWidth = this.lineWidth; - this.context.strokeStyle = this.lineColor; - this.context.fillStyle = this.fillColor; - if(this._game.stage.fillStyle !== this.fillColor) { - } - // Primitive Renderer - if(this.type == GeomSprite.CIRCLE) { - this.context.beginPath(); - this.context.arc(this._dx, this._dy, this.circle.radius, 0, Math.PI * 2); - if(this.renderOutline) { - this.context.stroke(); - } - if(this.renderFill) { - this.context.fill(); - } - this.context.closePath(); - } else if(this.type == GeomSprite.LINE) { - this.context.beginPath(); - this.context.moveTo(this._dx, this._dy); - this.context.lineTo(this.line.x2, this.line.y2); - this.context.stroke(); - this.context.closePath(); - } else if(this.type == GeomSprite.POINT) { - this.context.fillRect(this._dx, this._dy, 2, 2); - } else if(this.type == GeomSprite.RECTANGLE) { - // We can use the faster fillRect if we don't need the outline - if(this.renderOutline == false) { - this.context.fillRect(this._dx, this._dy, this.rect.width, this.rect.height); - } else { - this.context.beginPath(); - this.context.rect(this._dx, this._dy, this.rect.width, this.rect.height); - this.context.stroke(); - if(this.renderFill) { - this.context.fill(); - } - this.context.closePath(); - } - // And now the edge points - this.context.fillStyle = 'rgb(255,255,255)'; - //this.renderPoint(this.rect.topLeft, this._dx, this._dy, 2); - //this.renderPoint(this.rect.topCenter, this._dx, this._dy, 2); - //this.renderPoint(this.rect.topRight, this._dx, this._dy, 2); - //this.renderPoint(this.rect.leftCenter, this._dx, this._dy, 2); - //this.renderPoint(this.rect.center, this._dx, this._dy, 2); - //this.renderPoint(this.rect.rightCenter, this._dx, this._dy, 2); - //this.renderPoint(this.rect.bottomLeft, this._dx, this._dy, 2); - //this.renderPoint(this.rect.bottomCenter, this._dx, this._dy, 2); - //this.renderPoint(this.rect.bottomRight, this._dx, this._dy, 2); - this.renderPoint(this.rect.topLeft, 0, 0, 2); - this.renderPoint(this.rect.topCenter, 0, 0, 2); - this.renderPoint(this.rect.topRight, 0, 0, 2); - this.renderPoint(this.rect.leftCenter, 0, 0, 2); - this.renderPoint(this.rect.center, 0, 0, 2); - this.renderPoint(this.rect.rightCenter, 0, 0, 2); - this.renderPoint(this.rect.bottomLeft, 0, 0, 2); - this.renderPoint(this.rect.bottomCenter, 0, 0, 2); - this.renderPoint(this.rect.bottomRight, 0, 0, 2); - } - this._game.stage.restoreCanvasValues(); - if(this.rotation !== 0) { - this.context.translate(0, 0); - this.context.restore(); - } - if(globalAlpha > -1) { - this.context.globalAlpha = globalAlpha; - } return true; }; - GeomSprite.prototype.renderPoint = /** - * Render a point of geometry. - * @param point {Point} Position of the point. - * @param offsetX {number} X offset to its position. - * @param offsetY {number} Y offset to its position. - * @param [size] {number} point size. - */ - function (point, offsetX, offsetY, size) { - if (typeof offsetX === "undefined") { offsetX = 0; } - if (typeof offsetY === "undefined") { offsetY = 0; } - if (typeof size === "undefined") { size = 1; } - this.context.fillRect(offsetX + point.x, offsetY + point.y, size, size); - }; - GeomSprite.prototype.renderDebugInfo = /** - * Render debug infos. (this method does not work now) - * @param x {number} X position of the debug info to be rendered. - * @param y {number} Y position of the debug info to be rendered. - * @param [color] {number} color of the debug info to be rendered. (format is css color string) - */ - function (x, y, color) { - if (typeof color === "undefined") { color = 'rgb(255,255,255)'; } - //this.context.fillStyle = color; - //this.context.fillText('Sprite: ' + this.name + ' (' + this.frameBounds.width + ' x ' + this.frameBounds.height + ')', x, y); - //this.context.fillText('x: ' + this.frameBounds.x.toFixed(1) + ' y: ' + this.frameBounds.y.toFixed(1) + ' rotation: ' + this.angle.toFixed(1), x, y + 14); - //this.context.fillText('dx: ' + this._dx.toFixed(1) + ' dy: ' + this._dy.toFixed(1) + ' dw: ' + this._dw.toFixed(1) + ' dh: ' + this._dh.toFixed(1), x, y + 28); - //this.context.fillText('sx: ' + this._sx.toFixed(1) + ' sy: ' + this._sy.toFixed(1) + ' sw: ' + this._sw.toFixed(1) + ' sh: ' + this._sh.toFixed(1), x, y + 42); - }; - GeomSprite.prototype.collide = /** - * Gives a basic boolean response to a geometric collision. - * If you need the details of the collision use the Collision functions instead and inspect the IntersectResult object. - * @param source {GeomSprite} Sprite you want to check. - * @return {boolean} Whether they overlaps or not. - */ - function (source) { - // Circle vs. Circle - if(this.type == GeomSprite.CIRCLE && source.type == GeomSprite.CIRCLE) { - return Phaser.Collision.circleToCircle(this.circle, source.circle).result; - } - // Circle vs. Rect - if(this.type == GeomSprite.CIRCLE && source.type == GeomSprite.RECTANGLE) { - return Phaser.Collision.circleToRectangle(this.circle, source.rect).result; - } - // Circle vs. Point - if(this.type == GeomSprite.CIRCLE && source.type == GeomSprite.POINT) { - return Phaser.Collision.circleContainsPoint(this.circle, source.point).result; - } - // Circle vs. Line - if(this.type == GeomSprite.CIRCLE && source.type == GeomSprite.LINE) { - return Phaser.Collision.lineToCircle(source.line, this.circle).result; - } - // Rect vs. Rect - if(this.type == GeomSprite.RECTANGLE && source.type == GeomSprite.RECTANGLE) { - return Phaser.Collision.rectangleToRectangle(this.rect, source.rect).result; - } - // Rect vs. Circle - if(this.type == GeomSprite.RECTANGLE && source.type == GeomSprite.CIRCLE) { - return Phaser.Collision.circleToRectangle(source.circle, this.rect).result; - } - // Rect vs. Point - if(this.type == GeomSprite.RECTANGLE && source.type == GeomSprite.POINT) { - return Phaser.Collision.pointToRectangle(source.point, this.rect).result; - } - // Rect vs. Line - if(this.type == GeomSprite.RECTANGLE && source.type == GeomSprite.LINE) { - return Phaser.Collision.lineToRectangle(source.line, this.rect).result; - } - // Point vs. Point - if(this.type == GeomSprite.POINT && source.type == GeomSprite.POINT) { - return this.point.equals(source.point); - } - // Point vs. Circle - if(this.type == GeomSprite.POINT && source.type == GeomSprite.CIRCLE) { - return Phaser.Collision.circleContainsPoint(source.circle, this.point).result; - } - // Point vs. Rect - if(this.type == GeomSprite.POINT && source.type == GeomSprite.RECTANGLE) { - return Phaser.Collision.pointToRectangle(this.point, source.rect).result; - } - // Point vs. Line - if(this.type == GeomSprite.POINT && source.type == GeomSprite.LINE) { - return source.line.isPointOnLine(this.point.x, this.point.y); - } - // Line vs. Line - if(this.type == GeomSprite.LINE && source.type == GeomSprite.LINE) { - return Phaser.Collision.lineSegmentToLineSegment(this.line, source.line).result; - } - // Line vs. Circle - if(this.type == GeomSprite.LINE && source.type == GeomSprite.CIRCLE) { - return Phaser.Collision.lineToCircle(this.line, source.circle).result; - } - // Line vs. Rect - if(this.type == GeomSprite.LINE && source.type == GeomSprite.RECTANGLE) { - return Phaser.Collision.lineSegmentToRectangle(this.line, source.rect).result; - } - // Line vs. Point - if(this.type == GeomSprite.LINE && source.type == GeomSprite.POINT) { - return this.line.isPointOnLine(source.point.x, source.point.y); - } - return false; - }; - return GeomSprite; - })(Phaser.GameObject); - Phaser.GeomSprite = GeomSprite; -})(Phaser || (Phaser = {})); -/// -/// -/** -* Phaser - Particle -* -* This is a simple particle class that extends a Sprite to have a slightly more -* specialised behaviour. It is used exclusively by the Emitter class and can be extended as required. -*/ -var Phaser; -(function (Phaser) { - var Particle = (function (_super) { - __extends(Particle, _super); - /** - * Instantiate a new particle. Like Sprite, all meaningful creation - * happens during loadGraphic() or makeGraphic() or whatever. - */ - function Particle(game) { - _super.call(this, game); - this.lifespan = 0; - this.friction = 500; - } - Particle.prototype.update = /** - * The particle's main update logic. Basically it checks to see if it should - * be dead yet, and then has some special bounce behavior if there is some gravity on it. - */ - function () { - //lifespan behavior - if(this.lifespan <= 0) { - return; - } - this.lifespan -= this._game.time.elapsed; - if(this.lifespan <= 0) { - this.kill(); - } - //simpler bounce/spin behavior for now - if(this.touching) { - if(this.angularVelocity != 0) { - this.angularVelocity = -this.angularVelocity; - } - } - if(this.acceleration.y > 0)//special behavior for particles with gravity - { - if(this.touching & Phaser.Collision.FLOOR) { - this.drag.x = this.friction; - if(!(this.wasTouching & Phaser.Collision.FLOOR)) { - if(this.velocity.y < -this.elasticity * 10) { - if(this.angularVelocity != 0) { - this.angularVelocity *= -this.elasticity; - } - } else { - this.velocity.y = 0; - this.angularVelocity = 0; - } - } - } else { - this.drag.x = 0; - } - } - }; - Particle.prototype.onEmit = /** - * Triggered whenever this object is launched by a Emitter. - * You can override this to add custom behavior like a sound or AI or something. - */ - function () { - }; - return Particle; - })(Phaser.Sprite); - Phaser.Particle = Particle; -})(Phaser || (Phaser = {})); -/// -/** -* Phaser - TilemapLayer -* -* A Tilemap Layer. Tiled format maps can have multiple overlapping layers. -*/ -var Phaser; -(function (Phaser) { - var TilemapLayer = (function () { - /** - * TilemapLayer constructor - * Create a new TilemapLayer. - * - * @param game {Phaser.Game} Current game instance. - * @param parent {Tilemap} The tilemap that contains this layer. - * @param key {string} Asset key for this map. - * @param mapFormat {number} Format of this map data, available: Tilemap.FORMAT_CSV or Tilemap.FORMAT_TILED_JSON. - * @param name {string} Name of this layer, so you can get this layer by its name. - * @param tileWidth {number} Width of tiles in this map. - * @param tileHeight {number} Height of tiles in this map. - */ - function TilemapLayer(game, parent, key, mapFormat, name, tileWidth, tileHeight) { - this._startX = 0; - this._startY = 0; - this._maxX = 0; - this._maxY = 0; - this._tx = 0; - this._ty = 0; - this._dx = 0; - this._dy = 0; - this._oldCameraX = 0; - this._oldCameraY = 0; - /** - * Opacity of this layer. - * @type {number} - */ - this.alpha = 1; - /** - * Controls whether update() and draw() are automatically called. - * @type {boolean} - */ - this.exists = true; - /** - * Controls whether draw() are automatically called. - * @type {boolean} - */ - this.visible = true; - /** - * How many tiles in each row. - * Read-only variable, do NOT recommend changing after the map is loaded! - * @type {number} - */ - this.widthInTiles = 0; - /** - * How many tiles in each column. - * Read-only variable, do NOT recommend changing after the map is loaded! - * @type {number} - */ - this.heightInTiles = 0; - /** - * Read-only variable, do NOT recommend changing after the map is loaded! - * @type {number} - */ - this.widthInPixels = 0; - /** - * Read-only variable, do NOT recommend changing after the map is loaded! - * @type {number} - */ - this.heightInPixels = 0; - /** - * Distance between REAL tiles to the tileset texture bound. - * @type {number} - */ - this.tileMargin = 0; - /** - * Distance between every 2 neighbor tile in the tileset texture. - * @type {number} - */ - this.tileSpacing = 0; - this._game = game; - this._parent = parent; - this.name = name; - this.mapFormat = mapFormat; - this.tileWidth = tileWidth; - this.tileHeight = tileHeight; - this.boundsInTiles = new Phaser.Rectangle(); - //this.scrollFactor = new MicroPoint(1, 1); - this.canvas = game.stage.canvas; - this.context = game.stage.context; - this.mapData = []; - this._tempTileBlock = []; - this._texture = this._game.cache.getImage(key); - } - TilemapLayer.prototype.putTile = /** - * Set a specific tile with its x and y in tiles. - * @param x {number} X position of this tile. - * @param y {number} Y position of this tile. - * @param index {number} The index of this tile type in the core map data. - */ - function (x, y, index) { - x = this._game.math.snapToFloor(x, this.tileWidth) / this.tileWidth; - y = this._game.math.snapToFloor(y, this.tileHeight) / this.tileHeight; - if(y >= 0 && y < this.mapData.length) { - if(x >= 0 && x < this.mapData[y].length) { - this.mapData[y][x] = index; - } - } - }; - TilemapLayer.prototype.swapTile = /** - * Swap tiles with 2 kinds of indexes. - * @param tileA {number} First tile index. - * @param tileB {number} Second tile index. - * @param [x] {number} specify a rectangle of tiles to operate. The x position in tiles of rectangle's left-top corner. - * @param [y] {number} specify a rectangle of tiles to operate. The y position in tiles of rectangle's left-top corner. - * @param [width] {number} specify a rectangle of tiles to operate. The width in tiles. - * @param [height] {number} specify a rectangle of tiles to operate. The height in tiles. - */ - function (tileA, tileB, x, y, width, height) { - if (typeof x === "undefined") { x = 0; } - if (typeof y === "undefined") { y = 0; } - if (typeof width === "undefined") { width = this.widthInTiles; } - if (typeof height === "undefined") { height = this.heightInTiles; } - this.getTempBlock(x, y, width, height); - for(var r = 0; r < this._tempTileBlock.length; r++) { - // First sweep marking tileA as needing a new index - if(this._tempTileBlock[r].tile.index == tileA) { - this._tempTileBlock[r].newIndex = true; - } - // In the same pass we can swap tileB to tileA - if(this._tempTileBlock[r].tile.index == tileB) { - this.mapData[this._tempTileBlock[r].y][this._tempTileBlock[r].x] = tileA; - } - } - for(var r = 0; r < this._tempTileBlock.length; r++) { - // And now swap our newIndex tiles for tileB - if(this._tempTileBlock[r].newIndex == true) { - this.mapData[this._tempTileBlock[r].y][this._tempTileBlock[r].x] = tileB; - } - } - }; - TilemapLayer.prototype.fillTile = /** - * Fill a tile block with a specific tile index. - * @param index {number} Index of tiles you want to fill with. - * @param [x] {number} x position (in tiles) of block's left-top corner. - * @param [y] {number} y position (in tiles) of block's left-top corner. - * @param [width] {number} width of block. - * @param [height] {number} height of block. - */ - function (index, x, y, width, height) { - if (typeof x === "undefined") { x = 0; } - if (typeof y === "undefined") { y = 0; } - if (typeof width === "undefined") { width = this.widthInTiles; } - if (typeof height === "undefined") { height = this.heightInTiles; } - this.getTempBlock(x, y, width, height); - for(var r = 0; r < this._tempTileBlock.length; r++) { - this.mapData[this._tempTileBlock[r].y][this._tempTileBlock[r].x] = index; - } - }; - TilemapLayer.prototype.randomiseTiles = /** - * Set random tiles to a specific tile block. - * @param tiles {number[]} Tiles with indexes in this array will be randomly set to the given block. - * @param [x] {number} x position (in tiles) of block's left-top corner. - * @param [y] {number} y position (in tiles) of block's left-top corner. - * @param [width] {number} width of block. - * @param [height] {number} height of block. - */ - function (tiles, x, y, width, height) { - if (typeof x === "undefined") { x = 0; } - if (typeof y === "undefined") { y = 0; } - if (typeof width === "undefined") { width = this.widthInTiles; } - if (typeof height === "undefined") { height = this.heightInTiles; } - this.getTempBlock(x, y, width, height); - for(var r = 0; r < this._tempTileBlock.length; r++) { - this.mapData[this._tempTileBlock[r].y][this._tempTileBlock[r].x] = this._game.math.getRandom(tiles); - } - }; - TilemapLayer.prototype.replaceTile = /** - * Replace one kind of tiles to another kind. - * @param tileA {number} Index of tiles you want to replace. - * @param tileB {number} Index of tiles you want to set. - * @param [x] {number} x position (in tiles) of block's left-top corner. - * @param [y] {number} y position (in tiles) of block's left-top corner. - * @param [width] {number} width of block. - * @param [height] {number} height of block. - */ - function (tileA, tileB, x, y, width, height) { - if (typeof x === "undefined") { x = 0; } - if (typeof y === "undefined") { y = 0; } - if (typeof width === "undefined") { width = this.widthInTiles; } - if (typeof height === "undefined") { height = this.heightInTiles; } - this.getTempBlock(x, y, width, height); - for(var r = 0; r < this._tempTileBlock.length; r++) { - if(this._tempTileBlock[r].tile.index == tileA) { - this.mapData[this._tempTileBlock[r].y][this._tempTileBlock[r].x] = tileB; - } - } - }; - TilemapLayer.prototype.getTileBlock = /** - * Get a tile block with specific position and size.(both are in tiles) - * @param x {number} X position of block's left-top corner. - * @param y {number} Y position of block's left-top corner. - * @param width {number} Width of block. - * @param height {number} Height of block. - */ - function (x, y, width, height) { - var output = []; - this.getTempBlock(x, y, width, height); - for(var r = 0; r < this._tempTileBlock.length; r++) { - output.push({ - x: this._tempTileBlock[r].x, - y: this._tempTileBlock[r].y, - tile: this._tempTileBlock[r].tile - }); - } - return output; - }; - TilemapLayer.prototype.getTileFromWorldXY = /** - * Get a tile with specific position (in world coordinate). (thus you give a position of a point which is within the tile) - * @param x {number} X position of the point in target tile. - * @param x {number} Y position of the point in target tile. - */ - function (x, y) { - x = this._game.math.snapToFloor(x, this.tileWidth) / this.tileWidth; - y = this._game.math.snapToFloor(y, this.tileHeight) / this.tileHeight; - return this.getTileIndex(x, y); - }; - TilemapLayer.prototype.getTileOverlaps = /** - * Get tiles overlaps the given object. - * @param object {GameObject} Tiles you want to get that overlaps this. - * @return {array} Array with tiles informations. (Each contains x, y and the tile.) - */ - function (object) { - // If the object is outside of the world coordinates then abort the check (tilemap has to exist within world bounds) - if(object.collisionMask.x < 0 || object.collisionMask.x > this.widthInPixels || object.collisionMask.y < 0 || object.collisionMask.bottom > this.heightInPixels) { - return; - } - // What tiles do we need to check against? - this._tempTileX = this._game.math.snapToFloor(object.collisionMask.x, this.tileWidth) / this.tileWidth; - this._tempTileY = this._game.math.snapToFloor(object.collisionMask.y, this.tileHeight) / this.tileHeight; - this._tempTileW = (this._game.math.snapToCeil(object.collisionMask.width, this.tileWidth) + this.tileWidth) / this.tileWidth; - this._tempTileH = (this._game.math.snapToCeil(object.collisionMask.height, this.tileHeight) + this.tileHeight) / this.tileHeight; - // Loop through the tiles we've got and check overlaps accordingly (the results are stored in this._tempTileBlock) - this._tempBlockResults = []; - this.getTempBlock(this._tempTileX, this._tempTileY, this._tempTileW, this._tempTileH, true); - Phaser.Collision.TILE_OVERLAP = false; - for(var r = 0; r < this._tempTileBlock.length; r++) { - if(Phaser.Collision.separateTile(object, this._tempTileBlock[r].x * this.tileWidth, this._tempTileBlock[r].y * this.tileHeight, this.tileWidth, this.tileHeight, this._tempTileBlock[r].tile.mass, this._tempTileBlock[r].tile.collideLeft, this._tempTileBlock[r].tile.collideRight, this._tempTileBlock[r].tile.collideUp, this._tempTileBlock[r].tile.collideDown, this._tempTileBlock[r].tile.separateX, this._tempTileBlock[r].tile.separateY) == true) { - this._tempBlockResults.push({ - x: this._tempTileBlock[r].x, - y: this._tempTileBlock[r].y, - tile: this._tempTileBlock[r].tile - }); - } - } - return this._tempBlockResults; - }; - TilemapLayer.prototype.getTempBlock = /** - * Get a tile block with its position and size. (This method does not return, it'll set result to _tempTileBlock) - * @param x {number} X position of block's left-top corner. - * @param y {number} Y position of block's left-top corner. - * @param width {number} Width of block. - * @param height {number} Height of block. - * @param collisionOnly {boolean} Whethor or not ONLY return tiles which will collide (its allowCollisions value is not Collision.NONE). - */ - function (x, y, width, height, collisionOnly) { - if (typeof collisionOnly === "undefined") { collisionOnly = false; } - if(x < 0) { - x = 0; - } - if(y < 0) { - y = 0; - } - if(width > this.widthInTiles) { - width = this.widthInTiles; - } - if(height > this.heightInTiles) { - height = this.heightInTiles; - } - this._tempTileBlock = []; - for(var ty = y; ty < y + height; ty++) { - for(var tx = x; tx < x + width; tx++) { - if(collisionOnly) { - // We only want to consider the tile for checking if you can actually collide with it - if(this.mapData[ty] && this.mapData[ty][tx] && this._parent.tiles[this.mapData[ty][tx]].allowCollisions != Phaser.Collision.NONE) { - this._tempTileBlock.push({ - x: tx, - y: ty, - tile: this._parent.tiles[this.mapData[ty][tx]] - }); - } - } else { - if(this.mapData[ty] && this.mapData[ty][tx]) { - this._tempTileBlock.push({ - x: tx, - y: ty, - tile: this._parent.tiles[this.mapData[ty][tx]] - }); - } - } - } - } - }; - TilemapLayer.prototype.getTileIndex = /** - * Get the tile index of specific position (in tiles). - * @param x {number} X position of the tile. - * @param y {number} Y position of the tile. - * @return {number} Index of the tile at that position. Return null if there isn't a tile there. - */ - function (x, y) { - if(y >= 0 && y < this.mapData.length) { - if(x >= 0 && x < this.mapData[y].length) { - return this.mapData[y][x]; - } - } - return null; - }; - TilemapLayer.prototype.addColumn = /** - * Add a column of tiles into the layer. - * @param column {string[]/number[]} An array of tile indexes to be added. - */ - function (column) { - var data = []; - for(var c = 0; c < column.length; c++) { - data[c] = parseInt(column[c]); - } - if(this.widthInTiles == 0) { - this.widthInTiles = data.length; - this.widthInPixels = this.widthInTiles * this.tileWidth; - } - this.mapData.push(data); - this.heightInTiles++; - this.heightInPixels += this.tileHeight; - }; - TilemapLayer.prototype.updateBounds = /** - * Update boundsInTiles with widthInTiles and heightInTiles. - */ - function () { - this.boundsInTiles.setTo(0, 0, this.widthInTiles, this.heightInTiles); - }; - TilemapLayer.prototype.parseTileOffsets = /** - * Parse tile offsets from map data. - * @return {number} length of _tileOffsets array. - */ - function () { - this._tileOffsets = []; - var i = 0; - if(this.mapFormat == Phaser.Tilemap.FORMAT_TILED_JSON) { - // For some reason Tiled counts from 1 not 0 - this._tileOffsets[0] = null; - i = 1; - } - for(var ty = this.tileMargin; ty < this._texture.height; ty += (this.tileHeight + this.tileSpacing)) { - for(var tx = this.tileMargin; tx < this._texture.width; tx += (this.tileWidth + this.tileSpacing)) { - this._tileOffsets[i] = { - x: tx, - y: ty - }; - i++; - } - } - return this._tileOffsets.length; - }; - TilemapLayer.prototype.renderDebugInfo = function (x, y, color) { - if (typeof color === "undefined") { color = 'rgb(255,255,255)'; } - this.context.fillStyle = color; - this.context.fillText('TilemapLayer: ' + this.name, x, y); - this.context.fillText('startX: ' + this._startX + ' endX: ' + this._maxX, x, y + 14); - this.context.fillText('startY: ' + this._startY + ' endY: ' + this._maxY, x, y + 28); - this.context.fillText('dx: ' + this._dx + ' dy: ' + this._dy, x, y + 42); - }; - TilemapLayer.prototype.render = /** - * Render this layer to a specific camera with offset to camera. - * @param camera {Camera} The camera the layer is going to be rendered. - * @param dx {number} X offset to the camera. - * @param dy {number} Y offset to the camera. - * @return {boolean} Return false if layer is invisible or has a too low opacity(will stop rendering), return true if succeed. - */ - function (camera, dx, dy) { - if(this.visible === false || this.alpha < 0.1) { - return false; - } - // Work out how many tiles we can fit into our camera and round it up for the edges - this._maxX = this._game.math.ceil(camera.width / this.tileWidth) + 1; - this._maxY = this._game.math.ceil(camera.height / this.tileHeight) + 1; - // And now work out where in the tilemap the camera actually is - this._startX = this._game.math.floor(camera.worldView.x / this.tileWidth); - this._startY = this._game.math.floor(camera.worldView.y / this.tileHeight); - // Tilemap bounds check - if(this._startX < 0) { - this._startX = 0; - } - if(this._startY < 0) { - this._startY = 0; - } - if(this._maxX > this.widthInTiles) { - this._maxX = this.widthInTiles; - } - if(this._maxY > this.heightInTiles) { - this._maxY = this.heightInTiles; - } - if(this._startX + this._maxX > this.widthInTiles) { - this._startX = this.widthInTiles - this._maxX; - } - if(this._startY + this._maxY > this.heightInTiles) { - this._startY = this.heightInTiles - this._maxY; - } - // Finally get the offset to avoid the blocky movement - this._dx = dx; - this._dy = dy; - this._dx += -(camera.worldView.x - (this._startX * this.tileWidth)); - this._dy += -(camera.worldView.y - (this._startY * this.tileHeight)); - this._tx = this._dx; - this._ty = this._dy; - // Apply camera difference - /* - if (this.scrollFactor.x !== 1.0 || this.scrollFactor.y !== 1.0) - { - this._dx -= (camera.worldView.x * this.scrollFactor.x); - this._dy -= (camera.worldView.y * this.scrollFactor.y); - } - */ - // Alpha - if(this.alpha !== 1) { - var globalAlpha = this.context.globalAlpha; - this.context.globalAlpha = this.alpha; - } - for(var row = this._startY; row < this._startY + this._maxY; row++) { - this._columnData = this.mapData[row]; - for(var tile = this._startX; tile < this._startX + this._maxX; tile++) { - if(this._tileOffsets[this._columnData[tile]]) { - this.context.drawImage(this._texture, // Source Image - this._tileOffsets[this._columnData[tile]].x, // Source X (location within the source image) - this._tileOffsets[this._columnData[tile]].y, // Source Y - this.tileWidth, // Source Width - this.tileHeight, // Source Height - this._tx, // Destination X (where on the canvas it'll be drawn) - this._ty, // Destination Y - this.tileWidth, // Destination Width (always same as Source Width unless scaled) - this.tileHeight); - // Destination Height (always same as Source Height unless scaled) - } - this._tx += this.tileWidth; - } - this._tx = this._dx; - this._ty += this.tileHeight; - } - if(globalAlpha > -1) { - this.context.globalAlpha = globalAlpha; - } - return true; - }; - return TilemapLayer; + return HeadlessRenderer; })(); - Phaser.TilemapLayer = TilemapLayer; -})(Phaser || (Phaser = {})); -/// -/** -* Phaser - Tile -* -* A Tile is a single representation of a tile within a Tilemap -*/ -var Phaser; -(function (Phaser) { - var Tile = (function () { - /** - * Tile constructor - * Create a new Tile. - * - * @param tilemap {Tilemap} the tilemap this tile belongs to. - * @param index {number} The index of this tile type in the core map data. - * @param width {number} Width of the tile. - * @param height number} Height of the tile. - */ - function Tile(game, tilemap, index, width, height) { - /** - * The virtual mass of the tile. - * @type {number} - */ - this.mass = 1.0; - /** - * Indicating collide with any object on the left. - * @type {boolean} - */ - this.collideLeft = false; - /** - * Indicating collide with any object on the right. - * @type {boolean} - */ - this.collideRight = false; - /** - * Indicating collide with any object on the top. - * @type {boolean} - */ - this.collideUp = false; - /** - * Indicating collide with any object on the bottom. - * @type {boolean} - */ - this.collideDown = false; - /** - * Enable separation at x-axis. - * @type {boolean} - */ - this.separateX = true; - /** - * Enable separation at y-axis. - * @type {boolean} - */ - this.separateY = true; - this._game = game; - this.tilemap = tilemap; - this.index = index; - this.width = width; - this.height = height; - this.allowCollisions = Phaser.Collision.NONE; - } - Tile.prototype.destroy = /** - * Clean up memory. - */ - function () { - this.tilemap = null; - }; - Tile.prototype.setCollision = /** - * Set collision configs. - * @param collision {number} Bit field of flags. (see Tile.allowCollision) - * @param resetCollisions {boolean} Reset collision flags before set. - * @param separateX {boolean} Enable seprate at x-axis. - * @param separateY {boolean} Enable seprate at y-axis. - */ - function (collision, resetCollisions, separateX, separateY) { - if(resetCollisions) { - this.resetCollision(); - } - this.separateX = separateX; - this.separateY = separateY; - this.allowCollisions = collision; - if(collision & Phaser.Collision.ANY) { - this.collideLeft = true; - this.collideRight = true; - this.collideUp = true; - this.collideDown = true; - return; - } - if(collision & Phaser.Collision.LEFT || collision & Phaser.Collision.WALL) { - this.collideLeft = true; - } - if(collision & Phaser.Collision.RIGHT || collision & Phaser.Collision.WALL) { - this.collideRight = true; - } - if(collision & Phaser.Collision.UP || collision & Phaser.Collision.CEILING) { - this.collideUp = true; - } - if(collision & Phaser.Collision.DOWN || collision & Phaser.Collision.CEILING) { - this.collideDown = true; - } - }; - Tile.prototype.resetCollision = /** - * Reset collision status flags. - */ - function () { - this.allowCollisions = Phaser.Collision.NONE; - this.collideLeft = false; - this.collideRight = false; - this.collideUp = false; - this.collideDown = false; - }; - Tile.prototype.toString = /** - * Returns a string representation of this object. - * @method toString - * @return {string} a string representation of the object. - **/ - function () { - return "[{Tiled (index=" + this.index + " collisions=" + this.allowCollisions + " width=" + this.width + " height=" + this.height + ")}]"; - }; - return Tile; - })(); - Phaser.Tile = Tile; -})(Phaser || (Phaser = {})); -/// -/// -/// -/// -/** -* Phaser - Tilemap -* -* This GameObject allows for the display of a tilemap within the game world. Tile maps consist of an image, tile data and a size. -* Internally it creates a TilemapLayer for each layer in the tilemap. -*/ -var Phaser; -(function (Phaser) { - var Tilemap = (function (_super) { - __extends(Tilemap, _super); - /** - * Tilemap constructor - * Create a new Tilemap. - * - * @param game {Phaser.Game} Current game instance. - * @param key {string} Asset key for this map. - * @param mapData {string} Data of this map. (a big 2d array, normally in csv) - * @param format {number} Format of this map data, available: Tilemap.FORMAT_CSV or Tilemap.FORMAT_TILED_JSON. - * @param resizeWorld {boolean} Resize the world bound automatically based on this tilemap? - * @param tileWidth {number} Width of tiles in this map. - * @param tileHeight {number} Height of tiles in this map. - */ - function Tilemap(game, key, mapData, format, resizeWorld, tileWidth, tileHeight) { - if (typeof resizeWorld === "undefined") { resizeWorld = true; } - if (typeof tileWidth === "undefined") { tileWidth = 0; } - if (typeof tileHeight === "undefined") { tileHeight = 0; } - _super.call(this, game); - /** - * Tilemap collision callback. - * @type {function} - */ - this.collisionCallback = null; - this.isGroup = false; - this.tiles = []; - this.layers = []; - this.mapFormat = format; - switch(format) { - case Tilemap.FORMAT_CSV: - this.parseCSV(game.cache.getText(mapData), key, tileWidth, tileHeight); - break; - case Tilemap.FORMAT_TILED_JSON: - this.parseTiledJSON(game.cache.getText(mapData), key); - break; - } - if(this.currentLayer && resizeWorld) { - this._game.world.setSize(this.currentLayer.widthInPixels, this.currentLayer.heightInPixels, true); - } - } - Tilemap.FORMAT_CSV = 0; - Tilemap.FORMAT_TILED_JSON = 1; - Tilemap.prototype.update = /** - * Inherited update method. - */ - function () { - }; - Tilemap.prototype.render = /** - * Render this tilemap to a specific camera with specific offset. - * @param camera {Camera} The camera this tilemap will be rendered to. - * @param cameraOffsetX {number} X offset of the camera. - * @param cameraOffsetY {number} Y offset of the camera. - */ - function (camera, cameraOffsetX, cameraOffsetY) { - if(this.cameraBlacklist.indexOf(camera.ID) == -1) { - // Loop through the layers - for(var i = 0; i < this.layers.length; i++) { - this.layers[i].render(camera, cameraOffsetX, cameraOffsetY); - } - } - }; - Tilemap.prototype.parseCSV = /** - * Parset csv map data and generate tiles. - * @param data {string} CSV map data. - * @param key {string} Asset key for tileset image. - * @param tileWidth {number} Width of its tile. - * @param tileHeight {number} Height of its tile. - */ - function (data, key, tileWidth, tileHeight) { - var layer = new Phaser.TilemapLayer(this._game, this, key, Tilemap.FORMAT_CSV, 'TileLayerCSV' + this.layers.length.toString(), tileWidth, tileHeight); - // Trim any rogue whitespace from the data - data = data.trim(); - var rows = data.split("\n"); - for(var i = 0; i < rows.length; i++) { - var column = rows[i].split(","); - if(column.length > 0) { - layer.addColumn(column); - } - } - layer.updateBounds(); - var tileQuantity = layer.parseTileOffsets(); - this.currentLayer = layer; - this.collisionLayer = layer; - this.layers.push(layer); - this.generateTiles(tileQuantity); - }; - Tilemap.prototype.parseTiledJSON = /** - * Parset JSON map data and generate tiles. - * @param data {string} JSON map data. - * @param key {string} Asset key for tileset image. - */ - function (data, key) { - // Trim any rogue whitespace from the data - data = data.trim(); - var json = JSON.parse(data); - for(var i = 0; i < json.layers.length; i++) { - var layer = new Phaser.TilemapLayer(this._game, this, key, Tilemap.FORMAT_TILED_JSON, json.layers[i].name, json.tilewidth, json.tileheight); - layer.alpha = json.layers[i].opacity; - layer.visible = json.layers[i].visible; - layer.tileMargin = json.tilesets[0].margin; - layer.tileSpacing = json.tilesets[0].spacing; - var c = 0; - var row; - for(var t = 0; t < json.layers[i].data.length; t++) { - if(c == 0) { - row = []; - } - row.push(json.layers[i].data[t]); - c++; - if(c == json.layers[i].width) { - layer.addColumn(row); - c = 0; - } - } - layer.updateBounds(); - var tileQuantity = layer.parseTileOffsets(); - this.currentLayer = layer; - this.collisionLayer = layer; - this.layers.push(layer); - } - this.generateTiles(tileQuantity); - }; - Tilemap.prototype.generateTiles = /** - * Create tiles of given quantity. - * @param qty {number} Quentity of tiles to be generated. - */ - function (qty) { - for(var i = 0; i < qty; i++) { - this.tiles.push(new Phaser.Tile(this._game, this, i, this.currentLayer.tileWidth, this.currentLayer.tileHeight)); - } - }; - Object.defineProperty(Tilemap.prototype, "widthInPixels", { - get: function () { - return this.currentLayer.widthInPixels; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Tilemap.prototype, "heightInPixels", { - get: function () { - return this.currentLayer.heightInPixels; - }, - enumerable: true, - configurable: true - }); - Tilemap.prototype.setCollisionCallback = // Tile Collision - /** - * Set callback to be called when this tilemap collides. - * @param context {object} Callback will be called with this context. - * @param callback {function} Callback function. - */ - function (context, callback) { - this.collisionCallbackContext = context; - this.collisionCallback = callback; - }; - Tilemap.prototype.setCollisionRange = /** - * Set collision configs of tiles in a range index. - * @param start {number} First index of tiles. - * @param end {number} Last index of tiles. - * @param collision {number} Bit field of flags. (see Tile.allowCollision) - * @param resetCollisions {boolean} Reset collision flags before set. - * @param separateX {boolean} Enable seprate at x-axis. - * @param separateY {boolean} Enable seprate at y-axis. - */ - function (start, end, collision, resetCollisions, separateX, separateY) { - if (typeof collision === "undefined") { collision = Phaser.Collision.ANY; } - if (typeof resetCollisions === "undefined") { resetCollisions = false; } - if (typeof separateX === "undefined") { separateX = true; } - if (typeof separateY === "undefined") { separateY = true; } - for(var i = start; i < end; i++) { - this.tiles[i].setCollision(collision, resetCollisions, separateX, separateY); - } - }; - Tilemap.prototype.setCollisionByIndex = /** - * Set collision configs of tiles with given index. - * @param values {number[]} Index array which contains all tile indexes. The tiles with those indexes will be setup with rest parameters. - * @param collision {number} Bit field of flags. (see Tile.allowCollision) - * @param resetCollisions {boolean} Reset collision flags before set. - * @param separateX {boolean} Enable seprate at x-axis. - * @param separateY {boolean} Enable seprate at y-axis. - */ - function (values, collision, resetCollisions, separateX, separateY) { - if (typeof collision === "undefined") { collision = Phaser.Collision.ANY; } - if (typeof resetCollisions === "undefined") { resetCollisions = false; } - if (typeof separateX === "undefined") { separateX = true; } - if (typeof separateY === "undefined") { separateY = true; } - for(var i = 0; i < values.length; i++) { - this.tiles[values[i]].setCollision(collision, resetCollisions, separateX, separateY); - } - }; - Tilemap.prototype.getTileByIndex = // Tile Management - /** - * Get the tile by its index. - * @param value {number} Index of the tile you want to get. - * @return {Tile} The tile with given index. - */ - function (value) { - if(this.tiles[value]) { - return this.tiles[value]; - } - return null; - }; - Tilemap.prototype.getTile = /** - * Get the tile located at specific position and layer. - * @param x {number} X position of this tile located. - * @param y {number} Y position of this tile located. - * @param [layer] {number} layer of this tile located. - * @return {Tile} The tile with specific properties. - */ - function (x, y, layer) { - if (typeof layer === "undefined") { layer = 0; } - return this.tiles[this.layers[layer].getTileIndex(x, y)]; - }; - Tilemap.prototype.getTileFromWorldXY = /** - * Get the tile located at specific position (in world coordinate) and layer. (thus you give a position of a point which is within the tile) - * @param x {number} X position of the point in target tile. - * @param x {number} Y position of the point in target tile. - * @param [layer] {number} layer of this tile located. - * @return {Tile} The tile with specific properties. - */ - function (x, y, layer) { - if (typeof layer === "undefined") { layer = 0; } - return this.tiles[this.layers[layer].getTileFromWorldXY(x, y)]; - }; - Tilemap.prototype.getTileFromInputXY = function (layer) { - if (typeof layer === "undefined") { layer = 0; } - return this.tiles[this.layers[layer].getTileFromWorldXY(this._game.input.getWorldX(), this._game.input.getWorldY())]; - }; - Tilemap.prototype.getTileOverlaps = /** - * Get tiles overlaps the given object. - * @param object {GameObject} Tiles you want to get that overlaps this. - * @return {array} Array with tiles informations. (Each contains x, y and the tile.) - */ - function (object) { - return this.currentLayer.getTileOverlaps(object); - }; - Tilemap.prototype.collide = // COLLIDE - /** - * Check whether this tilemap collides with the given game object or group of objects. - * @param objectOrGroup {function} Target object of group you want to check. - * @param callback {function} This is called if objectOrGroup collides the tilemap. - * @param context {object} Callback will be called with this context. - * @return {boolean} Return true if this collides with given object, otherwise return false. - */ - function (objectOrGroup, callback, context) { - if (typeof objectOrGroup === "undefined") { objectOrGroup = null; } - if (typeof callback === "undefined") { callback = null; } - if (typeof context === "undefined") { context = null; } - if(callback !== null && context !== null) { - this.collisionCallback = callback; - this.collisionCallbackContext = context; - } - if(objectOrGroup == null) { - objectOrGroup = this._game.world.group; - } - // Group? - if(objectOrGroup.isGroup == false) { - this.collideGameObject(objectOrGroup); - } else { - objectOrGroup.forEachAlive(this, this.collideGameObject, true); - } - }; - Tilemap.prototype.collideGameObject = /** - * Check whether this tilemap collides with the given game object. - * @param object {GameObject} Target object you want to check. - * @return {boolean} Return true if this collides with given object, otherwise return false. - */ - function (object) { - if(object !== this && object.immovable == false && object.exists == true && object.allowCollisions != Phaser.Collision.NONE) { - this._tempCollisionData = this.collisionLayer.getTileOverlaps(object); - if(this.collisionCallback !== null && this._tempCollisionData.length > 0) { - this.collisionCallback.call(this.collisionCallbackContext, object, this._tempCollisionData); - } - return true; - } else { - return false; - } - }; - Tilemap.prototype.putTile = /** - * Set a tile to a specific layer. - * @param x {number} X position of this tile. - * @param y {number} Y position of this tile. - * @param index {number} The index of this tile type in the core map data. - * @param [layer] {number} which layer you want to set the tile to. - */ - function (x, y, index, layer) { - if (typeof layer === "undefined") { layer = 0; } - this.layers[layer].putTile(x, y, index); - }; - return Tilemap; - })(Phaser.GameObject); - Phaser.Tilemap = Tilemap; - // Set current layer - // Set layer order? - // Delete tiles of certain type - // Erase tiles + Phaser.HeadlessRenderer = HeadlessRenderer; + // Add Tilemap, ScrollZone, etc? })(Phaser || (Phaser = {})); /// -/// -/** -* Phaser - ScrollRegion -* -* Creates a scrolling region within a ScrollZone. -* It is scrolled via the scrollSpeed.x/y properties. -*/ +/// +/// +/// var Phaser; (function (Phaser) { - var ScrollRegion = (function () { - /** - * ScrollRegion constructor - * Create a new ScrollRegion. - * - * @param x {number} X position in world coordinate. - * @param y {number} Y position in world coordinate. - * @param width {number} Width of this object. - * @param height {number} Height of this object. - * @param speedX {number} X-axis scrolling speed. - * @param speedY {number} Y-axis scrolling speed. - */ - function ScrollRegion(x, y, width, height, speedX, speedY) { - this._anchorWidth = 0; - this._anchorHeight = 0; - this._inverseWidth = 0; - this._inverseHeight = 0; - /** - * Will this region be rendered? (default to true) - * @type {boolean} - */ - this.visible = true; - // Our seamless scrolling quads - this._A = new Phaser.Quad(x, y, width, height); - this._B = new Phaser.Quad(x, y, width, height); - this._C = new Phaser.Quad(x, y, width, height); - this._D = new Phaser.Quad(x, y, width, height); - this._scroll = new Phaser.MicroPoint(); - this._bounds = new Phaser.Quad(x, y, width, height); - this.scrollSpeed = new Phaser.MicroPoint(speedX, speedY); - } - ScrollRegion.prototype.update = /** - * Update region scrolling with tick time. - * @param delta {number} Elapsed time since last update. - */ - function (delta) { - this._scroll.x += this.scrollSpeed.x; - this._scroll.y += this.scrollSpeed.y; - if(this._scroll.x > this._bounds.right) { - this._scroll.x = this._bounds.x; - } - if(this._scroll.x < this._bounds.x) { - this._scroll.x = this._bounds.right; - } - if(this._scroll.y > this._bounds.bottom) { - this._scroll.y = this._bounds.y; - } - if(this._scroll.y < this._bounds.y) { - this._scroll.y = this._bounds.bottom; - } - // Anchor Dimensions - this._anchorWidth = (this._bounds.width - this._scroll.x) + this._bounds.x; - this._anchorHeight = (this._bounds.height - this._scroll.y) + this._bounds.y; - if(this._anchorWidth > this._bounds.width) { - this._anchorWidth = this._bounds.width; - } - if(this._anchorHeight > this._bounds.height) { - this._anchorHeight = this._bounds.height; - } - this._inverseWidth = this._bounds.width - this._anchorWidth; - this._inverseHeight = this._bounds.height - this._anchorHeight; - // Quad A - this._A.setTo(this._scroll.x, this._scroll.y, this._anchorWidth, this._anchorHeight); - // Quad B - this._B.y = this._scroll.y; - this._B.width = this._inverseWidth; - this._B.height = this._anchorHeight; - // Quad C - this._C.x = this._scroll.x; - this._C.width = this._anchorWidth; - this._C.height = this._inverseHeight; - // Quad D - this._D.width = this._inverseWidth; - this._D.height = this._inverseHeight; - }; - ScrollRegion.prototype.render = /** - * Render this region to specific context. - * @param context {CanvasRenderingContext2D} Canvas context this region will be rendered to. - * @param texture {object} The texture to be rendered. - * @param dx {number} X position in world coordinate. - * @param dy {number} Y position in world coordinate. - * @param width {number} Width of this region to be rendered. - * @param height {number} Height of this region to be rendered. - */ - function (context, texture, dx, dy, dw, dh) { - if(this.visible == false) { - return; - } - // dx/dy are the world coordinates to render the FULL ScrollZone into. - // This ScrollRegion may be smaller than that and offset from the dx/dy coordinates. - this.crop(context, texture, this._A.x, this._A.y, this._A.width, this._A.height, dx, dy, dw, dh, 0, 0); - this.crop(context, texture, this._B.x, this._B.y, this._B.width, this._B.height, dx, dy, dw, dh, this._A.width, 0); - this.crop(context, texture, this._C.x, this._C.y, this._C.width, this._C.height, dx, dy, dw, dh, 0, this._A.height); - this.crop(context, texture, this._D.x, this._D.y, this._D.width, this._D.height, dx, dy, dw, dh, this._C.width, this._A.height); - //context.fillStyle = 'rgb(255,255,255)'; - //context.font = '18px Arial'; - //context.fillText('QuadA: ' + this._A.toString(), 32, 450); - //context.fillText('QuadB: ' + this._B.toString(), 32, 480); - //context.fillText('QuadC: ' + this._C.toString(), 32, 510); - //context.fillText('QuadD: ' + this._D.toString(), 32, 540); - }; - ScrollRegion.prototype.crop = /** - * Crop part of the texture and render it to the given context. - * @param context {CanvasRenderingContext2D} Canvas context the texture will be rendered to. - * @param texture {object} Texture to be rendered. - * @param srcX {number} Target region top-left x coordinate in the texture. - * @param srcX {number} Target region top-left y coordinate in the texture. - * @param srcW {number} Target region width in the texture. - * @param srcH {number} Target region height in the texture. - * @param destX {number} Render region top-left x coordinate in the context. - * @param destX {number} Render region top-left y coordinate in the context. - * @param destW {number} Target region width in the context. - * @param destH {number} Target region height in the context. - * @param offsetX {number} X offset to the context. - * @param offsetY {number} Y offset to the context. - */ - function (context, texture, srcX, srcY, srcW, srcH, destX, destY, destW, destH, offsetX, offsetY) { - offsetX += destX; - offsetY += destY; - if(srcW > (destX + destW) - offsetX) { - srcW = (destX + destW) - offsetX; - } - if(srcH > (destY + destH) - offsetY) { - srcH = (destY + destH) - offsetY; - } - srcX = Math.floor(srcX); - srcY = Math.floor(srcY); - srcW = Math.floor(srcW); - srcH = Math.floor(srcH); - offsetX = Math.floor(offsetX + this._bounds.x); - offsetY = Math.floor(offsetY + this._bounds.y); - if(srcW > 0 && srcH > 0) { - context.drawImage(texture, srcX, srcY, srcW, srcH, offsetX, offsetY, srcW, srcH); - } - }; - return ScrollRegion; - })(); - Phaser.ScrollRegion = ScrollRegion; -})(Phaser || (Phaser = {})); -/// -/// -/// -/** -* Phaser - ScrollZone -* -* Creates a scrolling region of the given width and height from an image in the cache. -* The ScrollZone can be positioned anywhere in-world like a normal game object, re-act to physics, collision, etc. -* The image within it is scrolled via ScrollRegions and their scrollSpeed.x/y properties. -* If you create a scroll zone larger than the given source image it will create a DynamicTexture and fill it with a pattern of the source image. -*/ -var Phaser; -(function (Phaser) { - var ScrollZone = (function (_super) { - __extends(ScrollZone, _super); - /** - * ScrollZone constructor - * Create a new ScrollZone. - * - * @param game {Phaser.Game} Current game instance. - * @param key {string} Asset key for image texture of this object. - * @param x {number} X position in world coordinate. - * @param y {number} Y position in world coordinate. - * @param [width] {number} width of this object. - * @param [height] {number} height of this object. - */ - function ScrollZone(game, key, x, y, width, height) { - if (typeof x === "undefined") { x = 0; } - if (typeof y === "undefined") { y = 0; } - if (typeof width === "undefined") { width = 0; } - if (typeof height === "undefined") { height = 0; } - _super.call(this, game, x, y, width, height); - /** - * If this zone is larger than texture image, this will be filled with a pattern of texture. - * @type {DynamicTexture} - */ - this._dynamicTexture = null; - /** - * Local rendering related temp vars to help avoid gc spikes. - * @type {number} - */ + var CanvasRenderer = (function () { + function CanvasRenderer(game) { + // local rendering related temp vars to help avoid gc spikes with var creation + this._sx = 0; + this._sy = 0; + this._sw = 0; + this._sh = 0; this._dx = 0; - /** - * Local rendering related temp vars to help avoid gc spikes. - * @type {number} - */ this._dy = 0; - /** - * Local rendering related temp vars to help avoid gc spikes. - * @type {number} - */ this._dw = 0; - /** - * Local rendering related temp vars to help avoid gc spikes. - * @type {number} - */ this._dh = 0; - /** - * Flip this zone vertically? (default to false) - * @type {boolean} - */ - this.flipped = false; - this.regions = []; - if(this._game.cache.getImage(key)) { - this._texture = this._game.cache.getImage(key); - this.width = this._texture.width; - this.height = this._texture.height; - if(width > this._texture.width || height > this._texture.height) { - // Create our repeating texture (as the source image wasn't large enough for the requested size) - this.createRepeatingTexture(width, height); - this.width = width; - this.height = height; - } - // Create a default ScrollRegion at the requested size - this.addRegion(0, 0, this.width, this.height); - // If the zone is smaller than the image itself then shrink the bounds - if((width < this._texture.width || height < this._texture.height) && width !== 0 && height !== 0) { - this.width = width; - this.height = height; - } - } + this._fx = 1; + this._fy = 1; + this._game = game; } - ScrollZone.prototype.addRegion = /** - * Add a new region to this zone. - * @param x {number} X position of the new region. - * @param y {number} Y position of the new region. - * @param width {number} Width of the new region. - * @param height {number} Height of the new region. - * @param [speedX] {number} x-axis scrolling speed. - * @param [speedY] {number} y-axis scrolling speed. - * @return {ScrollRegion} The newly added region. - */ - function (x, y, width, height, speedX, speedY) { - if (typeof speedX === "undefined") { speedX = 0; } - if (typeof speedY === "undefined") { speedY = 0; } - if(x > this.width || y > this.height || x < 0 || y < 0 || (x + width) > this.width || (y + height) > this.height) { - throw Error('Invalid ScrollRegion defined. Cannot be larger than parent ScrollZone'); - return; - } - this.currentRegion = new Phaser.ScrollRegion(x, y, width, height, speedX, speedY); - this.regions.push(this.currentRegion); - return this.currentRegion; - }; - ScrollZone.prototype.setSpeed = /** - * Set scrolling speed of current region. - * @param x {number} X speed of current region. - * @param y {number} Y speed of current region. - */ - function (x, y) { - if(this.currentRegion) { - this.currentRegion.scrollSpeed.setTo(x, y); - } - return this; - }; - ScrollZone.prototype.update = /** - * Update regions. - */ - function () { - for(var i = 0; i < this.regions.length; i++) { - this.regions[i].update(this._game.time.delta); + CanvasRenderer.prototype.render = function () { + // Get a list of all the active cameras + this._cameraList = this._game.world.getAllCameras(); + // Then iterate through world.group on them all (where not blacklisted, etc) + for(var c = 0; c < this._cameraList.length; c++) { + this._camera = this._cameraList[c]; + this._camera.preRender(); + this._game.world.group.render(this._camera); + this._camera.postRender(); } }; - ScrollZone.prototype.inCamera = /** - * Check whether this zone is visible in a specific camera rectangle. - * @param camera {Rectangle} The rectangle you want to check. - * @return {boolean} Return true if bound of this zone intersects the given rectangle, otherwise return false. + CanvasRenderer.prototype.renderSprite = /** + * Render this sprite to specific camera. Called by game loop after update(). + * @param camera {Camera} Camera this sprite will be rendered to. + * @return {boolean} Return false if not rendered, otherwise return true. */ - function (camera) { - if(this.scrollFactor.x !== 1.0 || this.scrollFactor.y !== 1.0) { - this._dx = this.frameBounds.x - (camera.x * this.scrollFactor.x); - this._dy = this.frameBounds.y - (camera.y * this.scrollFactor.x); - this._dw = this.frameBounds.width * this.scale.x; - this._dh = this.frameBounds.height * this.scale.y; - return (camera.right > this._dx) && (camera.x < this._dx + this._dw) && (camera.bottom > this._dy) && (camera.y < this._dy + this._dh); - } else { - return camera.intersects(this.frameBounds, this.frameBounds.length); - } - }; - ScrollZone.prototype.render = /** - * Render this zone object to a specific camera. - * @param camera {Camera} The camera this object will be render to. - * @param cameraOffsetX {number} X offset of camera. - * @param cameraOffsetY {number} Y offset of camera. - * @return Return false if not rendered, otherwise return true. - */ - function (camera, cameraOffsetX, cameraOffsetY) { - // Render checks - if(this.visible == false || this.scale.x == 0 || this.scale.y == 0 || this.alpha < 0.1 || this.cameraBlacklist.indexOf(camera.ID) !== -1 || this.inCamera(camera.worldView) == false) { + function (camera, sprite) { + // Render checks (needs inCamera check added) + if(sprite.scale.x == 0 || sprite.scale.y == 0 || sprite.texture.alpha < 0.1) { return false; } // Alpha - if(this.alpha !== 1) { - var globalAlpha = this.context.globalAlpha; - this.context.globalAlpha = this.alpha; + if(sprite.texture.alpha !== 1) { + var globalAlpha = sprite.texture.context.globalAlpha; + sprite.texture.context.globalAlpha = sprite.texture.alpha; } - this._dx = cameraOffsetX + (this.frameBounds.topLeft.x - camera.worldView.x); - this._dy = cameraOffsetY + (this.frameBounds.topLeft.y - camera.worldView.y); - this._dw = this.frameBounds.width * this.scale.x; - this._dh = this.frameBounds.height * this.scale.y; + this._fx = sprite.scale.x; + this._fy = sprite.scale.y; + this._sx = 0; + this._sy = 0; + this._sw = sprite.frameBounds.width; + this._sh = sprite.frameBounds.height; + //if (sprite.texture.flippedX) + //{ + // this._fx = -1; + //} + //if (sprite.texture.flippedY) + //{ + // this._fy = -1; + //} + this._dx = (camera.scaledX * sprite.scrollFactor.x) + sprite.frameBounds.x - (camera.worldView.x * sprite.scrollFactor.x); + this._dy = (camera.scaledY * sprite.scrollFactor.y) + sprite.frameBounds.y - (camera.worldView.y * sprite.scrollFactor.y); + //this._dw = sprite.frameBounds.width * sprite.scale.x; + //this._dh = sprite.frameBounds.height * sprite.scale.y; + this._dw = sprite.frameBounds.width; + this._dh = sprite.frameBounds.height; + /* + if (this._dynamicTexture == false && this.animations.currentFrame !== null) + { + this._sx = this.animations.currentFrame.x; + this._sy = this.animations.currentFrame.y; + + if (this.animations.currentFrame.trimmed) + { + this._dx += this.animations.currentFrame.spriteSourceSizeX; + this._dy += this.animations.currentFrame.spriteSourceSizeY; + } + } + */ // Apply camera difference - if(this.scrollFactor.x !== 1.0 || this.scrollFactor.y !== 1.0) { - this._dx -= (camera.worldView.x * this.scrollFactor.x); - this._dy -= (camera.worldView.y * this.scrollFactor.y); - } - // Rotation - needs to work from origin point really, but for now from center - if(this.angle !== 0 || this.flipped == true) { - this.context.save(); - this.context.translate(this._dx + (this._dw / 2), this._dy + (this._dh / 2)); - if(this.angle !== 0) { - this.context.rotate(this.angle * (Math.PI / 180)); + if(sprite.scrollFactor.x !== 1 || sprite.scrollFactor.y !== 1) { + //this._dx -= (camera.worldView.x * this.scrollFactor.x); + //this._dy -= (camera.worldView.y * this.scrollFactor.y); + } + // Apply origin / alignment + if(sprite.origin.x != 0 || sprite.origin.y != 0) { + //this._dx += (sprite.origin.x * sprite.scale.x); + //this._dy += (sprite.origin.y * sprite.scale.y); + } + // Rotation and Flipped + if(sprite.scale.x != 1 || sprite.scale.y != 1 || sprite.position.rotation != 0 || sprite.position.rotationOffset != 0 || sprite.texture.flippedX || sprite.texture.flippedY)//if (sprite.position.rotation != 0 || sprite.position.rotationOffset != 0 || sprite.texture.flippedX || sprite.texture.flippedY) + { + sprite.texture.context.save(); + if(sprite.texture.flippedX) { + this._dx += this._dw * sprite.scale.x; } - this._dx = -(this._dw / 2); - this._dy = -(this._dh / 2); - if(this.flipped == true) { - this.context.scale(-1, 1); + if(sprite.texture.flippedY) { + this._dy += this._dh * sprite.scale.y; } + sprite.texture.context.translate(this._dx, this._dy); + //sprite.texture.context.translate(this._dx + (this._dw / 2), this._dy + (this._dh / 2)); + //sprite.texture.context.translate(this._dx + (sprite.origin.x * sprite.scale.x), this._dy + (sprite.origin.y * sprite.scale.y)); + //sprite.texture.context.translate(this._dx + sprite.origin.x, this._dy + sprite.origin.y); + //sprite.texture.context.translate(this._dx + sprite.origin.x - (this._dw / 2), this._dy + sprite.origin.y - (this._dh / 2)); + if(sprite.texture.renderRotation == true && (sprite.position.rotation !== 0 || sprite.position.rotationOffset !== 0)) { + // Apply point of rotation here + sprite.texture.context.rotate((sprite.position.rotationOffset + sprite.position.rotation) * (Math.PI / 180)); + } + if(sprite.scale.x != 1 || sprite.scale.y != 1 || sprite.texture.flippedX || sprite.texture.flippedY) { + if(sprite.texture.flippedX) { + this._fx = -sprite.scale.x; + } + if(sprite.texture.flippedY) { + this._fy = -sprite.scale.y; + } + sprite.texture.context.scale(this._fx, this._fy); + } + //if (sprite.texture.flippedX || sprite.texture.flippedY) + //{ + // sprite.texture.context.scale(this._fx, this._fy); + //} + this._dx = -(sprite.origin.x * sprite.scale.x); + this._dy = -(sprite.origin.y * sprite.scale.y); + //this._dx = -(sprite.origin.x * sprite.scale.x); + //this._dy = -(sprite.origin.y * sprite.scale.y); + //this._dx = -(this._dw / 2) * sprite.scale.x; + //this._dy = -(this._dh / 2) * sprite.scale.y; + //this._dx = 0; + //this._dy = 0; + } else { + if(sprite.origin.x != 0 || sprite.origin.y != 0) { + //this._dx -= (sprite.origin.x * sprite.scale.x); + //this._dy -= (sprite.origin.y * sprite.scale.y); + } } + this._sx = Math.round(this._sx); + this._sy = Math.round(this._sy); + this._sw = Math.round(this._sw); + this._sh = Math.round(this._sh); this._dx = Math.round(this._dx); this._dy = Math.round(this._dy); this._dw = Math.round(this._dw); this._dh = Math.round(this._dh); - for(var i = 0; i < this.regions.length; i++) { - if(this._dynamicTexture) { - this.regions[i].render(this.context, this._dynamicTexture.canvas, this._dx, this._dy, this._dw, this._dh); - } else { - this.regions[i].render(this.context, this._texture, this._dx, this._dy, this._dw, this._dh); - } + //if (this._texture != null) + //{ + sprite.texture.context.drawImage(sprite.texture.texture, // Source Image + this._sx, // Source X (location within the source image) + this._sy, // Source Y + this._sw, // Source Width + this._sh, // Source Height + this._dx, // Destination X (where on the canvas it'll be drawn) + this._dy, // Destination Y + this._dw, // Destination Width (always same as Source Width unless scaled) + this._dh); + // Destination Height (always same as Source Height unless scaled) + //} + //else + //{ + // this.context.fillStyle = this.fillColor; + // this.context.fillRect(this._dx, this._dy, this._dw, this._dh); + //} + if(sprite.scale.x != 1 || sprite.scale.y != 1 || sprite.position.rotation != 0 || sprite.position.rotationOffset != 0 || sprite.texture.flippedX || sprite.texture.flippedY)//if (sprite.position.rotation != 0 || sprite.position.rotationOffset != 0 || sprite.texture.flippedX || sprite.texture.flippedY) + { + //this.context.translate(0, 0); + sprite.texture.context.restore(); } + //if (this.renderDebug) + //{ + // this.renderBounds(camera, cameraOffsetX, cameraOffsetY); + //this.collisionMask.render(camera, cameraOffsetX, cameraOffsetY); + //} if(globalAlpha > -1) { - this.context.globalAlpha = globalAlpha; + sprite.texture.context.globalAlpha = globalAlpha; } return true; }; - ScrollZone.prototype.createRepeatingTexture = /** - * Create repeating texture with _texture, and store it into the _dynamicTexture. - * Used to create texture when texture image is small than size of the zone. - */ - function (regionWidth, regionHeight) { - // Work out how many we'll need of the source image to make it tile properly - var tileWidth = Math.ceil(this._texture.width / regionWidth) * regionWidth; - var tileHeight = Math.ceil(this._texture.height / regionHeight) * regionHeight; - this._dynamicTexture = new Phaser.DynamicTexture(this._game, tileWidth, tileHeight); - this._dynamicTexture.context.rect(0, 0, tileWidth, tileHeight); - this._dynamicTexture.context.fillStyle = this._dynamicTexture.context.createPattern(this._texture, "repeat"); - this._dynamicTexture.context.fill(); - }; - return ScrollZone; - })(Phaser.GameObject); - Phaser.ScrollZone = ScrollZone; + return CanvasRenderer; + })(); + Phaser.CanvasRenderer = CanvasRenderer; })(Phaser || (Phaser = {})); -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// /// /// -/// -/// +/// /// -/// /// -/// /// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// +/// +/// +/// +/// /** * Phaser - Game * @@ -16959,14 +10707,14 @@ var Phaser; }, 13); } else { this.device = new Phaser.Device(); - this.motion = new Phaser.Motion(this); + //this.motion = new Motion(this); this.math = new Phaser.GameMath(this); this.stage = new Phaser.Stage(this, parent, width, height); this.world = new Phaser.World(this, width, height); this.add = new Phaser.GameObjectFactory(this); this.sound = new Phaser.SoundManager(this); this.cache = new Phaser.Cache(this); - this.collision = new Phaser.Collision(this); + //this.collision = new Collision(this); this.loader = new Phaser.Loader(this, this.loadComplete); this.time = new Phaser.Time(this); this.tweens = new Phaser.TweenManager(this); @@ -16974,7 +10722,7 @@ var Phaser; this.rnd = new Phaser.RandomDataGenerator([ (Date.now() * Math.random()).toString() ]); - this.verlet = new Phaser.Verlet.VerletManager(this, width, height); + this.setRenderer(Phaser.Types.RENDERER_CANVAS); this.framerate = 60; this.isBooted = true; this.input.start(); @@ -16993,6 +10741,18 @@ var Phaser; } } }; + Game.prototype.setRenderer = function (type) { + switch(type) { + case Phaser.Types.RENDERER_AUTO_DETECT: + this.renderer = new Phaser.HeadlessRenderer(this); + break; + case Phaser.Types.RENDERER_AUTO_DETECT: + case Phaser.Types.RENDERER_CANVAS: + this.renderer = new Phaser.CanvasRenderer(this); + break; + // WebGL coming soon :) + } + }; Game.prototype.loadComplete = /** * Called when the loader has finished after init was run. */ @@ -17025,7 +10785,6 @@ var Phaser; this.tweens.update(); this.input.update(); this.stage.update(); - this.verlet.update(); this._accumulator += this.time.delta; if(this._accumulator > this._maxAccumulation) { this._accumulator = this._maxAccumulation; @@ -17038,7 +10797,7 @@ var Phaser; if(this._loadComplete && this.onUpdateCallback) { this.onUpdateCallback.call(this.callbackContext); } - this.world.render(); + this.renderer.render(); if(this._loadComplete && this.onRenderCallback) { this.onRenderCallback.call(this.callbackContext); } @@ -17202,25 +10961,21 @@ var Phaser; enumerable: true, configurable: true }); - Game.prototype.collide = /** - * Checks for overlaps between two objects using the world QuadTree. Can be GameObject vs. GameObject, GameObject vs. Group or Group vs. Group. - * Note: Does not take the objects scrollFactor into account. All overlaps are check in world space. - * @param object1 The first GameObject or Group to check. If null the world.group is used. - * @param object2 The second GameObject or Group to check. - * @param notifyCallback A callback function that is called if the objects overlap. The two objects will be passed to this function in the same order in which you passed them to Collision.overlap. - * @param processCallback A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then notifyCallback will only be called if processCallback returns true. - * @param context The context in which the callbacks will be called - * @returns {boolean} true if the objects overlap, otherwise false. - */ - function (objectOrGroup1, objectOrGroup2, notifyCallback, context) { - if (typeof objectOrGroup1 === "undefined") { objectOrGroup1 = null; } - if (typeof objectOrGroup2 === "undefined") { objectOrGroup2 = null; } - if (typeof notifyCallback === "undefined") { notifyCallback = null; } - if (typeof context === "undefined") { context = this.callbackContext; } - return this.collision.overlap(objectOrGroup1, objectOrGroup2, notifyCallback, Phaser.Collision.separate, context); - }; Object.defineProperty(Game.prototype, "camera", { - get: function () { + get: /** + * Checks for overlaps between two objects using the world QuadTree. Can be GameObject vs. GameObject, GameObject vs. Group or Group vs. Group. + * Note: Does not take the objects scrollFactor into account. All overlaps are check in world space. + * @param object1 The first GameObject or Group to check. If null the world.group is used. + * @param object2 The second GameObject or Group to check. + * @param notifyCallback A callback function that is called if the objects overlap. The two objects will be passed to this function in the same order in which you passed them to Collision.overlap. + * @param processCallback A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then notifyCallback will only be called if processCallback returns true. + * @param context The context in which the callbacks will be called + * @returns {boolean} true if the objects overlap, otherwise false. + */ + //public collide(objectOrGroup1 = null, objectOrGroup2 = null, notifyCallback = null, context? = this.callbackContext): bool { + // return this.collision.overlap(objectOrGroup1, objectOrGroup2, notifyCallback, Collision.separate, context); + //} + function () { return this.world.cameras.current; }, enumerable: true, @@ -17230,155 +10985,1172 @@ var Phaser; })(); Phaser.Game = Game; })(Phaser || (Phaser = {})); -/// +/// /** -* Phaser - FXManager +* Phaser - Point * -* The FXManager controls all special effects applied to game objects such as Cameras. +* The Point object represents a location in a two-dimensional coordinate system, where x represents the horizontal axis and y represents the vertical axis. */ var Phaser; (function (Phaser) { - var FXManager = (function () { - function FXManager(game, parent) { - this._game = game; - this._parent = parent; - this._fx = []; - this.active = true; - this.visible = true; + var Point = (function () { + /** + * Creates a new Point. If you pass no parameters a Point is created set to (0,0). + * @class Point + * @constructor + * @param {Number} x The horizontal position of this Point (default 0) + * @param {Number} y The vertical position of this Point (default 0) + **/ + function Point(x, y) { + if (typeof x === "undefined") { x = 0; } + if (typeof y === "undefined") { y = 0; } + this.x = x; + this.y = y; } - FXManager.prototype.add = /** - * Adds a new FX to the FXManager. - * The effect must be an object with at least one of the following methods: preUpdate, postUpdate, preRender, render or postRender. - * A new instance of the effect will be created and a reference to Game will be passed to the object constructor. - * @param {object} effect - * @return {any} - */ - function (effect) { - var result = false; - var newEffect = { - effect: { - }, - preUpdate: false, - postUpdate: false, - preRender: false, - render: false, - postRender: false - }; - if(typeof effect === 'function') { - newEffect.effect = new effect(this._game, this._parent); - } else { - throw new Error("Invalid object given to Phaser.FXManager.add"); - } - // Check for methods now to avoid having to do this every loop - if(typeof newEffect.effect['preUpdate'] === 'function') { - newEffect.preUpdate = true; - result = true; - } - if(typeof newEffect.effect['postUpdate'] === 'function') { - newEffect.postUpdate = true; - result = true; - } - if(typeof newEffect.effect['preRender'] === 'function') { - newEffect.preRender = true; - result = true; - } - if(typeof newEffect.effect['render'] === 'function') { - newEffect.render = true; - result = true; - } - if(typeof newEffect.effect['postRender'] === 'function') { - newEffect.postRender = true; - result = true; - } - if(result == true) { - this._length = this._fx.push(newEffect); - return newEffect.effect; - } else { - return result; - } + Point.prototype.copyFrom = /** + * Copies the x and y properties from any given object to this Point. + * @method copyFrom + * @param {any} source - The object to copy from. + * @return {Point} This Point object. + **/ + function (source) { + return this.setTo(source.x, source.y); }; - FXManager.prototype.preUpdate = /** - * Pre-update is called at the start of the objects update cycle, before any other updates have taken place. - */ + Point.prototype.invert = /** + * Inverts the x and y values of this Point + * @method invert + * @return {Point} This Point object. + **/ function () { - if(this.active) { - for(var i = 0; i < this._length; i++) { - if(this._fx[i].preUpdate) { - this._fx[i].effect.preUpdate(); - } - } - } + return this.setTo(this.y, this.x); }; - FXManager.prototype.postUpdate = /** - * Post-update is called at the end of the objects update cycle, after other update logic has taken place. - */ + Point.prototype.setTo = /** + * Sets the x and y values of this MicroPoint object to the given coordinates. + * @method setTo + * @param {Number} x - The horizontal position of this point. + * @param {Number} y - The vertical position of this point. + * @return {MicroPoint} This MicroPoint object. Useful for chaining method calls. + **/ + function (x, y) { + this.x = x; + this.y = y; + return this; + }; + Point.prototype.toString = /** + * Returns a string representation of this object. + * @method toString + * @return {string} a string representation of the instance. + **/ function () { - if(this.active) { - for(var i = 0; i < this._length; i++) { - if(this._fx[i].postUpdate) { - this._fx[i].effect.postUpdate(); - } - } - } + return '[{Point (x=' + this.x + ' y=' + this.y + ')}]'; }; - FXManager.prototype.preRender = /** - * Pre-render is called at the start of the object render cycle, before any transforms have taken place. - * It happens directly AFTER a canvas context.save has happened if added to a Camera. - * @param {Camera} camera - * @param {number} cameraX - * @param {number} cameraY - * @param {number} cameraWidth - * @param {number} cameraHeight - */ - function (camera, cameraX, cameraY, cameraWidth, cameraHeight) { - if(this.visible) { - for(var i = 0; i < this._length; i++) { - if(this._fx[i].preRender) { - this._fx[i].effect.preRender(camera, cameraX, cameraY, cameraWidth, cameraHeight); - } - } - } - }; - FXManager.prototype.render = /** - * render is called during the objects render cycle, right after all transforms have finished, but before any children/image data is rendered. - * @param {Camera} camera - * @param {number} cameraX - * @param {number} cameraY - * @param {number} cameraWidth - * @param {number} cameraHeight - */ - function (camera, cameraX, cameraY, cameraWidth, cameraHeight) { - if(this.visible) { - for(var i = 0; i < this._length; i++) { - if(this._fx[i].preRender) { - this._fx[i].effect.preRender(camera, cameraX, cameraY, cameraWidth, cameraHeight); - } - } - } - }; - FXManager.prototype.postRender = /** - * Post-render is called during the objects render cycle, after the children/image data has been rendered. - * It happens directly BEFORE a canvas context.restore has happened if added to a Camera. - */ - function (camera, cameraX, cameraY, cameraWidth, cameraHeight) { - if(this.visible) { - for(var i = 0; i < this._length; i++) { - if(this._fx[i].postRender) { - this._fx[i].effect.postRender(camera, cameraX, cameraY, cameraWidth, cameraHeight); - } - } - } - }; - FXManager.prototype.destroy = /** - * Clear down this FXManager and null out references - */ - function () { - this._game = null; - this._fx = null; - }; - return FXManager; + return Point; })(); - Phaser.FXManager = FXManager; + Phaser.Point = Point; +})(Phaser || (Phaser = {})); +/// +/** +* Rectangle +* +* @desc A Rectangle object is an area defined by its position, as indicated by its top-left corner (x,y) and width and height. +* +* @version 1.6 - 24th May 2013 +* @author Richard Davey +*/ +var Phaser; +(function (Phaser) { + var Rectangle = (function () { + /** + * Creates a new Rectangle object with the top-left corner specified by the x and y parameters and with the specified width and height parameters. If you call this function without parameters, a rectangle with x, y, width, and height properties set to 0 is created. + * @class Rectangle + * @constructor + * @param {Number} x The x coordinate of the top-left corner of the rectangle. + * @param {Number} y The y coordinate of the top-left corner of the rectangle. + * @param {Number} width The width of the rectangle in pixels. + * @param {Number} height The height of the rectangle in pixels. + * @return {Rectangle} This rectangle object + **/ + function Rectangle(x, y, width, height) { + if (typeof x === "undefined") { x = 0; } + if (typeof y === "undefined") { y = 0; } + if (typeof width === "undefined") { width = 0; } + if (typeof height === "undefined") { height = 0; } + this.x = x; + this.y = y; + this.width = width; + this.height = height; + } + Object.defineProperty(Rectangle.prototype, "halfWidth", { + get: /** + * Half of the width of the rectangle + * @property halfWidth + * @type Number + **/ + function () { + return Math.round(this.width / 2); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Rectangle.prototype, "halfHeight", { + get: /** + * Half of the height of the rectangle + * @property halfHeight + * @type Number + **/ + function () { + return Math.round(this.height / 2); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Rectangle.prototype, "bottom", { + get: /** + * 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 + * @return {Number} + **/ + function () { + return this.y + this.height; + }, + set: /** + * 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 + **/ + function (value) { + if(value <= this.y) { + this.height = 0; + } else { + this.height = (this.y - value); + } + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Rectangle.prototype, "bottomRight", { + set: /** + * Sets the bottom-right corner of the Rectangle, determined by the values of the given Point object. + * @method bottomRight + * @param {Point} value + **/ + function (value) { + this.right = value.x; + this.bottom = value.y; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Rectangle.prototype, "left", { + get: /** + * The x coordinate of the left of the Rectangle. Changing the left property of a Rectangle object has no effect on the y and height properties. However it does affect the width property, whereas changing the x value does not affect the width property. + * @method left + * @ return {number} + **/ + function () { + return this.x; + }, + set: /** + * The x coordinate of the left of the Rectangle. Changing the left property of a Rectangle object has no effect on the y and height properties. + * However it does affect the width, whereas changing the x value does not affect the width property. + * @method left + * @param {Number} value + **/ + function (value) { + if(value >= this.right) { + this.width = 0; + } else { + this.width = this.right - value; + } + this.x = value; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Rectangle.prototype, "right", { + get: /** + * The sum of the x and width properties. Changing the right property of a Rectangle object has no effect on the x, y and height properties. + * However it does affect the width property. + * @method right + * @return {Number} + **/ + function () { + return this.x + this.width; + }, + set: /** + * The sum of the x and width properties. Changing the right property of a Rectangle object has no effect on the x, y and height properties. + * However it does affect the width property. + * @method right + * @param {Number} value + **/ + function (value) { + if(value <= this.x) { + this.width = 0; + } else { + this.width = this.x + value; + } + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Rectangle.prototype, "volume", { + get: /** + * The volume of the Rectangle derived from width * height + * @method volume + * @return {Number} + **/ + function () { + return this.width * this.height; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Rectangle.prototype, "perimeter", { + get: /** + * The perimeter size of the Rectangle. This is the sum of all 4 sides. + * @method perimeter + * @return {Number} + **/ + function () { + return (this.width * 2) + (this.height * 2); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Rectangle.prototype, "top", { + get: /** + * The y coordinate of the top of the Rectangle. Changing the top property of a Rectangle object has no effect on the x and width properties. + * However it does affect the height property, whereas changing the y value does not affect the height property. + * @method top + * @return {Number} + **/ + function () { + return this.y; + }, + set: /** + * The y coordinate of the top of the Rectangle. Changing the top property of a Rectangle object has no effect on the x and width properties. + * However it does affect the height property, whereas changing the y value does not affect the height property. + * @method top + * @param {Number} value + **/ + function (value) { + if(value >= this.bottom) { + this.height = 0; + this.y = value; + } else { + this.height = (this.bottom - value); + } + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Rectangle.prototype, "topLeft", { + set: /** + * The location of the Rectangles top-left corner, determined by the x and y coordinates of the Point. + * @method topLeft + * @param {Point} value + **/ + function (value) { + this.x = value.x; + this.y = value.y; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Rectangle.prototype, "empty", { + get: /** + * Determines whether or not this Rectangle object is empty. + * @method isEmpty + * @return {Boolean} A value of true if the Rectangle object's width or height is less than or equal to 0; otherwise false. + **/ + function () { + return (!this.width || !this.height); + }, + set: /** + * Sets all of the Rectangle object's properties to 0. A Rectangle object is empty if its width or height is less than or equal to 0. + * @method setEmpty + * @return {Rectangle} This rectangle object + **/ + function (value) { + return this.setTo(0, 0, 0, 0); + }, + enumerable: true, + configurable: true + }); + Rectangle.prototype.offset = /** + * Adjusts the location of the Rectangle object, as determined by its top-left corner, by the specified amounts. + * @method offset + * @param {Number} dx Moves the x value of the Rectangle object by this amount. + * @param {Number} dy Moves the y value of the Rectangle object by this amount. + * @return {Rectangle} This Rectangle object. + **/ + function (dx, dy) { + this.x += dx; + this.y += dy; + return this; + }; + Rectangle.prototype.offsetPoint = /** + * Adjusts the location of the Rectangle object using a Point object as a parameter. This method is similar to the Rectangle.offset() method, except that it takes a Point object as a parameter. + * @method offsetPoint + * @param {Point} point A Point object to use to offset this Rectangle object. + * @return {Rectangle} This Rectangle object. + **/ + function (point) { + return this.offset(point.x, point.y); + }; + Rectangle.prototype.setTo = /** + * Sets the members of Rectangle to the specified values. + * @method setTo + * @param {Number} x The x coordinate of the top-left corner of the rectangle. + * @param {Number} y The y coordinate of the top-left corner of the rectangle. + * @param {Number} width The width of the rectangle in pixels. + * @param {Number} height The height of the rectangle in pixels. + * @return {Rectangle} This rectangle object + **/ + function (x, y, width, height) { + this.x = x; + this.y = y; + this.width = width; + this.height = height; + return this; + }; + Rectangle.prototype.copyFrom = /** + * Copies the x, y, width and height properties from any given object to this Rectangle. + * @method copyFrom + * @param {any} source - The object to copy from. + * @return {Rectangle} This Rectangle object. + **/ + function (source) { + return this.setTo(source.x, source.y, source.width, source.height); + }; + Rectangle.prototype.toString = /** + * Returns a string representation of this object. + * @method toString + * @return {string} a string representation of the instance. + **/ + function () { + return "[{Rectangle (x=" + this.x + " y=" + this.y + " width=" + this.width + " height=" + this.height + " empty=" + this.empty + ")}]"; + }; + return Rectangle; + })(); + Phaser.Rectangle = Rectangle; +})(Phaser || (Phaser = {})); +/// +/// +/// +/// +/** +* Phaser - CircleUtils +* +* A collection of methods useful for manipulating and comparing Circle objects. +* +* TODO: +*/ +var Phaser; +(function (Phaser) { + var CircleUtils = (function () { + function CircleUtils() { } + CircleUtils.clone = /** + * Returns a new Circle object with the same values for the x, y, width, and height properties as the original Circle object. + * @method clone + * @param {Circle} a - The Circle object. + * @param {Circle} [optional] out Optional Circle object. If given the values will be set into the object, otherwise a brand new Circle object will be created and returned. + * @return {Phaser.Circle} + **/ + function clone(a, out) { + if (typeof out === "undefined") { out = new Phaser.Circle(); } + return out.setTo(a.x, a.y, a.diameter); + }; + CircleUtils.contains = /** + * Return true if the given x/y coordinates are within the Circle object. + * If you need details about the intersection then use Phaser.Intersect.circleContainsPoint instead. + * @method contains + * @param {Circle} a - The Circle object. + * @param {Number} The X value of the coordinate to test. + * @param {Number} The Y value of the coordinate to test. + * @return {Boolean} True if the coordinates are within this circle, otherwise false. + **/ + function contains(a, x, y) { + //return (a.radius * a.radius >= Collision.distanceSquared(a.x, a.y, x, y)); + return true; + }; + CircleUtils.containsPoint = /** + * Return true if the coordinates of the given Point object are within this Circle object. + * If you need details about the intersection then use Phaser.Intersect.circleContainsPoint instead. + * @method containsPoint + * @param {Circle} a - The Circle object. + * @param {Point} The Point object to test. + * @return {Boolean} True if the coordinates are within this circle, otherwise false. + **/ + function containsPoint(a, point) { + return CircleUtils.contains(a, point.x, point.y); + }; + CircleUtils.containsCircle = /** + * Return true if the given Circle is contained entirely within this Circle object. + * If you need details about the intersection then use Phaser.Intersect.circleToCircle instead. + * @method containsCircle + * @param {Circle} The Circle object to test. + * @return {Boolean} True if the coordinates are within this circle, otherwise false. + **/ + function containsCircle(a, b) { + //return ((a.radius + b.radius) * (a.radius + b.radius)) >= Collision.distanceSquared(a.x, a.y, b.x, b.y); + return true; + }; + CircleUtils.distanceBetween = /** + * Returns the distance from the center of the Circle object to the given object (can be Circle, Point or anything with x/y properties) + * @method distanceBetween + * @param {Circle} a - The Circle object. + * @param {Circle} b - The target object. Must have visible x and y properties that represent the center of the object. + * @param {Boolean} [optional] round - Round the distance to the nearest integer (default false) + * @return {Number} The distance between this Point object and the destination Point object. + **/ + function distanceBetween(a, target, round) { + if (typeof round === "undefined") { round = false; } + var dx = a.x - target.x; + var dy = a.y - target.y; + if(round === true) { + return Math.round(Math.sqrt(dx * dx + dy * dy)); + } else { + return Math.sqrt(dx * dx + dy * dy); + } + }; + CircleUtils.equals = /** + * Determines whether the two Circle objects match. This method compares the x, y and diameter properties. + * @method equals + * @param {Circle} a - The first Circle object. + * @param {Circle} b - The second Circle object. + * @return {Boolean} A value of true if the object has exactly the same values for the x, y and diameter properties as this Circle object; otherwise false. + **/ + function equals(a, b) { + return (a.x == b.x && a.y == b.y && a.diameter == b.diameter); + }; + CircleUtils.intersects = /** + * Determines whether the two Circle objects intersect. + * This method checks the radius distances between the two Circle objects to see if they intersect. + * @method intersects + * @param {Circle} a - The first Circle object. + * @param {Circle} b - The second Circle object. + * @return {Boolean} A value of true if the specified object intersects with this Circle object; otherwise false. + **/ + function intersects(a, b) { + return (CircleUtils.distanceBetween(a, b) <= (a.radius + b.radius)); + }; + CircleUtils.circumferencePoint = /** + * Returns a Point object containing the coordinates of a point on the circumference of the Circle based on the given angle. + * @method circumferencePoint + * @param {Circle} a - The first Circle object. + * @param {Number} angle The angle in radians (unless asDegrees is true) to return the point from. + * @param {Boolean} asDegrees Is the given angle in radians (false) or degrees (true)? + * @param {Phaser.Point} [optional] output An optional Point object to put the result in to. If none specified a new Point object will be created. + * @return {Phaser.Point} The Point object holding the result. + **/ + function circumferencePoint(a, angle, asDegrees, out) { + if (typeof asDegrees === "undefined") { asDegrees = false; } + if (typeof out === "undefined") { out = new Phaser.Point(); } + if(asDegrees === true) { + angle = angle * Phaser.GameMath.DEG_TO_RAD; + } + return out.setTo(a.x + a.radius * Math.cos(angle), a.y + a.radius * Math.sin(angle)); + }; + return CircleUtils; + })(); + Phaser.CircleUtils = CircleUtils; +})(Phaser || (Phaser = {})); +/// +/// +/** +* Phaser - LinkedList +* +* A miniature linked list class. Useful for optimizing time-critical or highly repetitive tasks! +*/ +var Phaser; +(function (Phaser) { + var LinkedList = (function () { + /** + * Creates a new link, and sets object and next to null. + */ + function LinkedList() { + this.object = null; + this.next = null; + } + LinkedList.prototype.destroy = /** + * Clean up memory. + */ + function () { + this.object = null; + if(this.next != null) { + this.next.destroy(); + } + this.next = null; + }; + return LinkedList; + })(); + Phaser.LinkedList = LinkedList; +})(Phaser || (Phaser = {})); +var __extends = this.__extends || function (d, b) { + function __() { this.constructor = d; } + __.prototype = b.prototype; + d.prototype = new __(); +}; +/// +/// +/// +/** +* Phaser - QuadTree +* +* A fairly generic quad tree structure for rapid overlap checks. QuadTree is also configured for single or dual list operation. +* You can add items either to its A list or its B list. When you do an overlap check, you can compare the A list to itself, +* or the A list against the B list. Handy for different things! +*/ +var Phaser; +(function (Phaser) { + var QuadTree = (function (_super) { + __extends(QuadTree, _super); + /** + * Instantiate a new Quad Tree node. + * + * @param {Number} x The X-coordinate of the point in space. + * @param {Number} y The Y-coordinate of the point in space. + * @param {Number} width Desired width of this node. + * @param {Number} height Desired height of this node. + * @param {Number} parent The parent branch or node. Pass null to create a root. + */ + function QuadTree(x, y, width, height, parent) { + if (typeof parent === "undefined") { parent = null; } + _super.call(this, x, y, width, height); + this._headA = this._tailA = new Phaser.LinkedList(); + this._headB = this._tailB = new Phaser.LinkedList(); + //Copy the parent's children (if there are any) + if(parent != null) { + if(parent._headA.object != null) { + this._iterator = parent._headA; + while(this._iterator != null) { + if(this._tailA.object != null) { + this._ot = this._tailA; + this._tailA = new Phaser.LinkedList(); + this._ot.next = this._tailA; + } + this._tailA.object = this._iterator.object; + this._iterator = this._iterator.next; + } + } + if(parent._headB.object != null) { + this._iterator = parent._headB; + while(this._iterator != null) { + if(this._tailB.object != null) { + this._ot = this._tailB; + this._tailB = new Phaser.LinkedList(); + this._ot.next = this._tailB; + } + this._tailB.object = this._iterator.object; + this._iterator = this._iterator.next; + } + } + } else { + QuadTree._min = (this.width + this.height) / (2 * QuadTree.divisions); + } + this._canSubdivide = (this.width > QuadTree._min) || (this.height > QuadTree._min); + //Set up comparison/sort helpers + this._northWestTree = null; + this._northEastTree = null; + this._southEastTree = null; + this._southWestTree = null; + this._leftEdge = this.x; + this._rightEdge = this.x + this.width; + this._halfWidth = this.width / 2; + this._midpointX = this._leftEdge + this._halfWidth; + this._topEdge = this.y; + this._bottomEdge = this.y + this.height; + this._halfHeight = this.height / 2; + this._midpointY = this._topEdge + this._halfHeight; + } + QuadTree.A_LIST = 0; + QuadTree.B_LIST = 1; + QuadTree.prototype.destroy = /** + * Clean up memory. + */ + function () { + this._tailA.destroy(); + this._tailB.destroy(); + this._headA.destroy(); + this._headB.destroy(); + this._tailA = null; + this._tailB = null; + this._headA = null; + this._headB = null; + if(this._northWestTree != null) { + this._northWestTree.destroy(); + } + if(this._northEastTree != null) { + this._northEastTree.destroy(); + } + if(this._southEastTree != null) { + this._southEastTree.destroy(); + } + if(this._southWestTree != null) { + this._southWestTree.destroy(); + } + this._northWestTree = null; + this._northEastTree = null; + this._southEastTree = null; + this._southWestTree = null; + QuadTree._object = null; + QuadTree._processingCallback = null; + QuadTree._notifyCallback = null; + }; + QuadTree.prototype.load = /** + * Load objects and/or groups into the quad tree, and register notify and processing callbacks. + * + * @param {} objectOrGroup1 Any object that is or extends IGameObject or Group. + * @param {} objectOrGroup2 Any object that is or extends IGameObject or Group. If null, the first parameter will be checked against itself. + * @param {Function} notifyCallback A function with the form myFunction(Object1:GameObject,Object2:GameObject) that is called whenever two objects are found to overlap in world space, and either no processCallback is specified, or the processCallback returns true. + * @param {Function} processCallback A function with the form myFunction(Object1:GameObject,Object2:GameObject):bool that is called whenever two objects are found to overlap in world space. The notifyCallback is only called if this function returns true. See GameObject.separate(). + * @param context The context in which the callbacks will be called + */ + function (objectOrGroup1, objectOrGroup2, notifyCallback, processCallback, context) { + if (typeof objectOrGroup2 === "undefined") { objectOrGroup2 = null; } + if (typeof notifyCallback === "undefined") { notifyCallback = null; } + if (typeof processCallback === "undefined") { processCallback = null; } + if (typeof context === "undefined") { context = null; } + this.add(objectOrGroup1, QuadTree.A_LIST); + if(objectOrGroup2 != null) { + this.add(objectOrGroup2, QuadTree.B_LIST); + QuadTree._useBothLists = true; + } else { + QuadTree._useBothLists = false; + } + QuadTree._notifyCallback = notifyCallback; + QuadTree._processingCallback = processCallback; + QuadTree._callbackContext = context; + }; + QuadTree.prototype.add = /** + * Call this function to add an object to the root of the tree. + * This function will recursively add all group members, but + * not the groups themselves. + * + * @param {} objectOrGroup GameObjects are just added, Groups are recursed and their applicable members added accordingly. + * @param {Number} list A uint flag indicating the list to which you want to add the objects. Options are QuadTree.A_LIST and QuadTree.B_LIST. + */ + function (objectOrGroup, list) { + QuadTree._list = list; + if(objectOrGroup.isGroup == true) { + this._i = 0; + this._members = objectOrGroup['members']; + this._l = objectOrGroup['length']; + while(this._i < this._l) { + this._basic = this._members[this._i++]; + if(this._basic != null && this._basic.exists) { + if(this._basic.type == Phaser.Types.GROUP) { + this.add(this._basic, list); + } else { + QuadTree._object = this._basic; + if(QuadTree._object.exists && QuadTree._object.allowCollisions) { + this.addObject(); + } + } + } + } + } else { + QuadTree._object = objectOrGroup; + if(QuadTree._object.exists && QuadTree._object.allowCollisions) { + this.addObject(); + } + } + }; + QuadTree.prototype.addObject = /** + * Internal function for recursively navigating and creating the tree + * while adding objects to the appropriate nodes. + */ + function () { + //If this quad (not its children) lies entirely inside this object, add it here + if(!this._canSubdivide || ((this._leftEdge >= QuadTree._object.collisionMask.x) && (this._rightEdge <= QuadTree._object.collisionMask.right) && (this._topEdge >= QuadTree._object.collisionMask.y) && (this._bottomEdge <= QuadTree._object.collisionMask.bottom))) { + this.addToList(); + return; + } + //See if the selected object fits completely inside any of the quadrants + if((QuadTree._object.collisionMask.x > this._leftEdge) && (QuadTree._object.collisionMask.right < this._midpointX)) { + if((QuadTree._object.collisionMask.y > this._topEdge) && (QuadTree._object.collisionMask.bottom < this._midpointY)) { + if(this._northWestTree == null) { + this._northWestTree = new QuadTree(this._leftEdge, this._topEdge, this._halfWidth, this._halfHeight, this); + } + this._northWestTree.addObject(); + return; + } + if((QuadTree._object.collisionMask.y > this._midpointY) && (QuadTree._object.collisionMask.bottom < this._bottomEdge)) { + if(this._southWestTree == null) { + this._southWestTree = new QuadTree(this._leftEdge, this._midpointY, this._halfWidth, this._halfHeight, this); + } + this._southWestTree.addObject(); + return; + } + } + if((QuadTree._object.collisionMask.x > this._midpointX) && (QuadTree._object.collisionMask.right < this._rightEdge)) { + if((QuadTree._object.collisionMask.y > this._topEdge) && (QuadTree._object.collisionMask.bottom < this._midpointY)) { + if(this._northEastTree == null) { + this._northEastTree = new QuadTree(this._midpointX, this._topEdge, this._halfWidth, this._halfHeight, this); + } + this._northEastTree.addObject(); + return; + } + if((QuadTree._object.collisionMask.y > this._midpointY) && (QuadTree._object.collisionMask.bottom < this._bottomEdge)) { + if(this._southEastTree == null) { + this._southEastTree = new QuadTree(this._midpointX, this._midpointY, this._halfWidth, this._halfHeight, this); + } + this._southEastTree.addObject(); + return; + } + } + //If it wasn't completely contained we have to check out the partial overlaps + if((QuadTree._object.collisionMask.right > this._leftEdge) && (QuadTree._object.collisionMask.x < this._midpointX) && (QuadTree._object.collisionMask.bottom > this._topEdge) && (QuadTree._object.collisionMask.y < this._midpointY)) { + if(this._northWestTree == null) { + this._northWestTree = new QuadTree(this._leftEdge, this._topEdge, this._halfWidth, this._halfHeight, this); + } + this._northWestTree.addObject(); + } + if((QuadTree._object.collisionMask.right > this._midpointX) && (QuadTree._object.collisionMask.x < this._rightEdge) && (QuadTree._object.collisionMask.bottom > this._topEdge) && (QuadTree._object.collisionMask.y < this._midpointY)) { + if(this._northEastTree == null) { + this._northEastTree = new QuadTree(this._midpointX, this._topEdge, this._halfWidth, this._halfHeight, this); + } + this._northEastTree.addObject(); + } + if((QuadTree._object.collisionMask.right > this._midpointX) && (QuadTree._object.collisionMask.x < this._rightEdge) && (QuadTree._object.collisionMask.bottom > this._midpointY) && (QuadTree._object.collisionMask.y < this._bottomEdge)) { + if(this._southEastTree == null) { + this._southEastTree = new QuadTree(this._midpointX, this._midpointY, this._halfWidth, this._halfHeight, this); + } + this._southEastTree.addObject(); + } + if((QuadTree._object.collisionMask.right > this._leftEdge) && (QuadTree._object.collisionMask.x < this._midpointX) && (QuadTree._object.collisionMask.bottom > this._midpointY) && (QuadTree._object.collisionMask.y < this._bottomEdge)) { + if(this._southWestTree == null) { + this._southWestTree = new QuadTree(this._leftEdge, this._midpointY, this._halfWidth, this._halfHeight, this); + } + this._southWestTree.addObject(); + } + }; + QuadTree.prototype.addToList = /** + * Internal function for recursively adding objects to leaf lists. + */ + function () { + if(QuadTree._list == QuadTree.A_LIST) { + if(this._tailA.object != null) { + this._ot = this._tailA; + this._tailA = new Phaser.LinkedList(); + this._ot.next = this._tailA; + } + this._tailA.object = QuadTree._object; + } else { + if(this._tailB.object != null) { + this._ot = this._tailB; + this._tailB = new Phaser.LinkedList(); + this._ot.next = this._tailB; + } + this._tailB.object = QuadTree._object; + } + if(!this._canSubdivide) { + return; + } + if(this._northWestTree != null) { + this._northWestTree.addToList(); + } + if(this._northEastTree != null) { + this._northEastTree.addToList(); + } + if(this._southEastTree != null) { + this._southEastTree.addToList(); + } + if(this._southWestTree != null) { + this._southWestTree.addToList(); + } + }; + QuadTree.prototype.execute = /** + * QuadTree's other main function. Call this after adding objects + * using QuadTree.load() to compare the objects that you loaded. + * + * @return {Boolean} Whether or not any overlaps were found. + */ + function () { + this._overlapProcessed = false; + if(this._headA.object != null) { + this._iterator = this._headA; + while(this._iterator != null) { + QuadTree._object = this._iterator.object; + if(QuadTree._useBothLists) { + QuadTree._iterator = this._headB; + } else { + QuadTree._iterator = this._iterator.next; + } + if(QuadTree._object.exists && (QuadTree._object.allowCollisions > 0) && (QuadTree._iterator != null) && (QuadTree._iterator.object != null) && QuadTree._iterator.object.exists && this.overlapNode()) { + this._overlapProcessed = true; + } + this._iterator = this._iterator.next; + } + } + //Advance through the tree by calling overlap on each child + if((this._northWestTree != null) && this._northWestTree.execute()) { + this._overlapProcessed = true; + } + if((this._northEastTree != null) && this._northEastTree.execute()) { + this._overlapProcessed = true; + } + if((this._southEastTree != null) && this._southEastTree.execute()) { + this._overlapProcessed = true; + } + if((this._southWestTree != null) && this._southWestTree.execute()) { + this._overlapProcessed = true; + } + return this._overlapProcessed; + }; + QuadTree.prototype.overlapNode = /** + * A private for comparing an object against the contents of a node. + * + * @return {Boolean} Whether or not any overlaps were found. + */ + function () { + //Walk the list and check for overlaps + this._overlapProcessed = false; + while(QuadTree._iterator != null) { + if(!QuadTree._object.exists || (QuadTree._object.allowCollisions <= 0)) { + break; + } + this._checkObject = QuadTree._iterator.object; + if((QuadTree._object === this._checkObject) || !this._checkObject.exists || (this._checkObject.allowCollisions <= 0)) { + QuadTree._iterator = QuadTree._iterator.next; + continue; + } + if(QuadTree._object.collisionMask.checkHullIntersection(this._checkObject.collisionMask)) { + //Execute callback functions if they exist + if((QuadTree._processingCallback == null) || QuadTree._processingCallback(QuadTree._object, this._checkObject)) { + this._overlapProcessed = true; + } + if(this._overlapProcessed && (QuadTree._notifyCallback != null)) { + if(QuadTree._callbackContext !== null) { + QuadTree._notifyCallback.call(QuadTree._callbackContext, QuadTree._object, this._checkObject); + } else { + QuadTree._notifyCallback(QuadTree._object, this._checkObject); + } + } + } + QuadTree._iterator = QuadTree._iterator.next; + } + return this._overlapProcessed; + }; + return QuadTree; + })(Phaser.Rectangle); + Phaser.QuadTree = QuadTree; +})(Phaser || (Phaser = {})); +/// +/** +* Phaser - Line +* +* A Line object is an infinte line through space. The two sets of x/y coordinates define the Line Segment. +*/ +var Phaser; +(function (Phaser) { + var Line = (function () { + /** + * + * @constructor + * @param {Number} x1 + * @param {Number} y1 + * @param {Number} x2 + * @param {Number} y2 + * @return {Phaser.Line} This Object + */ + function Line(x1, y1, x2, y2) { + if (typeof x1 === "undefined") { x1 = 0; } + if (typeof y1 === "undefined") { y1 = 0; } + if (typeof x2 === "undefined") { x2 = 0; } + if (typeof y2 === "undefined") { y2 = 0; } + /** + * + * @property x1 + * @type {Number} + */ + this.x1 = 0; + /** + * + * @property y1 + * @type {Number} + */ + this.y1 = 0; + /** + * + * @property x2 + * @type {Number} + */ + this.x2 = 0; + /** + * + * @property y2 + * @type {Number} + */ + this.y2 = 0; + this.setTo(x1, y1, x2, y2); + } + Line.prototype.clone = /** + * + * @method clone + * @param {Phaser.Line} [output] + * @return {Phaser.Line} + */ + function (output) { + if (typeof output === "undefined") { output = new Line(); } + return output.setTo(this.x1, this.y1, this.x2, this.y2); + }; + Line.prototype.copyFrom = /** + * + * @method copyFrom + * @param {Phaser.Line} source + * @return {Phaser.Line} + */ + function (source) { + return this.setTo(source.x1, source.y1, source.x2, source.y2); + }; + Line.prototype.copyTo = /** + * + * @method copyTo + * @param {Phaser.Line} target + * @return {Phaser.Line} + */ + function (target) { + return target.copyFrom(this); + }; + Line.prototype.setTo = /** + * + * @method setTo + * @param {Number} x1 + * @param {Number} y1 + * @param {Number} x2 + * @param {Number} y2 + * @return {Phaser.Line} + */ + function (x1, y1, x2, y2) { + if (typeof x1 === "undefined") { x1 = 0; } + if (typeof y1 === "undefined") { y1 = 0; } + if (typeof x2 === "undefined") { x2 = 0; } + if (typeof y2 === "undefined") { y2 = 0; } + this.x1 = x1; + this.y1 = y1; + this.x2 = x2; + this.y2 = y2; + return this; + }; + Object.defineProperty(Line.prototype, "width", { + get: function () { + return Math.max(this.x1, this.x2) - Math.min(this.x1, this.x2); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Line.prototype, "height", { + get: function () { + return Math.max(this.y1, this.y2) - Math.min(this.y1, this.y2); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Line.prototype, "length", { + get: /** + * + * @method length + * @return {Number} + */ + function () { + return Math.sqrt((this.x2 - this.x1) * (this.x2 - this.x1) + (this.y2 - this.y1) * (this.y2 - this.y1)); + }, + enumerable: true, + configurable: true + }); + Line.prototype.getY = /** + * + * @method getY + * @param {Number} x + * @return {Number} + */ + function (x) { + return this.slope * x + this.yIntercept; + }; + Object.defineProperty(Line.prototype, "angle", { + get: /** + * + * @method angle + * @return {Number} + */ + function () { + return Math.atan2(this.x2 - this.x1, this.y2 - this.y1); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Line.prototype, "slope", { + get: /** + * + * @method slope + * @return {Number} + */ + function () { + return (this.y2 - this.y1) / (this.x2 - this.x1); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Line.prototype, "perpSlope", { + get: /** + * + * @method perpSlope + * @return {Number} + */ + function () { + return -((this.x2 - this.x1) / (this.y2 - this.y1)); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Line.prototype, "yIntercept", { + get: /** + * + * @method yIntercept + * @return {Number} + */ + function () { + return (this.y1 - this.slope * this.x1); + }, + enumerable: true, + configurable: true + }); + Line.prototype.isPointOnLine = /** + * + * @method isPointOnLine + * @param {Number} x + * @param {Number} y + * @return {Boolean} + */ + function (x, y) { + if((x - this.x1) * (this.y2 - this.y1) === (this.x2 - this.x1) * (y - this.y1)) { + return true; + } else { + return false; + } + }; + Line.prototype.isPointOnLineSegment = /** + * + * @method isPointOnLineSegment + * @param {Number} x + * @param {Number} y + * @return {Boolean} + */ + function (x, y) { + var xMin = Math.min(this.x1, this.x2); + var xMax = Math.max(this.x1, this.x2); + var yMin = Math.min(this.y1, this.y2); + var yMax = Math.max(this.y1, this.y2); + if(this.isPointOnLine(x, y) && (x >= xMin && x <= xMax) && (y >= yMin && y <= yMax)) { + return true; + } else { + return false; + } + }; + Line.prototype.intersectLineLine = /** + * + * @method intersectLineLine + * @param {Any} line + * @return {Any} + */ + function (line) { + //return Phaser.intersectLineLine(this,line); + }; + Line.prototype.perp = /** + * + * @method perp + * @param {Number} x + * @param {Number} y + * @param {Phaser.Line} [output] + * @return {Phaser.Line} + */ + function (x, y, output) { + if(this.y1 === this.y2) { + if(output) { + output.setTo(x, y, x, this.y1); + } else { + return new Line(x, y, x, this.y1); + } + } + var yInt = (y - this.perpSlope * x); + var pt = this.intersectLineLine({ + x1: x, + y1: y, + x2: 0, + y2: yInt + }); + if(output) { + output.setTo(x, y, pt.x, pt.y); + } else { + return new Line(x, y, pt.x, pt.y); + } + }; + Line.prototype.toString = /* + intersectLineCircle (circle:Circle) + { + var perp = this.perp() + return Phaser.intersectLineCircle(this,circle); + + } + */ + /** + * + * @method toString + * @return {String} + */ + function () { + return "[{Line (x1=" + this.x1 + " y1=" + this.y1 + " x2=" + this.x2 + " y2=" + this.y2 + ")}]"; + }; + return Line; + })(); + Phaser.Line = Line; +})(Phaser || (Phaser = {})); +/// +/** +* Phaser - IntersectResult +* +* A light-weight result object to hold the results of an intersection. For when you need more than just true/false. +*/ +var Phaser; +(function (Phaser) { + var IntersectResult = (function () { + function IntersectResult() { + /** + * Did they intersect or not? + * @property result + * @type {Boolean} + */ + this.result = false; + } + IntersectResult.prototype.setTo = /** + * + * @method setTo + * @param {Number} x1 + * @param {Number} y1 + * @param {Number} [x2] + * @param {Number} [y2] + * @param {Number} [width] + * @param {Number} [height] + */ + function (x1, y1, x2, y2, width, height) { + if (typeof x2 === "undefined") { x2 = 0; } + if (typeof y2 === "undefined") { y2 = 0; } + if (typeof width === "undefined") { width = 0; } + if (typeof height === "undefined") { height = 0; } + this.x = x1; + this.y = y1; + this.x1 = x1; + this.y1 = y1; + this.x2 = x2; + this.y2 = y2; + this.width = width; + this.height = height; + }; + return IntersectResult; + })(); + Phaser.IntersectResult = IntersectResult; })(Phaser || (Phaser = {})); /// /** @@ -17398,11 +12170,11 @@ var Phaser; this.add = game.add; this.camera = game.camera; this.cache = game.cache; - this.collision = game.collision; + //this.collision = game.collision; this.input = game.input; this.loader = game.loader; this.math = game.math; - this.motion = game.motion; + //this.motion = game.motion; this.sound = game.sound; this.stage = game.stage; this.time = game.time; @@ -17442,24 +12214,20 @@ var Phaser; */ function () { }; - State.prototype.collide = /** - * Checks for overlaps between two objects using the world QuadTree. Can be GameObject vs. GameObject, GameObject vs. Group or Group vs. Group. - * Note: Does not take the objects scrollFactor into account. All overlaps are check in world space. - * @param object1 The first GameObject or Group to check. If null the world.group is used. - * @param object2 The second GameObject or Group to check. - * @param notifyCallback A callback function that is called if the objects overlap. The two objects will be passed to this function in the same order in which you passed them to Collision.overlap. - * @param processCallback A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then notifyCallback will only be called if processCallback returns true. - * @param context The context in which the callbacks will be called - * @returns {boolean} true if the objects overlap, otherwise false. - */ - function (objectOrGroup1, objectOrGroup2, notifyCallback, context) { - if (typeof objectOrGroup1 === "undefined") { objectOrGroup1 = null; } - if (typeof objectOrGroup2 === "undefined") { objectOrGroup2 = null; } - if (typeof notifyCallback === "undefined") { notifyCallback = null; } - if (typeof context === "undefined") { context = this.game.callbackContext; } - return this.collision.overlap(objectOrGroup1, objectOrGroup2, notifyCallback, Phaser.Collision.separate, context); - }; return State; })(); Phaser.State = State; -})(Phaser || (Phaser = {})); + /** + * Checks for overlaps between two objects using the world QuadTree. Can be GameObject vs. GameObject, GameObject vs. Group or Group vs. Group. + * Note: Does not take the objects scrollFactor into account. All overlaps are check in world space. + * @param object1 The first GameObject or Group to check. If null the world.group is used. + * @param object2 The second GameObject or Group to check. + * @param notifyCallback A callback function that is called if the objects overlap. The two objects will be passed to this function in the same order in which you passed them to Collision.overlap. + * @param processCallback A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then notifyCallback will only be called if processCallback returns true. + * @param context The context in which the callbacks will be called + * @returns {boolean} true if the objects overlap, otherwise false. + */ + //public collide(objectOrGroup1 = null, objectOrGroup2 = null, notifyCallback = null, context? = this.game.callbackContext): bool { + // return this.collision.overlap(objectOrGroup1, objectOrGroup2, notifyCallback, Collision.separate, context); + //} + })(Phaser || (Phaser = {})); diff --git a/Tests/physics/temp1.js b/Tests/physics/temp1.js deleted file mode 100644 index 9b6e962b9..000000000 --- a/Tests/physics/temp1.js +++ /dev/null @@ -1,113 +0,0 @@ -/// -var Physics = (function () { - function Physics() { - this.max_bodies = 512; - this.max_vertices = 1024; - this.max_edges = 1024; - this.max_body_vertices = 64; - this.max_body_edges = 64; - this.vertices = []; - this.edges = []; - this.bodies = []; - } - Physics.prototype.updateForces = // Sets the force on each vertex to the gravity force. You could of course apply other forces like magnetism etc. - function () { - for(var i = 0; i < this.vertexCount; i++) { - this.vertices[i].acceleration = this.gravity; - } - }; - Physics.prototype.updateVerlet = // Updates the vertex position - function () { - for(var i = 0; i < this.vertexCount; i++) { - var v = this.vertices[i]; - var temp = v.position; - //v.position.mutableAdd( - //v.position += v.position - v.oldPosition + v.acceleration * this.timestep * this.timestep; - } - }; - Physics.prototype.updateEdges = function () { - }; - Physics.prototype.iterateCollisions = function () { - }; - Physics.prototype.detectCollision = function (body1, body2) { - }; - Physics.prototype.processCollision = function () { - }; - Physics.prototype.intervalDistance = function (minA, maxA, minB, maxB) { - }; - Physics.prototype.bodiesOverlap = function (body1, body2) { - }; - Physics.prototype.update = // CollisionInfo - // depth, normal, edge, vertex - function () { - }; - Physics.prototype.render = function () { - }; - Physics.prototype.addBody = function (body) { - this.bodies.push(body); - this.bodyCount = this.bodies.length; - }; - Physics.prototype.addEdge = function (edge) { - this.edges.push(edge); - this.edgeCount = this.edges.length; - }; - Physics.prototype.addVertex = function (vertex) { - this.vertices.push(vertex); - this.vertexCount = this.vertices.length; - }; - Physics.prototype.findVertex = function (x, y) { - }; - return Physics; -})(); -var PhysicsBody = (function () { - function PhysicsBody() { - this.vertices = []; - this.edges = []; - } - PhysicsBody.prototype.addEdge = function (edge) { - }; - PhysicsBody.prototype.addVertex = function (vertex) { - }; - PhysicsBody.prototype.projectToAxis = function (axis, min, max) { - }; - PhysicsBody.prototype.calculateCenter = function () { - }; - PhysicsBody.prototype.createBox = function (x, y, width, height) { - }; - return PhysicsBody; -})(); -var Vertex = (function () { - function Vertex(body, posX, posY) { - } - return Vertex; -})(); -var Edge = (function () { - function Edge(body, pV1, pV2, pBoundary) { - } - return Edge; -})(); -(function () { - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update, render); - function init() { - myGame.loader.addImageFile('atari1', 'assets/sprites/atari130xe.png'); - myGame.loader.load(); - } - function create() { - var p = new Physics(); - //p.max_bodies - } - function update() { - } - function render() { - //myGame.stage.context.strokeStyle = 'rgb(0,255,0)'; - //myGame.stage.context.beginPath(); - //myGame.stage.context.moveTo(poly1.points[0].x + poly1.pos.x, poly1.points[0].y + poly1.pos.y); - //for (var i = 1; i < poly1.points.length; i++) - //{ - // myGame.stage.context.lineTo(poly1.points[i].x + poly1.pos.x, poly1.points[i].y + poly1.pos.y); - //} - //myGame.stage.context.lineTo(poly1.points[0].x + poly1.pos.x, poly1.points[0].y + poly1.pos.y); - //myGame.stage.context.stroke(); - //myGame.stage.context.closePath(); - } -})(); diff --git a/Tests/physics/temp1.ts b/Tests/physics/temp1.ts deleted file mode 100644 index bd379200b..000000000 --- a/Tests/physics/temp1.ts +++ /dev/null @@ -1,200 +0,0 @@ -/// - -class Physics { - - constructor() { - - this.vertices = []; - this.edges = []; - this.bodies = []; - - } - - public gravity: Phaser.Vector2; - - public max_bodies: number = 512; - public max_vertices: number = 1024; - public max_edges: number = 1024; - public max_body_vertices: number = 64; - public max_body_edges: number = 64; - - public bodyCount: number; - public vertexCount: number; - public edgeCount: number; - public timestep: number; - public iterations; - - public vertices: Vertex[]; - public edges: Edge[]; - public bodies: PhysicsBody[]; - - // Sets the force on each vertex to the gravity force. You could of course apply other forces like magnetism etc. - public updateForces() { - - for (var i:number = 0; i < this.vertexCount; i++) - { - this.vertices[i].acceleration = this.gravity; - } - } - - // Updates the vertex position - public updateVerlet() { - - for (var i:number = 0; i < this.vertexCount; i++) - { - var v:Vertex = this.vertices[i]; - var temp: Phaser.Vector2 = v.position; - //v.position.mutableAdd( - //v.position += v.position - v.oldPosition + v.acceleration * this.timestep * this.timestep; - } - - } - - public updateEdges() { - } - - public iterateCollisions() { - } - - public detectCollision(body1, body2) { - } - - public processCollision() { - } - - public intervalDistance(minA, maxA, minB, maxB) { - } - - public bodiesOverlap(body1, body2) { - } - - // CollisionInfo - // depth, normal, edge, vertex - - public update() { - } - - public render() { - } - - public addBody(body:PhysicsBody) { - this.bodies.push(body); - this.bodyCount = this.bodies.length; - } - - public addEdge(edge:Edge) { - this.edges.push(edge); - this.edgeCount = this.edges.length; - } - - public addVertex(vertex:Vertex) { - this.vertices.push(vertex); - this.vertexCount = this.vertices.length; - } - - public findVertex(x, y) { - } - -} - -class PhysicsBody { - - constructor() { - } - - center: Phaser.Vector2; - minX; - minY; - maxX; - maxY; - vertextCount; - edgeCount; - - vertices = []; - edges = []; - - public addEdge(edge) { - } - - public addVertex(vertex) { - - } - - public projectToAxis(axis, min, max) { - } - - public calculateCenter() { - } - - public createBox(x, y, width, height) { - } - -} - -class Vertex { - - constructor(body, posX, posY) { - } - - position: Phaser.Vector2; - oldPosition: Phaser.Vector2; - acceleration: Phaser.Vector2; - parent: PhysicsBody; -} - -class Edge { - - constructor(body, pV1, pV2, pBoundary) { - } - - v1: Vertex; - v2: Vertex; - length; - boundary; - parent: PhysicsBody; - -} - -(function () { - - - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update, render); - - function init() { - - myGame.loader.addImageFile('atari1', 'assets/sprites/atari130xe.png'); - myGame.loader.load(); - - } - - function create() { - - var p = new Physics(); - //p.max_bodies - - } - - function update() { - - - } - - function render() { - - //myGame.stage.context.strokeStyle = 'rgb(0,255,0)'; - //myGame.stage.context.beginPath(); - //myGame.stage.context.moveTo(poly1.points[0].x + poly1.pos.x, poly1.points[0].y + poly1.pos.y); - - //for (var i = 1; i < poly1.points.length; i++) - //{ - // myGame.stage.context.lineTo(poly1.points[i].x + poly1.pos.x, poly1.points[i].y + poly1.pos.y); - //} - - //myGame.stage.context.lineTo(poly1.points[0].x + poly1.pos.x, poly1.points[0].y + poly1.pos.y); - - //myGame.stage.context.stroke(); - //myGame.stage.context.closePath(); - - } - -})(); diff --git a/Tests/physics/temp2.js b/Tests/physics/temp2.js deleted file mode 100644 index ca7d6f1a5..000000000 --- a/Tests/physics/temp2.js +++ /dev/null @@ -1,1413 +0,0 @@ -/// -var NPhysics = (function () { - function NPhysics() { - this.grav = 0.2; - this.drag = 1; - this.bounce = 0.3; - this.friction = 0.05; - this.min_f = 0; - this.max_f = 1; - this.min_b = 0; - this.max_b = 1; - this.min_g = 0; - this.max_g = 1; - this.xmin = 0; - this.xmax = 800; - this.ymin = 0; - this.ymax = 600; - this.objrad = 24; - this.tilerad = 24 * 2; - this.objspeed = 0.2; - this.maxspeed = 20; - } - NPhysics.prototype.update = function () { - // demoObj.Verlet(); - // demoObj.CollideVsWorldBounds(); - }; - return NPhysics; -})(); -var AABB = (function () { - function AABB(x, y, xw, yw) { - this.type = 0; - this.pos = new Phaser.Vector2(x, y); - this.oldpos = this.pos.clone(); - this.xw = Math.abs(xw); - this.yw = Math.abs(yw); - this.aabbTileProjections = { - }//hash object to hold tile-specific collision functions - ; - this.aabbTileProjections[TileMapCell.CTYPE_FULL] = this.ProjAABB_Full; - } - AABB.COL_NONE = 0; - AABB.COL_AXIS = 1; - AABB.COL_OTHER = 2; - AABB.prototype.IntegrateVerlet = function () { - //var d = DRAG; - //var g = GRAV; - var d = 1; - var g = 0.2; - var p = this.pos; - var o = this.oldpos; - var px, py; - var ox = o.x;//we can't swap buffers since mcs/sticks point directly to vector2s.. - - var oy = o.y; - o.x = px = p.x//get vector values - ; - o.y = py = p.y//p = position - ; - //o = oldposition - //integrate - p.x += (d * px) - (d * ox); - p.y += (d * py) - (d * oy) + g; - }; - AABB.prototype.ReportCollisionVsWorld = function (px, py, dx, dy, obj) { - var p = this.pos; - var o = this.oldpos; - //calc velocity - var vx = p.x - o.x; - var vy = p.y - o.y; - //find component of velocity parallel to collision normal - var dp = (vx * dx + vy * dy); - var nx = dp * dx;//project velocity onto collision normal - - var ny = dp * dy;//nx,ny is normal velocity - - var tx = vx - nx;//px,py is tangent velocity - - var ty = vy - ny; - //we only want to apply collision response forces if the object is travelling into, and not out of, the collision - var b, bx, by, f, fx, fy; - if(dp < 0) { - //f = FRICTION; - f = 0.05; - fx = tx * f; - fy = ty * f; - //b = 1 + BOUNCE;//this bounce constant should be elsewhere, i.e inside the object/tile/etc.. - b = 1 + 0.3//this bounce constant should be elsewhere, i.e inside the object/tile/etc.. - ; - bx = (nx * b); - by = (ny * b); - } else { - //moving out of collision, do not apply forces - bx = by = fx = fy = 0; - } - p.x += px//project object out of collision - ; - p.y += py; - o.x += px + bx + fx//apply bounce+friction impulses which alter velocity - ; - o.y += py + by + fy; - }; - AABB.prototype.CollideAABBVsWorldBounds = function () { - var p = this.pos; - var xw = this.xw; - var yw = this.yw; - var XMIN = 0; - var XMAX = 800; - var YMIN = 0; - var YMAX = 600; - //collide vs. x-bounds - //test XMIN - var dx = XMIN - (p.x - xw); - if(0 < dx) { - //object is colliding with XMIN - this.ReportCollisionVsWorld(dx, 0, 1, 0, null); - } else { - //test XMAX - dx = (p.x + xw) - XMAX; - if(0 < dx) { - //object is colliding with XMAX - this.ReportCollisionVsWorld(-dx, 0, -1, 0, null); - } - } - //collide vs. y-bounds - //test YMIN - var dy = YMIN - (p.y - yw); - if(0 < dy) { - //object is colliding with YMIN - this.ReportCollisionVsWorld(0, dy, 0, 1, null); - } else { - //test YMAX - dy = (p.y + yw) - YMAX; - if(0 < dy) { - //object is colliding with YMAX - this.ReportCollisionVsWorld(0, -dy, 0, -1, null); - } - } - }; - AABB.prototype.render = function (context) { - context.beginPath(); - context.strokeStyle = 'rgb(0,255,0)'; - context.strokeRect(this.pos.x - this.xw, this.pos.y - this.yw, this.xw * 2, this.yw * 2); - context.stroke(); - context.closePath(); - context.fillStyle = 'rgb(0,255,0)'; - context.fillRect(this.pos.x, this.pos.y, 2, 2); - /* - if (this.oH == 1) - { - context.beginPath(); - context.strokeStyle = 'rgb(255,0,0)'; - context.moveTo(this.pos.x - this.radius, this.pos.y - this.radius); - context.lineTo(this.pos.x - this.radius, this.pos.y + this.radius); - context.stroke(); - context.closePath(); - } - else if (this.oH == -1) - { - context.beginPath(); - context.strokeStyle = 'rgb(255,0,0)'; - context.moveTo(this.pos.x + this.radius, this.pos.y - this.radius); - context.lineTo(this.pos.x + this.radius, this.pos.y + this.radius); - context.stroke(); - context.closePath(); - } - - if (this.oV == 1) - { - context.beginPath(); - context.strokeStyle = 'rgb(255,0,0)'; - context.moveTo(this.pos.x - this.radius, this.pos.y - this.radius); - context.lineTo(this.pos.x + this.radius, this.pos.y - this.radius); - context.stroke(); - context.closePath(); - } - else if (this.oV == -1) - { - context.beginPath(); - context.strokeStyle = 'rgb(255,0,0)'; - context.moveTo(this.pos.x - this.radius, this.pos.y + this.radius); - context.lineTo(this.pos.x + this.radius, this.pos.y + this.radius); - context.stroke(); - context.closePath(); - } - */ - }; - AABB.prototype.ResolveBoxTile = function (x, y, box, t) { - if(0 < t.ID) { - return this.aabbTileProjections[t.CTYPE](x, y, box, t); - } else { - //trace("ResolveBoxTile() was called with an empty (or unknown) tile!: ID=" + t.ID + " ("+ t.i + "," + t.j + ")"); - return false; - } - }; - AABB.prototype.ProjAABB_Full = function (x, y, obj, t) { - var l = Math.sqrt(x * x + y * y); - obj.ReportCollisionVsWorld(x, y, x / l, y / l, t); - return AABB.COL_AXIS; - }; - return AABB; -})(); -var TileMapCell = (function () { - function TileMapCell(x, y, xw, yw) { - this.ID = TileMapCell.TID_EMPTY//all tiles start empty - ; - this.CTYPE = TileMapCell.CTYPE_EMPTY; - this.pos = new Phaser.Vector2(x, y)//setup collision properties - ; - this.xw = xw; - this.yw = yw; - this.minx = this.pos.x - this.xw; - this.maxx = this.pos.x + this.xw; - this.miny = this.pos.y - this.yw; - this.maxy = this.pos.y + this.yw; - //this stores tile-specific collision information - this.signx = 0; - this.signy = 0; - this.sx = 0; - this.sy = 0; - } - TileMapCell.TID_EMPTY = 0; - TileMapCell.TID_FULL = 1; - TileMapCell.TID_45DEGpn = 2; - TileMapCell.TID_45DEGnn = 3; - TileMapCell.TID_45DEGnp = 4; - TileMapCell.TID_45DEGpp = 5; - TileMapCell.TID_CONCAVEpn = 6; - TileMapCell.TID_CONCAVEnn = 7; - TileMapCell.TID_CONCAVEnp = 8; - TileMapCell.TID_CONCAVEpp = 9; - TileMapCell.TID_CONVEXpn = 10; - TileMapCell.TID_CONVEXnn = 11; - TileMapCell.TID_CONVEXnp = 12; - TileMapCell.TID_CONVEXpp = 13; - TileMapCell.TID_22DEGpnS = 14; - TileMapCell.TID_22DEGnnS = 15; - TileMapCell.TID_22DEGnpS = 16; - TileMapCell.TID_22DEGppS = 17; - TileMapCell.TID_22DEGpnB = 18; - TileMapCell.TID_22DEGnnB = 19; - TileMapCell.TID_22DEGnpB = 20; - TileMapCell.TID_22DEGppB = 21; - TileMapCell.TID_67DEGpnS = 22; - TileMapCell.TID_67DEGnnS = 23; - TileMapCell.TID_67DEGnpS = 24; - TileMapCell.TID_67DEGppS = 25; - TileMapCell.TID_67DEGpnB = 26; - TileMapCell.TID_67DEGnnB = 27; - TileMapCell.TID_67DEGnpB = 28; - TileMapCell.TID_67DEGppB = 29; - TileMapCell.TID_HALFd = 30; - TileMapCell.TID_HALFr = 31; - TileMapCell.TID_HALFu = 32; - TileMapCell.TID_HALFl = 33; - TileMapCell.CTYPE_EMPTY = 0; - TileMapCell.CTYPE_FULL = 1; - TileMapCell.CTYPE_45DEG = 2; - TileMapCell.CTYPE_CONCAVE = 6; - TileMapCell.CTYPE_CONVEX = 10; - TileMapCell.CTYPE_22DEGs = 14; - TileMapCell.CTYPE_22DEGb = 18; - TileMapCell.CTYPE_67DEGs = 22; - TileMapCell.CTYPE_67DEGb = 26; - TileMapCell.CTYPE_HALF = 30; - TileMapCell.prototype.SetState = //these functions are used to update the cell - //note: ID is assumed to NOT be "empty" state.. - //if it IS the empty state, the tile clears itself - function (ID) { - if(ID == TileMapCell.TID_EMPTY) { - this.Clear(); - } else { - //set tile state to a non-emtpy value, and update it's edges and those of the neighbors - this.ID = ID; - this.UpdateType(); - //this.Draw(); - } - return this; - }; - TileMapCell.prototype.Clear = function () { - //tile was on, turn it off - this.ID = TileMapCell.TID_EMPTY; - this.UpdateType(); - //this.Draw(); - }; - TileMapCell.prototype.render = function (context) { - context.beginPath(); - context.strokeStyle = 'rgb(255,255,0)'; - context.strokeRect(this.minx, this.miny, this.xw * 2, this.yw * 2); - context.strokeRect(this.pos.x, this.pos.y, 2, 2); - context.closePath(); - }; - TileMapCell.prototype.UpdateType = //this converts a tile from implicitly-defined (via ID), to explicit (via properties) - function () { - if(0 < this.ID) { - //tile is non-empty; collide - if(this.ID < TileMapCell.CTYPE_45DEG) { - //TID_FULL - this.CTYPE = TileMapCell.CTYPE_FULL; - this.signx = 0; - this.signy = 0; - this.sx = 0; - this.sy = 0; - } else if(this.ID < TileMapCell.CTYPE_CONCAVE) { - //45deg - this.CTYPE = TileMapCell.CTYPE_45DEG; - if(this.ID == TileMapCell.TID_45DEGpn) { - console.log('set tile as 45deg pn'); - this.signx = 1; - this.signy = -1; - this.sx = this.signx / Math.SQRT2//get slope _unit_ normal - ; - this.sy = this.signy / Math.SQRT2//since normal is (1,-1), length is sqrt(1*1 + -1*-1) = sqrt(2) - ; - } else if(this.ID == TileMapCell.TID_45DEGnn) { - this.signx = -1; - this.signy = -1; - this.sx = this.signx / Math.SQRT2//get slope _unit_ normal - ; - this.sy = this.signy / Math.SQRT2//since normal is (1,-1), length is sqrt(1*1 + -1*-1) = sqrt(2) - ; - } else if(this.ID == TileMapCell.TID_45DEGnp) { - this.signx = -1; - this.signy = 1; - this.sx = this.signx / Math.SQRT2//get slope _unit_ normal - ; - this.sy = this.signy / Math.SQRT2//since normal is (1,-1), length is sqrt(1*1 + -1*-1) = sqrt(2) - ; - } else if(this.ID == TileMapCell.TID_45DEGpp) { - this.signx = 1; - this.signy = 1; - this.sx = this.signx / Math.SQRT2//get slope _unit_ normal - ; - this.sy = this.signy / Math.SQRT2//since normal is (1,-1), length is sqrt(1*1 + -1*-1) = sqrt(2) - ; - } else { - //trace("BAAAD TILE!!!!!: ID=" + this.ID + " ("+ t.i + "," + t.j + ")"); - return false; - } - } else if(this.ID < TileMapCell.CTYPE_CONVEX) { - //concave - this.CTYPE = TileMapCell.CTYPE_CONCAVE; - if(this.ID == TileMapCell.TID_CONCAVEpn) { - this.signx = 1; - this.signy = -1; - this.sx = 0; - this.sy = 0; - } else if(this.ID == TileMapCell.TID_CONCAVEnn) { - this.signx = -1; - this.signy = -1; - this.sx = 0; - this.sy = 0; - } else if(this.ID == TileMapCell.TID_CONCAVEnp) { - this.signx = -1; - this.signy = 1; - this.sx = 0; - this.sy = 0; - } else if(this.ID == TileMapCell.TID_CONCAVEpp) { - this.signx = 1; - this.signy = 1; - this.sx = 0; - this.sy = 0; - } else { - //trace("BAAAD TILE!!!!!: ID=" + this.ID + " ("+ t.i + "," + t.j + ")"); - return false; - } - } else if(this.ID < TileMapCell.CTYPE_22DEGs) { - //convex - this.CTYPE = TileMapCell.CTYPE_CONVEX; - if(this.ID == TileMapCell.TID_CONVEXpn) { - this.signx = 1; - this.signy = -1; - this.sx = 0; - this.sy = 0; - } else if(this.ID == TileMapCell.TID_CONVEXnn) { - this.signx = -1; - this.signy = -1; - this.sx = 0; - this.sy = 0; - } else if(this.ID == TileMapCell.TID_CONVEXnp) { - this.signx = -1; - this.signy = 1; - this.sx = 0; - this.sy = 0; - } else if(this.ID == TileMapCell.TID_CONVEXpp) { - this.signx = 1; - this.signy = 1; - this.sx = 0; - this.sy = 0; - } else { - //trace("BAAAD TILE!!!!!: ID=" + this.ID + " ("+ t.i + "," + t.j + ")"); - return false; - } - } else if(this.ID < TileMapCell.CTYPE_22DEGb) { - //22deg small - this.CTYPE = TileMapCell.CTYPE_22DEGs; - if(this.ID == TileMapCell.TID_22DEGpnS) { - this.signx = 1; - this.signy = -1; - var slen = Math.sqrt(2 * 2 + 1 * 1); - this.sx = (this.signx * 1) / slen; - this.sy = (this.signy * 2) / slen; - } else if(this.ID == TileMapCell.TID_22DEGnnS) { - this.signx = -1; - this.signy = -1; - var slen = Math.sqrt(2 * 2 + 1 * 1); - this.sx = (this.signx * 1) / slen; - this.sy = (this.signy * 2) / slen; - } else if(this.ID == TileMapCell.TID_22DEGnpS) { - this.signx = -1; - this.signy = 1; - var slen = Math.sqrt(2 * 2 + 1 * 1); - this.sx = (this.signx * 1) / slen; - this.sy = (this.signy * 2) / slen; - } else if(this.ID == TileMapCell.TID_22DEGppS) { - this.signx = 1; - this.signy = 1; - var slen = Math.sqrt(2 * 2 + 1 * 1); - this.sx = (this.signx * 1) / slen; - this.sy = (this.signy * 2) / slen; - } else { - //trace("BAAAD TILE!!!!!: ID=" + this.ID + " ("+ t.i + "," + t.j + ")"); - return false; - } - } else if(this.ID < TileMapCell.CTYPE_67DEGs) { - //22deg big - this.CTYPE = TileMapCell.CTYPE_22DEGb; - if(this.ID == TileMapCell.TID_22DEGpnB) { - this.signx = 1; - this.signy = -1; - var slen = Math.sqrt(2 * 2 + 1 * 1); - this.sx = (this.signx * 1) / slen; - this.sy = (this.signy * 2) / slen; - } else if(this.ID == TileMapCell.TID_22DEGnnB) { - this.signx = -1; - this.signy = -1; - var slen = Math.sqrt(2 * 2 + 1 * 1); - this.sx = (this.signx * 1) / slen; - this.sy = (this.signy * 2) / slen; - } else if(this.ID == TileMapCell.TID_22DEGnpB) { - this.signx = -1; - this.signy = 1; - var slen = Math.sqrt(2 * 2 + 1 * 1); - this.sx = (this.signx * 1) / slen; - this.sy = (this.signy * 2) / slen; - } else if(this.ID == TileMapCell.TID_22DEGppB) { - this.signx = 1; - this.signy = 1; - var slen = Math.sqrt(2 * 2 + 1 * 1); - this.sx = (this.signx * 1) / slen; - this.sy = (this.signy * 2) / slen; - } else { - //trace("BAAAD TILE!!!!!: ID=" + this.ID + " ("+ t.i + "," + t.j + ")"); - return false; - } - } else if(this.ID < TileMapCell.CTYPE_67DEGb) { - //67deg small - this.CTYPE = TileMapCell.CTYPE_67DEGs; - if(this.ID == TileMapCell.TID_67DEGpnS) { - this.signx = 1; - this.signy = -1; - var slen = Math.sqrt(2 * 2 + 1 * 1); - this.sx = (this.signx * 2) / slen; - this.sy = (this.signy * 1) / slen; - } else if(this.ID == TileMapCell.TID_67DEGnnS) { - this.signx = -1; - this.signy = -1; - var slen = Math.sqrt(2 * 2 + 1 * 1); - this.sx = (this.signx * 2) / slen; - this.sy = (this.signy * 1) / slen; - } else if(this.ID == TileMapCell.TID_67DEGnpS) { - this.signx = -1; - this.signy = 1; - var slen = Math.sqrt(2 * 2 + 1 * 1); - this.sx = (this.signx * 2) / slen; - this.sy = (this.signy * 1) / slen; - } else if(this.ID == TileMapCell.TID_67DEGppS) { - this.signx = 1; - this.signy = 1; - var slen = Math.sqrt(2 * 2 + 1 * 1); - this.sx = (this.signx * 2) / slen; - this.sy = (this.signy * 1) / slen; - } else { - //trace("BAAAD TILE!!!!!: ID=" + this.ID + " ("+ t.i + "," + t.j + ")"); - return false; - } - } else if(this.ID < TileMapCell.CTYPE_HALF) { - //67deg big - this.CTYPE = TileMapCell.CTYPE_67DEGb; - if(this.ID == TileMapCell.TID_67DEGpnB) { - this.signx = 1; - this.signy = -1; - var slen = Math.sqrt(2 * 2 + 1 * 1); - this.sx = (this.signx * 2) / slen; - this.sy = (this.signy * 1) / slen; - } else if(this.ID == TileMapCell.TID_67DEGnnB) { - this.signx = -1; - this.signy = -1; - var slen = Math.sqrt(2 * 2 + 1 * 1); - this.sx = (this.signx * 2) / slen; - this.sy = (this.signy * 1) / slen; - } else if(this.ID == TileMapCell.TID_67DEGnpB) { - this.signx = -1; - this.signy = 1; - var slen = Math.sqrt(2 * 2 + 1 * 1); - this.sx = (this.signx * 2) / slen; - this.sy = (this.signy * 1) / slen; - } else if(this.ID == TileMapCell.TID_67DEGppB) { - this.signx = 1; - this.signy = 1; - var slen = Math.sqrt(2 * 2 + 1 * 1); - this.sx = (this.signx * 2) / slen; - this.sy = (this.signy * 1) / slen; - } else { - //trace("BAAAD TILE!!!!!: ID=" + this.ID + " ("+ t.i + "," + t.j + ")"); - return false; - } - } else { - //half-full tile - this.CTYPE = TileMapCell.CTYPE_HALF; - if(this.ID == TileMapCell.TID_HALFd) { - this.signx = 0; - this.signy = -1; - this.sx = this.signx; - this.sy = this.signy; - } else if(this.ID == TileMapCell.TID_HALFu) { - this.signx = 0; - this.signy = 1; - this.sx = this.signx; - this.sy = this.signy; - } else if(this.ID == TileMapCell.TID_HALFl) { - this.signx = 1; - this.signy = 0; - this.sx = this.signx; - this.sy = this.signy; - } else if(this.ID == TileMapCell.TID_HALFr) { - this.signx = -1; - this.signy = 0; - this.sx = this.signx; - this.sy = this.signy; - } else { - //trace("BAAD TILE!!!: ID=" + this.ID + " ("+ t.i + "," + t.j + ")"); - return false; - } - } - } else { - //TID_EMPTY - this.CTYPE = TileMapCell.CTYPE_EMPTY; - this.signx = 0; - this.signy = 0; - this.sx = 0; - this.sy = 0; - } - }; - return TileMapCell; -})(); -var Circle = (function () { - function Circle(x, y, radius) { - this.type = 1; - this.pos = new Phaser.Vector2(x, y); - this.oldpos = this.pos.clone(); - this.radius = radius; - this.circleTileProjections = { - }//hash object to hold tile-specific collision functions - ; - this.circleTileProjections[TileMapCell.CTYPE_FULL] = this.ProjCircle_Full; - this.circleTileProjections[TileMapCell.CTYPE_45DEG] = this.ProjCircle_45Deg; - this.circleTileProjections[TileMapCell.CTYPE_CONCAVE] = this.ProjCircle_Concave; - this.circleTileProjections[TileMapCell.CTYPE_CONVEX] = this.ProjCircle_Convex; - //Proj_CircleTile[CTYPE_22DEGs] = ProjCircle_22DegS; - //Proj_CircleTile[CTYPE_22DEGb] = ProjCircle_22DegB; - //Proj_CircleTile[CTYPE_67DEGs] = ProjCircle_67DegS; - //Proj_CircleTile[CTYPE_67DEGb] = ProjCircle_67DegB; - //Proj_CircleTile[CTYPE_HALF] = ProjCircle_Half; - } - Circle.COL_NONE = 0; - Circle.COL_AXIS = 1; - Circle.COL_OTHER = 2; - Circle.prototype.IntegrateVerlet = function () { - //var d = DRAG; - //var g = GRAV; - var d = 1; - var g = 0.2; - var p = this.pos; - var o = this.oldpos; - var px, py; - var ox = o.x;//we can't swap buffers since mcs/sticks point directly to vector2s.. - - var oy = o.y; - o.x = px = p.x//get vector values - ; - o.y = py = p.y//p = position - ; - //o = oldposition - //integrate - p.x += (d * px) - (d * ox); - p.y += (d * py) - (d * oy) + g; - }; - Circle.prototype.ReportCollisionVsWorld = function (px, py, dx, dy, obj) { - var p = this.pos; - var o = this.oldpos; - //calc velocity - var vx = p.x - o.x; - var vy = p.y - o.y; - //find component of velocity parallel to collision normal - var dp = (vx * dx + vy * dy); - var nx = dp * dx;//project velocity onto collision normal - - var ny = dp * dy;//nx,ny is normal velocity - - var tx = vx - nx;//px,py is tangent velocity - - var ty = vy - ny; - //we only want to apply collision response forces if the object is travelling into, and not out of, the collision - var b, bx, by, f, fx, fy; - if(dp < 0) { - //f = FRICTION; - f = 0.05; - fx = tx * f; - fy = ty * f; - //b = 1 + BOUNCE;//this bounce constant should be elsewhere, i.e inside the object/tile/etc.. - b = 1 + 0.3//this bounce constant should be elsewhere, i.e inside the object/tile/etc.. - ; - bx = (nx * b); - by = (ny * b); - } else { - //moving out of collision, do not apply forces - bx = by = fx = fy = 0; - } - p.x += px//project object out of collision - ; - p.y += py; - o.x += px + bx + fx//apply bounce+friction impulses which alter velocity - ; - o.y += py + by + fy; - }; - Circle.prototype.CollideCircleVsWorldBounds = function () { - var p = this.pos; - var r = this.radius; - var XMIN = 0; - var XMAX = 800; - var YMIN = 0; - var YMAX = 600; - //collide vs. x-bounds - //test XMIN - var dx = XMIN - (p.x - r); - if(0 < dx) { - //object is colliding with XMIN - this.ReportCollisionVsWorld(dx, 0, 1, 0, null); - } else { - //test XMAX - dx = (p.x + r) - XMAX; - if(0 < dx) { - //object is colliding with XMAX - this.ReportCollisionVsWorld(-dx, 0, -1, 0, null); - } - } - //collide vs. y-bounds - //test YMIN - var dy = YMIN - (p.y - r); - if(0 < dy) { - //object is colliding with YMIN - this.ReportCollisionVsWorld(0, dy, 0, 1, null); - } else { - //test YMAX - dy = (p.y + r) - YMAX; - if(0 < dy) { - //object is colliding with YMAX - this.ReportCollisionVsWorld(0, -dy, 0, -1, null); - } - } - }; - Circle.prototype.render = function (context) { - context.beginPath(); - context.strokeStyle = 'rgb(0,255,0)'; - context.arc(this.pos.x, this.pos.y, this.radius, 0, Math.PI * 2); - context.stroke(); - context.closePath(); - if(this.oH == 1) { - context.beginPath(); - context.strokeStyle = 'rgb(255,0,0)'; - context.moveTo(this.pos.x - this.radius, this.pos.y - this.radius); - context.lineTo(this.pos.x - this.radius, this.pos.y + this.radius); - context.stroke(); - context.closePath(); - } else if(this.oH == -1) { - context.beginPath(); - context.strokeStyle = 'rgb(255,0,0)'; - context.moveTo(this.pos.x + this.radius, this.pos.y - this.radius); - context.lineTo(this.pos.x + this.radius, this.pos.y + this.radius); - context.stroke(); - context.closePath(); - } - if(this.oV == 1) { - context.beginPath(); - context.strokeStyle = 'rgb(255,0,0)'; - context.moveTo(this.pos.x - this.radius, this.pos.y - this.radius); - context.lineTo(this.pos.x + this.radius, this.pos.y - this.radius); - context.stroke(); - context.closePath(); - } else if(this.oV == -1) { - context.beginPath(); - context.strokeStyle = 'rgb(255,0,0)'; - context.moveTo(this.pos.x - this.radius, this.pos.y + this.radius); - context.lineTo(this.pos.x + this.radius, this.pos.y + this.radius); - context.stroke(); - context.closePath(); - } - }; - Circle.prototype.CollideCircleVsTile = function (tile) { - var pos = this.pos; - var r = this.radius; - var c = tile; - var tx = c.pos.x; - var ty = c.pos.y; - var txw = c.xw; - var tyw = c.yw; - var dx = pos.x - tx;//tile->obj delta - - var px = (txw + r) - Math.abs(dx);//penetration depth in x - - if(0 < px) { - var dy = pos.y - ty;//tile->obj delta - - var py = (tyw + r) - Math.abs(dy);//pen depth in y - - if(0 < py) { - //object may be colliding with tile - //determine grid/voronoi region of circle center - this.oH = 0; - this.oV = 0; - if(dx < -txw) { - //circle is on left side of tile - this.oH = -1; - } else if(txw < dx) { - //circle is on right side of tile - this.oH = 1; - } - if(dy < -tyw) { - //circle is on top side of tile - this.oV = -1; - } else if(tyw < dy) { - //circle is on bottom side of tile - this.oV = 1; - } - this.ResolveCircleTile(px, py, this.oH, this.oV, this, c); - } - } - }; - Circle.prototype.ResolveCircleTile = function (x, y, oH, oV, obj, t) { - if(0 < t.ID) { - return this.circleTileProjections[t.CTYPE](x, y, oH, oV, obj, t); - } else { - console.log("ResolveCircleTile() was called with an empty (or unknown) tile!: ID=" + t.ID + " (" + t.i + "," + t.j + ")"); - return false; - } - }; - Circle.prototype.ProjCircle_Full = function (x, y, oH, oV, obj, t) { - //if we're colliding vs. the current cell, we need to project along the - //smallest penetration vector. - //if we're colliding vs. horiz. or vert. neighb, we simply project horiz/vert - //if we're colliding diagonally, we need to collide vs. tile corner - if(oH == 0) { - if(oV == 0) { - //collision with current cell - if(x < y) { - //penetration in x is smaller; project in x - var dx = obj.pos.x - t.pos.x;//get sign for projection along x-axis - - //NOTE: should we handle the delta == 0 case?! and how? (project towards oldpos?) - if(dx < 0) { - obj.ReportCollisionVsWorld(-x, 0, -1, 0, t); - return Circle.COL_AXIS; - } else { - obj.ReportCollisionVsWorld(x, 0, 1, 0, t); - return Circle.COL_AXIS; - } - } else { - //penetration in y is smaller; project in y - var dy = obj.pos.y - t.pos.y;//get sign for projection along y-axis - - //NOTE: should we handle the delta == 0 case?! and how? (project towards oldpos?) - if(dy < 0) { - obj.ReportCollisionVsWorld(0, -y, 0, -1, t); - return Circle.COL_AXIS; - } else { - obj.ReportCollisionVsWorld(0, y, 0, 1, t); - return Circle.COL_AXIS; - } - } - } else { - //collision with vertical neighbor - obj.ReportCollisionVsWorld(0, y * oV, 0, oV, t); - return Circle.COL_AXIS; - } - } else if(oV == 0) { - //collision with horizontal neighbor - obj.ReportCollisionVsWorld(x * oH, 0, oH, 0, t); - return Circle.COL_AXIS; - } else { - //diagonal collision - //get diag vertex position - var vx = t.pos.x + (oH * t.xw); - var vy = t.pos.y + (oV * t.yw); - var dx = obj.pos.x - vx;//calc vert->circle vector - - var dy = obj.pos.y - vy; - var len = Math.sqrt(dx * dx + dy * dy); - var pen = obj.radius - len; - if(0 < pen) { - //vertex is in the circle; project outward - if(len == 0) { - //project out by 45deg - dx = oH / Math.SQRT2; - dy = oV / Math.SQRT2; - } else { - dx /= len; - dy /= len; - } - obj.ReportCollisionVsWorld(dx * pen, dy * pen, dx, dy, t); - return Circle.COL_OTHER; - } - } - return Circle.COL_NONE; - }; - Circle.prototype.ProjCircle_45Deg = function (x, y, oH, oV, obj, t) { - //if we're colliding diagonally: - // -if obj is in the diagonal pointed to by the slope normal: we can't collide, do nothing - // -else, collide vs. the appropriate vertex - //if obj is in this tile: perform collision as for aabb-ve-45deg - //if obj is horiz OR very neighb in direction of slope: collide only vs. slope - //if obj is horiz or vert neigh against direction of slope: collide vs. face - var signx = t.signx; - var signy = t.signy; - var lenP; - if(oH == 0) { - if(oV == 0) { - //colliding with current tile - var sx = t.sx; - var sy = t.sy; - var ox = (obj.pos.x - (sx * obj.radius)) - t.pos.x;//this gives is the coordinates of the innermost - - var oy = (obj.pos.y - (sy * obj.radius)) - t.pos.y;//point on the circle, relative to the tile center - - //if the dotprod of (ox,oy) and (sx,sy) is negative, the innermost point is in the slope - //and we need toproject it out by the magnitude of the projection of (ox,oy) onto (sx,sy) - var dp = (ox * sx) + (oy * sy); - if(dp < 0) { - //collision; project delta onto slope and use this as the slope penetration vector - sx *= -dp//(sx,sy) is now the penetration vector - ; - sy *= -dp; - //find the smallest axial projection vector - if(x < y) { - //penetration in x is smaller - lenP = x; - y = 0; - //get sign for projection along x-axis - if((obj.pos.x - t.pos.x) < 0) { - x *= -1; - } - } else { - //penetration in y is smaller - lenP = y; - x = 0; - //get sign for projection along y-axis - if((obj.pos.y - t.pos.y) < 0) { - y *= -1; - } - } - var lenN = Math.sqrt(sx * sx + sy * sy); - if(lenP < lenN) { - obj.ReportCollisionVsWorld(x, y, x / lenP, y / lenP, t); - return Circle.COL_AXIS; - } else { - obj.ReportCollisionVsWorld(sx, sy, t.sx, t.sy, t); - return Circle.COL_OTHER; - } - } - } else { - //colliding vertically - if((signy * oV) < 0) { - //colliding with face/edge - obj.ReportCollisionVsWorld(0, y * oV, 0, oV, t); - return Circle.COL_AXIS; - } else { - //we could only be colliding vs the slope OR a vertex - //look at the vector form the closest vert to the circle to decide - var sx = t.sx; - var sy = t.sy; - var ox = obj.pos.x - (t.pos.x - (signx * t.xw));//this gives is the coordinates of the innermost - - var oy = obj.pos.y - (t.pos.y + (oV * t.yw));//point on the circle, relative to the closest tile vert - - //if the component of (ox,oy) parallel to the normal's righthand normal - //has the same sign as the slope of the slope (the sign of the slope's slope is signx*signy) - //then we project by the vertex, otherwise by the normal. - //note that this is simply a VERY tricky/weird method of determining - //if the circle is in side the slope/face's voronoi region, or that of the vertex. - var perp = (ox * -sy) + (oy * sx); - if(0 < (perp * signx * signy)) { - //collide vs. vertex - var len = Math.sqrt(ox * ox + oy * oy); - var pen = obj.radius - len; - if(0 < pen) { - //note: if len=0, then perp=0 and we'll never reach here, so don't worry about div-by-0 - ox /= len; - oy /= len; - obj.ReportCollisionVsWorld(ox * pen, oy * pen, ox, oy, t); - return Circle.COL_OTHER; - } - } else { - //collide vs. slope - //if the component of (ox,oy) parallel to the normal is less than the circle radius, we're - //penetrating the slope. note that this method of penetration calculation doesn't hold - //in general (i.e it won't work if the circle is in the slope), but works in this case - //because we know the circle is in a neighboring cell - var dp = (ox * sx) + (oy * sy); - var pen = obj.radius - Math.abs(dp);//note: we don't need the abs because we know the dp will be positive, but just in case.. - - if(0 < pen) { - //collision; circle out along normal by penetration amount - obj.ReportCollisionVsWorld(sx * pen, sy * pen, sx, sy, t); - return Circle.COL_OTHER; - } - } - } - } - } else if(oV == 0) { - //colliding horizontally - if((signx * oH) < 0) { - //colliding with face/edge - obj.ReportCollisionVsWorld(x * oH, 0, oH, 0, t); - return Circle.COL_AXIS; - } else { - //we could only be colliding vs the slope OR a vertex - //look at the vector form the closest vert to the circle to decide - var sx = t.sx; - var sy = t.sy; - var ox = obj.pos.x - (t.pos.x + (oH * t.xw));//this gives is the coordinates of the innermost - - var oy = obj.pos.y - (t.pos.y - (signy * t.yw));//point on the circle, relative to the closest tile vert - - //if the component of (ox,oy) parallel to the normal's righthand normal - //has the same sign as the slope of the slope (the sign of the slope's slope is signx*signy) - //then we project by the normal, otherwise by the vertex. - //(NOTE: this is the opposite logic of the vertical case; - // for vertical, if the perp prod and the slope's slope agree, it's outside. - // for horizontal, if the perp prod and the slope's slope agree, circle is inside. - // ..but this is only a property of flahs' coord system (i.e the rules might swap - // in righthanded systems)) - //note that this is simply a VERY tricky/weird method of determining - //if the circle is in side the slope/face's voronio region, or that of the vertex. - var perp = (ox * -sy) + (oy * sx); - if((perp * signx * signy) < 0) { - //collide vs. vertex - var len = Math.sqrt(ox * ox + oy * oy); - var pen = obj.radius - len; - if(0 < pen) { - //note: if len=0, then perp=0 and we'll never reach here, so don't worry about div-by-0 - ox /= len; - oy /= len; - obj.ReportCollisionVsWorld(ox * pen, oy * pen, ox, oy, t); - return Circle.COL_OTHER; - } - } else { - //collide vs. slope - //if the component of (ox,oy) parallel to the normal is less than the circle radius, we're - //penetrating the slope. note that this method of penetration calculation doesn't hold - //in general (i.e it won't work if the circle is in the slope), but works in this case - //because we know the circle is in a neighboring cell - var dp = (ox * sx) + (oy * sy); - var pen = obj.radius - Math.abs(dp);//note: we don't need the abs because we know the dp will be positive, but just in case.. - - if(0 < pen) { - //collision; circle out along normal by penetration amount - obj.ReportCollisionVsWorld(sx * pen, sy * pen, sx, sy, t); - return Circle.COL_OTHER; - } - } - } - } else { - //colliding diagonally - if(0 < ((signx * oH) + (signy * oV))) { - //the dotprod of slope normal and cell offset is strictly positive, - //therefore obj is in the diagonal neighb pointed at by the normal, and - //it cannot possibly reach/touch/penetrate the slope - return Circle.COL_NONE; - } else { - //collide vs. vertex - //get diag vertex position - var vx = t.pos.x + (oH * t.xw); - var vy = t.pos.y + (oV * t.yw); - var dx = obj.pos.x - vx;//calc vert->circle vector - - var dy = obj.pos.y - vy; - var len = Math.sqrt(dx * dx + dy * dy); - var pen = obj.radius - len; - if(0 < pen) { - //vertex is in the circle; project outward - if(len == 0) { - //project out by 45deg - dx = oH / Math.SQRT2; - dy = oV / Math.SQRT2; - } else { - dx /= len; - dy /= len; - } - obj.ReportCollisionVsWorld(dx * pen, dy * pen, dx, dy, t); - return Circle.COL_OTHER; - } - } - } - return Circle.COL_NONE; - }; - Circle.prototype.ProjCircle_Concave = function (x, y, oH, oV, obj, t) { - //if we're colliding diagonally: - // -if obj is in the diagonal pointed to by the slope normal: we can't collide, do nothing - // -else, collide vs. the appropriate vertex - //if obj is in this tile: perform collision as for aabb - //if obj is horiz OR very neighb in direction of slope: collide vs vert - //if obj is horiz or vert neigh against direction of slope: collide vs. face - var signx = t.signx; - var signy = t.signy; - var lenP; - if(oH == 0) { - if(oV == 0) { - //colliding with current tile - var ox = (t.pos.x + (signx * t.xw)) - obj.pos.x;//(ox,oy) is the vector from the circle to - - var oy = (t.pos.y + (signy * t.yw)) - obj.pos.y;//tile-circle's center - - var twid = t.xw * 2; - var trad = Math.sqrt(twid * twid + 0);//this gives us the radius of a circle centered on the tile's corner and extending to the opposite edge of the tile; - - //note that this should be precomputed at compile-time since it's constant - var len = Math.sqrt(ox * ox + oy * oy); - var pen = (len + obj.radius) - trad; - if(0 < pen) { - //find the smallest axial projection vector - if(x < y) { - //penetration in x is smaller - lenP = x; - y = 0; - //get sign for projection along x-axis - if((obj.pos.x - t.pos.x) < 0) { - x *= -1; - } - } else { - //penetration in y is smaller - lenP = y; - x = 0; - //get sign for projection along y-axis - if((obj.pos.y - t.pos.y) < 0) { - y *= -1; - } - } - if(lenP < pen) { - obj.ReportCollisionVsWorld(x, y, x / lenP, y / lenP, t); - return Circle.COL_AXIS; - } else { - //we can assume that len >0, because if we're here then - //(len + obj.radius) > trad, and since obj.radius <= trad - //len MUST be > 0 - ox /= len; - oy /= len; - obj.ReportCollisionVsWorld(ox * pen, oy * pen, ox, oy, t); - return Circle.COL_OTHER; - } - } else { - return Circle.COL_NONE; - } - } else { - //colliding vertically - if((signy * oV) < 0) { - //colliding with face/edge - obj.ReportCollisionVsWorld(0, y * oV, 0, oV, t); - return Circle.COL_AXIS; - } else { - //we could only be colliding vs the vertical tip - //get diag vertex position - var vx = t.pos.x - (signx * t.xw); - var vy = t.pos.y + (oV * t.yw); - var dx = obj.pos.x - vx;//calc vert->circle vector - - var dy = obj.pos.y - vy; - var len = Math.sqrt(dx * dx + dy * dy); - var pen = obj.radius - len; - if(0 < pen) { - //vertex is in the circle; project outward - if(len == 0) { - //project out vertically - dx = 0; - dy = oV; - } else { - dx /= len; - dy /= len; - } - obj.ReportCollisionVsWorld(dx * pen, dy * pen, dx, dy, t); - return Circle.COL_OTHER; - } - } - } - } else if(oV == 0) { - //colliding horizontally - if((signx * oH) < 0) { - //colliding with face/edge - obj.ReportCollisionVsWorld(x * oH, 0, oH, 0, t); - return Circle.COL_AXIS; - } else { - //we could only be colliding vs the horizontal tip - //get diag vertex position - var vx = t.pos.x + (oH * t.xw); - var vy = t.pos.y - (signy * t.yw); - var dx = obj.pos.x - vx;//calc vert->circle vector - - var dy = obj.pos.y - vy; - var len = Math.sqrt(dx * dx + dy * dy); - var pen = obj.radius - len; - if(0 < pen) { - //vertex is in the circle; project outward - if(len == 0) { - //project out horizontally - dx = oH; - dy = 0; - } else { - dx /= len; - dy /= len; - } - obj.ReportCollisionVsWorld(dx * pen, dy * pen, dx, dy, t); - return Circle.COL_OTHER; - } - } - } else { - //colliding diagonally - if(0 < ((signx * oH) + (signy * oV))) { - //the dotprod of slope normal and cell offset is strictly positive, - //therefore obj is in the diagonal neighb pointed at by the normal, and - //it cannot possibly reach/touch/penetrate the slope - return Circle.COL_NONE; - } else { - //collide vs. vertex - //get diag vertex position - var vx = t.pos.x + (oH * t.xw); - var vy = t.pos.y + (oV * t.yw); - var dx = obj.pos.x - vx;//calc vert->circle vector - - var dy = obj.pos.y - vy; - var len = Math.sqrt(dx * dx + dy * dy); - var pen = obj.radius - len; - if(0 < pen) { - //vertex is in the circle; project outward - if(len == 0) { - //project out by 45deg - dx = oH / Math.SQRT2; - dy = oV / Math.SQRT2; - } else { - dx /= len; - dy /= len; - } - obj.ReportCollisionVsWorld(dx * pen, dy * pen, dx, dy, t); - return Circle.COL_OTHER; - } - } - } - return Circle.COL_NONE; - }; - Circle.prototype.ProjCircle_Convex = function (x, y, oH, oV, obj, t) { - //if the object is horiz AND/OR vertical neighbor in the normal (signx,signy) - //direction, collide vs. tile-circle only. - //if we're colliding diagonally: - // -else, collide vs. the appropriate vertex - //if obj is in this tile: perform collision as for aabb - //if obj is horiz or vert neigh against direction of slope: collide vs. face - var signx = t.signx; - var signy = t.signy; - var lenP; - if(oH == 0) { - if(oV == 0) { - //colliding with current tile - var ox = obj.pos.x - (t.pos.x - (signx * t.xw));//(ox,oy) is the vector from the tile-circle to - - var oy = obj.pos.y - (t.pos.y - (signy * t.yw));//the circle's center - - var twid = t.xw * 2; - var trad = Math.sqrt(twid * twid + 0);//this gives us the radius of a circle centered on the tile's corner and extending to the opposite edge of the tile; - - //note that this should be precomputed at compile-time since it's constant - var len = Math.sqrt(ox * ox + oy * oy); - var pen = (trad + obj.radius) - len; - if(0 < pen) { - //find the smallest axial projection vector - if(x < y) { - //penetration in x is smaller - lenP = x; - y = 0; - //get sign for projection along x-axis - if((obj.pos.x - t.pos.x) < 0) { - x *= -1; - } - } else { - //penetration in y is smaller - lenP = y; - x = 0; - //get sign for projection along y-axis - if((obj.pos.y - t.pos.y) < 0) { - y *= -1; - } - } - if(lenP < pen) { - obj.ReportCollisionVsWorld(x, y, x / lenP, y / lenP, t); - return Circle.COL_AXIS; - } else { - //note: len should NEVER be == 0, because if it is, - //projeciton by an axis shoudl always be shorter, and we should - //never arrive here - ox /= len; - oy /= len; - obj.ReportCollisionVsWorld(ox * pen, oy * pen, ox, oy, t); - return Circle.COL_OTHER; - } - } - } else { - //colliding vertically - if((signy * oV) < 0) { - //colliding with face/edge - obj.ReportCollisionVsWorld(0, y * oV, 0, oV, t); - return Circle.COL_AXIS; - } else { - //obj in neighboring cell pointed at by tile normal; - //we could only be colliding vs the tile-circle surface - var ox = obj.pos.x - (t.pos.x - (signx * t.xw));//(ox,oy) is the vector from the tile-circle to - - var oy = obj.pos.y - (t.pos.y - (signy * t.yw));//the circle's center - - var twid = t.xw * 2; - var trad = Math.sqrt(twid * twid + 0);//this gives us the radius of a circle centered on the tile's corner and extending to the opposite edge of the tile; - - //note that this should be precomputed at compile-time since it's constant - var len = Math.sqrt(ox * ox + oy * oy); - var pen = (trad + obj.radius) - len; - if(0 < pen) { - //note: len should NEVER be == 0, because if it is, - //obj is not in a neighboring cell! - ox /= len; - oy /= len; - obj.ReportCollisionVsWorld(ox * pen, oy * pen, ox, oy, t); - return Circle.COL_OTHER; - } - } - } - } else if(oV == 0) { - //colliding horizontally - if((signx * oH) < 0) { - //colliding with face/edge - obj.ReportCollisionVsWorld(x * oH, 0, oH, 0, t); - return Circle.COL_AXIS; - } else { - //obj in neighboring cell pointed at by tile normal; - //we could only be colliding vs the tile-circle surface - var ox = obj.pos.x - (t.pos.x - (signx * t.xw));//(ox,oy) is the vector from the tile-circle to - - var oy = obj.pos.y - (t.pos.y - (signy * t.yw));//the circle's center - - var twid = t.xw * 2; - var trad = Math.sqrt(twid * twid + 0);//this gives us the radius of a circle centered on the tile's corner and extending to the opposite edge of the tile; - - //note that this should be precomputed at compile-time since it's constant - var len = Math.sqrt(ox * ox + oy * oy); - var pen = (trad + obj.radius) - len; - if(0 < pen) { - //note: len should NEVER be == 0, because if it is, - //obj is not in a neighboring cell! - ox /= len; - oy /= len; - obj.ReportCollisionVsWorld(ox * pen, oy * pen, ox, oy, t); - return Circle.COL_OTHER; - } - } - } else { - //colliding diagonally - if(0 < ((signx * oH) + (signy * oV))) { - //obj in diag neighb cell pointed at by tile normal; - //we could only be colliding vs the tile-circle surface - var ox = obj.pos.x - (t.pos.x - (signx * t.xw));//(ox,oy) is the vector from the tile-circle to - - var oy = obj.pos.y - (t.pos.y - (signy * t.yw));//the circle's center - - var twid = t.xw * 2; - var trad = Math.sqrt(twid * twid + 0);//this gives us the radius of a circle centered on the tile's corner and extending to the opposite edge of the tile; - - //note that this should be precomputed at compile-time since it's constant - var len = Math.sqrt(ox * ox + oy * oy); - var pen = (trad + obj.radius) - len; - if(0 < pen) { - //note: len should NEVER be == 0, because if it is, - //obj is not in a neighboring cell! - ox /= len; - oy /= len; - obj.ReportCollisionVsWorld(ox * pen, oy * pen, ox, oy, t); - return Circle.COL_OTHER; - } - } else { - //collide vs. vertex - //get diag vertex position - var vx = t.pos.x + (oH * t.xw); - var vy = t.pos.y + (oV * t.yw); - var dx = obj.pos.x - vx;//calc vert->circle vector - - var dy = obj.pos.y - vy; - var len = Math.sqrt(dx * dx + dy * dy); - var pen = obj.radius - len; - if(0 < pen) { - //vertex is in the circle; project outward - if(len == 0) { - //project out by 45deg - dx = oH / Math.SQRT2; - dy = oV / Math.SQRT2; - } else { - dx /= len; - dy /= len; - } - obj.ReportCollisionVsWorld(dx * pen, dy * pen, dx, dy, t); - return Circle.COL_OTHER; - } - } - } - return Circle.COL_NONE; - }; - return Circle; -})(); -(function () { - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update, render); - function init() { - myGame.loader.addImageFile('atari1', 'assets/sprites/atari130xe.png'); - myGame.loader.load(); - } - var cells; - var physics; - var b; - var c; - var t; - function create() { - this.physics = new NPhysics(); - this.c = new Circle(200, 100, 25); - this.b = new AABB(200, 200, 50, 50); - // pos is center, not upper-left - this.cells = []; - var tid; - for(var i = 0; i < 10; i++) { - if(i % 2 == 0) { - console.log('pn'); - tid = TileMapCell.TID_CONCAVEpn; - } else { - console.log('nn'); - tid = TileMapCell.TID_CONCAVEnn; - } - //this.cells.push(new TileMapCell(100 + (i * 100), 500, 50, 50).SetState(tid)); - this.cells.push(new TileMapCell(100 + (i * 100), 500, 50, 50).SetState(TileMapCell.TID_FULL)); - } - //this.t = new TileMapCell(200, 500, 100, 100); - //this.t.SetState(TileMapCell.TID_FULL); - //this.t.SetState(TileMapCell.TID_45DEGpn); - //this.t.SetState(TileMapCell.TID_CONCAVEpn); - //this.t.SetState(TileMapCell.TID_CONVEXpn); - } - function update() { - var fx = 0; - var fy = 0; - if(myGame.input.keyboard.isDown(Phaser.Keyboard.LEFT)) { - fx -= 0.2; - } else if(myGame.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) { - fx += 0.2; - } - if(myGame.input.keyboard.isDown(Phaser.Keyboard.UP)) { - fy -= 0.2 + 0.2; - } else if(myGame.input.keyboard.isDown(Phaser.Keyboard.DOWN)) { - fy += 0.2; - } - // update circle - var p = this.c.pos; - var o = this.c.oldpos; - var vx = p.x - o.x; - var vy = p.y - o.y; - var newx = Math.min(20, Math.max(-20, vx + fx)); - var newy = Math.min(20, Math.max(-20, vy + fy)); - p.x = o.x + newx; - p.y = o.y + newy; - this.c.IntegrateVerlet(); - // update box - var p = this.b.pos; - var o = this.b.oldpos; - var vx = p.x - o.x; - var vy = p.y - o.y; - var newx = Math.min(20, Math.max(-20, vx + fx)); - var newy = Math.min(20, Math.max(-20, vy + fy)); - p.x = o.x + newx; - p.y = o.y + newy; - this.b.IntegrateVerlet(); - for(var i = 0; i < this.cells.length; i++) { - this.c.CollideCircleVsTile(this.cells[i]); - //this.cells[i].render(myGame.stage.context); - } - this.c.CollideCircleVsWorldBounds(); - this.b.CollideAABBVsWorldBounds(); - } - function render() { - this.c.render(myGame.stage.context); - this.b.render(myGame.stage.context); - for(var i = 0; i < this.cells.length; i++) { - this.cells[i].render(myGame.stage.context); - } - } -})(); diff --git a/Tests/physics/temp2.ts b/Tests/physics/temp2.ts deleted file mode 100644 index 8fdc1da2b..000000000 --- a/Tests/physics/temp2.ts +++ /dev/null @@ -1,1934 +0,0 @@ -/// - -class NPhysics { - - grav: number = 0.2; - drag: number = 1; - bounce: number = 0.3; - friction: number = 0.05; - - min_f: number = 0; - max_f: number = 1; - - min_b: number = 0; - max_b: number = 1; - - min_g: number = 0; - max_g = 1; - - xmin: number = 0; - xmax: number = 800; - ymin: number = 0; - ymax: number = 600; - - objrad: number = 24; - tilerad: number = 24*2; - objspeed: number = 0.2; - maxspeed: number = 20; - - public update() { - // demoObj.Verlet(); - // demoObj.CollideVsWorldBounds(); - } - -} - -class AABB { - - constructor(x: number, y: number, xw, yw) { - - this.pos = new Phaser.Vector2(x, y); - this.oldpos = this.pos.clone(); - this.xw = Math.abs(xw); - this.yw = Math.abs(yw); - this.aabbTileProjections = {};//hash object to hold tile-specific collision functions - this.aabbTileProjections[TileMapCell.CTYPE_FULL] = this.ProjAABB_Full; - } - - type:number = 0; - pos: Phaser.Vector2; - oldpos: Phaser.Vector2; - xw: number; - yw: number; - aabbTileProjections; - public oH: number; - public oV: number; - static COL_NONE = 0; - static COL_AXIS = 1; - static COL_OTHER = 2; - - public IntegrateVerlet() { - - //var d = DRAG; - //var g = GRAV; - var d = 1; - var g = 0.2; - - var p = this.pos; - var o = this.oldpos; - var px, py; - - var ox = o.x; //we can't swap buffers since mcs/sticks point directly to vector2s.. - var oy = o.y; - o.x = px = p.x; //get vector values - o.y = py = p.y; //p = position - //o = oldposition - - //integrate - p.x += (d * px) - (d * ox); - p.y += (d * py) - (d * oy) + g; - - } - - public ReportCollisionVsWorld(px, py, dx, dy, obj: TileMapCell) { - - var p = this.pos; - var o = this.oldpos; - - //calc velocity - var vx = p.x - o.x; - var vy = p.y - o.y; - - //find component of velocity parallel to collision normal - var dp = (vx * dx + vy * dy); - var nx = dp * dx;//project velocity onto collision normal - - var ny = dp * dy;//nx,ny is normal velocity - - var tx = vx - nx;//px,py is tangent velocity - var ty = vy - ny; - - //we only want to apply collision response forces if the object is travelling into, and not out of, the collision - var b, bx, by, f, fx, fy; - - if (dp < 0) - { - //f = FRICTION; - f = 0.05; - fx = tx * f; - fy = ty * f; - - //b = 1 + BOUNCE;//this bounce constant should be elsewhere, i.e inside the object/tile/etc.. - b = 1 + 0.3;//this bounce constant should be elsewhere, i.e inside the object/tile/etc.. - - bx = (nx * b); - by = (ny * b); - - } - else - { - //moving out of collision, do not apply forces - bx = by = fx = fy = 0; - } - - p.x += px;//project object out of collision - p.y += py; - - o.x += px + bx + fx;//apply bounce+friction impulses which alter velocity - o.y += py + by + fy; - - } - - public CollideAABBVsWorldBounds() { - var p = this.pos; - var xw = this.xw; - var yw = this.yw; - var XMIN = 0; - var XMAX = 800; - var YMIN = 0; - var YMAX = 600; - - //collide vs. x-bounds - //test XMIN - var dx = XMIN - (p.x - xw); - if (0 < dx) - { - //object is colliding with XMIN - this.ReportCollisionVsWorld(dx, 0, 1, 0, null); - } - else - { - //test XMAX - dx = (p.x + xw) - XMAX; - if (0 < dx) - { - //object is colliding with XMAX - this.ReportCollisionVsWorld(-dx, 0, -1, 0, null); - } - } - - //collide vs. y-bounds - //test YMIN - var dy = YMIN - (p.y - yw); - if (0 < dy) - { - //object is colliding with YMIN - this.ReportCollisionVsWorld(0, dy, 0, 1, null); - } - else - { - //test YMAX - dy = (p.y + yw) - YMAX; - if (0 < dy) - { - //object is colliding with YMAX - this.ReportCollisionVsWorld(0, -dy, 0, -1, null); - } - } - } - - public render(context:CanvasRenderingContext2D) { - - context.beginPath(); - context.strokeStyle = 'rgb(0,255,0)'; - context.strokeRect(this.pos.x - this.xw, this.pos.y - this.yw, this.xw * 2, this.yw * 2); - context.stroke(); - context.closePath(); - - context.fillStyle = 'rgb(0,255,0)'; - context.fillRect(this.pos.x, this.pos.y, 2, 2); - - /* - if (this.oH == 1) - { - context.beginPath(); - context.strokeStyle = 'rgb(255,0,0)'; - context.moveTo(this.pos.x - this.radius, this.pos.y - this.radius); - context.lineTo(this.pos.x - this.radius, this.pos.y + this.radius); - context.stroke(); - context.closePath(); - } - else if (this.oH == -1) - { - context.beginPath(); - context.strokeStyle = 'rgb(255,0,0)'; - context.moveTo(this.pos.x + this.radius, this.pos.y - this.radius); - context.lineTo(this.pos.x + this.radius, this.pos.y + this.radius); - context.stroke(); - context.closePath(); - } - - if (this.oV == 1) - { - context.beginPath(); - context.strokeStyle = 'rgb(255,0,0)'; - context.moveTo(this.pos.x - this.radius, this.pos.y - this.radius); - context.lineTo(this.pos.x + this.radius, this.pos.y - this.radius); - context.stroke(); - context.closePath(); - } - else if (this.oV == -1) - { - context.beginPath(); - context.strokeStyle = 'rgb(255,0,0)'; - context.moveTo(this.pos.x - this.radius, this.pos.y + this.radius); - context.lineTo(this.pos.x + this.radius, this.pos.y + this.radius); - context.stroke(); - context.closePath(); - } - */ - - } - - public ResolveBoxTile(x, y, box, t) { - if (0 < t.ID) - { - return this.aabbTileProjections[t.CTYPE](x, y, box, t); - } - else - { - //trace("ResolveBoxTile() was called with an empty (or unknown) tile!: ID=" + t.ID + " ("+ t.i + "," + t.j + ")"); - return false; - } - } - - public ProjAABB_Full(x, y, obj, t) { - var l = Math.sqrt(x * x + y * y); - obj.ReportCollisionVsWorld(x, y, x / l, y / l, t); - - return AABB.COL_AXIS; - } - - - -} - -class TileMapCell { - - //TILETYPE ENUMERATION - static TID_EMPTY = 0; - static TID_FULL = 1;//fullAABB tile - static TID_45DEGpn = 2;//45-degree triangle, whose normal is (+ve,-ve) - static TID_45DEGnn = 3;//(+ve,+ve) - static TID_45DEGnp = 4;//(-ve,+ve) - static TID_45DEGpp = 5;//(-ve,-ve) - static TID_CONCAVEpn = 6;//1/4-circle cutout - static TID_CONCAVEnn = 7; - static TID_CONCAVEnp = 8; - static TID_CONCAVEpp = 9; - static TID_CONVEXpn = 10;//1/4/circle - static TID_CONVEXnn = 11; - static TID_CONVEXnp = 12; - static TID_CONVEXpp = 13; - static TID_22DEGpnS = 14;//22.5 degree slope - static TID_22DEGnnS = 15; - static TID_22DEGnpS = 16; - static TID_22DEGppS = 17; - static TID_22DEGpnB = 18; - static TID_22DEGnnB = 19; - static TID_22DEGnpB = 20; - static TID_22DEGppB = 21; - static TID_67DEGpnS = 22;//67.5 degree slope - static TID_67DEGnnS = 23; - static TID_67DEGnpS = 24; - static TID_67DEGppS = 25; - static TID_67DEGpnB = 26; - static TID_67DEGnnB = 27; - static TID_67DEGnpB = 28; - static TID_67DEGppB = 29; - static TID_HALFd = 30;//half-full tiles - static TID_HALFr = 31; - static TID_HALFu = 32; - static TID_HALFl = 33; - - //collision shape "types" - static CTYPE_EMPTY = 0; - static CTYPE_FULL = 1; - static CTYPE_45DEG = 2; - static CTYPE_CONCAVE = 6; - static CTYPE_CONVEX = 10; - static CTYPE_22DEGs = 14; - static CTYPE_22DEGb = 18; - static CTYPE_67DEGs = 22; - static CTYPE_67DEGb = 26; - static CTYPE_HALF = 30; - - ID; - CTYPE; - pos: Phaser.Vector2; - xw; - yw; - minx; - maxx; - miny; - maxy; - signx; - signy; - sx; - sy; - - constructor(x,y,xw,yw) { - - this.ID = TileMapCell.TID_EMPTY; //all tiles start empty - this.CTYPE = TileMapCell.CTYPE_EMPTY; - - this.pos = new Phaser.Vector2(x,y); //setup collision properties - this.xw = xw; - this.yw = yw; - this.minx = this.pos.x - this.xw; - this.maxx = this.pos.x + this.xw; - this.miny = this.pos.y - this.yw; - this.maxy = this.pos.y + this.yw; - - //this stores tile-specific collision information - this.signx = 0; - this.signy = 0; - this.sx = 0; - this.sy = 0; - } - - //these functions are used to update the cell - //note: ID is assumed to NOT be "empty" state.. - //if it IS the empty state, the tile clears itself - SetState(ID) { - if (ID == TileMapCell.TID_EMPTY) - { - this.Clear(); - } - else - { - //set tile state to a non-emtpy value, and update it's edges and those of the neighbors - this.ID = ID; - this.UpdateType(); - //this.Draw(); - } - return this; - } - - Clear() { - //tile was on, turn it off - this.ID = TileMapCell.TID_EMPTY - this.UpdateType(); - //this.Draw(); - } - - public render(context: CanvasRenderingContext2D) { - - context.beginPath(); - context.strokeStyle = 'rgb(255,255,0)'; - context.strokeRect(this.minx, this.miny, this.xw * 2, this.yw * 2); - context.strokeRect(this.pos.x, this.pos.y, 2, 2); - context.closePath(); - - } - - //this converts a tile from implicitly-defined (via ID), to explicit (via properties) - UpdateType() { - if (0 < this.ID) - { - //tile is non-empty; collide - if (this.ID < TileMapCell.CTYPE_45DEG) - { - //TID_FULL - this.CTYPE = TileMapCell.CTYPE_FULL; - this.signx = 0; - this.signy = 0; - this.sx = 0; - this.sy = 0; - - } - else if (this.ID < TileMapCell.CTYPE_CONCAVE) - { - - //45deg - this.CTYPE = TileMapCell.CTYPE_45DEG; - if (this.ID == TileMapCell.TID_45DEGpn) - { - console.log('set tile as 45deg pn'); - this.signx = 1; - this.signy = -1; - this.sx = this.signx / Math.SQRT2;//get slope _unit_ normal - this.sy = this.signy / Math.SQRT2;//since normal is (1,-1), length is sqrt(1*1 + -1*-1) = sqrt(2) - - } - else if (this.ID == TileMapCell.TID_45DEGnn) - { - this.signx = -1; - this.signy = -1; - this.sx = this.signx / Math.SQRT2;//get slope _unit_ normal - this.sy = this.signy / Math.SQRT2;//since normal is (1,-1), length is sqrt(1*1 + -1*-1) = sqrt(2) - - } - else if (this.ID == TileMapCell.TID_45DEGnp) - { - this.signx = -1; - this.signy = 1; - this.sx = this.signx / Math.SQRT2;//get slope _unit_ normal - this.sy = this.signy / Math.SQRT2;//since normal is (1,-1), length is sqrt(1*1 + -1*-1) = sqrt(2) - } - else if (this.ID == TileMapCell.TID_45DEGpp) - { - this.signx = 1; - this.signy = 1; - this.sx = this.signx / Math.SQRT2;//get slope _unit_ normal - this.sy = this.signy / Math.SQRT2;//since normal is (1,-1), length is sqrt(1*1 + -1*-1) = sqrt(2) - } - else - { - //trace("BAAAD TILE!!!!!: ID=" + this.ID + " ("+ t.i + "," + t.j + ")"); - return false; - } - } - else if (this.ID < TileMapCell.CTYPE_CONVEX) - { - - //concave - this.CTYPE = TileMapCell.CTYPE_CONCAVE; - if (this.ID == TileMapCell.TID_CONCAVEpn) - { - this.signx = 1; - this.signy = -1; - this.sx = 0; - this.sy = 0; - } - else if (this.ID == TileMapCell.TID_CONCAVEnn) - { - this.signx = -1; - this.signy = -1; - this.sx = 0; - this.sy = 0; - } - else if (this.ID == TileMapCell.TID_CONCAVEnp) - { - this.signx = -1; - this.signy = 1; - this.sx = 0; - this.sy = 0; - } - else if (this.ID == TileMapCell.TID_CONCAVEpp) - { - this.signx = 1; - this.signy = 1; - this.sx = 0; - this.sy = 0; - } - else - { - //trace("BAAAD TILE!!!!!: ID=" + this.ID + " ("+ t.i + "," + t.j + ")"); - return false; - } - } - else if (this.ID < TileMapCell.CTYPE_22DEGs) - { - - //convex - this.CTYPE = TileMapCell.CTYPE_CONVEX; - if (this.ID == TileMapCell.TID_CONVEXpn) - { - this.signx = 1; - this.signy = -1; - this.sx = 0; - this.sy = 0; - } - else if (this.ID == TileMapCell.TID_CONVEXnn) - { - this.signx = -1; - this.signy = -1; - this.sx = 0; - this.sy = 0; - } - else if (this.ID == TileMapCell.TID_CONVEXnp) - { - this.signx = -1; - this.signy = 1; - this.sx = 0; - this.sy = 0; - } - else if (this.ID == TileMapCell.TID_CONVEXpp) - { - this.signx = 1; - this.signy = 1; - this.sx = 0; - this.sy = 0; - } - else - { - //trace("BAAAD TILE!!!!!: ID=" + this.ID + " ("+ t.i + "," + t.j + ")"); - return false; - } - } - else if (this.ID < TileMapCell.CTYPE_22DEGb) - { - - //22deg small - this.CTYPE = TileMapCell.CTYPE_22DEGs; - if (this.ID == TileMapCell.TID_22DEGpnS) - { - this.signx = 1; - this.signy = -1; - var slen = Math.sqrt(2 * 2 + 1 * 1); - this.sx = (this.signx * 1) / slen; - this.sy = (this.signy * 2) / slen; - } - else if (this.ID == TileMapCell.TID_22DEGnnS) - { - this.signx = -1; - this.signy = -1; - var slen = Math.sqrt(2 * 2 + 1 * 1); - this.sx = (this.signx * 1) / slen; - this.sy = (this.signy * 2) / slen; - } - else if (this.ID == TileMapCell.TID_22DEGnpS) - { - this.signx = -1; - this.signy = 1; - var slen = Math.sqrt(2 * 2 + 1 * 1); - this.sx = (this.signx * 1) / slen; - this.sy = (this.signy * 2) / slen; - } - else if (this.ID == TileMapCell.TID_22DEGppS) - { - this.signx = 1; - this.signy = 1; - var slen = Math.sqrt(2 * 2 + 1 * 1); - this.sx = (this.signx * 1) / slen; - this.sy = (this.signy * 2) / slen; - } - else - { - //trace("BAAAD TILE!!!!!: ID=" + this.ID + " ("+ t.i + "," + t.j + ")"); - return false; - } - } - else if (this.ID < TileMapCell.CTYPE_67DEGs) - { - - //22deg big - this.CTYPE = TileMapCell.CTYPE_22DEGb; - if (this.ID == TileMapCell.TID_22DEGpnB) - { - this.signx = 1; - this.signy = -1; - var slen = Math.sqrt(2 * 2 + 1 * 1); - this.sx = (this.signx * 1) / slen; - this.sy = (this.signy * 2) / slen; - } - else if (this.ID == TileMapCell.TID_22DEGnnB) - { - this.signx = -1; - this.signy = -1; - var slen = Math.sqrt(2 * 2 + 1 * 1); - this.sx = (this.signx * 1) / slen; - this.sy = (this.signy * 2) / slen; - } - else if (this.ID == TileMapCell.TID_22DEGnpB) - { - this.signx = -1; - this.signy = 1; - var slen = Math.sqrt(2 * 2 + 1 * 1); - this.sx = (this.signx * 1) / slen; - this.sy = (this.signy * 2) / slen; - } - else if (this.ID == TileMapCell.TID_22DEGppB) - { - this.signx = 1; - this.signy = 1; - var slen = Math.sqrt(2 * 2 + 1 * 1); - this.sx = (this.signx * 1) / slen; - this.sy = (this.signy * 2) / slen; - } - else - { - //trace("BAAAD TILE!!!!!: ID=" + this.ID + " ("+ t.i + "," + t.j + ")"); - return false; - } - } - else if (this.ID < TileMapCell.CTYPE_67DEGb) - { - - //67deg small - this.CTYPE = TileMapCell.CTYPE_67DEGs; - if (this.ID == TileMapCell.TID_67DEGpnS) - { - this.signx = 1; - this.signy = -1; - var slen = Math.sqrt(2 * 2 + 1 * 1); - this.sx = (this.signx * 2) / slen; - this.sy = (this.signy * 1) / slen; - } - else if (this.ID == TileMapCell.TID_67DEGnnS) - { - this.signx = -1; - this.signy = -1; - var slen = Math.sqrt(2 * 2 + 1 * 1); - this.sx = (this.signx * 2) / slen; - this.sy = (this.signy * 1) / slen; - } - else if (this.ID == TileMapCell.TID_67DEGnpS) - { - this.signx = -1; - this.signy = 1; - var slen = Math.sqrt(2 * 2 + 1 * 1); - this.sx = (this.signx * 2) / slen; - this.sy = (this.signy * 1) / slen; - } - else if (this.ID == TileMapCell.TID_67DEGppS) - { - this.signx = 1; - this.signy = 1; - var slen = Math.sqrt(2 * 2 + 1 * 1); - this.sx = (this.signx * 2) / slen; - this.sy = (this.signy * 1) / slen; - } - else - { - //trace("BAAAD TILE!!!!!: ID=" + this.ID + " ("+ t.i + "," + t.j + ")"); - return false; - } - } - else if (this.ID < TileMapCell.CTYPE_HALF) - { - - //67deg big - this.CTYPE = TileMapCell.CTYPE_67DEGb; - if (this.ID == TileMapCell.TID_67DEGpnB) - { - this.signx = 1; - this.signy = -1; - var slen = Math.sqrt(2 * 2 + 1 * 1); - this.sx = (this.signx * 2) / slen; - this.sy = (this.signy * 1) / slen; - } - else if (this.ID == TileMapCell.TID_67DEGnnB) - { - this.signx = -1; - this.signy = -1; - var slen = Math.sqrt(2 * 2 + 1 * 1); - this.sx = (this.signx * 2) / slen; - this.sy = (this.signy * 1) / slen; - } - else if (this.ID == TileMapCell.TID_67DEGnpB) - { - this.signx = -1; - this.signy = 1; - var slen = Math.sqrt(2 * 2 + 1 * 1); - this.sx = (this.signx * 2) / slen; - this.sy = (this.signy * 1) / slen; - } - else if (this.ID == TileMapCell.TID_67DEGppB) - { - this.signx = 1; - this.signy = 1; - var slen = Math.sqrt(2 * 2 + 1 * 1); - this.sx = (this.signx * 2) / slen; - this.sy = (this.signy * 1) / slen; - } - else - { - //trace("BAAAD TILE!!!!!: ID=" + this.ID + " ("+ t.i + "," + t.j + ")"); - return false; - } - } - else - { - //half-full tile - this.CTYPE = TileMapCell.CTYPE_HALF; - if (this.ID == TileMapCell.TID_HALFd) - { - this.signx = 0; - this.signy = -1; - this.sx = this.signx; - this.sy = this.signy; - } - else if (this.ID == TileMapCell.TID_HALFu) - { - this.signx = 0; - this.signy = 1; - this.sx = this.signx; - this.sy = this.signy; - } - else if (this.ID == TileMapCell.TID_HALFl) - { - this.signx = 1; - this.signy = 0; - this.sx = this.signx; - this.sy = this.signy; - } - else if (this.ID == TileMapCell.TID_HALFr) - { - this.signx = -1; - this.signy = 0; - this.sx = this.signx; - this.sy = this.signy; - } - else - { - //trace("BAAD TILE!!!: ID=" + this.ID + " ("+ t.i + "," + t.j + ")"); - return false; - } - - } - - } - else - { - //TID_EMPTY - this.CTYPE = TileMapCell.CTYPE_EMPTY; - this.signx = 0; - this.signy = 0; - this.sx = 0; - this.sy = 0; - } - } - -} - -class Circle { - - constructor(x, y, radius) { - - this.pos = new Phaser.Vector2(x, y); - this.oldpos = this.pos.clone(); - this.radius = radius; - this.circleTileProjections = {};//hash object to hold tile-specific collision functions - this.circleTileProjections[TileMapCell.CTYPE_FULL] = this.ProjCircle_Full; - this.circleTileProjections[TileMapCell.CTYPE_45DEG] = this.ProjCircle_45Deg; - this.circleTileProjections[TileMapCell.CTYPE_CONCAVE] = this.ProjCircle_Concave; - this.circleTileProjections[TileMapCell.CTYPE_CONVEX] = this.ProjCircle_Convex; - - //Proj_CircleTile[CTYPE_22DEGs] = ProjCircle_22DegS; - //Proj_CircleTile[CTYPE_22DEGb] = ProjCircle_22DegB; - //Proj_CircleTile[CTYPE_67DEGs] = ProjCircle_67DegS; - //Proj_CircleTile[CTYPE_67DEGb] = ProjCircle_67DegB; - //Proj_CircleTile[CTYPE_HALF] = ProjCircle_Half; - - } - - type:number = 1; - pos: Phaser.Vector2; - oldpos: Phaser.Vector2; - radius: number; - circleTileProjections; - public oH: number; - public oV: number; - static COL_NONE = 0; - static COL_AXIS = 1; - static COL_OTHER = 2; - - public IntegrateVerlet() { - - //var d = DRAG; - //var g = GRAV; - var d = 1; - var g = 0.2; - - var p = this.pos; - var o = this.oldpos; - var px, py; - - var ox = o.x; //we can't swap buffers since mcs/sticks point directly to vector2s.. - var oy = o.y; - o.x = px = p.x; //get vector values - o.y = py = p.y; //p = position - //o = oldposition - - //integrate - p.x += (d * px) - (d * ox); - p.y += (d * py) - (d * oy) + g; - - } - - public ReportCollisionVsWorld(px, py, dx, dy, obj: TileMapCell) { - - var p = this.pos; - var o = this.oldpos; - - //calc velocity - var vx = p.x - o.x; - var vy = p.y - o.y; - - //find component of velocity parallel to collision normal - var dp = (vx * dx + vy * dy); - var nx = dp * dx;//project velocity onto collision normal - - var ny = dp * dy;//nx,ny is normal velocity - - var tx = vx - nx;//px,py is tangent velocity - var ty = vy - ny; - - //we only want to apply collision response forces if the object is travelling into, and not out of, the collision - var b, bx, by, f, fx, fy; - - if (dp < 0) - { - //f = FRICTION; - f = 0.05; - fx = tx * f; - fy = ty * f; - - //b = 1 + BOUNCE;//this bounce constant should be elsewhere, i.e inside the object/tile/etc.. - b = 1 + 0.3;//this bounce constant should be elsewhere, i.e inside the object/tile/etc.. - - bx = (nx * b); - by = (ny * b); - - } - else - { - //moving out of collision, do not apply forces - bx = by = fx = fy = 0; - } - - p.x += px;//project object out of collision - p.y += py; - - o.x += px + bx + fx;//apply bounce+friction impulses which alter velocity - o.y += py + by + fy; - - } - - public CollideCircleVsWorldBounds() { - var p = this.pos; - var r = this.radius; - var XMIN = 0; - var XMAX = 800; - var YMIN = 0; - var YMAX = 600; - - //collide vs. x-bounds - //test XMIN - var dx = XMIN - (p.x - r); - if (0 < dx) - { - //object is colliding with XMIN - this.ReportCollisionVsWorld(dx, 0, 1, 0, null); - } - else - { - //test XMAX - dx = (p.x + r) - XMAX; - if (0 < dx) - { - //object is colliding with XMAX - this.ReportCollisionVsWorld(-dx, 0, -1, 0, null); - } - } - - //collide vs. y-bounds - //test YMIN - var dy = YMIN - (p.y - r); - if (0 < dy) - { - //object is colliding with YMIN - this.ReportCollisionVsWorld(0, dy, 0, 1, null); - } - else - { - //test YMAX - dy = (p.y + r) - YMAX; - if (0 < dy) - { - //object is colliding with YMAX - this.ReportCollisionVsWorld(0, -dy, 0, -1, null); - } - } - } - - public render(context:CanvasRenderingContext2D) { - - context.beginPath(); - context.strokeStyle = 'rgb(0,255,0)'; - context.arc(this.pos.x, this.pos.y, this.radius, 0, Math.PI * 2); - context.stroke(); - context.closePath(); - - if (this.oH == 1) - { - context.beginPath(); - context.strokeStyle = 'rgb(255,0,0)'; - context.moveTo(this.pos.x - this.radius, this.pos.y - this.radius); - context.lineTo(this.pos.x - this.radius, this.pos.y + this.radius); - context.stroke(); - context.closePath(); - } - else if (this.oH == -1) - { - context.beginPath(); - context.strokeStyle = 'rgb(255,0,0)'; - context.moveTo(this.pos.x + this.radius, this.pos.y - this.radius); - context.lineTo(this.pos.x + this.radius, this.pos.y + this.radius); - context.stroke(); - context.closePath(); - } - - if (this.oV == 1) - { - context.beginPath(); - context.strokeStyle = 'rgb(255,0,0)'; - context.moveTo(this.pos.x - this.radius, this.pos.y - this.radius); - context.lineTo(this.pos.x + this.radius, this.pos.y - this.radius); - context.stroke(); - context.closePath(); - } - else if (this.oV == -1) - { - context.beginPath(); - context.strokeStyle = 'rgb(255,0,0)'; - context.moveTo(this.pos.x - this.radius, this.pos.y + this.radius); - context.lineTo(this.pos.x + this.radius, this.pos.y + this.radius); - context.stroke(); - context.closePath(); - } - - } - - public CollideCircleVsTile(tile) { - var pos = this.pos; - var r = this.radius; - var c = tile; - - var tx = c.pos.x; - var ty = c.pos.y; - var txw = c.xw; - var tyw = c.yw; - - var dx = pos.x - tx;//tile->obj delta - var px = (txw + r) - Math.abs(dx);//penetration depth in x - - if (0 < px) - { - var dy = pos.y - ty;//tile->obj delta - var py = (tyw + r) - Math.abs(dy);//pen depth in y - - if (0 < py) - { - //object may be colliding with tile - - //determine grid/voronoi region of circle center - this.oH = 0; - this.oV = 0; - if (dx < -txw) - { - //circle is on left side of tile - this.oH = -1; - } - else if (txw < dx) - { - //circle is on right side of tile - this.oH = 1; - } - - if (dy < -tyw) - { - //circle is on top side of tile - this.oV = -1; - } - else if (tyw < dy) - { - //circle is on bottom side of tile - this.oV = 1; - } - - this.ResolveCircleTile(px, py, this.oH, this.oV, this, c); - - } - } - } - - public ResolveCircleTile(x, y, oH, oV, obj, t) { - - if (0 < t.ID) - { - return this.circleTileProjections[t.CTYPE](x, y, oH, oV, obj, t); - } - else - { - console.log("ResolveCircleTile() was called with an empty (or unknown) tile!: ID=" + t.ID + " (" + t.i + "," + t.j + ")"); - return false; - } - } - - public ProjCircle_Full(x, y, oH, oV, obj:Circle, t:TileMapCell) { - - //if we're colliding vs. the current cell, we need to project along the - //smallest penetration vector. - //if we're colliding vs. horiz. or vert. neighb, we simply project horiz/vert - //if we're colliding diagonally, we need to collide vs. tile corner - - if (oH == 0) - { - if (oV == 0) - { - //collision with current cell - if (x < y) - { - //penetration in x is smaller; project in x - var dx = obj.pos.x - t.pos.x;//get sign for projection along x-axis - - //NOTE: should we handle the delta == 0 case?! and how? (project towards oldpos?) - if (dx < 0) - { - obj.ReportCollisionVsWorld(-x, 0, -1, 0, t); - return Circle.COL_AXIS; - } - else - { - obj.ReportCollisionVsWorld(x, 0, 1, 0, t); - return Circle.COL_AXIS; - } - } - else - { - //penetration in y is smaller; project in y - var dy = obj.pos.y - t.pos.y;//get sign for projection along y-axis - - //NOTE: should we handle the delta == 0 case?! and how? (project towards oldpos?) - if (dy < 0) - { - obj.ReportCollisionVsWorld(0, -y, 0, -1, t); - return Circle.COL_AXIS; - } - else - { - obj.ReportCollisionVsWorld(0, y, 0, 1, t); - return Circle.COL_AXIS; - } - } - } - else - { - //collision with vertical neighbor - obj.ReportCollisionVsWorld(0, y * oV, 0, oV, t); - - return Circle.COL_AXIS; - } - } - else if (oV == 0) - { - //collision with horizontal neighbor - obj.ReportCollisionVsWorld(x * oH, 0, oH, 0, t); - return Circle.COL_AXIS; - } - else - { - //diagonal collision - - //get diag vertex position - var vx = t.pos.x + (oH * t.xw); - var vy = t.pos.y + (oV * t.yw); - - var dx = obj.pos.x - vx;//calc vert->circle vector - var dy = obj.pos.y - vy; - - var len = Math.sqrt(dx * dx + dy * dy); - var pen = obj.radius - len; - if (0 < pen) - { - //vertex is in the circle; project outward - if (len == 0) - { - //project out by 45deg - dx = oH / Math.SQRT2; - dy = oV / Math.SQRT2; - } - else - { - dx /= len; - dy /= len; - } - - obj.ReportCollisionVsWorld(dx * pen, dy * pen, dx, dy, t); - - return Circle.COL_OTHER; - } - } - - return Circle.COL_NONE; - - } - - public ProjCircle_45Deg(x, y, oH, oV, obj: Circle, t: TileMapCell) { - - //if we're colliding diagonally: - // -if obj is in the diagonal pointed to by the slope normal: we can't collide, do nothing - // -else, collide vs. the appropriate vertex - //if obj is in this tile: perform collision as for aabb-ve-45deg - //if obj is horiz OR very neighb in direction of slope: collide only vs. slope - //if obj is horiz or vert neigh against direction of slope: collide vs. face - - var signx = t.signx; - var signy = t.signy; - var lenP; - - if (oH == 0) - { - if (oV == 0) - { - //colliding with current tile - - var sx = t.sx; - var sy = t.sy; - - var ox = (obj.pos.x - (sx * obj.radius)) - t.pos.x;//this gives is the coordinates of the innermost - var oy = (obj.pos.y - (sy * obj.radius)) - t.pos.y;//point on the circle, relative to the tile center - - //if the dotprod of (ox,oy) and (sx,sy) is negative, the innermost point is in the slope - //and we need toproject it out by the magnitude of the projection of (ox,oy) onto (sx,sy) - var dp = (ox * sx) + (oy * sy); - if (dp < 0) - { - //collision; project delta onto slope and use this as the slope penetration vector - sx *= -dp;//(sx,sy) is now the penetration vector - sy *= -dp; - - //find the smallest axial projection vector - if (x < y) - { - //penetration in x is smaller - lenP = x; - y = 0; - - //get sign for projection along x-axis - if ((obj.pos.x - t.pos.x) < 0) - { - x *= -1; - } - } - else - { - //penetration in y is smaller - lenP = y; - x = 0; - - //get sign for projection along y-axis - if ((obj.pos.y - t.pos.y) < 0) - { - y *= -1; - } - } - - var lenN = Math.sqrt(sx * sx + sy * sy); - - if (lenP < lenN) - { - obj.ReportCollisionVsWorld(x, y, x / lenP, y / lenP, t); - - return Circle.COL_AXIS; - } - else - { - obj.ReportCollisionVsWorld(sx, sy, t.sx, t.sy, t); - - return Circle.COL_OTHER; - } - } - - } - else - { - //colliding vertically - if ((signy * oV) < 0) - { - //colliding with face/edge - obj.ReportCollisionVsWorld(0, y * oV, 0, oV, t); - - return Circle.COL_AXIS; - } - else - { - //we could only be colliding vs the slope OR a vertex - //look at the vector form the closest vert to the circle to decide - - var sx = t.sx; - var sy = t.sy; - - var ox = obj.pos.x - (t.pos.x - (signx * t.xw));//this gives is the coordinates of the innermost - var oy = obj.pos.y - (t.pos.y + (oV * t.yw));//point on the circle, relative to the closest tile vert - - //if the component of (ox,oy) parallel to the normal's righthand normal - //has the same sign as the slope of the slope (the sign of the slope's slope is signx*signy) - //then we project by the vertex, otherwise by the normal. - //note that this is simply a VERY tricky/weird method of determining - //if the circle is in side the slope/face's voronoi region, or that of the vertex. - var perp = (ox * -sy) + (oy * sx); - if (0 < (perp * signx * signy)) - { - //collide vs. vertex - var len = Math.sqrt(ox * ox + oy * oy); - var pen = obj.radius - len; - if (0 < pen) - { - //note: if len=0, then perp=0 and we'll never reach here, so don't worry about div-by-0 - ox /= len; - oy /= len; - - obj.ReportCollisionVsWorld(ox * pen, oy * pen, ox, oy, t); - - return Circle.COL_OTHER; - } - } - else - { - //collide vs. slope - - //if the component of (ox,oy) parallel to the normal is less than the circle radius, we're - //penetrating the slope. note that this method of penetration calculation doesn't hold - //in general (i.e it won't work if the circle is in the slope), but works in this case - //because we know the circle is in a neighboring cell - var dp = (ox * sx) + (oy * sy); - var pen = obj.radius - Math.abs(dp);//note: we don't need the abs because we know the dp will be positive, but just in case.. - if (0 < pen) - { - //collision; circle out along normal by penetration amount - obj.ReportCollisionVsWorld(sx * pen, sy * pen, sx, sy, t); - - return Circle.COL_OTHER; - } - } - } - } - } - else if (oV == 0) - { - //colliding horizontally - if ((signx * oH) < 0) - { - //colliding with face/edge - obj.ReportCollisionVsWorld(x * oH, 0, oH, 0, t); - - return Circle.COL_AXIS; - } - else - { - //we could only be colliding vs the slope OR a vertex - //look at the vector form the closest vert to the circle to decide - - var sx = t.sx; - var sy = t.sy; - - var ox = obj.pos.x - (t.pos.x + (oH * t.xw));//this gives is the coordinates of the innermost - var oy = obj.pos.y - (t.pos.y - (signy * t.yw));//point on the circle, relative to the closest tile vert - - //if the component of (ox,oy) parallel to the normal's righthand normal - //has the same sign as the slope of the slope (the sign of the slope's slope is signx*signy) - //then we project by the normal, otherwise by the vertex. - //(NOTE: this is the opposite logic of the vertical case; - // for vertical, if the perp prod and the slope's slope agree, it's outside. - // for horizontal, if the perp prod and the slope's slope agree, circle is inside. - // ..but this is only a property of flahs' coord system (i.e the rules might swap - // in righthanded systems)) - //note that this is simply a VERY tricky/weird method of determining - //if the circle is in side the slope/face's voronio region, or that of the vertex. - var perp = (ox * -sy) + (oy * sx); - if ((perp * signx * signy) < 0) - { - //collide vs. vertex - var len = Math.sqrt(ox * ox + oy * oy); - var pen = obj.radius - len; - if (0 < pen) - { - //note: if len=0, then perp=0 and we'll never reach here, so don't worry about div-by-0 - ox /= len; - oy /= len; - - obj.ReportCollisionVsWorld(ox * pen, oy * pen, ox, oy, t); - - return Circle.COL_OTHER; - } - } - else - { - //collide vs. slope - - //if the component of (ox,oy) parallel to the normal is less than the circle radius, we're - //penetrating the slope. note that this method of penetration calculation doesn't hold - //in general (i.e it won't work if the circle is in the slope), but works in this case - //because we know the circle is in a neighboring cell - var dp = (ox * sx) + (oy * sy); - var pen = obj.radius - Math.abs(dp);//note: we don't need the abs because we know the dp will be positive, but just in case.. - if (0 < pen) - { - //collision; circle out along normal by penetration amount - obj.ReportCollisionVsWorld(sx * pen, sy * pen, sx, sy, t); - - return Circle.COL_OTHER; - } - } - } - } - else - { - //colliding diagonally - if (0 < ((signx * oH) + (signy * oV))) - { - //the dotprod of slope normal and cell offset is strictly positive, - //therefore obj is in the diagonal neighb pointed at by the normal, and - //it cannot possibly reach/touch/penetrate the slope - return Circle.COL_NONE; - } - else - { - //collide vs. vertex - //get diag vertex position - var vx = t.pos.x + (oH * t.xw); - var vy = t.pos.y + (oV * t.yw); - - var dx = obj.pos.x - vx;//calc vert->circle vector - var dy = obj.pos.y - vy; - - var len = Math.sqrt(dx * dx + dy * dy); - var pen = obj.radius - len; - if (0 < pen) - { - //vertex is in the circle; project outward - if (len == 0) - { - //project out by 45deg - dx = oH / Math.SQRT2; - dy = oV / Math.SQRT2; - } - else - { - dx /= len; - dy /= len; - } - - obj.ReportCollisionVsWorld(dx * pen, dy * pen, dx, dy, t); - return Circle.COL_OTHER; - } - - } - - } - - return Circle.COL_NONE; - } - - public ProjCircle_Concave(x, y, oH, oV, obj: Circle, t: TileMapCell) { - - //if we're colliding diagonally: - // -if obj is in the diagonal pointed to by the slope normal: we can't collide, do nothing - // -else, collide vs. the appropriate vertex - //if obj is in this tile: perform collision as for aabb - //if obj is horiz OR very neighb in direction of slope: collide vs vert - //if obj is horiz or vert neigh against direction of slope: collide vs. face - - var signx = t.signx; - var signy = t.signy; - var lenP; - - if (oH == 0) - { - if (oV == 0) - { - //colliding with current tile - - var ox = (t.pos.x + (signx * t.xw)) - obj.pos.x;//(ox,oy) is the vector from the circle to - var oy = (t.pos.y + (signy * t.yw)) - obj.pos.y;//tile-circle's center - - var twid = t.xw * 2; - var trad = Math.sqrt(twid * twid + 0);//this gives us the radius of a circle centered on the tile's corner and extending to the opposite edge of the tile; - //note that this should be precomputed at compile-time since it's constant - - var len = Math.sqrt(ox * ox + oy * oy); - var pen = (len + obj.radius) - trad; - - if (0 < pen) - { - //find the smallest axial projection vector - if (x < y) - { - //penetration in x is smaller - lenP = x; - y = 0; - - //get sign for projection along x-axis - if ((obj.pos.x - t.pos.x) < 0) - { - x *= -1; - } - } - else - { - //penetration in y is smaller - lenP = y; - x = 0; - - //get sign for projection along y-axis - if ((obj.pos.y - t.pos.y) < 0) - { - y *= -1; - } - } - - - if (lenP < pen) - { - obj.ReportCollisionVsWorld(x, y, x / lenP, y / lenP, t); - - return Circle.COL_AXIS; - } - else - { - //we can assume that len >0, because if we're here then - //(len + obj.radius) > trad, and since obj.radius <= trad - //len MUST be > 0 - ox /= len; - oy /= len; - - obj.ReportCollisionVsWorld(ox * pen, oy * pen, ox, oy, t); - - return Circle.COL_OTHER; - } - } - else - { - return Circle.COL_NONE; - } - - } - else - { - //colliding vertically - if ((signy * oV) < 0) - { - //colliding with face/edge - obj.ReportCollisionVsWorld(0, y * oV, 0, oV, t); - - return Circle.COL_AXIS; - } - else - { - //we could only be colliding vs the vertical tip - - //get diag vertex position - var vx = t.pos.x - (signx * t.xw); - var vy = t.pos.y + (oV * t.yw); - - var dx = obj.pos.x - vx;//calc vert->circle vector - var dy = obj.pos.y - vy; - - var len = Math.sqrt(dx * dx + dy * dy); - var pen = obj.radius - len; - if (0 < pen) - { - //vertex is in the circle; project outward - if (len == 0) - { - //project out vertically - dx = 0; - dy = oV; - } - else - { - dx /= len; - dy /= len; - } - - obj.ReportCollisionVsWorld(dx * pen, dy * pen, dx, dy, t); - - return Circle.COL_OTHER; - } - } - } - } - else if (oV == 0) - { - //colliding horizontally - if ((signx * oH) < 0) - { - //colliding with face/edge - obj.ReportCollisionVsWorld(x * oH, 0, oH, 0, t); - - return Circle.COL_AXIS; - } - else - { - //we could only be colliding vs the horizontal tip - - //get diag vertex position - var vx = t.pos.x + (oH * t.xw); - var vy = t.pos.y - (signy * t.yw); - - var dx = obj.pos.x - vx;//calc vert->circle vector - var dy = obj.pos.y - vy; - - var len = Math.sqrt(dx * dx + dy * dy); - var pen = obj.radius - len; - if (0 < pen) - { - //vertex is in the circle; project outward - if (len == 0) - { - //project out horizontally - dx = oH; - dy = 0; - } - else - { - dx /= len; - dy /= len; - } - - obj.ReportCollisionVsWorld(dx * pen, dy * pen, dx, dy, t); - - return Circle.COL_OTHER; - } - } - } - else - { - //colliding diagonally - if (0 < ((signx * oH) + (signy * oV))) - { - //the dotprod of slope normal and cell offset is strictly positive, - //therefore obj is in the diagonal neighb pointed at by the normal, and - //it cannot possibly reach/touch/penetrate the slope - return Circle.COL_NONE; - } - else - { - //collide vs. vertex - //get diag vertex position - var vx = t.pos.x + (oH * t.xw); - var vy = t.pos.y + (oV * t.yw); - - var dx = obj.pos.x - vx;//calc vert->circle vector - var dy = obj.pos.y - vy; - - var len = Math.sqrt(dx * dx + dy * dy); - var pen = obj.radius - len; - if (0 < pen) - { - //vertex is in the circle; project outward - if (len == 0) - { - //project out by 45deg - dx = oH / Math.SQRT2; - dy = oV / Math.SQRT2; - } - else - { - dx /= len; - dy /= len; - } - - obj.ReportCollisionVsWorld(dx * pen, dy * pen, dx, dy, t); - - return Circle.COL_OTHER; - } - - } - - } - - return Circle.COL_NONE; - - } - - public ProjCircle_Convex(x, y, oH, oV, obj: Circle, t: TileMapCell) { - //if the object is horiz AND/OR vertical neighbor in the normal (signx,signy) - //direction, collide vs. tile-circle only. - //if we're colliding diagonally: - // -else, collide vs. the appropriate vertex - //if obj is in this tile: perform collision as for aabb - //if obj is horiz or vert neigh against direction of slope: collide vs. face - - var signx = t.signx; - var signy = t.signy; - var lenP; - - if (oH == 0) - { - if (oV == 0) - { - //colliding with current tile - - - var ox = obj.pos.x - (t.pos.x - (signx * t.xw));//(ox,oy) is the vector from the tile-circle to - var oy = obj.pos.y - (t.pos.y - (signy * t.yw));//the circle's center - - var twid = t.xw * 2; - var trad = Math.sqrt(twid * twid + 0);//this gives us the radius of a circle centered on the tile's corner and extending to the opposite edge of the tile; - //note that this should be precomputed at compile-time since it's constant - - var len = Math.sqrt(ox * ox + oy * oy); - var pen = (trad + obj.radius) - len; - - if (0 < pen) - { - //find the smallest axial projection vector - if (x < y) - { - //penetration in x is smaller - lenP = x; - y = 0; - - //get sign for projection along x-axis - if ((obj.pos.x - t.pos.x) < 0) - { - x *= -1; - } - } - else - { - //penetration in y is smaller - lenP = y; - x = 0; - - //get sign for projection along y-axis - if ((obj.pos.y - t.pos.y) < 0) - { - y *= -1; - } - } - - - if (lenP < pen) - { - obj.ReportCollisionVsWorld(x, y, x / lenP, y / lenP, t); - - return Circle.COL_AXIS; - } - else - { - //note: len should NEVER be == 0, because if it is, - //projeciton by an axis shoudl always be shorter, and we should - //never arrive here - ox /= len; - oy /= len; - - obj.ReportCollisionVsWorld(ox * pen, oy * pen, ox, oy, t); - - return Circle.COL_OTHER; - - } - } - } - else - { - //colliding vertically - if ((signy * oV) < 0) - { - //colliding with face/edge - obj.ReportCollisionVsWorld(0, y * oV, 0, oV, t); - - return Circle.COL_AXIS; - } - else - { - //obj in neighboring cell pointed at by tile normal; - //we could only be colliding vs the tile-circle surface - - var ox = obj.pos.x - (t.pos.x - (signx * t.xw));//(ox,oy) is the vector from the tile-circle to - var oy = obj.pos.y - (t.pos.y - (signy * t.yw));//the circle's center - - var twid = t.xw * 2; - var trad = Math.sqrt(twid * twid + 0);//this gives us the radius of a circle centered on the tile's corner and extending to the opposite edge of the tile; - //note that this should be precomputed at compile-time since it's constant - - var len = Math.sqrt(ox * ox + oy * oy); - var pen = (trad + obj.radius) - len; - - if (0 < pen) - { - - //note: len should NEVER be == 0, because if it is, - //obj is not in a neighboring cell! - ox /= len; - oy /= len; - - obj.ReportCollisionVsWorld(ox * pen, oy * pen, ox, oy, t); - - return Circle.COL_OTHER; - } - } - } - } - else if (oV == 0) - { - //colliding horizontally - if ((signx * oH) < 0) - { - //colliding with face/edge - obj.ReportCollisionVsWorld(x * oH, 0, oH, 0, t); - - return Circle.COL_AXIS; - } - else - { - //obj in neighboring cell pointed at by tile normal; - //we could only be colliding vs the tile-circle surface - - var ox = obj.pos.x - (t.pos.x - (signx * t.xw));//(ox,oy) is the vector from the tile-circle to - var oy = obj.pos.y - (t.pos.y - (signy * t.yw));//the circle's center - - var twid = t.xw * 2; - var trad = Math.sqrt(twid * twid + 0);//this gives us the radius of a circle centered on the tile's corner and extending to the opposite edge of the tile; - //note that this should be precomputed at compile-time since it's constant - - var len = Math.sqrt(ox * ox + oy * oy); - var pen = (trad + obj.radius) - len; - - if (0 < pen) - { - - //note: len should NEVER be == 0, because if it is, - //obj is not in a neighboring cell! - ox /= len; - oy /= len; - - obj.ReportCollisionVsWorld(ox * pen, oy * pen, ox, oy, t); - - return Circle.COL_OTHER; - } - } - } - else - { - //colliding diagonally - if (0 < ((signx * oH) + (signy * oV))) - { - //obj in diag neighb cell pointed at by tile normal; - //we could only be colliding vs the tile-circle surface - - var ox = obj.pos.x - (t.pos.x - (signx * t.xw));//(ox,oy) is the vector from the tile-circle to - var oy = obj.pos.y - (t.pos.y - (signy * t.yw));//the circle's center - - var twid = t.xw * 2; - var trad = Math.sqrt(twid * twid + 0);//this gives us the radius of a circle centered on the tile's corner and extending to the opposite edge of the tile; - //note that this should be precomputed at compile-time since it's constant - - var len = Math.sqrt(ox * ox + oy * oy); - var pen = (trad + obj.radius) - len; - - if (0 < pen) - { - - //note: len should NEVER be == 0, because if it is, - //obj is not in a neighboring cell! - ox /= len; - oy /= len; - - obj.ReportCollisionVsWorld(ox * pen, oy * pen, ox, oy, t); - - return Circle.COL_OTHER; - } - } - else - { - //collide vs. vertex - //get diag vertex position - var vx = t.pos.x + (oH * t.xw); - var vy = t.pos.y + (oV * t.yw); - - var dx = obj.pos.x - vx;//calc vert->circle vector - var dy = obj.pos.y - vy; - - var len = Math.sqrt(dx * dx + dy * dy); - var pen = obj.radius - len; - if (0 < pen) - { - //vertex is in the circle; project outward - if (len == 0) - { - //project out by 45deg - dx = oH / Math.SQRT2; - dy = oV / Math.SQRT2; - } - else - { - dx /= len; - dy /= len; - } - - obj.ReportCollisionVsWorld(dx * pen, dy * pen, dx, dy, t); - - return Circle.COL_OTHER; - } - - } - - } - - return Circle.COL_NONE; - - } - -} - - - -(function () { - - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update, render); - - function init() { - - myGame.loader.addImageFile('atari1', 'assets/sprites/atari130xe.png'); - myGame.loader.load(); - - } - - var cells; - var physics: NPhysics; - var b: Circle; - var c: Circle; - var t: TileMapCell; - - function create() { - - this.physics = new NPhysics(); - this.c = new Circle(200, 100, 25); - this.b = new AABB(200, 200, 50, 50); - - // pos is center, not upper-left - this.cells = []; - - var tid; - - for (var i = 0; i < 10; i++) - { - if (i % 2 == 0) - { - console.log('pn'); - tid = TileMapCell.TID_CONCAVEpn; - } - else - { - console.log('nn'); - tid = TileMapCell.TID_CONCAVEnn; - } - - //this.cells.push(new TileMapCell(100 + (i * 100), 500, 50, 50).SetState(tid)); - this.cells.push(new TileMapCell(100 + (i * 100), 500, 50, 50).SetState(TileMapCell.TID_FULL)); - } - - //this.t = new TileMapCell(200, 500, 100, 100); - //this.t.SetState(TileMapCell.TID_FULL); - //this.t.SetState(TileMapCell.TID_45DEGpn); - //this.t.SetState(TileMapCell.TID_CONCAVEpn); - //this.t.SetState(TileMapCell.TID_CONVEXpn); - - } - - function update() { - - var fx = 0; - var fy = 0; - - if (myGame.input.keyboard.isDown(Phaser.Keyboard.LEFT)) - { - fx -= 0.2; - } - else if (myGame.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) - { - fx += 0.2; - } - - if (myGame.input.keyboard.isDown(Phaser.Keyboard.UP)) - { - fy -= 0.2 + 0.2; - } - else if (myGame.input.keyboard.isDown(Phaser.Keyboard.DOWN)) - { - fy += 0.2; - } - - // update circle - var p = this.c.pos; - var o = this.c.oldpos; - var vx = p.x - o.x; - var vy = p.y - o.y; - var newx = Math.min(20, Math.max(-20, vx+fx)); - var newy = Math.min(20, Math.max(-20, vy+fy)); - p.x = o.x + newx; - p.y = o.y + newy; - this.c.IntegrateVerlet(); - - // update box - var p = this.b.pos; - var o = this.b.oldpos; - var vx = p.x - o.x; - var vy = p.y - o.y; - var newx = Math.min(20, Math.max(-20, vx+fx)); - var newy = Math.min(20, Math.max(-20, vy+fy)); - p.x = o.x + newx; - p.y = o.y + newy; - this.b.IntegrateVerlet(); - - - for (var i = 0; i < this.cells.length; i++) - { - this.c.CollideCircleVsTile(this.cells[i]); - //this.cells[i].render(myGame.stage.context); - } - - this.c.CollideCircleVsWorldBounds(); - this.b.CollideAABBVsWorldBounds(); - - } - - function render() { - - this.c.render(myGame.stage.context); - this.b.render(myGame.stage.context); - - for (var i = 0; i < this.cells.length; i++) - { - this.cells[i].render(myGame.stage.context); - } - - } - -})(); diff --git a/Tests/scrollzones/ballscroller.js b/Tests/scrollzones/ballscroller.js deleted file mode 100644 index 3934d00bb..000000000 --- a/Tests/scrollzones/ballscroller.js +++ /dev/null @@ -1,25 +0,0 @@ -/// -/// -(function () { - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update); - function init() { - myGame.loader.addImageFile('balls', 'assets/sprites/balls.png'); - myGame.loader.load(); - } - var scroller; - function create() { - // The source image (balls.png) is only 102x17 in size, but we want it to create a scroll the size of the whole game window. - // We can take advantage of the way a ScrollZone can create a seamless pattern for us automatically. - // If you create a ScrollRegion larger than the source texture, it'll create a DynamicTexture and perform a pattern fill on it and use that - // for rendering. - // We've rounded the height up to 612 because in order to have a seamless pattern it needs to be a multiple of 17 (the height of the source image) - scroller = myGame.add.scrollZone('balls', 0, 0, 800, 612); - // Some sin/cos data for the movement - myGame.math.sinCosGenerator(256, 4, 4, 2); - } - function update() { - // Cycle through the wave data and apply it to the scroll speed (causes the circular wave motion) - scroller.currentRegion.scrollSpeed.x = myGame.math.shiftSinTable(); - scroller.currentRegion.scrollSpeed.y = myGame.math.shiftCosTable(); - } -})(); diff --git a/Tests/scrollzones/ballscroller.ts b/Tests/scrollzones/ballscroller.ts deleted file mode 100644 index 753243c7d..000000000 --- a/Tests/scrollzones/ballscroller.ts +++ /dev/null @@ -1,41 +0,0 @@ -/// -/// - -(function () { - - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update); - - function init() { - - myGame.loader.addImageFile('balls', 'assets/sprites/balls.png'); - - myGame.loader.load(); - - } - - var scroller: Phaser.ScrollZone; - - function create() { - - // The source image (balls.png) is only 102x17 in size, but we want it to create a scroll the size of the whole game window. - // We can take advantage of the way a ScrollZone can create a seamless pattern for us automatically. - // If you create a ScrollRegion larger than the source texture, it'll create a DynamicTexture and perform a pattern fill on it and use that - // for rendering. - - // We've rounded the height up to 612 because in order to have a seamless pattern it needs to be a multiple of 17 (the height of the source image) - scroller = myGame.add.scrollZone('balls', 0, 0, 800, 612); - - // Some sin/cos data for the movement - myGame.math.sinCosGenerator(256, 4, 4, 2); - - } - - function update() { - - // Cycle through the wave data and apply it to the scroll speed (causes the circular wave motion) - scroller.currentRegion.scrollSpeed.x = myGame.math.shiftSinTable(); - scroller.currentRegion.scrollSpeed.y = myGame.math.shiftCosTable(); - - } - -})(); diff --git a/Tests/scrollzones/blasteroids.js b/Tests/scrollzones/blasteroids.js deleted file mode 100644 index 422197adb..000000000 --- a/Tests/scrollzones/blasteroids.js +++ /dev/null @@ -1,95 +0,0 @@ -/// -/// -(function () { - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update); - function init() { - myGame.loader.addImageFile('nashwan', 'assets/sprites/xenon2_ship.png'); - myGame.loader.addImageFile('starfield', 'assets/misc/starfield.jpg'); - myGame.loader.addImageFile('jet', 'assets/sprites/particle1.png'); - myGame.loader.addImageFile('bullet', 'assets/misc/bullet1.png'); - myGame.loader.load(); - } - var scroller; - var emitter; - var ship; - var bullets; - var speed = 0; - var fireRate = 0; - var shipMotion; - function create() { - scroller = myGame.add.scrollZone('starfield', 0, 0, 1024, 1024); - emitter = myGame.add.emitter(myGame.stage.centerX + 16, myGame.stage.centerY + 12); - emitter.makeParticles('jet', 250, false, 0); - emitter.setRotation(0, 0); - // Looks like a smoke trail! - //emitter.globalCompositeOperation = 'xor'; - // Looks way cool :) - emitter.globalCompositeOperation = 'lighter'; - bullets = myGame.add.group(50); - // Create our bullet pool - for(var i = 0; i < 50; i++) { - var tempBullet = new Phaser.Sprite(myGame, myGame.stage.centerX, myGame.stage.centerY, 'bullet'); - tempBullet.exists = false; - tempBullet.rotationOffset = 90; - tempBullet.setBounds(-100, -100, 900, 700); - tempBullet.outOfBoundsAction = Phaser.GameObject.OUT_OF_BOUNDS_KILL; - bullets.add(tempBullet); - } - ship = myGame.add.sprite(myGame.stage.centerX, myGame.stage.centerY, 'nashwan'); - // We do this because the ship was drawn facing up, but 0 degrees is pointing to the right - ship.rotationOffset = 90; - myGame.input.onDown.add(test, this); - } - function test(event) { - myGame.stage.scale.startFullScreen(); - } - function update() { - ship.angularVelocity = 0; - if(myGame.input.keyboard.isDown(Phaser.Keyboard.LEFT)) { - ship.angularVelocity = -200; - } else if(myGame.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) { - ship.angularVelocity = 200; - } - if(myGame.input.keyboard.isDown(Phaser.Keyboard.UP)) { - speed += 0.1; - if(speed > 10) { - speed = 10; - } - } else { - speed -= 0.1; - if(speed < 0) { - speed = 0; - } - } - shipMotion = myGame.motion.velocityFromAngle(ship.angle, speed); - scroller.setSpeed(shipMotion.x, shipMotion.y); - // emit particles - if(speed > 2) { - // We use the opposite of the motion because the jets emit out the back of the ship - // The 20 and 30 values just keep them nice and fast - emitter.setXSpeed(-(shipMotion.x * 20), -(shipMotion.x * 30)); - emitter.setYSpeed(-(shipMotion.y * 20), -(shipMotion.y * 30)); - emitter.emitParticle(); - } - if(myGame.input.keyboard.isDown(Phaser.Keyboard.SPACEBAR)) { - fire(); - } - } - function recycleBullet(bullet) { - if(bullet.exists && bullet.x < -40 || bullet.x > 840 || bullet.y < -40 || bullet.y > 640) { - bullet.exists = false; - } - } - function fire() { - if(myGame.time.now > fireRate) { - var b = bullets.getFirstAvailable(); - b.x = ship.x; - b.y = ship.y - 26; - var bulletMotion = myGame.motion.velocityFromAngle(ship.angle, 400); - b.revive(); - b.angle = ship.angle; - b.velocity.setTo(bulletMotion.x, bulletMotion.y); - fireRate = myGame.time.now + 100; - } - } -})(); diff --git a/Tests/scrollzones/blasteroids.ts b/Tests/scrollzones/blasteroids.ts deleted file mode 100644 index c7cf776d1..000000000 --- a/Tests/scrollzones/blasteroids.ts +++ /dev/null @@ -1,151 +0,0 @@ -/// -/// - -(function () { - - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update); - - function init() { - - myGame.loader.addImageFile('nashwan', 'assets/sprites/xenon2_ship.png'); - myGame.loader.addImageFile('starfield', 'assets/misc/starfield.jpg'); - myGame.loader.addImageFile('jet', 'assets/sprites/particle1.png'); - myGame.loader.addImageFile('bullet', 'assets/misc/bullet1.png'); - - myGame.loader.load(); - - } - - var scroller: Phaser.ScrollZone; - var emitter: Phaser.Emitter; - var ship: Phaser.Sprite; - var bullets: Phaser.Group; - - var speed: number = 0; - var fireRate: number = 0; - var shipMotion: Phaser.Point; - - function create() { - - scroller = myGame.add.scrollZone('starfield', 0, 0, 1024, 1024); - - emitter = myGame.add.emitter(myGame.stage.centerX + 16, myGame.stage.centerY + 12); - emitter.makeParticles('jet', 250, false, 0); - emitter.setRotation(0, 0); - - // Looks like a smoke trail! - //emitter.globalCompositeOperation = 'xor'; - - // Looks way cool :) - emitter.globalCompositeOperation = 'lighter'; - - bullets = myGame.add.group(50); - - // Create our bullet pool - for (var i = 0; i < 50; i++) - { - var tempBullet = new Phaser.Sprite(myGame, myGame.stage.centerX, myGame.stage.centerY, 'bullet'); - tempBullet.exists = false; - tempBullet.rotationOffset = 90; - tempBullet.setBounds(-100, -100, 900, 700); - tempBullet.outOfBoundsAction = Phaser.GameObject.OUT_OF_BOUNDS_KILL; - bullets.add(tempBullet); - } - - ship = myGame.add.sprite(myGame.stage.centerX, myGame.stage.centerY, 'nashwan'); - - // We do this because the ship was drawn facing up, but 0 degrees is pointing to the right - ship.rotationOffset = 90; - - myGame.input.onDown.add(test, this); - - } - - function test(event) { - - myGame.stage.scale.startFullScreen(); - - } - - function update() { - - ship.angularVelocity = 0; - - if (myGame.input.keyboard.isDown(Phaser.Keyboard.LEFT)) - { - ship.angularVelocity = -200; - } - else if (myGame.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) - { - ship.angularVelocity = 200; - } - - if (myGame.input.keyboard.isDown(Phaser.Keyboard.UP)) - { - speed += 0.1; - - if (speed > 10) - { - speed = 10; - } - } - else - { - speed -= 0.1; - - if (speed < 0) { - speed = 0; - } - } - - shipMotion = myGame.motion.velocityFromAngle(ship.angle, speed); - - scroller.setSpeed(shipMotion.x, shipMotion.y); - - // emit particles - if (speed > 2) - { - // We use the opposite of the motion because the jets emit out the back of the ship - // The 20 and 30 values just keep them nice and fast - emitter.setXSpeed(-(shipMotion.x * 20), -(shipMotion.x * 30)); - emitter.setYSpeed(-(shipMotion.y * 20), -(shipMotion.y * 30)); - emitter.emitParticle(); - } - - if (myGame.input.keyboard.isDown(Phaser.Keyboard.SPACEBAR)) - { - fire(); - } - - } - - function recycleBullet(bullet:Phaser.Sprite) { - - if (bullet.exists && bullet.x < -40 || bullet.x > 840 || bullet.y < -40 || bullet.y > 640) - { - bullet.exists = false; - } - - } - - function fire() { - - if (myGame.time.now > fireRate) - { - var b:Phaser.Sprite = bullets.getFirstAvailable(); - - b.x = ship.x; - b.y = ship.y - 26; - - var bulletMotion = myGame.motion.velocityFromAngle(ship.angle, 400); - - b.revive(); - b.angle = ship.angle; - b.velocity.setTo(bulletMotion.x, bulletMotion.y); - - fireRate = myGame.time.now + 100; - } - - } - -})(); diff --git a/Tests/scrollzones/parallax.js b/Tests/scrollzones/parallax.js deleted file mode 100644 index d3e91cb43..000000000 --- a/Tests/scrollzones/parallax.js +++ /dev/null @@ -1,31 +0,0 @@ -/// -/// -(function () { - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create); - function init() { - myGame.loader.addImageFile('starray', 'assets/pics/auto_scroll_landscape.png'); - myGame.loader.load(); - } - function create() { - var zone = myGame.add.scrollZone('starray'); - // Hide the default region (the full image) - zone.currentRegion.visible = false; - var y = 0; - var speed = 16; - // The image consists of 10px high scrolling layers, this creates them quickly (top = fastest, getting slower as we move down) - for(var z = 0; z < 32; z++) { - zone.addRegion(0, y, 640, 10, speed); - if(z <= 15) { - speed -= 1; - } else { - speed += 1; - } - if(z == 15) { - y = 240; - speed += 1; - } else { - y += 10; - } - } - } -})(); diff --git a/Tests/scrollzones/parallax.ts b/Tests/scrollzones/parallax.ts deleted file mode 100644 index 5f74a2946..000000000 --- a/Tests/scrollzones/parallax.ts +++ /dev/null @@ -1,53 +0,0 @@ -/// -/// - -(function () { - - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create); - - function init() { - - myGame.loader.addImageFile('starray', 'assets/pics/auto_scroll_landscape.png'); - - myGame.loader.load(); - - } - - function create() { - - var zone: Phaser.ScrollZone = myGame.add.scrollZone('starray'); - - // Hide the default region (the full image) - zone.currentRegion.visible = false; - - var y:number = 0; - var speed:number = 16; - - // The image consists of 10px high scrolling layers, this creates them quickly (top = fastest, getting slower as we move down) - for (var z:number = 0; z < 32; z++) - { - zone.addRegion(0, y, 640, 10, speed); - - if (z <= 15) - { - speed -= 1; - } - else - { - speed += 1; - } - - if (z == 15) - { - y = 240; - speed += 1; - } - else - { - y += 10; - } - } - - } - -})(); diff --git a/Tests/scrollzones/region demo.js b/Tests/scrollzones/region demo.js deleted file mode 100644 index 9a0f1d294..000000000 --- a/Tests/scrollzones/region demo.js +++ /dev/null @@ -1,22 +0,0 @@ -/// -/// -(function () { - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create); - function init() { - myGame.loader.addImageFile('angelDawn', 'assets/pics/game14_angel_dawn.png'); - myGame.loader.load(); - } - var scroller; - function create() { - // This creates our ScrollZone centered in the middle of the stage. - scroller = myGame.add.scrollZone('angelDawn', myGame.stage.centerX - 320, 100); - // By default we won't scroll the full image, but we will create 3 ScrollRegions within it: - // This creates a ScrollRegion which can be thought of as a rectangle within the ScrollZone that can be scrolled - // independantly - this one scrolls the image of the spacemans head - scroller.addRegion(32, 32, 352, 240, 0, 2); - // The head in the top right - scroller.addRegion(480, 30, 96, 96, 4, 0); - // The small piece of text - scroller.addRegion(466, 160, 122, 14, 0, -0.5); - } -})(); diff --git a/Tests/scrollzones/region demo.ts b/Tests/scrollzones/region demo.ts deleted file mode 100644 index beabb6f0c..000000000 --- a/Tests/scrollzones/region demo.ts +++ /dev/null @@ -1,37 +0,0 @@ -/// -/// - -(function () { - - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create); - - function init() { - - myGame.loader.addImageFile('angelDawn', 'assets/pics/game14_angel_dawn.png'); - - myGame.loader.load(); - - } - - var scroller: Phaser.ScrollZone; - - function create() { - - // This creates our ScrollZone centered in the middle of the stage. - scroller = myGame.add.scrollZone('angelDawn', myGame.stage.centerX - 320, 100); - - // By default we won't scroll the full image, but we will create 3 ScrollRegions within it: - - // This creates a ScrollRegion which can be thought of as a rectangle within the ScrollZone that can be scrolled - // independantly - this one scrolls the image of the spacemans head - scroller.addRegion(32, 32, 352, 240, 0, 2); - - // The head in the top right - scroller.addRegion(480, 30, 96, 96, 4, 0); - - // The small piece of text - scroller.addRegion(466, 160, 122, 14, 0, -0.5); - - } - -})(); diff --git a/Tests/scrollzones/scroll window.js b/Tests/scrollzones/scroll window.js deleted file mode 100644 index 835558c63..000000000 --- a/Tests/scrollzones/scroll window.js +++ /dev/null @@ -1,18 +0,0 @@ -/// -/// -(function () { - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create); - function init() { - myGame.loader.addImageFile('dragonsun', 'assets/pics/cougar_dragonsun.png'); - myGame.loader.addImageFile('overlay', 'assets/pics/scrollframe.png'); - myGame.loader.load(); - } - var scroller; - function create() { - // This creates our ScrollZone. It is positioned at x32 y32 (world coodinates) - // and is a size of 352x240 (which matches the window in our overlay image) - scroller = myGame.add.scrollZone('dragonsun', 32, 32, 352, 240); - scroller.setSpeed(2, 2); - myGame.add.sprite(0, 0, 'overlay'); - } -})(); diff --git a/Tests/scrollzones/scroll window.ts b/Tests/scrollzones/scroll window.ts deleted file mode 100644 index 52f1ebbbf..000000000 --- a/Tests/scrollzones/scroll window.ts +++ /dev/null @@ -1,31 +0,0 @@ -/// -/// - -(function () { - - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create); - - function init() { - - myGame.loader.addImageFile('dragonsun', 'assets/pics/cougar_dragonsun.png'); - myGame.loader.addImageFile('overlay', 'assets/pics/scrollframe.png'); - - myGame.loader.load(); - - } - - var scroller: Phaser.ScrollZone; - - function create() { - - // This creates our ScrollZone. It is positioned at x32 y32 (world coodinates) - // and is a size of 352x240 (which matches the window in our overlay image) - scroller = myGame.add.scrollZone('dragonsun', 32, 32, 352, 240); - - scroller.setSpeed(2, 2); - - myGame.add.sprite(0, 0, 'overlay'); - - } - -})(); diff --git a/Tests/scrollzones/simple scrollzone.js b/Tests/scrollzones/simple scrollzone.js deleted file mode 100644 index 4b2466c6a..000000000 --- a/Tests/scrollzones/simple scrollzone.js +++ /dev/null @@ -1,16 +0,0 @@ -/// -/// -(function () { - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create); - function init() { - myGame.loader.addImageFile('crystal', 'assets/pics/jim_sachs_time_crystal.png'); - myGame.loader.load(); - } - function create() { - // This creates our ScrollZone. It is positioned at x0 y0 (world coodinates) by default and uses - // the 'crystal' image from the cache. - // The default is for the scroll zone to create 1 new scrolling region the size of the whole image you gave it. - // For this example we'll keep that, but look at the other tests to see reasons why you may not want to. - myGame.add.scrollZone('crystal').setSpeed(4, 2); - } -})(); diff --git a/Tests/scrollzones/simple scrollzone.ts b/Tests/scrollzones/simple scrollzone.ts deleted file mode 100644 index 31ecfd1db..000000000 --- a/Tests/scrollzones/simple scrollzone.ts +++ /dev/null @@ -1,28 +0,0 @@ -/// -/// - -(function () { - - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create); - - function init() { - - myGame.loader.addImageFile('crystal', 'assets/pics/jim_sachs_time_crystal.png'); - - myGame.loader.load(); - - } - - function create() { - - // This creates our ScrollZone. It is positioned at x0 y0 (world coodinates) by default and uses - // the 'crystal' image from the cache. - - // The default is for the scroll zone to create 1 new scrolling region the size of the whole image you gave it. - // For this example we'll keep that, but look at the other tests to see reasons why you may not want to. - - myGame.add.scrollZone('crystal').setSpeed(4, 2); - - } - -})(); diff --git a/Tests/sprites/align.js b/Tests/sprites/align.js deleted file mode 100644 index 0bbd6f932..000000000 --- a/Tests/sprites/align.js +++ /dev/null @@ -1,27 +0,0 @@ -/// -(function () { - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update); - function init() { - myGame.loader.addImageFile('teddy', 'assets/pics/profil-sad_plush.png'); - myGame.loader.load(); - } - var teddy; - function create() { - teddy = myGame.add.sprite(0, 0, 'teddy'); - teddy.x = myGame.stage.centerX - teddy.width / 2; - teddy.y = myGame.stage.centerY - teddy.height / 2; - myGame.input.onDown.add(click, this); - teddy.renderDebug = true; - } - function click() { - if(teddy.align == Phaser.GameObject.ALIGN_BOTTOM_RIGHT) { - teddy.align = Phaser.GameObject.ALIGN_TOP_LEFT; - } else { - teddy.align++; - } - } - function update() { - teddy.x = myGame.input.x; - teddy.y = myGame.input.y; - } -})(); diff --git a/Tests/sprites/align.ts b/Tests/sprites/align.ts deleted file mode 100644 index be666803d..000000000 --- a/Tests/sprites/align.ts +++ /dev/null @@ -1,50 +0,0 @@ -/// - -(function () { - - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update); - - function init() { - - myGame.loader.addImageFile('teddy', 'assets/pics/profil-sad_plush.png'); - - myGame.loader.load(); - - } - - var teddy: Phaser.Sprite; - - function create() { - - teddy = myGame.add.sprite(0, 0, 'teddy'); - - teddy.x = myGame.stage.centerX - teddy.width / 2; - teddy.y = myGame.stage.centerY - teddy.height / 2; - - myGame.input.onDown.add(click, this); - - teddy.renderDebug = true; - - } - - function click() { - - if (teddy.align == Phaser.GameObject.ALIGN_BOTTOM_RIGHT) - { - teddy.align = Phaser.GameObject.ALIGN_TOP_LEFT; - } - else - { - teddy.align++; - } - - } - - function update() { - - teddy.x = myGame.input.x; - teddy.y = myGame.input.y; - - } - -})(); diff --git a/Tests/sprites/animate by framename.js b/Tests/sprites/animate by framename.js deleted file mode 100644 index 0aaa7c21a..000000000 --- a/Tests/sprites/animate by framename.js +++ /dev/null @@ -1,34 +0,0 @@ -/// -(function () { - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update); - function init() { - myGame.loader.addTextureAtlas('bot', 'assets/sprites/running_bot.png', 'assets/sprites/running_bot.json'); - myGame.loader.load(); - } - var bot; - function create() { - bot = myGame.add.sprite(myGame.stage.width, 300, 'bot'); - // If you are using a Texture Atlas and want to specify the frames of an animation by their name rather than frame index - // then you can use this format: - bot.animations.add('run', [ - 'run00', - 'run01', - 'run02', - 'run03', - 'run04', - 'run05', - 'run06', - 'run07', - 'run08', - 'run09', - 'run10' - ], 10, true, false); - bot.animations.play('run'); - bot.velocity.x = -100; - } - function update() { - if(bot.x < -bot.width) { - bot.x = myGame.stage.width; - } - } -})(); diff --git a/Tests/sprites/animate by framename.ts b/Tests/sprites/animate by framename.ts deleted file mode 100644 index 6d253ca02..000000000 --- a/Tests/sprites/animate by framename.ts +++ /dev/null @@ -1,40 +0,0 @@ -/// - -(function () { - - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update); - - function init() { - - myGame.loader.addTextureAtlas('bot', 'assets/sprites/running_bot.png', 'assets/sprites/running_bot.json'); - - myGame.loader.load(); - - } - - var bot: Phaser.Sprite; - - function create() { - - bot = myGame.add.sprite(myGame.stage.width, 300, 'bot'); - - // If you are using a Texture Atlas and want to specify the frames of an animation by their name rather than frame index - // then you can use this format: - bot.animations.add('run', ['run00', 'run01', 'run02', 'run03', 'run04', 'run05', 'run06', 'run07', 'run08', 'run09', 'run10'], 10, true, false); - - bot.animations.play('run'); - - bot.velocity.x = -100; - - } - - function update() { - - if (bot.x < -bot.width) - { - bot.x = myGame.stage.width; - } - - } - -})(); diff --git a/Tests/sprites/animation 1.js b/Tests/sprites/animation 1.js deleted file mode 100644 index 081eb2118..000000000 --- a/Tests/sprites/animation 1.js +++ /dev/null @@ -1,32 +0,0 @@ -/// -(function () { - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update); - function init() { - myGame.loader.addSpriteSheet('mummy', 'assets/sprites/metalslug_mummy37x45.png', 37, 45, 18); - //myGame.loader.addSpriteSheet('coin', 'assets/sprites/coin.png', 32, 32); - myGame.loader.addSpriteSheet('monster', 'assets/sprites/metalslug_monster39x40.png', 39, 40); - myGame.loader.load(); - } - var car; - function create() { - car = myGame.add.sprite(200, 300, 'monster'); - car.animations.add('spin', null, 30, true); - //car.animations.play('spin', 30, true); - car.animations.play('spin'); - } - function update() { - car.renderDebugInfo(16, 16); - car.velocity.x = 0; - car.velocity.y = 0; - car.angularVelocity = 0; - car.angularAcceleration = 0; - if(myGame.input.keyboard.isDown(Phaser.Keyboard.LEFT)) { - car.angularVelocity = -200; - } else if(myGame.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) { - car.angularVelocity = 200; - } - if(myGame.input.keyboard.isDown(Phaser.Keyboard.UP)) { - car.velocity.copyFrom(myGame.motion.velocityFromAngle(car.angle, 200)); - } - } -})(); diff --git a/Tests/sprites/animation 1.ts b/Tests/sprites/animation 1.ts deleted file mode 100644 index 81d580f6a..000000000 --- a/Tests/sprites/animation 1.ts +++ /dev/null @@ -1,55 +0,0 @@ -/// - -(function () { - - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update); - - function init() { - - myGame.loader.addSpriteSheet('mummy', 'assets/sprites/metalslug_mummy37x45.png', 37, 45, 18); - //myGame.loader.addSpriteSheet('coin', 'assets/sprites/coin.png', 32, 32); - myGame.loader.addSpriteSheet('monster', 'assets/sprites/metalslug_monster39x40.png', 39, 40); - - myGame.loader.load(); - - } - - var car: Phaser.Sprite; - - function create() { - - car = myGame.add.sprite(200, 300, 'monster'); - - car.animations.add('spin', null, 30, true); - - //car.animations.play('spin', 30, true); - car.animations.play('spin'); - - } - - function update() { - - car.renderDebugInfo(16, 16); - - car.velocity.x = 0; - car.velocity.y = 0; - car.angularVelocity = 0; - car.angularAcceleration = 0; - - if (myGame.input.keyboard.isDown(Phaser.Keyboard.LEFT)) - { - car.angularVelocity = -200; - } - else if (myGame.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) - { - car.angularVelocity = 200; - } - - if (myGame.input.keyboard.isDown(Phaser.Keyboard.UP)) - { - car.velocity.copyFrom(myGame.motion.velocityFromAngle(car.angle, 200)); - } - - } - -})(); diff --git a/Tests/sprites/create sprite 1.js b/Tests/sprites/create sprite 1.js new file mode 100644 index 000000000..20145d1a8 --- /dev/null +++ b/Tests/sprites/create sprite 1.js @@ -0,0 +1,14 @@ +/// +(function () { + var game = new Phaser.Game(this, 'game', 800, 600, init, create); + function init() { + // Using Phasers asset loader we load up a PNG from the assets folder + game.loader.addImageFile('bunny', 'assets/sprites/bunny.png'); + game.loader.load(); + } + function create() { + // This will create a Sprite positioned at the top-left of the game (0,0) + // Try changing the 0, 0 values + game.add.sprite(0, 0, 'bunny'); + } +})(); diff --git a/Tests/sprites/create sprite 1.ts b/Tests/sprites/create sprite 1.ts new file mode 100644 index 000000000..d17252014 --- /dev/null +++ b/Tests/sprites/create sprite 1.ts @@ -0,0 +1,23 @@ +/// + +(function () { + + var game = new Phaser.Game(this, 'game', 800, 600, init, create); + + function init() { + + // Using Phasers asset loader we load up a PNG from the assets folder + game.loader.addImageFile('bunny', 'assets/sprites/bunny.png'); + game.loader.load(); + + } + + function create() { + + // This will create a Sprite positioned at the top-left of the game (0,0) + // Try changing the 0, 0 values + game.add.sprite(0, 0, 'bunny'); + + } + +})(); diff --git a/Tests/sprites/dynamic texture 1.js b/Tests/sprites/dynamic texture 1.js deleted file mode 100644 index 89890eb92..000000000 --- a/Tests/sprites/dynamic texture 1.js +++ /dev/null @@ -1,59 +0,0 @@ -/// -(function () { - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update); - function init() { - myGame.loader.addImageFile('ball', 'assets/sprites/shinyball.png'); - myGame.loader.load(); - } - var wobblyBall; - function create() { - // Create our DynamicTexture - wobblyBall = myGame.add.dynamicTexture(32, 64); - // And apply it to 100 randomly positioned sprites - for(var i = 0; i < 100; i++) { - var temp = myGame.add.sprite(myGame.world.randomX, myGame.world.randomY); - temp.width = 32; - temp.height = 64; - temp.loadDynamicTexture(wobblyBall); - } - // Populate the wave with some data - waveData = myGame.math.sinCosGenerator(32, 8, 8, 2); - } - function update() { - wobblyBall.clear(); - updateWobblyBall(); - } - // This creates a simple sine-wave effect running through our DynamicTexture. - // This is then duplicated across all sprites using it, meaning we only have to calculate it once. - var waveSize = 8; - var wavePixelChunk = 2; - var waveData; - var waveDataCounter; - function updateWobblyBall() { - var s = 0; - var copyRect = { - x: 0, - y: 0, - w: wavePixelChunk, - h: 32 - }; - var copyPoint = { - x: 0, - y: 0 - }; - for(var x = 0; x < 32; x += wavePixelChunk) { - copyPoint.x = x; - copyPoint.y = waveSize + (waveSize / 2) + waveData[s]; - wobblyBall.context.drawImage(myGame.cache.getImage('ball'), copyRect.x, copyRect.y, copyRect.w, copyRect.h, copyPoint.x, copyPoint.y, copyRect.w, copyRect.h); - copyRect.x += wavePixelChunk; - s++; - } - // Cycle through the wave data - this is what causes the image to "undulate" - var t = waveData.shift(); - waveData.push(t); - waveDataCounter++; - if(waveDataCounter == waveData.length) { - waveDataCounter = 0; - } - } -})(); diff --git a/Tests/sprites/dynamic texture 1.ts b/Tests/sprites/dynamic texture 1.ts deleted file mode 100644 index 88b75e3a2..000000000 --- a/Tests/sprites/dynamic texture 1.ts +++ /dev/null @@ -1,82 +0,0 @@ -/// - -(function () { - - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update); - - function init() { - - myGame.loader.addImageFile('ball', 'assets/sprites/shinyball.png'); - - myGame.loader.load(); - - } - - var wobblyBall: Phaser.DynamicTexture; - - function create() { - - // Create our DynamicTexture - wobblyBall = myGame.add.dynamicTexture(32, 64); - - // And apply it to 100 randomly positioned sprites - for (var i = 0; i < 100; i++) - { - var temp = myGame.add.sprite(myGame.world.randomX, myGame.world.randomY); - temp.width = 32; - temp.height = 64; - temp.loadDynamicTexture(wobblyBall); - } - - // Populate the wave with some data - waveData = myGame.math.sinCosGenerator(32, 8, 8, 2); - - } - - function update() { - - wobblyBall.clear(); - - updateWobblyBall(); - - } - - // This creates a simple sine-wave effect running through our DynamicTexture. - // This is then duplicated across all sprites using it, meaning we only have to calculate it once. - - var waveSize = 8; - var wavePixelChunk = 2; - var waveData; - var waveDataCounter; - - function updateWobblyBall() - { - var s = 0; - var copyRect = { x: 0, y: 0, w: wavePixelChunk, h: 32 }; - var copyPoint = { x: 0, y: 0 }; - - for (var x = 0; x < 32; x += wavePixelChunk) - { - copyPoint.x = x; - copyPoint.y = waveSize + (waveSize / 2) + waveData[s]; - - wobblyBall.context.drawImage(myGame.cache.getImage('ball'), copyRect.x, copyRect.y, copyRect.w, copyRect.h, copyPoint.x, copyPoint.y, copyRect.w, copyRect.h); - - copyRect.x += wavePixelChunk; - - s++; - } - - // Cycle through the wave data - this is what causes the image to "undulate" - var t = waveData.shift(); - waveData.push(t); - - waveDataCounter++; - - if (waveDataCounter == waveData.length) - { - waveDataCounter = 0; - } - } - -})(); diff --git a/Tests/sprites/dynamic texture 2.js b/Tests/sprites/dynamic texture 2.js deleted file mode 100644 index 5494a16a9..000000000 --- a/Tests/sprites/dynamic texture 2.js +++ /dev/null @@ -1,78 +0,0 @@ -/// -(function () { - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update); - function init() { - myGame.loader.addImageFile('slime', 'assets/sprites/slime.png'); - myGame.loader.addImageFile('eyes', 'assets/sprites/slimeeyes.png'); - myGame.loader.load(); - } - var slime; - var eyes; - var wobble; - function create() { - myGame.camera.backgroundColor = 'rgb(82,154,206)'; - // Create our DynamicTexture - wobble = myGame.add.dynamicTexture(48, 100); - slime = myGame.add.sprite(200, 300); - slime.width = 48; - slime.height = 100; - slime.loadDynamicTexture(wobble); - eyes = myGame.add.sprite(210, 326, 'eyes'); - // Populate the wave with some data - waveData = myGame.math.sinCosGenerator(32, 8, 8, 2); - } - function update() { - wobble.clear(); - updateWobble(); - slime.velocity.x = 0; - slime.velocity.y = 0; - slime.angularVelocity = 0; - eyes.velocity.x = 0; - eyes.velocity.y = 0; - eyes.angularVelocity = 0; - if(myGame.input.keyboard.isDown(Phaser.Keyboard.LEFT)) { - slime.angularVelocity = -200; - eyes.angularVelocity = -200; - } else if(myGame.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) { - slime.angularVelocity = 200; - eyes.angularVelocity = 200; - } - if(myGame.input.keyboard.isDown(Phaser.Keyboard.UP)) { - slime.velocity.copyFrom(myGame.motion.velocityFromAngle(slime.angle, 200)); - eyes.velocity.copyFrom(myGame.motion.velocityFromAngle(slime.angle, 200)); - } - } - // This creates a simple sine-wave effect running through our DynamicTexture. - // This is then duplicated across all sprites using it, meaning we only have to calculate it once. - var waveSize = 8; - var wavePixelChunk = 2; - var waveData; - var waveDataCounter; - function updateWobble() { - var s = 0; - var copyRect = { - x: 0, - y: 0, - w: wavePixelChunk, - h: 52 - }; - var copyPoint = { - x: 0, - y: 0 - }; - for(var x = 0; x < 48; x += wavePixelChunk) { - copyPoint.x = x; - copyPoint.y = waveSize + (waveSize / 2) + waveData[s]; - wobble.context.drawImage(myGame.cache.getImage('slime'), copyRect.x, copyRect.y, copyRect.w, copyRect.h, copyPoint.x, copyPoint.y, copyRect.w, copyRect.h); - copyRect.x += wavePixelChunk; - s++; - } - // Cycle through the wave data - this is what causes the image to "undulate" - var t = waveData.shift(); - waveData.push(t); - waveDataCounter++; - if(waveDataCounter == waveData.length) { - waveDataCounter = 0; - } - } -})(); diff --git a/Tests/sprites/dynamic texture 2.ts b/Tests/sprites/dynamic texture 2.ts deleted file mode 100644 index e5c83faa8..000000000 --- a/Tests/sprites/dynamic texture 2.ts +++ /dev/null @@ -1,109 +0,0 @@ -/// - -(function () { - - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update); - - function init() { - - myGame.loader.addImageFile('slime', 'assets/sprites/slime.png'); - myGame.loader.addImageFile('eyes', 'assets/sprites/slimeeyes.png'); - - myGame.loader.load(); - - } - - var slime: Phaser.Sprite; - var eyes: Phaser.Sprite; - var wobble: Phaser.DynamicTexture; - - function create() { - - myGame.camera.backgroundColor = 'rgb(82,154,206)'; - - // Create our DynamicTexture - wobble = myGame.add.dynamicTexture(48, 100); - - slime = myGame.add.sprite(200, 300); - slime.width = 48; - slime.height = 100; - slime.loadDynamicTexture(wobble); - - eyes = myGame.add.sprite(210, 326, 'eyes'); - - // Populate the wave with some data - waveData = myGame.math.sinCosGenerator(32, 8, 8, 2); - - } - - function update() { - - wobble.clear(); - - updateWobble(); - - slime.velocity.x = 0; - slime.velocity.y = 0; - slime.angularVelocity = 0; - eyes.velocity.x = 0; - eyes.velocity.y = 0; - eyes.angularVelocity = 0; - - if (myGame.input.keyboard.isDown(Phaser.Keyboard.LEFT)) - { - slime.angularVelocity = -200; - eyes.angularVelocity = -200; - } - else if (myGame.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) - { - slime.angularVelocity = 200; - eyes.angularVelocity = 200; - } - - if (myGame.input.keyboard.isDown(Phaser.Keyboard.UP)) - { - slime.velocity.copyFrom(myGame.motion.velocityFromAngle(slime.angle, 200)); - eyes.velocity.copyFrom(myGame.motion.velocityFromAngle(slime.angle, 200)); - } - - } - - // This creates a simple sine-wave effect running through our DynamicTexture. - // This is then duplicated across all sprites using it, meaning we only have to calculate it once. - - var waveSize = 8; - var wavePixelChunk = 2; - var waveData; - var waveDataCounter; - - function updateWobble() - { - var s = 0; - var copyRect = { x: 0, y: 0, w: wavePixelChunk, h: 52 }; - var copyPoint = { x: 0, y: 0 }; - - for (var x = 0; x < 48; x += wavePixelChunk) - { - copyPoint.x = x; - copyPoint.y = waveSize + (waveSize / 2) + waveData[s]; - - wobble.context.drawImage(myGame.cache.getImage('slime'), copyRect.x, copyRect.y, copyRect.w, copyRect.h, copyPoint.x, copyPoint.y, copyRect.w, copyRect.h); - - copyRect.x += wavePixelChunk; - - s++; - } - - // Cycle through the wave data - this is what causes the image to "undulate" - var t = waveData.shift(); - waveData.push(t); - - waveDataCounter++; - - if (waveDataCounter == waveData.length) - { - waveDataCounter = 0; - } - } - -})(); diff --git a/Tests/sprites/flipped.js b/Tests/sprites/flipped.js deleted file mode 100644 index a176e5ddf..000000000 --- a/Tests/sprites/flipped.js +++ /dev/null @@ -1,42 +0,0 @@ -/// -(function () { - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update); - function init() { - myGame.loader.addTextureAtlas('bot', 'assets/sprites/running_bot.png', 'assets/sprites/running_bot.json'); - myGame.loader.addTextureAtlas('atlas', 'assets/pics/texturepacker_test.png', 'assets/pics/texturepacker_test.json'); - myGame.loader.load(); - } - var bot; - var bot2; - var car; - function create() { - // This bot will flip properly when he reaches the edge - bot = myGame.add.sprite(myGame.stage.width, 300, 'bot'); - bot.animations.add('run'); - bot.animations.play('run', 10, true); - bot.velocity.x = -200; - // This one won't - bot2 = myGame.add.sprite(myGame.stage.width, 200, 'bot'); - bot2.animations.add('run'); - bot2.animations.play('run', 10, true); - bot2.velocity.x = -150; - // Flip a static sprite (not an animation) - car = myGame.add.sprite(100, 400, 'atlas'); - car.frameName = 'supercars_parsec.png'; - car.flipped = true; - } - function update() { - if(bot.x < -bot.width) { - bot.flipped = true; - bot.velocity.x = 200; - } else if(bot.x > myGame.stage.width) { - bot.flipped = false; - bot.velocity.x = -200; - } - if(bot2.x < -bot2.width) { - bot2.velocity.x = 200; - } else if(bot2.x > myGame.stage.width) { - bot2.velocity.x = -200; - } - } -})(); diff --git a/Tests/sprites/flipped.ts b/Tests/sprites/flipped.ts deleted file mode 100644 index 19b6052ce..000000000 --- a/Tests/sprites/flipped.ts +++ /dev/null @@ -1,64 +0,0 @@ -/// - -(function () { - - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update); - - function init() { - - myGame.loader.addTextureAtlas('bot', 'assets/sprites/running_bot.png', 'assets/sprites/running_bot.json'); - myGame.loader.addTextureAtlas('atlas', 'assets/pics/texturepacker_test.png', 'assets/pics/texturepacker_test.json'); - myGame.loader.load(); - - } - - var bot: Phaser.Sprite; - var bot2: Phaser.Sprite; - var car: Phaser.Sprite; - - function create() { - - // This bot will flip properly when he reaches the edge - bot = myGame.add.sprite(myGame.stage.width, 300, 'bot'); - bot.animations.add('run'); - bot.animations.play('run', 10, true); - bot.velocity.x = -200; - - // This one won't - bot2 = myGame.add.sprite(myGame.stage.width, 200, 'bot'); - bot2.animations.add('run'); - bot2.animations.play('run', 10, true); - bot2.velocity.x = -150; - - // Flip a static sprite (not an animation) - car = myGame.add.sprite(100, 400, 'atlas'); - car.frameName = 'supercars_parsec.png'; - car.flipped = true; - - } - - function update() { - - if (bot.x < -bot.width) - { - bot.flipped = true; - bot.velocity.x = 200; - } - else if (bot.x > myGame.stage.width) - { - bot.flipped = false; - bot.velocity.x = -200; - } - - if (bot2.x < -bot2.width) - { - bot2.velocity.x = 200; - } - else if (bot2.x > myGame.stage.width) - { - bot2.velocity.x = -200; - } - - } - -})(); diff --git a/Tests/sprites/mark of the bunny.js b/Tests/sprites/mark of the bunny.js deleted file mode 100644 index fcaa675a0..000000000 --- a/Tests/sprites/mark of the bunny.js +++ /dev/null @@ -1,56 +0,0 @@ -/// -(function () { - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update); - function init() { - myGame.loader.addImageFile('bunny', 'assets/sprites/wabbit.png'); - myGame.loader.load(); - } - var maxX; - var maxY; - var minX; - var minY; - var fps; - function create() { - // FPS counter TextArea - fps = document.createElement('textarea'); - fps.style.width = '300px'; - fps.style.height = '100px'; - document.getElementById('game').appendChild(fps); - minX = 0; - minY = 0; - maxX = myGame.stage.width - 26; - maxY = myGame.stage.height - 37; - addBunnies(500); - } - function addBunnies(quantity) { - for(var i = 0; i < quantity; i++) { - var tempSprite = myGame.add.sprite(myGame.stage.randomX, 0, 'bunny'); - tempSprite.velocity.x = -200 + (Math.random() * 400); - tempSprite.velocity.y = 100 + Math.random() * 200; - } - } - function update() { - fps.textContent = 'Press Up to add more\n\nBunnies: ' + myGame.world.group.length + '\nFPS: ' + myGame.time.fps + ' (' + myGame.time.fpsMin + '-' + myGame.time.fpsMax + ')'; - myGame.world.group.forEach(checkWalls); - if(myGame.input.keyboard.isDown(Phaser.Keyboard.UP)) { - addBunnies(10); - } - } - function checkWalls(bunny) { - if(bunny.x > maxX) { - bunny.velocity.x *= -1; - bunny.x = maxX; - } else if(bunny.x < minX) { - bunny.velocity.x *= -1; - bunny.x = minX; - } - if(bunny.y > maxY) { - bunny.velocity.y *= -0.8; - bunny.y = maxY; - } else if(bunny.y < minY) { - bunny.velocity.x = -200 + (Math.random() * 400); - bunny.velocity.y = 100 + Math.random() * 200; - bunny.y = minY; - } - } -})(); diff --git a/Tests/sprites/mark of the bunny.ts b/Tests/sprites/mark of the bunny.ts deleted file mode 100644 index cd8af7d85..000000000 --- a/Tests/sprites/mark of the bunny.ts +++ /dev/null @@ -1,89 +0,0 @@ -/// - -(function () { - - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update); - - function init() { - - myGame.loader.addImageFile('bunny', 'assets/sprites/wabbit.png'); - - myGame.loader.load(); - - } - - var maxX: number; - var maxY: number; - var minX: number; - var minY: number; - var fps: HTMLTextAreaElement; - - function create() { - - // FPS counter TextArea - fps = document.createElement('textarea'); - fps.style.width = '300px'; - fps.style.height = '100px'; - document.getElementById('game').appendChild(fps); - - minX = 0; - minY = 0; - maxX = myGame.stage.width - 26; - maxY = myGame.stage.height - 37; - - addBunnies(500); - - } - - function addBunnies(quantity) { - - for (var i = 0; i < quantity; i++) - { - var tempSprite = myGame.add.sprite(myGame.stage.randomX, 0, 'bunny'); - tempSprite.velocity.x = -200 + (Math.random() * 400); - tempSprite.velocity.y = 100 + Math.random() * 200; - } - - } - - function update() { - - fps.textContent = 'Press Up to add more\n\nBunnies: ' + myGame.world.group.length + '\nFPS: ' + myGame.time.fps + ' (' + myGame.time.fpsMin + '-' + myGame.time.fpsMax + ')'; - - myGame.world.group.forEach(checkWalls); - - if (myGame.input.keyboard.isDown(Phaser.Keyboard.UP)) - { - addBunnies(10); - } - - } - - function checkWalls(bunny:Phaser.Sprite) { - - if (bunny.x > maxX) - { - bunny.velocity.x *= -1; - bunny.x = maxX; - } - else if (bunny.x < minX) - { - bunny.velocity.x *= -1; - bunny.x = minX; - } - - if (bunny.y > maxY) - { - bunny.velocity.y *= -0.8; - bunny.y = maxY; - } - else if (bunny.y < minY) - { - bunny.velocity.x = -200 + (Math.random() * 400); - bunny.velocity.y = 100 + Math.random() * 200; - bunny.y = minY; - } - - } - -})(); diff --git a/Tests/sprites/rotation.js b/Tests/sprites/rotation.js deleted file mode 100644 index a338099a9..000000000 --- a/Tests/sprites/rotation.js +++ /dev/null @@ -1,22 +0,0 @@ -/// -(function () { - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update); - function init() { - myGame.loader.addImageFile('teddy', 'assets/pics/profil-sad_plush.png'); - myGame.loader.load(); - } - var teddy; - function create() { - teddy = myGame.add.sprite(0, 0, 'teddy'); - teddy.x = myGame.stage.centerX - teddy.width / 2; - teddy.y = myGame.stage.centerY - teddy.height / 2; - teddy.renderDebug = true; - } - function update() { - if(myGame.input.keyboard.isDown(Phaser.Keyboard.LEFT)) { - teddy.angularAcceleration = -40; - } else if(myGame.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) { - teddy.angularAcceleration = 40; - } - } -})(); diff --git a/Tests/sprites/rotation.ts b/Tests/sprites/rotation.ts deleted file mode 100644 index 52e629ab8..000000000 --- a/Tests/sprites/rotation.ts +++ /dev/null @@ -1,39 +0,0 @@ -/// - -(function () { - - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update); - - function init() { - - myGame.loader.addImageFile('teddy', 'assets/pics/profil-sad_plush.png'); - - myGame.loader.load(); - - } - - var teddy: Phaser.Sprite; - - function create() { - - teddy = myGame.add.sprite(0, 0, 'teddy'); - teddy.x = myGame.stage.centerX - teddy.width / 2; - teddy.y = myGame.stage.centerY - teddy.height / 2; - teddy.renderDebug = true; - - } - - function update() { - - if (myGame.input.keyboard.isDown(Phaser.Keyboard.LEFT)) - { - teddy.angularAcceleration = -40; - } - else if (myGame.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) - { - teddy.angularAcceleration = 40; - } - - } - -})(); diff --git a/Tests/sprites/scale origin 1.js b/Tests/sprites/scale origin 1.js new file mode 100644 index 000000000..7123cfe99 --- /dev/null +++ b/Tests/sprites/scale origin 1.js @@ -0,0 +1,58 @@ +/// +(function () { + var game = new Phaser.Game(this, 'game', 800, 600, init, create); + function init() { + // Using Phasers asset loader we load up a PNG from the assets folder + game.loader.addImageFile('fuji', 'assets/pics/atari_fujilogo.png'); + game.loader.load(); + } + var fuji; + var tween; + function create() { + game.stage.backgroundColor = 'rgb(0,0,100)'; + // Here we'll assign the new sprite to the local fuji variable + fuji = game.add.sprite(100, 200, 'fuji'); + // The sprite is 320 x 200 pixels in size + //fuji.origin.setTo(160, 0); + fuji.origin.setTo(160, 100); + //fuji.origin.setTo(320, 0); + //fuji.origin.setTo(320, 200); + //fuji.origin.setTo(260, 100); + fuji.scale.x = 2; + fuji.scale.y = 0.5; + //fuji.position.rotation = 45; + game.add.tween(fuji.position).to({ + rotation: 360 + }, 3000).start(); + // Create our tween + //tween = game.add.tween(fuji.scale); + //tween = game.add.tween(fuji.scale); + // Start it going + //scaleLeft(); + } + function rotate() { + tween.to({ + x: 0 + }, 1000); + tween.onComplete.add(scaleRight, this); + tween.start(); + } + function scaleLeft() { + tween.clear(); + tween.to({ + x: 0 + }, 1000); + tween.onComplete.add(scaleRight, this); + tween.start(); + } + function scaleRight() { + tween.clear(); + tween.to({ + x: 1 + }, 1000); + tween.onComplete.add(scaleLeft, this); + tween.start(); + // This line says "if the texture is flippedX then unflip it (set flippedX to false), otherwise set flippedX to true + (fuji.texture.flippedX) ? fuji.texture.flippedX = false : fuji.texture.flippedX = true; + } +})(); diff --git a/Tests/sprites/scale origin 1.ts b/Tests/sprites/scale origin 1.ts new file mode 100644 index 000000000..ba83efe1e --- /dev/null +++ b/Tests/sprites/scale origin 1.ts @@ -0,0 +1,75 @@ +/// + +(function () { + + var game = new Phaser.Game(this, 'game', 800, 600, init, create); + + function init() { + + // Using Phasers asset loader we load up a PNG from the assets folder + game.loader.addImageFile('fuji', 'assets/pics/atari_fujilogo.png'); + game.loader.load(); + + } + + var fuji: Phaser.Sprite; + var tween: Phaser.Tween; + + function create() { + + game.stage.backgroundColor = 'rgb(0,0,100)'; + + // Here we'll assign the new sprite to the local fuji variable + fuji = game.add.sprite(100, 200, 'fuji'); + + // The sprite is 320 x 200 pixels in size + //fuji.origin.setTo(160, 0); + fuji.origin.setTo(160, 100); + //fuji.origin.setTo(320, 0); + //fuji.origin.setTo(320, 200); + + //fuji.origin.setTo(260, 100); + fuji.scale.x = 2; + fuji.scale.y = 0.5; + //fuji.position.rotation = 45; + game.add.tween(fuji.position).to({ rotation: 360 }, 3000).start(); + + // Create our tween + //tween = game.add.tween(fuji.scale); + //tween = game.add.tween(fuji.scale); + + // Start it going + //scaleLeft(); + + } + + function rotate() { + + tween.to({ x: 0 }, 1000); + tween.onComplete.add(scaleRight, this); + tween.start(); + + } + + function scaleLeft() { + + tween.clear(); + tween.to({ x: 0 }, 1000); + tween.onComplete.add(scaleRight, this); + tween.start(); + + } + + function scaleRight() { + + tween.clear(); + tween.to({ x: 1 }, 1000); + tween.onComplete.add(scaleLeft, this); + tween.start(); + + // This line says "if the texture is flippedX then unflip it (set flippedX to false), otherwise set flippedX to true + (fuji.texture.flippedX) ? fuji.texture.flippedX = false: fuji.texture.flippedX = true; + + } + +})(); diff --git a/Tests/sprites/scale sprite 1.js b/Tests/sprites/scale sprite 1.js new file mode 100644 index 000000000..baef3bb0a --- /dev/null +++ b/Tests/sprites/scale sprite 1.js @@ -0,0 +1,20 @@ +/// +(function () { + var game = new Phaser.Game(this, 'game', 800, 600, init, create); + function init() { + // Using Phasers asset loader we load up a PNG from the assets folder + game.loader.addImageFile('bunny', 'assets/sprites/bunny.png'); + game.loader.load(); + } + var smallBunny; + function create() { + // Here we'll assign the new sprite to the local smallBunny variable + smallBunny = game.add.sprite(0, 0, 'bunny'); + // And now let's scale the sprite in half + // You can do either: + // smallBunny.scale.x = 0.5; + // smallBunny.scale.y = 0.5; + // Or you can set them both at the same time using setTo: + smallBunny.scale.setTo(0.5, 0.5); + } +})(); diff --git a/Tests/sprites/scale sprite 1.ts b/Tests/sprites/scale sprite 1.ts new file mode 100644 index 000000000..d5c5c2ede --- /dev/null +++ b/Tests/sprites/scale sprite 1.ts @@ -0,0 +1,33 @@ +/// + +(function () { + + var game = new Phaser.Game(this, 'game', 800, 600, init, create); + + function init() { + + // Using Phasers asset loader we load up a PNG from the assets folder + game.loader.addImageFile('bunny', 'assets/sprites/bunny.png'); + game.loader.load(); + + } + + var smallBunny: Phaser.Sprite; + + function create() { + + // Here we'll assign the new sprite to the local smallBunny variable + smallBunny = game.add.sprite(0, 0, 'bunny'); + + // And now let's scale the sprite in half + + // You can do either: + // smallBunny.scale.x = 0.5; + // smallBunny.scale.y = 0.5; + + // Or you can set them both at the same time using setTo: + smallBunny.scale.setTo(0.5, 0.5); + + } + +})(); diff --git a/Tests/sprites/scale sprite 2.js b/Tests/sprites/scale sprite 2.js new file mode 100644 index 000000000..298b25599 --- /dev/null +++ b/Tests/sprites/scale sprite 2.js @@ -0,0 +1,20 @@ +/// +(function () { + var game = new Phaser.Game(this, 'game', 800, 600, init, create); + function init() { + // Using Phasers asset loader we load up a PNG from the assets folder + game.loader.addImageFile('bunny', 'assets/sprites/bunny.png'); + game.loader.load(); + } + var bigBunny; + function create() { + // Here we'll assign the new sprite to the local bigBunny variable + bigBunny = game.add.sprite(0, 0, 'bunny'); + // And now let's scale the sprite by two + // You can do either: + // smallBunny.scale.x = 2; + // smallBunny.scale.y = 2; + // Or you can set them both at the same time using setTo: + bigBunny.scale.setTo(2, 2); + } +})(); diff --git a/Tests/sprites/scale sprite 2.ts b/Tests/sprites/scale sprite 2.ts new file mode 100644 index 000000000..95a24e60b --- /dev/null +++ b/Tests/sprites/scale sprite 2.ts @@ -0,0 +1,33 @@ +/// + +(function () { + + var game = new Phaser.Game(this, 'game', 800, 600, init, create); + + function init() { + + // Using Phasers asset loader we load up a PNG from the assets folder + game.loader.addImageFile('bunny', 'assets/sprites/bunny.png'); + game.loader.load(); + + } + + var bigBunny: Phaser.Sprite; + + function create() { + + // Here we'll assign the new sprite to the local bigBunny variable + bigBunny = game.add.sprite(0, 0, 'bunny'); + + // And now let's scale the sprite by two + + // You can do either: + // smallBunny.scale.x = 2; + // smallBunny.scale.y = 2; + + // Or you can set them both at the same time using setTo: + bigBunny.scale.setTo(2, 2); + + } + +})(); diff --git a/Tests/sprites/scale sprite 3.js b/Tests/sprites/scale sprite 3.js new file mode 100644 index 000000000..6cfbb5b69 --- /dev/null +++ b/Tests/sprites/scale sprite 3.js @@ -0,0 +1,17 @@ +/// +(function () { + var game = new Phaser.Game(this, 'game', 800, 600, init, create); + function init() { + // Using Phasers asset loader we load up a PNG from the assets folder + game.loader.addImageFile('bunny', 'assets/sprites/bunny.png'); + game.loader.load(); + } + var bunny; + function create() { + // Here we'll assign the new sprite to the local bunny variable + bunny = game.add.sprite(0, 0, 'bunny'); + // You don't have to use the same values when scaling a sprite, + // here we'll create a short and wide bunny + bunny.scale.setTo(3, 0.7); + } +})(); diff --git a/Tests/sprites/scale sprite 3.ts b/Tests/sprites/scale sprite 3.ts new file mode 100644 index 000000000..f4ee18984 --- /dev/null +++ b/Tests/sprites/scale sprite 3.ts @@ -0,0 +1,29 @@ +/// + +(function () { + + var game = new Phaser.Game(this, 'game', 800, 600, init, create); + + function init() { + + // Using Phasers asset loader we load up a PNG from the assets folder + game.loader.addImageFile('bunny', 'assets/sprites/bunny.png'); + game.loader.load(); + + } + + var bunny: Phaser.Sprite; + + function create() { + + // Here we'll assign the new sprite to the local bunny variable + bunny = game.add.sprite(0, 0, 'bunny'); + + // You don't have to use the same values when scaling a sprite, + // here we'll create a short and wide bunny + + bunny.scale.setTo(3, 0.7); + + } + +})(); diff --git a/Tests/sprites/scale sprite 4.js b/Tests/sprites/scale sprite 4.js new file mode 100644 index 000000000..73f09f146 --- /dev/null +++ b/Tests/sprites/scale sprite 4.js @@ -0,0 +1,39 @@ +/// +(function () { + var game = new Phaser.Game(this, 'game', 800, 600, init, create); + function init() { + // Using Phasers asset loader we load up a PNG from the assets folder + game.loader.addImageFile('bunny', 'assets/sprites/bunny.png'); + game.loader.load(); + } + var bunny; + var tweenUp; + var tweenDown; + function create() { + // Here we'll assign the new sprite to the local bunny variable + bunny = game.add.sprite(0, 0, 'bunny'); + // This time let's scale the sprite by using two tweens + // The first tween will scale the sprite up, the second will scale it down again + // Create our 2 tweens + tweenUp = game.add.tween(bunny.scale); + tweenUp.onComplete.add(scaleDown, this); + tweenDown = game.add.tween(bunny.scale); + tweenDown.onComplete.add(scaleUp, this); + // Start it going + scaleUp(); + } + function scaleUp() { + tweenUp.to({ + x: 2, + y: 2 + }, 2000, Phaser.Easing.Elastic.Out); + tweenUp.start(); + } + function scaleDown() { + tweenDown.to({ + x: 0.5, + y: 0.5 + }, 2000, Phaser.Easing.Elastic.Out); + tweenDown.start(); + } +})(); diff --git a/Tests/sprites/scale sprite 4.ts b/Tests/sprites/scale sprite 4.ts new file mode 100644 index 000000000..6fc986ceb --- /dev/null +++ b/Tests/sprites/scale sprite 4.ts @@ -0,0 +1,53 @@ +/// + +(function () { + + var game = new Phaser.Game(this, 'game', 800, 600, init, create); + + function init() { + + // Using Phasers asset loader we load up a PNG from the assets folder + game.loader.addImageFile('bunny', 'assets/sprites/bunny.png'); + game.loader.load(); + + } + + var bunny: Phaser.Sprite; + var tweenUp: Phaser.Tween; + var tweenDown: Phaser.Tween; + + function create() { + + // Here we'll assign the new sprite to the local bunny variable + bunny = game.add.sprite(0, 0, 'bunny'); + + // This time let's scale the sprite by using two tweens + // The first tween will scale the sprite up, the second will scale it down again + + // Create our 2 tweens + tweenUp = game.add.tween(bunny.scale); + tweenUp.onComplete.add(scaleDown, this); + + tweenDown = game.add.tween(bunny.scale); + tweenDown.onComplete.add(scaleUp, this); + + // Start it going + scaleUp(); + + } + + function scaleUp() { + + tweenUp.to({ x: 2, y: 2 }, 2000, Phaser.Easing.Elastic.Out); + tweenUp.start(); + + } + + function scaleDown() { + + tweenDown.to({ x: 0.5, y: 0.5 }, 2000, Phaser.Easing.Elastic.Out); + tweenDown.start(); + + } + +})(); diff --git a/Tests/sprites/scale sprite 5.js b/Tests/sprites/scale sprite 5.js new file mode 100644 index 000000000..0ce541a8b --- /dev/null +++ b/Tests/sprites/scale sprite 5.js @@ -0,0 +1,52 @@ +/// +(function () { + var game = new Phaser.Game(this, 'game', 800, 600, init, create); + function init() { + // Using Phasers asset loader we load up a PNG from the assets folder + game.loader.addImageFile('fuji', 'assets/pics/atari_fujilogo.png'); + game.loader.load(); + } + var fuji; + var tween; + function create() { + game.stage.backgroundColor = 'rgb(0,0,100)'; + // Here we'll assign the new sprite to the local fuji variable + //fuji = game.add.sprite(game.stage.centerX - 160, game.stage.centerY - 100, 'fuji'); + fuji = game.add.sprite(100, game.stage.centerY - 100, 'fuji'); + //fuji.scale.x = 2; + //fuji.scale.y = 2; + //fuji.texture.flippedX = true; + fuji.texture.flippedY = true; + //fuji.origin.setTo(160, 100); + //fuji.rotation = 45; + game.add.tween(fuji.position).to({ + rotation: 360 + }, 3000).start(); + // We set the origin of the Sprite to be the center so that the scaling happens around the center, not the left-hand side + //fuji.origin.setTo(160, 100); + // We'll tween the scale down to zero (which will make the sprite invisible) and then flip it + // The end result should look like turning over a card + // Create our tween + //tween = game.add.tween(fuji.scale); + // Start it going + //scaleLeft(); + } + function scaleLeft() { + tween.clear(); + tween.to({ + x: 0 + }, 1000); + tween.onComplete.add(scaleRight, this); + tween.start(); + } + function scaleRight() { + tween.clear(); + tween.to({ + x: 1 + }, 1000); + tween.onComplete.add(scaleLeft, this); + tween.start(); + // This line says "if the texture is flippedX then unflip it (set flippedX to false), otherwise set flippedX to true + (fuji.texture.flippedX) ? fuji.texture.flippedX = false : fuji.texture.flippedX = true; + } +})(); diff --git a/Tests/sprites/scale sprite 5.ts b/Tests/sprites/scale sprite 5.ts new file mode 100644 index 000000000..1dc098519 --- /dev/null +++ b/Tests/sprites/scale sprite 5.ts @@ -0,0 +1,71 @@ +/// + +(function () { + + var game = new Phaser.Game(this, 'game', 800, 600, init, create); + + function init() { + + // Using Phasers asset loader we load up a PNG from the assets folder + game.loader.addImageFile('fuji', 'assets/pics/atari_fujilogo.png'); + game.loader.load(); + + } + + var fuji: Phaser.Sprite; + var tween: Phaser.Tween; + + function create() { + + game.stage.backgroundColor = 'rgb(0,0,100)'; + + + // Here we'll assign the new sprite to the local fuji variable + //fuji = game.add.sprite(game.stage.centerX - 160, game.stage.centerY - 100, 'fuji'); + fuji = game.add.sprite(100, game.stage.centerY - 100, 'fuji'); + + //fuji.scale.x = 2; + //fuji.scale.y = 2; + //fuji.texture.flippedX = true; + fuji.texture.flippedY = true; + + //fuji.origin.setTo(160, 100); + //fuji.rotation = 45; + game.add.tween(fuji.position).to({ rotation: 360 }, 3000).start(); + + // We set the origin of the Sprite to be the center so that the scaling happens around the center, not the left-hand side + //fuji.origin.setTo(160, 100); + + // We'll tween the scale down to zero (which will make the sprite invisible) and then flip it + // The end result should look like turning over a card + + // Create our tween + //tween = game.add.tween(fuji.scale); + + // Start it going + //scaleLeft(); + + } + + function scaleLeft() { + + tween.clear(); + tween.to({ x: 0 }, 1000); + tween.onComplete.add(scaleRight, this); + tween.start(); + + } + + function scaleRight() { + + tween.clear(); + tween.to({ x: 1 }, 1000); + tween.onComplete.add(scaleLeft, this); + tween.start(); + + // This line says "if the texture is flippedX then unflip it (set flippedX to false), otherwise set flippedX to true + (fuji.texture.flippedX) ? fuji.texture.flippedX = false: fuji.texture.flippedX = true; + + } + +})(); diff --git a/Tests/sprites/starling texture atlas 1.js b/Tests/sprites/starling texture atlas 1.js deleted file mode 100644 index fc7cdeeea..000000000 --- a/Tests/sprites/starling texture atlas 1.js +++ /dev/null @@ -1,32 +0,0 @@ -/// -(function () { - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update); - function init() { - // Starling/Sparrow XML Texture Atlas Method 1 - // - // In this example we assume that the XML data is stored in an external file - myGame.loader.addTextureAtlas('bits', 'assets/sprites/shoebox.png', 'assets/sprites/shoebox.xml', null, Phaser.Loader.TEXTURE_ATLAS_XML_STARLING); - myGame.loader.addTextureAtlas('bot', 'assets/sprites/shoebot.png', 'assets/sprites/shoebot.xml', null, Phaser.Loader.TEXTURE_ATLAS_XML_STARLING); - myGame.loader.load(); - } - var bits; - var bot; - function create() { - bot = myGame.add.sprite(800, 200, 'bot'); - bot.animations.add('run'); - bot.animations.play('run', 10, true); - bits = myGame.add.sprite(200, 200, 'bits'); - bits.frame = 0; - bot.velocity.x = -300; - } - function update() { - if(bot.x < -bot.width) { - bot.x = myGame.stage.width; - bits.frame++; - console.log(bits.frame, bits.animations.frameTotal); - if(bits.frame == bits.animations.frameTotal - 1) { - bits.frame = 0; - } - } - } -})(); diff --git a/Tests/sprites/starling texture atlas 1.ts b/Tests/sprites/starling texture atlas 1.ts deleted file mode 100644 index c6dc0d8fc..000000000 --- a/Tests/sprites/starling texture atlas 1.ts +++ /dev/null @@ -1,52 +0,0 @@ -/// - -(function () { - - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update); - - function init() { - - // Starling/Sparrow XML Texture Atlas Method 1 - // - // In this example we assume that the XML data is stored in an external file - myGame.loader.addTextureAtlas('bits', 'assets/sprites/shoebox.png', 'assets/sprites/shoebox.xml', null, Phaser.Loader.TEXTURE_ATLAS_XML_STARLING); - myGame.loader.addTextureAtlas('bot', 'assets/sprites/shoebot.png', 'assets/sprites/shoebot.xml', null, Phaser.Loader.TEXTURE_ATLAS_XML_STARLING); - - myGame.loader.load(); - - } - - var bits: Phaser.Sprite; - var bot: Phaser.Sprite; - - function create() { - - bot = myGame.add.sprite(800, 200, 'bot'); - bot.animations.add('run'); - bot.animations.play('run', 10, true); - - bits = myGame.add.sprite(200, 200, 'bits'); - bits.frame = 0; - - bot.velocity.x = -300; - - } - - function update() { - - if (bot.x < -bot.width) - { - bot.x = myGame.stage.width; - - bits.frame++; - console.log(bits.frame, bits.animations.frameTotal); - - if (bits.frame == bits.animations.frameTotal - 1) - { - bits.frame = 0; - } - } - - } - -})(); diff --git a/Tests/sprites/texture atlas 2.js b/Tests/sprites/texture atlas 2.js deleted file mode 100644 index 1fb6d2a88..000000000 --- a/Tests/sprites/texture atlas 2.js +++ /dev/null @@ -1,25 +0,0 @@ -/// -(function () { - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update); - function init() { - // Texture Atlas Method 2 - // - // In this example we assume that the TexturePacker JSON data is a string of json data stored as a var - // (in this case botData) - myGame.loader.addTextureAtlas('bot', 'assets/sprites/running_bot.png', null, botData); - myGame.loader.load(); - } - var bot; - function create() { - bot = myGame.add.sprite(myGame.stage.width, 300, 'bot'); - bot.animations.add('run'); - bot.animations.play('run', 10, true); - bot.velocity.x = -100; - } - function update() { - if(bot.x < -bot.width) { - bot.x = myGame.stage.width; - } - } - var botData = '{"frames": [{"filename": "running bot.swf/0000","frame": { "x": 34, "y": 128, "w": 56, "h": 60 },"rotated": false,"trimmed": true,"spriteSourceSize": { "x": 0, "y": 2, "w": 56, "h": 60 },"sourceSize": { "w": 56, "h": 64 }},{"filename": "running bot.swf/0001","frame": { "x": 54, "y": 0, "w": 56, "h": 58 },"rotated": false,"trimmed": true,"spriteSourceSize": { "x": 0, "y": 3, "w": 56, "h": 58 },"sourceSize": { "w": 56, "h": 64 }},{"filename": "running bot.swf/0002","frame": { "x": 54, "y": 58, "w": 56, "h": 58 },"rotated": false,"trimmed": true,"spriteSourceSize": { "x": 0, "y": 3, "w": 56, "h": 58 },"sourceSize": { "w": 56, "h": 64 }},{"filename": "running bot.swf/0003","frame": { "x": 0, "y": 192, "w": 34, "h": 64 },"rotated": false,"trimmed": true,"spriteSourceSize": { "x": 11, "y": 0, "w": 34, "h": 64 },"sourceSize": { "w": 56, "h": 64 }},{"filename": "running bot.swf/0004","frame": { "x": 0, "y": 64, "w": 54, "h": 64 },"rotated": false,"trimmed": true,"spriteSourceSize": { "x": 1, "y": 0, "w": 54, "h": 64 },"sourceSize": { "w": 56, "h": 64 }},{"filename": "running bot.swf/0005","frame": { "x": 196, "y": 0, "w": 56, "h": 58 },"rotated": false,"trimmed": true,"spriteSourceSize": { "x": 0, "y": 3, "w": 56, "h": 58 },"sourceSize": { "w": 56, "h": 64 }},{"filename": "running bot.swf/0006","frame": { "x": 0, "y": 0, "w": 54, "h": 64 },"rotated": false,"trimmed": true,"spriteSourceSize": { "x": 1, "y": 0, "w": 54, "h": 64 },"sourceSize": { "w": 56, "h": 64 }},{"filename": "running bot.swf/0007","frame": { "x": 140, "y": 0, "w": 56, "h": 58 },"rotated": false,"trimmed": true,"spriteSourceSize": { "x": 0, "y": 3, "w": 56, "h": 58 },"sourceSize": { "w": 56, "h": 64 }},{"filename": "running bot.swf/0008","frame": { "x": 34, "y": 188, "w": 50, "h": 60 },"rotated": false,"trimmed": true,"spriteSourceSize": { "x": 3, "y": 2, "w": 50, "h": 60 },"sourceSize": { "w": 56, "h": 64 }},{"filename": "running bot.swf/0009","frame": { "x": 0, "y": 128, "w": 34, "h": 64 },"rotated": false,"trimmed": true,"spriteSourceSize": { "x": 11, "y": 0, "w": 34, "h": 64 },"sourceSize": { "w": 56, "h": 64 }},{"filename": "running bot.swf/0010","frame": { "x": 84, "y": 188, "w": 56, "h": 58 },"rotated": false,"trimmed": true,"spriteSourceSize": { "x": 0, "y": 3, "w": 56, "h": 58 },"sourceSize": { "w": 56, "h": 64 }}]}'; -})(); diff --git a/Tests/sprites/texture atlas 2.ts b/Tests/sprites/texture atlas 2.ts deleted file mode 100644 index 7ae3264b2..000000000 --- a/Tests/sprites/texture atlas 2.ts +++ /dev/null @@ -1,43 +0,0 @@ -/// - -(function () { - - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update); - - function init() { - - // Texture Atlas Method 2 - // - // In this example we assume that the TexturePacker JSON data is a string of json data stored as a var - // (in this case botData) - myGame.loader.addTextureAtlas('bot', 'assets/sprites/running_bot.png', null, botData); - - myGame.loader.load(); - - } - - var bot: Phaser.Sprite; - - function create() { - - bot = myGame.add.sprite(myGame.stage.width, 300, 'bot'); - - bot.animations.add('run'); - bot.animations.play('run', 10, true); - - bot.velocity.x = -100; - - } - - function update() { - - if (bot.x < -bot.width) - { - bot.x = myGame.stage.width; - } - - } - - var botData = '{"frames": [{"filename": "running bot.swf/0000","frame": { "x": 34, "y": 128, "w": 56, "h": 60 },"rotated": false,"trimmed": true,"spriteSourceSize": { "x": 0, "y": 2, "w": 56, "h": 60 },"sourceSize": { "w": 56, "h": 64 }},{"filename": "running bot.swf/0001","frame": { "x": 54, "y": 0, "w": 56, "h": 58 },"rotated": false,"trimmed": true,"spriteSourceSize": { "x": 0, "y": 3, "w": 56, "h": 58 },"sourceSize": { "w": 56, "h": 64 }},{"filename": "running bot.swf/0002","frame": { "x": 54, "y": 58, "w": 56, "h": 58 },"rotated": false,"trimmed": true,"spriteSourceSize": { "x": 0, "y": 3, "w": 56, "h": 58 },"sourceSize": { "w": 56, "h": 64 }},{"filename": "running bot.swf/0003","frame": { "x": 0, "y": 192, "w": 34, "h": 64 },"rotated": false,"trimmed": true,"spriteSourceSize": { "x": 11, "y": 0, "w": 34, "h": 64 },"sourceSize": { "w": 56, "h": 64 }},{"filename": "running bot.swf/0004","frame": { "x": 0, "y": 64, "w": 54, "h": 64 },"rotated": false,"trimmed": true,"spriteSourceSize": { "x": 1, "y": 0, "w": 54, "h": 64 },"sourceSize": { "w": 56, "h": 64 }},{"filename": "running bot.swf/0005","frame": { "x": 196, "y": 0, "w": 56, "h": 58 },"rotated": false,"trimmed": true,"spriteSourceSize": { "x": 0, "y": 3, "w": 56, "h": 58 },"sourceSize": { "w": 56, "h": 64 }},{"filename": "running bot.swf/0006","frame": { "x": 0, "y": 0, "w": 54, "h": 64 },"rotated": false,"trimmed": true,"spriteSourceSize": { "x": 1, "y": 0, "w": 54, "h": 64 },"sourceSize": { "w": 56, "h": 64 }},{"filename": "running bot.swf/0007","frame": { "x": 140, "y": 0, "w": 56, "h": 58 },"rotated": false,"trimmed": true,"spriteSourceSize": { "x": 0, "y": 3, "w": 56, "h": 58 },"sourceSize": { "w": 56, "h": 64 }},{"filename": "running bot.swf/0008","frame": { "x": 34, "y": 188, "w": 50, "h": 60 },"rotated": false,"trimmed": true,"spriteSourceSize": { "x": 3, "y": 2, "w": 50, "h": 60 },"sourceSize": { "w": 56, "h": 64 }},{"filename": "running bot.swf/0009","frame": { "x": 0, "y": 128, "w": 34, "h": 64 },"rotated": false,"trimmed": true,"spriteSourceSize": { "x": 11, "y": 0, "w": 34, "h": 64 },"sourceSize": { "w": 56, "h": 64 }},{"filename": "running bot.swf/0010","frame": { "x": 84, "y": 188, "w": 56, "h": 58 },"rotated": false,"trimmed": true,"spriteSourceSize": { "x": 0, "y": 3, "w": 56, "h": 58 },"sourceSize": { "w": 56, "h": 64 }}]}'; - -})(); diff --git a/Tests/sprites/texture atlas 3.js b/Tests/sprites/texture atlas 3.js deleted file mode 100644 index b430c9fd8..000000000 --- a/Tests/sprites/texture atlas 3.js +++ /dev/null @@ -1,23 +0,0 @@ -/// -(function () { - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update); - function init() { - // Texture Atlas Method 3 - // - // In this example we assume that the TexturePacker JSON data is stored in an external file - myGame.loader.addTextureAtlas('bot', 'assets/sprites/running_bot.png', 'assets/sprites/running_bot.json'); - myGame.loader.load(); - } - var bot; - function create() { - bot = myGame.add.sprite(myGame.stage.width, 300, 'bot'); - bot.animations.add('run'); - bot.animations.play('run', 10, true); - bot.velocity.x = -100; - } - function update() { - if(bot.x < -bot.width) { - bot.x = myGame.stage.width; - } - } -})(); diff --git a/Tests/sprites/texture atlas 3.ts b/Tests/sprites/texture atlas 3.ts deleted file mode 100644 index 49fec4faf..000000000 --- a/Tests/sprites/texture atlas 3.ts +++ /dev/null @@ -1,40 +0,0 @@ -/// - -(function () { - - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update); - - function init() { - - // Texture Atlas Method 3 - // - // In this example we assume that the TexturePacker JSON data is stored in an external file - myGame.loader.addTextureAtlas('bot', 'assets/sprites/running_bot.png', 'assets/sprites/running_bot.json'); - - myGame.loader.load(); - - } - - var bot: Phaser.Sprite; - - function create() { - - bot = myGame.add.sprite(myGame.stage.width, 300, 'bot'); - - bot.animations.add('run'); - bot.animations.play('run', 10, true); - - bot.velocity.x = -100; - - } - - function update() { - - if (bot.x < -bot.width) - { - bot.x = myGame.stage.width; - } - - } - -})(); diff --git a/Tests/sprites/texture atlas 4.js b/Tests/sprites/texture atlas 4.js deleted file mode 100644 index a5e7b5d12..000000000 --- a/Tests/sprites/texture atlas 4.js +++ /dev/null @@ -1,32 +0,0 @@ -/// -(function () { - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create); - function init() { - // Texture Atlas Method 4 - // - // We load a TexturePacker JSON file and image and show you how to make several unique sprites from the same file - myGame.loader.addTextureAtlas('atlas', 'assets/pics/texturepacker_test.png', 'assets/pics/texturepacker_test.json'); - myGame.loader.load(); - } - var chick; - var car; - var mech; - var robot; - var cop; - function create() { - myGame.camera.backgroundColor = 'rgb(40, 40, 40)'; - chick = myGame.add.sprite(64, 64, 'atlas'); - // You can set the frame based on the frame name (which TexturePacker usually sets to be the filename of the image itself) - chick.frameName = 'budbrain_chick.png'; - // Or by setting the frame index - //chick.frame = 0; - cop = myGame.add.sprite(600, 64, 'atlas'); - cop.frameName = 'ladycop.png'; - robot = myGame.add.sprite(50, 300, 'atlas'); - robot.frameName = 'robot.png'; - car = myGame.add.sprite(100, 400, 'atlas'); - car.frameName = 'supercars_parsec.png'; - mech = myGame.add.sprite(250, 100, 'atlas'); - mech.frameName = 'titan_mech.png'; - } -})(); diff --git a/Tests/sprites/texture atlas 4.ts b/Tests/sprites/texture atlas 4.ts deleted file mode 100644 index faf74f464..000000000 --- a/Tests/sprites/texture atlas 4.ts +++ /dev/null @@ -1,50 +0,0 @@ -/// - -(function () { - - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create); - - function init() { - - // Texture Atlas Method 4 - // - // We load a TexturePacker JSON file and image and show you how to make several unique sprites from the same file - myGame.loader.addTextureAtlas('atlas', 'assets/pics/texturepacker_test.png', 'assets/pics/texturepacker_test.json'); - - myGame.loader.load(); - - } - - var chick: Phaser.Sprite; - var car: Phaser.Sprite; - var mech: Phaser.Sprite; - var robot: Phaser.Sprite; - var cop: Phaser.Sprite; - - function create() { - - myGame.camera.backgroundColor = 'rgb(40, 40, 40)'; - - chick = myGame.add.sprite(64, 64, 'atlas'); - - // You can set the frame based on the frame name (which TexturePacker usually sets to be the filename of the image itself) - chick.frameName = 'budbrain_chick.png'; - - // Or by setting the frame index - //chick.frame = 0; - - cop = myGame.add.sprite(600, 64, 'atlas'); - cop.frameName = 'ladycop.png'; - - robot = myGame.add.sprite(50, 300, 'atlas'); - robot.frameName = 'robot.png'; - - car = myGame.add.sprite(100, 400, 'atlas'); - car.frameName = 'supercars_parsec.png'; - - mech = myGame.add.sprite(250, 100, 'atlas'); - mech.frameName = 'titan_mech.png'; - - } - -})(); diff --git a/Tests/sprites/texture atlas.js b/Tests/sprites/texture atlas.js deleted file mode 100644 index ce5837bfd..000000000 --- a/Tests/sprites/texture atlas.js +++ /dev/null @@ -1,271 +0,0 @@ -/// -(function () { - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update); - function init() { - // Texture Atlas Method 1 - // - // In this example we assume that the TexturePacker JSON data is a real json object stored as a var - // (in this case botData) - myGame.loader.addTextureAtlas('bot', 'assets/sprites/running_bot.png', null, botData); - myGame.loader.load(); - } - var bot; - function create() { - bot = myGame.add.sprite(myGame.stage.width, 300, 'bot'); - bot.animations.add('run'); - bot.animations.play('run', 10, true); - bot.velocity.x = -100; - } - function update() { - if(bot.x < -bot.width) { - bot.x = myGame.stage.width; - } - } - var botData = { - "frames": [ - { - "filename": "running bot.swf/0000", - "frame": { - "x": 34, - "y": 128, - "w": 56, - "h": 60 - }, - "rotated": false, - "trimmed": true, - "spriteSourceSize": { - "x": 0, - "y": 2, - "w": 56, - "h": 60 - }, - "sourceSize": { - "w": 56, - "h": 64 - } - }, - { - "filename": "running bot.swf/0001", - "frame": { - "x": 54, - "y": 0, - "w": 56, - "h": 58 - }, - "rotated": false, - "trimmed": true, - "spriteSourceSize": { - "x": 0, - "y": 3, - "w": 56, - "h": 58 - }, - "sourceSize": { - "w": 56, - "h": 64 - } - }, - { - "filename": "running bot.swf/0002", - "frame": { - "x": 54, - "y": 58, - "w": 56, - "h": 58 - }, - "rotated": false, - "trimmed": true, - "spriteSourceSize": { - "x": 0, - "y": 3, - "w": 56, - "h": 58 - }, - "sourceSize": { - "w": 56, - "h": 64 - } - }, - { - "filename": "running bot.swf/0003", - "frame": { - "x": 0, - "y": 192, - "w": 34, - "h": 64 - }, - "rotated": false, - "trimmed": true, - "spriteSourceSize": { - "x": 11, - "y": 0, - "w": 34, - "h": 64 - }, - "sourceSize": { - "w": 56, - "h": 64 - } - }, - { - "filename": "running bot.swf/0004", - "frame": { - "x": 0, - "y": 64, - "w": 54, - "h": 64 - }, - "rotated": false, - "trimmed": true, - "spriteSourceSize": { - "x": 1, - "y": 0, - "w": 54, - "h": 64 - }, - "sourceSize": { - "w": 56, - "h": 64 - } - }, - { - "filename": "running bot.swf/0005", - "frame": { - "x": 196, - "y": 0, - "w": 56, - "h": 58 - }, - "rotated": false, - "trimmed": true, - "spriteSourceSize": { - "x": 0, - "y": 3, - "w": 56, - "h": 58 - }, - "sourceSize": { - "w": 56, - "h": 64 - } - }, - { - "filename": "running bot.swf/0006", - "frame": { - "x": 0, - "y": 0, - "w": 54, - "h": 64 - }, - "rotated": false, - "trimmed": true, - "spriteSourceSize": { - "x": 1, - "y": 0, - "w": 54, - "h": 64 - }, - "sourceSize": { - "w": 56, - "h": 64 - } - }, - { - "filename": "running bot.swf/0007", - "frame": { - "x": 140, - "y": 0, - "w": 56, - "h": 58 - }, - "rotated": false, - "trimmed": true, - "spriteSourceSize": { - "x": 0, - "y": 3, - "w": 56, - "h": 58 - }, - "sourceSize": { - "w": 56, - "h": 64 - } - }, - { - "filename": "running bot.swf/0008", - "frame": { - "x": 34, - "y": 188, - "w": 50, - "h": 60 - }, - "rotated": false, - "trimmed": true, - "spriteSourceSize": { - "x": 3, - "y": 2, - "w": 50, - "h": 60 - }, - "sourceSize": { - "w": 56, - "h": 64 - } - }, - { - "filename": "running bot.swf/0009", - "frame": { - "x": 0, - "y": 128, - "w": 34, - "h": 64 - }, - "rotated": false, - "trimmed": true, - "spriteSourceSize": { - "x": 11, - "y": 0, - "w": 34, - "h": 64 - }, - "sourceSize": { - "w": 56, - "h": 64 - } - }, - { - "filename": "running bot.swf/0010", - "frame": { - "x": 84, - "y": 188, - "w": 56, - "h": 58 - }, - "rotated": false, - "trimmed": true, - "spriteSourceSize": { - "x": 0, - "y": 3, - "w": 56, - "h": 58 - }, - "sourceSize": { - "w": 56, - "h": 64 - } - } - ], - "meta": { - "app": "http://www.texturepacker.com", - "version": "1.0", - "image": "running_bot.png", - "format": "RGBA8888", - "size": { - "w": 252, - "h": 256 - }, - "scale": "0.2", - "smartupdate": "$TexturePacker:SmartUpdate:fb56f261b1eb04e3215824426595f64c$" - } - }; -})(); diff --git a/Tests/sprites/texture atlas.ts b/Tests/sprites/texture atlas.ts deleted file mode 100644 index 1aa46bff4..000000000 --- a/Tests/sprites/texture atlas.ts +++ /dev/null @@ -1,143 +0,0 @@ -/// - -(function () { - - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update); - - function init() { - - // Texture Atlas Method 1 - // - // In this example we assume that the TexturePacker JSON data is a real json object stored as a var - // (in this case botData) - myGame.loader.addTextureAtlas('bot', 'assets/sprites/running_bot.png', null, botData); - - myGame.loader.load(); - - } - - var bot: Phaser.Sprite; - - function create() { - - bot = myGame.add.sprite(myGame.stage.width, 300, 'bot'); - - bot.animations.add('run'); - bot.animations.play('run', 10, true); - - bot.velocity.x = -100; - - } - - function update() { - - if (bot.x < -bot.width) - { - bot.x = myGame.stage.width; - } - - } - - var botData = { - "frames": [ - - { - "filename": "running bot.swf/0000", - "frame": { "x": 34, "y": 128, "w": 56, "h": 60 }, - "rotated": false, - "trimmed": true, - "spriteSourceSize": { "x": 0, "y": 2, "w": 56, "h": 60 }, - "sourceSize": { "w": 56, "h": 64 } - }, - { - "filename": "running bot.swf/0001", - "frame": { "x": 54, "y": 0, "w": 56, "h": 58 }, - "rotated": false, - "trimmed": true, - "spriteSourceSize": { "x": 0, "y": 3, "w": 56, "h": 58 }, - "sourceSize": { "w": 56, "h": 64 } - }, - { - "filename": "running bot.swf/0002", - "frame": { "x": 54, "y": 58, "w": 56, "h": 58 }, - "rotated": false, - "trimmed": true, - "spriteSourceSize": { "x": 0, "y": 3, "w": 56, "h": 58 }, - "sourceSize": { "w": 56, "h": 64 } - }, - { - "filename": "running bot.swf/0003", - "frame": { "x": 0, "y": 192, "w": 34, "h": 64 }, - "rotated": false, - "trimmed": true, - "spriteSourceSize": { "x": 11, "y": 0, "w": 34, "h": 64 }, - "sourceSize": { "w": 56, "h": 64 } - }, - { - "filename": "running bot.swf/0004", - "frame": { "x": 0, "y": 64, "w": 54, "h": 64 }, - "rotated": false, - "trimmed": true, - "spriteSourceSize": { "x": 1, "y": 0, "w": 54, "h": 64 }, - "sourceSize": { "w": 56, "h": 64 } - }, - { - "filename": "running bot.swf/0005", - "frame": { "x": 196, "y": 0, "w": 56, "h": 58 }, - "rotated": false, - "trimmed": true, - "spriteSourceSize": { "x": 0, "y": 3, "w": 56, "h": 58 }, - "sourceSize": { "w": 56, "h": 64 } - }, - { - "filename": "running bot.swf/0006", - "frame": { "x": 0, "y": 0, "w": 54, "h": 64 }, - "rotated": false, - "trimmed": true, - "spriteSourceSize": { "x": 1, "y": 0, "w": 54, "h": 64 }, - "sourceSize": { "w": 56, "h": 64 } - }, - { - "filename": "running bot.swf/0007", - "frame": { "x": 140, "y": 0, "w": 56, "h": 58 }, - "rotated": false, - "trimmed": true, - "spriteSourceSize": { "x": 0, "y": 3, "w": 56, "h": 58 }, - "sourceSize": { "w": 56, "h": 64 } - }, - { - "filename": "running bot.swf/0008", - "frame": { "x": 34, "y": 188, "w": 50, "h": 60 }, - "rotated": false, - "trimmed": true, - "spriteSourceSize": { "x": 3, "y": 2, "w": 50, "h": 60 }, - "sourceSize": { "w": 56, "h": 64 } - }, - { - "filename": "running bot.swf/0009", - "frame": { "x": 0, "y": 128, "w": 34, "h": 64 }, - "rotated": false, - "trimmed": true, - "spriteSourceSize": { "x": 11, "y": 0, "w": 34, "h": 64 }, - "sourceSize": { "w": 56, "h": 64 } - }, - { - "filename": "running bot.swf/0010", - "frame": { "x": 84, "y": 188, "w": 56, "h": 58 }, - "rotated": false, - "trimmed": true, - "spriteSourceSize": { "x": 0, "y": 3, "w": 56, "h": 58 }, - "sourceSize": { "w": 56, "h": 64 } - }], - "meta": { - "app": "http://www.texturepacker.com", - "version": "1.0", - "image": "running_bot.png", - "format": "RGBA8888", - "size": { "w": 252, "h": 256 }, - "scale": "0.2", - "smartupdate": "$TexturePacker:SmartUpdate:fb56f261b1eb04e3215824426595f64c$" - } - }; - -})(); diff --git a/Tests/sprites/velocity.js b/Tests/sprites/velocity.js deleted file mode 100644 index 6731ad5e0..000000000 --- a/Tests/sprites/velocity.js +++ /dev/null @@ -1,33 +0,0 @@ -/// -(function () { - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update); - function init() { - myGame.loader.addImageFile('car', 'assets/sprites/asteroids_ship.png'); - myGame.loader.load(); - } - var car; - function create() { - car = myGame.add.sprite(200, 300, 'car'); - } - function update() { - car.renderDebugInfo(16, 16); - car.velocity.x = 0; - car.velocity.y = 0; - car.angularVelocity = 0; - car.angularAcceleration = 0; - if(myGame.input.keyboard.isDown(Phaser.Keyboard.LEFT)) { - car.angularVelocity = -200; - } else if(myGame.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) { - car.angularVelocity = 200; - } - if(myGame.input.keyboard.isDown(Phaser.Keyboard.UP)) { - var motion = myGame.motion.velocityFromAngle(car.angle, 200); - // instant - car.velocity.copyFrom(motion); - // acceleration - //car.acceleration.copyFrom(motion); - } else if(myGame.input.keyboard.isDown(Phaser.Keyboard.DOWN)) { - //car.velocity.y = 200; - } - } -})(); diff --git a/Tests/sprites/velocity.ts b/Tests/sprites/velocity.ts deleted file mode 100644 index 50d756820..000000000 --- a/Tests/sprites/velocity.ts +++ /dev/null @@ -1,58 +0,0 @@ -/// - -(function () { - - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update); - - function init() { - - myGame.loader.addImageFile('car', 'assets/sprites/asteroids_ship.png'); - - myGame.loader.load(); - - } - - var car: Phaser.Sprite; - - function create() { - - car = myGame.add.sprite(200, 300, 'car'); - - } - - function update() { - - car.renderDebugInfo(16, 16); - - car.velocity.x = 0; - car.velocity.y = 0; - car.angularVelocity = 0; - car.angularAcceleration = 0; - - if (myGame.input.keyboard.isDown(Phaser.Keyboard.LEFT)) - { - car.angularVelocity = -200; - } - else if (myGame.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) - { - car.angularVelocity = 200; - } - - if (myGame.input.keyboard.isDown(Phaser.Keyboard.UP)) - { - var motion:Phaser.Point = myGame.motion.velocityFromAngle(car.angle, 200); - - // instant - car.velocity.copyFrom(motion); - - // acceleration - //car.acceleration.copyFrom(motion); - } - else if (myGame.input.keyboard.isDown(Phaser.Keyboard.DOWN)) - { - //car.velocity.y = 200; - } - - } - -})(); diff --git a/Tests/tilemap/basic tilemap.js b/Tests/tilemap/basic tilemap.js deleted file mode 100644 index 2b52968e3..000000000 --- a/Tests/tilemap/basic tilemap.js +++ /dev/null @@ -1,50 +0,0 @@ -/// -/// -(function () { - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update); - function init() { - // Tiled JSON Test - //myGame.loader.addTextFile('jsontest', 'assets/maps/test.json'); - myGame.loader.addTextFile('jsontest', 'assets/maps/multi-layer-test.json'); - myGame.loader.addImageFile('jsontiles', 'assets/tiles/platformer_tiles.png'); - // CSV Test - myGame.loader.addTextFile('csvtest', 'assets/maps/catastrophi_level2.csv'); - myGame.loader.addImageFile('csvtiles', 'assets/tiles/catastrophi_tiles_16.png'); - myGame.loader.addImageFile('car', 'assets/sprites/car90.png'); - myGame.loader.load(); - } - var car; - var map; - var bigCam; - function create() { - myGame.camera.deadzone = new Phaser.Rectangle(64, 64, myGame.stage.width - 128, myGame.stage.height - 128); - //bigCam = myGame.add.camera(30, 30, 200, 200); - //bigCam.showBorder = true; - //bigCam.scale.setTo(1.5, 1.5); - //map = myGame.add.tilemap('jsontiles', 'jsontest', Phaser.Tilemap.FORMAT_TILED_JSON); - map = myGame.add.tilemap('csvtiles', 'csvtest', Phaser.Tilemap.FORMAT_CSV, true, 16, 16); - car = myGame.add.sprite(300, 100, 'car'); - myGame.camera.follow(car); - //bigCam.follow(car, Phaser.Camera.STYLE_LOCKON); - myGame.onRenderCallback = render; - } - function update() { - //bigCam.rotation += 0.5; - car.velocity.x = 0; - car.velocity.y = 0; - car.angularVelocity = 0; - car.angularAcceleration = 0; - if(myGame.input.keyboard.isDown(Phaser.Keyboard.LEFT)) { - car.angularVelocity = -200; - } else if(myGame.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) { - car.angularVelocity = 200; - } - if(myGame.input.keyboard.isDown(Phaser.Keyboard.UP)) { - var motion = myGame.motion.velocityFromAngle(car.angle, 300); - car.velocity.copyFrom(motion); - } - } - function render() { - //map.renderDebugInfo(400, 16); - } -})(); diff --git a/Tests/tilemap/basic tilemap.ts b/Tests/tilemap/basic tilemap.ts deleted file mode 100644 index 2bdcb3b68..000000000 --- a/Tests/tilemap/basic tilemap.ts +++ /dev/null @@ -1,82 +0,0 @@ -/// -/// - -(function () { - - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update); - - function init() { - - // Tiled JSON Test - //myGame.loader.addTextFile('jsontest', 'assets/maps/test.json'); - myGame.loader.addTextFile('jsontest', 'assets/maps/multi-layer-test.json'); - myGame.loader.addImageFile('jsontiles', 'assets/tiles/platformer_tiles.png'); - - // CSV Test - myGame.loader.addTextFile('csvtest', 'assets/maps/catastrophi_level2.csv'); - myGame.loader.addImageFile('csvtiles', 'assets/tiles/catastrophi_tiles_16.png'); - - myGame.loader.addImageFile('car', 'assets/sprites/car90.png'); - - myGame.loader.load(); - - } - - var car: Phaser.Sprite; - var map: Phaser.Tilemap; - var bigCam: Phaser.Camera; - - function create() { - - myGame.camera.deadzone = new Phaser.Rectangle(64, 64, myGame.stage.width - 128, myGame.stage.height - 128); - - //bigCam = myGame.add.camera(30, 30, 200, 200); - //bigCam.showBorder = true; - //bigCam.scale.setTo(1.5, 1.5); - - //map = myGame.add.tilemap('jsontiles', 'jsontest', Phaser.Tilemap.FORMAT_TILED_JSON); - map = myGame.add.tilemap('csvtiles', 'csvtest', Phaser.Tilemap.FORMAT_CSV, true, 16, 16); - - car = myGame.add.sprite(300, 100, 'car'); - - myGame.camera.follow(car); - //bigCam.follow(car, Phaser.Camera.STYLE_LOCKON); - - myGame.onRenderCallback = render; - - } - - function update() { - - //bigCam.rotation += 0.5; - - car.velocity.x = 0; - car.velocity.y = 0; - car.angularVelocity = 0; - car.angularAcceleration = 0; - - if (myGame.input.keyboard.isDown(Phaser.Keyboard.LEFT)) - { - car.angularVelocity = -200; - } - else if (myGame.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) - { - car.angularVelocity = 200; - } - - if (myGame.input.keyboard.isDown(Phaser.Keyboard.UP)) - { - var motion:Phaser.Point = myGame.motion.velocityFromAngle(car.angle, 300); - - car.velocity.copyFrom(motion); - } - - } - - function render { - - //map.renderDebugInfo(400, 16); - - } - -})(); diff --git a/Tests/tilemap/collide with tile.js b/Tests/tilemap/collide with tile.js deleted file mode 100644 index d6ad11de3..000000000 --- a/Tests/tilemap/collide with tile.js +++ /dev/null @@ -1,66 +0,0 @@ -/// -/// -/// -/// -(function () { - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update); - function init() { - myGame.loader.addTextFile('desert', 'assets/maps/desert.json'); - myGame.loader.addImageFile('tiles', 'assets/tiles/tmw_desert_spacing.png'); - myGame.loader.addImageFile('car', 'assets/sprites/car90.png'); - myGame.loader.load(); - } - var CACTUS = 31; - var SIGN_POST = 46; - var map; - var car; - var tile; - var flash; - function create() { - map = myGame.add.tilemap('tiles', 'desert', Phaser.Tilemap.FORMAT_TILED_JSON); - // When the car collides with the cactus tile we'll flash the screen red briefly, - // but it won't stop the car (the separateX/Y values are set to false) - map.setCollisionByIndex([ - CACTUS - ], Phaser.Collision.ANY, true, false, false); - // When the car collides with the sign post tile we'll stop the car moving (separation is set to true) - map.setCollisionByIndex([ - SIGN_POST - ], Phaser.Collision.ANY, true, true, true); - // This is the callback that will be called every time map.collide() returns true - map.collisionCallback = collide; - // This is the context in which the callback is called (usually 'this' if you want to be able to access local vars) - map.collisionCallbackContext = this; - car = myGame.add.sprite(250, 200, 'car'); - car.setBounds(0, 0, map.widthInPixels - 32, map.heightInPixels - 32); - myGame.camera.follow(car); - flash = myGame.camera.fx.add(Phaser.FX.Camera.Flash); - } - function update() { - // Collide the car object with the tilemap - // It's important to do this BEFORE you adjust the object velocity (below) otherwise it can jitter around a lot - map.collide(car); - car.velocity.x = 0; - car.velocity.y = 0; - car.angularVelocity = 0; - if(myGame.input.keyboard.isDown(Phaser.Keyboard.LEFT)) { - car.angularVelocity = -200; - } else if(myGame.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) { - car.angularVelocity = 200; - } - if(myGame.input.keyboard.isDown(Phaser.Keyboard.UP)) { - car.velocity.copyFrom(myGame.motion.velocityFromAngle(car.angle, 300)); - } - } - function collide(object, collisionData) { - // collisionData is an array containing all of the tiles the object overlapped with (can be more than 1) - for(var i = 0; i < collisionData.length; i++) { - if(collisionData[i].tile.index == CACTUS) { - console.log('you hit a cactus!'); - flash.start(0xff0000, 1); - } else if(collisionData[i].tile.index == SIGN_POST) { - console.log('you hit a sign post!'); - } - } - } -})(); diff --git a/Tests/tilemap/collide with tile.ts b/Tests/tilemap/collide with tile.ts deleted file mode 100644 index 9f9fa08b0..000000000 --- a/Tests/tilemap/collide with tile.ts +++ /dev/null @@ -1,96 +0,0 @@ -/// -/// -/// -/// - -(function () { - - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update); - - function init() { - - myGame.loader.addTextFile('desert', 'assets/maps/desert.json'); - myGame.loader.addImageFile('tiles', 'assets/tiles/tmw_desert_spacing.png'); - myGame.loader.addImageFile('car', 'assets/sprites/car90.png'); - - myGame.loader.load(); - - } - var CACTUS = 31; - var SIGN_POST = 46; - var map: Phaser.Tilemap; - var car: Phaser.Sprite; - var tile: Phaser.Tile; - var flash: Phaser.FX.Camera.Flash; - - function create() { - - map = myGame.add.tilemap('tiles', 'desert', Phaser.Tilemap.FORMAT_TILED_JSON); - - // When the car collides with the cactus tile we'll flash the screen red briefly, - // but it won't stop the car (the separateX/Y values are set to false) - map.setCollisionByIndex([CACTUS], Phaser.Collision.ANY, true, false, false); - - // When the car collides with the sign post tile we'll stop the car moving (separation is set to true) - map.setCollisionByIndex([SIGN_POST], Phaser.Collision.ANY, true, true, true); - - // This is the callback that will be called every time map.collide() returns true - map.collisionCallback = collide; - - // This is the context in which the callback is called (usually 'this' if you want to be able to access local vars) - map.collisionCallbackContext = this; - - car = myGame.add.sprite(250, 200, 'car'); - car.setBounds(0, 0, map.widthInPixels - 32, map.heightInPixels - 32); - - myGame.camera.follow(car); - - flash = myGame.camera.fx.add(Phaser.FX.Camera.Flash); - - } - - function update() { - - // Collide the car object with the tilemap - // It's important to do this BEFORE you adjust the object velocity (below) otherwise it can jitter around a lot - map.collide(car); - - car.velocity.x = 0; - car.velocity.y = 0; - car.angularVelocity = 0; - - if (myGame.input.keyboard.isDown(Phaser.Keyboard.LEFT)) - { - car.angularVelocity = -200; - } - else if (myGame.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) - { - car.angularVelocity = 200; - } - - if (myGame.input.keyboard.isDown(Phaser.Keyboard.UP)) - { - car.velocity.copyFrom(myGame.motion.velocityFromAngle(car.angle, 300)); - } - - } - - function collide(object, collisionData) { - - // collisionData is an array containing all of the tiles the object overlapped with (can be more than 1) - for (var i = 0; i < collisionData.length; i++) - { - if (collisionData[i].tile.index == CACTUS) - { - console.log('you hit a cactus!'); - flash.start(0xff0000, 1); - } - else if (collisionData[i].tile.index == SIGN_POST) - { - console.log('you hit a sign post!'); - } - } - - } - -})(); diff --git a/Tests/tilemap/collision.js b/Tests/tilemap/collision.js deleted file mode 100644 index 36ded0b41..000000000 --- a/Tests/tilemap/collision.js +++ /dev/null @@ -1,63 +0,0 @@ -/// -/// -(function () { - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update); - function init() { - myGame.loader.addTextFile('platform', 'assets/maps/platform-test-1.json'); - myGame.loader.addImageFile('tiles', 'assets/tiles/platformer_tiles.png'); - myGame.loader.addImageFile('ufo', 'assets/sprites/ufo.png'); - myGame.loader.addImageFile('melon', 'assets/sprites/melon.png'); - myGame.loader.addImageFile('chunk', 'assets/sprites/chunk.png'); - myGame.loader.load(); - } - var map; - var ufo; - var tile; - var emitter; - var test; - function create() { - map = myGame.add.tilemap('tiles', 'platform', Phaser.Tilemap.FORMAT_TILED_JSON); - map.setCollisionRange(21, 53); - map.setCollisionRange(105, 109); - myGame.camera.opaque = true; - myGame.camera.backgroundColor = 'rgb(47,154,204)'; - myGame.input.keyboard.addKeyCapture([ - Phaser.Keyboard.LEFT, - Phaser.Keyboard.RIGHT, - Phaser.Keyboard.UP, - Phaser.Keyboard.DOWN - ]); - //emitter = myGame.add.emitter(32, 80); - //emitter.width = 700; - //emitter.makeParticles('chunk', 100, false, 1); - //emitter.gravity = 200; - //emitter.bounce = 0.8; - //emitter.start(false, 10, 0.05); - ufo = myGame.add.sprite(250, 64, 'ufo'); - ufo.renderDebug = true; - ufo.renderRotation = false; - test = myGame.add.sprite(200, 64, 'ufo'); - test.elasticity = 1; - test.velocity.x = 50; - test.velocity.y = 100; - ufo.setBounds(0, 0, map.widthInPixels - 32, map.heightInPixels - 32); - } - function update() { - // Collide everything with the map - map.collide(); - // And collide everything in the game :) - myGame.collide(); - ufo.velocity.x = 0; - ufo.velocity.y = 0; - if(myGame.input.keyboard.isDown(Phaser.Keyboard.LEFT)) { - ufo.velocity.x = -200; - } else if(myGame.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) { - ufo.velocity.x = 200; - } - if(myGame.input.keyboard.isDown(Phaser.Keyboard.UP)) { - ufo.velocity.y = -200; - } else if(myGame.input.keyboard.isDown(Phaser.Keyboard.DOWN)) { - ufo.velocity.y = 200; - } - } -})(); diff --git a/Tests/tilemap/collision.ts b/Tests/tilemap/collision.ts deleted file mode 100644 index d3520434c..000000000 --- a/Tests/tilemap/collision.ts +++ /dev/null @@ -1,88 +0,0 @@ -/// -/// - -(function () { - - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update); - - function init() { - - myGame.loader.addTextFile('platform', 'assets/maps/platform-test-1.json'); - myGame.loader.addImageFile('tiles', 'assets/tiles/platformer_tiles.png'); - myGame.loader.addImageFile('ufo', 'assets/sprites/ufo.png'); - myGame.loader.addImageFile('melon', 'assets/sprites/melon.png'); - myGame.loader.addImageFile('chunk', 'assets/sprites/chunk.png'); - - myGame.loader.load(); - - } - - var map: Phaser.Tilemap; - var ufo: Phaser.Sprite; - var tile: Phaser.Tile; - var emitter: Phaser.Emitter; - var test: Phaser.Sprite; - - function create() { - - map = myGame.add.tilemap('tiles', 'platform', Phaser.Tilemap.FORMAT_TILED_JSON); - map.setCollisionRange(21,53); - map.setCollisionRange(105,109); - - myGame.camera.opaque = true; - myGame.camera.backgroundColor = 'rgb(47,154,204)'; - - myGame.input.keyboard.addKeyCapture([Phaser.Keyboard.LEFT, Phaser.Keyboard.RIGHT, Phaser.Keyboard.UP, Phaser.Keyboard.DOWN]); - - //emitter = myGame.add.emitter(32, 80); - //emitter.width = 700; - //emitter.makeParticles('chunk', 100, false, 1); - //emitter.gravity = 200; - //emitter.bounce = 0.8; - //emitter.start(false, 10, 0.05); - - ufo = myGame.add.sprite(250, 64, 'ufo'); - ufo.renderDebug = true; - ufo.renderRotation = false; - - test = myGame.add.sprite(200, 64, 'ufo'); - test.elasticity = 1; - test.velocity.x = 50; - test.velocity.y = 100; - - ufo.setBounds(0, 0, map.widthInPixels - 32, map.heightInPixels - 32); - - } - - function update() { - - // Collide everything with the map - map.collide(); - - // And collide everything in the game :) - myGame.collide(); - - ufo.velocity.x = 0; - ufo.velocity.y = 0; - - if (myGame.input.keyboard.isDown(Phaser.Keyboard.LEFT)) - { - ufo.velocity.x = -200; - } - else if (myGame.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) - { - ufo.velocity.x = 200; - } - - if (myGame.input.keyboard.isDown(Phaser.Keyboard.UP)) - { - ufo.velocity.y = -200; - } - else if (myGame.input.keyboard.isDown(Phaser.Keyboard.DOWN)) - { - ufo.velocity.y = 200; - } - - } - -})(); diff --git a/Tests/tilemap/fill tiles.js b/Tests/tilemap/fill tiles.js deleted file mode 100644 index bba31d50e..000000000 --- a/Tests/tilemap/fill tiles.js +++ /dev/null @@ -1,54 +0,0 @@ -/// -/// -/// -(function () { - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update); - function init() { - myGame.loader.addTextFile('desert', 'assets/maps/desert.json'); - myGame.loader.addImageFile('tiles', 'assets/tiles/tmw_desert_spacing.png'); - myGame.loader.addImageFile('car', 'assets/sprites/car90.png'); - myGame.loader.load(); - } - var map; - var car; - var marker; - var tile; - function create() { - map = myGame.add.tilemap('tiles', 'desert', Phaser.Tilemap.FORMAT_TILED_JSON); - car = myGame.add.sprite(250, 200, 'car'); - car.setBounds(0, 0, map.widthInPixels - 32, map.heightInPixels - 32); - marker = myGame.add.geomSprite(0, 0); - marker.createRectangle(32, 32); - marker.renderFill = false; - marker.lineColor = 'rgb(0,0,0)'; - myGame.camera.follow(car); - myGame.onRenderCallback = render; - myGame.input.onDown.add(fillTiles); - } - function fillTiles() { - // Fills the given region of the map (2,2,10,20) with tile index 15 - map.currentLayer.fillTile(15, 2, 2, 10, 20); - } - function update() { - marker.x = myGame.math.snapToFloor(myGame.input.getWorldX(), 32); - marker.y = myGame.math.snapToFloor(myGame.input.getWorldY(), 32); - car.velocity.x = 0; - car.velocity.y = 0; - car.angularVelocity = 0; - if(myGame.input.keyboard.isDown(Phaser.Keyboard.LEFT)) { - car.angularVelocity = -200; - } else if(myGame.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) { - car.angularVelocity = 200; - } - if(myGame.input.keyboard.isDown(Phaser.Keyboard.UP)) { - car.velocity.copyFrom(myGame.motion.velocityFromAngle(car.angle, 300)); - } - } - function render() { - tile = map.getTileFromInputXY(); - myGame.stage.context.font = '18px Arial'; - myGame.stage.context.fillStyle = 'rgb(0,0,0)'; - myGame.stage.context.fillText(tile.toString(), 32, 32); - myGame.input.renderDebugInfo(32, 64, 'rgb(0,0,0)'); - } -})(); diff --git a/Tests/tilemap/fill tiles.ts b/Tests/tilemap/fill tiles.ts deleted file mode 100644 index defbfb407..000000000 --- a/Tests/tilemap/fill tiles.ts +++ /dev/null @@ -1,86 +0,0 @@ -/// -/// -/// - -(function () { - - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update); - - function init() { - - myGame.loader.addTextFile('desert', 'assets/maps/desert.json'); - myGame.loader.addImageFile('tiles', 'assets/tiles/tmw_desert_spacing.png'); - myGame.loader.addImageFile('car', 'assets/sprites/car90.png'); - - myGame.loader.load(); - - } - - var map: Phaser.Tilemap; - var car: Phaser.Sprite; - var marker: Phaser.GeomSprite; - var tile: Phaser.Tile; - - function create() { - - map = myGame.add.tilemap('tiles', 'desert', Phaser.Tilemap.FORMAT_TILED_JSON); - - car = myGame.add.sprite(250, 200, 'car'); - car.setBounds(0, 0, map.widthInPixels - 32, map.heightInPixels - 32); - - marker = myGame.add.geomSprite(0, 0); - marker.createRectangle(32, 32); - marker.renderFill = false; - marker.lineColor = 'rgb(0,0,0)'; - - myGame.camera.follow(car); - myGame.onRenderCallback = render; - - myGame.input.onDown.add(fillTiles); - } - - function fillTiles() { - - // Fills the given region of the map (2,2,10,20) with tile index 15 - map.currentLayer.fillTile(15, 2, 2, 10, 20); - - } - - function update() { - - marker.x = myGame.math.snapToFloor(myGame.input.getWorldX(), 32); - marker.y = myGame.math.snapToFloor(myGame.input.getWorldY(), 32); - - car.velocity.x = 0; - car.velocity.y = 0; - car.angularVelocity = 0; - - if (myGame.input.keyboard.isDown(Phaser.Keyboard.LEFT)) - { - car.angularVelocity = -200; - } - else if (myGame.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) - { - car.angularVelocity = 200; - } - - if (myGame.input.keyboard.isDown(Phaser.Keyboard.UP)) - { - car.velocity.copyFrom(myGame.motion.velocityFromAngle(car.angle, 300)); - } - - } - - function render { - - tile = map.getTileFromInputXY(); - - myGame.stage.context.font = '18px Arial'; - myGame.stage.context.fillStyle = 'rgb(0,0,0)'; - myGame.stage.context.fillText(tile.toString(), 32, 32); - - myGame.input.renderDebugInfo(32, 64, 'rgb(0,0,0)'); - - } - -})(); diff --git a/Tests/tilemap/get tile.js b/Tests/tilemap/get tile.js deleted file mode 100644 index 4b9978dc3..000000000 --- a/Tests/tilemap/get tile.js +++ /dev/null @@ -1,49 +0,0 @@ -/// -/// -/// -(function () { - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update); - function init() { - myGame.loader.addTextFile('desert', 'assets/maps/desert.json'); - myGame.loader.addImageFile('tiles', 'assets/tiles/tmw_desert_spacing.png'); - myGame.loader.addImageFile('car', 'assets/sprites/car90.png'); - myGame.loader.load(); - } - var map; - var car; - var marker; - var tile; - function create() { - map = myGame.add.tilemap('tiles', 'desert', Phaser.Tilemap.FORMAT_TILED_JSON); - car = myGame.add.sprite(250, 200, 'car'); - car.setBounds(0, 0, map.widthInPixels - 32, map.heightInPixels - 32); - marker = myGame.add.geomSprite(0, 0); - marker.createRectangle(32, 32); - marker.renderFill = false; - marker.lineColor = 'rgb(0,0,0)'; - myGame.camera.follow(car); - myGame.onRenderCallback = render; - } - function update() { - marker.x = myGame.math.snapToFloor(myGame.input.getWorldX(), 32); - marker.y = myGame.math.snapToFloor(myGame.input.getWorldY(), 32); - car.velocity.x = 0; - car.velocity.y = 0; - car.angularVelocity = 0; - if(myGame.input.keyboard.isDown(Phaser.Keyboard.LEFT)) { - car.angularVelocity = -200; - } else if(myGame.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) { - car.angularVelocity = 200; - } - if(myGame.input.keyboard.isDown(Phaser.Keyboard.UP)) { - car.velocity.copyFrom(myGame.motion.velocityFromAngle(car.angle, 300)); - } - } - function render() { - tile = map.getTileFromInputXY(); - myGame.stage.context.font = '18px Arial'; - myGame.stage.context.fillStyle = 'rgb(0,0,0)'; - myGame.stage.context.fillText(tile.toString(), 32, 32); - myGame.input.renderDebugInfo(32, 64, 'rgb(0,0,0)'); - } -})(); diff --git a/Tests/tilemap/get tile.ts b/Tests/tilemap/get tile.ts deleted file mode 100644 index e7fe58875..000000000 --- a/Tests/tilemap/get tile.ts +++ /dev/null @@ -1,78 +0,0 @@ -/// -/// -/// - -(function () { - - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update); - - function init() { - - myGame.loader.addTextFile('desert', 'assets/maps/desert.json'); - myGame.loader.addImageFile('tiles', 'assets/tiles/tmw_desert_spacing.png'); - myGame.loader.addImageFile('car', 'assets/sprites/car90.png'); - - myGame.loader.load(); - - } - - var map: Phaser.Tilemap; - var car: Phaser.Sprite; - var marker: Phaser.GeomSprite; - var tile: Phaser.Tile; - - function create() { - - map = myGame.add.tilemap('tiles', 'desert', Phaser.Tilemap.FORMAT_TILED_JSON); - - car = myGame.add.sprite(250, 200, 'car'); - car.setBounds(0, 0, map.widthInPixels - 32, map.heightInPixels - 32); - - marker = myGame.add.geomSprite(0, 0); - marker.createRectangle(32, 32); - marker.renderFill = false; - marker.lineColor = 'rgb(0,0,0)'; - - myGame.camera.follow(car); - myGame.onRenderCallback = render; - - } - - function update() { - - marker.x = myGame.math.snapToFloor(myGame.input.getWorldX(), 32); - marker.y = myGame.math.snapToFloor(myGame.input.getWorldY(), 32); - - car.velocity.x = 0; - car.velocity.y = 0; - car.angularVelocity = 0; - - if (myGame.input.keyboard.isDown(Phaser.Keyboard.LEFT)) - { - car.angularVelocity = -200; - } - else if (myGame.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) - { - car.angularVelocity = 200; - } - - if (myGame.input.keyboard.isDown(Phaser.Keyboard.UP)) - { - car.velocity.copyFrom(myGame.motion.velocityFromAngle(car.angle, 300)); - } - - } - - function render { - - tile = map.getTileFromInputXY(); - - myGame.stage.context.font = '18px Arial'; - myGame.stage.context.fillStyle = 'rgb(0,0,0)'; - myGame.stage.context.fillText(tile.toString(), 32, 32); - - myGame.input.renderDebugInfo(32, 64, 'rgb(0,0,0)'); - - } - -})(); diff --git a/Tests/tilemap/map draw.js b/Tests/tilemap/map draw.js deleted file mode 100644 index ef99703a2..000000000 --- a/Tests/tilemap/map draw.js +++ /dev/null @@ -1,39 +0,0 @@ -/// -/// -(function () { - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update); - function init() { - myGame.loader.addTextFile('platform', 'assets/maps/mapdraw.json'); - myGame.loader.addImageFile('tiles', 'assets/tiles/platformer_tiles.png'); - myGame.loader.addImageFile('carrot', 'assets/sprites/carrot.png'); - myGame.loader.load(); - } - var map; - var emitter; - var marker; - function create() { - map = myGame.add.tilemap('tiles', 'platform', Phaser.Tilemap.FORMAT_TILED_JSON); - map.setCollisionRange(21, 53); - map.setCollisionRange(105, 109); - myGame.camera.backgroundColor = 'rgb(47,154,204)'; - marker = myGame.add.geomSprite(0, 0); - marker.createRectangle(16, 16); - marker.renderFill = false; - marker.lineColor = 'rgb(0,0,0)'; - emitter = myGame.add.emitter(32, 80); - emitter.width = 700; - emitter.makeParticles('carrot', 100, false, 1); - emitter.gravity = 150; - emitter.bounce = 0.8; - emitter.start(false, 20, 0.05); - } - function update() { - // Collide everything with the map - map.collide(); - marker.x = myGame.math.snapToFloor(myGame.input.getWorldX(), 16); - marker.y = myGame.math.snapToFloor(myGame.input.getWorldY(), 16); - if(myGame.input.mousePointer.isDown) { - map.putTile(marker.x, marker.y, 32); - } - } -})(); diff --git a/Tests/tilemap/map draw.ts b/Tests/tilemap/map draw.ts deleted file mode 100644 index 5e2c994e8..000000000 --- a/Tests/tilemap/map draw.ts +++ /dev/null @@ -1,58 +0,0 @@ -/// -/// - -(function () { - - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update); - - function init() { - - myGame.loader.addTextFile('platform', 'assets/maps/mapdraw.json'); - myGame.loader.addImageFile('tiles', 'assets/tiles/platformer_tiles.png'); - myGame.loader.addImageFile('carrot', 'assets/sprites/carrot.png'); - - myGame.loader.load(); - - } - - var map: Phaser.Tilemap; - var emitter: Phaser.Emitter; - var marker: Phaser.GeomSprite; - - function create() { - - map = myGame.add.tilemap('tiles', 'platform', Phaser.Tilemap.FORMAT_TILED_JSON); - map.setCollisionRange(21,53); - map.setCollisionRange(105,109); - - myGame.camera.backgroundColor = 'rgb(47,154,204)'; - - marker = myGame.add.geomSprite(0, 0); - marker.createRectangle(16, 16); - marker.renderFill = false; - marker.lineColor = 'rgb(0,0,0)'; - - emitter = myGame.add.emitter(32, 80); - emitter.width = 700; - emitter.makeParticles('carrot', 100, false, 1); - emitter.gravity = 150; - emitter.bounce = 0.8; - emitter.start(false, 20, 0.05); - } - - function update() { - - // Collide everything with the map - map.collide(); - - marker.x = myGame.math.snapToFloor(myGame.input.getWorldX(), 16); - marker.y = myGame.math.snapToFloor(myGame.input.getWorldY(), 16); - - if (myGame.input.mousePointer.isDown) - { - map.putTile(marker.x, marker.y, 32); - } - - } - -})(); diff --git a/Tests/tilemap/put tile.js b/Tests/tilemap/put tile.js deleted file mode 100644 index b6ae38a97..000000000 --- a/Tests/tilemap/put tile.js +++ /dev/null @@ -1,52 +0,0 @@ -/// -/// -/// -(function () { - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update); - function init() { - myGame.loader.addTextFile('desert', 'assets/maps/desert.json'); - myGame.loader.addImageFile('tiles', 'assets/tiles/tmw_desert_spacing.png'); - myGame.loader.addImageFile('car', 'assets/sprites/car90.png'); - myGame.loader.load(); - } - var map; - var car; - var marker; - var tile; - function create() { - map = myGame.add.tilemap('tiles', 'desert', Phaser.Tilemap.FORMAT_TILED_JSON); - car = myGame.add.sprite(250, 200, 'car'); - car.setBounds(0, 0, map.widthInPixels - 32, map.heightInPixels - 32); - marker = myGame.add.geomSprite(0, 0); - marker.createRectangle(32, 32); - marker.renderFill = false; - marker.lineColor = 'rgb(0,0,0)'; - myGame.camera.follow(car); - myGame.onRenderCallback = render; - } - function paintTile() { - map.putTile(marker.x, marker.y, 32); - } - function update() { - marker.x = myGame.math.snapToFloor(myGame.input.getWorldX(), 32); - marker.y = myGame.math.snapToFloor(myGame.input.getWorldY(), 32); - car.velocity.x = 0; - car.velocity.y = 0; - car.angularVelocity = 0; - if(myGame.input.keyboard.isDown(Phaser.Keyboard.LEFT)) { - car.angularVelocity = -200; - } else if(myGame.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) { - car.angularVelocity = 200; - } - if(myGame.input.keyboard.isDown(Phaser.Keyboard.UP)) { - car.velocity.copyFrom(myGame.motion.velocityFromAngle(car.angle, 300)); - } - } - function render() { - tile = map.getTileFromInputXY(); - myGame.stage.context.font = '18px Arial'; - myGame.stage.context.fillStyle = 'rgb(0,0,0)'; - myGame.stage.context.fillText(tile.toString(), 32, 32); - myGame.input.renderDebugInfo(32, 64, 'rgb(0,0,0)'); - } -})(); diff --git a/Tests/tilemap/put tile.ts b/Tests/tilemap/put tile.ts deleted file mode 100644 index ce2397b99..000000000 --- a/Tests/tilemap/put tile.ts +++ /dev/null @@ -1,83 +0,0 @@ -/// -/// -/// - -(function () { - - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update); - - function init() { - - myGame.loader.addTextFile('desert', 'assets/maps/desert.json'); - myGame.loader.addImageFile('tiles', 'assets/tiles/tmw_desert_spacing.png'); - myGame.loader.addImageFile('car', 'assets/sprites/car90.png'); - - myGame.loader.load(); - - } - - var map: Phaser.Tilemap; - var car: Phaser.Sprite; - var marker: Phaser.GeomSprite; - var tile: Phaser.Tile; - - function create() { - - map = myGame.add.tilemap('tiles', 'desert', Phaser.Tilemap.FORMAT_TILED_JSON); - - car = myGame.add.sprite(250, 200, 'car'); - car.setBounds(0, 0, map.widthInPixels - 32, map.heightInPixels - 32); - - marker = myGame.add.geomSprite(0, 0); - marker.createRectangle(32, 32); - marker.renderFill = false; - marker.lineColor = 'rgb(0,0,0)'; - - myGame.camera.follow(car); - myGame.onRenderCallback = render; - } - - function paintTile() { - - map.putTile(marker.x, marker.y, 32); - - } - - function update() { - - marker.x = myGame.math.snapToFloor(myGame.input.getWorldX(), 32); - marker.y = myGame.math.snapToFloor(myGame.input.getWorldY(), 32); - - car.velocity.x = 0; - car.velocity.y = 0; - car.angularVelocity = 0; - - if (myGame.input.keyboard.isDown(Phaser.Keyboard.LEFT)) - { - car.angularVelocity = -200; - } - else if (myGame.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) - { - car.angularVelocity = 200; - } - - if (myGame.input.keyboard.isDown(Phaser.Keyboard.UP)) - { - car.velocity.copyFrom(myGame.motion.velocityFromAngle(car.angle, 300)); - } - - } - - function render { - - tile = map.getTileFromInputXY(); - - myGame.stage.context.font = '18px Arial'; - myGame.stage.context.fillStyle = 'rgb(0,0,0)'; - myGame.stage.context.fillText(tile.toString(), 32, 32); - - myGame.input.renderDebugInfo(32, 64, 'rgb(0,0,0)'); - - } - -})(); diff --git a/Tests/tilemap/random tiles.js b/Tests/tilemap/random tiles.js deleted file mode 100644 index 3da7e3788..000000000 --- a/Tests/tilemap/random tiles.js +++ /dev/null @@ -1,60 +0,0 @@ -/// -/// -/// -(function () { - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update); - function init() { - myGame.loader.addTextFile('desert', 'assets/maps/desert.json'); - myGame.loader.addImageFile('tiles', 'assets/tiles/tmw_desert_spacing.png'); - myGame.loader.addImageFile('car', 'assets/sprites/car90.png'); - myGame.loader.load(); - } - var map; - var car; - var marker; - var tile; - function create() { - map = myGame.add.tilemap('tiles', 'desert', Phaser.Tilemap.FORMAT_TILED_JSON); - car = myGame.add.sprite(250, 200, 'car'); - car.setBounds(0, 0, map.widthInPixels - 32, map.heightInPixels - 32); - marker = myGame.add.geomSprite(0, 0); - marker.createRectangle(32, 32); - marker.renderFill = false; - marker.lineColor = 'rgb(0,0,0)'; - myGame.camera.follow(car); - myGame.onRenderCallback = render; - myGame.input.onDown.add(randomTiles); - } - function randomTiles() { - map.currentLayer.randomiseTiles([ - 30, - 31, - 32, - 38, - 39, - 40 - ]); - } - function update() { - marker.x = myGame.math.snapToFloor(myGame.input.getWorldX(), 32); - marker.y = myGame.math.snapToFloor(myGame.input.getWorldY(), 32); - car.velocity.x = 0; - car.velocity.y = 0; - car.angularVelocity = 0; - if(myGame.input.keyboard.isDown(Phaser.Keyboard.LEFT)) { - car.angularVelocity = -200; - } else if(myGame.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) { - car.angularVelocity = 200; - } - if(myGame.input.keyboard.isDown(Phaser.Keyboard.UP)) { - car.velocity.copyFrom(myGame.motion.velocityFromAngle(car.angle, 300)); - } - } - function render() { - tile = map.getTileFromInputXY(); - myGame.stage.context.font = '18px Arial'; - myGame.stage.context.fillStyle = 'rgb(0,0,0)'; - myGame.stage.context.fillText(tile.toString(), 32, 32); - myGame.input.renderDebugInfo(32, 64, 'rgb(0,0,0)'); - } -})(); diff --git a/Tests/tilemap/random tiles.ts b/Tests/tilemap/random tiles.ts deleted file mode 100644 index 019fa284e..000000000 --- a/Tests/tilemap/random tiles.ts +++ /dev/null @@ -1,85 +0,0 @@ -/// -/// -/// - -(function () { - - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update); - - function init() { - - myGame.loader.addTextFile('desert', 'assets/maps/desert.json'); - myGame.loader.addImageFile('tiles', 'assets/tiles/tmw_desert_spacing.png'); - myGame.loader.addImageFile('car', 'assets/sprites/car90.png'); - - myGame.loader.load(); - - } - - var map: Phaser.Tilemap; - var car: Phaser.Sprite; - var marker: Phaser.GeomSprite; - var tile: Phaser.Tile; - - function create() { - - map = myGame.add.tilemap('tiles', 'desert', Phaser.Tilemap.FORMAT_TILED_JSON); - - car = myGame.add.sprite(250, 200, 'car'); - car.setBounds(0, 0, map.widthInPixels - 32, map.heightInPixels - 32); - - marker = myGame.add.geomSprite(0, 0); - marker.createRectangle(32, 32); - marker.renderFill = false; - marker.lineColor = 'rgb(0,0,0)'; - - myGame.camera.follow(car); - myGame.onRenderCallback = render; - - myGame.input.onDown.add(randomTiles); - } - - function randomTiles() { - - map.currentLayer.randomiseTiles([30, 31, 32, 38, 39, 40]); - - } - - function update() { - - marker.x = myGame.math.snapToFloor(myGame.input.getWorldX(), 32); - marker.y = myGame.math.snapToFloor(myGame.input.getWorldY(), 32); - - car.velocity.x = 0; - car.velocity.y = 0; - car.angularVelocity = 0; - - if (myGame.input.keyboard.isDown(Phaser.Keyboard.LEFT)) - { - car.angularVelocity = -200; - } - else if (myGame.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) - { - car.angularVelocity = 200; - } - - if (myGame.input.keyboard.isDown(Phaser.Keyboard.UP)) - { - car.velocity.copyFrom(myGame.motion.velocityFromAngle(car.angle, 300)); - } - - } - - function render { - - tile = map.getTileFromInputXY(); - - myGame.stage.context.font = '18px Arial'; - myGame.stage.context.fillStyle = 'rgb(0,0,0)'; - myGame.stage.context.fillText(tile.toString(), 32, 32); - - myGame.input.renderDebugInfo(32, 64, 'rgb(0,0,0)'); - - } - -})(); diff --git a/Tests/tilemap/replace tiles.js b/Tests/tilemap/replace tiles.js deleted file mode 100644 index 9242fbe95..000000000 --- a/Tests/tilemap/replace tiles.js +++ /dev/null @@ -1,53 +0,0 @@ -/// -/// -/// -(function () { - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update); - function init() { - myGame.loader.addTextFile('desert', 'assets/maps/desert.json'); - myGame.loader.addImageFile('tiles', 'assets/tiles/tmw_desert_spacing.png'); - myGame.loader.addImageFile('car', 'assets/sprites/car90.png'); - myGame.loader.load(); - } - var map; - var car; - var marker; - var tile; - function create() { - map = myGame.add.tilemap('tiles', 'desert', Phaser.Tilemap.FORMAT_TILED_JSON); - car = myGame.add.sprite(250, 200, 'car'); - car.setBounds(0, 0, map.widthInPixels - 32, map.heightInPixels - 32); - marker = myGame.add.geomSprite(0, 0); - marker.createRectangle(32, 32); - marker.renderFill = false; - marker.lineColor = 'rgb(0,0,0)'; - myGame.camera.follow(car); - myGame.onRenderCallback = render; - myGame.input.onDown.add(swapTiles); - } - function swapTiles() { - map.currentLayer.replaceTile(30, 31); - } - function update() { - marker.x = myGame.math.snapToFloor(myGame.input.getWorldX(), 32); - marker.y = myGame.math.snapToFloor(myGame.input.getWorldY(), 32); - car.velocity.x = 0; - car.velocity.y = 0; - car.angularVelocity = 0; - if(myGame.input.keyboard.isDown(Phaser.Keyboard.LEFT)) { - car.angularVelocity = -200; - } else if(myGame.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) { - car.angularVelocity = 200; - } - if(myGame.input.keyboard.isDown(Phaser.Keyboard.UP)) { - car.velocity.copyFrom(myGame.motion.velocityFromAngle(car.angle, 300)); - } - } - function render() { - tile = map.getTileFromInputXY(); - myGame.stage.context.font = '18px Arial'; - myGame.stage.context.fillStyle = 'rgb(0,0,0)'; - myGame.stage.context.fillText(tile.toString(), 32, 32); - myGame.input.renderDebugInfo(32, 64, 'rgb(0,0,0)'); - } -})(); diff --git a/Tests/tilemap/replace tiles.ts b/Tests/tilemap/replace tiles.ts deleted file mode 100644 index ff808e33b..000000000 --- a/Tests/tilemap/replace tiles.ts +++ /dev/null @@ -1,85 +0,0 @@ -/// -/// -/// - -(function () { - - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update); - - function init() { - - myGame.loader.addTextFile('desert', 'assets/maps/desert.json'); - myGame.loader.addImageFile('tiles', 'assets/tiles/tmw_desert_spacing.png'); - myGame.loader.addImageFile('car', 'assets/sprites/car90.png'); - - myGame.loader.load(); - - } - - var map: Phaser.Tilemap; - var car: Phaser.Sprite; - var marker: Phaser.GeomSprite; - var tile: Phaser.Tile; - - function create() { - - map = myGame.add.tilemap('tiles', 'desert', Phaser.Tilemap.FORMAT_TILED_JSON); - - car = myGame.add.sprite(250, 200, 'car'); - car.setBounds(0, 0, map.widthInPixels - 32, map.heightInPixels - 32); - - marker = myGame.add.geomSprite(0, 0); - marker.createRectangle(32, 32); - marker.renderFill = false; - marker.lineColor = 'rgb(0,0,0)'; - - myGame.camera.follow(car); - myGame.onRenderCallback = render; - - myGame.input.onDown.add(swapTiles); - } - - function swapTiles() { - - map.currentLayer.replaceTile(30, 31); - - } - - function update() { - - marker.x = myGame.math.snapToFloor(myGame.input.getWorldX(), 32); - marker.y = myGame.math.snapToFloor(myGame.input.getWorldY(), 32); - - car.velocity.x = 0; - car.velocity.y = 0; - car.angularVelocity = 0; - - if (myGame.input.keyboard.isDown(Phaser.Keyboard.LEFT)) - { - car.angularVelocity = -200; - } - else if (myGame.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) - { - car.angularVelocity = 200; - } - - if (myGame.input.keyboard.isDown(Phaser.Keyboard.UP)) - { - car.velocity.copyFrom(myGame.motion.velocityFromAngle(car.angle, 300)); - } - - } - - function render { - - tile = map.getTileFromInputXY(); - - myGame.stage.context.font = '18px Arial'; - myGame.stage.context.fillStyle = 'rgb(0,0,0)'; - myGame.stage.context.fillText(tile.toString(), 32, 32); - - myGame.input.renderDebugInfo(32, 64, 'rgb(0,0,0)'); - - } - -})(); diff --git a/Tests/tilemap/small map.js b/Tests/tilemap/small map.js deleted file mode 100644 index bf3b85baf..000000000 --- a/Tests/tilemap/small map.js +++ /dev/null @@ -1,42 +0,0 @@ -/// -/// -(function () { - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update); - function init() { - myGame.loader.addTextFile('jsontest', 'assets/maps/multi-layer-test.json'); - myGame.loader.addImageFile('jsontiles', 'assets/tiles/platformer_tiles.png'); - myGame.loader.addImageFile('overlay', 'assets/pics/scrollframe.png'); - myGame.loader.addImageFile('car', 'assets/sprites/car90.png'); - myGame.loader.load(); - } - var car; - var map; - var overlay; - var smallCam; - function create() { - map = myGame.add.tilemap('jsontiles', 'jsontest', Phaser.Tilemap.FORMAT_TILED_JSON); - car = myGame.add.sprite(300, 100, 'car'); - car.setBounds(0, 0, map.widthInPixels - 32, map.heightInPixels - 32); - // Hide the tilemap and car sprite from the main camera (it will still be seen by the smallCam) - map.hideFromCamera(myGame.camera); - car.hideFromCamera(myGame.camera); - smallCam = myGame.add.camera(32, 32, 352, 240); - smallCam.setBounds(0, 0, map.widthInPixels, map.heightInPixels); - smallCam.follow(car); - overlay = myGame.add.sprite(0, 0, 'overlay'); - overlay.hideFromCamera(smallCam); - } - function update() { - car.velocity.x = 0; - car.velocity.y = 0; - car.angularVelocity = 0; - if(myGame.input.keyboard.isDown(Phaser.Keyboard.LEFT)) { - car.angularVelocity = -200; - } else if(myGame.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) { - car.angularVelocity = 200; - } - if(myGame.input.keyboard.isDown(Phaser.Keyboard.UP)) { - car.velocity.copyFrom(myGame.motion.velocityFromAngle(car.angle, 300)); - } - } -})(); diff --git a/Tests/tilemap/small map.ts b/Tests/tilemap/small map.ts deleted file mode 100644 index 0014c0c0e..000000000 --- a/Tests/tilemap/small map.ts +++ /dev/null @@ -1,66 +0,0 @@ -/// -/// - -(function () { - - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update); - - function init() { - - myGame.loader.addTextFile('jsontest', 'assets/maps/multi-layer-test.json'); - myGame.loader.addImageFile('jsontiles', 'assets/tiles/platformer_tiles.png'); - myGame.loader.addImageFile('overlay', 'assets/pics/scrollframe.png'); - myGame.loader.addImageFile('car', 'assets/sprites/car90.png'); - - myGame.loader.load(); - - } - - var car: Phaser.Sprite; - var map: Phaser.Tilemap; - var overlay: Phaser.Sprite; - var smallCam: Phaser.Camera; - - function create() { - - map = myGame.add.tilemap('jsontiles', 'jsontest', Phaser.Tilemap.FORMAT_TILED_JSON); - - car = myGame.add.sprite(300, 100, 'car'); - car.setBounds(0, 0, map.widthInPixels - 32, map.heightInPixels - 32); - - // Hide the tilemap and car sprite from the main camera (it will still be seen by the smallCam) - map.hideFromCamera(myGame.camera); - car.hideFromCamera(myGame.camera); - - smallCam = myGame.add.camera(32, 32, 352, 240); - smallCam.setBounds(0, 0, map.widthInPixels, map.heightInPixels); - smallCam.follow(car); - - overlay = myGame.add.sprite(0, 0, 'overlay'); - overlay.hideFromCamera(smallCam); - - } - - function update() { - - car.velocity.x = 0; - car.velocity.y = 0; - car.angularVelocity = 0; - - if (myGame.input.keyboard.isDown(Phaser.Keyboard.LEFT)) - { - car.angularVelocity = -200; - } - else if (myGame.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) - { - car.angularVelocity = 200; - } - - if (myGame.input.keyboard.isDown(Phaser.Keyboard.UP)) - { - car.velocity.copyFrom(myGame.motion.velocityFromAngle(car.angle, 300)); - } - - } - -})(); diff --git a/Tests/tilemap/sprite draw tiles.js b/Tests/tilemap/sprite draw tiles.js deleted file mode 100644 index 301a20c17..000000000 --- a/Tests/tilemap/sprite draw tiles.js +++ /dev/null @@ -1,36 +0,0 @@ -/// -/// -/// -(function () { - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update); - function init() { - myGame.loader.addTextFile('desert', 'assets/maps/desert.json'); - myGame.loader.addImageFile('tiles', 'assets/tiles/tmw_desert_spacing.png'); - myGame.loader.addImageFile('car', 'assets/sprites/car90.png'); - myGame.loader.load(); - } - var map; - var car; - function create() { - map = myGame.add.tilemap('tiles', 'desert', Phaser.Tilemap.FORMAT_TILED_JSON); - // Fills the whole map to one tile - map.currentLayer.fillTile(30); - car = myGame.add.sprite(250, 200, 'car'); - car.setBounds(0, 0, map.widthInPixels - 32, map.heightInPixels - 32); - myGame.camera.follow(car); - } - function update() { - map.putTile(car.x + 16, car.y + 16, 34); - car.velocity.x = 0; - car.velocity.y = 0; - car.angularVelocity = 0; - if(myGame.input.keyboard.isDown(Phaser.Keyboard.LEFT)) { - car.angularVelocity = -200; - } else if(myGame.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) { - car.angularVelocity = 200; - } - if(myGame.input.keyboard.isDown(Phaser.Keyboard.UP)) { - car.velocity.copyFrom(myGame.motion.velocityFromAngle(car.angle, 300)); - } - } -})(); diff --git a/Tests/tilemap/sprite draw tiles.ts b/Tests/tilemap/sprite draw tiles.ts deleted file mode 100644 index 19c4c3d3d..000000000 --- a/Tests/tilemap/sprite draw tiles.ts +++ /dev/null @@ -1,59 +0,0 @@ -/// -/// -/// - -(function () { - - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update); - - function init() { - - myGame.loader.addTextFile('desert', 'assets/maps/desert.json'); - myGame.loader.addImageFile('tiles', 'assets/tiles/tmw_desert_spacing.png'); - myGame.loader.addImageFile('car', 'assets/sprites/car90.png'); - - myGame.loader.load(); - - } - - var map: Phaser.Tilemap; - var car: Phaser.Sprite; - - function create() { - - map = myGame.add.tilemap('tiles', 'desert', Phaser.Tilemap.FORMAT_TILED_JSON); - - // Fills the whole map to one tile - map.currentLayer.fillTile(30); - - car = myGame.add.sprite(250, 200, 'car'); - car.setBounds(0, 0, map.widthInPixels - 32, map.heightInPixels - 32); - - myGame.camera.follow(car); - } - - function update() { - - map.putTile(car.x + 16, car.y + 16, 34); - - car.velocity.x = 0; - car.velocity.y = 0; - car.angularVelocity = 0; - - if (myGame.input.keyboard.isDown(Phaser.Keyboard.LEFT)) - { - car.angularVelocity = -200; - } - else if (myGame.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) - { - car.angularVelocity = 200; - } - - if (myGame.input.keyboard.isDown(Phaser.Keyboard.UP)) - { - car.velocity.copyFrom(myGame.motion.velocityFromAngle(car.angle, 300)); - } - - } - -})(); diff --git a/Tests/tilemap/swap tiles.js b/Tests/tilemap/swap tiles.js deleted file mode 100644 index 17f3ca602..000000000 --- a/Tests/tilemap/swap tiles.js +++ /dev/null @@ -1,53 +0,0 @@ -/// -/// -/// -(function () { - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update); - function init() { - myGame.loader.addTextFile('desert', 'assets/maps/desert.json'); - myGame.loader.addImageFile('tiles', 'assets/tiles/tmw_desert_spacing.png'); - myGame.loader.addImageFile('car', 'assets/sprites/car90.png'); - myGame.loader.load(); - } - var map; - var car; - var marker; - var tile; - function create() { - map = myGame.add.tilemap('tiles', 'desert', Phaser.Tilemap.FORMAT_TILED_JSON); - car = myGame.add.sprite(250, 200, 'car'); - car.setBounds(0, 0, map.widthInPixels - 32, map.heightInPixels - 32); - marker = myGame.add.geomSprite(0, 0); - marker.createRectangle(32, 32); - marker.renderFill = false; - marker.lineColor = 'rgb(0,0,0)'; - myGame.camera.follow(car); - myGame.onRenderCallback = render; - myGame.input.onDown.add(swapTiles); - } - function swapTiles() { - map.currentLayer.swapTile(30, 31); - } - function update() { - marker.x = myGame.math.snapToFloor(myGame.input.getWorldX(), 32); - marker.y = myGame.math.snapToFloor(myGame.input.getWorldY(), 32); - car.velocity.x = 0; - car.velocity.y = 0; - car.angularVelocity = 0; - if(myGame.input.keyboard.isDown(Phaser.Keyboard.LEFT)) { - car.angularVelocity = -200; - } else if(myGame.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) { - car.angularVelocity = 200; - } - if(myGame.input.keyboard.isDown(Phaser.Keyboard.UP)) { - car.velocity.copyFrom(myGame.motion.velocityFromAngle(car.angle, 300)); - } - } - function render() { - tile = map.getTileFromInputXY(); - myGame.stage.context.font = '18px Arial'; - myGame.stage.context.fillStyle = 'rgb(0,0,0)'; - myGame.stage.context.fillText(tile.toString(), 32, 32); - myGame.input.renderDebugInfo(32, 64, 'rgb(0,0,0)'); - } -})(); diff --git a/Tests/tilemap/swap tiles.ts b/Tests/tilemap/swap tiles.ts deleted file mode 100644 index e68025528..000000000 --- a/Tests/tilemap/swap tiles.ts +++ /dev/null @@ -1,85 +0,0 @@ -/// -/// -/// - -(function () { - - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update); - - function init() { - - myGame.loader.addTextFile('desert', 'assets/maps/desert.json'); - myGame.loader.addImageFile('tiles', 'assets/tiles/tmw_desert_spacing.png'); - myGame.loader.addImageFile('car', 'assets/sprites/car90.png'); - - myGame.loader.load(); - - } - - var map: Phaser.Tilemap; - var car: Phaser.Sprite; - var marker: Phaser.GeomSprite; - var tile: Phaser.Tile; - - function create() { - - map = myGame.add.tilemap('tiles', 'desert', Phaser.Tilemap.FORMAT_TILED_JSON); - - car = myGame.add.sprite(250, 200, 'car'); - car.setBounds(0, 0, map.widthInPixels - 32, map.heightInPixels - 32); - - marker = myGame.add.geomSprite(0, 0); - marker.createRectangle(32, 32); - marker.renderFill = false; - marker.lineColor = 'rgb(0,0,0)'; - - myGame.camera.follow(car); - myGame.onRenderCallback = render; - - myGame.input.onDown.add(swapTiles); - } - - function swapTiles() { - - map.currentLayer.swapTile(30, 31); - - } - - function update() { - - marker.x = myGame.math.snapToFloor(myGame.input.getWorldX(), 32); - marker.y = myGame.math.snapToFloor(myGame.input.getWorldY(), 32); - - car.velocity.x = 0; - car.velocity.y = 0; - car.angularVelocity = 0; - - if (myGame.input.keyboard.isDown(Phaser.Keyboard.LEFT)) - { - car.angularVelocity = -200; - } - else if (myGame.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) - { - car.angularVelocity = 200; - } - - if (myGame.input.keyboard.isDown(Phaser.Keyboard.UP)) - { - car.velocity.copyFrom(myGame.motion.velocityFromAngle(car.angle, 300)); - } - - } - - function render { - - tile = map.getTileFromInputXY(); - - myGame.stage.context.font = '18px Arial'; - myGame.stage.context.fillStyle = 'rgb(0,0,0)'; - myGame.stage.context.fillText(tile.toString(), 32, 32); - - myGame.input.renderDebugInfo(32, 64, 'rgb(0,0,0)'); - - } - -})(); diff --git a/Tests/tweens/bounce.js b/Tests/tweens/bounce.js deleted file mode 100644 index a50fd04bc..000000000 --- a/Tests/tweens/bounce.js +++ /dev/null @@ -1,22 +0,0 @@ -/// -(function () { - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create); - function init() { - myGame.loader.addImageFile('atari', 'assets/sprites/atari130xe.png'); - myGame.loader.load(); - } - var atari; - function create() { - atari = myGame.add.sprite(300, 0, 'atari'); - startBounceTween(); - } - function startBounceTween() { - atari.y = 0; - var bounce = myGame.add.tween(atari); - bounce.to({ - y: 500 - }, 1000 + Math.random() * 3000, Phaser.Easing.Bounce.Out); - bounce.onComplete.add(startBounceTween, this); - bounce.start(); - } -})(); diff --git a/Tests/tweens/bounce.ts b/Tests/tweens/bounce.ts deleted file mode 100644 index 575cb9502..000000000 --- a/Tests/tweens/bounce.ts +++ /dev/null @@ -1,36 +0,0 @@ -/// - -(function () { - - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create); - - function init() { - - myGame.loader.addImageFile('atari', 'assets/sprites/atari130xe.png'); - - myGame.loader.load(); - - } - - var atari: Phaser.Sprite; - - function create() { - - atari = myGame.add.sprite(300, 0, 'atari'); - - startBounceTween(); - } - - function startBounceTween() { - - atari.y = 0; - - var bounce: Phaser.Tween = myGame.add.tween(atari); - - bounce.to({ y: 500 }, 1000 + Math.random() * 3000, Phaser.Easing.Bounce.Out); - bounce.onComplete.add(startBounceTween, this); - bounce.start(); - - } - -})(); diff --git a/Tests/tweens/elastic.js b/Tests/tweens/elastic.js deleted file mode 100644 index 5d793f574..000000000 --- a/Tests/tweens/elastic.js +++ /dev/null @@ -1,15 +0,0 @@ -/// -(function () { - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create); - function init() { - myGame.loader.addImageFile('atari', 'assets/sprites/atari130xe.png'); - myGame.loader.load(); - } - function create() { - var atari = myGame.add.sprite(300, 0, 'atari'); - // Here is the short-hand way of creating a tween, by chaining the call to it: - myGame.add.tween(atari).to({ - y: 400 - }, 5000, Phaser.Easing.Elastic.Out, true); - } -})(); diff --git a/Tests/tweens/elastic.ts b/Tests/tweens/elastic.ts deleted file mode 100644 index 6d60f5b73..000000000 --- a/Tests/tweens/elastic.ts +++ /dev/null @@ -1,24 +0,0 @@ -/// - -(function () { - - var myGame = new Phaser.Game(this, 'game', 800, 600, init, create); - - function init() { - - myGame.loader.addImageFile('atari', 'assets/sprites/atari130xe.png'); - - myGame.loader.load(); - - } - - function create() { - - var atari = myGame.add.sprite(300, 0, 'atari'); - - // Here is the short-hand way of creating a tween, by chaining the call to it: - myGame.add.tween(atari).to({ y: 400 }, 5000, Phaser.Easing.Elastic.Out, true); - - } - -})(); diff --git a/build/phaser-fx.d.ts b/build/phaser-fx.d.ts index 87feeb0ff..2a32af5d6 100644 --- a/build/phaser-fx.d.ts +++ b/build/phaser-fx.d.ts @@ -25,6 +25,37 @@ module Phaser.FX.Camera { } } /** +* Phaser - FX - Camera - Border +* +* Creates a border around a camera. +*/ +module Phaser.FX.Camera { + class Border { + constructor(game: Game, parent: Camera); + private _game; + private _parent; + /** + * Whether render border of this camera or not. (default is false) + * @type {boolean} + */ + public showBorder: bool; + /** + * Color of border of this camera. (in css color string) + * @type {string} + */ + public borderColor: string; + /** + * You can name the function that starts the effect whatever you like, but we used 'start' in our effects. + */ + public start(): void; + /** + * Post-render is called during the objects render cycle, after the children/image data has been rendered. + * It happens directly BEFORE a canvas context.restore has happened if added to a Camera. + */ + public postRender(camera: Camera, cameraX: number, cameraY: number, cameraWidth: number, cameraHeight: number): void; + } +} +/** * Phaser - FX - Camera - Template * * A Template FX file you can use to create your own Camera FX. @@ -92,7 +123,7 @@ module Phaser.FX.Camera { * This is the rectangular region to grab from the Camera used in the Mirror effect * It is rendered to the Stage at Mirror.x/y (note the use of Stage coordinates, not World coordinates) */ - public start(x: number, y: number, region: Quad, fillColor?: string): void; + public start(x: number, y: number, region: Rectangle, fillColor?: string): void; /** * Post-render is called during the objects render cycle, after the children/image data has been rendered. * It happens directly BEFORE a canvas context.restore has happened if added to a Camera. @@ -101,6 +132,51 @@ module Phaser.FX.Camera { } } /** +* Phaser - FX - Camera - Shadow +* +* Creates a drop-shadow effect on the camera window. +*/ +module Phaser.FX.Camera { + class Shadow { + constructor(game: Game, parent: Camera); + private _game; + private _parent; + /** + * Render camera shadow or not. (default is false) + * @type {boolean} + */ + public showShadow: bool; + /** + * Color of shadow, in css color string. + * @type {string} + */ + public shadowColor: string; + /** + * Blur factor of shadow. + * @type {number} + */ + public shadowBlur: number; + /** + * Offset of the shadow from camera's position. + * @type {Point} + */ + public shadowOffset: Point; + /** + * You can name the function that starts the effect whatever you like, but we used 'start' in our effects. + */ + public start(): void; + /** + * Pre-render is called at the start of the object render cycle, before any transforms have taken place. + * It happens directly AFTER a canvas context.save has happened if added to a Camera. + */ + public preRender(camera: Camera, cameraX: number, cameraY: number, cameraWidth: number, cameraHeight: number): void; + /** + * render is called during the objects render cycle, right after all transforms have finished, but before any children/image data is rendered. + */ + public render(camera: Camera, cameraX: number, cameraY: number, cameraWidth: number, cameraHeight: number): void; + } +} +/** * Phaser - FX - Camera - Scanlines * * Give your game that classic retro feel! diff --git a/build/phaser-fx.js b/build/phaser-fx.js index 89db41375..6499d8dac 100644 --- a/build/phaser-fx.js +++ b/build/phaser-fx.js @@ -1,8 +1,7 @@ var Phaser; (function (Phaser) { (function (FX) { - /// - /// + /// /** * Phaser - FX - Camera - Flash * @@ -73,9 +72,7 @@ var Phaser; var Phaser; (function (Phaser) { (function (FX) { - /// - /// - /// + /// /** * Phaser - FX - Camera - Border * @@ -110,7 +107,7 @@ var Phaser; if(this.showBorder == true) { this._game.stage.context.strokeStyle = this.borderColor; this._game.stage.context.lineWidth = 1; - this._game.stage.context.rect(this._sx, this._sy, this.worldView.width, this.worldView.height); + this._game.stage.context.rect(camera.scaledX, camera.scaledY, camera.worldView.width, camera.worldView.height); this._game.stage.context.stroke(); } }; @@ -125,9 +122,7 @@ var Phaser; var Phaser; (function (Phaser) { (function (FX) { - /// - /// - /// + /// /** * Phaser - FX - Camera - Template * @@ -183,9 +178,7 @@ var Phaser; var Phaser; (function (Phaser) { (function (FX) { - /// - /// - /// + /// /** * Phaser - FX - Camera - Mirror * @@ -228,9 +221,10 @@ var Phaser; * It happens directly BEFORE a canvas context.restore has happened if added to a Camera. */ function (camera, cameraX, cameraY, cameraWidth, cameraHeight) { - if(this.cls) { - this._context.clearRect(0, 0, this._mirrorWidth, this._mirrorHeight); - } + //if (this.cls) + //{ + // this._context.clearRect(0, 0, this._mirrorWidth, this._mirrorHeight); + //} this._sx = cameraX + this._mirrorX; this._sy = cameraY + this._mirrorY; if(this.flipX == true && this.flipY == false) { @@ -273,9 +267,7 @@ var Phaser; var Phaser; (function (Phaser) { (function (FX) { - /// - /// - /// + /// /** * Phaser - FX - Camera - Shadow * @@ -301,9 +293,9 @@ var Phaser; this.shadowBlur = 10; /** * Offset of the shadow from camera's position. - * @type {MicroPoint} + * @type {Point} */ - this.shadowOffset = new Phaser.MicroPoint(4, 4); + this.shadowOffset = new Phaser.Point(4, 4); this._game = game; this._parent = parent; } @@ -347,9 +339,7 @@ var Phaser; var Phaser; (function (Phaser) { (function (FX) { - /// - /// - /// + /// /** * Phaser - FX - Camera - Scanlines * @@ -380,8 +370,7 @@ var Phaser; var Phaser; (function (Phaser) { (function (FX) { - /// - /// + /// /** * Phaser - FX - Camera - Shake * @@ -393,7 +382,7 @@ var Phaser; this._fxShakeIntensity = 0; this._fxShakeDuration = 0; this._fxShakeComplete = null; - this._fxShakeOffset = new Phaser.MicroPoint(0, 0); + this._fxShakeOffset = new Phaser.Point(0, 0); this._fxShakeDirection = 0; this._fxShakePrevX = 0; this._fxShakePrevY = 0; @@ -473,8 +462,7 @@ var Phaser; var Phaser; (function (Phaser) { (function (FX) { - /// - /// + /// /** * Phaser - FX - Camera - Fade * diff --git a/build/phaser.d.ts b/build/phaser.d.ts index 4baa1d4c4..aa0778276 100644 --- a/build/phaser.d.ts +++ b/build/phaser.d.ts @@ -1,1388 +1,161 @@ /** -* Phaser - Basic +* Phaser - Loader * -* A useful "generic" object on which all GameObjects and Groups are based. -* It has no size, position or graphical data. +* The Loader handles loading all external content such as Images, Sounds, Texture Atlases and data files. +* It uses a combination of Image() loading and xhr and provides for progress and completion callbacks. */ module Phaser { - class Basic { + class Loader { /** - * Instantiate the basic object. - */ - constructor(game: Game); - /** - * The essential reference to the main game object - */ - public _game: Game; - /** - * Allows you to give this object a name. Useful for debugging, but not actually used internally. - */ - public name: string; - /** - * IDs seem like they could be pretty useful, huh? - * They're not actually used for anything yet though. - */ - public ID: number; - /** - * A boolean to store if this object is a Group or not. - * Saves us an expensive typeof check inside of core loops. - */ - public isGroup: bool; - /** - * Controls whether update() and draw() are automatically called by State/Group. - */ - public exists: bool; - /** - * Controls whether update() is automatically called by State/Group. - */ - public active: bool; - /** - * Controls whether draw() is automatically called by State/Group. - */ - public visible: bool; - /** - * Useful state for many game objects - "dead" (!alive) vs alive. - * kill() and revive() both flip this switch (along with exists, but you can override that). - */ - public alive: bool; - /** - * Setting this to true will prevent the object from being updated during the main game loop (you will have to call update on it yourself) - */ - public ignoreGlobalUpdate: bool; - /** - * Setting this to true will prevent the object from being rendered during the main game loop (you will have to call render on it yourself) - */ - public ignoreGlobalRender: bool; - /** - * Setting this to true will prevent the object from appearing - * when the visual debug mode in the debugger overlay is toggled on. - */ - public ignoreDrawDebug: bool; - /** - * Override this to null out iables or manually call - * destroy() on class members if necessary. - * Don't forget to call super.destroy()! - */ - public destroy(): void; - /** - * Pre-update is called right before update() on each object in the game loop. - */ - public preUpdate(): void; - /** - * Override this to update your class's position and appearance. - * This is where most of your game rules and behavioral code will go. - */ - public update(forceUpdate?: bool): void; - /** - * Post-update is called right after update() on each object in the game loop. - */ - public postUpdate(): void; - public render(camera: Camera, cameraOffsetX: number, cameraOffsetY: number, forceRender?: bool): void; - /** - * Handy for "killing" game objects. - * Default behavior is to flag them as nonexistent AND dead. - * However, if you want the "corpse" to remain in the game, - * like to animate an effect or whatever, you should override this, - * setting only alive to false, and leaving exists true. - */ - public kill(): void; - /** - * Handy for bringing game objects "back to life". Just sets alive and exists back to true. - * In practice, this is most often called by Object.reset(). - */ - public revive(): void; - /** - * Convert object to readable string name. Useful for debugging, save games, etc. - */ - public toString(): string; - } -} -/** -* Phaser - SignalBinding -* -* An object that represents a binding between a Signal and a listener function. -* Based on JS Signals by Miller Medeiros. Converted by TypeScript by Richard Davey. -* Released under the MIT license -* http://millermedeiros.github.com/js-signals/ -*/ -module Phaser { - class SignalBinding { - /** - * Object that represents a binding between a Signal and a listener function. - *
- This is an internal constructor and shouldn't be called by regular users. - *
- inspired by Joa Ebert AS3 SignalBinding and Robert Penner's Slot classes. - * @author Miller Medeiros - * @constructor - * @internal - * @name SignalBinding - * @param {Signal} signal Reference to Signal object that listener is currently bound to. - * @param {Function} listener Handler function bound to the signal. - * @param {boolean} isOnce If binding should be executed just once. - * @param {Object} [listenerContext] Context on which listener will be executed (object that should represent the `this` variable inside listener function). - * @param {Number} [priority] The priority level of the event listener. (default = 0). - */ - constructor(signal: Signal, listener, isOnce: bool, listenerContext, priority?: number); - /** - * Handler function bound to the signal. - * @type Function - * @private - */ - private _listener; - /** - * If binding should be executed just once. - * @type boolean - * @private - */ - private _isOnce; - /** - * Context on which listener will be executed (object that should represent the `this` variable inside listener function). - * @memberOf SignalBinding.prototype - * @name context - * @type Object|undefined|null - */ - public context; - /** - * Reference to Signal object that listener is currently bound to. - * @type Signal - * @private - */ - private _signal; - /** - * Listener priority - * @type Number - */ - public priority: number; - /** - * If binding is active and should be executed. - * @type boolean - */ - public active: bool; - /** - * Default parameters passed to listener during `Signal.dispatch` and `SignalBinding.execute`. (curried parameters) - * @type Array|null - */ - public params; - /** - * Call listener passing arbitrary parameters. - *

If binding was added using `Signal.addOnce()` it will be automatically removed from signal dispatch queue, this method is used internally for the signal dispatch.

- * @param {Array} [paramsArr] Array of parameters that should be passed to the listener - * @return {*} Value returned by the listener. - */ - public execute(paramsArr?: any[]); - /** - * Detach binding from signal. - * - alias to: mySignal.remove(myBinding.getListener()); - * @return {Function|null} Handler function bound to the signal or `null` if binding was previously detached. - */ - public detach(); - /** - * @return {Boolean} `true` if binding is still bound to the signal and have a listener. - */ - public isBound(): bool; - /** - * @return {boolean} If SignalBinding will only be executed once. - */ - public isOnce(): bool; - /** - * @return {Function} Handler function bound to the signal. - */ - public getListener(); - /** - * @return {Signal} Signal that listener is currently bound to. - */ - public getSignal(): Signal; - /** - * Delete instance properties - * @private - */ - public _destroy(): void; - /** - * @return {string} String representation of the object. - */ - public toString(): string; - } -} -/** -* Phaser - Signal -* -* A Signal is used for object communication via a custom broadcaster instead of Events. -* Based on JS Signals by Miller Medeiros. Converted by TypeScript by Richard Davey. -* Released under the MIT license -* http://millermedeiros.github.com/js-signals/ -*/ -module Phaser { - class Signal { - /** - * - * @property _bindings - * @type Array - * @private - */ - private _bindings; - /** - * - * @property _prevParams - * @type Any - * @private - */ - private _prevParams; - /** - * Signals Version Number - * @property VERSION - * @type String - * @const - */ - static VERSION: string; - /** - * If Signal should keep record of previously dispatched parameters and - * automatically execute listener during `add()`/`addOnce()` if Signal was - * already dispatched before. - * @type boolean - */ - public memorize: bool; - /** - * @type boolean - * @private - */ - private _shouldPropagate; - /** - * If Signal is active and should broadcast events. - *

IMPORTANT: Setting this property during a dispatch will only affect the next dispatch, if you want to stop the propagation of a signal use `halt()` instead.

- * @type boolean - */ - public active: bool; - /** - * - * @method validateListener - * @param {Any} listener - * @param {Any} fnName - */ - public validateListener(listener, fnName): void; - /** - * @param {Function} listener - * @param {boolean} isOnce - * @param {Object} [listenerContext] - * @param {Number} [priority] - * @return {SignalBinding} - * @private - */ - private _registerListener(listener, isOnce, listenerContext, priority); - /** - * - * @method _addBinding - * @param {SignalBinding} binding - * @private - */ - private _addBinding(binding); - /** - * - * @method _indexOfListener - * @param {Function} listener - * @return {number} - * @private - */ - private _indexOfListener(listener, context); - /** - * Check if listener was attached to Signal. - * @param {Function} listener - * @param {Object} [context] - * @return {boolean} if Signal has the specified listener. - */ - public has(listener, context?: any): bool; - /** - * Add a listener to the signal. - * @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 {SignalBinding} An Object representing the binding between the Signal and listener. - */ - public add(listener, listenerContext?: any, priority?: number): SignalBinding; - /** - * Add listener to the signal that should be removed after first execution (will be executed only once). - * @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 {SignalBinding} An Object representing the binding between the Signal and listener. - */ - public addOnce(listener, listenerContext?: any, priority?: number): SignalBinding; - /** - * Remove a single listener from the dispatch queue. - * @param {Function} listener Handler function that should be removed. - * @param {Object} [context] Execution context (since you can add the same handler multiple times if executing in a different context). - * @return {Function} Listener handler function. - */ - public remove(listener, context?: any); - /** - * Remove all listeners from the Signal. - */ - public removeAll(): void; - /** - * @return {number} Number of listeners attached to the Signal. - */ - public getNumListeners(): number; - /** - * Stop propagation of the event, blocking the dispatch to next listeners on the queue. - *

IMPORTANT: should be called only during signal dispatch, calling it before/after dispatch won't affect signal broadcast.

- * @see Signal.prototype.disable - */ - public halt(): void; - /** - * Dispatch/Broadcast Signal to all listeners added to the queue. - * @param {...*} [params] Parameters that should be passed to each handler. - */ - public dispatch(...paramsArr: any[]): void; - /** - * Forget memorized arguments. - * @see Signal.memorize - */ - public forget(): void; - /** - * Remove all bindings from signal and destroy any reference to external objects (destroy Signal object). - *

IMPORTANT: calling any method on the signal instance after calling dispose will throw errors.

- */ - public dispose(): void; - /** - * @return {string} String representation of the object. - */ - public toString(): string; - } -} -/** -* Phaser - CollisionMask -*/ -module Phaser { - class CollisionMask { - /** - * CollisionMask constructor. Creates a new CollisionMask for the given GameObject. + * Loader constructor * * @param game {Phaser.Game} Current game instance. - * @param parent {Phaser.GameObject} The GameObject this CollisionMask belongs to. - * @param x {number} The initial x position of the CollisionMask. - * @param y {number} The initial y position of the CollisionMask. - * @param width {number} The width of the CollisionMask. - * @param height {number} The height of the CollisionMask. + * @param callback {function} This will be called when assets completely loaded. */ - constructor(game: Game, parent: GameObject, x: number, y: number, width: number, height: number); - private _game; - private _parent; - private _ref; - /** - * Geom type of this sprite. (available: QUAD, POINT, CIRCLE, LINE, RECTANGLE, POLYGON) - * @type {number} - */ - public type: number; - /** - * Quad (a smaller version of Rectangle). - * @type {number} - */ - static QUAD: number; - /** - * Point. - * @type {number} - */ - static POINT: number; - /** - * Circle. - * @type {number} - */ - static CIRCLE: number; - /** - * Line. - * @type {number} - */ - static LINE: number; - /** - * Rectangle. - * @type {number} - */ - static RECTANGLE: number; - /** - * Polygon. - * @type {number} - */ - static POLYGON: number; - /** - * Rectangle shape container. A Rectangle instance. - * @type {Rectangle} - */ - public quad: Quad; - /** - * Point shape container. A Point instance. - * @type {Point} - */ - public point: Point; - /** - * Circle shape container. A Circle instance. - * @type {Circle} - */ - public circle: Circle; - /** - * Line shape container. A Line instance. - * @type {Line} - */ - public line: Line; - /** - * Rectangle shape container. A Rectangle instance. - * @type {Rectangle} - */ - public rect: Rectangle; - /** - * A value from the top-left of the GameObject frame that this collisionMask is offset to. - * If the CollisionMask is a Quad/Rectangle the offset relates to the top-left of that Quad. - * If the CollisionMask is a Circle the offset relates to the center of the circle. - * @type {MicroPoint} - */ - public offset: MicroPoint; - /** - * The previous x/y coordinates of the CollisionMask, used for hull calculations - * @type {MicroPoint} - */ - public last: MicroPoint; - /** - * Create a circle shape with specific diameter. - * @param diameter {number} Diameter of the circle. - * @return {CollisionMask} This - */ - public createCircle(diameter: number): CollisionMask; - /** - * Pre-update is called right before update() on each object in the game loop. - */ - public preUpdate(): void; - public update(): void; - /** - * Renders the bounding box around this Sprite and the contact points. Useful for visually debugging. - * @param camera {Camera} Camera the bound will be rendered to. - * @param cameraOffsetX {number} X offset of bound to the camera. - * @param cameraOffsetY {number} Y offset of bound to the camera. - */ - public render(camera: Camera, cameraOffsetX: number, cameraOffsetY: number): void; - /** - * Destroy all objects and references belonging to this CollisionMask - */ - public destroy(): void; - public intersectsRaw(left: number, right: number, top: number, bottom: number): bool; - public intersectsVector(vector: Vector2): bool; - /** - * Gives a basic boolean response to a geometric collision. - * If you need the details of the collision use the Collision functions instead and inspect the IntersectResult object. - * @param source {GeomSprite} Sprite you want to check. - * @return {boolean} Whether they overlaps or not. - */ - public intersects(source: CollisionMask): bool; - public checkHullIntersection(mask: CollisionMask): bool; - public hullWidth : number; - public hullHeight : number; - public hullX : number; - public hullY : number; - public deltaXAbs : number; - public deltaYAbs : number; - public deltaX : number; - public deltaY : number; - public x : number; - public y : number; - public width : number; - public height : number; - public left : number; - public right : number; - public top : number; - public bottom : number; - public halfWidth : number; - public halfHeight : number; - } -} -/** -* Phaser - GameObject -* -* This is the base GameObject on which all other game objects are derived. It contains all the logic required for position, -* motion, size, collision and input. -*/ -module Phaser { - class GameObject extends Basic { - /** - * GameObject constructor - * - * Create a new GameObject object at specific position with specific width and height. - * - * @param [x] {number} The x position of the object. - * @param [y] {number} The y position of the object. - * @param [width] {number} The width of the object. - * @param [height] {number} The height of the object. - */ - constructor(game: Game, x?: number, y?: number, width?: number, height?: number); - /** - * Angle of this object. - * @type {number} - */ - private _angle; - /** - * Pivot position enum: at the top-left corner. - * @type {number} - */ - static ALIGN_TOP_LEFT: number; - /** - * Pivot position enum: at the top-center corner. - * @type {number} - */ - static ALIGN_TOP_CENTER: number; - /** - * Pivot position enum: at the top-right corner. - * @type {number} - */ - static ALIGN_TOP_RIGHT: number; - /** - * Pivot position enum: at the center-left corner. - * @type {number} - */ - static ALIGN_CENTER_LEFT: number; - /** - * Pivot position enum: at the center corner. - * @type {number} - */ - static ALIGN_CENTER: number; - /** - * Pivot position enum: at the center-right corner. - * @type {number} - */ - static ALIGN_CENTER_RIGHT: number; - /** - * Pivot position enum: at the bottom-left corner. - * @type {number} - */ - static ALIGN_BOTTOM_LEFT: number; - /** - * Pivot position enum: at the bottom-center corner. - * @type {number} - */ - static ALIGN_BOTTOM_CENTER: number; - /** - * Pivot position enum: at the bottom-right corner. - * @type {number} - */ - static ALIGN_BOTTOM_RIGHT: number; - /** - * Enum value for outOfBoundsAction. Stop the object when is out of world bounds. - * @type {number} - */ - static OUT_OF_BOUNDS_STOP: number; - /** - * Enum value for outOfBoundsAction. Kill the object when is out of world bounds. - * @type {number} - */ - static OUT_OF_BOUNDS_KILL: number; - /** - * A reference to the Canvas this GameObject will render to - * @type {HTMLCanvasElement} - */ - public canvas: HTMLCanvasElement; - /** - * A reference to the Canvas Context2D this GameObject will render to - * @type {CanvasRenderingContext2D} - */ - public context: CanvasRenderingContext2D; - /** - * Position of this object after scrolling. - * @type {MicroPoint} - */ - public _point: MicroPoint; - /** - * An Array of Cameras to which this GameObject won't render - * @type {Array} - */ - public cameraBlacklist: number[]; - /** - * Rectangle container of this object. - * @type {Rectangle} - */ - public frameBounds: Rectangle; - /** - * This objects CollisionMask - * @type {CollisionMask} - */ - public collisionMask: CollisionMask; - /** - * A rectangular area which is object is allowed to exist within. If it travels outside of this area it will perform the outOfBoundsAction. - * @type {Quad} - */ - public worldBounds: Quad; - /** - * What action will be performed when object is out of the worldBounds. - * This will default to GameObject.OUT_OF_BOUNDS_STOP. - * @type {number} - */ - public outOfBoundsAction: number; - /** - * At which point the graphic of this object will align to. - * Align of the object will default to GameObject.ALIGN_TOP_LEFT. - * @type {number} - */ - public align: number; - /** - * Orientation of the object. - * @type {number} - */ - public facing: number; - /** - * Set alpha to a number between 0 and 1 to change the opacity. - * @type {number} - */ - public alpha: number; - /** - * Scale factor of the object. - * @type {MicroPoint} - */ - public scale: MicroPoint; - /** - * Origin is the anchor point that the object will rotate by. - * The origin will default to its center. - * @type {MicroPoint} - */ - public origin: MicroPoint; - /** - * Z-order value of the object. - */ - public z: number; - /** - * This value is added to the angle of the GameObject. - * For example if you had a sprite drawn facing straight up then you could set - * rotationOffset to 90 and it would correspond correctly with Phasers rotation system - * @type {number} - */ - public rotationOffset: number; - /** - * Controls if the GameObject is rendered rotated or not. - * If renderRotation is false then the object can still rotate but it will never be rendered rotated. - * @type {boolean} - */ - public renderRotation: bool; - /** - * Whether this object will be moved by impacts with other objects or not. - * @type {boolean} - */ - public immovable: bool; - /** - * Basic speed of this object. - * - * Velocity is given in pixels per second. Therefore a velocity of - * 100 will move at a rate of 100 pixels every 1000 ms (1sec). It's not balls-on - * accurate due to the way timers work, but it's pretty close. Expect tolerance - * of +- 10 px. Also that speed assumes no drag. - * - * @type {MicroPoint} - */ - public velocity: MicroPoint; - /** - * The virtual mass of the object. - * @type {number} - */ - public mass: number; - /** - * The bounciness of the object. - * @type {number} - */ - public elasticity: number; - /** - * How fast the speed of this object is changing. - * @type {number} - */ - public acceleration: MicroPoint; - /** - * This isn't drag exactly, more like deceleration that is only applied - * when acceleration is not affecting the sprite. - * @type {MicroPoint} - */ - public drag: MicroPoint; - /** - * It will cap the speed automatically if you use the acceleration - * to change its velocity. - * @type {MicroPoint} - */ - public maxVelocity: MicroPoint; - /** - * How fast this object is rotating. - * @type {number} - */ - public angularVelocity: number; - /** - * How fast angularVelocity of this object is changing. - * @type {number} - */ - public angularAcceleration: number; - /** - * Deacceleration of angularVelocity will be applied when it's rotating. - * @type {number} - */ - public angularDrag: number; - /** - * It will cap the rotate speed automatically if you use the angularAcceleration - * to change its angularVelocity. - * @type {number} - */ - public maxAngular: number; - /** - * A point that can store numbers from 0 to 1 (for X and Y independently) - * which governs how much this object is affected by the camera . - * @type {MicroPoint} - */ - public scrollFactor: MicroPoint; - /** - * Handy for storing health percentage or armor points or whatever. - * @type {number} - */ - public health: number; - /** - * Set this to false if you want to skip the automatic motion/movement stuff - * (see updateMotion()). - * @type {boolean} - */ - public moves: bool; - /** - * Bit field of flags (use with UP, DOWN, LEFT, RIGHT, etc) indicating surface contacts. - * @type {number} - */ - public touching: number; - /** - * Bit field of flags (use with UP, DOWN, LEFT, RIGHT, etc) indicating surface contacts from the previous game loop step. - * @type {number} - */ - public wasTouching: number; - /** - * Bit field of flags (use with UP, DOWN, LEFT, RIGHT, etc) indicating collision directions. - * @type {number} - */ - public allowCollisions: number; - /** - * Important variable for collision processing. - * @type {MicroPoint} - */ - public last: MicroPoint; - public inputEnabled: bool; - private _inputOver; - public onInputOver: Signal; - public onInputOut: Signal; - public onInputDown: Signal; - public onInputUp: Signal; - /** - * Pre-update is called right before update() on each object in the game loop. - */ - public preUpdate(): void; - /** - * Override this function to update your class's position and appearance. - */ - public update(): void; - /** - * Automatically called after update() by the game loop. - */ - public postUpdate(): void; - /** - * Update input. - */ - private updateInput(); - /** - * Internal function for updating the position and speed of this object. - */ - private updateMotion(); - /** - * Checks to see if some GameObject overlaps this GameObject or Group. - * If the group has a LOT of things in it, it might be faster to use Collision.overlaps(). - * WARNING: Currently tilemaps do NOT support screen space overlap checks! - * - * @param objectOrGroup {object} The object or group being tested. - * @param inScreenSpace {boolean} Whether to take scroll factors numbero account when checking for overlap. Default is false, or "only compare in world space." - * @param camera {Camera} Specify which game camera you want. If null getScreenXY() will just grab the first global camera. - * - * @return {boolean} Whether or not the objects overlap this. - */ - public overlaps(objectOrGroup, inScreenSpace?: bool, camera?: Camera): bool; - /** - * Checks to see if this GameObject were located at the given position, would it overlap the GameObject or Group? - * This is distinct from overlapsPoint(), which just checks that point, rather than taking the object's size numbero account. - * WARNING: Currently tilemaps do NOT support screen space overlap checks! - * - * @param X {number} The X position you want to check. Pretends this object (the caller, not the parameter) is located here. - * @param Y {number} The Y position you want to check. Pretends this object (the caller, not the parameter) is located here. - * @param objectOrGroup {object} The object or group being tested. - * @param inScreenSpace {boolean} Whether to take scroll factors numbero account when checking for overlap. Default is false, or "only compare in world space." - * @param camera {Camera} Specify which game camera you want. If null getScreenXY() will just grab the first global camera. - * - * @return {boolean} Whether or not the two objects overlap. - */ - public overlapsAt(X: number, Y: number, objectOrGroup, inScreenSpace?: bool, camera?: Camera): bool; - /** - * Checks to see if a point in 2D world space overlaps this GameObject. - * - * @param point {Point} The point in world space you want to check. - * @param inScreenSpace {boolean} Whether to take scroll factors into account when checking for overlap. - * @param camera {Camera} Specify which game camera you want. If null getScreenXY() will just grab the first global camera. - * - * @return Whether or not the point overlaps this object. - */ - public overlapsPoint(point: Point, inScreenSpace?: bool, camera?: Camera): bool; - /** - * Check and see if this object is currently on screen. - * - * @param camera {Camera} Specify which game camera you want. If null getScreenXY() will just grab the first global camera. - * - * @return {boolean} Whether the object is on screen or not. - */ - public onScreen(camera?: Camera): bool; - /** - * Call this to figure out the on-screen position of the object. - * - * @param point {Point} Takes a MicroPoint object and assigns the post-scrolled X and Y values of this object to it. - * @param camera {Camera} Specify which game camera you want. If null getScreenXY() will just grab the first global camera. - * - * @return {MicroPoint} The MicroPoint you passed in, or a new Point if you didn't pass one, containing the screen X and Y position of this object. - */ - public getScreenXY(point?: MicroPoint, camera?: Camera): MicroPoint; - /** - * Whether the object collides or not. For more control over what directions - * the object will collide from, use collision constants (like LEFT, FLOOR, etc) - * to set the value of allowCollisions directly. - */ - public solid : bool; - /** - * Retrieve the midpoint of this object in world coordinates. - * - * @param point {Point} Allows you to pass in an existing Point object if you're so inclined. Otherwise a new one is created. - * - * @return {MicroPoint} A Point object containing the midpoint of this object in world coordinates. - */ - public getMidpoint(point?: MicroPoint): MicroPoint; - /** - * Handy for reviving game objects. - * Resets their existence flags and position. - * - * @param x {number} The new X position of this object. - * @param y {number} The new Y position of this object. - */ - public reset(x: number, y: number): void; - /** - * Handy for checking if this object is touching a particular surface. - * For slightly better performance you can just & the value directly into touching. - * However, this method is good for readability and accessibility. - * - * @param Direction {number} Any of the collision flags (e.g. LEFT, FLOOR, etc). - * - * @return {boolean} Whether the object is touching an object in (any of) the specified direction(s) this frame. - */ - public isTouching(direction: number): bool; - /** - * Handy function for checking if this object just landed on a particular surface. - * - * @param Direction {number} Any of the collision flags (e.g. LEFT, FLOOR, etc). - * - * @returns {boolean} Whether the object just landed on any specicied surfaces. - */ - public justTouched(direction: number): bool; - /** - * Reduces the "health" variable of this sprite by the amount specified in Damage. - * Calls kill() if health drops to or below zero. - * - * @param Damage {number} How much health to take away (use a negative number to give a health bonus). - */ - public hurt(damage: number): void; - /** - * Set the world bounds that this GameObject can exist within. By default a GameObject can exist anywhere - * in the world. But by setting the bounds (which are given in world dimensions, not screen dimensions) - * it can be stopped from leaving the world, or a section of it. - * - * @param x {number} x position of the bound - * @param y {number} y position of the bound - * @param width {number} width of its bound - * @param height {number} height of its bound - */ - public setBounds(x: number, y: number, width: number, height: number): void; - /** - * Set the world bounds that this GameObject can exist within based on the size of the current game world. - * - * @param action {number} The action to take if the object hits the world bounds, either OUT_OF_BOUNDS_KILL or OUT_OF_BOUNDS_STOP - */ - public setBoundsFromWorld(action?: number): void; - /** - * If you do not wish this object to be visible to a specific camera, pass the camera here. - * - * @param camera {Camera} The specific camera. - */ - public hideFromCamera(camera: Camera): void; - /** - * Make this object only visible to a specific camera. - * - * @param camera {Camera} The camera you wish it to be visible. - */ - public showToCamera(camera: Camera): void; - /** - * This clears the camera black list, making the GameObject visible to all cameras. - */ - public clearCameraList(): void; - /** - * Clean up memory. - */ - public destroy(): void; - public setPosition(x: number, y: number): void; - public x : number; - public y : number; - public rotation : number; - public angle : number; - public width : number; - public height : number; - } -} -/** -* Phaser - Camera -* -* A Camera is your view into the game world. It has a position, size, scale and rotation and renders only those objects -* within its field of view. The game automatically creates a single Stage sized camera on boot, but it can be changed and -* additional cameras created via the CameraManager. -*/ -module Phaser { - class Camera { - /** - *Sprite constructor - * Instantiates a new camera at the specified location, with the specified size and zoom level. - * - * @param game {Phaser.Game} Current game instance. - * @param id {number} Unique identity. - * @param x {number} X location of the camera's display in pixels. Uses native, 1:1 resolution, ignores zoom. - * @param y {number} Y location of the camera's display in pixels. Uses native, 1:1 resolution, ignores zoom. - * @param width {number} The width of the camera display in pixels. - * @param height {number} The height of the camera display in pixels. - */ - constructor(game: Game, id: number, x: number, y: number, width: number, height: number); - /** - * Local private reference to Game. - */ - private _game; - private _clip; - private _stageX; - private _stageY; - private _rotation; - private _target; - private _sx; - private _sy; - /** - * Camera "follow" style preset: camera has no deadzone, just tracks the focus object directly. - * @type {number} - */ - static STYLE_LOCKON: number; - /** - * Camera "follow" style preset: camera deadzone is narrow but tall. - * @type {number} - */ - static STYLE_PLATFORMER: number; - /** - * Camera "follow" style preset: camera deadzone is a medium-size square around the focus object. - * @type {number} - */ - static STYLE_TOPDOWN: number; - /** - * Camera "follow" style preset: camera deadzone is a small square around the focus object. - * @type {number} - */ - static STYLE_TOPDOWN_TIGHT: number; - /** - * Identity of this camera. - */ - public ID: number; - /** - * Camera view rectangle in world coordinate. - * @type {Rectangle} - */ - public worldView: Rectangle; - /** - * How many sprites will be rendered by this camera. - * @type {number} - */ - public totalSpritesRendered: number; - /** - * Scale factor of the camera. - * @type {MicroPoint} - */ - public scale: MicroPoint; - /** - * Scrolling factor. - * @type {MicroPoint} - */ - public scroll: MicroPoint; - /** - * Camera bounds. - * @type {Rectangle} - */ - public bounds: Rectangle; - /** - * Sprite moving inside this rectangle will not cause camera moving. - * @type {Rectangle} - */ - public deadzone: Rectangle; - public disableClipping: bool; - /** - * Whether render border of this camera or not. (default is false) - * @type {boolean} - */ - public showBorder: bool; - /** - * Color of border of this camera. (in css color string) - * @type {string} - */ - public borderColor: string; - /** - * Whether the camera background is opaque or not. If set to true the Camera is filled with - * the value of Camera.backgroundColor every frame. - * @type {boolean} - */ - public opaque: bool; - /** - * Clears the camera every frame using a canvas clearRect call (default to true). - * Note that this erases anything below the camera as well, so do not use it in conjuction with a camera - * that uses alpha or that needs to be able to manage opacity. Equally if Camera.opaque is set to true - * then set Camera.clear to false to save rendering time. - * By default the Stage will clear itself every frame, so be sure not to double-up clear calls. - * @type {boolean} - */ - public clear: bool; - /** - * Background color in css color string. - * @type {string} - */ - private _bgColor; - /** - * Background texture to be rendered if background is visible. - */ - private _bgTexture; - /** - * Background texture repeat style. (default is 'repeat') - * @type {string} - */ - private _bgTextureRepeat; - /** - * Render camera shadow or not. (default is false) - * @type {boolean} - */ - public showShadow: bool; - /** - * Color of shadow, in css color string. - * @type {string} - */ - public shadowColor: string; - /** - * Blur factor of shadow. - * @type {number} - */ - public shadowBlur: number; - /** - * Offset of the shadow from camera's position. - * @type {MicroPoint} - */ - public shadowOffset: MicroPoint; - /** - * Whether this camera visible or not. (default is true) - * @type {boolean} - */ - public visible: bool; - /** - * Alpha of the camera. (everything rendered to this camera will be affected) - * @type {number} - */ - public alpha: number; - /** - * The x position of the current input event in world coordinates. - * @type {number} - */ - public inputX: number; - /** - * The y position of the current input event in world coordinates. - * @type {number} - */ - public inputY: number; - /** - * Effects manager. - * @type {FXManager} - */ - public fx: FXManager; - /** - * Tells this camera object what sprite to track. - * @param target {Sprite} The object you want the camera to track. Set to null to not follow anything. - * @param [style] {number} Leverage one of the existing "deadzone" presets. If you use a custom deadzone, ignore this parameter and manually specify the deadzone after calling follow(). - */ - public follow(target: Sprite, style?: number): void; - /** - * Move the camera focus to this location instantly. - * @param x {number} X position. - * @param y {number} Y position. - */ - public focusOnXY(x: number, y: number): void; - /** - * Move the camera focus to this location instantly. - * @param point {any} Point you want to focus. - */ - public focusOn(point): void; - /** - * Specify the boundaries of the world or where the camera is allowed to move. - * - * @param x {number} The smallest X value of your world (usually 0). - * @param y {number} The smallest Y value of your world (usually 0). - * @param width {number} The largest X value of your world (usually the world width). - * @param height {number} The largest Y value of your world (usually the world height). - */ - public setBounds(x?: number, y?: number, width?: number, height?: number): void; - /** - * Update focusing and scrolling. - */ - public update(): void; - /** - * Draw background, shadow, effects, and objects if this is visible. - */ - public render(): void; - public backgroundColor : string; - /** - * Set camera background texture. - * @param key {string} Asset key of the texture. - * @param [repeat] {string} what kind of repeat will this texture used for background. - */ - public setTexture(key: string, repeat?: string): void; - /** - * Set position of this camera. - * @param x {number} X position. - * @param y {number} Y position. - */ - public setPosition(x: number, y: number): void; - /** - * Give this camera a new size. - * @param width {number} Width of new size. - * @param height {number} Height of new size. - */ - public setSize(width: number, height: number): void; - /** - * Render debug infos. (including id, position, rotation, scrolling factor, bounds and some other properties) - * @param x {number} X position of the debug info to be rendered. - * @param y {number} Y position of the debug info to be rendered. - * @param [color] {number} color of the debug info to be rendered. (format is css color string) - */ - public renderDebugInfo(x: number, y: number, color?: string): void; - public x : number; - public y : number; - public width : number; - public height : number; - public rotation : number; - private checkClip(); - } -} -/** -* Phaser - Sprite -* -* The Sprite GameObject is an extension of the core GameObject that includes support for animation and dynamic textures. -* It's probably the most used GameObject of all. -*/ -module Phaser { - class Sprite extends GameObject { - /** - * Sprite constructor - * Create a new Sprite. - * - * @param game {Phaser.Game} Current game instance. - * @param [x] {number} the initial x position of the sprite. - * @param [y] {number} the initial y position of the sprite. - * @param [key] {string} Key of the graphic you want to load for this sprite. - */ - constructor(game: Game, x?: number, y?: number, key?: string); - /** - * Texture of this sprite to be rendered. - */ - private _texture; - /** - * Texture of this sprite is DynamicTexture? (default to false) - * @type {boolean} - */ - private _dynamicTexture; - private _sx; - private _sy; - private _sw; - private _sh; - private _dx; - private _dy; - private _dw; - private _dh; - /** - * This manages animations of the sprite. You can modify animations though it. (see AnimationManager) - * @type AnimationManager - */ - public animations: AnimationManager; - /** - * The cache key that was used for this texture (if any) - */ - public cacheKey: string; - /** - * Render bound of this sprite for debugging? (default to false) - * @type {boolean} - */ - public renderDebug: bool; - /** - * Color of the Sprite when no image is present. Format is a css color string. - * @type {string} - */ - public fillColor: string; - /** - * Color of bound when render debug. (see renderDebug) Format is a css color string. - * @type {string} - */ - public renderDebugColor: string; - /** - * Color of points when render debug. (see renderDebug) Format is a css color string. - * @type {string} - */ - public renderDebugPointColor: string; - /** - * Flip the graphic horizontally? (defaults to false) - * @type {boolean} - */ - public flipped: bool; - /** - * Load graphic for this sprite. (graphic can be SpriteSheet or Texture) - * @param key {string} Key of the graphic you want to load for this sprite. - * @param clearAnimations {boolean} If this Sprite has a set of animation data already loaded you can choose to keep or clear it with this boolean - * @return {Sprite} Sprite instance itself. - */ - public loadGraphic(key: string, clearAnimations?: bool): Sprite; - /** - * Load a DynamicTexture as its texture. - * @param texture {DynamicTexture} The texture object to be used by this sprite. - * @return {Sprite} Sprite instance itself. - */ - public loadDynamicTexture(texture: DynamicTexture): Sprite; - /** - * This function creates a flat colored square image dynamically. - * @param width {number} The width of the sprite you want to generate. - * @param height {number} The height of the sprite you want to generate. - * @param [color] {number} specifies the color of the generated block. (format is 0xAARRGGBB) - * @return {Sprite} Sprite instance itself. - */ - public makeGraphic(width: number, height: number, color?: string): Sprite; - /** - * Check whether this object is visible in a specific camera rectangle. - * @param camera {Rectangle} The rectangle you want to check. - * @return {boolean} Return true if bounds of this sprite intersects the given rectangle, otherwise return false. - */ - public inCamera(camera: Rectangle, cameraOffsetX: number, cameraOffsetY: number): bool; - /** - * Automatically called after update() by the game loop, this function just updates animations. - */ - public postUpdate(): void; - public frame : number; - public frameName : string; - /** - * Render this sprite to specific camera. Called by game loop after update(). - * @param camera {Camera} Camera this sprite will be rendered to. - * @cameraOffsetX {number} X offset to the camera. - * @cameraOffsetY {number} Y offset to the camera. - * @return {boolean} Return false if not rendered, otherwise return true. - */ - public render(camera: Camera, cameraOffsetX: number, cameraOffsetY: number): bool; - /** - * Renders the bounding box around this Sprite and the contact points. Useful for visually debugging. - * @param camera {Camera} Camera the bound will be rendered to. - * @param cameraOffsetX {number} X offset of bound to the camera. - * @param cameraOffsetY {number} Y offset of bound to the camera. - */ - private renderBounds(camera, cameraOffsetX, cameraOffsetY); - /** - * Render debug infos. (including name, bounds info, position and some other properties) - * @param x {number} X position of the debug info to be rendered. - * @param y {number} Y position of the debug info to be rendered. - * @param [color] {number} color of the debug info to be rendered. (format is css color string) - */ - public renderDebugInfo(x: number, y: number, color?: string): void; - } -} -/** -* Phaser - AnimationManager -* -* Any Sprite that has animation contains an instance of the AnimationManager, which is used to add, play and update -* sprite specific animations. -*/ -module Phaser { - class AnimationManager { - /** - * AnimationManager constructor - * Create a new AnimationManager. - * - * @param parent {Sprite} Owner sprite of this manager. - */ - constructor(game: Game, parent: Sprite); + constructor(game: Game, callback); /** * Local private reference to game. */ private _game; /** - * Local private reference to its owner sprite. + * Array stors assets keys. So you can get that asset by its unique key. */ - private _parent; + private _keys; /** - * Animation key-value container. + * Contains all the assets file infos. */ - private _anims; + private _fileList; /** - * Index of current frame. + * Game initialial assets loading callback. + */ + private _gameCreateComplete; + private _onComplete; + private _onFileLoad; + /** + * Indicates assets loading progress. (from 0 to 100) * @type {number} */ - private _frameIndex; + private _progressChunk; + private _xhr; /** - * Data contains animation frames. - * @type {FrameData} + * Length of assets queue. + * @type {number} */ - private _frameData; + private _queueSize; /** - * Keeps track of the current animation being played. + * True if game is completely loaded. + * @type {boolean} */ - public currentAnim: Animation; + public hasLoaded: bool; /** - * Keeps track of the current frame of animation. + * Loading progress (from 0 to 1) + * @type {number} */ - public currentFrame: Frame; + public progress: number; /** - * Load animation frame data. - * @param frameData Data to be loaded. + * The crossOrigin value applied to loaded images + * @type {string} */ - public loadFrameData(frameData: FrameData): void; + public crossOrigin: string; /** - * Add a new animation. - * @param name {string} What this animation should be called (e.g. "run"). - * @param frames {any[]} An array of numbers/strings indicating what frames to play in what order (e.g. [1, 2, 3] or ['run0', 'run1', run2]). - * @param frameRate {number} The speed in frames per second that the animation should play at (e.g. 60 fps). - * @param loop {boolean} Whether or not the animation is looped or just plays once. - * @param useNumericIndex {boolean} Use number indexes instead of string indexes? - * @return {Animation} The Animation that was created + * TextureAtlas data format constants */ - public add(name: string, frames?: any[], frameRate?: number, loop?: bool, useNumericIndex?: bool): Animation; + static TEXTURE_ATLAS_JSON_ARRAY: number; + static TEXTURE_ATLAS_JSON_HASH: number; + static TEXTURE_ATLAS_XML_STARLING: number; /** - * Check whether the frames is valid. - * @param frames {any[]} Frames to be validated. - * @param useNumericIndex {boolean} Does these frames use number indexes or string indexes? - * @return {boolean} True if they're valid, otherwise return false. + * Reset loader, this will remove all loaded assets. */ - private validateFrames(frames, useNumericIndex); + public reset(): void; + public queueSize : number; /** - * Play animation with specific name. - * @param name {string} The string name of the animation you want to play. - * @param frameRate {number} FrameRate you want to specify instead of using default. - * @param loop {boolean} Whether or not the animation is looped or just plays once. + * Add a new image asset loading request with key and url. + * @param key {string} Unique asset key of this image file. + * @param url {string} URL of image file. */ - public play(name: string, frameRate?: number, loop?: bool): void; + public addImageFile(key: string, url: string): void; /** - * Stop animation by name. - * Current animation will be automatically set to the stopped one. + * Add a new sprite sheet loading request. + * @param key {string} Unique asset key of the sheet file. + * @param url {string} URL of sheet file. + * @param frameWidth {number} Width of each single frame. + * @param frameHeight {number} Height of each single frame. + * @param frameMax {number} How many frames in this sprite sheet. */ - public stop(name: string): void; + public addSpriteSheet(key: string, url: string, frameWidth: number, frameHeight: number, frameMax?: number): void; /** - * Update animation and parent sprite's bounds. + * Add a new texture atlas loading request. + * @param key {string} Unique asset key of the texture atlas file. + * @param textureURL {string} The url of the texture atlas image file. + * @param [atlasURL] {string} The url of the texture atlas data file (json/xml) + * @param [atlasData] {object} A JSON or XML data object. + * @param [format] {number} A value describing the format of the data. */ - public update(): void; - public frameData : FrameData; - public frameTotal : number; - public frame : number; - public frameName : string; + public addTextureAtlas(key: string, textureURL: string, atlasURL?: string, atlasData?, format?: number): void; /** - * Removes all related references + * Add a new audio file loading request. + * @param key {string} Unique asset key of the audio file. + * @param url {string} URL of audio file. */ - public destroy(): void; + public addAudioFile(key: string, url: string): void; + /** + * Add a new text file loading request. + * @param key {string} Unique asset key of the text file. + * @param url {string} URL of text file. + */ + public addTextFile(key: string, url: string): void; + /** + * Remove loading request of a file. + * @param key {string} Key of the file you want to remove. + */ + public removeFile(key: string): void; + /** + * Remove all file loading requests. + */ + public removeAll(): void; + /** + * Load assets. + * @param onFileLoadCallback {function} Called when each file loaded successfully. + * @param onCompleteCallback {function} Called when all assets completely loaded. + */ + public load(onFileLoadCallback?, onCompleteCallback?): void; + /** + * Load files. Private method ONLY used by loader. + */ + private loadFile(); + /** + * Error occured when load a file. + * @param key {string} Key of the error loading file. + */ + private fileError(key); + /** + * Called when a file is successfully loaded. + * @param key {string} Key of the successfully loaded file. + */ + private fileComplete(key); + /** + * Successfully loaded a JSON file. + * @param key {string} Key of the loaded JSON file. + */ + private jsonLoadComplete(key); + /** + * Error occured when load a JSON. + * @param key {string} Key of the error loading JSON file. + */ + private dataLoadError(key); + private xmlLoadComplete(key); + /** + * 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(previousKey, success); + /** + * Check whether asset exists with a specific key. + * @param key {string} Key of the asset you want to check. + * @return {boolean} Return true if exists, otherwise return false. + */ + private checkKeyExists(key); } } /** @@ -1523,2369 +296,6 @@ module Phaser { } } /** -* Phaser - CameraManager -* -* Your game only has one CameraManager instance and it's responsible for looking after, creating and destroying -* all of the cameras in the world. -*/ -module Phaser { - class CameraManager { - /** - * CameraManager constructor - * This will create a new Camera with position and size. - * - * @param x {number} X Position of the created camera. - * @param y {number} y Position of the created camera. - * @param width {number} Width of the created camera. - * @param height {number} Height of the created camera. - */ - constructor(game: Game, x: number, y: number, width: number, height: number); - /** - * Local private reference to Game. - */ - private _game; - /** - * Local container for storing cameras. - */ - private _cameras; - /** - * Local helper stores index of next created camera. - */ - private _cameraInstance; - /** - * Currently used camera. - */ - public current: Camera; - /** - * Get all the cameras. - * - * @returns {Camera[]} An array contains all the cameras. - */ - public getAll(): Camera[]; - /** - * Update cameras. - */ - public update(): void; - /** - * Render cameras. - */ - public render(): void; - /** - * Create a new camera with specific position and size. - * - * @param x {number} X position of the new camera. - * @param y {number} Y position of the new camera. - * @param width {number} Width of the new camera. - * @param height {number} Height of the new camera. - * @returns {Camera} The newly created camera object. - */ - public addCamera(x: number, y: number, width: number, height: number): Camera; - /** - * Remove a new camera with its id. - * - * @param id {number} ID of the camera you want to remove. - * @returns {boolean} True if successfully removed the camera, otherwise return false. - */ - public removeCamera(id: number): bool; - /** - * Clean up memory. - */ - public destroy(): void; - } -} -/** -* Phaser - Point -* -* The Point object represents a location in a two-dimensional coordinate system, where x represents the horizontal axis and y represents the vertical axis. -*/ -module Phaser { - class Point { - /** - * Creates a new point. If you pass no parameters to this method, a point is created at (0,0). - * @class Point - * @constructor - * @param {Number} x The horizontal position of this point (default 0) - * @param {Number} y The vertical position of this point (default 0) - **/ - constructor(x?: number, y?: number); - /** - * The horizontal position of this point (default 0) - * @property x - * @type {Number} - **/ - public x: number; - /** - * The vertical position of this point (default 0) - * @property y - * @type {Number} - **/ - public y: number; - /** - * Adds the coordinates of another point to the coordinates of this point to create a new point. - * @method add - * @param {Point} point - The point to be added. - * @return {Point} The new Point object. - **/ - public add(toAdd: Point, output?: Point): Point; - /** - * Adds the given values to the coordinates of this point and returns it - * @method addTo - * @param {Number} x - The amount to add to the x value of the point - * @param {Number} y - The amount to add to the x value of the point - * @return {Point} This Point object. - **/ - public addTo(x?: number, y?: number): Point; - /** - * Adds the given values to the coordinates of this point and returns it - * @method addTo - * @param {Number} x - The amount to add to the x value of the point - * @param {Number} y - The amount to add to the x value of the point - * @return {Point} This Point object. - **/ - public subtractFrom(x?: number, y?: number): Point; - /** - * Inverts the x and y values of this point - * @method invert - * @return {Point} This Point object. - **/ - public invert(): Point; - /** - * Clamps this Point object to be between the given min and max - * @method clamp - * @param {number} The minimum value to clamp this Point to - * @param {number} The maximum value to clamp this Point to - * @return {Point} This Point object. - **/ - public clamp(min: number, max: number): Point; - /** - * Clamps the x value of this Point object to be between the given min and max - * @method clampX - * @param {number} The minimum value to clamp this Point to - * @param {number} The maximum value to clamp this Point to - * @return {Point} This Point object. - **/ - public clampX(min: number, max: number): Point; - /** - * Clamps the y value of this Point object to be between the given min and max - * @method clampY - * @param {number} The minimum value to clamp this Point to - * @param {number} The maximum value to clamp this Point to - * @return {Point} This Point object. - **/ - public clampY(min: number, max: number): Point; - /** - * Creates a copy of this Point. - * @method clone - * @param {Point} output Optional Point object. If given the values will be set into this object, otherwise a brand new Point object will be created and returned. - * @return {Point} The new Point object. - **/ - public clone(output?: Point): Point; - /** - * Copies the point data from the source Point object into this Point object. - * @method copyFrom - * @param {Point} source - The point to copy from. - * @return {Point} This Point object. Useful for chaining method calls. - **/ - public copyFrom(source: Point): Point; - /** - * Copies the point data from this Point object to the given target Point object. - * @method copyTo - * @param {Point} target - The point to copy to. - * @return {Point} The target Point object. - **/ - public copyTo(target: Point): Point; - /** - * Returns the distance from this Point object to the given Point object. - * @method distanceFrom - * @param {Point} target - The destination Point object. - * @param {Boolean} round - Round the distance to the nearest integer (default false) - * @return {Number} The distance between this Point object and the destination Point object. - **/ - public distanceTo(target: Point, round?: bool): number; - /** - * Returns the distance between the two Point objects. - * @method distanceBetween - * @param {Point} pointA - The first Point object. - * @param {Point} pointB - The second Point object. - * @param {Boolean} round - Round the distance to the nearest integer (default false) - * @return {Number} The distance between the two Point objects. - **/ - static distanceBetween(pointA: Point, pointB: Point, round?: bool): number; - /** - * Returns true if the distance between this point and a target point is greater than or equal a specified distance. - * This avoids using a costly square root operation - * @method distanceCompare - * @param {Point} target - The Point object to use for comparison. - * @param {Number} distance - The distance to use for comparison. - * @return {Boolena} True if distance is >= specified distance. - **/ - public distanceCompare(target: Point, distance: number): bool; - /** - * Determines whether this Point object and the given point object are equal. They are equal if they have the same x and y values. - * @method equals - * @param {Point} point - The point to compare against. - * @return {Boolean} A value of true if the object is equal to this Point object; false if it is not equal. - **/ - public equals(toCompare: Point): bool; - /** - * Determines a point between two specified points. The parameter f determines where the new interpolated point is located relative to the two end points specified by parameters pt1 and pt2. - * The closer the value of the parameter f is to 1.0, the closer the interpolated point is to the first point (parameter pt1). The closer the value of the parameter f is to 0, the closer the interpolated point is to the second point (parameter pt2). - * @method interpolate - * @param {Point} pointA - The first Point object. - * @param {Point} pointB - The second Point object. - * @param {Number} f - The level of interpolation between the two points. Indicates where the new point will be, along the line between pt1 and pt2. If f=1, pt1 is returned; if f=0, pt2 is returned. - * @return {Point} The new interpolated Point object. - **/ - public interpolate(pointA, pointB, f): void; - /** - * Offsets the Point object by the specified amount. The value of dx is added to the original value of x to create the new x value. - * The value of dy is added to the original value of y to create the new y value. - * @method offset - * @param {Number} dx - The amount by which to offset the horizontal coordinate, x. - * @param {Number} dy - The amount by which to offset the vertical coordinate, y. - * @return {Point} This Point object. Useful for chaining method calls. - **/ - public offset(dx: number, dy: number): Point; - /** - * Converts a pair of polar coordinates to a Cartesian point coordinate. - * @method polar - * @param {Number} length - The length coordinate of the polar pair. - * @param {Number} angle - The angle, in radians, of the polar pair. - * @return {Point} The new Cartesian Point object. - **/ - public polar(length, angle): void; - /** - * Rotates the point around the x/y coordinates given to the desired angle - * @param x {number} The x coordinate of the anchor point - * @param y {number} The y coordinate of the anchor point - * @param {Number} angle The angle in radians (unless asDegrees is true) to return the point from. - * @param {Boolean} asDegrees Is the given angle in radians (false) or degrees (true)? - * @param {Number} distance An optional distance constraint between the point and the anchor - * @return The modified point object - */ - public rotate(cx: number, cy: number, angle: number, asDegrees?: bool, distance?: number): Point; - /** - * Sets the x and y values of this Point object to the given coordinates. - * @method setTo - * @param {Number} x - The horizontal position of this point. - * @param {Number} y - The vertical position of this point. - * @return {Point} This Point object. Useful for chaining method calls. - **/ - public setTo(x: number, y: number): Point; - /** - * Subtracts the coordinates of another point from the coordinates of this point to create a new point. - * @method subtract - * @param {Point} point - The point to be subtracted. - * @param {Point} output Optional Point object. If given the values will be set into this object, otherwise a brand new Point object will be created and returned. - * @return {Point} The new Point object. - **/ - public subtract(point: Point, output?: Point): Point; - /** - * Returns a string representation of this object. - * @method toString - * @return {string} a string representation of the instance. - **/ - public toString(): string; - } -} -/** -* Phaser - MicroPoint -* -* The MicroPoint object represents a location in a two-dimensional coordinate system, -* where x represents the horizontal axis and y represents the vertical axis. -* It is different to the Point class in that it doesn't contain any of the help methods like add/substract/distanceTo, etc. -* Use a MicroPoint when all you literally need is a solid container for x and y (such as in the Rectangle class). -*/ -module Phaser { - class MicroPoint { - /** - * Creates a new point. If you pass no parameters to this method, a point is created at (0,0). - * @class MicroPoint - * @constructor - * @param {Number} x The horizontal position of this point (default 0) - * @param {Number} y The vertical position of this point (default 0) - **/ - constructor(x?: number, y?: number, parent?: any); - private _x; - private _y; - public parent: any; - /** - * The x coordinate of the top-left corner of the rectangle - * @property x - * @type {Number} - **/ - /** - * The x coordinate of the top-left corner of the rectangle - * @property x - * @type {Number} - **/ - public x : number; - /** - * The y coordinate of the top-left corner of the rectangle - * @property y - * @type {Number} - **/ - /** - * The y coordinate of the top-left corner of the rectangle - * @property y - * @type {Number} - **/ - public y : number; - /** - * Copies the x and y values from any given object to this MicroPoint. - * @method copyFrom - * @param {any} source - The object to copy from. - * @return {MicroPoint} This MicroPoint object. Useful for chaining method calls. - **/ - public copyFrom(source: any): MicroPoint; - /** - * Copies the x and y values from this MicroPoint to any given object. - * @method copyTo - * @param {any} target - The object to copy to. - * @return {any} The target object. - **/ - public copyTo(target: any): MicroPoint; - /** - * Sets the x and y values of this MicroPoint object to the given coordinates. - * @method setTo - * @param {Number} x - The horizontal position of this point. - * @param {Number} y - The vertical position of this point. - * @return {MicroPoint} This MicroPoint object. Useful for chaining method calls. - **/ - public setTo(x: number, y: number, callParent?: bool): MicroPoint; - /** - * Determines whether this MicroPoint object and the given object are equal. They are equal if they have the same x and y values. - * @method equals - * @param {any} point - The object to compare against. Must have x and y properties. - * @return {Boolean} A value of true if the object is equal to this MicroPoin object; false if it is not equal. - **/ - public equals(toCompare): bool; - /** - * Returns a string representation of this object. - * @method toString - * @return {string} a string representation of the instance. - **/ - public toString(): string; - } -} -/** -* Phaser - Rectangle -* -* A Rectangle object is an area defined by its position, as indicated by its top-left corner (x,y) and width and height. -*/ -module Phaser { - class Rectangle { - /** - * Creates a new Rectangle object with the top-left corner specified by the x and y parameters and with the specified width and height parameters. - * If you call this function without parameters, a rectangle with x, y, width, and height properties set to 0 is created. - * @class Rectangle - * @constructor - * @param {Number} x The x coordinate of the top-left corner of the rectangle. - * @param {Number} y The y coordinate of the top-left corner of the rectangle. - * @param {Number} width The width of the rectangle. - * @param {Number} height The height of the rectangle. - * @return {Rectangle} This rectangle object - **/ - constructor(x?: number, y?: number, width?: number, height?: number); - private _tempX; - private _tempY; - private _tempWidth; - private _tempHeight; - /** - * The x coordinate of the top-left corner of the rectangle - * @property x - * @type {Number} - **/ - /** - * The x coordinate of the top-left corner of the rectangle - * @property x - * @type {Number} - **/ - public x : number; - /** - * The y coordinate of the top-left corner of the rectangle - * @property y - * @type {Number} - **/ - /** - * The y coordinate of the top-left corner of the rectangle - * @property y - * @type {Number} - **/ - public y : number; - /** - * The x and y coordinate of the top-left corner of the rectangle (same as x/y) - * @property topLeft - * @type {MicroPoint} - **/ - public topLeft: MicroPoint; - /** - * The x and y coordinate of the top-center of the rectangle - * @property topCenter - * @type {MicroPoint} - **/ - public topCenter: MicroPoint; - /** - * The x and y coordinate of the top-right corner of the rectangle - * @property topRight - * @type {MicroPoint} - **/ - public topRight: MicroPoint; - /** - * The x and y coordinate of the left-center of the rectangle - * @property leftCenter - * @type {MicroPoint} - **/ - public leftCenter: MicroPoint; - /** - * The x and y coordinate of the center of the rectangle - * @property center - * @type {MicroPoint} - **/ - public center: MicroPoint; - /** - * The x and y coordinate of the right-center of the rectangle - * @property rightCenter - * @type {MicroPoint} - **/ - public rightCenter: MicroPoint; - /** - * The x and y coordinate of the bottom-left corner of the rectangle - * @property bottomLeft - * @type {MicroPoint} - **/ - public bottomLeft: MicroPoint; - /** - * The x and y coordinate of the bottom-center of the rectangle - * @property bottomCenter - * @type {MicroPoint} - **/ - public bottomCenter: MicroPoint; - /** - * The x and y coordinate of the bottom-right corner of the rectangle - * @property bottomRight - * @type {MicroPoint} - **/ - public bottomRight: MicroPoint; - /** - * The width of the rectangle - * @property width - * @type {Number} - **/ - private _width; - /** - * The height of the rectangle - * @property height - * @type {Number} - **/ - private _height; - /** - * Half of the width of the rectangle - * @property halfWidth - * @type {Number} - **/ - private _halfWidth; - /** - * Half of the height of the rectangle - * @property halfHeight - * @type {Number} - **/ - private _halfHeight; - /** - * The size of the longest side (width or height) - * @property length - * @type {Number} - **/ - public length: number; - /** - * Updates all of the MicroPoints based on the values of width and height. - * You should not normally call this directly. - **/ - public updateBounds(): void; - /** - * The width of the rectangle - * @property width - * @type {Number} - **/ - /** - * The width of the rectangle - * @property width - * @type {Number} - **/ - public width : number; - /** - * The height of the rectangle - * @property height - * @type {Number} - **/ - /** - * The height of the rectangle - * @property height - * @type {Number} - **/ - public height : number; - /** - * Half of the width of the rectangle - * @property halfWidth - * @type {Number} - **/ - public halfWidth : number; - /** - * Half of the height of the rectangle - * @property halfHeight - * @type {Number} - **/ - public halfHeight : number; - /** - * 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 - * @return {Number} - **/ - /** - * 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 - **/ - public bottom : number; - /** - * The x coordinate of the top-left corner of the rectangle. - * Changing the left property of a Rectangle object has no effect on the y and height properties. - * However it does affect the width property, whereas changing the x value does not affect the width property. - * @method left - * @ return {Number} - **/ - /** - * The x coordinate of the top-left corner of the rectangle. - * Changing the left property of a Rectangle object has no effect on the y and height properties. - * However it does affect the width property, whereas changing the x value does not affect the width property. - * @method left - * @param {Number} value - **/ - public left : number; - /** - * The sum of the x and width properties. - * Changing the right property of a Rectangle object has no effect on the x, y and height properties. - * However it does affect the width property. - * @method right - * @return {Number} - **/ - /** - * The sum of the x and width properties. - * Changing the right property of a Rectangle object has no effect on the x, y and height properties. - * However it does affect the width property. - * @method right - * @param {Number} value - **/ - public right : number; - /** - * The size of the Rectangle object, expressed as a Point object with the values of the width and height properties. - * @method size - * @param {Point} output Optional Point object. If given the values will be set into the object, otherwise a brand new Point object will be created and returned. - * @return {Point} The size of the Rectangle object - **/ - public size(output?: Point): Point; - /** - * The volume of the Rectangle object in pixels, derived from width * height - * @method volume - * @return {Number} - **/ - public volume : number; - /** - * The perimeter size of the Rectangle object in pixels. This is the sum of all 4 sides. - * @method perimeter - * @return {Number} - **/ - public perimeter : number; - /** - * The y coordinate of the top-left corner of the rectangle. - * Changing the top property of a Rectangle object has no effect on the x and width properties. - * However it does affect the height property, whereas changing the y value does not affect the height property. - * @method top - * @return {Number} - **/ - /** - * The y coordinate of the top-left corner of the rectangle. - * Changing the top property of a Rectangle object has no effect on the x and width properties. - * However it does affect the height property, whereas changing the y value does not affect the height property. - * @method top - * @param {Number} value - **/ - public top : number; - /** - * Returns a new Rectangle object with the same values for the x, y, width, and height properties as the original Rectangle object. - * @method clone - * @param {Rectangle} output Optional Rectangle object. If given the values will be set into the object, otherwise a brand new Rectangle object will be created and returned. - * @return {Rectangle} - **/ - public clone(output?: Rectangle): Rectangle; - /** - * Determines whether the specified coordinates are contained within the region defined by this Rectangle object. - * @method contains - * @param {Number} x The x coordinate of the point to test. - * @param {Number} y The y coordinate of the point to test. - * @return {Boolean} A value of true if the Rectangle object contains the specified point; otherwise false. - **/ - public contains(x: number, y: number): bool; - /** - * Determines whether the specified point is contained within the rectangular region defined by this Rectangle object. - * This method is similar to the Rectangle.contains() method, except that it takes a Point object as a parameter. - * @method containsPoint - * @param {Point} point The point object being checked. Can be Point or any object with .x and .y values. - * @return {Boolean} A value of true if the Rectangle object contains the specified point; otherwise false. - **/ - public containsPoint(point: any): bool; - /** - * Determines whether the Rectangle object specified by the rect parameter is contained within this Rectangle object. - * A Rectangle object is said to contain another if the second Rectangle object falls entirely within the boundaries of the first. - * @method containsRect - * @param {Rectangle} rect The rectangle object being checked. - * @return {Boolean} A value of true if the Rectangle object contains the specified point; otherwise false. - **/ - public containsRect(rect: Rectangle): bool; - /** - * Copies all of rectangle data from the source Rectangle object into the calling Rectangle object. - * @method copyFrom - * @param {Rectangle} rect The source rectangle object to copy from - * @return {Rectangle} This rectangle object - **/ - public copyFrom(source: Rectangle): Rectangle; - /** - * Copies all the rectangle data from this Rectangle object into the destination Rectangle object. - * @method copyTo - * @param {Rectangle} rect The destination rectangle object to copy in to - * @return {Rectangle} The destination rectangle object - **/ - public copyTo(target: Rectangle): Rectangle; - /** - * Determines whether the object specified in the toCompare parameter is equal to this Rectangle object. - * This method compares the x, y, width, and height properties of an object against the same properties of this Rectangle object. - * @method equals - * @param {Rectangle} toCompare The rectangle to compare to this Rectangle object. - * @return {Boolean} A value of true if the object has exactly the same values for the x, y, width, and height properties as this Rectangle object; otherwise false. - **/ - public equals(toCompare: Rectangle): bool; - /** - * Increases the size of the Rectangle object by the specified amounts. - * The center point of the Rectangle object stays the same, and its size increases to the left and right by the dx value, - * and to the top and the bottom by the dy value. - * @method inflate - * @param {Number} dx The amount to be added to the left side of this Rectangle. - * @param {Number} dy The amount to be added to the bottom side of this Rectangle. - * @return {Rectangle} This Rectangle object. - **/ - public inflate(dx: number, dy: number): Rectangle; - /** - * Increases the size of the Rectangle object. - * This method is similar to the Rectangle.inflate() method except it takes a Point object as a parameter. - * @method inflatePoint - * @param {Point} point The x property of this Point object is used to increase the horizontal dimension of the Rectangle object. The y property is used to increase the vertical dimension of the Rectangle object. - * @return {Rectangle} This Rectangle object. - **/ - public inflatePoint(point: Point): Rectangle; - /** - * If the Rectangle object specified in the toIntersect parameter intersects with this Rectangle object, - * returns the area of intersection as a Rectangle object. If the rectangles do not intersect, this method - * returns an empty Rectangle object with its properties set to 0. - * @method intersection - * @param {Rectangle} toIntersect The Rectangle object to compare against to see if it intersects with this Rectangle object. - * @param {Rectangle} output Optional Rectangle object. If given the intersection values will be set into this object, otherwise a brand new Rectangle object will be created and returned. - * @return {Rectangle} A Rectangle object that equals the area of intersection. If the rectangles do not intersect, this method returns an empty Rectangle object; that is, a rectangle with its x, y, width, and height properties set to 0. - **/ - public intersection(toIntersect: Rectangle, output?: Rectangle): Rectangle; - /** - * Determines whether the object specified intersects (overlaps) with this Rectangle object. - * This method checks the x, y, width, and height properties of the specified Rectangle object to see if it intersects with this Rectangle object. - * @method intersects - * @param {Rectangle} r2 The Rectangle object to compare against to see if it intersects with this Rectangle object. - * @param {Number} t A tolerance value to allow for an intersection test with padding, default to 0 - * @return {Boolean} A value of true if the specified object intersects with this Rectangle object; otherwise false. - **/ - public intersects(r2: Rectangle, t?: number): bool; - /** - * Determines whether or not this Rectangle object is empty. - * @method isEmpty - * @return {Boolean} A value of true if the Rectangle object's width or height is less than or equal to 0; otherwise false. - **/ - public isEmpty : bool; - /** - * Adjusts the location of the Rectangle object, as determined by its top-left corner, by the specified amounts. - * @method offset - * @param {Number} dx Moves the x value of the Rectangle object by this amount. - * @param {Number} dy Moves the y value of the Rectangle object by this amount. - * @return {Rectangle} This Rectangle object. - **/ - public offset(dx: number, dy: number): Rectangle; - /** - * Adjusts the location of the Rectangle object using a Point object as a parameter. This method is similar to the Rectangle.offset() method, except that it takes a Point object as a parameter. - * @method offsetPoint - * @param {Point} point A Point object to use to offset this Rectangle object. - * @return {Rectangle} This Rectangle object. - **/ - public offsetPoint(point: Point): Rectangle; - /** - * Sets all of the Rectangle object's properties to 0. A Rectangle object is empty if its width or height is less than or equal to 0. - * @method setEmpty - * @return {Rectangle} This rectangle object - **/ - public setEmpty(): Rectangle; - /** - * Sets the members of Rectangle to the specified values. - * @method setTo - * @param {Number} x The x coordinate of the top-left corner of the rectangle. - * @param {Number} y The y coordinate of the top-left corner of the rectangle. - * @param {Number} width The width of the rectangle in pixels. - * @param {Number} height The height of the rectangle in pixels. - * @return {Rectangle} This rectangle object - **/ - public setTo(x: number, y: number, width: number, height: number): Rectangle; - /** - * Adds two rectangles together to create a new Rectangle object, by filling in the horizontal and vertical space between the two rectangles. - * @method union - * @param {Rectangle} toUnion A Rectangle object to add to this Rectangle object. - * @param {Rectangle} output Optional Rectangle object. If given the new values will be set into this object, otherwise a brand new Rectangle object will be created and returned. - * @return {Rectangle} A Rectangle object that is the union of the two rectangles. - **/ - public union(toUnion: Rectangle, output?: Rectangle): Rectangle; - /** - * Returns a string representation of this object. - * @method toString - * @return {String} a string representation of the instance. - **/ - public toString(): string; - } -} -/** -* Phaser - Polygon -* -*/ -module Phaser { - class Polygon { - /** - * A *convex* clockwise polygon - * @class Polygon - * @constructor - * @param {Vector2} pos A vector representing the origin of the polygon (all other points are relative to this one) - * @param {Array.} points An Array of vectors representing the points in the polygon, in clockwise order. - **/ - constructor(pos?: Vector2, points?: Vector2[], parent?: any); - public parent: any; - public pos: Vector2; - public points: Vector2[]; - public edges: Vector2[]; - public normals: Vector2[]; - /** - * Recalculate the edges and normals of the polygon. This - * MUST be called if the points array is modified at all and - * the edges or normals are to be accessed. - */ - public recalc(): void; - } -} -/** -* Phaser - Quad -* -* A Quad object is an area defined by its position, as indicated by its top-left corner (x,y) and width and height. -* Very much like a Rectangle only without all of the additional methods and properties of that class. -*/ -module Phaser { - class Quad { - /** - * Creates a new Quad object with the top-left corner specified by the x and y parameters and with the specified width and height parameters. If you call this function without parameters, a rectangle with x, y, width, and height properties set to 0 is created. - * @class Quad - * @constructor - * @param {Number} x The x coordinate of the top-left corner of the quad. - * @param {Number} y The y coordinate of the top-left corner of the quad. - * @param {Number} width The width of the quad. - * @param {Number} height The height of the quad. - * @return {Quad} This object - **/ - constructor(x?: number, y?: number, width?: number, height?: number); - public x: number; - public y: number; - public width: number; - public height: number; - /** - * Sets the Quad to the specified size. - * @method setTo - * @param {Number} x The x coordinate of the top-left corner of the quad. - * @param {Number} y The y coordinate of the top-left corner of the quad. - * @param {Number} width The width of the quad. - * @param {Number} height The height of the quad. - * @return {Quad} This object - **/ - public setTo(x: number, y: number, width: number, height: number): Quad; - public left : number; - public right : number; - public top : number; - public bottom : number; - public halfWidth : number; - public halfHeight : number; - /** - * Determines whether the object specified intersects (overlaps) with this Quad object. - * This method checks the x, y, width, and height properties of the specified Quad object to see if it intersects with this Quad object. - * @method intersects - * @param {Object} quad The object to check for intersection with this Quad. Must have left/right/top/bottom properties (Rectangle, Quad). - * @param {Number} tolerance A tolerance value to allow for an intersection test with padding, default to 0 - * @return {Boolean} A value of true if the specified object intersects with this Quad; otherwise false. - **/ - public intersects(quad, tolerance?: number): bool; - /** - * Determines whether the object specified intersects (overlaps) with the given values. - * @method intersectsProps - * @param {Number} left - * @param {Number} right - * @param {Number} top - * @param {Number} bottomt - * @param {Number} tolerance A tolerance value to allow for an intersection test with padding, default to 0 - * @return {Boolean} A value of true if the specified object intersects with this Quad; otherwise false. - **/ - public intersectsRaw(left: number, right: number, top: number, bottom: number, tolerance?: number): bool; - /** - * Determines whether the specified coordinates are contained within the region defined by this Quad object. - * @method contains - * @param {Number} x The x coordinate of the point to test. - * @param {Number} y The y coordinate of the point to test. - * @return {Boolean} A value of true if the Rectangle object contains the specified point; otherwise false. - **/ - public contains(x: number, y: number): bool; - /** - * Copies the x/y/width/height values from the source object into this Quad - * @method copyFrom - * @param {Any} source The source object to copy from. Can be a Quad, Rectangle or any object with exposed x/y/width/height properties - * @return {Quad} This object - **/ - public copyFrom(source): Quad; - /** - * Copies the x/y/width/height values from this Quad into the given target object - * @method copyTo - * @param {Any} target The object to copy this quads values in to. Can be a Quad, Rectangle or any object with exposed x/y/width/height properties - * @return {Any} The target object - **/ - public copyTo(target): any; - /** - * Creates and returns a Polygon that is the same as this Quad. - * @method toPolygon - * @return {Polygon} A new Polygon that represents this quad. - **/ - public toPolygon(): Polygon; - /** - * Returns a string representation of this object. - * @method toString - * @return {string} a string representation of the object. - **/ - public toString(): string; - } -} -/** -* Phaser - Circle -* -* A Circle object is an area defined by its position, as indicated by its center point (x,y) and diameter. -*/ -module Phaser { - class Circle { - /** - * Creates a new Circle object with the center coordinate specified by the x and y parameters and the diameter specified by the diameter parameter. If you call this function without parameters, a circle with x, y, diameter and radius properties set to 0 is created. - * @class Circle - * @constructor - * @param {Number} [x] The x coordinate of the center of the circle. - * @param {Number} [y] The y coordinate of the center of the circle. - * @param {Number} [diameter] The diameter of the circle. - * @return {Circle} This circle object - **/ - constructor(x?: number, y?: number, diameter?: number); - private _diameter; - private _radius; - private _pos; - /** - * The x coordinate of the center of the circle - * @property x - * @type Number - **/ - public x: number; - /** - * The y coordinate of the center of the circle - * @property y - * @type Number - **/ - public y: number; - /** - * The position of this Circle object represented by a Vector2 - * @property pos - * @type Vector2 - **/ - public pos : Vector2; - /** - * The diameter of the circle. The largest distance between any two points on the circle. The same as the radius * 2. - * @method diameter - * @return {Number} - **/ - /** - * The diameter of the circle. The largest distance between any two points on the circle. The same as the radius * 2. - * @method diameter - * @param {Number} The diameter of the circle. - **/ - public diameter : number; - /** - * The radius of the circle. The length of a line extending from the center of the circle to any point on the circle itself. The same as half the diameter. - * @method radius - * @return {Number} - **/ - /** - * The radius of the circle. The length of a line extending from the center of the circle to any point on the circle itself. The same as half the diameter. - * @method radius - * @param {Number} The radius of the circle. - **/ - public radius : number; - /** - * The circumference of the circle. - * @method circumference - * @return {Number} - **/ - public circumference(): number; - /** - * The sum of the y and radius properties. Changing the bottom property of a Circle object has no effect on the x and y properties, but does change the diameter. - * @method bottom - * @return {Number} - **/ - /** - * The sum of the y and radius properties. Changing the bottom property of a Circle object has no effect on the x and y properties, but does change the diameter. - * @method bottom - * @param {Number} The value to adjust the height of the circle by. - **/ - public bottom : number; - /** - * The x coordinate of the leftmost point of the circle. Changing the left property of a Circle object has no effect on the x and y properties. However it does affect the diameter, whereas changing the x value does not affect the diameter property. - * @method left - * @return {Number} The x coordinate of the leftmost point of the circle. - **/ - /** - * The x coordinate of the leftmost point of the circle. Changing the left property of a Circle object has no effect on the x and y properties. However it does affect the diameter, whereas changing the x value does not affect the diameter property. - * @method left - * @param {Number} The value to adjust the position of the leftmost point of the circle by. - **/ - public left : number; - /** - * The x coordinate of the rightmost point of the circle. Changing the right property of a Circle object has no effect on the x and y properties. However it does affect the diameter, whereas changing the x value does not affect the diameter property. - * @method right - * @return {Number} - **/ - /** - * The x coordinate of the rightmost point of the circle. Changing the right property of a Circle object has no effect on the x and y properties. However it does affect the diameter, whereas changing the x value does not affect the diameter property. - * @method right - * @param {Number} The amount to adjust the diameter of the circle by. - **/ - public right : number; - /** - * The sum of the y minus the radius property. Changing the top property of a Circle object has no effect on the x and y properties, but does change the diameter. - * @method bottom - * @return {Number} - **/ - /** - * The sum of the y minus the radius property. Changing the top property of a Circle object has no effect on the x and y properties, but does change the diameter. - * @method bottom - * @param {Number} The amount to adjust the height of the circle by. - **/ - public top : number; - /** - * Gets the area of this Circle. - * @method area - * @return {Number} This area of this circle. - **/ - public area : number; - /** - * Determines whether or not this Circle object is empty. - * @method isEmpty - * @return {Boolean} A value of true if the Circle objects diameter is less than or equal to 0; otherwise false. - **/ - public isEmpty : bool; - /** - * Whether the circle intersects with a line. Checks against infinite line defined by the two points on the line, not the line segment. - * If you need details about the intersection then use Collision.lineToCircle instead. - * @method intersectCircleLine - * @param {Object} the line object to check. - * @return {Boolean} - **/ - public intersectCircleLine(line: Line): bool; - /** - * Returns a new Circle object with the same values for the x, y, width, and height properties as the original Circle object. - * @method clone - * @param {Circle} [optional] output Optional Circle object. If given the values will be set into the object, otherwise a brand new Circle object will be created and returned. - * @return {Phaser.Circle} - **/ - public clone(output?: Circle): Circle; - /** - * Return true if the given x/y coordinates are within this Circle object. - * If you need details about the intersection then use Phaser.Intersect.circleContainsPoint instead. - * @method contains - * @param {Number} The X value of the coordinate to test. - * @param {Number} The Y value of the coordinate to test. - * @return {Boolean} True if the coordinates are within this circle, otherwise false. - **/ - public contains(x: number, y: number): bool; - /** - * Return true if the coordinates of the given Point object are within this Circle object. - * If you need details about the intersection then use Phaser.Intersect.circleContainsPoint instead. - * @method containsPoint - * @param {Phaser.Point} The Point object to test. - * @return {Boolean} True if the coordinates are within this circle, otherwise false. - **/ - public containsPoint(point: Point): bool; - /** - * Return true if the given Circle is contained entirely within this Circle object. - * If you need details about the intersection then use Phaser.Intersect.circleToCircle instead. - * @method containsCircle - * @param {Phaser.Circle} The Circle object to test. - * @return {Boolean} True if the coordinates are within this circle, otherwise false. - **/ - public containsCircle(circle: Circle): bool; - /** - * Copies all of circle data from the source Circle object into the calling Circle object. - * @method copyFrom - * @param {Circle} rect The source circle object to copy from - * @return {Circle} This circle object - **/ - public copyFrom(source: Circle): Circle; - /** - * Copies all of circle data from this Circle object into the destination Circle object. - * @method copyTo - * @param {Circle} circle The destination circle object to copy in to - * @return {Circle} The destination circle object - **/ - public copyTo(target: Circle): Circle; - /** - * Returns the distance from the center of this Circle object to the given object (can be Circle, Point or anything with x/y values) - * @method distanceFrom - * @param {Circle/Point} target - The destination Point object. - * @param {Boolean} [optional] round - Round the distance to the nearest integer (default false) - * @return {Number} The distance between this Point object and the destination Point object. - **/ - public distanceTo(target: any, round?: bool): number; - /** - * Determines whether the object specified in the toCompare parameter is equal to this Circle object. This method compares the x, y and diameter properties of an object against the same properties of this Circle object. - * @method equals - * @param {Circle} toCompare The circle to compare to this Circle object. - * @return {Boolean} A value of true if the object has exactly the same values for the x, y and diameter properties as this Circle object; otherwise false. - **/ - public equals(toCompare: Circle): bool; - /** - * Determines whether the Circle object specified in the toIntersect parameter intersects with this Circle object. This method checks the radius distances between the two Circle objects to see if they intersect. - * @method intersects - * @param {Circle} toIntersect The Circle object to compare against to see if it intersects with this Circle object. - * @return {Boolean} A value of true if the specified object intersects with this Circle object; otherwise false. - **/ - public intersects(toIntersect: Circle): bool; - /** - * Returns a Point object containing the coordinates of a point on the circumference of this Circle based on the given angle. - * @method circumferencePoint - * @param {Number} angle The angle in radians (unless asDegrees is true) to return the point from. - * @param {Boolean} asDegrees Is the given angle in radians (false) or degrees (true)? - * @param {Phaser.Point} [optional] output An optional Point object to put the result in to. If none specified a new Point object will be created. - * @return {Phaser.Point} The Point object holding the result. - **/ - public circumferencePoint(angle: number, asDegrees?: bool, output?: Point): Point; - /** - * Adjusts the location of the Circle object, as determined by its center coordinate, by the specified amounts. - * @method offset - * @param {Number} dx Moves the x value of the Circle object by this amount. - * @param {Number} dy Moves the y value of the Circle object by this amount. - * @return {Circle} This Circle object. - **/ - public offset(dx: number, dy: number): Circle; - /** - * Adjusts the location of the Circle object using a Point object as a parameter. This method is similar to the Circle.offset() method, except that it takes a Point object as a parameter. - * @method offsetPoint - * @param {Point} point A Point object to use to offset this Circle object. - * @return {Circle} This Circle object. - **/ - public offsetPoint(point: Point): Circle; - /** - * Sets the members of Circle to the specified values. - * @method setTo - * @param {Number} x The x coordinate of the center of the circle. - * @param {Number} y The y coordinate of the center of the circle. - * @param {Number} diameter The diameter of the circle in pixels. - * @return {Circle} This circle object - **/ - public setTo(x: number, y: number, diameter: number): Circle; - /** - * Returns a string representation of this object. - * @method toString - * @return {string} a string representation of the instance. - **/ - public toString(): string; - } -} -/** -* Phaser - Line -* -* A Line object is an infinte line through space. The two sets of x/y coordinates define the Line Segment. -*/ -module Phaser { - class Line { - /** - * - * @constructor - * @param {Number} x1 - * @param {Number} y1 - * @param {Number} x2 - * @param {Number} y2 - * @return {Phaser.Line} This Object - */ - constructor(x1?: number, y1?: number, x2?: number, y2?: number); - /** - * - * @property x1 - * @type {Number} - */ - public x1: number; - /** - * - * @property y1 - * @type {Number} - */ - public y1: number; - /** - * - * @property x2 - * @type {Number} - */ - public x2: number; - /** - * - * @property y2 - * @type {Number} - */ - public y2: number; - /** - * - * @method clone - * @param {Phaser.Line} [output] - * @return {Phaser.Line} - */ - public clone(output?: Line): Line; - /** - * - * @method copyFrom - * @param {Phaser.Line} source - * @return {Phaser.Line} - */ - public copyFrom(source: Line): Line; - /** - * - * @method copyTo - * @param {Phaser.Line} target - * @return {Phaser.Line} - */ - public copyTo(target: Line): Line; - /** - * - * @method setTo - * @param {Number} x1 - * @param {Number} y1 - * @param {Number} x2 - * @param {Number} y2 - * @return {Phaser.Line} - */ - public setTo(x1?: number, y1?: number, x2?: number, y2?: number): Line; - public width : number; - public height : number; - /** - * - * @method length - * @return {Number} - */ - public length : number; - /** - * - * @method getY - * @param {Number} x - * @return {Number} - */ - public getY(x: number): number; - /** - * - * @method angle - * @return {Number} - */ - public angle : number; - /** - * - * @method slope - * @return {Number} - */ - public slope : number; - /** - * - * @method perpSlope - * @return {Number} - */ - public perpSlope : number; - /** - * - * @method yIntercept - * @return {Number} - */ - public yIntercept : number; - /** - * - * @method isPointOnLine - * @param {Number} x - * @param {Number} y - * @return {Boolean} - */ - public isPointOnLine(x: number, y: number): bool; - /** - * - * @method isPointOnLineSegment - * @param {Number} x - * @param {Number} y - * @return {Boolean} - */ - public isPointOnLineSegment(x: number, y: number): bool; - /** - * - * @method intersectLineLine - * @param {Any} line - * @return {Any} - */ - public intersectLineLine(line): any; - /** - * - * @method perp - * @param {Number} x - * @param {Number} y - * @param {Phaser.Line} [output] - * @return {Phaser.Line} - */ - public perp(x: number, y: number, output?: Line): Line; - /** - * - * @method toString - * @return {String} - */ - public toString(): string; - } -} -/** -* Phaser - IntersectResult -* -* A light-weight result object to hold the results of an intersection. For when you need more than just true/false. -*/ -module Phaser { - class IntersectResult { - /** - * Did they intersect or not? - * @property result - * @type {Boolean} - */ - public result: bool; - /** - * @property x - * @type {Number} - */ - public x: number; - /** - * @property y - * @type {Number} - */ - public y: number; - /** - * @property x1 - * @type {Number} - */ - public x1: number; - /** - * @property y1 - * @type {Number} - */ - public y1: number; - /** - * @property x2 - * @type {Number} - */ - public x2: number; - /** - * @property y2 - * @type {Number} - */ - public y2: number; - /** - * @property width - * @type {Number} - */ - public width: number; - /** - * @property height - * @type {Number} - */ - public height: number; - /** - * - * @method setTo - * @param {Number} x1 - * @param {Number} y1 - * @param {Number} [x2] - * @param {Number} [y2] - * @param {Number} [width] - * @param {Number} [height] - */ - public setTo(x1: number, y1: number, x2?: number, y2?: number, width?: number, height?: number): void; - } -} -/** -* Phaser - Response -* -*/ -module Phaser { - class Response { - /** - * An object representing the result of an intersection. Contain information about: - * - The two objects participating in the intersection - * - The vector representing the minimum change necessary to extract the first object - * from the second one. - * - Whether the first object is entirely inside the second, or vice versa. - * - * @constructor - */ - constructor(); - /** - * The first object in the collision - */ - public a; - /** - * The second object in the collision - */ - public b; - /** - * The shortest colliding axis (unit-vector) - */ - public overlapN: Vector2; - /** - * The overlap vector (i.e. overlapN.scale(overlap, overlap)). - * If this vector is subtracted from the position of `a`, `a` and `b` will no longer be colliding. - */ - public overlapV: Vector2; - /** - * Whether the first object is completely inside the second. - */ - public aInB: bool; - /** - * Whether the second object is completely inside the first. - */ - public bInA: bool; - /** - * Magnitude of the overlap on the shortest colliding axis - */ - public overlap: number; - /** - * Set some values of the response back to their defaults. Call this between tests if - * you are going to reuse a single Response object for multiple intersection tests (recommented) - * - * @return {Response} This for chaining - */ - public clear(): Response; - } -} -/** -* Phaser - Vector2 -* -* A two dimensional vector. -* Contains methods and ideas from verlet-js by Sub Protocol, SAT.js by Jim Riecken and N by Metanet Software. Brandon Jones, Colin MacKenzie IV -*/ -module Phaser { - class Vector2 { - /** - * Creates a new Vector2 object. - * @class Vector2 - * @constructor - * @param {Number} x The x position of the vector - * @param {Number} y The y position of the vector - * @return {Vector2} This object - **/ - constructor(x?: number, y?: number); - public x: number; - public y: number; - public setTo(x: number, y: number): Vector2; - /** - * Add this vector to the given one and return the result. - * - * @param {Vector2} v The other Vector. - * @param {Vector2} The output Vector. - * @return {Vector2} The new Vector - */ - public add(v: Vector2, output?: Vector2): Vector2; - /** - * Subtract this vector to the given one and return the result. - * - * @param {Vector2} v The other Vector. - * @param {Vector2} The output Vector. - * @return {Vector2} The new Vector - */ - public sub(v: Vector2, output?: Vector2): Vector2; - /** - * Multiply this vector with the given one and return the result. - * - * @param {Vector2} v The other Vector. - * @param {Vector2} The output Vector. - * @return {Vector2} The new Vector - */ - public mul(v: Vector2, output?: Vector2): Vector2; - /** - * Divide this vector by the given one and return the result. - * - * @param {Vector2} v The other Vector. - * @param {Vector2} The output Vector. - * @return {Vector2} The new Vector - */ - public div(v: Vector2, output?: Vector2): Vector2; - /** - * Scale this vector by the given values and return the result. - * - * @param {number} x The scaling factor in the x direction. - * @param {?number=} y The scaling factor in the y direction. If this - * is not specified, the x scaling factor will be used. - * @return {Vector} The new Vector - */ - public scale(x: number, y?: number, output?: Vector2): Vector2; - /** - * Rotate this vector by 90 degrees - * - * @return {Vector} This for chaining. - */ - public perp(output?: Vector2): Vector2; - public mutableSet(v: Vector2): Vector2; - /** - * Add another vector to this one. - * - * @param {Vector} other The other Vector. - * @return {Vector} This for chaining. - */ - public mutableAdd(v: Vector2): Vector2; - /** - * Subtract another vector from this one. - * - * @param {Vector} other The other Vector. - * @return {Vector} This for chaining. - */ - public mutableSub(v: Vector2): Vector2; - /** - * Multiply another vector with this one. - * - * @param {Vector} other The other Vector. - * @return {Vector} This for chaining. - */ - public mutableMul(v: Vector2): Vector2; - /** - * Divide this vector by another one. - * - * @param {Vector} other The other Vector. - * @return {Vector} This for chaining. - */ - public mutableDiv(v: Vector2): Vector2; - /** - * Scale this vector. - * - * @param {number} x The scaling factor in the x direction. - * @param {?number=} y The scaling factor in the y direction. If this - * is not specified, the x scaling factor will be used. - * @return {Vector} This for chaining. - */ - public mutableScale(x: number, y?: number): Vector2; - /** - * Multiply this vector by the given scalar. - * - * @param {number} scalar - * @return {Vector2} This for chaining. - */ - public mutableMultiplyByScalar(scalar: number): Vector2; - /** - * Divide this vector by the given scalar. - * - * @param {number} scalar - * @return {Vector2} This for chaining. - */ - public mutableDivideByScalar(scalar: number): Vector2; - /** - * Reverse this vector. - * - * @return {Vector} This for chaining. - */ - public reverse(): Vector2; - public edge(v: Vector2, output?: Vector2): Vector2; - public equals(v: Vector2): bool; - public epsilonEquals(v: Vector2, epsilon: number): bool; - /** - * Get the length of this vector. - * - * @return {number} The length of this vector. - */ - public length(): number; - /** - * Get the length^2 of this vector. - * - * @return {number} The length^2 of this vector. - */ - public length2(): number; - /** - * Get the distance between this vector and the given vector. - * - * @return {Vector2} v The vector to check - */ - public distance(v: Vector2): number; - /** - * Get the distance^2 between this vector and the given vector. - * - * @return {Vector2} v The vector to check - */ - public distance2(v: Vector2): number; - /** - * Project this vector on to another vector. - * - * @param {Vector} other The vector to project onto. - * @return {Vector} This for chaining. - */ - public project(other: Vector2): Vector2; - /** - * Project this vector onto a vector of unit length. - * - * @param {Vector} other The unit vector to project onto. - * @return {Vector} This for chaining. - */ - public projectN(other: Vector2): Vector2; - /** - * Reflect this vector on an arbitrary axis. - * - * @param {Vector} axis The vector representing the axis. - * @return {Vector} This for chaining. - */ - public reflect(axis): Vector2; - /** - * Reflect this vector on an arbitrary axis (represented by a unit vector) - * - * @param {Vector} axis The unit vector representing the axis. - * @return {Vector} This for chaining. - */ - public reflectN(axis): Vector2; - public getProjectionMagnitude(v: Vector2): number; - public direction(output?: Vector2): Vector2; - public normalRightHand(output?: Vector2): Vector2; - /** - * Normalize (make unit length) this vector. - * - * @return {Vector} This for chaining. - */ - public normalize(output?: Vector2): Vector2; - public getMagnitude(): number; - /** - * Get the dot product of this vector against another. - * - * @param {Vector} other The vector to dot this one against. - * @return {number} The dot product. - */ - public dot(v: Vector2): number; - /** - * Get the cross product of this vector against another. - * - * @param {Vector} other The vector to cross this one against. - * @return {number} The cross product. - */ - public cross(v: Vector2): number; - /** - * Get the angle between this vector and the given vector. - * - * @return {Vector2} v The vector to check - */ - public angle(v: Vector2): number; - public angle2(vLeft: Vector2, vRight: Vector2): number; - /** - * Rotate this vector around the origin to the given angle (theta) and return the result in a new Vector - * - * @return {Vector2} v The vector to check - */ - public rotate(origin, theta, output?: Vector2): Vector2; - public clone(output?: Vector2): Vector2; - public copyFrom(v: Vector2): Vector2; - public copyTo(v: Vector2): Vector2; - /** - * Returns a string representation of this object. - * @method toString - * @return {string} a string representation of the object. - **/ - public toString(): string; - } -} -/** -* Phaser - LinkedList -* -* A miniature linked list class. Useful for optimizing time-critical or highly repetitive tasks! -*/ -module Phaser { - class LinkedList { - /** - * Creates a new link, and sets object and next to null. - */ - constructor(); - /** - * Stores a reference to an Basic. - */ - public object: Basic; - /** - * Stores a reference to the next link in the list. - */ - public next: LinkedList; - /** - * Clean up memory. - */ - public destroy(): void; - } -} -/** -* Phaser - QuadTree -* -* A fairly generic quad tree structure for rapid overlap checks. QuadTree is also configured for single or dual list operation. -* You can add items either to its A list or its B list. When you do an overlap check, you can compare the A list to itself, -* or the A list against the B list. Handy for different things! -*/ -module Phaser { - class QuadTree extends Rectangle { - /** - * Instantiate a new Quad Tree node. - * - * @param {Number} x The X-coordinate of the point in space. - * @param {Number} y The Y-coordinate of the point in space. - * @param {Number} width Desired width of this node. - * @param {Number} height Desired height of this node. - * @param {Number} parent The parent branch or node. Pass null to create a root. - */ - constructor(x: number, y: number, width: number, height: number, parent?: QuadTree); - /** - * Flag for specifying that you want to add an object to the A list. - */ - static A_LIST: number; - /** - * Flag for specifying that you want to add an object to the B list. - */ - static B_LIST: number; - /** - * Controls the granularity of the quad tree. Default is 6 (decent performance on large and small worlds). - */ - static divisions: number; - /** - * Whether this branch of the tree can be subdivided or not. - */ - private _canSubdivide; - /** - * Refers to the internal A and B linked lists, - * which are used to store objects in the leaves. - */ - private _headA; - /** - * Refers to the internal A and B linked lists, - * which are used to store objects in the leaves. - */ - private _tailA; - /** - * Refers to the internal A and B linked lists, - * which are used to store objects in the leaves. - */ - private _headB; - /** - * Refers to the internal A and B linked lists, - * which are used to store objects in the leaves. - */ - private _tailB; - /** - * Internal, governs and assists with the formation of the tree. - */ - private static _min; - /** - * Internal, governs and assists with the formation of the tree. - */ - private _northWestTree; - /** - * Internal, governs and assists with the formation of the tree. - */ - private _northEastTree; - /** - * Internal, governs and assists with the formation of the tree. - */ - private _southEastTree; - /** - * Internal, governs and assists with the formation of the tree. - */ - private _southWestTree; - /** - * Internal, governs and assists with the formation of the tree. - */ - private _leftEdge; - /** - * Internal, governs and assists with the formation of the tree. - */ - private _rightEdge; - /** - * Internal, governs and assists with the formation of the tree. - */ - private _topEdge; - /** - * Internal, governs and assists with the formation of the tree. - */ - private _bottomEdge; - /** - * Internal, governs and assists with the formation of the tree. - */ - private _halfWidth; - /** - * Internal, governs and assists with the formation of the tree. - */ - private _halfHeight; - /** - * Internal, governs and assists with the formation of the tree. - */ - private _midpointX; - /** - * Internal, governs and assists with the formation of the tree. - */ - private _midpointY; - /** - * Internal, used to reduce recursive method parameters during object placement and tree formation. - */ - private static _object; - /** - * Internal, used during tree processing and overlap checks. - */ - private static _list; - /** - * Internal, used during tree processing and overlap checks. - */ - private static _useBothLists; - /** - * Internal, used during tree processing and overlap checks. - */ - private static _processingCallback; - /** - * Internal, used during tree processing and overlap checks. - */ - private static _notifyCallback; - /** - * Internal, used during tree processing and overlap checks. - */ - private static _callbackContext; - /** - * Internal, used during tree processing and overlap checks. - */ - private static _iterator; - /** - * Clean up memory. - */ - public destroy(): void; - /** - * Load objects and/or groups into the quad tree, and register notify and processing callbacks. - * - * @param {Basic} objectOrGroup1 Any object that is or extends GameObject or Group. - * @param {Basic} objectOrGroup2 Any object that is or extends GameObject or Group. If null, the first parameter will be checked against itself. - * @param {Function} notifyCallback A function with the form myFunction(Object1:GameObject,Object2:GameObject) that is called whenever two objects are found to overlap in world space, and either no processCallback is specified, or the processCallback returns true. - * @param {Function} processCallback A function with the form myFunction(Object1:GameObject,Object2:GameObject):bool that is called whenever two objects are found to overlap in world space. The notifyCallback is only called if this function returns true. See GameObject.separate(). - * @param context The context in which the callbacks will be called - */ - public load(objectOrGroup1: Basic, objectOrGroup2?: Basic, notifyCallback?, processCallback?, context?): void; - /** - * Call this function to add an object to the root of the tree. - * This function will recursively add all group members, but - * not the groups themselves. - * - * @param {Basic} objectOrGroup GameObjects are just added, Groups are recursed and their applicable members added accordingly. - * @param {Number} list A uint flag indicating the list to which you want to add the objects. Options are QuadTree.A_LIST and QuadTree.B_LIST. - */ - public add(objectOrGroup: Basic, list: number): void; - /** - * Internal function for recursively navigating and creating the tree - * while adding objects to the appropriate nodes. - */ - private addObject(); - /** - * Internal function for recursively adding objects to leaf lists. - */ - private addToList(); - /** - * QuadTree's other main function. Call this after adding objects - * using QuadTree.load() to compare the objects that you loaded. - * - * @return {Boolean} Whether or not any overlaps were found. - */ - public execute(): bool; - /** - * A private for comparing an object against the contents of a node. - * - * @return {Boolean} Whether or not any overlaps were found. - */ - private overlapNode(); - } -} -/** -* Phaser - Collision -* -* A set of extremely useful collision and geometry intersection functions. -*/ -module Phaser { - class Collision { - /** - * Collision constructor - * @param game A reference to the current Game - */ - constructor(game: Game); - /** - * Local private reference to Game - */ - private _game; - /** - * Flag used to allow GameObjects to collide on their left side - * @type {number} - */ - static LEFT: number; - /** - * Flag used to allow GameObjects to collide on their right side - * @type {number} - */ - static RIGHT: number; - /** - * Flag used to allow GameObjects to collide on their top side - * @type {number} - */ - static UP: number; - /** - * Flag used to allow GameObjects to collide on their bottom side - * @type {number} - */ - static DOWN: number; - /** - * Flag used with GameObjects to disable collision - * @type {number} - */ - static NONE: number; - /** - * Flag used to allow GameObjects to collide with a ceiling - * @type {number} - */ - static CEILING: number; - /** - * Flag used to allow GameObjects to collide with a floor - * @type {number} - */ - static FLOOR: number; - /** - * Flag used to allow GameObjects to collide with a wall (same as LEFT+RIGHT) - * @type {number} - */ - static WALL: number; - /** - * Flag used to allow GameObjects to collide on any face - * @type {number} - */ - static ANY: number; - /** - * The overlap bias is used when calculating hull overlap before separation - change it if you have especially small or large GameObjects - * @type {number} - */ - static OVERLAP_BIAS: number; - /** - * This holds the result of the tile separation check, true if the object was moved, otherwise false - * @type {boolean} - */ - static TILE_OVERLAP: bool; - /** - * A temporary Quad used in the separation process to help avoid gc spikes - * @type {Quad} - */ - static _tempBounds: Quad; - /** - * Checks for Line to Line intersection and returns an IntersectResult object containing the results of the intersection. - * @param line1 The first Line object to check - * @param line2 The second Line object to check - * @param [output] An optional IntersectResult object to store the intersection values in. One is created if none given. - * @returns {IntersectResult=} An IntersectResult object containing the results of the intersection - */ - static lineToLine(line1: Line, line2: Line, output?: IntersectResult): IntersectResult; - /** - * Checks for Line to Line Segment intersection and returns an IntersectResult object containing the results of the intersection. - * @param line The Line object to check - * @param seg The Line segment object to check - * @param [output] An optional IntersectResult object to store the intersection values in. One is created if none given. - * @returns {IntersectResult=} An IntersectResult object containing the results of the intersection - */ - static lineToLineSegment(line: Line, seg: Line, output?: IntersectResult): IntersectResult; - /** - * Checks for Line to Raw Line Segment intersection and returns the result in the IntersectResult object. - * @param line The Line object to check - * @param x1 The start x coordinate of the raw segment - * @param y1 The start y coordinate of the raw segment - * @param x2 The end x coordinate of the raw segment - * @param y2 The end y coordinate of the raw segment - * @param [output] An optional IntersectResult object to store the intersection values in. One is created if none given. - * @returns {IntersectResult=} An IntersectResult object containing the results of the intersection - */ - static lineToRawSegment(line: Line, x1: number, y1: number, x2: number, y2: number, output?: IntersectResult): IntersectResult; - /** - * Checks for Line to Ray intersection and returns the result in an IntersectResult object. - * @param line1 The Line object to check - * @param ray The Ray object to check - * @param [output] An optional IntersectResult object to store the intersection values in. One is created if none given. - * @returns {IntersectResult=} An IntersectResult object containing the results of the intersection - */ - static lineToRay(line1: Line, ray: Line, output?: IntersectResult): IntersectResult; - /** - * Check if the Line and Circle objects intersect - * @param line The Line object to check - * @param circle The Circle object to check - * @param [output] An optional IntersectResult object to store the intersection values in. One is created if none given. - * @returns {IntersectResult=} An IntersectResult object containing the results of the intersection - */ - static lineToCircle(line: Line, circle: Circle, output?: IntersectResult): IntersectResult; - /** - * Check if the Line intersects each side of the Rectangle - * @param line The Line object to check - * @param rect The Rectangle object to check - * @param [output] An optional IntersectResult object to store the intersection values in. One is created if none given. - * @returns {IntersectResult=} An IntersectResult object containing the results of the intersection - */ - static lineToRectangle(line: Line, rect: Rectangle, output?: IntersectResult): IntersectResult; - /** - * Check if the two Line Segments intersect and returns the result in an IntersectResult object. - * @param line1 The first Line Segment to check - * @param line2 The second Line Segment to check - * @param [output] An optional IntersectResult object to store the intersection values in. One is created if none given. - * @returns {IntersectResult=} An IntersectResult object containing the results of the intersection - */ - static lineSegmentToLineSegment(line1: Line, line2: Line, output?: IntersectResult): IntersectResult; - /** - * Check if the Line Segment intersects with the Ray and returns the result in an IntersectResult object. - * @param line The Line Segment to check. - * @param ray The Ray to check. - * @param [output] An optional IntersectResult object to store the intersection values in. One is created if none given. - * @returns {IntersectResult=} An IntersectResult object containing the results of the intersection - */ - static lineSegmentToRay(line: Line, ray: Line, output?: IntersectResult): IntersectResult; - /** - * Check if the Line Segment intersects with the Circle and returns the result in an IntersectResult object. - * @param seg The Line Segment to check. - * @param circle The Circle to check - * @param [output] An optional IntersectResult object to store the intersection values in. One is created if none given. - * @returns {IntersectResult=} An IntersectResult object containing the results of the intersection - */ - static lineSegmentToCircle(seg: Line, circle: Circle, output?: IntersectResult): IntersectResult; - /** - * Check if the Line Segment intersects with the Rectangle and returns the result in an IntersectResult object. - * @param seg The Line Segment to check. - * @param rect The Rectangle to check. - * @param [output] An optional IntersectResult object to store the intersection values in. One is created if none given. - * @returns {IntersectResult=} An IntersectResult object containing the results of the intersection - */ - static lineSegmentToRectangle(seg: Line, rect: Rectangle, output?: IntersectResult): IntersectResult; - /** - * Check for Ray to Rectangle intersection and returns the result in an IntersectResult object. - * @param ray The Ray to check. - * @param rect The Rectangle to check. - * @param [output] An optional IntersectResult object to store the intersection values in. One is created if none given. - * @returns {IntersectResult=} An IntersectResult object containing the results of the intersection - */ - static rayToRectangle(ray: Line, rect: Rectangle, output?: IntersectResult): IntersectResult; - /** - * Check whether a Ray intersects a Line segment and returns the parametric value where the intersection occurs in an IntersectResult object. - * @param rayX1 - * @param rayY1 - * @param rayX2 - * @param rayY2 - * @param lineX1 - * @param lineY1 - * @param lineX2 - * @param lineY2 - * @param [output] An optional IntersectResult object to store the intersection values in. One is created if none given. - * @returns {IntersectResult=} An IntersectResult object containing the results of the intersection - */ - static rayToLineSegment(rayX1, rayY1, rayX2, rayY2, lineX1, lineY1, lineX2, lineY2, output?: IntersectResult): IntersectResult; - /** - * Determines whether the specified point is contained within the rectangular region defined by the Rectangle object and returns the result in an IntersectResult object. - * @param point The Point or MicroPoint object to check, or any object with x and y properties. - * @param rect The Rectangle object to check the point against - * @param [output] An optional IntersectResult object to store the intersection values in. One is created if none given. - * @returns {IntersectResult=} An IntersectResult object containing the results of the intersection - */ - static pointToRectangle(point, rect: Rectangle, output?: IntersectResult): IntersectResult; - /** - * Check whether two axis aligned Rectangles intersect and returns the intersecting rectangle dimensions in an IntersectResult object if they do. - * @param rect1 The first Rectangle object. - * @param rect2 The second Rectangle object. - * @param [output] An optional IntersectResult object to store the intersection values in. One is created if none given. - * @returns {IntersectResult=} An IntersectResult object containing the results of the intersection - */ - static rectangleToRectangle(rect1: Rectangle, rect2: Rectangle, output?: IntersectResult): IntersectResult; - /** - * Checks if the Rectangle and Circle objects intersect and returns the result in an IntersectResult object. - * @param rect The Rectangle object to check - * @param circle The Circle object to check - * @param [output] An optional IntersectResult object to store the intersection values in. One is created if none given. - * @returns {IntersectResult=} An IntersectResult object containing the results of the intersection - */ - static rectangleToCircle(rect: Rectangle, circle: Circle, output?: IntersectResult): IntersectResult; - /** - * Checks if the two Circle objects intersect and returns the result in an IntersectResult object. - * @param circle1 The first Circle object to check - * @param circle2 The second Circle object to check - * @param [output] An optional IntersectResult object to store the intersection values in. One is created if none given. - * @returns {IntersectResult=} An IntersectResult object containing the results of the intersection - */ - static circleToCircle(circle1: Circle, circle2: Circle, output?: IntersectResult): IntersectResult; - /** - * Checks if the Circle object intersects with the Rectangle and returns the result in an IntersectResult object. - * @param circle The Circle object to check - * @param rect The Rectangle object to check - * @param [output] An optional IntersectResult object to store the intersection values in. One is created if none given. - * @returns {IntersectResult=} An IntersectResult object containing the results of the intersection - */ - static circleToRectangle(circle: Circle, rect: Rectangle, output?: IntersectResult): IntersectResult; - /** - * Checks if the Point object is contained within the Circle and returns the result in an IntersectResult object. - * @param circle The Circle object to check - * @param point A Point or MicroPoint object to check, or any object with x and y properties - * @param [output] An optional IntersectResult object to store the intersection values in. One is created if none given. - * @returns {IntersectResult=} An IntersectResult object containing the results of the intersection - */ - static circleContainsPoint(circle: Circle, point, output?: IntersectResult): IntersectResult; - /** - * Checks for overlaps between two objects using the world QuadTree. Can be GameObject vs. GameObject, GameObject vs. Group or Group vs. Group. - * Note: Does not take the objects scrollFactor into account. All overlaps are check in world space. - * @param object1 The first GameObject or Group to check. If null the world.group is used. - * @param object2 The second GameObject or Group to check. - * @param notifyCallback A callback function that is called if the objects overlap. The two objects will be passed to this function in the same order in which you passed them to Collision.overlap. - * @param processCallback A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then notifyCallback will only be called if processCallback returns true. - * @param context The context in which the callbacks will be called - * @returns {boolean} true if the objects overlap, otherwise false. - */ - public overlap(object1?: Basic, object2?: Basic, notifyCallback?, processCallback?, context?): bool; - /** - * The core Collision separation function used by Collision.overlap. - * @param object1 The first GameObject to separate - * @param object2 The second GameObject to separate - * @returns {boolean} Returns true if the objects were separated, otherwise false. - */ - static separate(object1, object2): bool; - /** - * Collision resolution specifically for GameObjects vs. Tiles. - * @param object The GameObject to separate - * @param tile The Tile to separate - * @returns {boolean} Whether the objects in fact touched and were separated - */ - static separateTile(object: GameObject, x: number, y: number, width: number, height: number, mass: number, collideLeft: bool, collideRight: bool, collideUp: bool, collideDown: bool, separateX: bool, separateY: bool): bool; - /** - * Separates the two objects on their x axis - * @param object The GameObject to separate - * @param tile The Tile to separate - * @returns {boolean} Whether the objects in fact touched and were separated along the X axis. - */ - static separateTileX(object: GameObject, x: number, y: number, width: number, height: number, mass: number, collideLeft: bool, collideRight: bool, separate: bool): bool; - /** - * Separates the two objects on their y axis - * @param object The first GameObject to separate - * @param tile The second GameObject to separate - * @returns {boolean} Whether the objects in fact touched and were separated along the Y axis. - */ - static separateTileY(object: GameObject, x: number, y: number, width: number, height: number, mass: number, collideUp: bool, collideDown: bool, separate: bool): bool; - /** - * Separates the two objects on their x axis - * @param object The GameObject to separate - * @param tile The Tile to separate - * @returns {boolean} Whether the objects in fact touched and were separated along the X axis. - */ - static NEWseparateTileX(object: GameObject, x: number, y: number, width: number, height: number, mass: number, collideLeft: bool, collideRight: bool, separate: bool): bool; - /** - * Separates the two objects on their y axis - * @param object The first GameObject to separate - * @param tile The second GameObject to separate - * @returns {boolean} Whether the objects in fact touched and were separated along the Y axis. - */ - static NEWseparateTileY(object: GameObject, x: number, y: number, width: number, height: number, mass: number, collideUp: bool, collideDown: bool, separate: bool): bool; - /** - * Separates the two objects on their x axis - * @param object1 The first GameObject to separate - * @param object2 The second GameObject to separate - * @returns {boolean} Whether the objects in fact touched and were separated along the X axis. - */ - static separateX(object1, object2): bool; - /** - * Separates the two objects on their y axis - * @param object1 The first GameObject to separate - * @param object2 The second GameObject to separate - * @returns {boolean} Whether the objects in fact touched and were separated along the Y axis. - */ - static separateY(object1, object2): bool; - /** - * Returns the distance between the two given coordinates. - * @param x1 The X value of the first coordinate - * @param y1 The Y value of the first coordinate - * @param x2 The X value of the second coordinate - * @param y2 The Y value of the second coordinate - * @returns {number} The distance between the two coordinates - */ - static distance(x1: number, y1: number, x2: number, y2: number): number; - /** - * Returns the distanced squared between the two given coordinates. - * @param x1 The X value of the first coordinate - * @param y1 The Y value of the first coordinate - * @param x2 The X value of the second coordinate - * @param y2 The Y value of the second coordinate - * @returns {number} The distance between the two coordinates - */ - static distanceSquared(x1: number, y1: number, x2: number, y2: number): number; - /** - * Flattens the specified array of points onto a unit vector axis, - * resulting in a one dimensional range of the minimum and - * maximum value on that axis. - * - * @param {Array.} points The points to flatten. - * @param {Vector} normal The unit vector axis to flatten on. - * @param {Array.} result An array. After calling this function, - * result[0] will be the minimum value, - * result[1] will be the maximum value. - */ - static flattenPointsOn(points, normal, result): void; - /** - * Pool of Vectors used in calculations. - * - * @type {Array.} - */ - static T_VECTORS: Vector2[]; - /** - * Pool of Arrays used in calculations. - * - * @type {Array.>} - */ - static T_ARRAYS; - /** - * Check whether two convex clockwise polygons are separated by the specified - * axis (must be a unit vector). - * - * @param {Vector} aPos The position of the first polygon. - * @param {Vector} bPos The position of the second polygon. - * @param {Array.} aPoints The points in the first polygon. - * @param {Array.} bPoints The points in the second polygon. - * @param {Vector} axis The axis (unit sized) to test against. The points of both polygons - * will be projected onto this axis. - * @param {Response=} response A Response object (optional) which will be populated - * if the axis is not a separating axis. - * @return {boolean} true if it is a separating axis, false otherwise. If false, - * and a response is passed in, information about how much overlap and - * the direction of the overlap will be populated. - */ - static isSeparatingAxis(aPos, bPos, aPoints, bPoints, axis, response?: Response): bool; - static LEFT_VORNOI_REGION: number; - static MIDDLE_VORNOI_REGION: number; - static RIGHT_VORNOI_REGION: number; - /** - * Calculates which Vornoi region a point is on a line segment. - * It is assumed that both the line and the point are relative to (0, 0) - * - * | (0) | - * (-1) [0]--------------[1] (1) - * | (0) | - * - * @param {Vector} line The line segment. - * @param {Vector} point The point. - * @return {number} LEFT_VORNOI_REGION (-1) if it is the left region, - * MIDDLE_VORNOI_REGION (0) if it is the middle region, - * RIGHT_VORNOI_REGION (1) if it is the right region. - */ - static vornoiRegion(line: Vector2, point: Vector2): number; - /** - * Check if two circles intersect. - * - * @param {Circle} a The first circle. - * @param {Circle} b The second circle. - * @param {Response=} response Response object (optional) that will be populated if - * the circles intersect. - * @return {boolean} true if the circles intersect, false if they don't. - */ - static testCircleCircle(a: Circle, b: Circle, response?: Response): bool; - /** - * Check if a polygon and a circle intersect. - * - * @param {Polygon} polygon The polygon. - * @param {Circle} circle The circle. - * @param {Response=} response Response object (optional) that will be populated if - * they interset. - * @return {boolean} true if they intersect, false if they don't. - */ - static testPolygonCircle(polygon: Polygon, circle: Circle, response?: Response): bool; - /** - * Check if a circle and a polygon intersect. - * - * NOTE: This runs slightly slower than polygonCircle as it just - * runs polygonCircle and reverses everything at the end. - * - * @param {Circle} circle The circle. - * @param {Polygon} polygon The polygon. - * @param {Response=} response Response object (optional) that will be populated if - * they interset. - * @return {boolean} true if they intersect, false if they don't. - */ - static testCirclePolygon(circle: Circle, polygon: Polygon, response?: Response): bool; - /** - * Checks whether two convex, clockwise polygons intersect. - * - * @param {Polygon} a The first polygon. - * @param {Polygon} b The second polygon. - * @param {Response=} response Response object (optional) that will be populated if - * they interset. - * @return {boolean} true if they intersect, false if they don't. - */ - static testPolygonPolygon(a: Polygon, b: Polygon, response?: Response): bool; - } -} -/** -* Phaser - DynamicTexture -* -* A DynamicTexture can be thought of as a mini canvas into which you can draw anything. -* Game Objects can be assigned a DynamicTexture, so when they render in the world they do so -* based on the contents of the texture at the time. This allows you to create powerful effects -* once and have them replicated across as many game objects as you like. -*/ -module Phaser { - class DynamicTexture { - /** - * DynamicTexture constructor - * Create a new DynamicTexture. - * - * @param game {Phaser.Game} Current game instance. - * @param width {number} Init width of this texture. - * @param height {number} Init height of this texture. - */ - constructor(game: Game, width: number, height: number); - /** - * Local private reference to game. - */ - private _game; - private _sx; - private _sy; - private _sw; - private _sh; - private _dx; - private _dy; - private _dw; - private _dh; - /** - * Bound of this texture with width and height info. - * @type {Rectangle} - */ - public bounds: Rectangle; - /** - * This class is actually a wrapper of canvas. - * @type {HTMLCanvasElement} - */ - public canvas: HTMLCanvasElement; - /** - * Canvas context of this object. - * @type {CanvasRenderingContext2D} - */ - public context: CanvasRenderingContext2D; - /** - * Get a color of a specific pixel. - * @param x {number} X position of the pixel in this texture. - * @param y {number} Y position of the pixel in this texture. - * @return {number} A native color value integer (format: 0xRRGGBB) - */ - public getPixel(x: number, y: number): number; - /** - * Get a color of a specific pixel (including alpha value). - * @param x {number} X position of the pixel in this texture. - * @param y {number} Y position of the pixel in this texture. - * @return A native color value integer (format: 0xAARRGGBB) - */ - public getPixel32(x: number, y: number): number; - /** - * Get pixels in array in a specific rectangle. - * @param rect {Rectangle} The specific rectangle. - * @returns {array} CanvasPixelArray. - */ - public getPixels(rect: Rectangle): ImageData; - /** - * Set color of a specific pixel. - * @param x {number} X position of the target pixel. - * @param y {number} Y position of the target pixel. - * @param color {number} Native integer with color value. (format: 0xRRGGBB) - */ - public setPixel(x: number, y: number, color: string): void; - /** - * Set color (with alpha) of a specific pixel. - * @param x {number} X position of the target pixel. - * @param y {number} Y position of the target pixel. - * @param color {number} Native integer with color value. (format: 0xAARRGGBB) - */ - public setPixel32(x: number, y: number, color: number): void; - /** - * Set image data to a specific rectangle. - * @param rect {Rectangle} Target rectangle. - * @param input {object} Source image data. - */ - public setPixels(rect: Rectangle, input): void; - /** - * Fill a given rectangle with specific color. - * @param rect {Rectangle} Target rectangle you want to fill. - * @param color {number} A native number with color value. (format: 0xRRGGBB) - */ - public fillRect(rect: Rectangle, color: number): void; - /** - * - */ - public pasteImage(key: string, frame?: number, destX?: number, destY?: number, destWidth?: number, destHeight?: number): void; - /** - * Copy pixel from another DynamicTexture to this texture. - * @param sourceTexture {DynamicTexture} Source texture object. - * @param sourceRect {Rectangle} The specific region rectangle to be copied to this in the source. - * @param destPoint {Point} Top-left point the target image data will be paste at. - */ - public copyPixels(sourceTexture: DynamicTexture, sourceRect: Rectangle, destPoint: Point): void; - /** - * Given an array of GameObjects it will update each of them so that their canvas/contexts reference this DynamicTexture - * @param objects {Array} An array of GameObjects, or objects that inherit from it such as Sprites - */ - public assignCanvasToGameObjects(objects: GameObject[]): void; - /** - * Clear the whole canvas. - */ - public clear(): void; - /** - * Renders this DynamicTexture to the Stage at the given x/y coordinates - * - * @param x {number} The X coordinate to render on the stage to (given in screen coordinates, not world) - * @param y {number} The Y coordinate to render on the stage to (given in screen coordinates, not world) - */ - public render(x?: number, y?: number): void; - public width : number; - public height : number; - /** - * Given an alpha and 3 color values this will return an integer representation of it - * - * @param alpha {number} The Alpha value (between 0 and 255) - * @param red {number} The Red channel value (between 0 and 255) - * @param green {number} The Green channel value (between 0 and 255) - * @param blue {number} The Blue channel value (between 0 and 255) - * - * @return A native color value integer (format: 0xAARRGGBB) - */ - private getColor32(alpha, red, green, blue); - /** - * Given 3 color values this will return an integer representation of it - * - * @param red {number} The Red channel value (between 0 and 255) - * @param green {number} The Green channel value (between 0 and 255) - * @param blue {number} The Blue channel value (between 0 and 255) - * - * @return A native color value integer (format: 0xRRGGBB) - */ - private getColor(red, green, blue); - } -} -/** * Phaser - GameMath * * Adds a set of extra Math functions used through-out Phaser. @@ -4401,6 +811,2091 @@ module Phaser { } } /** +* Phaser - RandomDataGenerator +* +* An extremely useful repeatable random data generator. Access it via Game.rnd +* Based on Nonsense by Josh Faul https://github.com/jocafa/Nonsense +* Random number generator from http://baagoe.org/en/wiki/Better_random_numbers_for_javascript +*/ +module Phaser { + class RandomDataGenerator { + /** + * @constructor + * @param {Array} seeds + * @return {Phaser.RandomDataGenerator} + */ + constructor(seeds?: string[]); + /** + * @property s0 + * @type Any + * @private + */ + private s0; + /** + * @property s1 + * @type Any + * @private + */ + private s1; + /** + * @property s2 + * @type Any + * @private + */ + private s2; + /** + * @property c + * @type Number + * @private + */ + private c; + /** + * @method uint32 + * @private + */ + private uint32(); + /** + * @method fract32 + * @private + */ + private fract32(); + /** + * @method rnd + * @private + */ + private rnd(); + /** + * @method hash + * @param {Any} data + * @private + */ + private hash(data); + /** + * Reset the seed of the random data generator + * @method sow + * @param {Array} seeds + */ + public sow(seeds?: string[]): void; + /** + * Returns a random integer between 0 and 2^32 + * @method integer + * @return {Number} + */ + public integer : number; + /** + * Returns a random real number between 0 and 1 + * @method frac + * @return {Number} + */ + public frac : number; + /** + * Returns a random real number between 0 and 2^32 + * @method real + * @return {Number} + */ + public real : number; + /** + * Returns a random integer between min and max + * @method integerInRange + * @param {Number} min + * @param {Number} max + * @return {Number} + */ + public integerInRange(min: number, max: number): number; + /** + * Returns a random real number between min and max + * @method realInRange + * @param {Number} min + * @param {Number} max + * @return {Number} + */ + public realInRange(min: number, max: number): number; + /** + * Returns a random real number between -1 and 1 + * @method normal + * @return {Number} + */ + public normal : number; + /** + * Returns a valid v4 UUID hex string (from https://gist.github.com/1308368) + * @method uuid + * @return {String} + */ + public uuid : string; + /** + * Returns a random member of `array` + * @method pick + * @param {Any} array + */ + public pick(array); + /** + * Returns a random member of `array`, favoring the earlier entries + * @method weightedPick + * @param {Any} array + */ + public weightedPick(array); + /** + * 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 timestamp + * @param {Number} min + * @param {Number} max + */ + public timestamp(min?: number, max?: number): number; + /** + * Returns a random angle between -180 and 180 + * @method angle + */ + public angle : number; + } +} +/** +* Phaser - Vec2 +* +* A Circle object is an area defined by its position, as indicated by its center point (x,y) and diameter. +*/ +module Phaser { + class Vec2 { + /** + * Creates a new Vec2 object. + * @class Vec2 + * @constructor + * @param {Number} x The x position of the vector + * @param {Number} y The y position of the vector + * @return {Vec2} This object + **/ + constructor(x?: number, y?: number); + /** + * The x coordinate of the vector + * @property x + * @type Number + **/ + public x: number; + /** + * The y coordinate of the vector + * @property y + * @type Number + **/ + public y: number; + /** + * Copies the x and y properties from any given object to this Vec2. + * @method copyFrom + * @param {any} source - The object to copy from. + * @return {Vec2} This Vec2 object. + **/ + public copyFrom(source: any): Vec2; + /** + * Sets the x and y properties of the Vector. + * @param {Number} x The x position of the vector + * @param {Number} y The y position of the vector + * @return {Vec2} This object + **/ + public setTo(x: number, y: number): Vec2; + /** + * Add another vector to this one. + * + * @param {Vec2} other The other Vector. + * @return {Vec2} This for chaining. + */ + public add(a: Vec2): Vec2; + /** + * Subtract another vector from this one. + * + * @param {Vec2} other The other Vector. + * @return {Vec2} This for chaining. + */ + public subtract(v: Vec2): Vec2; + /** + * Multiply another vector with this one. + * + * @param {Vec2} other The other Vector. + * @return {Vec2} This for chaining. + */ + public multiply(v: Vec2): Vec2; + /** + * Divide this vector by another one. + * + * @param {Vec2} other The other Vector. + * @return {Vec2} This for chaining. + */ + public divide(v: Vec2): Vec2; + /** + * Get the length of this vector. + * + * @return {number} The length of this vector. + */ + public length(): number; + /** + * Get the length squared of this vector. + * + * @return {number} The length^2 of this vector. + */ + public lengthSq(): number; + /** + * The dot product of two 2D vectors. + * + * @param {Vec2} a Reference to a source Vec2 object. + * @return {Number} + */ + public dot(a: Vec2): number; + /** + * The cross product of two 2D vectors. + * + * @param {Vec2} a Reference to a source Vec2 object. + * @return {Number} + */ + public cross(a: Vec2): number; + /** + * The projection magnitude of two 2D vectors. + * + * @param {Vec2} a Reference to a source Vec2 object. + * @return {Number} + */ + public projectionLength(a: Vec2): number; + /** + * The angle between two 2D vectors. + * + * @param {Vec2} a Reference to a source Vec2 object. + * @return {Number} + */ + public angle(a: Vec2): number; + /** + * Scale this vector. + * + * @param {number} x The scaling factor in the x direction. + * @param {?number=} y The scaling factor in the y direction. If this is not specified, the x scaling factor will be used. + * @return {Vec2} This for chaining. + */ + public scale(x: number, y?: number): Vec2; + /** + * Divide this vector by the given scalar. + * + * @param {number} scalar + * @return {Vec2} This for chaining. + */ + public divideByScalar(scalar: number): Vec2; + /** + * Reverse this vector. + * + * @return {Vec2} This for chaining. + */ + public reverse(): Vec2; + /** + * Returns a string representation of this object. + * @method toString + * @return {string} a string representation of the object. + **/ + public toString(): string; + } +} +/** +* Phaser - AnimationLoader +* +* Responsible for parsing sprite sheet and JSON data into the internal FrameData format that Phaser uses for animations. +*/ +module Phaser { + class AnimationLoader { + /** + * Parse a sprite sheet from asset data. + * @param key {string} Asset key for the sprite sheet data. + * @param frameWidth {number} Width of animation frame. + * @param frameHeight {number} Height of animation frame. + * @param frameMax {number} Number of animation frames. + * @return {FrameData} Generated FrameData object. + */ + static parseSpriteSheet(game: Game, key: string, frameWidth: number, frameHeight: number, frameMax: number): FrameData; + /** + * Parse frame datas from json. + * @param json {object} Json data you want to parse. + * @return {FrameData} Generated FrameData object. + */ + static parseJSONData(game: Game, json): FrameData; + static parseXMLData(game: Game, xml, format: number): FrameData; + } +} +/** +* Phaser - Animation +* +* An Animation is a single animation. It is created by the AnimationManager and belongs to Sprite objects. +*/ +module Phaser { + class Animation { + /** + * Animation constructor + * Create a new Animation. + * + * @param parent {Sprite} Owner sprite of this animation. + * @param frameData {FrameData} The FrameData object contains animation data. + * @param name {string} Unique name of this animation. + * @param frames {number[]/string[]} An array of numbers or strings indicating what frames to play in what order. + * @param delay {number} Time between frames in ms. + * @param looped {boolean} Whether or not the animation is looped or just plays once. + */ + constructor(game: Game, parent: Sprite, frameData: FrameData, name: string, frames, delay: number, looped: bool); + /** + * Local private reference to game. + */ + private _game; + /** + * Local private reference to its owner sprite. + * @type {Sprite} + */ + private _parent; + /** + * Animation frame container. + * @type {number[]} + */ + private _frames; + /** + * Frame data of this animation.(parsed from sprite sheet) + * @type {FrameData} + */ + private _frameData; + /** + * Index of current frame. + * @type {number} + */ + private _frameIndex; + /** + * Time when switched to last frame (in ms). + * @type number + */ + private _timeLastFrame; + /** + * Time when this will switch to next frame (in ms). + * @type number + */ + private _timeNextFrame; + /** + * Name of this animation. + * @type {string} + */ + public name: string; + /** + * Currently played frame instance. + * @type {Frame} + */ + public currentFrame: Frame; + /** + * Whether or not this animation finished playing. + * @type {boolean} + */ + public isFinished: bool; + /** + * Whethor or not this animation is currently playing. + * @type {boolean} + */ + public isPlaying: bool; + /** + * Whether or not the animation is looped. + * @type {boolean} + */ + public looped: bool; + /** + * Time between frames in ms. + * @type {number} + */ + public delay: number; + public frameTotal : number; + public frame : number; + /** + * Play this animation. + * @param frameRate {number} FrameRate you want to specify instead of using default. + * @param loop {boolean} Whether or not the animation is looped or just plays once. + */ + public play(frameRate?: number, loop?: bool): void; + /** + * Play this animation from the first frame. + */ + public restart(): void; + /** + * Stop playing animation and set it finished. + */ + public stop(): void; + /** + * Update animation frames. + */ + public update(): bool; + /** + * Clean up animation memory. + */ + public destroy(): void; + /** + * Animation complete callback method. + */ + private onComplete(); + } +} +/** +* Phaser - Frame +* +* A Frame is a single frame of an animation and is part of a FrameData collection. +*/ +module Phaser { + class Frame { + /** + * Frame constructor + * Create a new Frame with specific position, size and name. + * + * @param x {number} X position within the image to cut from. + * @param y {number} Y position within the image to cut from. + * @param width {number} Width of the frame. + * @param height {number} Height of the frame. + * @param name {string} Name of this frame. + */ + constructor(x: number, y: number, width: number, height: number, name: string); + /** + * X position within the image to cut from. + * @type {number} + */ + public x: number; + /** + * Y position within the image to cut from. + * @type {number} + */ + public y: number; + /** + * Width of the frame. + * @type {number} + */ + public width: number; + /** + * Height of the frame. + * @type {number} + */ + public height: number; + /** + * Useful for Sprite Sheets. + * @type {number} + */ + public index: number; + /** + * Useful for Texture Atlas files. (is set to the filename value) + */ + public name: string; + /** + * Rotated? (not yet implemented) + */ + public rotated: bool; + /** + * Either cw or ccw, rotation is always 90 degrees. + */ + public rotationDirection: string; + /** + * Was it trimmed when packed? + * @type {boolean} + */ + public trimmed: bool; + /** + * Width of the original sprite. + * @type {number} + */ + public sourceSizeW: number; + /** + * Height of the original sprite. + * @type {number} + */ + public sourceSizeH: number; + /** + * X position of the trimmed sprite inside original sprite. + * @type {number} + */ + public spriteSourceSizeX: number; + /** + * Y position of the trimmed sprite inside original sprite. + * @type {number} + */ + public spriteSourceSizeY: number; + /** + * Width of the trimmed sprite. + * @type {number} + */ + public spriteSourceSizeW: number; + /** + * Height of the trimmed sprite. + * @type {number} + */ + public spriteSourceSizeH: number; + /** + * Set rotation of this frame. (Not yet supported!) + */ + public setRotation(rotated: bool, rotationDirection: string): void; + /** + * Set trim of the frame. + * @param trimmed {boolean} Whether this frame trimmed or not. + * @param actualWidth {number} Actual width of this frame. + * @param actualHeight {number} Actual height of this frame. + * @param destX {number} Destiny x position. + * @param destY {number} Destiny y position. + * @param destWidth {number} Destiny draw width. + * @param destHeight {number} Destiny draw height. + */ + public setTrim(trimmed: bool, actualWidth: number, actualHeight: number, destX: number, destY: number, destWidth: number, destHeight: number): void; + } +} +/** +* Phaser - FrameData +* +* FrameData is a container for Frame objects, the internal representation of animation data in Phaser. +*/ +module Phaser { + class FrameData { + /** + * FrameData constructor + */ + constructor(); + /** + * Local frame container. + */ + private _frames; + /** + * Local frameName<->index container. + */ + private _frameNames; + public total : number; + /** + * Add a new frame. + * @param frame {Frame} The frame you want to add. + * @return {Frame} The frame you just added. + */ + public addFrame(frame: Frame): Frame; + /** + * Get a frame by its index. + * @param index {number} Index of the frame you want to get. + * @return {Frame} The frame you want. + */ + public getFrame(index: number): Frame; + /** + * Get a frame by its name. + * @param name {string} Name of the frame you want to get. + * @return {Frame} The frame you want. + */ + public getFrameByName(name: string): Frame; + /** + * Check whether there's a frame with given name. + * @param name {string} Name of the frame you want to check. + * @return {boolean} True if frame with given name found, otherwise return false. + */ + public checkFrameName(name: string): bool; + /** + * Get ranges of frames in an array. + * @param start {number} Start index of frames you want. + * @param end {number} End index of frames you want. + * @param [output] {Frame[]} result will be added into this array. + * @return {Frame[]} Ranges of specific frames in an array. + */ + public getFrameRange(start: number, end: number, output?: Frame[]): Frame[]; + /** + * Get all indexes of frames by giving their name. + * @param [output] {number[]} result will be added into this array. + * @return {number[]} Indexes of specific frames in an array. + */ + public getFrameIndexes(output?: number[]): number[]; + /** + * Get all names of frames by giving their indexes. + * @param [output] {number[]} result will be added into this array. + * @return {number[]} Names of specific frames in an array. + */ + public getFrameIndexesByName(input: string[]): number[]; + /** + * Get all frames in this frame data. + * @return {Frame[]} All the frames in an array. + */ + public getAllFrames(): Frame[]; + /** + * Get All frames with specific ranges. + * @param range {number[]} Ranges in an array. + * @return {Frame[]} All frames in an array. + */ + public getFrames(range: number[]): Frame[]; + } +} +/** +* Phaser - AnimationManager +* +* Any Sprite that has animation contains an instance of the AnimationManager, which is used to add, play and update +* sprite specific animations. +*/ +module Phaser { + class AnimationManager { + /** + * AnimationManager constructor + * Create a new AnimationManager. + * + * @param parent {Sprite} Owner sprite of this manager. + */ + constructor(game: Game, parent: Sprite); + /** + * Local private reference to game. + */ + private _game; + /** + * Local private reference to its owner sprite. + */ + private _parent; + /** + * Animation key-value container. + */ + private _anims; + /** + * Index of current frame. + * @type {number} + */ + private _frameIndex; + /** + * Data contains animation frames. + * @type {FrameData} + */ + private _frameData; + /** + * Keeps track of the current animation being played. + */ + public currentAnim: Animation; + /** + * Keeps track of the current frame of animation. + */ + public currentFrame: Frame; + /** + * Load animation frame data. + * @param frameData Data to be loaded. + */ + public loadFrameData(frameData: FrameData): void; + /** + * Add a new animation. + * @param name {string} What this animation should be called (e.g. "run"). + * @param frames {any[]} An array of numbers/strings indicating what frames to play in what order (e.g. [1, 2, 3] or ['run0', 'run1', run2]). + * @param frameRate {number} The speed in frames per second that the animation should play at (e.g. 60 fps). + * @param loop {boolean} Whether or not the animation is looped or just plays once. + * @param useNumericIndex {boolean} Use number indexes instead of string indexes? + * @return {Animation} The Animation that was created + */ + public add(name: string, frames?: any[], frameRate?: number, loop?: bool, useNumericIndex?: bool): Animation; + /** + * Check whether the frames is valid. + * @param frames {any[]} Frames to be validated. + * @param useNumericIndex {boolean} Does these frames use number indexes or string indexes? + * @return {boolean} True if they're valid, otherwise return false. + */ + private validateFrames(frames, useNumericIndex); + /** + * Play animation with specific name. + * @param name {string} The string name of the animation you want to play. + * @param frameRate {number} FrameRate you want to specify instead of using default. + * @param loop {boolean} Whether or not the animation is looped or just plays once. + */ + public play(name: string, frameRate?: number, loop?: bool): void; + /** + * Stop animation by name. + * Current animation will be automatically set to the stopped one. + */ + public stop(name: string): void; + /** + * Update animation and parent sprite's bounds. + */ + public update(): void; + public frameData : FrameData; + public frameTotal : number; + public frame : number; + public frameName : string; + /** + * Removes all related references + */ + public destroy(): void; + } +} +/** +* Phaser - Components - Position +* +* Sprite position, both world and screen, and rotation values and methods. +*/ +module Phaser.Components { + class Position { + constructor(parent: Sprite, x: number, y: number); + /** + * Reference to the Image stored in the Game.Cache that is used as the texture for the Sprite. + */ + private _sprite; + public world: Vec2; + public screen: Vec2; + public offset: Vec2; + public midpoint: Vec2; + /** + * Rotation angle of this object. + * @type {number} + */ + private _rotation; + /** + * Z-order value of the object. + */ + public z: number; + /** + * This value is added to the rotation of the Sprite. + * For example if you had a sprite graphic drawn facing straight up then you could set + * rotationOffset to 90 and it would correspond correctly with Phasers right-handed coordinate system. + * @type {number} + */ + public rotationOffset: number; + public rotation : number; + } +} +/** +* Phaser - RectangleUtils +* +* A collection of methods useful for manipulating and comparing Rectangle objects. +* +* TODO: Check docs + overlap + intersect + toPolygon? +*/ +module Phaser { + class RectangleUtils { + /** + * Get the location of the Rectangles top-left corner as a Point object. + * @method getTopLeftAsPoint + * @param {Rectangle} a - The Rectangle object. + * @param {Point} out - Optional Point to store the value in, if not supplied a new Point object will be created. + * @return {Point} The new Point object. + **/ + static getTopLeftAsPoint(a: Rectangle, out?: Point): Point; + /** + * Get the location of the Rectangles bottom-right corner as a Point object. + * @method getTopLeftAsPoint + * @param {Rectangle} a - The Rectangle object. + * @param {Point} out - Optional Point to store the value in, if not supplied a new Point object will be created. + * @return {Point} The new Point object. + **/ + static getBottomRightAsPoint(a: Rectangle, out?: Point): Point; + /** + * Increases the size of the Rectangle object by the specified amounts. The center point of the Rectangle object stays the same, and its size increases to the left and right by the dx value, and to the top and the bottom by the dy value. + * @method inflate + * @param {Rectangle} a - The Rectangle object. + * @param {Number} dx The amount to be added to the left side of the Rectangle. + * @param {Number} dy The amount to be added to the bottom side of the Rectangle. + * @return {Rectangle} This Rectangle object. + **/ + static inflate(a: Rectangle, dx: number, dy: number): Rectangle; + /** + * Increases the size of the Rectangle object. This method is similar to the Rectangle.inflate() method except it takes a Point object as a parameter. + * @method inflatePoint + * @param {Rectangle} a - The Rectangle object. + * @param {Point} point The x property of this Point object is used to increase the horizontal dimension of the Rectangle object. The y property is used to increase the vertical dimension of the Rectangle object. + * @return {Rectangle} The Rectangle object. + **/ + static inflatePoint(a: Rectangle, point: Point): Rectangle; + /** + * The size of the Rectangle object, expressed as a Point object with the values of the width and height properties. + * @method size + * @param {Rectangle} a - The Rectangle object. + * @param {Point} output Optional Point object. If given the values will be set into the object, otherwise a brand new Point object will be created and returned. + * @return {Point} The size of the Rectangle object + **/ + static size(a: Rectangle, output?: Point): Point; + /** + * Returns a new Rectangle object with the same values for the x, y, width, and height properties as the original Rectangle object. + * @method clone + * @param {Rectangle} a - The Rectangle object. + * @param {Rectangle} output Optional Rectangle object. If given the values will be set into the object, otherwise a brand new Rectangle object will be created and returned. + * @return {Rectangle} + **/ + static clone(a: Rectangle, output?: Rectangle): Rectangle; + /** + * Determines whether the specified coordinates are contained within the region defined by this Rectangle object. + * @method contains + * @param {Rectangle} a - The Rectangle object. + * @param {Number} x The x coordinate of the point to test. + * @param {Number} y The y coordinate of the point to test. + * @return {Boolean} A value of true if the Rectangle object contains the specified point; otherwise false. + **/ + static contains(a: Rectangle, x: number, y: number): bool; + /** + * Determines whether the specified point is contained within the rectangular region defined by this Rectangle object. This method is similar to the Rectangle.contains() method, except that it takes a Point object as a parameter. + * @method containsPoint + * @param {Rectangle} a - The Rectangle object. + * @param {Point} point The point object being checked. Can be Point or any object with .x and .y values. + * @return {Boolean} A value of true if the Rectangle object contains the specified point; otherwise false. + **/ + static containsPoint(a: Rectangle, point: Point): bool; + /** + * Determines whether the first Rectangle object is fully contained within the second Rectangle object. + * A Rectangle object is said to contain another if the second Rectangle object falls entirely within the boundaries of the first. + * @method containsRect + * @param {Rectangle} a - The first Rectangle object. + * @param {Rectangle} b - The second Rectangle object. + * @return {Boolean} A value of true if the Rectangle object contains the specified point; otherwise false. + **/ + static containsRect(a: Rectangle, b: Rectangle): bool; + /** + * Determines whether the two Rectangles are equal. + * This method compares the x, y, width and height properties of each Rectangle. + * @method equals + * @param {Rectangle} a - The first Rectangle object. + * @param {Rectangle} b - The second Rectangle object. + * @return {Boolean} A value of true if the two Rectangles have exactly the same values for the x, y, width and height properties; otherwise false. + **/ + static equals(a: Rectangle, b: Rectangle): bool; + /** + * If the Rectangle object specified in the toIntersect parameter intersects with this Rectangle object, returns the area of intersection as a Rectangle object. If the rectangles do not intersect, this method returns an empty Rectangle object with its properties set to 0. + * @method intersection + * @param {Rectangle} a - The first Rectangle object. + * @param {Rectangle} b - The second Rectangle object. + * @param {Rectangle} output Optional Rectangle object. If given the intersection values will be set into this object, otherwise a brand new Rectangle object will be created and returned. + * @return {Rectangle} A Rectangle object that equals the area of intersection. If the rectangles do not intersect, this method returns an empty Rectangle object; that is, a rectangle with its x, y, width, and height properties set to 0. + **/ + static intersection(a: Rectangle, b: Rectangle, out?: Rectangle): Rectangle; + /** + * Determines whether the two Rectangles intersect with each other. + * This method checks the x, y, width, and height properties of the Rectangles. + * @method intersects + * @param {Rectangle} a - The first Rectangle object. + * @param {Rectangle} b - The second Rectangle object. + * @param {Number} tolerance A tolerance value to allow for an intersection test with padding, default to 0 + * @return {Boolean} A value of true if the specified object intersects with this Rectangle object; otherwise false. + **/ + static intersects(a: Rectangle, b: Rectangle, tolerance?: number): bool; + /** + * Determines whether the object specified intersects (overlaps) with the given values. + * @method intersectsRaw + * @param {Number} left + * @param {Number} right + * @param {Number} top + * @param {Number} bottomt + * @param {Number} tolerance A tolerance value to allow for an intersection test with padding, default to 0 + * @return {Boolean} A value of true if the specified object intersects with the Rectangle; otherwise false. + **/ + static intersectsRaw(a: Rectangle, left: number, right: number, top: number, bottom: number, tolerance?: number): bool; + /** + * Adds two rectangles together to create a new Rectangle object, by filling in the horizontal and vertical space between the two rectangles. + * @method union + * @param {Rectangle} a - The first Rectangle object. + * @param {Rectangle} b - The second Rectangle object. + * @param {Rectangle} output Optional Rectangle object. If given the new values will be set into this object, otherwise a brand new Rectangle object will be created and returned. + * @return {Rectangle} A Rectangle object that is the union of the two rectangles. + **/ + static union(a: Rectangle, b: Rectangle, out?: Rectangle): Rectangle; + } +} +module Phaser { + interface IGameObject { + /** + * Reference to the main game object + */ + game: Game; + /** + * The type of game object. + */ + type: number; + /** + * Reference to the Renderer.renderSprite method. Can be overriden by custom classes. + */ + render; + /** + * Controls if both update and render are called by the core game loop. + */ + exists: bool; + /** + * Controls if update() is automatically called by the core game loop. + */ + active: bool; + /** + * Controls if this Sprite is rendered or skipped during the core game loop. + */ + visible: bool; + /** + * The position of the Sprite in world and screen coordinates. + */ + position: Components.Position; + /** + * The texture used to render the Sprite. + */ + texture: Components.Texture; + /** + * Scale of the Sprite. A scale of 1.0 is the original size. 0.5 half size. 2.0 double sized. + */ + scale: Vec2; + /** + * The influence of camera movement upon the Sprite. + */ + scrollFactor: Vec2; + } +} +/** +* Phaser - DynamicTexture +* +* A DynamicTexture can be thought of as a mini canvas into which you can draw anything. +* Game Objects can be assigned a DynamicTexture, so when they render in the world they do so +* based on the contents of the texture at the time. This allows you to create powerful effects +* once and have them replicated across as many game objects as you like. +*/ +module Phaser { + class DynamicTexture { + /** + * DynamicTexture constructor + * Create a new DynamicTexture. + * + * @param game {Phaser.Game} Current game instance. + * @param width {number} Init width of this texture. + * @param height {number} Init height of this texture. + */ + constructor(game: Game, width: number, height: number); + /** + * Reference to game. + */ + public game: Game; + /** + * The type of game object. + */ + public type: number; + private _sx; + private _sy; + private _sw; + private _sh; + private _dx; + private _dy; + private _dw; + private _dh; + /** + * Bound of this texture with width and height info. + * @type {Rectangle} + */ + public bounds: Rectangle; + /** + * This class is actually a wrapper of canvas. + * @type {HTMLCanvasElement} + */ + public canvas: HTMLCanvasElement; + /** + * Canvas context of this object. + * @type {CanvasRenderingContext2D} + */ + public context: CanvasRenderingContext2D; + /** + * Get a color of a specific pixel. + * @param x {number} X position of the pixel in this texture. + * @param y {number} Y position of the pixel in this texture. + * @return {number} A native color value integer (format: 0xRRGGBB) + */ + public getPixel(x: number, y: number): number; + /** + * Get a color of a specific pixel (including alpha value). + * @param x {number} X position of the pixel in this texture. + * @param y {number} Y position of the pixel in this texture. + * @return A native color value integer (format: 0xAARRGGBB) + */ + public getPixel32(x: number, y: number): number; + /** + * Get pixels in array in a specific rectangle. + * @param rect {Rectangle} The specific rectangle. + * @returns {array} CanvasPixelArray. + */ + public getPixels(rect: Rectangle): ImageData; + /** + * Set color of a specific pixel. + * @param x {number} X position of the target pixel. + * @param y {number} Y position of the target pixel. + * @param color {number} Native integer with color value. (format: 0xRRGGBB) + */ + public setPixel(x: number, y: number, color: string): void; + /** + * Set color (with alpha) of a specific pixel. + * @param x {number} X position of the target pixel. + * @param y {number} Y position of the target pixel. + * @param color {number} Native integer with color value. (format: 0xAARRGGBB) + */ + public setPixel32(x: number, y: number, color: number): void; + /** + * Set image data to a specific rectangle. + * @param rect {Rectangle} Target rectangle. + * @param input {object} Source image data. + */ + public setPixels(rect: Rectangle, input): void; + /** + * Fill a given rectangle with specific color. + * @param rect {Rectangle} Target rectangle you want to fill. + * @param color {number} A native number with color value. (format: 0xRRGGBB) + */ + public fillRect(rect: Rectangle, color: number): void; + /** + * + */ + public pasteImage(key: string, frame?: number, destX?: number, destY?: number, destWidth?: number, destHeight?: number): void; + /** + * Copy pixel from another DynamicTexture to this texture. + * @param sourceTexture {DynamicTexture} Source texture object. + * @param sourceRect {Rectangle} The specific region rectangle to be copied to this in the source. + * @param destPoint {Point} Top-left point the target image data will be paste at. + */ + public copyPixels(sourceTexture: DynamicTexture, sourceRect: Rectangle, destPoint: Point): void; + /** + * Given an array of Sprites it will update each of them so that their canvas/contexts reference this DynamicTexture + * @param objects {Array} An array of GameObjects, or objects that inherit from it such as Sprites + */ + public assignCanvasToGameObjects(objects: IGameObject[]): void; + /** + * Clear the whole canvas. + */ + public clear(): void; + /** + * Renders this DynamicTexture to the Stage at the given x/y coordinates + * + * @param x {number} The X coordinate to render on the stage to (given in screen coordinates, not world) + * @param y {number} The Y coordinate to render on the stage to (given in screen coordinates, not world) + */ + public render(x?: number, y?: number): void; + public width : number; + public height : number; + /** + * Given an alpha and 3 color values this will return an integer representation of it + * + * @param alpha {number} The Alpha value (between 0 and 255) + * @param red {number} The Red channel value (between 0 and 255) + * @param green {number} The Green channel value (between 0 and 255) + * @param blue {number} The Blue channel value (between 0 and 255) + * + * @return A native color value integer (format: 0xAARRGGBB) + */ + private getColor32(alpha, red, green, blue); + /** + * Given 3 color values this will return an integer representation of it + * + * @param red {number} The Red channel value (between 0 and 255) + * @param green {number} The Green channel value (between 0 and 255) + * @param blue {number} The Blue channel value (between 0 and 255) + * + * @return A native color value integer (format: 0xRRGGBB) + */ + private getColor(red, green, blue); + } +} +/** +* Phaser - Circle +* +* A Circle object is an area defined by its position, as indicated by its center point (x,y) and diameter. +*/ +module Phaser { + class Circle { + /** + * Creates a new Circle object with the center coordinate specified by the x and y parameters and the diameter specified by the diameter parameter. If you call this function without parameters, a circle with x, y, diameter and radius properties set to 0 is created. + * @class Circle + * @constructor + * @param {Number} [x] The x coordinate of the center of the circle. + * @param {Number} [y] The y coordinate of the center of the circle. + * @param {Number} [diameter] The diameter of the circle. + * @return {Circle} This circle object + **/ + constructor(x?: number, y?: number, diameter?: number); + private _diameter; + private _radius; + /** + * The x coordinate of the center of the circle + * @property x + * @type Number + **/ + public x: number; + /** + * The y coordinate of the center of the circle + * @property y + * @type Number + **/ + public y: number; + /** + * The diameter of the circle. The largest distance between any two points on the circle. The same as the radius * 2. + * @method diameter + * @return {Number} + **/ + /** + * The diameter of the circle. The largest distance between any two points on the circle. The same as the radius * 2. + * @method diameter + * @param {Number} The diameter of the circle. + **/ + public diameter : number; + /** + * The radius of the circle. The length of a line extending from the center of the circle to any point on the circle itself. The same as half the diameter. + * @method radius + * @return {Number} + **/ + /** + * The radius of the circle. The length of a line extending from the center of the circle to any point on the circle itself. The same as half the diameter. + * @method radius + * @param {Number} The radius of the circle. + **/ + public radius : number; + /** + * The circumference of the circle. + * @method circumference + * @return {Number} + **/ + public circumference(): number; + /** + * The sum of the y and radius properties. Changing the bottom property of a Circle object has no effect on the x and y properties, but does change the diameter. + * @method bottom + * @return {Number} + **/ + /** + * The sum of the y and radius properties. Changing the bottom property of a Circle object has no effect on the x and y properties, but does change the diameter. + * @method bottom + * @param {Number} The value to adjust the height of the circle by. + **/ + public bottom : number; + /** + * The x coordinate of the leftmost point of the circle. Changing the left property of a Circle object has no effect on the x and y properties. However it does affect the diameter, whereas changing the x value does not affect the diameter property. + * @method left + * @return {Number} The x coordinate of the leftmost point of the circle. + **/ + /** + * The x coordinate of the leftmost point of the circle. Changing the left property of a Circle object has no effect on the x and y properties. However it does affect the diameter, whereas changing the x value does not affect the diameter property. + * @method left + * @param {Number} The value to adjust the position of the leftmost point of the circle by. + **/ + public left : number; + /** + * The x coordinate of the rightmost point of the circle. Changing the right property of a Circle object has no effect on the x and y properties. However it does affect the diameter, whereas changing the x value does not affect the diameter property. + * @method right + * @return {Number} + **/ + /** + * The x coordinate of the rightmost point of the circle. Changing the right property of a Circle object has no effect on the x and y properties. However it does affect the diameter, whereas changing the x value does not affect the diameter property. + * @method right + * @param {Number} The amount to adjust the diameter of the circle by. + **/ + public right : number; + /** + * The sum of the y minus the radius property. Changing the top property of a Circle object has no effect on the x and y properties, but does change the diameter. + * @method bottom + * @return {Number} + **/ + /** + * The sum of the y minus the radius property. Changing the top property of a Circle object has no effect on the x and y properties, but does change the diameter. + * @method bottom + * @param {Number} The amount to adjust the height of the circle by. + **/ + public top : number; + /** + * Gets the area of this Circle. + * @method area + * @return {Number} This area of this circle. + **/ + public area : number; + /** + * Sets the members of Circle to the specified values. + * @method setTo + * @param {Number} x The x coordinate of the center of the circle. + * @param {Number} y The y coordinate of the center of the circle. + * @param {Number} diameter The diameter of the circle in pixels. + * @return {Circle} This circle object + **/ + public setTo(x: number, y: number, diameter: number): Circle; + /** + * Copies the x, y and diameter properties from any given object to this Circle. + * @method copyFrom + * @param {any} source - The object to copy from. + * @return {Circle} This Circle object. + **/ + public copyFrom(source: any): Circle; + /** + * Determines whether or not this Circle object is empty. + * @method empty + * @return {Boolean} A value of true if the Circle objects diameter is less than or equal to 0; otherwise false. + **/ + /** + * Sets all of the Circle objects properties to 0. A Circle object is empty if its diameter is less than or equal to 0. + * @method setEmpty + * @return {Circle} This Circle object + **/ + public empty : bool; + /** + * Adjusts the location of the Circle object, as determined by its center coordinate, by the specified amounts. + * @method offset + * @param {Number} dx Moves the x value of the Circle object by this amount. + * @param {Number} dy Moves the y value of the Circle object by this amount. + * @return {Circle} This Circle object. + **/ + public offset(dx: number, dy: number): Circle; + /** + * Adjusts the location of the Circle object using a Point object as a parameter. This method is similar to the Circle.offset() method, except that it takes a Point object as a parameter. + * @method offsetPoint + * @param {Point} point A Point object to use to offset this Circle object. + * @return {Circle} This Circle object. + **/ + public offsetPoint(point: Point): Circle; + /** + * Returns a string representation of this object. + * @method toString + * @return {string} a string representation of the instance. + **/ + public toString(): string; + } +} +/** +* Phaser - SpriteUtils +* +* A collection of methods useful for manipulating and checking Sprites. +* +* TODO: +*/ +module Phaser { + class SpriteUtils { + /** + * Pivot position enum: at the top-left corner. + * @type {number} + */ + static ALIGN_TOP_LEFT: number; + /** + * Pivot position enum: at the top-center corner. + * @type {number} + */ + static ALIGN_TOP_CENTER: number; + /** + * Pivot position enum: at the top-right corner. + * @type {number} + */ + static ALIGN_TOP_RIGHT: number; + /** + * Pivot position enum: at the center-left corner. + * @type {number} + */ + static ALIGN_CENTER_LEFT: number; + /** + * Pivot position enum: at the center corner. + * @type {number} + */ + static ALIGN_CENTER: number; + /** + * Pivot position enum: at the center-right corner. + * @type {number} + */ + static ALIGN_CENTER_RIGHT: number; + /** + * Pivot position enum: at the bottom-left corner. + * @type {number} + */ + static ALIGN_BOTTOM_LEFT: number; + /** + * Pivot position enum: at the bottom-center corner. + * @type {number} + */ + static ALIGN_BOTTOM_CENTER: number; + /** + * Pivot position enum: at the bottom-right corner. + * @type {number} + */ + static ALIGN_BOTTOM_RIGHT: number; + /** + * Set the world bounds that this GameObject can exist within. By default a GameObject can exist anywhere + * in the world. But by setting the bounds (which are given in world dimensions, not screen dimensions) + * it can be stopped from leaving the world, or a section of it. + * + * @param x {number} x position of the bound + * @param y {number} y position of the bound + * @param width {number} width of its bound + * @param height {number} height of its bound + */ + static setBounds(x: number, y: number, width: number, height: number): void; + } +} +/** +* Phaser - Components - Texture +* +* The Texture being used to render the Sprite. Either Image based on a DynamicTexture. +*/ +module Phaser.Components { + class Texture { + constructor(parent: Sprite, key?: string, canvas?: HTMLCanvasElement, context?: CanvasRenderingContext2D); + /** + * + */ + private _game; + /** + * Reference to the Image stored in the Game.Cache that is used as the texture for the Sprite. + */ + private _sprite; + /** + * Reference to the Image stored in the Game.Cache that is used as the texture for the Sprite. + */ + private _imageTexture; + /** + * Reference to the DynamicTexture that is used as the texture for the Sprite. + * @type {DynamicTexture} + */ + private _dynamicTexture; + /** + * Opacity of the Sprite texture where 1 is opaque and 0 is fully transparent. + * @type {number} + */ + public alpha: number; + /** + * A reference to the Canvas this Sprite renders to. + * @type {HTMLCanvasElement} + */ + public canvas: HTMLCanvasElement; + /** + * A reference to the Canvas Context2D this Sprite renders to. + * @type {CanvasRenderingContext2D} + */ + public context: CanvasRenderingContext2D; + /** + * The Cache key used for the Image Texture. + */ + public cacheKey: string; + /** + * The Texture being used to render the Sprite. Either an Image Texture from the Cache or a DynamicTexture. + */ + public texture; + /** + * Controls if the Sprite is rendered rotated or not. + * If renderRotation is false then the object can still rotate but it will never be rendered rotated. + * @type {boolean} + */ + public renderRotation: bool; + /** + * Flip the graphic horizontally (defaults to false) + * @type {boolean} + */ + public flippedX: bool; + /** + * Flip the graphic vertically (defaults to false) + * @type {boolean} + */ + public flippedY: bool; + /** + * Updates the texture being used to render the Sprite. + * Called automatically by SpriteUtils.loadTexture and SpriteUtils.loadDynamicTexture. + */ + public setTo(image?, dynamic?: DynamicTexture): Sprite; + /** + * Sets a new graphic from the game cache to use as the texture for this Sprite. + * The graphic can be SpriteSheet or Texture Atlas. If you need to use a DynamicTexture see loadDynamicTexture. + * @param key {string} Key of the graphic you want to load for this sprite. + * @param clearAnimations {boolean} If this Sprite has a set of animation data already loaded you can choose to keep or clear it with this boolean + * @return {Sprite} Sprite instance itself. + */ + public loadImage(key: string, clearAnimations?: bool): void; + /** + * Load a DynamicTexture as its texture. + * @param texture {DynamicTexture} The texture object to be used by this sprite. + * @return {Sprite} Sprite instance itself. + */ + public loadDynamicTexture(texture: DynamicTexture): void; + /** + * Getter only. The width of the texture. + * @type {number} + */ + public width : number; + /** + * Getter only. The height of the texture. + * @type {number} + */ + public height : number; + } +} +/** +* Phaser - Sprite +* +*/ +module Phaser { + class Sprite implements IGameObject { + /** + * Create a new Sprite. + * + * @param game {Phaser.Game} Current game instance. + * @param [x] {number} the initial x position of the sprite. + * @param [y] {number} the initial y position of the sprite. + * @param [key] {string} Key of the graphic you want to load for this sprite. + * @param [width] {number} The width of the object. + * @param [height] {number} The height of the object. + */ + constructor(game: Game, x?: number, y?: number, key?: string, width?: number, height?: number); + /** + * Reference to the main game object + */ + public game: Game; + /** + * The type of game object. + */ + public type: number; + /** + * Reference to the Renderer.renderSprite method. Can be overriden by custom classes. + */ + public render; + /** + * Controls if both update and render are called by the core game loop. + */ + public exists: bool; + /** + * Controls if update() is automatically called by the core game loop. + */ + public active: bool; + /** + * Controls if this Sprite is rendered or skipped during the core game loop. + */ + public visible: bool; + /** + * + */ + public alive: bool; + public width: number; + public height: number; + /** + * The position of the Sprite in world and screen coordinates. + */ + public position: Components.Position; + /** + * The texture used to render the Sprite. + */ + public texture: Components.Texture; + /** + * The frame boundary around this Sprite. + * For non-animated sprites this matches the loaded texture dimensions. + * For animated sprites it will be updated as part of the animation loop, changing to the dimensions of the current animation frame. + */ + public frameBounds: Rectangle; + /** + * Scale of the Sprite. A scale of 1.0 is the original size. 0.5 half size. 2.0 double sized. + */ + public scale: Vec2; + /** + * The influence of camera movement upon the Sprite. + */ + public scrollFactor: Vec2; + /** + * The Sprite origin is the point around which scale and rotation transforms take place. + */ + public origin: Vec2; + /** + * Pre-update is called right before update() on each object in the game loop. + */ + public preUpdate(): void; + /** + * Override this function to update your class's position and appearance. + */ + public update(): void; + /** + * Automatically called after update() by the game loop. + */ + public postUpdate(): void; + /** + * Clean up memory. + */ + public destroy(): void; + /** + * x value of the object. + */ + public x : number; + /** + * y value of the object. + */ + public y : number; + /** + * z value of the object. + */ + public z : number; + /** + * rotation value of the object. + */ + public rotation : number; + } +} +/** +* Phaser - CameraFX +* +* CameraFX controls all special effects applied to game Cameras. +*/ +module Phaser { + class CameraFX { + constructor(game: Game, parent); + /** + * The essential reference to the main game object. + */ + private _game; + /** + * A reference to the object that owns this FXManager instance. + */ + private _parent; + /** + * The array in which we keep all of the registered FX + */ + private _fx; + /** + * Holds the size of the _fx array + */ + private _length; + /** + * Controls whether any of the FX have preUpdate, update or postUpdate called + */ + public active: bool; + /** + * Controls whether any of the FX have preRender, render or postRender called + */ + public visible: bool; + /** + * Adds a new FX to the FXManager. + * The effect must be an object with at least one of the following methods: preUpdate, postUpdate, preRender, render or postRender. + * A new instance of the effect will be created and a reference to Game will be passed to the object constructor. + * @param {object} effect + * @return {any} + */ + public add(effect): any; + /** + * Pre-update is called at the start of the objects update cycle, before any other updates have taken place. + */ + public preUpdate(): void; + /** + * Post-update is called at the end of the objects update cycle, after other update logic has taken place. + */ + public postUpdate(): void; + /** + * Pre-render is called at the start of the object render cycle, before any transforms have taken place. + * It happens directly AFTER a canvas context.save has happened if added to a Camera. + * @param {Camera} camera + * @param {number} cameraX + * @param {number} cameraY + * @param {number} cameraWidth + * @param {number} cameraHeight + */ + public preRender(camera: Camera, cameraX: number, cameraY: number, cameraWidth: number, cameraHeight: number): void; + /** + * render is called during the objects render cycle, right after all transforms have finished, but before any children/image data is rendered. + * @param {Camera} camera + * @param {number} cameraX + * @param {number} cameraY + * @param {number} cameraWidth + * @param {number} cameraHeight + */ + public render(camera: Camera, cameraX: number, cameraY: number, cameraWidth: number, cameraHeight: number): void; + /** + * Post-render is called during the objects render cycle, after the children/image data has been rendered. + * It happens directly BEFORE a canvas context.restore has happened if added to a Camera. + */ + public postRender(camera: Camera, cameraX: number, cameraY: number, cameraWidth: number, cameraHeight: number): void; + /** + * Clear down this FXManager and null out references + */ + public destroy(): void; + } +} +/** +* Phaser - Camera +* +* A Camera is your view into the game world. It has a position, size, scale and rotation and renders only those objects +* within its field of view. The game automatically creates a single Stage sized camera on boot, but it can be changed and +* additional cameras created via the CameraManager. +*/ +module Phaser { + class Camera { + /** + * Instantiates a new camera at the specified location, with the specified size and zoom level. + * + * @param game {Phaser.Game} Current game instance. + * @param id {number} Unique identity. + * @param x {number} X location of the camera's display in pixels. Uses native, 1:1 resolution, ignores zoom. + * @param y {number} Y location of the camera's display in pixels. Uses native, 1:1 resolution, ignores zoom. + * @param width {number} The width of the camera display in pixels. + * @param height {number} The height of the camera display in pixels. + */ + constructor(game: Game, id: number, x: number, y: number, width: number, height: number); + /** + * Local private reference to Game. + */ + private _game; + private _clip; + private _stageX; + private _stageY; + private _rotation; + private _target; + public scaledX: number; + public scaledY: number; + /** + * Camera "follow" style preset: camera has no deadzone, just tracks the focus object directly. + * @type {number} + */ + static STYLE_LOCKON: number; + /** + * Camera "follow" style preset: camera deadzone is narrow but tall. + * @type {number} + */ + static STYLE_PLATFORMER: number; + /** + * Camera "follow" style preset: camera deadzone is a medium-size square around the focus object. + * @type {number} + */ + static STYLE_TOPDOWN: number; + /** + * Camera "follow" style preset: camera deadzone is a small square around the focus object. + * @type {number} + */ + static STYLE_TOPDOWN_TIGHT: number; + /** + * Identity of this camera. + */ + public ID: number; + /** + * Camera view rectangle in world coordinate. + * @type {Rectangle} + */ + public worldView: Rectangle; + /** + * Scale factor of the camera. + * @type {Vec2} + */ + public scale: Vec2; + /** + * Scrolling factor. + * @type {MicroPoint} + */ + public scroll: Vec2; + /** + * Camera bounds. + * @type {Rectangle} + */ + public bounds: Rectangle; + /** + * Sprite moving inside this rectangle will not cause camera moving. + * @type {Rectangle} + */ + public deadzone: Rectangle; + /** + * Disable the automatic camera canvas clipping when Camera is non-Stage sized. + * @type {Boolean} + */ + public disableClipping: bool; + /** + * Whether the camera background is opaque or not. If set to true the Camera is filled with + * the value of Camera.backgroundColor every frame. Normally you wouldn't enable this if the + * Camera is the full Stage size, as the Stage.backgroundColor has the same effect. But for + * multiple or mini cameras it can be very useful. + * @type {boolean} + */ + public opaque: bool; + /** + * The Background Color of the camera in css color string format, i.e. 'rgb(0,0,0)' or '#ff0000'. + * Not used if the Camera.opaque property is false. + * @type {string} + */ + public backgroundColor: string; + /** + * Whether this camera visible or not. (default is true) + * @type {boolean} + */ + public visible: bool; + /** + * Alpha of the camera. (everything rendered to this camera will be affected) + * @type {number} + */ + public alpha: number; + /** + * The x position of the current input event in world coordinates. + * @type {number} + */ + public inputX: number; + /** + * The y position of the current input event in world coordinates. + * @type {number} + */ + public inputY: number; + /** + * Effects manager. + * @type {CameraFX} + */ + public fx: CameraFX; + /** + * Hides an object from this Camera. Hidden objects are not rendered. + * The object must implement a public cameraBlacklist property. + * + * @param object {Sprite/Group} The object this camera should ignore. + */ + public hide(object): void; + /** + * Returns true if the object is hidden from this Camera. + * + * @param object {Sprite/Group} The object to check. + */ + public isHidden(object): bool; + /** + * Un-hides an object previously hidden to this Camera. + * The object must implement a public cameraBlacklist property. + * + * @param object {Sprite/Group} The object this camera should display. + */ + public show(object): void; + /** + * Tells this camera object what sprite to track. + * @param target {Sprite} The object you want the camera to track. Set to null to not follow anything. + * @param [style] {number} Leverage one of the existing "deadzone" presets. If you use a custom deadzone, ignore this parameter and manually specify the deadzone after calling follow(). + */ + public follow(target: Sprite, style?: number): void; + /** + * Move the camera focus to this location instantly. + * @param x {number} X position. + * @param y {number} Y position. + */ + public focusOnXY(x: number, y: number): void; + /** + * Move the camera focus to this location instantly. + * @param point {any} Point you want to focus. + */ + public focusOn(point): void; + /** + * Specify the boundaries of the world or where the camera is allowed to move. + * + * @param x {number} The smallest X value of your world (usually 0). + * @param y {number} The smallest Y value of your world (usually 0). + * @param width {number} The largest X value of your world (usually the world width). + * @param height {number} The largest Y value of your world (usually the world height). + */ + public setBounds(x?: number, y?: number, width?: number, height?: number): void; + /** + * Update focusing and scrolling. + */ + public update(): void; + /** + * Camera preRender + */ + public preRender(): void; + /** + * Camera postRender + */ + public postRender(): void; + /** + * Set position of this camera. + * @param x {number} X position. + * @param y {number} Y position. + */ + public setPosition(x: number, y: number): void; + /** + * Give this camera a new size. + * @param width {number} Width of new size. + * @param height {number} Height of new size. + */ + public setSize(width: number, height: number): void; + /** + * Render debug infos. (including id, position, rotation, scrolling factor, bounds and some other properties) + * @param x {number} X position of the debug info to be rendered. + * @param y {number} Y position of the debug info to be rendered. + * @param [color] {number} color of the debug info to be rendered. (format is css color string) + */ + public renderDebugInfo(x: number, y: number, color?: string): void; + /** + * Destroys this camera, associated FX and removes itself from the CameraManager. + */ + public destroy(): void; + public x : number; + public y : number; + public width : number; + public height : number; + public rotation : number; + private checkClip(); + } +} +/** +* Phaser - CameraManager +* +* Your game only has one CameraManager instance and it's responsible for looking after, creating and destroying +* all of the cameras in the world. +*/ +module Phaser { + class CameraManager { + /** + * CameraManager constructor + * This will create a new Camera with position and size. + * + * @param x {number} X Position of the created camera. + * @param y {number} y Position of the created camera. + * @param width {number} Width of the created camera. + * @param height {number} Height of the created camera. + */ + constructor(game: Game, x: number, y: number, width: number, height: number); + /** + * Local private reference to Game. + */ + private _game; + /** + * Local container for storing cameras. + */ + private _cameras; + /** + * Local helper stores index of next created camera. + */ + private _cameraInstance; + static CAMERA_TYPE_ORTHOGRAPHIC: number; + static CAMERA_TYPE_ISOMETRIC: number; + /** + * Currently used camera. + */ + public current: Camera; + /** + * Get all the cameras. + * + * @returns {Camera[]} An array contains all the cameras. + */ + public getAll(): Camera[]; + /** + * Update cameras. + */ + public update(): void; + /** + * Create a new camera with specific position and size. + * + * @param x {number} X position of the new camera. + * @param y {number} Y position of the new camera. + * @param width {number} Width of the new camera. + * @param height {number} Height of the new camera. + * @returns {Camera} The newly created camera object. + */ + public addCamera(x: number, y: number, width: number, height: number, type?: number): Camera; + /** + * Remove a new camera with its id. + * + * @param id {number} ID of the camera you want to remove. + * @returns {boolean} True if successfully removed the camera, otherwise return false. + */ + public removeCamera(id: number): bool; + /** + * Clean up memory. + */ + public destroy(): void; + } +} +/** +* Phaser - Easing - Back +* +* For use with Phaser.Tween +*/ +module Phaser.Easing { + class Back { + static In(k): number; + static Out(k): number; + static InOut(k): number; + } +} +/** +* Phaser - Easing - Bounce +* +* For use with Phaser.Tween +*/ +module Phaser.Easing { + class Bounce { + static In(k): number; + static Out(k): number; + static InOut(k): number; + } +} +/** +* Phaser - Easing - Circular +* +* For use with Phaser.Tween +*/ +module Phaser.Easing { + class Circular { + static In(k): number; + static Out(k): number; + static InOut(k): number; + } +} +/** +* Phaser - Easing - Cubic +* +* For use with Phaser.Tween +*/ +module Phaser.Easing { + class Cubic { + static In(k): number; + static Out(k): number; + static InOut(k): number; + } +} +/** +* Phaser - Easing - Elastic +* +* For use with Phaser.Tween +*/ +module Phaser.Easing { + class Elastic { + static In(k): number; + static Out(k): number; + static InOut(k): number; + } +} +/** +* Phaser - Easing - Exponential +* +* For use with Phaser.Tween +*/ +module Phaser.Easing { + class Exponential { + static In(k): number; + static Out(k): number; + static InOut(k): number; + } +} +/** +* Phaser - Easing - Linear +* +* For use with Phaser.Tween +*/ +module Phaser.Easing { + class Linear { + static None(k); + } +} +/** +* Phaser - Easing - Quadratic +* +* For use with Phaser.Tween +*/ +module Phaser.Easing { + class Quadratic { + static In(k): number; + static Out(k): number; + static InOut(k): number; + } +} +/** +* Phaser - Easing - Quartic +* +* For use with Phaser.Tween +*/ +module Phaser.Easing { + class Quartic { + static In(k): number; + static Out(k): number; + static InOut(k): number; + } +} +/** +* Phaser - Easing - Quintic +* +* For use with Phaser.Tween +*/ +module Phaser.Easing { + class Quintic { + static In(k): number; + static Out(k): number; + static InOut(k): number; + } +} +/** +* Phaser - Easing - Sinusoidal +* +* For use with Phaser.Tween +*/ +module Phaser.Easing { + class Sinusoidal { + static In(k): number; + static Out(k): number; + static InOut(k): number; + } +} +/** +* Phaser - Tween +* +* Based heavily on tween.js by sole (https://github.com/sole/tween.js) converted to TypeScript and integrated into Phaser +*/ +module Phaser { + class Tween { + /** + * Tween constructor + * Create a new Tween. + * + * @param object {object} Target object will be affected by this tween. + * @param game {Phaser.Game} Current game instance. + */ + constructor(object, game: Game); + /** + * Local private reference to game. + */ + private _game; + /** + * Manager of this tween. + * @type {Phaser.TweenManager} + */ + private _manager; + /** + * Reference to the target object. + * @type {object} + */ + private _object; + private _pausedTime; + /** + * Start values container. + * @type {object} + */ + private _valuesStart; + /** + * End values container. + * @type {object} + */ + private _valuesEnd; + /** + * How long this tween will perform. + * @type {number} + */ + private _duration; + private _delayTime; + private _startTime; + /** + * Easing function which actually updating this tween. + * @type {function} + */ + private _easingFunction; + private _interpolationFunction; + /** + * Contains chained tweens. + * @type {Tweens[]} + */ + private _chainedTweens; + /** + * Signal to be dispatched when this tween start. + * @type {Phaser.Signal} + */ + public onStart: Signal; + /** + * Signal to be dispatched when this tween updating. + * @type {Phaser.Signal} + */ + public onUpdate: Signal; + /** + * Signal to be dispatched when this tween completed. + * @type {Phaser.Signal} + */ + public onComplete: Signal; + /** + * Configure the Tween + * @param properties {object} Propertis you want to tween. + * @param [duration] {number} duration of this tween. + * @param [ease] {any} Easing function. + * @param [autoStart] {boolean} Whether this tween will start automatically or not. + * @param [delay] {number} delay before this tween will start, defaults to 0 (no delay) + * @return {Tween} Itself. + */ + public to(properties, duration?: number, ease?: any, autoStart?: bool, delay?: number): Tween; + /** + * Start to tween. + */ + public start(): Tween; + public clear(): Tween; + /** + * Stop tweening. + */ + public stop(): Tween; + public parent : Game; + public delay : number; + public easing : any; + public interpolation : any; + /** + * Add another chained tween, which will start automatically when the one before it completes. + * @param tween {Phaser.Tween} Tween object you want to chain with this. + * @return {Phaser.Tween} Itselfe. + */ + public chain(tween: Tween): Tween; + /** + * Debug value? + */ + public debugValue; + /** + * Update tweening. + * @param time {number} Current time from game clock. + * @return {boolean} Return false if this completed and no need to update, otherwise return true. + */ + public update(time): bool; + } +} +/** * Phaser - GameObjectFactory * * A quick way to create new world objects and add existing objects to the current world. @@ -4431,14 +2926,6 @@ module Phaser { */ public camera(x: number, y: number, width: number, height: number): Camera; /** - * Create a new GeomSprite with specific position. - * - * @param x {number} X position of the new geom sprite. - * @param y {number} Y position of the new geom sprite. - * @returns {GeomSprite} The newly created geom sprite object. - */ - public geomSprite(x: number, y: number): GeomSprite; - /** * Create a new Sprite with specific position and sprite sheet key. * * @param x {number} X position of the new sprite. @@ -4463,44 +2950,6 @@ module Phaser { */ public group(maxSize?: number): Group; /** - * Create a new Particle. - * - * @return {Particle} The newly created particle object. - */ - public particle(): Particle; - /** - * Create a new Emitter. - * - * @param x {number} Optional, x position of the emitter. - * @param y {number} Optional, y position of the emitter. - * @param size {number} Optional, size of this emitter. - * @return {Emitter} The newly created emitter object. - */ - public emitter(x?: number, y?: number, size?: number): Emitter; - /** - * Create a new ScrollZone object with image key, position and size. - * - * @param key {string} Key to a image you wish this object to use. - * @param x {number} X position of this object. - * @param y {number} Y position of this object. - * @param width number} Width of this object. - * @param height {number} Height of this object. - * @returns {ScrollZone} The newly created scroll zone object. - */ - public scrollZone(key: string, x?: number, y?: number, width?: number, height?: number): ScrollZone; - /** - * Create a new Tilemap. - * - * @param key {string} Key for tileset image. - * @param mapData {string} Data of this tilemap. - * @param format {number} Format of map data. (Tilemap.FORMAT_CSV or Tilemap.FORMAT_TILED_JSON) - * @param [resizeWorld] {boolean} resize the world to make same as tilemap? - * @param [tileWidth] {number} width of each tile. - * @param [tileHeight] {number} height of each tile. - * @return {Tilemap} The newly created tilemap object. - */ - public tilemap(key: string, mapData: string, format: number, resizeWorld?: bool, tileWidth?: number, tileHeight?: number): Tilemap; - /** * Create a tween object for a specific object. * * @param obj Object you wish the tween will affect. @@ -4516,38 +2965,6 @@ module Phaser { */ public existingSprite(sprite: Sprite): Sprite; /** - * Add an existing GeomSprite to the current world. - * Note: This doesn't check or update the objects reference to Game. If that is wrong, all kinds of things will break. - * - * @param sprite The GeomSprite to add to the Game World - * @return {Phaser.GeomSprite} The GeomSprite object - */ - public existingGeomSprite(sprite: GeomSprite): GeomSprite; - /** - * Add an existing Emitter to the current world. - * Note: This doesn't check or update the objects reference to Game. If that is wrong, all kinds of things will break. - * - * @param emitter The Emitter to add to the Game World - * @return {Phaser.Emitter} The Emitter object - */ - public existingEmitter(emitter: Emitter): Emitter; - /** - * Add an existing ScrollZone to the current world. - * Note: This doesn't check or update the objects reference to Game. If that is wrong, all kinds of things will break. - * - * @param scrollZone The ScrollZone to add to the Game World - * @return {Phaser.ScrollZone} The ScrollZone object - */ - public existingScrollZone(scrollZone: ScrollZone): ScrollZone; - /** - * Add an existing Tilemap to the current world. - * Note: This doesn't check or update the objects reference to Game. If that is wrong, all kinds of things will break. - * - * @param tilemap The Tilemap to add to the Game World - * @return {Phaser.Tilemap} The Tilemap object - */ - public existingTilemap(tilemap: Tilemap): Tilemap; - /** * Add an existing Tween to the current world. * Note: This doesn't check or update the objects reference to Game. If that is wrong, all kinds of things will break. * @@ -4557,14 +2974,37 @@ module Phaser { public existingTween(tween: Tween): Tween; } } +module Phaser { + /** + * Constants used to define game object types (faster than doing typeof object checks in core loops) + */ + class Types { + static RENDERER_AUTO_DETECT: number; + static RENDERER_HEADLESS: number; + static RENDERER_CANVAS: number; + static RENDERER_WEBGL: number; + static GROUP: number; + static SPRITE: number; + static GEOMSPRITE: number; + static PARTICLE: number; + static EMITTER: number; + static TILEMAP: number; + static SCROLLZONE: number; + static GEOM_POINT: number; + static GEOM_CIRCLE: number; + static GEOM_RECTANGLE: number; + static GEOM_LINE: number; + static GEOM_POLYGON: number; + } +} /** * Phaser - Group * * This class is used for organising, updating and sorting game objects. */ module Phaser { - class Group extends Basic { - constructor(game: Game, MaxSize?: number); + class Group { + constructor(game: Game, maxSize?: number); /** * Internal tracker for the maximum capacity of the group. * Default is 0, or no max capacity. @@ -4583,6 +3023,30 @@ module Phaser { */ private _sortOrder; /** + * Temp vars to help avoid gc spikes + */ + private _member; + private _length; + private _i; + private _prevAlpha; + private _count; + /** + * Reference to the main game object + */ + public game: Game; + /** + * The type of game object. + */ + public type: number; + /** + * If this Group exists or not. Can be set to false to skip certain loop checks. + */ + public exists: bool; + /** + * Controls if this Group (and all of its contents) are rendered or skipped during the core game loop. + */ + public visible: bool; + /** * Use with sort() to sort in ascending order. */ static ASCENDING: number; @@ -4591,9 +3055,9 @@ module Phaser { */ static DESCENDING: number; /** - * Array of all the Basics that exist in this group. + * Array of all the objects that exist in this group. */ - public members: Basic[]; + public members; /** * The number of entries in the members array. * For performance and safety you should check this variable @@ -4619,34 +3083,20 @@ module Phaser { */ public cameraBlacklist: number[]; /** - * If you do not wish this object to be visible to a specific camera, pass the camera here. - * - * @param camera {Camera} The specific camera. - */ - public hideFromCamera(camera: Camera): void; - /** - * Make this object only visible to a specific camera. - * - * @param camera {Camera} The camera you wish it to be visible. - */ - public showToCamera(camera: Camera): void; - /** - * This clears the camera black list, making the GameObject visible to all cameras. - */ - public clearCameraList(): void; - /** * Override this function to handle any deleting or "shutdown" type operations you might need, * such as removing traditional Flash children like Basic objects. */ public destroy(): void; /** - * Automatically goes through and calls update on everything you added. + * Calls update on all members of this Group who have a status of active=true and exists=true + * You can also call Object.update directly, which will bypass the active/exists check. */ public update(forceUpdate?: bool): void; /** - * Automatically goes through and calls render on everything you added. + * Calls render on all members of this Group who have a status of visible=true and exists=true + * You can also call Object.render directly, which will bypass the visible/exists check. */ - public render(camera: Camera, cameraOffsetX: number, cameraOffsetY: number, forceRender?: bool): void; + public render(camera: Camera): void; /** * The maximum capacity of this group. Default is 0, meaning no max capacity, and the group can just grow. */ @@ -4666,7 +3116,7 @@ module Phaser { * @param {Basic} Object The object you want to add to the group. * @return {Basic} The same Basic object that was passed in. */ - public add(Object: Basic): any; + public add(object): any; /** * Recycling is designed to help you reuse game objects without always re-allocating or "newing" them. * @@ -4690,7 +3140,7 @@ module Phaser { * * @return {any} A reference to the object that was created. Don't forget to cast it back to the Class you want (e.g. myObject = myGroup.recycle(myObjectClass) as myObjectClass;). */ - public recycle(ObjectClass?); + public recycle(objectClass?); /** * Removes an object from the group. * @@ -4699,7 +3149,7 @@ module Phaser { * * @return {Basic} The removed object. */ - public remove(object: Basic, splice?: bool): Basic; + public remove(object, splice?: bool); /** * Replaces an existing Basic with a new one. * @@ -4708,7 +3158,7 @@ module Phaser { * * @return {Basic} The new object. */ - public replace(oldObject: Basic, newObject: Basic): Basic; + public replace(oldObject, newObject); /** * Call this function to sort the group according to a particular value and order. * For example, to sort game objects for Zelda-style overlaps you might call @@ -4727,7 +3177,7 @@ module Phaser { * @param {Object} Value The value you want to assign to that variable. * @param {boolean} Recurse Default value is true, meaning if setAll() encounters a member that is a group, it will call setAll() on that group rather than modifying its variable. */ - public setAll(VariableName: string, Value: Object, Recurse?: bool): void; + public setAll(variableName: string, value: Object, recurse?: bool): void; /** * Go through and call the specified function on all members of the group. * Currently only works on functions that have no required parameters. @@ -4735,7 +3185,7 @@ module Phaser { * @param {string} FunctionName The string representation of the function you want to call on each object, for example "kill()" or "init()". * @param {boolean} Recurse Default value is true, meaning if callAll() encounters a member that is a group, it will call callAll() on that group rather than calling the group's function. */ - public callAll(FunctionName: string, Recurse?: bool): void; + public callAll(functionName: string, recurse?: bool): void; /** * @param {function} callback * @param {boolean} recursive @@ -4755,7 +3205,7 @@ module Phaser { * * @return {any} A Basic currently flagged as not existing. */ - public getFirstAvailable(ObjectClass?); + public getFirstAvailable(objectClass?); /** * Call this function to retrieve the first index set to 'null'. * Returns -1 if no index stores a null object. @@ -4769,21 +3219,21 @@ module Phaser { * * @return {Basic} A Basic currently flagged as existing. */ - public getFirstExtant(): Basic; + public getFirstExtant(); /** * Call this function to retrieve the first object with dead == false in the group. * This is handy for checking if everything's wiped out, or choosing a squad leader, etc. * * @return {Basic} A Basic currently flagged as not dead. */ - public getFirstAlive(): Basic; + public getFirstAlive(); /** * Call this function to retrieve the first object with dead == true in the group. * This is handy for checking if everything's wiped out, or choosing a squad leader, etc. * * @return {Basic} A Basic currently flagged as dead. */ - public getFirstDead(): Basic; + public getFirstDead(); /** * Call this function to find out how many members of the group are not dead. * @@ -4804,7 +3254,7 @@ module Phaser { * * @return {Basic} A Basic from the members list. */ - public getRandom(StartIndex?: number, Length?: number): Basic; + public getRandom(startIndex?: number, length?: number); /** * Remove all instances of Basic subclass (Basic, Block, etc) from the list. * WARNING: does not destroy() or kill() any of these objects! @@ -4822,334 +3272,257 @@ module Phaser { * * @return {number} An integer value: -1 (Obj1 before Obj2), 0 (same), or 1 (Obj1 after Obj2). */ - public sortHandler(Obj1: Basic, Obj2: Basic): number; + public sortHandler(obj1, obj2): number; } } /** -* Phaser - Loader +* Phaser - SignalBinding * -* The Loader handles loading all external content such as Images, Sounds, Texture Atlases and data files. -* It uses a combination of Image() loading and xhr and provides for progress and completion callbacks. +* An object that represents a binding between a Signal and a listener function. +* Based on JS Signals by Miller Medeiros. Converted by TypeScript by Richard Davey. +* Released under the MIT license +* http://millermedeiros.github.com/js-signals/ */ module Phaser { - class Loader { + class SignalBinding { + /** + * Object that represents a binding between a Signal and a listener function. + *
- This is an internal constructor and shouldn't be called by regular users. + *
- inspired by Joa Ebert AS3 SignalBinding and Robert Penner's Slot classes. + * @author Miller Medeiros + * @constructor + * @internal + * @name SignalBinding + * @param {Signal} signal Reference to Signal object that listener is currently bound to. + * @param {Function} listener Handler function bound to the signal. + * @param {boolean} isOnce If binding should be executed just once. + * @param {Object} [listenerContext] Context on which listener will be executed (object that should represent the `this` variable inside listener function). + * @param {Number} [priority] The priority level of the event listener. (default = 0). + */ + constructor(signal: Signal, listener, isOnce: bool, listenerContext, priority?: number); + /** + * Handler function bound to the signal. + * @type Function + * @private + */ + private _listener; + /** + * If binding should be executed just once. + * @type boolean + * @private + */ + private _isOnce; + /** + * Context on which listener will be executed (object that should represent the `this` variable inside listener function). + * @memberOf SignalBinding.prototype + * @name context + * @type Object|undefined|null + */ + public context; + /** + * Reference to Signal object that listener is currently bound to. + * @type Signal + * @private + */ + private _signal; + /** + * Listener priority + * @type Number + */ + public priority: number; + /** + * If binding is active and should be executed. + * @type boolean + */ + public active: bool; + /** + * Default parameters passed to listener during `Signal.dispatch` and `SignalBinding.execute`. (curried parameters) + * @type Array|null + */ + public params; + /** + * Call listener passing arbitrary parameters. + *

If binding was added using `Signal.addOnce()` it will be automatically removed from signal dispatch queue, this method is used internally for the signal dispatch.

+ * @param {Array} [paramsArr] Array of parameters that should be passed to the listener + * @return {*} Value returned by the listener. + */ + public execute(paramsArr?: any[]); + /** + * Detach binding from signal. + * - alias to: mySignal.remove(myBinding.getListener()); + * @return {Function|null} Handler function bound to the signal or `null` if binding was previously detached. + */ + public detach(); + /** + * @return {Boolean} `true` if binding is still bound to the signal and have a listener. + */ + public isBound(): bool; + /** + * @return {boolean} If SignalBinding will only be executed once. + */ + public isOnce(): bool; + /** + * @return {Function} Handler function bound to the signal. + */ + public getListener(); + /** + * @return {Signal} Signal that listener is currently bound to. + */ + public getSignal(): Signal; + /** + * Delete instance properties + * @private + */ + public _destroy(): void; + /** + * @return {string} String representation of the object. + */ + public toString(): string; + } +} +/** +* Phaser - Signal +* +* A Signal is used for object communication via a custom broadcaster instead of Events. +* Based on JS Signals by Miller Medeiros. Converted by TypeScript by Richard Davey. +* Released under the MIT license +* http://millermedeiros.github.com/js-signals/ +*/ +module Phaser { + class Signal { /** - * Loader constructor * - * @param game {Phaser.Game} Current game instance. - * @param callback {function} This will be called when assets completely loaded. + * @property _bindings + * @type Array + * @private */ - constructor(game: Game, callback); + private _bindings; /** - * Local private reference to game. + * + * @property _prevParams + * @type Any + * @private */ - private _game; + private _prevParams; /** - * Array stors assets keys. So you can get that asset by its unique key. + * Signals Version Number + * @property VERSION + * @type String + * @const */ - private _keys; + static VERSION: string; /** - * Contains all the assets file infos. + * If Signal should keep record of previously dispatched parameters and + * automatically execute listener during `add()`/`addOnce()` if Signal was + * already dispatched before. + * @type boolean */ - private _fileList; + public memorize: bool; /** - * Game initialial assets loading callback. + * @type boolean + * @private */ - private _gameCreateComplete; - private _onComplete; - private _onFileLoad; + private _shouldPropagate; /** - * Indicates assets loading progress. (from 0 to 100) - * @type {number} + * If Signal is active and should broadcast events. + *

IMPORTANT: Setting this property during a dispatch will only affect the next dispatch, if you want to stop the propagation of a signal use `halt()` instead.

+ * @type boolean */ - private _progressChunk; - private _xhr; + public active: bool; /** - * Length of assets queue. - * @type {number} + * + * @method validateListener + * @param {Any} listener + * @param {Any} fnName */ - private _queueSize; + public validateListener(listener, fnName): void; /** - * True if game is completely loaded. - * @type {boolean} + * @param {Function} listener + * @param {boolean} isOnce + * @param {Object} [listenerContext] + * @param {Number} [priority] + * @return {SignalBinding} + * @private */ - public hasLoaded: bool; + private _registerListener(listener, isOnce, listenerContext, priority); /** - * Loading progress (from 0 to 1) - * @type {number} + * + * @method _addBinding + * @param {SignalBinding} binding + * @private */ - public progress: number; + private _addBinding(binding); /** - * The crossOrigin value applied to loaded images - * @type {string} + * + * @method _indexOfListener + * @param {Function} listener + * @return {number} + * @private */ - public crossOrigin: string; + private _indexOfListener(listener, context); /** - * TextureAtlas data format constants + * Check if listener was attached to Signal. + * @param {Function} listener + * @param {Object} [context] + * @return {boolean} if Signal has the specified listener. */ - static TEXTURE_ATLAS_JSON_ARRAY: number; - static TEXTURE_ATLAS_JSON_HASH: number; - static TEXTURE_ATLAS_XML_STARLING: number; + public has(listener, context?: any): bool; /** - * Reset loader, this will remove all loaded assets. + * Add a listener to the signal. + * @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 {SignalBinding} An Object representing the binding between the Signal and listener. */ - public reset(): void; - public queueSize : number; + public add(listener, listenerContext?: any, priority?: number): SignalBinding; /** - * Add a new image asset loading request with key and url. - * @param key {string} Unique asset key of this image file. - * @param url {string} URL of image file. + * Add listener to the signal that should be removed after first execution (will be executed only once). + * @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 {SignalBinding} An Object representing the binding between the Signal and listener. */ - public addImageFile(key: string, url: string): void; + public addOnce(listener, listenerContext?: any, priority?: number): SignalBinding; /** - * Add a new sprite sheet loading request. - * @param key {string} Unique asset key of the sheet file. - * @param url {string} URL of sheet file. - * @param frameWidth {number} Width of each single frame. - * @param frameHeight {number} Height of each single frame. - * @param frameMax {number} How many frames in this sprite sheet. + * Remove a single listener from the dispatch queue. + * @param {Function} listener Handler function that should be removed. + * @param {Object} [context] Execution context (since you can add the same handler multiple times if executing in a different context). + * @return {Function} Listener handler function. */ - public addSpriteSheet(key: string, url: string, frameWidth: number, frameHeight: number, frameMax?: number): void; + public remove(listener, context?: any); /** - * Add a new texture atlas loading request. - * @param key {string} Unique asset key of the texture atlas file. - * @param textureURL {string} The url of the texture atlas image file. - * @param [atlasURL] {string} The url of the texture atlas data file (json/xml) - * @param [atlasData] {object} A JSON or XML data object. - * @param [format] {number} A value describing the format of the data. - */ - public addTextureAtlas(key: string, textureURL: string, atlasURL?: string, atlasData?, format?: number): void; - /** - * Add a new audio file loading request. - * @param key {string} Unique asset key of the audio file. - * @param url {string} URL of audio file. - */ - public addAudioFile(key: string, url: string): void; - /** - * Add a new text file loading request. - * @param key {string} Unique asset key of the text file. - * @param url {string} URL of text file. - */ - public addTextFile(key: string, url: string): void; - /** - * Remove loading request of a file. - * @param key {string} Key of the file you want to remove. - */ - public removeFile(key: string): void; - /** - * Remove all file loading requests. + * Remove all listeners from the Signal. */ public removeAll(): void; /** - * Load assets. - * @param onFileLoadCallback {function} Called when each file loaded successfully. - * @param onCompleteCallback {function} Called when all assets completely loaded. + * @return {number} Number of listeners attached to the Signal. */ - public load(onFileLoadCallback?, onCompleteCallback?): void; + public getNumListeners(): number; /** - * Load files. Private method ONLY used by loader. + * Stop propagation of the event, blocking the dispatch to next listeners on the queue. + *

IMPORTANT: should be called only during signal dispatch, calling it before/after dispatch won't affect signal broadcast.

+ * @see Signal.prototype.disable */ - private loadFile(); + public halt(): void; /** - * Error occured when load a file. - * @param key {string} Key of the error loading file. + * Dispatch/Broadcast Signal to all listeners added to the queue. + * @param {...*} [params] Parameters that should be passed to each handler. */ - private fileError(key); + public dispatch(...paramsArr: any[]): void; /** - * Called when a file is successfully loaded. - * @param key {string} Key of the successfully loaded file. + * Forget memorized arguments. + * @see Signal.memorize */ - private fileComplete(key); + public forget(): void; /** - * Successfully loaded a JSON file. - * @param key {string} Key of the loaded JSON file. + * Remove all bindings from signal and destroy any reference to external objects (destroy Signal object). + *

IMPORTANT: calling any method on the signal instance after calling dispose will throw errors.

*/ - private jsonLoadComplete(key); + public dispose(): void; /** - * Error occured when load a JSON. - * @param key {string} Key of the error loading JSON file. + * @return {string} String representation of the object. */ - private dataLoadError(key); - private xmlLoadComplete(key); - /** - * 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(previousKey, success); - /** - * Check whether asset exists with a specific key. - * @param key {string} Key of the asset you want to check. - * @return {boolean} Return true if exists, otherwise return false. - */ - private checkKeyExists(key); - } -} -/** -* Phaser - Motion -* -* The Motion class contains lots of useful functions for moving game objects around in world space. -*/ -module Phaser { - class Motion { - constructor(game: Game); - private _game; - /** - * A tween-like function that takes a starting velocity and some other factors and returns an altered velocity. - * - * @param {number} Velocity Any component of velocity (e.g. 20). - * @param {number} Acceleration Rate at which the velocity is changing. - * @param {number} Drag Really kind of a deceleration, this is how much the velocity changes if Acceleration is not set. - * @param {number} Max An absolute value cap for the velocity. - * - * @return {number} The altered Velocity value. - */ - public computeVelocity(Velocity: number, Acceleration?: number, Drag?: number, Max?: number): number; - /** - * Given the angle and speed calculate the velocity and return it as a Point - * - * @param {number} angle The angle (in degrees) calculated in clockwise positive direction (down = 90 degrees positive, right = 0 degrees positive, up = 90 degrees negative) - * @param {number} speed The speed it will move, in pixels per second sq - * - * @return {Point} A Point where Point.x contains the velocity x value and Point.y contains the velocity y value - */ - public velocityFromAngle(angle: number, speed: number): Point; - /** - * Sets the source Sprite x/y velocity so it will move directly towards the destination Sprite at the speed given (in pixels per second)
- * If you specify a maxTime then it will adjust the speed (over-writing what you set) so it arrives at the destination in that number of seconds.
- * Timings are approximate due to the way Flash timers work, and irrespective of SWF frame rate. Allow for a variance of +- 50ms.
- * The source object doesn't stop moving automatically should it ever reach the destination coordinates.
- * If you need the object to accelerate, see accelerateTowardsObject() instead - * Note: Doesn't take into account acceleration, maxVelocity or drag (if you set drag or acceleration too high this object may not move at all) - * - * @param {GameObject} source The Sprite on which the velocity will be set - * @param {GameObject} dest The Sprite where the source object will move to - * @param {number} speed The speed it will move, in pixels per second (default is 60 pixels/sec) - * @param {number} maxTime Time given in milliseconds (1000 = 1 sec). If set the speed is adjusted so the source will arrive at destination in the given number of ms - */ - public moveTowardsObject(source: GameObject, dest: GameObject, speed?: number, maxTime?: number): void; - /** - * Sets the x/y acceleration on the source Sprite so it will move towards the destination Sprite at the speed given (in pixels per second)
- * You must give a maximum speed value, beyond which the Sprite won't go any faster.
- * If you don't need acceleration look at moveTowardsObject() instead. - * - * @param {GameObject} source The Sprite on which the acceleration will be set - * @param {GameObject} dest The Sprite where the source object will move towards - * @param {number} speed The speed it will accelerate in pixels per second - * @param {number} xSpeedMax The maximum speed in pixels per second in which the sprite can move horizontally - * @param {number} ySpeedMax The maximum speed in pixels per second in which the sprite can move vertically - */ - public accelerateTowardsObject(source: GameObject, dest: GameObject, speed: number, xSpeedMax: number, ySpeedMax: number): void; - /** - * Move the given Sprite towards the mouse pointer coordinates at a steady velocity - * If you specify a maxTime then it will adjust the speed (over-writing what you set) so it arrives at the destination in that number of seconds.
- * Timings are approximate due to the way Flash timers work, and irrespective of SWF frame rate. Allow for a variance of +- 50ms.
- * The source object doesn't stop moving automatically should it ever reach the destination coordinates.
- * - * @param {GameObject} source The Sprite to move - * @param {number} speed The speed it will move, in pixels per second (default is 60 pixels/sec) - * @param {number} maxTime Time given in milliseconds (1000 = 1 sec). If set the speed is adjusted so the source will arrive at destination in the given number of ms - */ - public moveTowardsMouse(source: GameObject, speed?: number, maxTime?: number): void; - /** - * Sets the x/y acceleration on the source Sprite so it will move towards the mouse coordinates at the speed given (in pixels per second)
- * You must give a maximum speed value, beyond which the Sprite won't go any faster.
- * If you don't need acceleration look at moveTowardsMouse() instead. - * - * @param {GameObject} source The Sprite on which the acceleration will be set - * @param {number} speed The speed it will accelerate in pixels per second - * @param {number} xSpeedMax The maximum speed in pixels per second in which the sprite can move horizontally - * @param {number} ySpeedMax The maximum speed in pixels per second in which the sprite can move vertically - */ - public accelerateTowardsMouse(source: GameObject, speed: number, xSpeedMax: number, ySpeedMax: number): void; - /** - * Sets the x/y velocity on the source Sprite so it will move towards the target coordinates at the speed given (in pixels per second)
- * If you specify a maxTime then it will adjust the speed (over-writing what you set) so it arrives at the destination in that number of seconds.
- * Timings are approximate due to the way Flash timers work, and irrespective of SWF frame rate. Allow for a variance of +- 50ms.
- * The source object doesn't stop moving automatically should it ever reach the destination coordinates.
- * - * @param {GameObject} source The Sprite to move - * @param {Point} target The Point coordinates to move the source Sprite towards - * @param {number} speed The speed it will move, in pixels per second (default is 60 pixels/sec) - * @param {number} maxTime Time given in milliseconds (1000 = 1 sec). If set the speed is adjusted so the source will arrive at destination in the given number of ms - */ - public moveTowardsPoint(source: GameObject, target: Point, speed?: number, maxTime?: number): void; - /** - * Sets the x/y acceleration on the source Sprite so it will move towards the target coordinates at the speed given (in pixels per second)
- * You must give a maximum speed value, beyond which the Sprite won't go any faster.
- * If you don't need acceleration look at moveTowardsPoint() instead. - * - * @param {GameObject} source The Sprite on which the acceleration will be set - * @param {Point} target The Point coordinates to move the source Sprite towards - * @param {number} speed The speed it will accelerate in pixels per second - * @param {number} xSpeedMax The maximum speed in pixels per second in which the sprite can move horizontally - * @param {number} ySpeedMax The maximum speed in pixels per second in which the sprite can move vertically - */ - public accelerateTowardsPoint(source: GameObject, target: Point, speed: number, xSpeedMax: number, ySpeedMax: number): void; - /** - * Find the distance (in pixels, rounded) between two Sprites, taking their origin into account - * - * @param {GameObject} a The first Sprite - * @param {GameObject} b The second Sprite - * @return {number} int Distance (in pixels) - */ - public distanceBetween(a: GameObject, b: GameObject): number; - /** - * Find the distance (in pixels, rounded) from an Sprite to the given Point, taking the source origin into account - * - * @param {GameObject} a The Sprite - * @param {Point} target The Point - * @return {number} Distance (in pixels) - */ - public distanceToPoint(a: GameObject, target: Point): number; - /** - * Find the distance (in pixels, rounded) from the object x/y and the mouse x/y - * - * @param {GameObject} a Sprite to test against - * @return {number} The distance between the given sprite and the mouse coordinates - */ - public distanceToMouse(a: GameObject): number; - /** - * Find the angle (in radians) between an Sprite and an Point. The source sprite takes its x/y and origin into account. - * The angle is calculated in clockwise positive direction (down = 90 degrees positive, right = 0 degrees positive, up = 90 degrees negative) - * - * @param {GameObject} a The Sprite to test from - * @param {Point} target The Point to angle the Sprite towards - * @param {boolean} asDegrees If you need the value in degrees instead of radians, set to true - * - * @return {number} The angle (in radians unless asDegrees is true) - */ - public angleBetweenPoint(a: GameObject, target: Point, asDegrees?: bool): number; - /** - * Find the angle (in radians) between the two Sprite, taking their x/y and origin into account. - * The angle is calculated in clockwise positive direction (down = 90 degrees positive, right = 0 degrees positive, up = 90 degrees negative) - * - * @param {GameObject} a The Sprite to test from - * @param {GameObject} b The Sprite to test to - * @param {boolean} asDegrees If you need the value in degrees instead of radians, set to true - * - * @return {number} The angle (in radians unless asDegrees is true) - */ - public angleBetween(a: GameObject, b: GameObject, asDegrees?: bool): number; - /** - * Given the GameObject and speed calculate the velocity and return it as an Point based on the direction the sprite is facing - * - * @param {GameObject} parent The Sprite to get the facing value from - * @param {number} speed The speed it will move, in pixels per second sq - * - * @return {Point} An Point where Point.x contains the velocity x value and Point.y contains the velocity y value - */ - public velocityFromFacing(parent: GameObject, speed: number): Point; - /** - * Find the angle (in radians) between an Sprite and the mouse, taking their x/y and origin into account. - * The angle is calculated in clockwise positive direction (down = 90 degrees positive, right = 0 degrees positive, up = 90 degrees negative) - * - * @param {GameObject} a The Object to test from - * @param {boolean} asDegrees If you need the value in degrees instead of radians, set to true - * - * @return {number} The angle (in radians unless asDegrees is true) - */ - public angleBetweenMouse(a: GameObject, asDegrees?: bool): number; + public toString(): string; } } /** @@ -5274,13 +3647,14 @@ module Phaser { /** * Phaser * -* v0.9.6 - May 21st 2013 +* v1.0.0 - June XX 2013 * * A small and feature-packed 2D canvas game framework born from the firey pits of Flixel and Kiwi. * * Richard Davey (@photonstorm) * -* Many thanks to Adam Saltsman (@ADAMATOMIC) for releasing Flixel on which Phaser took a lot of inspiration. +* Many thanks to Adam Saltsman (@ADAMATOMIC) for releasing Flixel, from both which Phaser +* and my love of game development took a lot of inspiration. * * "If you want your children to be intelligent, read them fairy tales." * "If you want them to be more intelligent, read them more fairy tales." @@ -5559,9 +3933,9 @@ module Phaser { private _pauseScreen; /** * Bound of this stage. - * @type {Quad} + * @type {Rectangle} */ - public bounds: Quad; + public bounds: Rectangle; /** * Asperct ratio, thus: width / height. * @type {number} @@ -5598,7 +3972,7 @@ module Phaser { * Offset from this stage to the canvas element. * @type {MicroPoint} */ - public offset: MicroPoint; + public offset: Point; /** * This object manages scaling of the game, see(StageScaleMode). * @type {StageScaleMode} @@ -5781,249 +4155,6 @@ module Phaser { } } /** -* Phaser - Easing - Back -* -* For use with Phaser.Tween -*/ -module Phaser.Easing { - class Back { - static In(k): number; - static Out(k): number; - static InOut(k): number; - } -} -/** -* Phaser - Easing - Bounce -* -* For use with Phaser.Tween -*/ -module Phaser.Easing { - class Bounce { - static In(k): number; - static Out(k): number; - static InOut(k): number; - } -} -/** -* Phaser - Easing - Circular -* -* For use with Phaser.Tween -*/ -module Phaser.Easing { - class Circular { - static In(k): number; - static Out(k): number; - static InOut(k): number; - } -} -/** -* Phaser - Easing - Cubic -* -* For use with Phaser.Tween -*/ -module Phaser.Easing { - class Cubic { - static In(k): number; - static Out(k): number; - static InOut(k): number; - } -} -/** -* Phaser - Easing - Elastic -* -* For use with Phaser.Tween -*/ -module Phaser.Easing { - class Elastic { - static In(k): number; - static Out(k): number; - static InOut(k): number; - } -} -/** -* Phaser - Easing - Exponential -* -* For use with Phaser.Tween -*/ -module Phaser.Easing { - class Exponential { - static In(k): number; - static Out(k): number; - static InOut(k): number; - } -} -/** -* Phaser - Easing - Linear -* -* For use with Phaser.Tween -*/ -module Phaser.Easing { - class Linear { - static None(k); - } -} -/** -* Phaser - Easing - Quadratic -* -* For use with Phaser.Tween -*/ -module Phaser.Easing { - class Quadratic { - static In(k): number; - static Out(k): number; - static InOut(k): number; - } -} -/** -* Phaser - Easing - Quartic -* -* For use with Phaser.Tween -*/ -module Phaser.Easing { - class Quartic { - static In(k): number; - static Out(k): number; - static InOut(k): number; - } -} -/** -* Phaser - Easing - Quintic -* -* For use with Phaser.Tween -*/ -module Phaser.Easing { - class Quintic { - static In(k): number; - static Out(k): number; - static InOut(k): number; - } -} -/** -* Phaser - Easing - Sinusoidal -* -* For use with Phaser.Tween -*/ -module Phaser.Easing { - class Sinusoidal { - static In(k): number; - static Out(k): number; - static InOut(k): number; - } -} -/** -* Phaser - Tween -* -* Based heavily on tween.js by sole (https://github.com/sole/tween.js) converted to TypeScript and integrated into Phaser -*/ -module Phaser { - class Tween { - /** - * Tween constructor - * Create a new Tween. - * - * @param object {object} Target object will be affected by this tween. - * @param game {Phaser.Game} Current game instance. - */ - constructor(object, game: Game); - /** - * Local private reference to game. - */ - private _game; - /** - * Manager of this tween. - * @type {Phaser.TweenManager} - */ - private _manager; - /** - * Reference to the target object. - * @type {object} - */ - private _object; - private _pausedTime; - /** - * Start values container. - * @type {object} - */ - private _valuesStart; - /** - * End values container. - * @type {object} - */ - private _valuesEnd; - /** - * How long this tween will perform. - * @type {number} - */ - private _duration; - private _delayTime; - private _startTime; - /** - * Easing function which actually updating this tween. - * @type {function} - */ - private _easingFunction; - private _interpolationFunction; - /** - * Contains chained tweens. - * @type {Tweens[]} - */ - private _chainedTweens; - /** - * Signal to be dispatched when this tween start. - * @type {Phaser.Signal} - */ - public onStart: Signal; - /** - * Signal to be dispatched when this tween updating. - * @type {Phaser.Signal} - */ - public onUpdate: Signal; - /** - * Signal to be dispatched when this tween completed. - * @type {Phaser.Signal} - */ - public onComplete: Signal; - /** - * Configure the Tween - * @param properties {object} Propertis you want to tween. - * @param [duration] {number} duration of this tween. - * @param [ease] {any} Easing function. - * @param [autoStart] {boolean} Whether this tween will start automatically or not. - * @param [delay] {number} delay before this tween will start, defaults to 0 (no delay) - * @return {Tween} Itself. - */ - public to(properties, duration?: number, ease?: any, autoStart?: bool, delay?: number): Tween; - /** - * Start to tween. - */ - public start(): Tween; - /** - * Stop tweening. - */ - public stop(): Tween; - public parent : Game; - public delay : number; - public easing : any; - public interpolation : any; - /** - * Add another chained tween, which will start automatically when the one before it completes. - * @param tween {Phaser.Tween} Tween object you want to chain with this. - * @return {Phaser.Tween} Itselfe. - */ - public chain(tween: Tween): Tween; - /** - * Debug value? - */ - public debugValue; - /** - * Update tweening. - * @param time {number} Current time from game clock. - * @return {boolean} Return false if this completed and no need to update, otherwise return true. - */ - public update(time): bool; - } -} -/** * Phaser - TweenManager * * The Game has a single instance of the TweenManager through which all Tween objects are created and updated. @@ -6085,67 +4216,6 @@ module Phaser { } } /** -* Phaser - Verlet -* -* Based on verlet-js by Sub Protocol released under MIT -*/ -module Phaser.Verlet { - class VerletManager { - /** - * Creates a new Vector2 object. - * @class Vector2 - * @constructor - * @param {Number} x The x coordinate of vector2 - * @param {Number} y The y coordinate of vector2 - * @return {Vector2} This object - **/ - constructor(game: Game, width: number, height: number); - private _game; - private _v; - public composites: any[]; - public width: number; - public height: number; - public step: number; - public gravity: Vector2; - public friction: number; - public groundFriction: number; - public selectionRadius: number; - public draggedEntity; - public highlightColor: string; - /** - * A reference to the canvas this renders to - * @type {HTMLCanvasElement} - */ - public canvas: HTMLCanvasElement; - /** - * A reference to the context this renders to - * @type {CanvasRenderingContext2D} - */ - public context: CanvasRenderingContext2D; - /** - * Computes time of intersection of a particle with a wall - * - * @param {Vec2} line walls root position - * @param {Vec2} p particle position - * @param {Vec2} dir walls direction - * @param {Vec2} v particles velocity - */ - public intersectionTime(wall, p, dir, v): number; - public intersectionPoint(wall, p, dir, v): Vector2; - public bounds(particle: Particle): void; - public createPoint(pos: Vector2): Composite; - public createLineSegments(vertices, stiffness): Composite; - public createCloth(origin, width, height, segments, pinMod, stiffness): Composite; - public createTire(origin, radius, segments, spokeStiffness, treadStiffness): Composite; - public update(): void; - private mouseDownHandler(); - private mouseUpHandler(); - public nearestEntity(); - public hideNearestEntityCircle: bool; - public render(): void; - } -} -/** * Phaser - World * * "This world is but a canvas to our imagination." - Henry David Thoreau @@ -6188,27 +4258,21 @@ module Phaser { */ public worldDivisions: number; /** - * This is called automatically every frame, and is where main logic performs. + * This is called automatically every frame, and is where main logic happens. */ public update(): void; /** - * Render every thing to the screen, automatically called after update(). - */ - public render(): void; - /** * Clean up memory. */ public destroy(): void; /** - * Update size of this world with specific width and height. - * You can choose update camera bounds and verlet manager automatically or not. + * Updates the size of this world. * * @param width {number} New width of the world. * @param height {number} New height of the world. - * @param [updateCameraBounds] {boolean} update camera bounds automatically or not. Default to true. - * @param [updateVerletBounds] {boolean} update verlet bounds automatically or not. Default to true. + * @param [updateCameraBounds] {boolean} Update camera bounds automatically or not. Default to true. */ - public setSize(width: number, height: number, updateCameraBounds?: bool, updateVerletBounds?: bool): void; + public setSize(width: number, height: number, updateCameraBounds?: bool): void; public width : number; public height : number; public centerX : number; @@ -6216,98 +4280,11 @@ module Phaser { public randomX : number; public randomY : number; /** - * Create a new camera with specific position and size. - * - * @param x {number} X position of the new camera. - * @param y {number} Y position of the new camera. - * @param width {number} Width of the new camera. - * @param height {number} Height of the new camera. - * @returns {Camera} The newly created camera object. - */ - public createCamera(x: number, y: number, width: number, height: number): Camera; - /** - * Remove a new camera with its id. - * - * @param id {number} ID of the camera you want to remove. - * @returns {boolean} True if successfully removed the camera, otherwise return false. - */ - public removeCamera(id: number): bool; - /** * Get all the cameras. * * @returns {array} An array contains all the cameras. */ public getAllCameras(): Camera[]; - /** - * Create a new Sprite with specific position and sprite sheet key. - * - * @param x {number} X position of the new sprite. - * @param y {number} Y position of the new sprite. - * @param [key] {string} key for the sprite sheet you want it to use. - * @returns {Sprite} The newly created sprite object. - */ - public createSprite(x: number, y: number, key?: string): Sprite; - /** - * Create a new GeomSprite with specific position. - * - * @param x {number} X position of the new geom sprite. - * @param y {number} Y position of the new geom sprite. - * @returns {GeomSprite} The newly created geom sprite object. - */ - public createGeomSprite(x: number, y: number): GeomSprite; - /** - * Create a new DynamicTexture with specific size. - * - * @param width {number} Width of the texture. - * @param height {number} Height of the texture. - * @returns {DynamicTexture} The newly created dynamic texture object. - */ - public createDynamicTexture(width: number, height: number): DynamicTexture; - /** - * Create a new object container. - * - * @param [maxSize] {number} capacity of this group. - * @returns {Group} The newly created group. - */ - public createGroup(maxSize?: number): Group; - /** - * Create a new ScrollZone object with image key, position and size. - * - * @param key {number} Key to a image you wish this object to use. - * @param x {number} X position of this object. - * @param y {number} Y position of this object. - * @param width {number} Width of this object. - * @param height {number} Height of this object. - * @returns {ScrollZone} The newly created scroll zone object. - */ - public createScrollZone(key: string, x?: number, y?: number, width?: number, height?: number): ScrollZone; - /** - * Create a new Tilemap. - * - * @param key {string} Key for tileset image. - * @param mapData {string} Data of this tilemap. - * @param format {number} Format of map data. (Tilemap.FORMAT_CSV or Tilemap.FORMAT_TILED_JSON) - * @param [resizeWorld] {boolean} resize the world to make same as tilemap? - * @param [tileWidth] {number} width of each tile. - * @param [tileHeight] {number} height of each tile. - * @return {Tilemap} The newly created tilemap object. - */ - public createTilemap(key: string, mapData: string, format: number, resizeWorld?: bool, tileWidth?: number, tileHeight?: number): Tilemap; - /** - * Create a new Particle. - * - * @return {Particle} The newly created particle object. - */ - public createParticle(): Particle; - /** - * Create a new Emitter. - * - * @param [x] {number} x position of the emitter. - * @param [y] {number} y position of the emitter. - * @param [size] {number} size of this emitter. - * @return {Emitter} The newly created emitter object. - */ - public createEmitter(x?: number, y?: number, size?: number): Emitter; } } /** @@ -6542,144 +4519,6 @@ module Phaser { } } /** -* Phaser - RandomDataGenerator -* -* An extremely useful repeatable random data generator. Access it via Game.rnd -* Based on Nonsense by Josh Faul https://github.com/jocafa/Nonsense -* Random number generator from http://baagoe.org/en/wiki/Better_random_numbers_for_javascript -*/ -module Phaser { - class RandomDataGenerator { - /** - * @constructor - * @param {Array} seeds - * @return {Phaser.RandomDataGenerator} - */ - constructor(seeds?: string[]); - /** - * @property s0 - * @type Any - * @private - */ - private s0; - /** - * @property s1 - * @type Any - * @private - */ - private s1; - /** - * @property s2 - * @type Any - * @private - */ - private s2; - /** - * @property c - * @type Number - * @private - */ - private c; - /** - * @method uint32 - * @private - */ - private uint32(); - /** - * @method fract32 - * @private - */ - private fract32(); - /** - * @method rnd - * @private - */ - private rnd(); - /** - * @method hash - * @param {Any} data - * @private - */ - private hash(data); - /** - * Reset the seed of the random data generator - * @method sow - * @param {Array} seeds - */ - public sow(seeds?: string[]): void; - /** - * Returns a random integer between 0 and 2^32 - * @method integer - * @return {Number} - */ - public integer : number; - /** - * Returns a random real number between 0 and 1 - * @method frac - * @return {Number} - */ - public frac : number; - /** - * Returns a random real number between 0 and 2^32 - * @method real - * @return {Number} - */ - public real : number; - /** - * Returns a random integer between min and max - * @method integerInRange - * @param {Number} min - * @param {Number} max - * @return {Number} - */ - public integerInRange(min: number, max: number): number; - /** - * Returns a random real number between min and max - * @method realInRange - * @param {Number} min - * @param {Number} max - * @return {Number} - */ - public realInRange(min: number, max: number): number; - /** - * Returns a random real number between -1 and 1 - * @method normal - * @return {Number} - */ - public normal : number; - /** - * Returns a valid v4 UUID hex string (from https://gist.github.com/1308368) - * @method uuid - * @return {String} - */ - public uuid : string; - /** - * Returns a random member of `array` - * @method pick - * @param {Any} array - */ - public pick(array); - /** - * Returns a random member of `array`, favoring the earlier entries - * @method weightedPick - * @param {Any} array - */ - public weightedPick(array); - /** - * 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 timestamp - * @param {Number} min - * @param {Number} max - */ - public timestamp(min?: number, max?: number): number; - /** - * Returns a random angle between -180 and 180 - * @method angle - */ - public angle : number; - } -} -/** * Phaser - RequestAnimationFrame * * Abstracts away the use of RAF or setTimeOut for the core game update loop. The callback can be re-mapped on the fly. @@ -6758,1620 +4597,192 @@ module Phaser { } } /** -* Phaser - Emitter +* Phaser - PointUtils * -* Emitter is a lightweight particle emitter. It can be used for one-time explosions or for -* continuous effects like rain and fire. All it really does is launch Particle objects out -* at set intervals, and fixes their positions and velocities accorindgly. +* A collection of methods useful for manipulating and comparing Point objects. +* +* TODO: interpolate & polar */ module Phaser { - class Emitter extends Group { - /** - * Creates a new Emitter object at a specific position. - * Does NOT automatically generate or attach particles! - * - * @param x {number} The X position of the emitter. - * @param y {number} The Y position of the emitter. - * @param [size] {number} Specifies a maximum capacity for this emitter. - */ - constructor(game: Game, x?: number, y?: number, size?: number); - /** - * The X position of the top left corner of the emitter in world space. - */ - public x: number; - /** - * The Y position of the top left corner of emitter in world space. - */ - public y: number; - /** - * The width of the emitter. Particles can be randomly generated from anywhere within this box. - */ - public width: number; - /** - * The height of the emitter. Particles can be randomly generated from anywhere within this box. - */ - public height: number; - /** - * The minimum possible velocity of a particle. - * The default value is (-100,-100). - */ - public minParticleSpeed: MicroPoint; - /** - * The maximum possible velocity of a particle. - * The default value is (100,100). - */ - public maxParticleSpeed: MicroPoint; - /** - * The X and Y drag component of particles launched from the emitter. - */ - public particleDrag: MicroPoint; - /** - * The minimum possible angular velocity of a particle. The default value is -360. - * NOTE: rotating particles are more expensive to draw than non-rotating ones! - */ - public minRotation: number; - /** - * The maximum possible angular velocity of a particle. The default value is 360. - * NOTE: rotating particles are more expensive to draw than non-rotating ones! - */ - public maxRotation: number; - /** - * Sets the acceleration.y member of each particle to this value on launch. - */ - public gravity: number; - /** - * Determines whether the emitter is currently emitting particles. - * It is totally safe to directly toggle this. - */ - public on: bool; - /** - * How often a particle is emitted (if emitter is started with Explode == false). - */ - public frequency: number; - /** - * How long each particle lives once it is emitted. - * Set lifespan to 'zero' for particles to live forever. - */ - public lifespan: number; - /** - * How much each particle should bounce. 1 = full bounce, 0 = no bounce. - */ - public bounce: number; - /** - * Set your own particle class type here. - * Default is Particle. - */ - public particleClass; - /** - * Internal helper for deciding how many particles to launch. - */ - private _quantity; - /** - * Internal helper for the style of particle emission (all at once, or one at a time). - */ - private _explode; - /** - * Internal helper for deciding when to launch particles or kill them. - */ - private _timer; - /** - * Internal counter for figuring out how many particles to launch. - */ - private _counter; - /** - * Internal point object, handy for reusing for memory mgmt purposes. - */ - private _point; - /** - * Clean up memory. - */ - public destroy(): void; - /** - * This function generates a new array of particle sprites to attach to the emitter. - * - * @param graphics If you opted to not pre-configure an array of Sprite objects, you can simply pass in a particle image or sprite sheet. - * @param quantity {number} The number of particles to generate when using the "create from image" option. - * @param multiple {boolean} Whether the image in the Graphics param is a single particle or a bunch of particles (if it's a bunch, they need to be square!). - * @param collide {number} Whether the particles should be flagged as not 'dead' (non-colliding particles are higher performance). 0 means no collisions, 0-1 controls scale of particle's bounding box. - * - * @return This Emitter instance (nice for chaining stuff together, if you're into that). - */ - public makeParticles(graphics, quantity?: number, multiple?: bool, collide?: number): Emitter; - /** - * Called automatically by the game loop, decides when to launch particles and when to "die". - */ - public update(): void; - /** - * Call this function to turn off all the particles and the emitter. - */ - public kill(): void; - /** - * Call this function to start emitting particles. - * - * @param explode {boolean} Whether the particles should all burst out at once. - * @param lifespan {number} How long each particle lives once emitted. 0 = forever. - * @param frequency {number} Ignored if Explode is set to true. Frequency is how often to emit a particle. 0 = never emit, 0.1 = 1 particle every 0.1 seconds, 5 = 1 particle every 5 seconds. - * @param quantity {number} How many particles to launch. 0 = "all of the particles". - */ - public start(explode?: bool, lifespan?: number, frequency?: number, quantity?: number): void; - /** - * This function can be used both internally and externally to emit the next particle. - */ - public emitParticle(): void; - /** - * A more compact way of setting the width and height of the emitter. - * - * @param width {number} The desired width of the emitter (particles are spawned randomly within these dimensions). - * @param height {number} The desired height of the emitter. - */ - public setSize(width: number, height: number): void; - /** - * A more compact way of setting the X velocity range of the emitter. - * - * @param Min {number} The minimum value for this range. - * @param Max {number} The maximum value for this range. - */ - public setXSpeed(min?: number, max?: number): void; - /** - * A more compact way of setting the Y velocity range of the emitter. - * - * @param Min {number} The minimum value for this range. - * @param Max {number} The maximum value for this range. - */ - public setYSpeed(min?: number, max?: number): void; - /** - * A more compact way of setting the angular velocity constraints of the emitter. - * - * @param Min {number} The minimum value for this range. - * @param Max {number} The maximum value for this range. - */ - public setRotation(min?: number, max?: number): void; - /** - * Change the emitter's midpoint to match the midpoint of a Object. - * - * @param Object {object} The Object that you want to sync up with. - */ - public at(object): void; - } } /** -* Phaser - GeomSprite +* Phaser - Vec2Utils +* +* A collection of methods useful for manipulating and performing operations on 2D vectors. * -* A GeomSprite is a special kind of GameObject that contains a base geometry class (Circle, Line, Point, Rectangle). -* They can be rendered in the game and used for collision just like any other game object. Display of them is controlled -* via the lineWidth / lineColor / fillColor and renderOutline / renderFill properties. */ module Phaser { - class GeomSprite extends GameObject { + class Vec2Utils { /** - * GeomSprite constructor - * Create a new GeomSprite. + * Adds two 2D vectors. * - * @param game {Phaser.Game} Current game instance. - * @param [x] {number} the initial x position of the sprite. - * @param [y] {number} the initial y position of the sprite. + * @param {Vec2} a Reference to a source Vec2 object. + * @param {Vec2} b Reference to a source Vec2 object. + * @param {Vec2} out The output Vec2 that is the result of the operation. + * @return {Vec2} A Vec2 that is the sum of the two vectors. */ - constructor(game: Game, x?: number, y?: number); - private _dx; - private _dy; - private _dw; - private _dh; + static add(a: Vec2, b: Vec2, out?: Vec2): Vec2; /** - * Geom type of this sprite. (available: UNASSIGNED, CIRCLE, LINE, POINT, RECTANGLE) - * @type {number} - */ - public type: number; - /** - * Not completely set yet. (the default type) - */ - static UNASSIGNED: number; - /** - * Circle. - * @type {number} - */ - static CIRCLE: number; - /** - * Line. - * @type {number} - */ - static LINE: number; - /** - * Point. - * @type {number} - */ - static POINT: number; - /** - * Rectangle. - * @type {number} - */ - static RECTANGLE: number; - /** - * Polygon. - * @type {number} - */ - static POLYGON: number; - /** - * Circle shape container. A Circle instance. - * @type {Circle} - */ - public circle: Circle; - /** - * Line shape container. A Line instance. - * @type {Line} - */ - public line: Line; - /** - * Point shape container. A Point instance. - * @type {Point} - */ - public point: Point; - /** - * Rectangle shape container. A Rectangle instance. - * @type {Rectangle} - */ - public rect: Rectangle; - /** - * Polygon shape container. A Polygon instance. - * @type {Polygon} - */ - public polygon: Polygon; - /** - * Render outline of this sprite or not. (default is true) - * @type {boolean} - */ - public renderOutline: bool; - /** - * Fill the shape or not. (default is true) - * @type {boolean} - */ - public renderFill: bool; - /** - * Width of outline. (default is 1) - * @type {number} - */ - public lineWidth: number; - /** - * Width of outline. (default is 1) - * @type {number} - */ - public lineColor: string; - /** - * The color of the filled area in rgb or rgba string format - * @type {string} Defaults to rgb(0,100,0) - a green color - */ - public fillColor: string; - /** - * Just like Sprite.loadGraphic(), this will load a circle and set its shape to Circle. - * @param circle {Circle} Circle geometry define. - * @return {GeomSprite} GeomSprite instance itself. - */ - public loadCircle(circle: Circle): GeomSprite; - /** - * Just like Sprite.loadGraphic(), this will load a line and set its shape to Line. - * @param line {Line} Line geometry define. - * @return {GeomSprite} GeomSprite instance itself. - */ - public loadLine(line: Line): GeomSprite; - /** - * Just like Sprite.loadGraphic(), this will load a point and set its shape to Point. - * @param point {Point} Point geometry define. - * @return {GeomSprite} GeomSprite instance itself. - */ - public loadPoint(point: Point): GeomSprite; - /** - * Just like Sprite.loadGraphic(), this will load a rect and set its shape to Rectangle. - * @param rect {Rectangle} Rectangle geometry define. - * @return {GeomSprite} GeomSprite instance itself. - */ - public loadRectangle(rect: Rectangle): GeomSprite; - /** - * Create a circle shape with specific diameter. - * @param diameter {number} Diameter of the circle. - * @return {GeomSprite} GeomSprite instance itself. - */ - public createCircle(diameter: number): GeomSprite; - /** - * Create a line shape with specific end point. - * @param x {number} X position of the end point. - * @param y {number} Y position of the end point. - * @return {GeomSprite} GeomSprite instance itself. - */ - public createLine(x: number, y: number): GeomSprite; - /** - * Create a point shape at spriter's position. - * @return {GeomSprite} GeomSprite instance itself. - */ - public createPoint(): GeomSprite; - /** - * Create a rectangle shape of the given width and height size - * @param width {Number} Width of the rectangle - * @param height {Number} Height of the rectangle - * @return {GeomSprite} GeomSprite instance. - */ - public createRectangle(width: number, height: number): GeomSprite; - /** - * Create a polygon object - * @param width {Number} Width of the rectangle - * @param height {Number} Height of the rectangle - * @return {GeomSprite} GeomSprite instance. - */ - public createPolygon(points?: Vector2[]): GeomSprite; - /** - * Destroy all geom shapes of this sprite. - */ - public refresh(): void; - /** - * Update bounds. - */ - public update(): void; - /** - * Check whether this object is visible in a specific camera rectangle. - * @param camera {Rectangle} The rectangle you want to check. - * @return {boolean} Return true if bounds of this sprite intersects the given rectangle, otherwise return false. - */ - public inCamera(camera: Rectangle): bool; - /** - * Render this sprite to specific camera. Called by game loop after update(). - * @param camera {Camera} Camera this sprite will be rendered to. - * @cameraOffsetX {number} X offset to the camera. - * @cameraOffsetY {number} Y offset to the camera. - * @return {boolean} Return false if not rendered, otherwise return true. - */ - public render(camera: Camera, cameraOffsetX: number, cameraOffsetY: number): bool; - /** - * Render a point of geometry. - * @param point {Point} Position of the point. - * @param offsetX {number} X offset to its position. - * @param offsetY {number} Y offset to its position. - * @param [size] {number} point size. - */ - public renderPoint(point, offsetX?: number, offsetY?: number, size?: number): void; - /** - * Render debug infos. (this method does not work now) - * @param x {number} X position of the debug info to be rendered. - * @param y {number} Y position of the debug info to be rendered. - * @param [color] {number} color of the debug info to be rendered. (format is css color string) - */ - public renderDebugInfo(x: number, y: number, color?: string): void; - /** - * Gives a basic boolean response to a geometric collision. - * If you need the details of the collision use the Collision functions instead and inspect the IntersectResult object. - * @param source {GeomSprite} Sprite you want to check. - * @return {boolean} Whether they overlaps or not. - */ - public collide(source: GeomSprite): bool; - } -} -/** -* Phaser - Particle -* -* This is a simple particle class that extends a Sprite to have a slightly more -* specialised behaviour. It is used exclusively by the Emitter class and can be extended as required. -*/ -module Phaser { - class Particle extends Sprite { - /** - * Instantiate a new particle. Like Sprite, all meaningful creation - * happens during loadGraphic() or makeGraphic() or whatever. - */ - constructor(game: Game); - /** - * How long this particle lives before it disappears. - * NOTE: this is a maximum, not a minimum; the object - * could get recycled before its lifespan is up. - */ - public lifespan: number; - /** - * Determines how quickly the particles come to rest on the ground. - * Only used if the particle has gravity-like acceleration applied. - * @default 500 - */ - public friction: number; - /** - * The particle's main update logic. Basically it checks to see if it should - * be dead yet, and then has some special bounce behavior if there is some gravity on it. - */ - public update(): void; - /** - * Triggered whenever this object is launched by a Emitter. - * You can override this to add custom behavior like a sound or AI or something. - */ - public onEmit(): void; - } -} -/** -* Phaser - TilemapLayer -* -* A Tilemap Layer. Tiled format maps can have multiple overlapping layers. -*/ -module Phaser { - class TilemapLayer { - /** - * TilemapLayer constructor - * Create a new TilemapLayer. + * Subtracts two 2D vectors. * - * @param game {Phaser.Game} Current game instance. - * @param parent {Tilemap} The tilemap that contains this layer. - * @param key {string} Asset key for this map. - * @param mapFormat {number} Format of this map data, available: Tilemap.FORMAT_CSV or Tilemap.FORMAT_TILED_JSON. - * @param name {string} Name of this layer, so you can get this layer by its name. - * @param tileWidth {number} Width of tiles in this map. - * @param tileHeight {number} Height of tiles in this map. + * @param {Vec2} a Reference to a source Vec2 object. + * @param {Vec2} b Reference to a source Vec2 object. + * @param {Vec2} out The output Vec2 that is the result of the operation. + * @return {Vec2} A Vec2 that is the difference of the two vectors. */ - constructor(game: Game, parent: Tilemap, key: string, mapFormat: number, name: string, tileWidth: number, tileHeight: number); + static subtract(a: Vec2, b: Vec2, out?: Vec2): Vec2; /** - * Local private reference to game. - */ - private _game; - /** - * The tilemap that contains this layer. - * @type {Tilemap} - */ - private _parent; - /** - * Tileset of this layer. - */ - private _texture; - private _tileOffsets; - private _startX; - private _startY; - private _maxX; - private _maxY; - private _tx; - private _ty; - private _dx; - private _dy; - private _oldCameraX; - private _oldCameraY; - private _columnData; - private _tempTileX; - private _tempTileY; - private _tempTileW; - private _tempTileH; - private _tempTileBlock; - private _tempBlockResults; - /** - * Name of this layer, so you can get this layer by its name. - * @type {string} - */ - public name: string; - /** - * A reference to the Canvas this GameObject will render to - * @type {HTMLCanvasElement} - */ - public canvas: HTMLCanvasElement; - /** - * A reference to the Canvas Context2D this GameObject will render to - * @type {CanvasRenderingContext2D} - */ - public context: CanvasRenderingContext2D; - /** - * Opacity of this layer. - * @type {number} - */ - public alpha: number; - /** - * Controls whether update() and draw() are automatically called. - * @type {boolean} - */ - public exists: bool; - /** - * Controls whether draw() are automatically called. - * @type {boolean} - */ - public visible: bool; - /** - * @type {string} - */ - public orientation: string; - /** - * Properties of this map layer. (normally set by map editors) - */ - public properties: {}; - /** - * Map data in a 2d array, its element is a index number for that tile. - * @type {number[][]} - */ - public mapData; - /** - * Format of this map data, available: Tilemap.FORMAT_CSV or Tilemap.FORMAT_TILED_JSON. - */ - public mapFormat: number; - /** - * It's width and height are in tiles instead of pixels. - * @type {Rectangle} - */ - public boundsInTiles: Rectangle; - /** - * Width of each tile. - * @type {number} - */ - public tileWidth: number; - /** - * Height of a single tile. - * @type {number} - */ - public tileHeight: number; - /** - * How many tiles in each row. - * Read-only variable, do NOT recommend changing after the map is loaded! - * @type {number} - */ - public widthInTiles: number; - /** - * How many tiles in each column. - * Read-only variable, do NOT recommend changing after the map is loaded! - * @type {number} - */ - public heightInTiles: number; - /** - * Read-only variable, do NOT recommend changing after the map is loaded! - * @type {number} - */ - public widthInPixels: number; - /** - * Read-only variable, do NOT recommend changing after the map is loaded! - * @type {number} - */ - public heightInPixels: number; - /** - * Distance between REAL tiles to the tileset texture bound. - * @type {number} - */ - public tileMargin: number; - /** - * Distance between every 2 neighbor tile in the tileset texture. - * @type {number} - */ - public tileSpacing: number; - /** - * Set a specific tile with its x and y in tiles. - * @param x {number} X position of this tile. - * @param y {number} Y position of this tile. - * @param index {number} The index of this tile type in the core map data. - */ - public putTile(x: number, y: number, index: number): void; - /** - * Swap tiles with 2 kinds of indexes. - * @param tileA {number} First tile index. - * @param tileB {number} Second tile index. - * @param [x] {number} specify a rectangle of tiles to operate. The x position in tiles of rectangle's left-top corner. - * @param [y] {number} specify a rectangle of tiles to operate. The y position in tiles of rectangle's left-top corner. - * @param [width] {number} specify a rectangle of tiles to operate. The width in tiles. - * @param [height] {number} specify a rectangle of tiles to operate. The height in tiles. - */ - public swapTile(tileA: number, tileB: number, x?: number, y?: number, width?: number, height?: number): void; - /** - * Fill a tile block with a specific tile index. - * @param index {number} Index of tiles you want to fill with. - * @param [x] {number} x position (in tiles) of block's left-top corner. - * @param [y] {number} y position (in tiles) of block's left-top corner. - * @param [width] {number} width of block. - * @param [height] {number} height of block. - */ - public fillTile(index: number, x?: number, y?: number, width?: number, height?: number): void; - /** - * Set random tiles to a specific tile block. - * @param tiles {number[]} Tiles with indexes in this array will be randomly set to the given block. - * @param [x] {number} x position (in tiles) of block's left-top corner. - * @param [y] {number} y position (in tiles) of block's left-top corner. - * @param [width] {number} width of block. - * @param [height] {number} height of block. - */ - public randomiseTiles(tiles: number[], x?: number, y?: number, width?: number, height?: number): void; - /** - * Replace one kind of tiles to another kind. - * @param tileA {number} Index of tiles you want to replace. - * @param tileB {number} Index of tiles you want to set. - * @param [x] {number} x position (in tiles) of block's left-top corner. - * @param [y] {number} y position (in tiles) of block's left-top corner. - * @param [width] {number} width of block. - * @param [height] {number} height of block. - */ - public replaceTile(tileA: number, tileB: number, x?: number, y?: number, width?: number, height?: number): void; - /** - * Get a tile block with specific position and size.(both are in tiles) - * @param x {number} X position of block's left-top corner. - * @param y {number} Y position of block's left-top corner. - * @param width {number} Width of block. - * @param height {number} Height of block. - */ - public getTileBlock(x: number, y: number, width: number, height: number): any[]; - /** - * Get a tile with specific position (in world coordinate). (thus you give a position of a point which is within the tile) - * @param x {number} X position of the point in target tile. - * @param x {number} Y position of the point in target tile. - */ - public getTileFromWorldXY(x: number, y: number): number; - /** - * Get tiles overlaps the given object. - * @param object {GameObject} Tiles you want to get that overlaps this. - * @return {array} Array with tiles informations. (Each contains x, y and the tile.) - */ - public getTileOverlaps(object: GameObject); - /** - * Get a tile block with its position and size. (This method does not return, it'll set result to _tempTileBlock) - * @param x {number} X position of block's left-top corner. - * @param y {number} Y position of block's left-top corner. - * @param width {number} Width of block. - * @param height {number} Height of block. - * @param collisionOnly {boolean} Whethor or not ONLY return tiles which will collide (its allowCollisions value is not Collision.NONE). - */ - private getTempBlock(x, y, width, height, collisionOnly?); - /** - * Get the tile index of specific position (in tiles). - * @param x {number} X position of the tile. - * @param y {number} Y position of the tile. - * @return {number} Index of the tile at that position. Return null if there isn't a tile there. - */ - public getTileIndex(x: number, y: number): number; - /** - * Add a column of tiles into the layer. - * @param column {string[]/number[]} An array of tile indexes to be added. - */ - public addColumn(column): void; - /** - * Update boundsInTiles with widthInTiles and heightInTiles. - */ - public updateBounds(): void; - /** - * Parse tile offsets from map data. - * @return {number} length of _tileOffsets array. - */ - public parseTileOffsets(): number; - public renderDebugInfo(x: number, y: number, color?: string): void; - /** - * Render this layer to a specific camera with offset to camera. - * @param camera {Camera} The camera the layer is going to be rendered. - * @param dx {number} X offset to the camera. - * @param dy {number} Y offset to the camera. - * @return {boolean} Return false if layer is invisible or has a too low opacity(will stop rendering), return true if succeed. - */ - public render(camera: Camera, dx, dy): bool; - } -} -/** -* Phaser - Tile -* -* A Tile is a single representation of a tile within a Tilemap -*/ -module Phaser { - class Tile { - /** - * Tile constructor - * Create a new Tile. + * Multiplies two 2D vectors. * - * @param tilemap {Tilemap} the tilemap this tile belongs to. - * @param index {number} The index of this tile type in the core map data. - * @param width {number} Width of the tile. - * @param height number} Height of the tile. + * @param {Vec2} a Reference to a source Vec2 object. + * @param {Vec2} b Reference to a source Vec2 object. + * @param {Vec2} out The output Vec2 that is the result of the operation. + * @return {Vec2} A Vec2 that is the sum of the two vectors multiplied. */ - constructor(game: Game, tilemap: Tilemap, index: number, width: number, height: number); + static multiply(a: Vec2, b: Vec2, out?: Vec2): Vec2; /** - * Local private reference to game. - */ - private _game; - /** - * You can give this Tile a friendly name to help with debugging. Never used internally. - * @type {string} - */ - public name: string; - /** - * The virtual mass of the tile. - * @type {number} - */ - public mass: number; - /** - * Tile width. - * @type {number} - */ - public width: number; - /** - * Tile height. - * @type {number} - */ - public height: number; - /** - * Bit field of flags (use with UP, DOWN, LEFT, RIGHT, etc) indicating collision directions. - * @type {number} - */ - public allowCollisions: number; - /** - * Indicating collide with any object on the left. - * @type {boolean} - */ - public collideLeft: bool; - /** - * Indicating collide with any object on the right. - * @type {boolean} - */ - public collideRight: bool; - /** - * Indicating collide with any object on the top. - * @type {boolean} - */ - public collideUp: bool; - /** - * Indicating collide with any object on the bottom. - * @type {boolean} - */ - public collideDown: bool; - /** - * Enable separation at x-axis. - * @type {boolean} - */ - public separateX: bool; - /** - * Enable separation at y-axis. - * @type {boolean} - */ - public separateY: bool; - /** - * A reference to the tilemap this tile object belongs to. - * @type {Tilemap} - */ - public tilemap: Tilemap; - /** - * The index of this tile type in the core map data. - * For example, if your map only has 16 kinds of tiles in it, - * this number is usually between 0 and 15. - * @type {number} - */ - public index: number; - /** - * Clean up memory. - */ - public destroy(): void; - /** - * Set collision configs. - * @param collision {number} Bit field of flags. (see Tile.allowCollision) - * @param resetCollisions {boolean} Reset collision flags before set. - * @param separateX {boolean} Enable seprate at x-axis. - * @param separateY {boolean} Enable seprate at y-axis. - */ - public setCollision(collision: number, resetCollisions: bool, separateX: bool, separateY: bool): void; - /** - * Reset collision status flags. - */ - public resetCollision(): void; - /** - * Returns a string representation of this object. - * @method toString - * @return {string} a string representation of the object. - **/ - public toString(): string; - } -} -/** -* Phaser - Tilemap -* -* This GameObject allows for the display of a tilemap within the game world. Tile maps consist of an image, tile data and a size. -* Internally it creates a TilemapLayer for each layer in the tilemap. -*/ -module Phaser { - class Tilemap extends GameObject { - /** - * Tilemap constructor - * Create a new Tilemap. + * Divides two 2D vectors. * - * @param game {Phaser.Game} Current game instance. - * @param key {string} Asset key for this map. - * @param mapData {string} Data of this map. (a big 2d array, normally in csv) - * @param format {number} Format of this map data, available: Tilemap.FORMAT_CSV or Tilemap.FORMAT_TILED_JSON. - * @param resizeWorld {boolean} Resize the world bound automatically based on this tilemap? - * @param tileWidth {number} Width of tiles in this map. - * @param tileHeight {number} Height of tiles in this map. + * @param {Vec2} a Reference to a source Vec2 object. + * @param {Vec2} b Reference to a source Vec2 object. + * @param {Vec2} out The output Vec2 that is the result of the operation. + * @return {Vec2} A Vec2 that is the sum of the two vectors divided. */ - constructor(game: Game, key: string, mapData: string, format: number, resizeWorld?: bool, tileWidth?: number, tileHeight?: number); - private _tempCollisionData; + static divide(a: Vec2, b: Vec2, out?: Vec2): Vec2; /** - * Tilemap data format enum: CSV. - * @type {number} - */ - static FORMAT_CSV: number; - /** - * Tilemap data format enum: Tiled JSON. - * @type {number} - */ - static FORMAT_TILED_JSON: number; - /** - * Array contains tile objects of this map. - * @type {Tile[]} - */ - public tiles: Tile[]; - /** - * Array contains tilemap layer objects of this map. - * @type {TilemapLayer[]} - */ - public layers: TilemapLayer[]; - /** - * Current tilemap layer. - * @type {TilemapLayer} - */ - public currentLayer: TilemapLayer; - /** - * The tilemap layer for collision. - * @type {TilemapLayer} - */ - public collisionLayer: TilemapLayer; - /** - * Tilemap collision callback. - * @type {function} - */ - public collisionCallback; - /** - * Context for the collision callback called with. - */ - public collisionCallbackContext; - /** - * Format of this tilemap data. Available values: Tilemap.FORMAT_CSV or Tilemap.FORMAT_TILED_JSON. - * @type {number} - */ - public mapFormat: number; - /** - * Inherited update method. - */ - public update(): void; - /** - * Render this tilemap to a specific camera with specific offset. - * @param camera {Camera} The camera this tilemap will be rendered to. - * @param cameraOffsetX {number} X offset of the camera. - * @param cameraOffsetY {number} Y offset of the camera. - */ - public render(camera: Camera, cameraOffsetX: number, cameraOffsetY: number): void; - /** - * Parset csv map data and generate tiles. - * @param data {string} CSV map data. - * @param key {string} Asset key for tileset image. - * @param tileWidth {number} Width of its tile. - * @param tileHeight {number} Height of its tile. - */ - private parseCSV(data, key, tileWidth, tileHeight); - /** - * Parset JSON map data and generate tiles. - * @param data {string} JSON map data. - * @param key {string} Asset key for tileset image. - */ - private parseTiledJSON(data, key); - /** - * Create tiles of given quantity. - * @param qty {number} Quentity of tiles to be generated. - */ - private generateTiles(qty); - public widthInPixels : number; - public heightInPixels : number; - /** - * Set callback to be called when this tilemap collides. - * @param context {object} Callback will be called with this context. - * @param callback {function} Callback function. - */ - public setCollisionCallback(context, callback): void; - /** - * Set collision configs of tiles in a range index. - * @param start {number} First index of tiles. - * @param end {number} Last index of tiles. - * @param collision {number} Bit field of flags. (see Tile.allowCollision) - * @param resetCollisions {boolean} Reset collision flags before set. - * @param separateX {boolean} Enable seprate at x-axis. - * @param separateY {boolean} Enable seprate at y-axis. - */ - public setCollisionRange(start: number, end: number, collision?: number, resetCollisions?: bool, separateX?: bool, separateY?: bool): void; - /** - * Set collision configs of tiles with given index. - * @param values {number[]} Index array which contains all tile indexes. The tiles with those indexes will be setup with rest parameters. - * @param collision {number} Bit field of flags. (see Tile.allowCollision) - * @param resetCollisions {boolean} Reset collision flags before set. - * @param separateX {boolean} Enable seprate at x-axis. - * @param separateY {boolean} Enable seprate at y-axis. - */ - public setCollisionByIndex(values: number[], collision?: number, resetCollisions?: bool, separateX?: bool, separateY?: bool): void; - /** - * Get the tile by its index. - * @param value {number} Index of the tile you want to get. - * @return {Tile} The tile with given index. - */ - public getTileByIndex(value: number): Tile; - /** - * Get the tile located at specific position and layer. - * @param x {number} X position of this tile located. - * @param y {number} Y position of this tile located. - * @param [layer] {number} layer of this tile located. - * @return {Tile} The tile with specific properties. - */ - public getTile(x: number, y: number, layer?: number): Tile; - /** - * Get the tile located at specific position (in world coordinate) and layer. (thus you give a position of a point which is within the tile) - * @param x {number} X position of the point in target tile. - * @param x {number} Y position of the point in target tile. - * @param [layer] {number} layer of this tile located. - * @return {Tile} The tile with specific properties. - */ - public getTileFromWorldXY(x: number, y: number, layer?: number): Tile; - public getTileFromInputXY(layer?: number): Tile; - /** - * Get tiles overlaps the given object. - * @param object {GameObject} Tiles you want to get that overlaps this. - * @return {array} Array with tiles informations. (Each contains x, y and the tile.) - */ - public getTileOverlaps(object: GameObject); - /** - * Check whether this tilemap collides with the given game object or group of objects. - * @param objectOrGroup {function} Target object of group you want to check. - * @param callback {function} This is called if objectOrGroup collides the tilemap. - * @param context {object} Callback will be called with this context. - * @return {boolean} Return true if this collides with given object, otherwise return false. - */ - public collide(objectOrGroup?, callback?, context?): void; - /** - * Check whether this tilemap collides with the given game object. - * @param object {GameObject} Target object you want to check. - * @return {boolean} Return true if this collides with given object, otherwise return false. - */ - public collideGameObject(object: GameObject): bool; - /** - * Set a tile to a specific layer. - * @param x {number} X position of this tile. - * @param y {number} Y position of this tile. - * @param index {number} The index of this tile type in the core map data. - * @param [layer] {number} which layer you want to set the tile to. - */ - public putTile(x: number, y: number, index: number, layer?: number): void; - } -} -/** -* Phaser - ScrollRegion -* -* Creates a scrolling region within a ScrollZone. -* It is scrolled via the scrollSpeed.x/y properties. -*/ -module Phaser { - class ScrollRegion { - /** - * ScrollRegion constructor - * Create a new ScrollRegion. + * Scales a 2D vector. * - * @param x {number} X position in world coordinate. - * @param y {number} Y position in world coordinate. - * @param width {number} Width of this object. - * @param height {number} Height of this object. - * @param speedX {number} X-axis scrolling speed. - * @param speedY {number} Y-axis scrolling speed. + * @param {Vec2} a Reference to a source Vec2 object. + * @param {number} s Scaling value. + * @param {Vec2} out The output Vec2 that is the result of the operation. + * @return {Vec2} A Vec2 that is the scaled vector. */ - constructor(x: number, y: number, width: number, height: number, speedX: number, speedY: number); - private _A; - private _B; - private _C; - private _D; - private _bounds; - private _scroll; - private _anchorWidth; - private _anchorHeight; - private _inverseWidth; - private _inverseHeight; + static scale(a: Vec2, s: number, out?: Vec2): Vec2; /** - * Will this region be rendered? (default to true) - * @type {boolean} - */ - public visible: bool; - /** - * Region scrolling speed. - * @type {MicroPoint} - */ - public scrollSpeed: MicroPoint; - /** - * Update region scrolling with tick time. - * @param delta {number} Elapsed time since last update. - */ - public update(delta: number): void; - /** - * Render this region to specific context. - * @param context {CanvasRenderingContext2D} Canvas context this region will be rendered to. - * @param texture {object} The texture to be rendered. - * @param dx {number} X position in world coordinate. - * @param dy {number} Y position in world coordinate. - * @param width {number} Width of this region to be rendered. - * @param height {number} Height of this region to be rendered. - */ - public render(context: CanvasRenderingContext2D, texture, dx: number, dy: number, dw: number, dh: number): void; - /** - * Crop part of the texture and render it to the given context. - * @param context {CanvasRenderingContext2D} Canvas context the texture will be rendered to. - * @param texture {object} Texture to be rendered. - * @param srcX {number} Target region top-left x coordinate in the texture. - * @param srcX {number} Target region top-left y coordinate in the texture. - * @param srcW {number} Target region width in the texture. - * @param srcH {number} Target region height in the texture. - * @param destX {number} Render region top-left x coordinate in the context. - * @param destX {number} Render region top-left y coordinate in the context. - * @param destW {number} Target region width in the context. - * @param destH {number} Target region height in the context. - * @param offsetX {number} X offset to the context. - * @param offsetY {number} Y offset to the context. - */ - private crop(context, texture, srcX, srcY, srcW, srcH, destX, destY, destW, destH, offsetX, offsetY); - } -} -/** -* Phaser - ScrollZone -* -* Creates a scrolling region of the given width and height from an image in the cache. -* The ScrollZone can be positioned anywhere in-world like a normal game object, re-act to physics, collision, etc. -* The image within it is scrolled via ScrollRegions and their scrollSpeed.x/y properties. -* If you create a scroll zone larger than the given source image it will create a DynamicTexture and fill it with a pattern of the source image. -*/ -module Phaser { - class ScrollZone extends GameObject { - /** - * ScrollZone constructor - * Create a new ScrollZone. + * Rotate a 2D vector by 90 degrees. * - * @param game {Phaser.Game} Current game instance. - * @param key {string} Asset key for image texture of this object. - * @param x {number} X position in world coordinate. - * @param y {number} Y position in world coordinate. - * @param [width] {number} width of this object. - * @param [height] {number} height of this object. + * @param {Vec2} a Reference to a source Vec2 object. + * @param {Vec2} out The output Vec2 that is the result of the operation. + * @return {Vec2} A Vec2 that is the scaled vector. */ - constructor(game: Game, key: string, x?: number, y?: number, width?: number, height?: number); + static perp(a: Vec2, out?: Vec2): Vec2; /** - * Texture of this object. - */ - private _texture; - /** - * If this zone is larger than texture image, this will be filled with a pattern of texture. - * @type {DynamicTexture} - */ - private _dynamicTexture; - /** - * Local rendering related temp vars to help avoid gc spikes. - * @type {number} - */ - private _dx; - /** - * Local rendering related temp vars to help avoid gc spikes. - * @type {number} - */ - private _dy; - /** - * Local rendering related temp vars to help avoid gc spikes. - * @type {number} - */ - private _dw; - /** - * Local rendering related temp vars to help avoid gc spikes. - * @type {number} - */ - private _dh; - /** - * Current region this zone is scrolling. - * @type {ScrollRegion} - */ - public currentRegion: ScrollRegion; - /** - * Array contains all added regions. - * @type {ScrollRegion[]} - */ - public regions: ScrollRegion[]; - /** - * Flip this zone vertically? (default to false) - * @type {boolean} - */ - public flipped: bool; - /** - * Add a new region to this zone. - * @param x {number} X position of the new region. - * @param y {number} Y position of the new region. - * @param width {number} Width of the new region. - * @param height {number} Height of the new region. - * @param [speedX] {number} x-axis scrolling speed. - * @param [speedY] {number} y-axis scrolling speed. - * @return {ScrollRegion} The newly added region. - */ - public addRegion(x: number, y: number, width: number, height: number, speedX?: number, speedY?: number): ScrollRegion; - /** - * Set scrolling speed of current region. - * @param x {number} X speed of current region. - * @param y {number} Y speed of current region. - */ - public setSpeed(x: number, y: number): ScrollZone; - /** - * Update regions. - */ - public update(): void; - /** - * Check whether this zone is visible in a specific camera rectangle. - * @param camera {Rectangle} The rectangle you want to check. - * @return {boolean} Return true if bound of this zone intersects the given rectangle, otherwise return false. - */ - public inCamera(camera: Rectangle): bool; - /** - * Render this zone object to a specific camera. - * @param camera {Camera} The camera this object will be render to. - * @param cameraOffsetX {number} X offset of camera. - * @param cameraOffsetY {number} Y offset of camera. - * @return Return false if not rendered, otherwise return true. - */ - public render(camera: Camera, cameraOffsetX: number, cameraOffsetY: number): bool; - /** - * Create repeating texture with _texture, and store it into the _dynamicTexture. - * Used to create texture when texture image is small than size of the zone. - */ - private createRepeatingTexture(regionWidth, regionHeight); - } -} -/** -* Phaser - Game -* -* This is where the magic happens. The Game object is the heart of your game, -* providing quick access to common functions and handling the boot process. -* -* "Hell, there are no rules here - we're trying to accomplish something." -* Thomas A. Edison -*/ -module Phaser { - class Game { - /** - * Game constructor + * Checks if two 2D vectors are equal. * - * Instantiate a new Phaser.Game object. + * @param {Vec2} a Reference to a source Vec2 object. + * @param {Vec2} b Reference to a source Vec2 object. + * @return {Boolean} + */ + static equals(a: Vec2, b: Vec2): bool; + /** * - * @param callbackContext Which context will the callbacks be called with. - * @param parent {string} ID of its parent DOM element. - * @param width {number} The width of your game in game pixels. - * @param height {number} The height of your game in game pixels. - * @param initCallback {function} Init callback invoked when init default screen. - * @param createCallback {function} Create callback invoked when create default screen. - * @param updateCallback {function} Update callback invoked when update default screen. - * @param renderCallback {function} Render callback invoked when render default screen. - * @param destroyCallback {function} Destroy callback invoked when state is destroyed. + * + * @param {Vec2} a Reference to a source Vec2 object. + * @param {Vec2} b Reference to a source Vec2 object. + * @param {Vec2} epsilon + * @return {Boolean} */ - constructor(callbackContext, parent?: string, width?: number, height?: number, initCallback?, createCallback?, updateCallback?, renderCallback?, destroyCallback?); + static epsilonEquals(a: Vec2, b: Vec2, epsilon: number): bool; /** - * Game loop trigger wrapper. + * Get the distance between two 2D vectors. + * + * @param {Vec2} a Reference to a source Vec2 object. + * @param {Vec2} b Reference to a source Vec2 object. + * @return {Number} */ - public _raf: RequestAnimationFrame; + static distance(a: Vec2, b: Vec2): number; /** - * Max allowable accumulation. - * @type {number} + * Get the distance squared between two 2D vectors. + * + * @param {Vec2} a Reference to a source Vec2 object. + * @param {Vec2} b Reference to a source Vec2 object. + * @return {Number} */ - private _maxAccumulation; + static distanceSq(a: Vec2, b: Vec2): number; /** - * Total number of milliseconds elapsed since last update loop. - * @type {number} + * Project two 2D vectors onto another vector. + * + * @param {Vec2} a Reference to a source Vec2 object. + * @param {Vec2} b Reference to a source Vec2 object. + * @param {Vec2} out The output Vec2 that is the result of the operation. + * @return {Vec2} A Vec2. */ - private _accumulator; + static project(a: Vec2, b: Vec2, out?: Vec2): Vec2; /** - * Milliseconds of time per step of the game loop. - * @type {number} + * Project this vector onto a vector of unit length. + * + * @param {Vec2} a Reference to a source Vec2 object. + * @param {Vec2} b Reference to a source Vec2 object. + * @param {Vec2} out The output Vec2 that is the result of the operation. + * @return {Vec2} A Vec2. */ - private _step; + static projectUnit(a: Vec2, b: Vec2, out?: Vec2): Vec2; /** - * Whether loader complete loading or not. - * @type {boolean} + * Right-hand normalize (make unit length) a 2D vector. + * + * @param {Vec2} a Reference to a source Vec2 object. + * @param {Vec2} out The output Vec2 that is the result of the operation. + * @return {Vec2} A Vec2. */ - private _loadComplete; + static normalRightHand(a: Vec2, out?: Vec2): Vec2; /** - * Game is paused? - * @type {boolean} + * Normalize (make unit length) a 2D vector. + * + * @param {Vec2} a Reference to a source Vec2 object. + * @param {Vec2} out The output Vec2 that is the result of the operation. + * @return {Vec2} A Vec2. */ - private _paused; + static normalize(a: Vec2, out?: Vec2): Vec2; /** - * The state to be switched to in the next frame. - * @type {State} + * The dot product of two 2D vectors. + * + * @param {Vec2} a Reference to a source Vec2 object. + * @param {Vec2} b Reference to a source Vec2 object. + * @return {Number} */ - private _pendingState; + static dot(a: Vec2, b: Vec2): number; /** - * The current State object (defaults to null) - * @type {State} + * The cross product of two 2D vectors. + * + * @param {Vec2} a Reference to a source Vec2 object. + * @param {Vec2} b Reference to a source Vec2 object. + * @return {Number} */ - public state; + static cross(a: Vec2, b: Vec2): number; /** - * Context for calling the callbacks. + * The angle between two 2D vectors. + * + * @param {Vec2} a Reference to a source Vec2 object. + * @param {Vec2} b Reference to a source Vec2 object. + * @return {Number} */ - public callbackContext; + static angle(a: Vec2, b: Vec2): number; /** - * This will be called when init states. (loading assets...) - * @type {function} + * The angle squared between two 2D vectors. + * + * @param {Vec2} a Reference to a source Vec2 object. + * @param {Vec2} b Reference to a source Vec2 object. + * @return {Number} */ - public onInitCallback; + static angleSq(a: Vec2, b: Vec2): number; /** - * This will be called when create states. (setup states...) - * @type {function} + * Rotate a 2D vector around the origin to the given angle (theta). + * + * @param {Vec2} a Reference to a source Vec2 object. + * @param {Vec2} b Reference to a source Vec2 object. + * @param {Number} theta The angle of rotation in radians. + * @param {Vec2} out The output Vec2 that is the result of the operation. + * @return {Vec2} A Vec2. */ - public onCreateCallback; + static rotate(a: Vec2, b: Vec2, theta: number, out?: Vec2): Vec2; /** - * This will be called when update states. - * @type {function} + * Clone a 2D vector. + * + * @param {Vec2} a Reference to a source Vec2 object. + * @param {Vec2} out The output Vec2 that is the result of the operation. + * @return {Vec2} A Vec2 that is a copy of the source Vec2. */ - public onUpdateCallback; - /** - * This will be called when render states. - * @type {function} - */ - public onRenderCallback; - /** - * This will be called when states paused. - * @type {function} - */ - public onPausedCallback; - /** - * This will be called when the state is destroyed (i.e. swapping to a new state) - * @type {function} - */ - public onDestroyCallback; - /** - * Reference to the GameObject Factory. - * @type {GameObjectFactory} - */ - public add: GameObjectFactory; - /** - * Reference to the assets cache. - * @type {Cache} - */ - public cache: Cache; - /** - * Reference to the collision helper. - * @type {Collision} - */ - public collision: Collision; - /** - * Reference to the input manager - * @type {Input} - */ - public input: Input; - /** - * Reference to the assets loader. - * @type {Loader} - */ - public loader: Loader; - /** - * Reference to the math helper. - * @type {GameMath} - */ - public math: GameMath; - /** - * Reference to the motion helper. - * @type {Motion} - */ - public motion: Motion; - /** - * Reference to the sound manager. - * @type {SoundManager} - */ - public sound: SoundManager; - /** - * Reference to the stage. - * @type {Stage} - */ - public stage: Stage; - /** - * Reference to game clock. - * @type {Time} - */ - public time: Time; - /** - * Reference to the tween manager. - * @type {TweenManager} - */ - public tweens: TweenManager; - /** - * Reference to the verlet manager. - * @type {VerletManager} - */ - public verlet: Verlet.VerletManager; - /** - * Reference to the world. - * @type {World} - */ - public world: World; - /** - * Instance of repeatable random data generator helper. - * @type {RandomDataGenerator} - */ - public rnd: RandomDataGenerator; - /** - * Contains device information and capabilities. - * @type {Device} - */ - public device: Device; - /** - * Whether the game engine is booted, aka available. - * @type {boolean} - */ - public isBooted: bool; - /** - * Is game running or paused? - * @type {boolean} - */ - public isRunning: bool; - /** - * Initialize engine sub modules and start the game. - * @param parent {string} ID of parent Dom element. - * @param width {number} Width of the game screen. - * @param height {number} Height of the game screen. - */ - private boot(parent, width, height); - /** - * Called when the loader has finished after init was run. - */ - private loadComplete(); - /** - * Game loop method will be called when it's booting. - */ - private bootLoop(); - /** - * Game loop method will be called when it's paused. - */ - private pausedLoop(); - /** - * Game loop method will be called when it's running. - */ - private loop(); - /** - * Start current state. - */ - private startState(); - /** - * Set all state callbacks (init, create, update, render). - * @param initCallback {function} Init callback invoked when init state. - * @param createCallback {function} Create callback invoked when create state. - * @param updateCallback {function} Update callback invoked when update state. - * @param renderCallback {function} Render callback invoked when render state. - * @param destroyCallback {function} Destroy callback invoked when state is destroyed. - */ - public setCallbacks(initCallback?, createCallback?, updateCallback?, renderCallback?, destroyCallback?): void; - /** - * Switch to a new State. - * @param state {State} The state you want to switch to. - * @param [clearWorld] {boolean} clear everything in the world? (Default to true) - * @param [clearCache] {boolean} clear asset cache? (Default to false and ONLY available when clearWorld=true) - */ - public switchState(state, clearWorld?: bool, clearCache?: bool): void; - /** - * Nuke the whole game from orbit - */ - public destroy(): void; - public paused : bool; - public framerate : number; - /** - * Checks for overlaps between two objects using the world QuadTree. Can be GameObject vs. GameObject, GameObject vs. Group or Group vs. Group. - * Note: Does not take the objects scrollFactor into account. All overlaps are check in world space. - * @param object1 The first GameObject or Group to check. If null the world.group is used. - * @param object2 The second GameObject or Group to check. - * @param notifyCallback A callback function that is called if the objects overlap. The two objects will be passed to this function in the same order in which you passed them to Collision.overlap. - * @param processCallback A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then notifyCallback will only be called if processCallback returns true. - * @param context The context in which the callbacks will be called - * @returns {boolean} true if the objects overlap, otherwise false. - */ - public collide(objectOrGroup1?: Basic, objectOrGroup2?: Basic, notifyCallback?, context?): bool; - public camera : Camera; - } -} -/** -* Phaser - FXManager -* -* The FXManager controls all special effects applied to game objects such as Cameras. -*/ -module Phaser { - class FXManager { - constructor(game: Game, parent); - /** - * The essential reference to the main game object. - */ - private _game; - /** - * A reference to the object that owns this FXManager instance. - */ - private _parent; - /** - * The array in which we keep all of the registered FX - */ - private _fx; - /** - * Holds the size of the _fx array - */ - private _length; - /** - * Controls whether any of the FX have preUpdate, update or postUpdate called - */ - public active: bool; - /** - * Controls whether any of the FX have preRender, render or postRender called - */ - public visible: bool; - /** - * Adds a new FX to the FXManager. - * The effect must be an object with at least one of the following methods: preUpdate, postUpdate, preRender, render or postRender. - * A new instance of the effect will be created and a reference to Game will be passed to the object constructor. - * @param {object} effect - * @return {any} - */ - public add(effect): any; - /** - * Pre-update is called at the start of the objects update cycle, before any other updates have taken place. - */ - public preUpdate(): void; - /** - * Post-update is called at the end of the objects update cycle, after other update logic has taken place. - */ - public postUpdate(): void; - /** - * Pre-render is called at the start of the object render cycle, before any transforms have taken place. - * It happens directly AFTER a canvas context.save has happened if added to a Camera. - * @param {Camera} camera - * @param {number} cameraX - * @param {number} cameraY - * @param {number} cameraWidth - * @param {number} cameraHeight - */ - public preRender(camera: Camera, cameraX: number, cameraY: number, cameraWidth: number, cameraHeight: number): void; - /** - * render is called during the objects render cycle, right after all transforms have finished, but before any children/image data is rendered. - * @param {Camera} camera - * @param {number} cameraX - * @param {number} cameraY - * @param {number} cameraWidth - * @param {number} cameraHeight - */ - public render(camera: Camera, cameraX: number, cameraY: number, cameraWidth: number, cameraHeight: number): void; - /** - * Post-render is called during the objects render cycle, after the children/image data has been rendered. - * It happens directly BEFORE a canvas context.restore has happened if added to a Camera. - */ - public postRender(camera: Camera, cameraX: number, cameraY: number, cameraWidth: number, cameraHeight: number): void; - /** - * Clear down this FXManager and null out references - */ - public destroy(): void; - } -} -/** -* Phaser - Verlet - Particle -* -* -*/ -module Phaser.Verlet { - class Particle { - /** - * Creates a new Particle object. - * @class Particle - * @constructor - * @param {Number} x The x coordinate of vector2 - * @param {Number} y The y coordinate of vector2 - * @return {Particle} This object - **/ - constructor(pos: Vector2); - public pos: Vector2; - public lastPos: Vector2; - public render(ctx): void; - } -} -/** -* Phaser - AngleConstraint -* -* constrains 3 particles to an angle -*/ -module Phaser.Verlet { - class AngleConstraint { - /** - * Creates a new AngleConstraint object. - * @class AngleConstraint - * @constructor - * @param {Number} x The x coordinate of vector2 - * @param {Number} y The y coordinate of vector2 - * @return {AngleConstraint} This object - **/ - constructor(a: Particle, b: Particle, c: Particle, stiffness: number); - public a: Particle; - public b: Particle; - public c: Particle; - public angle: number; - public stiffness: number; - public relax(stepCoef: number): void; - public render(ctx): void; - } -} -/** -* Phaser - DistanceConstraint -* -* Constrains to initial distance -*/ -module Phaser.Verlet { - class DistanceConstraint { - /** - * Creates a new DistanceConstraint object. - * @class DistanceConstraint - * @constructor - * @param {Number} x The x coordinate of vector2 - * @param {Number} y The y coordinate of vector2 - * @return {DistanceConstraint} This object - **/ - constructor(a: Particle, b: Particle, stiffness: number, distance?: number); - public a: Particle; - public b: Particle; - public distance: number; - public stiffness: number; - public relax(stepCoef: number): void; - public render(ctx): void; - } -} -/** -* Phaser - PinConstraint -* -* Constrains to static / fixed point -*/ -module Phaser.Verlet { - class PinConstraint { - /** - * Creates a new PinConstraint object. - * @class PinConstraint - * @constructor - * @param {Number} x The x coordinate of vector2 - * @param {Number} y The y coordinate of vector2 - * @return {PinConstraint} This object - **/ - constructor(a: Particle, pos: Vector2); - public a: Particle; - public pos: Vector2; - public relax(): void; - public render(ctx): void; - } -} -/** -* Phaser - Verlet - Composite -* -* -*/ -module Phaser.Verlet { - class Composite { - /** - * Creates a new Composite object. - * @class Composite - * @constructor - * @param {Number} x The x coordinate of vector2 - * @param {Number} y The y coordinate of vector2 - * @return {Composite} This object - **/ - constructor(game: Game); - private _game; - /** - * Texture of the particles to be rendered. - */ - private _texture; - /** - * Rendering bounds for the texture - * @type {Quad} - */ - private frameBounds; - private _sx; - private _sy; - private _sw; - private _sh; - private _dx; - private _dy; - private _dw; - private _dh; - private _hw; - private _hh; - public sprites: Sprite[]; - public particles: Particle[]; - public constraints; - public drawParticles; - public drawConstraints; - public createDistanceConstraint(a: Particle, b: Particle, stiffness: number, distance?: number): DistanceConstraint; - public createAngleConstraint(a: Particle, b: Particle, c: Particle, stiffness: number): AngleConstraint; - public createPinConstraint(a: Particle, pos: Vector2): PinConstraint; - /** - * Load a graphic for this Composite. The graphic cannot be a SpriteSheet yet. - * @param key {string} Key of the graphic you want to load for this sprite. - * @return {Composite} This object - */ - public loadGraphic(key: string): Composite; - public hideConstraints: bool; - public constraintLineColor: string; - private renderConstraints(context); - private render(context); - public pin(index, pos?): PinConstraint; + static clone(a: Vec2, out?: Vec2): Vec2; } } /** @@ -8438,15 +4849,15 @@ module Phaser { /** * A Vector object containing the initial position when the Pointer was engaged with the screen. * @property positionDown - * @type {Vector2} + * @type {Vec2} **/ - public positionDown: Vector2; + public positionDown: Vec2; /** * A Vector object containing the current position of the Pointer on the screen. * @property position - * @type {Vector2} + * @type {Vec2} **/ - public position: Vector2; + public position: Vec2; /** * A Circle object centered on the x/y screen coordinates of the Pointer. * Default size of 44px (Apple's recommended "finger tip" size) @@ -8727,92 +5138,6 @@ module Phaser { } } /** -* Phaser - Touch -* -* The Touch class handles touch interactions with the game and the resulting Pointer objects. -* http://www.w3.org/TR/touch-events/ -* https://developer.mozilla.org/en-US/docs/DOM/TouchList -* http://www.html5rocks.com/en/mobile/touchandmouse/ -* Note: Android 2.x only supports 1 touch event at once, no multi-touch -*/ -module Phaser { - class Touch { - /** - * Constructor - * @param {Game} game. - * @return {Touch} This object. - */ - constructor(game: Game); - /** - * Local private reference to game. - * @property _game - * @type {Phaser.Game} - * @private - **/ - private _game; - /** - * You can disable all Input by setting disabled = true. While set all new input related events will be ignored. - * @type {Boolean} - */ - public disabled: bool; - /** - * Starts the event listeners running - * @method start - */ - public start(): void; - /** - * Prevent iOS bounce-back (doesn't work?) - * @method consumeTouchMove - * @param {Any} event - **/ - private consumeTouchMove(event); - /** - * - * @method onTouchStart - * @param {Any} event - **/ - private onTouchStart(event); - /** - * Touch cancel - touches that were disrupted (perhaps by moving into a plugin or browser chrome) - * Occurs for example on iOS when you put down 4 fingers and the app selector UI appears - * @method onTouchCancel - * @param {Any} event - **/ - private onTouchCancel(event); - /** - * For touch enter and leave its a list of the touch points that have entered or left the target - * Doesn't appear to be supported by most browsers yet - * @method onTouchEnter - * @param {Any} event - **/ - private onTouchEnter(event); - /** - * For touch enter and leave its a list of the touch points that have entered or left the target - * Doesn't appear to be supported by most browsers yet - * @method onTouchLeave - * @param {Any} event - **/ - private onTouchLeave(event); - /** - * - * @method onTouchMove - * @param {Any} event - **/ - private onTouchMove(event); - /** - * - * @method onTouchEnd - * @param {Any} event - **/ - private onTouchEnd(event); - /** - * Stop the event listeners - * @method stop - */ - public stop(): void; - } -} -/** * Phaser - Mouse * * The Mouse class handles mouse interactions with the game and the resulting events. @@ -9018,6 +5343,92 @@ module Phaser { } } /** +* Phaser - Touch +* +* The Touch class handles touch interactions with the game and the resulting Pointer objects. +* http://www.w3.org/TR/touch-events/ +* https://developer.mozilla.org/en-US/docs/DOM/TouchList +* http://www.html5rocks.com/en/mobile/touchandmouse/ +* Note: Android 2.x only supports 1 touch event at once, no multi-touch +*/ +module Phaser { + class Touch { + /** + * Constructor + * @param {Game} game. + * @return {Touch} This object. + */ + constructor(game: Game); + /** + * Local private reference to game. + * @property _game + * @type {Phaser.Game} + * @private + **/ + private _game; + /** + * You can disable all Input by setting disabled = true. While set all new input related events will be ignored. + * @type {Boolean} + */ + public disabled: bool; + /** + * Starts the event listeners running + * @method start + */ + public start(): void; + /** + * Prevent iOS bounce-back (doesn't work?) + * @method consumeTouchMove + * @param {Any} event + **/ + private consumeTouchMove(event); + /** + * + * @method onTouchStart + * @param {Any} event + **/ + private onTouchStart(event); + /** + * Touch cancel - touches that were disrupted (perhaps by moving into a plugin or browser chrome) + * Occurs for example on iOS when you put down 4 fingers and the app selector UI appears + * @method onTouchCancel + * @param {Any} event + **/ + private onTouchCancel(event); + /** + * For touch enter and leave its a list of the touch points that have entered or left the target + * Doesn't appear to be supported by most browsers yet + * @method onTouchEnter + * @param {Any} event + **/ + private onTouchEnter(event); + /** + * For touch enter and leave its a list of the touch points that have entered or left the target + * Doesn't appear to be supported by most browsers yet + * @method onTouchLeave + * @param {Any} event + **/ + private onTouchLeave(event); + /** + * + * @method onTouchMove + * @param {Any} event + **/ + private onTouchMove(event); + /** + * + * @method onTouchEnd + * @param {Any} event + **/ + private onTouchEnd(event); + /** + * Stop the event listeners + * @method stop + */ + public stop(): void; + } +} +/** * Phaser - Input * * A game specific Input manager that looks after the mouse, keyboard and touch objects. @@ -9083,9 +5494,9 @@ module Phaser { /** * A vector object representing the current position of the Pointer. * @property vector - * @type {Vector2} + * @type {Vec2} **/ - public position: Vector2; + public position: Vec2; /** * A Circle object centered on the x/y screen coordinates of the Input. * Default size of 44px (Apples recommended "finger tip" size) but can be changed to anything @@ -9376,326 +5787,1019 @@ module Phaser { public getAngle(pointer1: Pointer, pointer2: Pointer): number; } } +module Phaser { + interface IRenderer { + render(); + renderSprite(camera: Camera, sprite: Sprite): bool; + } +} +module Phaser { + class HeadlessRenderer implements IRenderer { + constructor(game: Game); + /** + * The essential reference to the main game object + */ + private _game; + public render(): void; + public renderSprite(camera: Camera, sprite: Sprite): bool; + } +} +module Phaser { + class CanvasRenderer implements IRenderer { + constructor(game: Game); + /** + * The essential reference to the main game object + */ + private _game; + private _sx; + private _sy; + private _sw; + private _sh; + private _dx; + private _dy; + private _dw; + private _dh; + private _fx; + private _fy; + private _cameraList; + private _camera; + private _groupLength; + public render(): void; + /** + * Render this sprite to specific camera. Called by game loop after update(). + * @param camera {Camera} Camera this sprite will be rendered to. + * @return {boolean} Return false if not rendered, otherwise return true. + */ + public renderSprite(camera: Camera, sprite: Sprite): bool; + } +} /** -* Phaser - FrameData +* Phaser - Game * -* FrameData is a container for Frame objects, the internal representation of animation data in Phaser. +* This is where the magic happens. The Game object is the heart of your game, +* providing quick access to common functions and handling the boot process. +* +* "Hell, there are no rules here - we're trying to accomplish something." +* Thomas A. Edison */ module Phaser { - class FrameData { + class Game { /** - * FrameData constructor + * Game constructor + * + * Instantiate a new Phaser.Game object. + * + * @param callbackContext Which context will the callbacks be called with. + * @param parent {string} ID of its parent DOM element. + * @param width {number} The width of your game in game pixels. + * @param height {number} The height of your game in game pixels. + * @param initCallback {function} Init callback invoked when init default screen. + * @param createCallback {function} Create callback invoked when create default screen. + * @param updateCallback {function} Update callback invoked when update default screen. + * @param renderCallback {function} Render callback invoked when render default screen. + * @param destroyCallback {function} Destroy callback invoked when state is destroyed. + */ + constructor(callbackContext, parent?: string, width?: number, height?: number, initCallback?, createCallback?, updateCallback?, renderCallback?, destroyCallback?); + /** + * Game loop trigger wrapper. + */ + public _raf: RequestAnimationFrame; + /** + * Max allowable accumulation. + * @type {number} + */ + private _maxAccumulation; + /** + * Total number of milliseconds elapsed since last update loop. + * @type {number} + */ + private _accumulator; + /** + * Milliseconds of time per step of the game loop. + * @type {number} + */ + private _step; + /** + * Whether loader complete loading or not. + * @type {boolean} + */ + private _loadComplete; + /** + * Game is paused? + * @type {boolean} + */ + private _paused; + /** + * The state to be switched to in the next frame. + * @type {State} + */ + private _pendingState; + /** + * The current State object (defaults to null) + * @type {State} + */ + public state; + /** + * Context for calling the callbacks. + */ + public callbackContext; + /** + * This will be called when init states. (loading assets...) + * @type {function} + */ + public onInitCallback; + /** + * This will be called when create states. (setup states...) + * @type {function} + */ + public onCreateCallback; + /** + * This will be called when update states. + * @type {function} + */ + public onUpdateCallback; + /** + * This will be called when render states. + * @type {function} + */ + public onRenderCallback; + /** + * This will be called when states paused. + * @type {function} + */ + public onPausedCallback; + /** + * This will be called when the state is destroyed (i.e. swapping to a new state) + * @type {function} + */ + public onDestroyCallback; + /** + * Reference to the GameObject Factory. + * @type {GameObjectFactory} + */ + public add: GameObjectFactory; + /** + * Reference to the assets cache. + * @type {Cache} + */ + public cache: Cache; + /** + * Reference to the input manager + * @type {Input} + */ + public input: Input; + /** + * Reference to the assets loader. + * @type {Loader} + */ + public loader: Loader; + /** + * Reference to the math helper. + * @type {GameMath} + */ + public math: GameMath; + /** + * Reference to the sound manager. + * @type {SoundManager} + */ + public sound: SoundManager; + /** + * Reference to the stage. + * @type {Stage} + */ + public stage: Stage; + /** + * Reference to game clock. + * @type {Time} + */ + public time: Time; + /** + * Reference to the tween manager. + * @type {TweenManager} + */ + public tweens: TweenManager; + /** + * Reference to the world. + * @type {World} + */ + public world: World; + /** + * Instance of repeatable random data generator helper. + * @type {RandomDataGenerator} + */ + public rnd: RandomDataGenerator; + /** + * Contains device information and capabilities. + * @type {Device} + */ + public device: Device; + /** + * Reference to the render manager + * @type {RenderManager} + */ + public renderer: IRenderer; + /** + * Whether the game engine is booted, aka available. + * @type {boolean} + */ + public isBooted: bool; + /** + * Is game running or paused? + * @type {boolean} + */ + public isRunning: bool; + /** + * Initialize engine sub modules and start the game. + * @param parent {string} ID of parent Dom element. + * @param width {number} Width of the game screen. + * @param height {number} Height of the game screen. + */ + private boot(parent, width, height); + public setRenderer(type: number): void; + /** + * Called when the loader has finished after init was run. + */ + private loadComplete(); + /** + * Game loop method will be called when it's booting. + */ + private bootLoop(); + /** + * Game loop method will be called when it's paused. + */ + private pausedLoop(); + /** + * Game loop method will be called when it's running. + */ + private loop(); + /** + * Start current state. + */ + private startState(); + /** + * Set all state callbacks (init, create, update, render). + * @param initCallback {function} Init callback invoked when init state. + * @param createCallback {function} Create callback invoked when create state. + * @param updateCallback {function} Update callback invoked when update state. + * @param renderCallback {function} Render callback invoked when render state. + * @param destroyCallback {function} Destroy callback invoked when state is destroyed. + */ + public setCallbacks(initCallback?, createCallback?, updateCallback?, renderCallback?, destroyCallback?): void; + /** + * Switch to a new State. + * @param state {State} The state you want to switch to. + * @param [clearWorld] {boolean} clear everything in the world? (Default to true) + * @param [clearCache] {boolean} clear asset cache? (Default to false and ONLY available when clearWorld=true) + */ + public switchState(state, clearWorld?: bool, clearCache?: bool): void; + /** + * Nuke the whole game from orbit + */ + public destroy(): void; + public paused : bool; + public framerate : number; + public camera : Camera; + } +} +/** +* Phaser - Point +* +* The Point object represents a location in a two-dimensional coordinate system, where x represents the horizontal axis and y represents the vertical axis. +*/ +module Phaser { + class Point { + /** + * Creates a new Point. If you pass no parameters a Point is created set to (0,0). + * @class Point + * @constructor + * @param {Number} x The horizontal position of this Point (default 0) + * @param {Number} y The vertical position of this Point (default 0) + **/ + constructor(x?: number, y?: number); + public x: number; + public y: number; + /** + * Copies the x and y properties from any given object to this Point. + * @method copyFrom + * @param {any} source - The object to copy from. + * @return {Point} This Point object. + **/ + public copyFrom(source: any): Point; + /** + * Inverts the x and y values of this Point + * @method invert + * @return {Point} This Point object. + **/ + public invert(): Point; + /** + * Sets the x and y values of this MicroPoint object to the given coordinates. + * @method setTo + * @param {Number} x - The horizontal position of this point. + * @param {Number} y - The vertical position of this point. + * @return {MicroPoint} This MicroPoint object. Useful for chaining method calls. + **/ + public setTo(x: number, y: number): Point; + /** + * Returns a string representation of this object. + * @method toString + * @return {string} a string representation of the instance. + **/ + public toString(): string; + } +} +/** +* Rectangle +* +* @desc A Rectangle object is an area defined by its position, as indicated by its top-left corner (x,y) and width and height. +* +* @version 1.6 - 24th May 2013 +* @author Richard Davey +*/ +module Phaser { + class Rectangle { + /** + * Creates a new Rectangle object with the top-left corner specified by the x and y parameters and with the specified width and height parameters. If you call this function without parameters, a rectangle with x, y, width, and height properties set to 0 is created. + * @class Rectangle + * @constructor + * @param {Number} x The x coordinate of the top-left corner of the rectangle. + * @param {Number} y The y coordinate of the top-left corner of the rectangle. + * @param {Number} width The width of the rectangle in pixels. + * @param {Number} height The height of the rectangle in pixels. + * @return {Rectangle} This rectangle object + **/ + constructor(x?: number, y?: number, width?: number, height?: number); + /** + * The x coordinate of the top-left corner of the rectangle + * @property x + * @type Number + **/ + public x: number; + /** + * The y coordinate of the top-left corner of the rectangle + * @property y + * @type Number + **/ + public y: number; + /** + * The width of the rectangle in pixels + * @property width + * @type Number + **/ + public width: number; + /** + * The height of the rectangle in pixels + * @property height + * @type Number + **/ + public height: number; + /** + * Half of the width of the rectangle + * @property halfWidth + * @type Number + **/ + public halfWidth : number; + /** + * Half of the height of the rectangle + * @property halfHeight + * @type Number + **/ + public halfHeight : number; + /** + * 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 + * @return {Number} + **/ + /** + * 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 + **/ + public bottom : number; + /** + * Sets the bottom-right corner of the Rectangle, determined by the values of the given Point object. + * @method bottomRight + * @param {Point} value + **/ + public bottomRight : Point; + /** + * The x coordinate of the left of the Rectangle. Changing the left property of a Rectangle object has no effect on the y and height properties. However it does affect the width property, whereas changing the x value does not affect the width property. + * @method left + * @ return {number} + **/ + /** + * The x coordinate of the left of the Rectangle. Changing the left property of a Rectangle object has no effect on the y and height properties. + * However it does affect the width, whereas changing the x value does not affect the width property. + * @method left + * @param {Number} value + **/ + public left : number; + /** + * The sum of the x and width properties. Changing the right property of a Rectangle object has no effect on the x, y and height properties. + * However it does affect the width property. + * @method right + * @return {Number} + **/ + /** + * The sum of the x and width properties. Changing the right property of a Rectangle object has no effect on the x, y and height properties. + * However it does affect the width property. + * @method right + * @param {Number} value + **/ + public right : number; + /** + * The volume of the Rectangle derived from width * height + * @method volume + * @return {Number} + **/ + public volume : number; + /** + * The perimeter size of the Rectangle. This is the sum of all 4 sides. + * @method perimeter + * @return {Number} + **/ + public perimeter : number; + /** + * The y coordinate of the top of the Rectangle. Changing the top property of a Rectangle object has no effect on the x and width properties. + * However it does affect the height property, whereas changing the y value does not affect the height property. + * @method top + * @return {Number} + **/ + /** + * The y coordinate of the top of the Rectangle. Changing the top property of a Rectangle object has no effect on the x and width properties. + * However it does affect the height property, whereas changing the y value does not affect the height property. + * @method top + * @param {Number} value + **/ + public top : number; + /** + * The location of the Rectangles top-left corner, determined by the x and y coordinates of the Point. + * @method topLeft + * @param {Point} value + **/ + public topLeft : Point; + /** + * Determines whether or not this Rectangle object is empty. + * @method isEmpty + * @return {Boolean} A value of true if the Rectangle object's width or height is less than or equal to 0; otherwise false. + **/ + /** + * Sets all of the Rectangle object's properties to 0. A Rectangle object is empty if its width or height is less than or equal to 0. + * @method setEmpty + * @return {Rectangle} This rectangle object + **/ + public empty : bool; + /** + * Adjusts the location of the Rectangle object, as determined by its top-left corner, by the specified amounts. + * @method offset + * @param {Number} dx Moves the x value of the Rectangle object by this amount. + * @param {Number} dy Moves the y value of the Rectangle object by this amount. + * @return {Rectangle} This Rectangle object. + **/ + public offset(dx: number, dy: number): Rectangle; + /** + * Adjusts the location of the Rectangle object using a Point object as a parameter. This method is similar to the Rectangle.offset() method, except that it takes a Point object as a parameter. + * @method offsetPoint + * @param {Point} point A Point object to use to offset this Rectangle object. + * @return {Rectangle} This Rectangle object. + **/ + public offsetPoint(point: Point): Rectangle; + /** + * Sets the members of Rectangle to the specified values. + * @method setTo + * @param {Number} x The x coordinate of the top-left corner of the rectangle. + * @param {Number} y The y coordinate of the top-left corner of the rectangle. + * @param {Number} width The width of the rectangle in pixels. + * @param {Number} height The height of the rectangle in pixels. + * @return {Rectangle} This rectangle object + **/ + public setTo(x: number, y: number, width: number, height: number): Rectangle; + /** + * Copies the x, y, width and height properties from any given object to this Rectangle. + * @method copyFrom + * @param {any} source - The object to copy from. + * @return {Rectangle} This Rectangle object. + **/ + public copyFrom(source: any): Rectangle; + /** + * Returns a string representation of this object. + * @method toString + * @return {string} a string representation of the instance. + **/ + public toString(): string; + } +} +/** +* Phaser - CircleUtils +* +* A collection of methods useful for manipulating and comparing Circle objects. +* +* TODO: +*/ +module Phaser { + class CircleUtils { + /** + * Returns a new Circle object with the same values for the x, y, width, and height properties as the original Circle object. + * @method clone + * @param {Circle} a - The Circle object. + * @param {Circle} [optional] out Optional Circle object. If given the values will be set into the object, otherwise a brand new Circle object will be created and returned. + * @return {Phaser.Circle} + **/ + static clone(a: Circle, out?: Circle): Circle; + /** + * Return true if the given x/y coordinates are within the Circle object. + * If you need details about the intersection then use Phaser.Intersect.circleContainsPoint instead. + * @method contains + * @param {Circle} a - The Circle object. + * @param {Number} The X value of the coordinate to test. + * @param {Number} The Y value of the coordinate to test. + * @return {Boolean} True if the coordinates are within this circle, otherwise false. + **/ + static contains(a: Circle, x: number, y: number): bool; + /** + * Return true if the coordinates of the given Point object are within this Circle object. + * If you need details about the intersection then use Phaser.Intersect.circleContainsPoint instead. + * @method containsPoint + * @param {Circle} a - The Circle object. + * @param {Point} The Point object to test. + * @return {Boolean} True if the coordinates are within this circle, otherwise false. + **/ + static containsPoint(a: Circle, point: Point): bool; + /** + * Return true if the given Circle is contained entirely within this Circle object. + * If you need details about the intersection then use Phaser.Intersect.circleToCircle instead. + * @method containsCircle + * @param {Circle} The Circle object to test. + * @return {Boolean} True if the coordinates are within this circle, otherwise false. + **/ + static containsCircle(a: Circle, b: Circle): bool; + /** + * Returns the distance from the center of the Circle object to the given object (can be Circle, Point or anything with x/y properties) + * @method distanceBetween + * @param {Circle} a - The Circle object. + * @param {Circle} b - The target object. Must have visible x and y properties that represent the center of the object. + * @param {Boolean} [optional] round - Round the distance to the nearest integer (default false) + * @return {Number} The distance between this Point object and the destination Point object. + **/ + static distanceBetween(a: Circle, target: any, round?: bool): number; + /** + * Determines whether the two Circle objects match. This method compares the x, y and diameter properties. + * @method equals + * @param {Circle} a - The first Circle object. + * @param {Circle} b - The second Circle object. + * @return {Boolean} A value of true if the object has exactly the same values for the x, y and diameter properties as this Circle object; otherwise false. + **/ + static equals(a: Circle, b: Circle): bool; + /** + * Determines whether the two Circle objects intersect. + * This method checks the radius distances between the two Circle objects to see if they intersect. + * @method intersects + * @param {Circle} a - The first Circle object. + * @param {Circle} b - The second Circle object. + * @return {Boolean} A value of true if the specified object intersects with this Circle object; otherwise false. + **/ + static intersects(a: Circle, b: Circle): bool; + /** + * Returns a Point object containing the coordinates of a point on the circumference of the Circle based on the given angle. + * @method circumferencePoint + * @param {Circle} a - The first Circle object. + * @param {Number} angle The angle in radians (unless asDegrees is true) to return the point from. + * @param {Boolean} asDegrees Is the given angle in radians (false) or degrees (true)? + * @param {Phaser.Point} [optional] output An optional Point object to put the result in to. If none specified a new Point object will be created. + * @return {Phaser.Point} The Point object holding the result. + **/ + static circumferencePoint(a: Circle, angle: number, asDegrees?: bool, out?: Point): Point; + } +} +/** +* Phaser - LinkedList +* +* A miniature linked list class. Useful for optimizing time-critical or highly repetitive tasks! +*/ +module Phaser { + class LinkedList { + /** + * Creates a new link, and sets object and next to null. */ constructor(); /** - * Local frame container. + * Stores a reference to an IGameObject. */ - private _frames; + public object: IGameObject; /** - * Local frameName<->index container. + * Stores a reference to the next link in the list. */ - private _frameNames; - public total : number; + public next: LinkedList; /** - * Add a new frame. - * @param frame {Frame} The frame you want to add. - * @return {Frame} The frame you just added. + * Clean up memory. */ - public addFrame(frame: Frame): Frame; - /** - * Get a frame by its index. - * @param index {number} Index of the frame you want to get. - * @return {Frame} The frame you want. - */ - public getFrame(index: number): Frame; - /** - * Get a frame by its name. - * @param name {string} Name of the frame you want to get. - * @return {Frame} The frame you want. - */ - public getFrameByName(name: string): Frame; - /** - * Check whether there's a frame with given name. - * @param name {string} Name of the frame you want to check. - * @return {boolean} True if frame with given name found, otherwise return false. - */ - public checkFrameName(name: string): bool; - /** - * Get ranges of frames in an array. - * @param start {number} Start index of frames you want. - * @param end {number} End index of frames you want. - * @param [output] {Frame[]} result will be added into this array. - * @return {Frame[]} Ranges of specific frames in an array. - */ - public getFrameRange(start: number, end: number, output?: Frame[]): Frame[]; - /** - * Get all indexes of frames by giving their name. - * @param [output] {number[]} result will be added into this array. - * @return {number[]} Indexes of specific frames in an array. - */ - public getFrameIndexes(output?: number[]): number[]; - /** - * Get all names of frames by giving their indexes. - * @param [output] {number[]} result will be added into this array. - * @return {number[]} Names of specific frames in an array. - */ - public getFrameIndexesByName(input: string[]): number[]; - /** - * Get all frames in this frame data. - * @return {Frame[]} All the frames in an array. - */ - public getAllFrames(): Frame[]; - /** - * Get All frames with specific ranges. - * @param range {number[]} Ranges in an array. - * @return {Frame[]} All frames in an array. - */ - public getFrames(range: number[]): Frame[]; + public destroy(): void; } } /** -* Phaser - Frame +* Phaser - QuadTree * -* A Frame is a single frame of an animation and is part of a FrameData collection. +* A fairly generic quad tree structure for rapid overlap checks. QuadTree is also configured for single or dual list operation. +* You can add items either to its A list or its B list. When you do an overlap check, you can compare the A list to itself, +* or the A list against the B list. Handy for different things! */ module Phaser { - class Frame { + class QuadTree extends Rectangle { /** - * Frame constructor - * Create a new Frame with specific position, size and name. + * Instantiate a new Quad Tree node. * - * @param x {number} X position within the image to cut from. - * @param y {number} Y position within the image to cut from. - * @param width {number} Width of the frame. - * @param height {number} Height of the frame. - * @param name {string} Name of this frame. + * @param {Number} x The X-coordinate of the point in space. + * @param {Number} y The Y-coordinate of the point in space. + * @param {Number} width Desired width of this node. + * @param {Number} height Desired height of this node. + * @param {Number} parent The parent branch or node. Pass null to create a root. */ - constructor(x: number, y: number, width: number, height: number, name: string); + constructor(x: number, y: number, width: number, height: number, parent?: QuadTree); + private _iterator; + private _ot; + private _i; + private _basic; + private _members; + private _l; + private _overlapProcessed; + private _checkObject; /** - * X position within the image to cut from. - * @type {number} + * Flag for specifying that you want to add an object to the A list. */ - public x: number; + static A_LIST: number; /** - * Y position within the image to cut from. - * @type {number} + * Flag for specifying that you want to add an object to the B list. */ - public y: number; + static B_LIST: number; /** - * Width of the frame. - * @type {number} + * Controls the granularity of the quad tree. Default is 6 (decent performance on large and small worlds). */ - public width: number; + static divisions: number; /** - * Height of the frame. - * @type {number} + * Whether this branch of the tree can be subdivided or not. */ - public height: number; + private _canSubdivide; /** - * Useful for Sprite Sheets. - * @type {number} + * Refers to the internal A and B linked lists, + * which are used to store objects in the leaves. */ - public index: number; + private _headA; /** - * Useful for Texture Atlas files. (is set to the filename value) + * Refers to the internal A and B linked lists, + * which are used to store objects in the leaves. */ - public name: string; + private _tailA; /** - * Rotated? (not yet implemented) + * Refers to the internal A and B linked lists, + * which are used to store objects in the leaves. */ - public rotated: bool; + private _headB; /** - * Either cw or ccw, rotation is always 90 degrees. + * Refers to the internal A and B linked lists, + * which are used to store objects in the leaves. */ - public rotationDirection: string; + private _tailB; /** - * Was it trimmed when packed? - * @type {boolean} + * Internal, governs and assists with the formation of the tree. */ - public trimmed: bool; + private static _min; /** - * Width of the original sprite. - * @type {number} + * Internal, governs and assists with the formation of the tree. */ - public sourceSizeW: number; + private _northWestTree; /** - * Height of the original sprite. - * @type {number} + * Internal, governs and assists with the formation of the tree. */ - public sourceSizeH: number; + private _northEastTree; /** - * X position of the trimmed sprite inside original sprite. - * @type {number} + * Internal, governs and assists with the formation of the tree. */ - public spriteSourceSizeX: number; + private _southEastTree; /** - * Y position of the trimmed sprite inside original sprite. - * @type {number} + * Internal, governs and assists with the formation of the tree. */ - public spriteSourceSizeY: number; + private _southWestTree; /** - * Width of the trimmed sprite. - * @type {number} + * Internal, governs and assists with the formation of the tree. */ - public spriteSourceSizeW: number; + private _leftEdge; /** - * Height of the trimmed sprite. - * @type {number} + * Internal, governs and assists with the formation of the tree. */ - public spriteSourceSizeH: number; + private _rightEdge; /** - * Set rotation of this frame. (Not yet supported!) + * Internal, governs and assists with the formation of the tree. */ - public setRotation(rotated: bool, rotationDirection: string): void; + private _topEdge; /** - * Set trim of the frame. - * @param trimmed {boolean} Whether this frame trimmed or not. - * @param actualWidth {number} Actual width of this frame. - * @param actualHeight {number} Actual height of this frame. - * @param destX {number} Destiny x position. - * @param destY {number} Destiny y position. - * @param destWidth {number} Destiny draw width. - * @param destHeight {number} Destiny draw height. + * Internal, governs and assists with the formation of the tree. */ - public setTrim(trimmed: bool, actualWidth: number, actualHeight: number, destX: number, destY: number, destWidth: number, destHeight: number): void; - } -} -/** -* Phaser - AnimationLoader -* -* Responsible for parsing sprite sheet and JSON data into the internal FrameData format that Phaser uses for animations. -*/ -module Phaser { - class AnimationLoader { + private _bottomEdge; /** - * Parse a sprite sheet from asset data. - * @param key {string} Asset key for the sprite sheet data. - * @param frameWidth {number} Width of animation frame. - * @param frameHeight {number} Height of animation frame. - * @param frameMax {number} Number of animation frames. - * @return {FrameData} Generated FrameData object. + * Internal, governs and assists with the formation of the tree. */ - static parseSpriteSheet(game: Game, key: string, frameWidth: number, frameHeight: number, frameMax: number): FrameData; + private _halfWidth; /** - * Parse frame datas from json. - * @param json {object} Json data you want to parse. - * @return {FrameData} Generated FrameData object. + * Internal, governs and assists with the formation of the tree. */ - static parseJSONData(game: Game, json): FrameData; - static parseXMLData(game: Game, xml, format: number): FrameData; - } -} -/** -* Phaser - Animation -* -* An Animation is a single animation. It is created by the AnimationManager and belongs to Sprite objects. -*/ -module Phaser { - class Animation { + private _halfHeight; /** - * Animation constructor - * Create a new Animation. - * - * @param parent {Sprite} Owner sprite of this animation. - * @param frameData {FrameData} The FrameData object contains animation data. - * @param name {string} Unique name of this animation. - * @param frames {number[]/string[]} An array of numbers or strings indicating what frames to play in what order. - * @param delay {number} Time between frames in ms. - * @param looped {boolean} Whether or not the animation is looped or just plays once. + * Internal, governs and assists with the formation of the tree. */ - constructor(game: Game, parent: Sprite, frameData: FrameData, name: string, frames, delay: number, looped: bool); + private _midpointX; /** - * Local private reference to game. + * Internal, governs and assists with the formation of the tree. */ - private _game; + private _midpointY; /** - * Local private reference to its owner sprite. - * @type {Sprite} + * Internal, used to reduce recursive method parameters during object placement and tree formation. */ - private _parent; + private static _object; /** - * Animation frame container. - * @type {number[]} + * Internal, used during tree processing and overlap checks. */ - private _frames; + private static _list; /** - * Frame data of this animation.(parsed from sprite sheet) - * @type {FrameData} + * Internal, used during tree processing and overlap checks. */ - private _frameData; + private static _useBothLists; /** - * Index of current frame. - * @type {number} + * Internal, used during tree processing and overlap checks. */ - private _frameIndex; + private static _processingCallback; /** - * Time when switched to last frame (in ms). - * @type number + * Internal, used during tree processing and overlap checks. */ - private _timeLastFrame; + private static _notifyCallback; /** - * Time when this will switch to next frame (in ms). - * @type number + * Internal, used during tree processing and overlap checks. */ - private _timeNextFrame; + private static _callbackContext; /** - * Name of this animation. - * @type {string} + * Internal, used during tree processing and overlap checks. */ - public name: string; + private static _iterator; /** - * Currently played frame instance. - * @type {Frame} - */ - public currentFrame: Frame; - /** - * Whether or not this animation finished playing. - * @type {boolean} - */ - public isFinished: bool; - /** - * Whethor or not this animation is currently playing. - * @type {boolean} - */ - public isPlaying: bool; - /** - * Whether or not the animation is looped. - * @type {boolean} - */ - public looped: bool; - /** - * Time between frames in ms. - * @type {number} - */ - public delay: number; - public frameTotal : number; - public frame : number; - /** - * Play this animation. - * @param frameRate {number} FrameRate you want to specify instead of using default. - * @param loop {boolean} Whether or not the animation is looped or just plays once. - */ - public play(frameRate?: number, loop?: bool): void; - /** - * Play this animation from the first frame. - */ - public restart(): void; - /** - * Stop playing animation and set it finished. - */ - public stop(): void; - /** - * Update animation frames. - */ - public update(): bool; - /** - * Clean up animation memory. + * Clean up memory. */ public destroy(): void; /** - * Animation complete callback method. + * Load objects and/or groups into the quad tree, and register notify and processing callbacks. + * + * @param {} objectOrGroup1 Any object that is or extends IGameObject or Group. + * @param {} objectOrGroup2 Any object that is or extends IGameObject or Group. If null, the first parameter will be checked against itself. + * @param {Function} notifyCallback A function with the form myFunction(Object1:GameObject,Object2:GameObject) that is called whenever two objects are found to overlap in world space, and either no processCallback is specified, or the processCallback returns true. + * @param {Function} processCallback A function with the form myFunction(Object1:GameObject,Object2:GameObject):bool that is called whenever two objects are found to overlap in world space. The notifyCallback is only called if this function returns true. See GameObject.separate(). + * @param context The context in which the callbacks will be called */ - private onComplete(); + public load(objectOrGroup1, objectOrGroup2?, notifyCallback?, processCallback?, context?): void; + /** + * Call this function to add an object to the root of the tree. + * This function will recursively add all group members, but + * not the groups themselves. + * + * @param {} objectOrGroup GameObjects are just added, Groups are recursed and their applicable members added accordingly. + * @param {Number} list A uint flag indicating the list to which you want to add the objects. Options are QuadTree.A_LIST and QuadTree.B_LIST. + */ + public add(objectOrGroup, list: number): void; + /** + * Internal function for recursively navigating and creating the tree + * while adding objects to the appropriate nodes. + */ + private addObject(); + /** + * Internal function for recursively adding objects to leaf lists. + */ + private addToList(); + /** + * QuadTree's other main function. Call this after adding objects + * using QuadTree.load() to compare the objects that you loaded. + * + * @return {Boolean} Whether or not any overlaps were found. + */ + public execute(): bool; + /** + * A private for comparing an object against the contents of a node. + * + * @return {Boolean} Whether or not any overlaps were found. + */ + private overlapNode(); + } +} +/** +* Phaser - Line +* +* A Line object is an infinte line through space. The two sets of x/y coordinates define the Line Segment. +*/ +module Phaser { + class Line { + /** + * + * @constructor + * @param {Number} x1 + * @param {Number} y1 + * @param {Number} x2 + * @param {Number} y2 + * @return {Phaser.Line} This Object + */ + constructor(x1?: number, y1?: number, x2?: number, y2?: number); + /** + * + * @property x1 + * @type {Number} + */ + public x1: number; + /** + * + * @property y1 + * @type {Number} + */ + public y1: number; + /** + * + * @property x2 + * @type {Number} + */ + public x2: number; + /** + * + * @property y2 + * @type {Number} + */ + public y2: number; + /** + * + * @method clone + * @param {Phaser.Line} [output] + * @return {Phaser.Line} + */ + public clone(output?: Line): Line; + /** + * + * @method copyFrom + * @param {Phaser.Line} source + * @return {Phaser.Line} + */ + public copyFrom(source: Line): Line; + /** + * + * @method copyTo + * @param {Phaser.Line} target + * @return {Phaser.Line} + */ + public copyTo(target: Line): Line; + /** + * + * @method setTo + * @param {Number} x1 + * @param {Number} y1 + * @param {Number} x2 + * @param {Number} y2 + * @return {Phaser.Line} + */ + public setTo(x1?: number, y1?: number, x2?: number, y2?: number): Line; + public width : number; + public height : number; + /** + * + * @method length + * @return {Number} + */ + public length : number; + /** + * + * @method getY + * @param {Number} x + * @return {Number} + */ + public getY(x: number): number; + /** + * + * @method angle + * @return {Number} + */ + public angle : number; + /** + * + * @method slope + * @return {Number} + */ + public slope : number; + /** + * + * @method perpSlope + * @return {Number} + */ + public perpSlope : number; + /** + * + * @method yIntercept + * @return {Number} + */ + public yIntercept : number; + /** + * + * @method isPointOnLine + * @param {Number} x + * @param {Number} y + * @return {Boolean} + */ + public isPointOnLine(x: number, y: number): bool; + /** + * + * @method isPointOnLineSegment + * @param {Number} x + * @param {Number} y + * @return {Boolean} + */ + public isPointOnLineSegment(x: number, y: number): bool; + /** + * + * @method intersectLineLine + * @param {Any} line + * @return {Any} + */ + public intersectLineLine(line): any; + /** + * + * @method perp + * @param {Number} x + * @param {Number} y + * @param {Phaser.Line} [output] + * @return {Phaser.Line} + */ + public perp(x: number, y: number, output?: Line): Line; + /** + * + * @method toString + * @return {String} + */ + public toString(): string; + } +} +/** +* Phaser - IntersectResult +* +* A light-weight result object to hold the results of an intersection. For when you need more than just true/false. +*/ +module Phaser { + class IntersectResult { + /** + * Did they intersect or not? + * @property result + * @type {Boolean} + */ + public result: bool; + /** + * @property x + * @type {Number} + */ + public x: number; + /** + * @property y + * @type {Number} + */ + public y: number; + /** + * @property x1 + * @type {Number} + */ + public x1: number; + /** + * @property y1 + * @type {Number} + */ + public y1: number; + /** + * @property x2 + * @type {Number} + */ + public x2: number; + /** + * @property y2 + * @type {Number} + */ + public y2: number; + /** + * @property width + * @type {Number} + */ + public width: number; + /** + * @property height + * @type {Number} + */ + public height: number; + /** + * + * @method setTo + * @param {Number} x1 + * @param {Number} y1 + * @param {Number} [x2] + * @param {Number} [y2] + * @param {Number} [width] + * @param {Number} [height] + */ + public setTo(x1: number, y1: number, x2?: number, y2?: number, width?: number, height?: number): void; } } /** @@ -9725,11 +6829,6 @@ module Phaser { */ public cache: Cache; /** - * Reference to the collision helper. - * @type {Collision} - */ - public collision: Collision; - /** * Reference to the GameObject Factory. * @type {GameObjectFactory} */ @@ -9750,11 +6849,6 @@ module Phaser { */ public math: GameMath; /** - * Reference to the motion helper. - * @type {Motion} - */ - public motion: Motion; - /** * Reference to the sound manager. * @type {SoundManager} */ @@ -9805,16 +6899,5 @@ module Phaser { * This method will be called when the state is destroyed */ public destroy(): void; - /** - * Checks for overlaps between two objects using the world QuadTree. Can be GameObject vs. GameObject, GameObject vs. Group or Group vs. Group. - * Note: Does not take the objects scrollFactor into account. All overlaps are check in world space. - * @param object1 The first GameObject or Group to check. If null the world.group is used. - * @param object2 The second GameObject or Group to check. - * @param notifyCallback A callback function that is called if the objects overlap. The two objects will be passed to this function in the same order in which you passed them to Collision.overlap. - * @param processCallback A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then notifyCallback will only be called if processCallback returns true. - * @param context The context in which the callbacks will be called - * @returns {boolean} true if the objects overlap, otherwise false. - */ - public collide(objectOrGroup1?: Basic, objectOrGroup2?: Basic, notifyCallback?, context?): bool; } } diff --git a/build/phaser.js b/build/phaser.js index f7b1ad0cf..9fcb30c69 100644 --- a/build/phaser.js +++ b/build/phaser.js @@ -2685,6 +2685,206 @@ var Phaser; var Components = Phaser.Components; })(Phaser || (Phaser = {})); /// +/// +/// +/** +* Phaser - RectangleUtils +* +* A collection of methods useful for manipulating and comparing Rectangle objects. +* +* TODO: Check docs + overlap + intersect + toPolygon? +*/ +var Phaser; +(function (Phaser) { + var RectangleUtils = (function () { + function RectangleUtils() { } + RectangleUtils.getTopLeftAsPoint = /** + * Get the location of the Rectangles top-left corner as a Point object. + * @method getTopLeftAsPoint + * @param {Rectangle} a - The Rectangle object. + * @param {Point} out - Optional Point to store the value in, if not supplied a new Point object will be created. + * @return {Point} The new Point object. + **/ + function getTopLeftAsPoint(a, out) { + if (typeof out === "undefined") { out = new Phaser.Point(); } + return out.setTo(a.x, a.y); + }; + RectangleUtils.getBottomRightAsPoint = /** + * Get the location of the Rectangles bottom-right corner as a Point object. + * @method getTopLeftAsPoint + * @param {Rectangle} a - The Rectangle object. + * @param {Point} out - Optional Point to store the value in, if not supplied a new Point object will be created. + * @return {Point} The new Point object. + **/ + function getBottomRightAsPoint(a, out) { + if (typeof out === "undefined") { out = new Phaser.Point(); } + return out.setTo(a.right, a.bottom); + }; + RectangleUtils.inflate = /** + * Increases the size of the Rectangle object by the specified amounts. The center point of the Rectangle object stays the same, and its size increases to the left and right by the dx value, and to the top and the bottom by the dy value. + * @method inflate + * @param {Rectangle} a - The Rectangle object. + * @param {Number} dx The amount to be added to the left side of the Rectangle. + * @param {Number} dy The amount to be added to the bottom side of the Rectangle. + * @return {Rectangle} This Rectangle object. + **/ + function inflate(a, dx, dy) { + a.x -= dx; + a.width += 2 * dx; + a.y -= dy; + a.height += 2 * dy; + return a; + }; + RectangleUtils.inflatePoint = /** + * Increases the size of the Rectangle object. This method is similar to the Rectangle.inflate() method except it takes a Point object as a parameter. + * @method inflatePoint + * @param {Rectangle} a - The Rectangle object. + * @param {Point} point The x property of this Point object is used to increase the horizontal dimension of the Rectangle object. The y property is used to increase the vertical dimension of the Rectangle object. + * @return {Rectangle} The Rectangle object. + **/ + function inflatePoint(a, point) { + return RectangleUtils.inflate(a, point.x, point.y); + }; + RectangleUtils.size = /** + * The size of the Rectangle object, expressed as a Point object with the values of the width and height properties. + * @method size + * @param {Rectangle} a - The Rectangle object. + * @param {Point} output Optional Point object. If given the values will be set into the object, otherwise a brand new Point object will be created and returned. + * @return {Point} The size of the Rectangle object + **/ + function size(a, output) { + if (typeof output === "undefined") { output = new Phaser.Point(); } + return output.setTo(a.width, a.height); + }; + RectangleUtils.clone = /** + * Returns a new Rectangle object with the same values for the x, y, width, and height properties as the original Rectangle object. + * @method clone + * @param {Rectangle} a - The Rectangle object. + * @param {Rectangle} output Optional Rectangle object. If given the values will be set into the object, otherwise a brand new Rectangle object will be created and returned. + * @return {Rectangle} + **/ + function clone(a, output) { + if (typeof output === "undefined") { output = new Phaser.Rectangle(); } + return output.setTo(a.x, a.y, a.width, a.height); + }; + RectangleUtils.contains = /** + * Determines whether the specified coordinates are contained within the region defined by this Rectangle object. + * @method contains + * @param {Rectangle} a - The Rectangle object. + * @param {Number} x The x coordinate of the point to test. + * @param {Number} y The y coordinate of the point to test. + * @return {Boolean} A value of true if the Rectangle object contains the specified point; otherwise false. + **/ + function contains(a, x, y) { + return (x >= a.x && x <= a.right && y >= a.y && y <= a.bottom); + }; + RectangleUtils.containsPoint = /** + * Determines whether the specified point is contained within the rectangular region defined by this Rectangle object. This method is similar to the Rectangle.contains() method, except that it takes a Point object as a parameter. + * @method containsPoint + * @param {Rectangle} a - The Rectangle object. + * @param {Point} point The point object being checked. Can be Point or any object with .x and .y values. + * @return {Boolean} A value of true if the Rectangle object contains the specified point; otherwise false. + **/ + function containsPoint(a, point) { + return RectangleUtils.contains(a, point.x, point.y); + }; + RectangleUtils.containsRect = /** + * Determines whether the first Rectangle object is fully contained within the second Rectangle object. + * A Rectangle object is said to contain another if the second Rectangle object falls entirely within the boundaries of the first. + * @method containsRect + * @param {Rectangle} a - The first Rectangle object. + * @param {Rectangle} b - The second Rectangle object. + * @return {Boolean} A value of true if the Rectangle object contains the specified point; otherwise false. + **/ + function containsRect(a, b) { + // If the given rect has a larger volume than this one then it can never contain it + if(a.volume > b.volume) { + return false; + } + return (a.x >= b.x && a.y >= b.y && a.right <= b.right && a.bottom <= b.bottom); + }; + RectangleUtils.equals = /** + * Determines whether the two Rectangles are equal. + * This method compares the x, y, width and height properties of each Rectangle. + * @method equals + * @param {Rectangle} a - The first Rectangle object. + * @param {Rectangle} b - The second Rectangle object. + * @return {Boolean} A value of true if the two Rectangles have exactly the same values for the x, y, width and height properties; otherwise false. + **/ + function equals(a, b) { + return (a.x == b.x && a.y == b.y && a.width == b.width && a.height == b.height); + }; + RectangleUtils.intersection = /** + * If the Rectangle object specified in the toIntersect parameter intersects with this Rectangle object, returns the area of intersection as a Rectangle object. If the rectangles do not intersect, this method returns an empty Rectangle object with its properties set to 0. + * @method intersection + * @param {Rectangle} a - The first Rectangle object. + * @param {Rectangle} b - The second Rectangle object. + * @param {Rectangle} output Optional Rectangle object. If given the intersection values will be set into this object, otherwise a brand new Rectangle object will be created and returned. + * @return {Rectangle} A Rectangle object that equals the area of intersection. If the rectangles do not intersect, this method returns an empty Rectangle object; that is, a rectangle with its x, y, width, and height properties set to 0. + **/ + function intersection(a, b, out) { + if (typeof out === "undefined") { out = new Phaser.Rectangle(); } + if(RectangleUtils.intersects(a, b)) { + out.x = Math.max(a.x, b.x); + out.y = Math.max(a.y, b.y); + out.width = Math.min(a.right, b.right) - out.x; + out.height = Math.min(a.bottom, b.bottom) - out.y; + } + return out; + }; + RectangleUtils.intersects = /** + * Determines whether the two Rectangles intersect with each other. + * This method checks the x, y, width, and height properties of the Rectangles. + * @method intersects + * @param {Rectangle} a - The first Rectangle object. + * @param {Rectangle} b - The second Rectangle object. + * @param {Number} tolerance A tolerance value to allow for an intersection test with padding, default to 0 + * @return {Boolean} A value of true if the specified object intersects with this Rectangle object; otherwise false. + **/ + function intersects(a, b, tolerance) { + if (typeof tolerance === "undefined") { tolerance = 0; } + // ? + //return (a.right > b.x) && (a.x < b.right) && (a.bottom > b.y) && (a.y < b.bottom); + return !(a.left > b.right + tolerance || a.right < b.left - tolerance || a.top > b.bottom + tolerance || a.bottom < b.top - tolerance); + //if (a.x >= b.right || a.right <= b.x || a.bottom <= b.y || a.y >= b.bottom) + //{ + // return false; + //} + //return true; + }; + RectangleUtils.intersectsRaw = /** + * Determines whether the object specified intersects (overlaps) with the given values. + * @method intersectsRaw + * @param {Number} left + * @param {Number} right + * @param {Number} top + * @param {Number} bottomt + * @param {Number} tolerance A tolerance value to allow for an intersection test with padding, default to 0 + * @return {Boolean} A value of true if the specified object intersects with the Rectangle; otherwise false. + **/ + function intersectsRaw(a, left, right, top, bottom, tolerance) { + if (typeof tolerance === "undefined") { tolerance = 0; } + return !(left > a.right + tolerance || right < a.left - tolerance || top > a.bottom + tolerance || bottom < a.top - tolerance); + }; + RectangleUtils.union = /** + * Adds two rectangles together to create a new Rectangle object, by filling in the horizontal and vertical space between the two rectangles. + * @method union + * @param {Rectangle} a - The first Rectangle object. + * @param {Rectangle} b - The second Rectangle object. + * @param {Rectangle} output Optional Rectangle object. If given the new values will be set into this object, otherwise a brand new Rectangle object will be created and returned. + * @return {Rectangle} A Rectangle object that is the union of the two rectangles. + **/ + function union(a, b, out) { + if (typeof out === "undefined") { out = new Phaser.Rectangle(); } + return out.setTo(Math.min(a.x, b.x), Math.min(a.y, b.y), Math.max(a.right, b.right), Math.max(a.bottom, b.bottom)); + }; + return RectangleUtils; + })(); + Phaser.RectangleUtils = RectangleUtils; +})(Phaser || (Phaser = {})); +/// +/// +/// /** * Phaser - DynamicTexture * @@ -2847,20 +3047,20 @@ var Phaser; */ function (sourceTexture, sourceRect, destPoint) { // Swap for drawImage if the sourceRect is the same size as the sourceTexture to avoid a costly getImageData call - if(sourceRect.equals(this.bounds) == true) { + if(Phaser.RectangleUtils.equals(sourceRect, this.bounds) == true) { this.context.drawImage(sourceTexture.canvas, destPoint.x, destPoint.y); } else { this.context.putImageData(sourceTexture.getPixels(sourceRect), destPoint.x, destPoint.y); } }; DynamicTexture.prototype.assignCanvasToGameObjects = /** - * Given an array of GameObjects it will update each of them so that their canvas/contexts reference this DynamicTexture + * Given an array of Sprites it will update each of them so that their canvas/contexts reference this DynamicTexture * @param objects {Array} An array of GameObjects, or objects that inherit from it such as Sprites */ function (objects) { for(var i = 0; i < objects.length; i++) { - objects[i].canvas = this.canvas; - objects[i].context = this.context; + objects[i].texture.canvas = this.canvas; + objects[i].texture.context = this.context; } }; DynamicTexture.prototype.clear = /** @@ -3494,50 +3694,6 @@ var Phaser; function setBounds(x, y, width, height) { //this.worldBounds = new Quad(x, y, width, height); }; - SpriteUtils.loadTexture = /** - * Load graphic for this sprite. (graphic can be SpriteSheet or Texture) - * @param key {string} Key of the graphic you want to load for this sprite. - * @param clearAnimations {boolean} If this Sprite has a set of animation data already loaded you can choose to keep or clear it with this boolean - * @return {Sprite} Sprite instance itself. - */ - function loadTexture(sprite, key, clearAnimations) { - if (typeof clearAnimations === "undefined") { clearAnimations = true; } - //if (clearAnimations && sprite.animations.frameData !== null) - //{ - // sprite.animations.destroy(); - //} - if(sprite.game.cache.getImage(key) !== null) { - if(sprite.game.cache.isSpriteSheet(key)) { - sprite.texture.setTo(null, sprite.game.cache.getImage(key)); - //sprite.animations.loadFrameData(sprite._game.cache.getFrameData(key)); - //sprite.collisionMask.width = sprite.animations.currentFrame.width; - //sprite.collisionMask.height = sprite.animations.currentFrame.height; - } else { - sprite.texture.setTo(sprite.game.cache.getImage(key), null); - sprite.frameBounds.width = sprite.texture.width; - sprite.frameBounds.height = sprite.texture.height; - //sprite.collisionMask.width = sprite._texture.width; - //sprite.collisionMask.height = sprite._texture.height; - } - } - return sprite; - }; - SpriteUtils.loadDynamicTexture = /** - * Load a DynamicTexture as its texture. - * @param texture {DynamicTexture} The texture object to be used by this sprite. - * @return {Sprite} Sprite instance itself. - */ - function loadDynamicTexture(sprite, texture) { - //if (sprite.animations.frameData !== null) - //{ - // sprite.animations.destroy(); - //} - //sprite._texture = texture; - //sprite.frameBounds.width = sprite._texture.width; - //sprite.frameBounds.height = sprite._texture.height; - //sprite._dynamicTexture = true; - return sprite; - }; return SpriteUtils; })(); Phaser.SpriteUtils = SpriteUtils; @@ -3602,6 +3758,7 @@ var Phaser; * @type {boolean} */ this.flippedY = false; + this._game = parent.game; this._sprite = parent; this.canvas = canvas; this.context = context; @@ -3638,7 +3795,23 @@ var Phaser; */ function (key, clearAnimations) { if (typeof clearAnimations === "undefined") { clearAnimations = true; } - return Phaser.SpriteUtils.loadTexture(this._sprite, key, clearAnimations); + //if (clearAnimations && sprite.animations.frameData !== null) + //{ + // sprite.animations.destroy(); + //} + if(this._game.cache.getImage(key) !== null) { + this.setTo(this._game.cache.getImage(key), null); + if(this._game.cache.isSpriteSheet(key)) { + //sprite.animations.loadFrameData(sprite._game.cache.getFrameData(key)); + //sprite.collisionMask.width = sprite.animations.currentFrame.width; + //sprite.collisionMask.height = sprite.animations.currentFrame.height; + } else { + this._sprite.frameBounds.width = this.width; + this._sprite.frameBounds.height = this.height; + //sprite.collisionMask.width = sprite._texture.width; + //sprite.collisionMask.height = sprite._texture.height; + } + } }; Texture.prototype.loadDynamicTexture = /** * Load a DynamicTexture as its texture. @@ -3646,7 +3819,13 @@ var Phaser; * @return {Sprite} Sprite instance itself. */ function (texture) { - return Phaser.SpriteUtils.loadDynamicTexture(this._sprite, texture); + //if (sprite.animations.frameData !== null) + //{ + // sprite.animations.destroy(); + //} + this.setTo(null, texture); + this._sprite.frameBounds.width = this.width; + this._sprite.frameBounds.height = this.height; }; Object.defineProperty(Texture.prototype, "width", { get: /** @@ -3719,11 +3898,88 @@ var Phaser; this.active = true; this.visible = true; this.alive = true; + this.frameBounds = new Phaser.Rectangle(x, y, width, height); + this.origin = new Phaser.Vec2(0, 0); this.scrollFactor = new Phaser.Vec2(1, 1); this.scale = new Phaser.Vec2(1, 1); this.position = new Phaser.Components.Position(this, x, y); this.texture = new Phaser.Components.Texture(this, key, game.stage.canvas, game.stage.context); + this.width = this.frameBounds.width; + this.height = this.frameBounds.height; + this.rotation = this.position.rotation; } + Sprite.prototype.preUpdate = /** + * Pre-update is called right before update() on each object in the game loop. + */ + function () { + //this.last.x = this.frameBounds.x; + //this.last.y = this.frameBounds.y; + //this.collisionMask.preUpdate(); + }; + Sprite.prototype.update = /** + * Override this function to update your class's position and appearance. + */ + function () { + }; + Sprite.prototype.postUpdate = /** + * Automatically called after update() by the game loop. + */ + function () { + /* + this.animations.update(); + + if (this.moves) + { + this.updateMotion(); + } + + if (this.worldBounds != null) + { + if (this.outOfBoundsAction == GameObject.OUT_OF_BOUNDS_KILL) + { + if (this.x < this.worldBounds.x || this.x > this.worldBounds.right || this.y < this.worldBounds.y || this.y > this.worldBounds.bottom) + { + this.kill(); + } + } + else + { + if (this.x < this.worldBounds.x) + { + this.x = this.worldBounds.x; + } + else if (this.x > this.worldBounds.right) + { + this.x = this.worldBounds.right; + } + + if (this.y < this.worldBounds.y) + { + this.y = this.worldBounds.y; + } + else if (this.y > this.worldBounds.bottom) + { + this.y = this.worldBounds.bottom; + } + } + } + + this.collisionMask.update(); + + if (this.inputEnabled) + { + this.updateInput(); + } + + this.wasTouching = this.touching; + this.touching = Collision.NONE; + */ + }; + Sprite.prototype.destroy = /** + * Clean up memory. + */ + function () { + }; Object.defineProperty(Sprite.prototype, "x", { get: /** * x value of the object. @@ -3763,6 +4019,19 @@ var Phaser; enumerable: true, configurable: true }); + Object.defineProperty(Sprite.prototype, "rotation", { + get: /** + * rotation value of the object. + */ + function () { + return this.position.rotation; + }, + set: function (value) { + this.position.rotation = value; + }, + enumerable: true, + configurable: true + }); return Sprite; })(); Phaser.Sprite = Sprite; @@ -4935,6 +5204,13 @@ var Phaser; } return this; }; + Tween.prototype.clear = function () { + this._chainedTweens = []; + this.onStart.removeAll(); + this.onUpdate.removeAll(); + this.onComplete.removeAll(); + return this; + }; Tween.prototype.stop = /** * Stop tweening. */ @@ -5109,7 +5385,7 @@ var Phaser; if (typeof maxSize === "undefined") { maxSize = 0; } return this._world.group.add(new Phaser.Group(this._game, maxSize)); }; - GameObjectFactory.prototype.tilemap = /** + GameObjectFactory.prototype.tween = /** * Create a new Particle. * * @return {Particle} The newly created particle object. @@ -5152,13 +5428,10 @@ var Phaser; * @param [tileHeight] {number} height of each tile. * @return {Tilemap} The newly created tilemap object. */ - function (key, mapData, format, resizeWorld, tileWidth, tileHeight) { - if (typeof resizeWorld === "undefined") { resizeWorld = true; } - if (typeof tileWidth === "undefined") { tileWidth = 0; } - if (typeof tileHeight === "undefined") { tileHeight = 0; } - return this._world.group.add(new Tilemap(this._game, key, mapData, format, resizeWorld, tileWidth, tileHeight)); - }; - GameObjectFactory.prototype.tween = /** + //public tilemap(key: string, mapData: string, format: number, resizeWorld: bool = true, tileWidth?: number = 0, tileHeight?: number = 0): Tilemap { + // return this._world.group.add(new Tilemap(this._game, key, mapData, format, resizeWorld, tileWidth, tileHeight)); + //} + /** * Create a tween object for a specific object. * * @param obj Object you wish the tween will affect. @@ -5177,7 +5450,7 @@ var Phaser; function (sprite) { return this._world.group.add(sprite); }; - GameObjectFactory.prototype.existingTilemap = /** + GameObjectFactory.prototype.existingTween = /** * Add an existing GeomSprite to the current world. * Note: This doesn't check or update the objects reference to Game. If that is wrong, all kinds of things will break. * @@ -5214,10 +5487,10 @@ var Phaser; * @param tilemap The Tilemap to add to the Game World * @return {Phaser.Tilemap} The Tilemap object */ - function (tilemap) { - return this._world.group.add(tilemap); - }; - GameObjectFactory.prototype.existingTween = /** + //public existingTilemap(tilemap: Tilemap): Tilemap { + // return this._world.group.add(tilemap); + //} + /** * Add an existing Tween to the current world. * Note: This doesn't check or update the objects reference to Game. If that is wrong, all kinds of things will break. * @@ -7971,6 +8244,497 @@ var Phaser; Phaser.RequestAnimationFrame = RequestAnimationFrame; })(Phaser || (Phaser = {})); /// +/// +/** +* Phaser - PointUtils +* +* A collection of methods useful for manipulating and comparing Point objects. +* +* TODO: interpolate & polar +*/ +var Phaser; +(function (Phaser) { + var PointUtils = (function () { + function PointUtils() { } + PointUtils.add = /** + * Adds the coordinates of two points together to create a new point. + * @method add + * @param {Point} a - The first Point object. + * @param {Point} b - The second Point object. + * @param {Point} out - Optional Point to store the value in, if not supplied a new Point object will be created. + * @return {Point} The new Point object. + **/ + function add(a, b, out) { + if (typeof out === "undefined") { out = new Phaser.Point(); } + return out.setTo(a.x + b.x, a.y + b.y); + }; + PointUtils.subtract = /** + * Subtracts the coordinates of two points to create a new point. + * @method subtract + * @param {Point} a - The first Point object. + * @param {Point} b - The second Point object. + * @param {Point} out - Optional Point to store the value in, if not supplied a new Point object will be created. + * @return {Point} The new Point object. + **/ + function subtract(a, b, out) { + if (typeof out === "undefined") { out = new Phaser.Point(); } + return out.setTo(a.x - b.x, a.y - b.y); + }; + PointUtils.multiply = /** + * Multiplies the coordinates of two points to create a new point. + * @method subtract + * @param {Point} a - The first Point object. + * @param {Point} b - The second Point object. + * @param {Point} out - Optional Point to store the value in, if not supplied a new Point object will be created. + * @return {Point} The new Point object. + **/ + function multiply(a, b, out) { + if (typeof out === "undefined") { out = new Phaser.Point(); } + return out.setTo(a.x * b.x, a.y * b.y); + }; + PointUtils.divide = /** + * Divides the coordinates of two points to create a new point. + * @method subtract + * @param {Point} a - The first Point object. + * @param {Point} b - The second Point object. + * @param {Point} out - Optional Point to store the value in, if not supplied a new Point object will be created. + * @return {Point} The new Point object. + **/ + function divide(a, b, out) { + if (typeof out === "undefined") { out = new Phaser.Point(); } + return out.setTo(a.x / b.x, a.y / b.y); + }; + PointUtils.clamp = /** + * Clamps the Point object values to be between the given min and max + * @method clamp + * @param {Point} a - The point. + * @param {number} The minimum value to clamp this Point to + * @param {number} The maximum value to clamp this Point to + * @return {Point} This Point object. + **/ + function clamp(a, min, max) { + PointUtils.clampX(a, min, max); + PointUtils.clampY(a, min, max); + return a; + }; + PointUtils.clampX = /** + * Clamps the x value of the given Point object to be between the min and max values. + * @method clampX + * @param {Point} a - The point. + * @param {number} The minimum value to clamp this Point to + * @param {number} The maximum value to clamp this Point to + * @return {Point} This Point object. + **/ + function clampX(a, min, max) { + a.x = Math.max(Math.min(a.x, max), min); + return a; + }; + PointUtils.clampY = /** + * Clamps the y value of the given Point object to be between the min and max values. + * @method clampY + * @param {Point} a - The point. + * @param {number} The minimum value to clamp this Point to + * @param {number} The maximum value to clamp this Point to + * @return {Point} This Point object. + **/ + function clampY(a, min, max) { + a.y = Math.max(Math.min(a.y, max), min); + return a; + }; + PointUtils.clone = /** + * Creates a copy of the given Point. + * @method clone + * @param {Point} output Optional Point object. If given the values will be set into this object, otherwise a brand new Point object will be created and returned. + * @return {Point} The new Point object. + **/ + function clone(a, output) { + if (typeof output === "undefined") { output = new Phaser.Point(); } + return output.setTo(a.x, a.y); + }; + PointUtils.distanceBetween = /** + * Returns the distance between the two given Point objects. + * @method distanceBetween + * @param {Point} a - The first Point object. + * @param {Point} b - The second Point object. + * @param {Boolean} round - Round the distance to the nearest integer (default false) + * @return {Number} The distance between the two Point objects. + **/ + function distanceBetween(a, b, round) { + if (typeof round === "undefined") { round = false; } + var dx = a.x - b.x; + var dy = a.y - b.y; + if(round === true) { + return Math.round(Math.sqrt(dx * dx + dy * dy)); + } else { + return Math.sqrt(dx * dx + dy * dy); + } + }; + PointUtils.equals = /** + * Determines whether the two given Point objects are equal. They are considered equal if they have the same x and y values. + * @method equals + * @param {Point} a - The first Point object. + * @param {Point} b - The second Point object. + * @return {Boolean} A value of true if the Points are equal, otherwise false. + **/ + function equals(a, b) { + return (a.x == b.x && a.y == b.y); + }; + PointUtils.rotate = /** + * Determines a point between two specified points. The parameter f determines where the new interpolated point is located relative to the two end points specified by parameters pt1 and pt2. + * The closer the value of the parameter f is to 1.0, the closer the interpolated point is to the first point (parameter pt1). The closer the value of the parameter f is to 0, the closer the interpolated point is to the second point (parameter pt2). + * @method interpolate + * @param {Point} pointA - The first Point object. + * @param {Point} pointB - The second Point object. + * @param {Number} f - The level of interpolation between the two points. Indicates where the new point will be, along the line between pt1 and pt2. If f=1, pt1 is returned; if f=0, pt2 is returned. + * @return {Point} The new interpolated Point object. + **/ + //static interpolate(pointA, pointB, f) { + //} + /** + * Converts a pair of polar coordinates to a Cartesian point coordinate. + * @method polar + * @param {Number} length - The length coordinate of the polar pair. + * @param {Number} angle - The angle, in radians, of the polar pair. + * @return {Point} The new Cartesian Point object. + **/ + //static polar(length, angle) { + //} + /** + * Rotates a Point around the x/y coordinates given to the desired angle. + * @param a {Point} The Point object to rotate. + * @param x {number} The x coordinate of the anchor point + * @param y {number} The y coordinate of the anchor point + * @param {Number} angle The angle in radians (unless asDegrees is true) to rotate the Point to. + * @param {Boolean} asDegrees Is the given angle in radians (false) or degrees (true)? + * @param {Number} distance An optional distance constraint between the Point and the anchor. + * @return The modified point object + */ + function rotate(a, x, y, angle, asDegrees, distance) { + if (typeof asDegrees === "undefined") { asDegrees = false; } + if (typeof distance === "undefined") { distance = null; } + if(asDegrees) { + angle = angle * Phaser.GameMath.DEG_TO_RAD; + } + // Get distance from origin (cx/cy) to this point + if(distance === null) { + distance = Math.sqrt(((x - a.x) * (x - a.x)) + ((y - a.y) * (y - a.y))); + } + return a.setTo(x + distance * Math.cos(angle), y + distance * Math.sin(angle)); + }; + PointUtils.rotateAroundPoint = /** + * Rotates a Point around the given Point to the desired angle. + * @param a {Point} The Point object to rotate. + * @param b {Point} The Point object to serve as point of rotation. + * @param x {number} The x coordinate of the anchor point + * @param y {number} The y coordinate of the anchor point + * @param {Number} angle The angle in radians (unless asDegrees is true) to rotate the Point to. + * @param {Boolean} asDegrees Is the given angle in radians (false) or degrees (true)? + * @param {Number} distance An optional distance constraint between the Point and the anchor. + * @return The modified point object + */ + function rotateAroundPoint(a, b, angle, asDegrees, distance) { + if (typeof asDegrees === "undefined") { asDegrees = false; } + if (typeof distance === "undefined") { distance = null; } + return PointUtils.rotate(a, b.x, b.y, angle, asDegrees, distance); + }; + return PointUtils; + })(); +})(Phaser || (Phaser = {})); +/// +/// +/** +* Phaser - Vec2Utils +* +* A collection of methods useful for manipulating and performing operations on 2D vectors. +* +*/ +var Phaser; +(function (Phaser) { + var Vec2Utils = (function () { + function Vec2Utils() { } + Vec2Utils.add = /** + * Adds two 2D vectors. + * + * @param {Vec2} a Reference to a source Vec2 object. + * @param {Vec2} b Reference to a source Vec2 object. + * @param {Vec2} out The output Vec2 that is the result of the operation. + * @return {Vec2} A Vec2 that is the sum of the two vectors. + */ + function add(a, b, out) { + if (typeof out === "undefined") { out = new Phaser.Vec2(); } + return out.setTo(a.x + b.x, a.y + b.y); + }; + Vec2Utils.subtract = /** + * Subtracts two 2D vectors. + * + * @param {Vec2} a Reference to a source Vec2 object. + * @param {Vec2} b Reference to a source Vec2 object. + * @param {Vec2} out The output Vec2 that is the result of the operation. + * @return {Vec2} A Vec2 that is the difference of the two vectors. + */ + function subtract(a, b, out) { + if (typeof out === "undefined") { out = new Phaser.Vec2(); } + return out.setTo(a.x - b.x, a.y - b.y); + }; + Vec2Utils.multiply = /** + * Multiplies two 2D vectors. + * + * @param {Vec2} a Reference to a source Vec2 object. + * @param {Vec2} b Reference to a source Vec2 object. + * @param {Vec2} out The output Vec2 that is the result of the operation. + * @return {Vec2} A Vec2 that is the sum of the two vectors multiplied. + */ + function multiply(a, b, out) { + if (typeof out === "undefined") { out = new Phaser.Vec2(); } + return out.setTo(a.x * b.x, a.y * b.y); + }; + Vec2Utils.divide = /** + * Divides two 2D vectors. + * + * @param {Vec2} a Reference to a source Vec2 object. + * @param {Vec2} b Reference to a source Vec2 object. + * @param {Vec2} out The output Vec2 that is the result of the operation. + * @return {Vec2} A Vec2 that is the sum of the two vectors divided. + */ + function divide(a, b, out) { + if (typeof out === "undefined") { out = new Phaser.Vec2(); } + return out.setTo(a.x / b.x, a.y / b.y); + }; + Vec2Utils.scale = /** + * Scales a 2D vector. + * + * @param {Vec2} a Reference to a source Vec2 object. + * @param {number} s Scaling value. + * @param {Vec2} out The output Vec2 that is the result of the operation. + * @return {Vec2} A Vec2 that is the scaled vector. + */ + function scale(a, s, out) { + if (typeof out === "undefined") { out = new Phaser.Vec2(); } + return out.setTo(a.x * s, a.y * s); + }; + Vec2Utils.perp = /** + * Rotate a 2D vector by 90 degrees. + * + * @param {Vec2} a Reference to a source Vec2 object. + * @param {Vec2} out The output Vec2 that is the result of the operation. + * @return {Vec2} A Vec2 that is the scaled vector. + */ + function perp(a, out) { + if (typeof out === "undefined") { out = new Phaser.Vec2(); } + return out.setTo(a.y, -a.x); + }; + Vec2Utils.equals = /** + * Checks if two 2D vectors are equal. + * + * @param {Vec2} a Reference to a source Vec2 object. + * @param {Vec2} b Reference to a source Vec2 object. + * @return {Boolean} + */ + function equals(a, b) { + return a.x == b.x && a.y == b.y; + }; + Vec2Utils.epsilonEquals = /** + * + * + * @param {Vec2} a Reference to a source Vec2 object. + * @param {Vec2} b Reference to a source Vec2 object. + * @param {Vec2} epsilon + * @return {Boolean} + */ + function epsilonEquals(a, b, epsilon) { + return Math.abs(a.x - b.x) <= epsilon && Math.abs(a.y - b.y) <= epsilon; + }; + Vec2Utils.distance = /** + * Get the distance between two 2D vectors. + * + * @param {Vec2} a Reference to a source Vec2 object. + * @param {Vec2} b Reference to a source Vec2 object. + * @return {Number} + */ + function distance(a, b) { + return Math.sqrt(Vec2Utils.distanceSq(a, b)); + }; + Vec2Utils.distanceSq = /** + * Get the distance squared between two 2D vectors. + * + * @param {Vec2} a Reference to a source Vec2 object. + * @param {Vec2} b Reference to a source Vec2 object. + * @return {Number} + */ + function distanceSq(a, b) { + return ((a.x - b.x) * (a.x - b.x)) + ((a.y - b.y) * (a.y - b.y)); + }; + Vec2Utils.project = /** + * Project two 2D vectors onto another vector. + * + * @param {Vec2} a Reference to a source Vec2 object. + * @param {Vec2} b Reference to a source Vec2 object. + * @param {Vec2} out The output Vec2 that is the result of the operation. + * @return {Vec2} A Vec2. + */ + function project(a, b, out) { + if (typeof out === "undefined") { out = new Phaser.Vec2(); } + var amt = a.dot(b) / b.lengthSq(); + if(amt != 0) { + out.setTo(amt * b.x, amt * b.y); + } + return out; + }; + Vec2Utils.projectUnit = /** + * Project this vector onto a vector of unit length. + * + * @param {Vec2} a Reference to a source Vec2 object. + * @param {Vec2} b Reference to a source Vec2 object. + * @param {Vec2} out The output Vec2 that is the result of the operation. + * @return {Vec2} A Vec2. + */ + function projectUnit(a, b, out) { + if (typeof out === "undefined") { out = new Phaser.Vec2(); } + var amt = a.dot(b); + if(amt != 0) { + out.setTo(amt * b.x, amt * b.y); + } + return out; + }; + Vec2Utils.normalRightHand = /** + * Right-hand normalize (make unit length) a 2D vector. + * + * @param {Vec2} a Reference to a source Vec2 object. + * @param {Vec2} out The output Vec2 that is the result of the operation. + * @return {Vec2} A Vec2. + */ + function normalRightHand(a, out) { + if (typeof out === "undefined") { out = this; } + return out.setTo(a.y * -1, a.x); + }; + Vec2Utils.normalize = /** + * Normalize (make unit length) a 2D vector. + * + * @param {Vec2} a Reference to a source Vec2 object. + * @param {Vec2} out The output Vec2 that is the result of the operation. + * @return {Vec2} A Vec2. + */ + function normalize(a, out) { + if (typeof out === "undefined") { out = new Phaser.Vec2(); } + var m = a.length(); + if(m != 0) { + out.setTo(a.x / m, a.y / m); + } + return out; + }; + Vec2Utils.dot = /** + * The dot product of two 2D vectors. + * + * @param {Vec2} a Reference to a source Vec2 object. + * @param {Vec2} b Reference to a source Vec2 object. + * @return {Number} + */ + function dot(a, b) { + return ((a.x * b.x) + (a.y * b.y)); + }; + Vec2Utils.cross = /** + * The cross product of two 2D vectors. + * + * @param {Vec2} a Reference to a source Vec2 object. + * @param {Vec2} b Reference to a source Vec2 object. + * @return {Number} + */ + function cross(a, b) { + return ((a.x * b.y) - (a.y * b.x)); + }; + Vec2Utils.angle = /** + * The angle between two 2D vectors. + * + * @param {Vec2} a Reference to a source Vec2 object. + * @param {Vec2} b Reference to a source Vec2 object. + * @return {Number} + */ + function angle(a, b) { + return Math.atan2(a.x * b.y - a.y * b.x, a.x * b.x + a.y * b.y); + }; + Vec2Utils.angleSq = /** + * The angle squared between two 2D vectors. + * + * @param {Vec2} a Reference to a source Vec2 object. + * @param {Vec2} b Reference to a source Vec2 object. + * @return {Number} + */ + function angleSq(a, b) { + return a.subtract(b).angle(b.subtract(a)); + }; + Vec2Utils.rotate = /** + * Rotate a 2D vector around the origin to the given angle (theta). + * + * @param {Vec2} a Reference to a source Vec2 object. + * @param {Vec2} b Reference to a source Vec2 object. + * @param {Number} theta The angle of rotation in radians. + * @param {Vec2} out The output Vec2 that is the result of the operation. + * @return {Vec2} A Vec2. + */ + function rotate(a, b, theta, out) { + if (typeof out === "undefined") { out = new Phaser.Vec2(); } + var x = a.x - b.x; + var y = a.y - b.y; + return out.setTo(x * Math.cos(theta) - y * Math.sin(theta) + b.x, x * Math.sin(theta) + y * Math.cos(theta) + b.y); + }; + Vec2Utils.clone = /** + * Clone a 2D vector. + * + * @param {Vec2} a Reference to a source Vec2 object. + * @param {Vec2} out The output Vec2 that is the result of the operation. + * @return {Vec2} A Vec2 that is a copy of the source Vec2. + */ + function clone(a, out) { + if (typeof out === "undefined") { out = new Phaser.Vec2(); } + return out.setTo(a.x, a.y); + }; + return Vec2Utils; + })(); + Phaser.Vec2Utils = Vec2Utils; + /** + * Reflect this vector on an arbitrary axis. + * + * @param {Vec2} axis The vector representing the axis. + * @return {Vec2} This for chaining. + */ + /* + static reflect(axis): Vec2 { + + var x = this.x; + var y = this.y; + this.project(axis).scale(2); + this.x -= x; + this.y -= y; + + return this; + + } + */ + /** + * Reflect this vector on an arbitrary axis (represented by a unit vector) + * + * @param {Vec2} axis The unit vector representing the axis. + * @return {Vec2} This for chaining. + */ + /* + static reflectN(axis): Vec2 { + + var x = this.x; + var y = this.y; + this.projectN(axis).scale(2); + this.x -= x; + this.y -= y; + + return this; + + } + + static getMagnitude(): number { + return Math.sqrt(Math.pow(this.x, 2) + Math.pow(this.y, 2)); + } + */ + })(Phaser || (Phaser = {})); +/// /// /** * Phaser - Pointer @@ -8510,503 +9274,507 @@ var Phaser; Phaser.Gestures = Gestures; })(Phaser || (Phaser = {})); /// -/// /** -* Phaser - PointUtils +* Phaser - Mouse * -* A collection of methods useful for manipulating and comparing Point objects. -* -* TODO: interpolate & polar +* The Mouse class handles mouse interactions with the game and the resulting events. */ var Phaser; (function (Phaser) { - var PointUtils = (function () { - function PointUtils() { } - PointUtils.add = /** - * Adds the coordinates of two points together to create a new point. - * @method add - * @param {Point} a - The first Point object. - * @param {Point} b - The second Point object. - * @param {Point} out - Optional Point to store the value in, if not supplied a new Point object will be created. - * @return {Point} The new Point object. - **/ - function add(a, b, out) { - if (typeof out === "undefined") { out = new Phaser.Point(); } - return out.setTo(a.x + b.x, a.y + b.y); - }; - PointUtils.subtract = /** - * Subtracts the coordinates of two points to create a new point. - * @method subtract - * @param {Point} a - The first Point object. - * @param {Point} b - The second Point object. - * @param {Point} out - Optional Point to store the value in, if not supplied a new Point object will be created. - * @return {Point} The new Point object. - **/ - function subtract(a, b, out) { - if (typeof out === "undefined") { out = new Phaser.Point(); } - return out.setTo(a.x - b.x, a.y - b.y); - }; - PointUtils.multiply = /** - * Multiplies the coordinates of two points to create a new point. - * @method subtract - * @param {Point} a - The first Point object. - * @param {Point} b - The second Point object. - * @param {Point} out - Optional Point to store the value in, if not supplied a new Point object will be created. - * @return {Point} The new Point object. - **/ - function multiply(a, b, out) { - if (typeof out === "undefined") { out = new Phaser.Point(); } - return out.setTo(a.x * b.x, a.y * b.y); - }; - PointUtils.divide = /** - * Divides the coordinates of two points to create a new point. - * @method subtract - * @param {Point} a - The first Point object. - * @param {Point} b - The second Point object. - * @param {Point} out - Optional Point to store the value in, if not supplied a new Point object will be created. - * @return {Point} The new Point object. - **/ - function divide(a, b, out) { - if (typeof out === "undefined") { out = new Phaser.Point(); } - return out.setTo(a.x / b.x, a.y / b.y); - }; - PointUtils.clamp = /** - * Clamps the Point object values to be between the given min and max - * @method clamp - * @param {Point} a - The point. - * @param {number} The minimum value to clamp this Point to - * @param {number} The maximum value to clamp this Point to - * @return {Point} This Point object. - **/ - function clamp(a, min, max) { - PointUtils.clampX(a, min, max); - PointUtils.clampY(a, min, max); - return a; - }; - PointUtils.clampX = /** - * Clamps the x value of the given Point object to be between the min and max values. - * @method clampX - * @param {Point} a - The point. - * @param {number} The minimum value to clamp this Point to - * @param {number} The maximum value to clamp this Point to - * @return {Point} This Point object. - **/ - function clampX(a, min, max) { - a.x = Math.max(Math.min(a.x, max), min); - return a; - }; - PointUtils.clampY = /** - * Clamps the y value of the given Point object to be between the min and max values. - * @method clampY - * @param {Point} a - The point. - * @param {number} The minimum value to clamp this Point to - * @param {number} The maximum value to clamp this Point to - * @return {Point} This Point object. - **/ - function clampY(a, min, max) { - a.y = Math.max(Math.min(a.y, max), min); - return a; - }; - PointUtils.clone = /** - * Creates a copy of the given Point. - * @method clone - * @param {Point} output Optional Point object. If given the values will be set into this object, otherwise a brand new Point object will be created and returned. - * @return {Point} The new Point object. - **/ - function clone(a, output) { - if (typeof output === "undefined") { output = new Phaser.Point(); } - return output.setTo(a.x, a.y); - }; - PointUtils.distanceBetween = /** - * Returns the distance between the two given Point objects. - * @method distanceBetween - * @param {Point} a - The first Point object. - * @param {Point} b - The second Point object. - * @param {Boolean} round - Round the distance to the nearest integer (default false) - * @return {Number} The distance between the two Point objects. - **/ - function distanceBetween(a, b, round) { - if (typeof round === "undefined") { round = false; } - var dx = a.x - b.x; - var dy = a.y - b.y; - if(round === true) { - return Math.round(Math.sqrt(dx * dx + dy * dy)); - } else { - return Math.sqrt(dx * dx + dy * dy); - } - }; - PointUtils.equals = /** - * Determines whether the two given Point objects are equal. They are considered equal if they have the same x and y values. - * @method equals - * @param {Point} a - The first Point object. - * @param {Point} b - The second Point object. - * @return {Boolean} A value of true if the Points are equal, otherwise false. - **/ - function equals(a, b) { - return (a.x == b.x && a.y == b.y); - }; - PointUtils.rotate = /** - * Determines a point between two specified points. The parameter f determines where the new interpolated point is located relative to the two end points specified by parameters pt1 and pt2. - * The closer the value of the parameter f is to 1.0, the closer the interpolated point is to the first point (parameter pt1). The closer the value of the parameter f is to 0, the closer the interpolated point is to the second point (parameter pt2). - * @method interpolate - * @param {Point} pointA - The first Point object. - * @param {Point} pointB - The second Point object. - * @param {Number} f - The level of interpolation between the two points. Indicates where the new point will be, along the line between pt1 and pt2. If f=1, pt1 is returned; if f=0, pt2 is returned. - * @return {Point} The new interpolated Point object. - **/ - //static interpolate(pointA, pointB, f) { - //} - /** - * Converts a pair of polar coordinates to a Cartesian point coordinate. - * @method polar - * @param {Number} length - The length coordinate of the polar pair. - * @param {Number} angle - The angle, in radians, of the polar pair. - * @return {Point} The new Cartesian Point object. - **/ - //static polar(length, angle) { - //} - /** - * Rotates a Point around the x/y coordinates given to the desired angle. - * @param a {Point} The Point object to rotate. - * @param x {number} The x coordinate of the anchor point - * @param y {number} The y coordinate of the anchor point - * @param {Number} angle The angle in radians (unless asDegrees is true) to rotate the Point to. - * @param {Boolean} asDegrees Is the given angle in radians (false) or degrees (true)? - * @param {Number} distance An optional distance constraint between the Point and the anchor. - * @return The modified point object + var Mouse = (function () { + function Mouse(game) { + /** + * You can disable all Input by setting disabled = true. While set all new input related events will be ignored. + * @type {Boolean} + */ + this.disabled = false; + this._game = game; + } + Mouse.LEFT_BUTTON = 0; + Mouse.MIDDLE_BUTTON = 1; + Mouse.RIGHT_BUTTON = 2; + Mouse.prototype.start = /** + * Starts the event listeners running + * @method start */ - function rotate(a, x, y, angle, asDegrees, distance) { - if (typeof asDegrees === "undefined") { asDegrees = false; } - if (typeof distance === "undefined") { distance = null; } - if(asDegrees) { - angle = angle * Phaser.GameMath.DEG_TO_RAD; - } - // Get distance from origin (cx/cy) to this point - if(distance === null) { - distance = Math.sqrt(((x - a.x) * (x - a.x)) + ((y - a.y) * (y - a.y))); - } - return a.setTo(x + distance * Math.cos(angle), y + distance * Math.sin(angle)); + function () { + var _this = this; + this._game.stage.canvas.addEventListener('mousedown', function (event) { + return _this.onMouseDown(event); + }, true); + this._game.stage.canvas.addEventListener('mousemove', function (event) { + return _this.onMouseMove(event); + }, true); + this._game.stage.canvas.addEventListener('mouseup', function (event) { + return _this.onMouseUp(event); + }, true); }; - PointUtils.rotateAroundPoint = /** - * Rotates a Point around the given Point to the desired angle. - * @param a {Point} The Point object to rotate. - * @param b {Point} The Point object to serve as point of rotation. - * @param x {number} The x coordinate of the anchor point - * @param y {number} The y coordinate of the anchor point - * @param {Number} angle The angle in radians (unless asDegrees is true) to rotate the Point to. - * @param {Boolean} asDegrees Is the given angle in radians (false) or degrees (true)? - * @param {Number} distance An optional distance constraint between the Point and the anchor. - * @return The modified point object + Mouse.prototype.onMouseDown = /** + * @param {MouseEvent} event */ - function rotateAroundPoint(a, b, angle, asDegrees, distance) { - if (typeof asDegrees === "undefined") { asDegrees = false; } - if (typeof distance === "undefined") { distance = null; } - return PointUtils.rotate(a, b.x, b.y, angle, asDegrees, distance); + function (event) { + if(this._game.input.disabled || this.disabled) { + return; + } + event['identifier'] = 0; + this._game.input.mousePointer.start(event); }; - return PointUtils; - })(); + Mouse.prototype.onMouseMove = /** + * @param {MouseEvent} event + */ + function (event) { + if(this._game.input.disabled || this.disabled) { + return; + } + event['identifier'] = 0; + this._game.input.mousePointer.move(event); + }; + Mouse.prototype.onMouseUp = /** + * @param {MouseEvent} event + */ + function (event) { + if(this._game.input.disabled || this.disabled) { + return; + } + event['identifier'] = 0; + this._game.input.mousePointer.stop(event); + }; + Mouse.prototype.stop = /** + * Stop the event listeners + * @method stop + */ + function () { + //this._game.stage.canvas.addEventListener('mousedown', (event: MouseEvent) => this.onMouseDown(event), true); + //this._game.stage.canvas.addEventListener('mousemove', (event: MouseEvent) => this.onMouseMove(event), true); + //this._game.stage.canvas.addEventListener('mouseup', (event: MouseEvent) => this.onMouseUp(event), true); + }; + return Mouse; + })(); + Phaser.Mouse = Mouse; })(Phaser || (Phaser = {})); /// -/// /** -* Phaser - Vec2Utils -* -* A collection of methods useful for manipulating and performing operations on 2D vectors. +* Phaser - Keyboard * +* The Keyboard class handles keyboard interactions with the game and the resulting events. +* The avoid stealing all browser input we don't use event.preventDefault. If you would like to trap a specific key however +* then use the addKeyCapture() method. */ var Phaser; (function (Phaser) { - var Vec2Utils = (function () { - function Vec2Utils() { } - Vec2Utils.add = /** - * Adds two 2D vectors. - * - * @param {Vec2} a Reference to a source Vec2 object. - * @param {Vec2} b Reference to a source Vec2 object. - * @param {Vec2} out The output Vec2 that is the result of the operation. - * @return {Vec2} A Vec2 that is the sum of the two vectors. - */ - function add(a, b, out) { - if (typeof out === "undefined") { out = new Phaser.Vec2(); } - return out.setTo(a.x + b.x, a.y + b.y); + var Keyboard = (function () { + function Keyboard(game) { + this._keys = { + }; + this._capture = { + }; + /** + * You can disable all Input by setting disabled = true. While set all new input related events will be ignored. + * @type {Boolean} + */ + this.disabled = false; + this._game = game; + } + Keyboard.prototype.start = function () { + var _this = this; + document.body.addEventListener('keydown', function (event) { + return _this.onKeyDown(event); + }, false); + document.body.addEventListener('keyup', function (event) { + return _this.onKeyUp(event); + }, false); }; - Vec2Utils.subtract = /** - * Subtracts two 2D vectors. - * - * @param {Vec2} a Reference to a source Vec2 object. - * @param {Vec2} b Reference to a source Vec2 object. - * @param {Vec2} out The output Vec2 that is the result of the operation. - * @return {Vec2} A Vec2 that is the difference of the two vectors. + Keyboard.prototype.addKeyCapture = /** + * By default when a key is pressed Phaser will not stop the event from propagating up to the browser. + * There are some keys this can be annoying for, like the arrow keys or space bar, which make the browser window scroll. + * You can use addKeyCapture to consume the keyboard event for specific keys so it doesn't bubble up to the the browser. + * Pass in either a single keycode or an array of keycodes. + * @param {Any} keycode */ - function subtract(a, b, out) { - if (typeof out === "undefined") { out = new Phaser.Vec2(); } - return out.setTo(a.x - b.x, a.y - b.y); + function (keycode) { + if(typeof keycode === 'object') { + for(var i = 0; i < keycode.length; i++) { + this._capture[keycode[i]] = true; + } + } else { + this._capture[keycode] = true; + } }; - Vec2Utils.multiply = /** - * Multiplies two 2D vectors. - * - * @param {Vec2} a Reference to a source Vec2 object. - * @param {Vec2} b Reference to a source Vec2 object. - * @param {Vec2} out The output Vec2 that is the result of the operation. - * @return {Vec2} A Vec2 that is the sum of the two vectors multiplied. + Keyboard.prototype.removeKeyCapture = /** + * @param {Number} keycode */ - function multiply(a, b, out) { - if (typeof out === "undefined") { out = new Phaser.Vec2(); } - return out.setTo(a.x * b.x, a.y * b.y); + function (keycode) { + delete this._capture[keycode]; }; - Vec2Utils.divide = /** - * Divides two 2D vectors. - * - * @param {Vec2} a Reference to a source Vec2 object. - * @param {Vec2} b Reference to a source Vec2 object. - * @param {Vec2} out The output Vec2 that is the result of the operation. - * @return {Vec2} A Vec2 that is the sum of the two vectors divided. + Keyboard.prototype.clearCaptures = function () { + this._capture = { + }; + }; + Keyboard.prototype.onKeyDown = /** + * @param {KeyboardEvent} event */ - function divide(a, b, out) { - if (typeof out === "undefined") { out = new Phaser.Vec2(); } - return out.setTo(a.x / b.x, a.y / b.y); + function (event) { + if(this._game.input.disabled || this.disabled) { + return; + } + if(this._capture[event.keyCode]) { + event.preventDefault(); + } + if(!this._keys[event.keyCode]) { + this._keys[event.keyCode] = { + isDown: true, + timeDown: this._game.time.now, + timeUp: 0 + }; + } else { + this._keys[event.keyCode].isDown = true; + this._keys[event.keyCode].timeDown = this._game.time.now; + } }; - Vec2Utils.scale = /** - * Scales a 2D vector. - * - * @param {Vec2} a Reference to a source Vec2 object. - * @param {number} s Scaling value. - * @param {Vec2} out The output Vec2 that is the result of the operation. - * @return {Vec2} A Vec2 that is the scaled vector. + Keyboard.prototype.onKeyUp = /** + * @param {KeyboardEvent} event */ - function scale(a, s, out) { - if (typeof out === "undefined") { out = new Phaser.Vec2(); } - return out.setTo(a.x * s, a.y * s); + function (event) { + if(this._game.input.disabled || this.disabled) { + return; + } + if(this._capture[event.keyCode]) { + event.preventDefault(); + } + if(!this._keys[event.keyCode]) { + this._keys[event.keyCode] = { + isDown: false, + timeDown: 0, + timeUp: this._game.time.now + }; + } else { + this._keys[event.keyCode].isDown = false; + this._keys[event.keyCode].timeUp = this._game.time.now; + } }; - Vec2Utils.perp = /** - * Rotate a 2D vector by 90 degrees. - * - * @param {Vec2} a Reference to a source Vec2 object. - * @param {Vec2} out The output Vec2 that is the result of the operation. - * @return {Vec2} A Vec2 that is the scaled vector. - */ - function perp(a, out) { - if (typeof out === "undefined") { out = new Phaser.Vec2(); } - return out.setTo(a.y, -a.x); + Keyboard.prototype.reset = function () { + for(var key in this._keys) { + this._keys[key].isDown = false; + } }; - Vec2Utils.equals = /** - * Checks if two 2D vectors are equal. - * - * @param {Vec2} a Reference to a source Vec2 object. - * @param {Vec2} b Reference to a source Vec2 object. + Keyboard.prototype.justPressed = /** + * @param {Number} keycode + * @param {Number} [duration] * @return {Boolean} */ - function equals(a, b) { - return a.x == b.x && a.y == b.y; + function (keycode, duration) { + if (typeof duration === "undefined") { duration = 250; } + if(this._keys[keycode] && this._keys[keycode].isDown === true && (this._game.time.now - this._keys[keycode].timeDown < duration)) { + return true; + } else { + return false; + } }; - Vec2Utils.epsilonEquals = /** - * - * - * @param {Vec2} a Reference to a source Vec2 object. - * @param {Vec2} b Reference to a source Vec2 object. - * @param {Vec2} epsilon + Keyboard.prototype.justReleased = /** + * @param {Number} keycode + * @param {Number} [duration] * @return {Boolean} */ - function epsilonEquals(a, b, epsilon) { - return Math.abs(a.x - b.x) <= epsilon && Math.abs(a.y - b.y) <= epsilon; - }; - Vec2Utils.distance = /** - * Get the distance between two 2D vectors. - * - * @param {Vec2} a Reference to a source Vec2 object. - * @param {Vec2} b Reference to a source Vec2 object. - * @return {Number} - */ - function distance(a, b) { - return Math.sqrt(Vec2Utils.distanceSq(a, b)); - }; - Vec2Utils.distanceSq = /** - * Get the distance squared between two 2D vectors. - * - * @param {Vec2} a Reference to a source Vec2 object. - * @param {Vec2} b Reference to a source Vec2 object. - * @return {Number} - */ - function distanceSq(a, b) { - return ((a.x - b.x) * (a.x - b.x)) + ((a.y - b.y) * (a.y - b.y)); - }; - Vec2Utils.project = /** - * Project two 2D vectors onto another vector. - * - * @param {Vec2} a Reference to a source Vec2 object. - * @param {Vec2} b Reference to a source Vec2 object. - * @param {Vec2} out The output Vec2 that is the result of the operation. - * @return {Vec2} A Vec2. - */ - function project(a, b, out) { - if (typeof out === "undefined") { out = new Phaser.Vec2(); } - var amt = a.dot(b) / b.lengthSq(); - if(amt != 0) { - out.setTo(amt * b.x, amt * b.y); + function (keycode, duration) { + if (typeof duration === "undefined") { duration = 250; } + if(this._keys[keycode] && this._keys[keycode].isDown === false && (this._game.time.now - this._keys[keycode].timeUp < duration)) { + return true; + } else { + return false; } - return out; }; - Vec2Utils.projectUnit = /** - * Project this vector onto a vector of unit length. - * - * @param {Vec2} a Reference to a source Vec2 object. - * @param {Vec2} b Reference to a source Vec2 object. - * @param {Vec2} out The output Vec2 that is the result of the operation. - * @return {Vec2} A Vec2. + Keyboard.prototype.isDown = /** + * @param {Number} keycode + * @return {Boolean} */ - function projectUnit(a, b, out) { - if (typeof out === "undefined") { out = new Phaser.Vec2(); } - var amt = a.dot(b); - if(amt != 0) { - out.setTo(amt * b.x, amt * b.y); + function (keycode) { + if(this._keys[keycode]) { + return this._keys[keycode].isDown; + } else { + return false; } - return out; }; - Vec2Utils.normalRightHand = /** - * Right-hand normalize (make unit length) a 2D vector. - * - * @param {Vec2} a Reference to a source Vec2 object. - * @param {Vec2} out The output Vec2 that is the result of the operation. - * @return {Vec2} A Vec2. - */ - function normalRightHand(a, out) { - if (typeof out === "undefined") { out = this; } - return out.setTo(a.y * -1, a.x); - }; - Vec2Utils.normalize = /** - * Normalize (make unit length) a 2D vector. - * - * @param {Vec2} a Reference to a source Vec2 object. - * @param {Vec2} out The output Vec2 that is the result of the operation. - * @return {Vec2} A Vec2. - */ - function normalize(a, out) { - if (typeof out === "undefined") { out = new Phaser.Vec2(); } - var m = a.length(); - if(m != 0) { - out.setTo(a.x / m, a.y / m); - } - return out; - }; - Vec2Utils.dot = /** - * The dot product of two 2D vectors. - * - * @param {Vec2} a Reference to a source Vec2 object. - * @param {Vec2} b Reference to a source Vec2 object. - * @return {Number} - */ - function dot(a, b) { - return ((a.x * b.x) + (a.y * b.y)); - }; - Vec2Utils.cross = /** - * The cross product of two 2D vectors. - * - * @param {Vec2} a Reference to a source Vec2 object. - * @param {Vec2} b Reference to a source Vec2 object. - * @return {Number} - */ - function cross(a, b) { - return ((a.x * b.y) - (a.y * b.x)); - }; - Vec2Utils.angle = /** - * The angle between two 2D vectors. - * - * @param {Vec2} a Reference to a source Vec2 object. - * @param {Vec2} b Reference to a source Vec2 object. - * @return {Number} - */ - function angle(a, b) { - return Math.atan2(a.x * b.y - a.y * b.x, a.x * b.x + a.y * b.y); - }; - Vec2Utils.angleSq = /** - * The angle squared between two 2D vectors. - * - * @param {Vec2} a Reference to a source Vec2 object. - * @param {Vec2} b Reference to a source Vec2 object. - * @return {Number} - */ - function angleSq(a, b) { - return a.subtract(b).angle(b.subtract(a)); - }; - Vec2Utils.rotate = /** - * Rotate a 2D vector around the origin to the given angle (theta). - * - * @param {Vec2} a Reference to a source Vec2 object. - * @param {Vec2} b Reference to a source Vec2 object. - * @param {Number} theta The angle of rotation in radians. - * @param {Vec2} out The output Vec2 that is the result of the operation. - * @return {Vec2} A Vec2. - */ - function rotate(a, b, theta, out) { - if (typeof out === "undefined") { out = new Phaser.Vec2(); } - var x = a.x - b.x; - var y = a.y - b.y; - return out.setTo(x * Math.cos(theta) - y * Math.sin(theta) + b.x, x * Math.sin(theta) + y * Math.cos(theta) + b.y); - }; - Vec2Utils.clone = /** - * Clone a 2D vector. - * - * @param {Vec2} a Reference to a source Vec2 object. - * @param {Vec2} out The output Vec2 that is the result of the operation. - * @return {Vec2} A Vec2 that is a copy of the source Vec2. - */ - function clone(a, out) { - if (typeof out === "undefined") { out = new Phaser.Vec2(); } - return out.setTo(a.x, a.y); - }; - return Vec2Utils; + Keyboard.A = "A".charCodeAt(0); + Keyboard.B = "B".charCodeAt(0); + Keyboard.C = "C".charCodeAt(0); + Keyboard.D = "D".charCodeAt(0); + Keyboard.E = "E".charCodeAt(0); + Keyboard.F = "F".charCodeAt(0); + Keyboard.G = "G".charCodeAt(0); + Keyboard.H = "H".charCodeAt(0); + Keyboard.I = "I".charCodeAt(0); + Keyboard.J = "J".charCodeAt(0); + Keyboard.K = "K".charCodeAt(0); + Keyboard.L = "L".charCodeAt(0); + Keyboard.M = "M".charCodeAt(0); + Keyboard.N = "N".charCodeAt(0); + Keyboard.O = "O".charCodeAt(0); + Keyboard.P = "P".charCodeAt(0); + Keyboard.Q = "Q".charCodeAt(0); + Keyboard.R = "R".charCodeAt(0); + Keyboard.S = "S".charCodeAt(0); + Keyboard.T = "T".charCodeAt(0); + Keyboard.U = "U".charCodeAt(0); + Keyboard.V = "V".charCodeAt(0); + Keyboard.W = "W".charCodeAt(0); + Keyboard.X = "X".charCodeAt(0); + Keyboard.Y = "Y".charCodeAt(0); + Keyboard.Z = "Z".charCodeAt(0); + Keyboard.ZERO = "0".charCodeAt(0); + Keyboard.ONE = "1".charCodeAt(0); + Keyboard.TWO = "2".charCodeAt(0); + Keyboard.THREE = "3".charCodeAt(0); + Keyboard.FOUR = "4".charCodeAt(0); + Keyboard.FIVE = "5".charCodeAt(0); + Keyboard.SIX = "6".charCodeAt(0); + Keyboard.SEVEN = "7".charCodeAt(0); + Keyboard.EIGHT = "8".charCodeAt(0); + Keyboard.NINE = "9".charCodeAt(0); + Keyboard.NUMPAD_0 = 96; + Keyboard.NUMPAD_1 = 97; + Keyboard.NUMPAD_2 = 98; + Keyboard.NUMPAD_3 = 99; + Keyboard.NUMPAD_4 = 100; + Keyboard.NUMPAD_5 = 101; + Keyboard.NUMPAD_6 = 102; + Keyboard.NUMPAD_7 = 103; + Keyboard.NUMPAD_8 = 104; + Keyboard.NUMPAD_9 = 105; + Keyboard.NUMPAD_MULTIPLY = 106; + Keyboard.NUMPAD_ADD = 107; + Keyboard.NUMPAD_ENTER = 108; + Keyboard.NUMPAD_SUBTRACT = 109; + Keyboard.NUMPAD_DECIMAL = 110; + Keyboard.NUMPAD_DIVIDE = 111; + Keyboard.F1 = 112; + Keyboard.F2 = 113; + Keyboard.F3 = 114; + Keyboard.F4 = 115; + Keyboard.F5 = 116; + Keyboard.F6 = 117; + Keyboard.F7 = 118; + Keyboard.F8 = 119; + Keyboard.F9 = 120; + Keyboard.F10 = 121; + Keyboard.F11 = 122; + Keyboard.F12 = 123; + Keyboard.F13 = 124; + Keyboard.F14 = 125; + Keyboard.F15 = 126; + Keyboard.COLON = 186; + Keyboard.EQUALS = 187; + Keyboard.UNDERSCORE = 189; + Keyboard.QUESTION_MARK = 191; + Keyboard.TILDE = 192; + Keyboard.OPEN_BRACKET = 219; + Keyboard.BACKWARD_SLASH = 220; + Keyboard.CLOSED_BRACKET = 221; + Keyboard.QUOTES = 222; + Keyboard.BACKSPACE = 8; + Keyboard.TAB = 9; + Keyboard.CLEAR = 12; + Keyboard.ENTER = 13; + Keyboard.SHIFT = 16; + Keyboard.CONTROL = 17; + Keyboard.ALT = 18; + Keyboard.CAPS_LOCK = 20; + Keyboard.ESC = 27; + Keyboard.SPACEBAR = 32; + Keyboard.PAGE_UP = 33; + Keyboard.PAGE_DOWN = 34; + Keyboard.END = 35; + Keyboard.HOME = 36; + Keyboard.LEFT = 37; + Keyboard.UP = 38; + Keyboard.RIGHT = 39; + Keyboard.DOWN = 40; + Keyboard.INSERT = 45; + Keyboard.DELETE = 46; + Keyboard.HELP = 47; + Keyboard.NUM_LOCK = 144; + return Keyboard; })(); - Phaser.Vec2Utils = Vec2Utils; - /** - * Reflect this vector on an arbitrary axis. - * - * @param {Vec2} axis The vector representing the axis. - * @return {Vec2} This for chaining. - */ - /* - static reflect(axis): Vec2 { - - var x = this.x; - var y = this.y; - this.project(axis).scale(2); - this.x -= x; - this.y -= y; - - return this; - - } - */ - /** - * Reflect this vector on an arbitrary axis (represented by a unit vector) - * - * @param {Vec2} axis The unit vector representing the axis. - * @return {Vec2} This for chaining. - */ - /* - static reflectN(axis): Vec2 { - - var x = this.x; - var y = this.y; - this.projectN(axis).scale(2); - this.x -= x; - this.y -= y; - - return this; - - } - - static getMagnitude(): number { - return Math.sqrt(Math.pow(this.x, 2) + Math.pow(this.y, 2)); - } - */ - })(Phaser || (Phaser = {})); + Phaser.Keyboard = Keyboard; +})(Phaser || (Phaser = {})); /// -/// +/// +/** +* Phaser - Touch +* +* The Touch class handles touch interactions with the game and the resulting Pointer objects. +* http://www.w3.org/TR/touch-events/ +* https://developer.mozilla.org/en-US/docs/DOM/TouchList +* http://www.html5rocks.com/en/mobile/touchandmouse/ +* Note: Android 2.x only supports 1 touch event at once, no multi-touch +*/ +var Phaser; +(function (Phaser) { + var Touch = (function () { + /** + * Constructor + * @param {Game} game. + * @return {Touch} This object. + */ + function Touch(game) { + /** + * You can disable all Input by setting disabled = true. While set all new input related events will be ignored. + * @type {Boolean} + */ + this.disabled = false; + this._game = game; + } + Touch.prototype.start = /** + * Starts the event listeners running + * @method start + */ + function () { + var _this = this; + if(this._game.device.touch) { + this._game.stage.canvas.addEventListener('touchstart', function (event) { + return _this.onTouchStart(event); + }, false); + this._game.stage.canvas.addEventListener('touchmove', function (event) { + return _this.onTouchMove(event); + }, false); + this._game.stage.canvas.addEventListener('touchend', function (event) { + return _this.onTouchEnd(event); + }, false); + this._game.stage.canvas.addEventListener('touchenter', function (event) { + return _this.onTouchEnter(event); + }, false); + this._game.stage.canvas.addEventListener('touchleave', function (event) { + return _this.onTouchLeave(event); + }, false); + this._game.stage.canvas.addEventListener('touchcancel', function (event) { + return _this.onTouchCancel(event); + }, false); + document.addEventListener('touchmove', function (event) { + return _this.consumeTouchMove(event); + }, false); + } + }; + Touch.prototype.consumeTouchMove = /** + * Prevent iOS bounce-back (doesn't work?) + * @method consumeTouchMove + * @param {Any} event + **/ + function (event) { + event.preventDefault(); + }; + Touch.prototype.onTouchStart = /** + * + * @method onTouchStart + * @param {Any} event + **/ + function (event) { + if(this._game.input.disabled || this.disabled) { + return; + } + event.preventDefault(); + // event.targetTouches = list of all touches on the TARGET ELEMENT (i.e. game dom element) + // event.touches = list of all touches on the ENTIRE DOCUMENT, not just the target element + // event.changedTouches = the touches that CHANGED in this event, not the total number of them + for(var i = 0; i < event.changedTouches.length; i++) { + this._game.input.startPointer(event.changedTouches[i]); + } + }; + Touch.prototype.onTouchCancel = /** + * Touch cancel - touches that were disrupted (perhaps by moving into a plugin or browser chrome) + * Occurs for example on iOS when you put down 4 fingers and the app selector UI appears + * @method onTouchCancel + * @param {Any} event + **/ + function (event) { + if(this._game.input.disabled || this.disabled) { + return; + } + event.preventDefault(); + // Touch cancel - touches that were disrupted (perhaps by moving into a plugin or browser chrome) + // http://www.w3.org/TR/touch-events/#dfn-touchcancel + for(var i = 0; i < event.changedTouches.length; i++) { + this._game.input.stopPointer(event.changedTouches[i]); + } + }; + Touch.prototype.onTouchEnter = /** + * For touch enter and leave its a list of the touch points that have entered or left the target + * Doesn't appear to be supported by most browsers yet + * @method onTouchEnter + * @param {Any} event + **/ + function (event) { + if(this._game.input.disabled || this.disabled) { + return; + } + event.preventDefault(); + for(var i = 0; i < event.changedTouches.length; i++) { + console.log('touch enter'); + } + }; + Touch.prototype.onTouchLeave = /** + * For touch enter and leave its a list of the touch points that have entered or left the target + * Doesn't appear to be supported by most browsers yet + * @method onTouchLeave + * @param {Any} event + **/ + function (event) { + event.preventDefault(); + for(var i = 0; i < event.changedTouches.length; i++) { + console.log('touch leave'); + } + }; + Touch.prototype.onTouchMove = /** + * + * @method onTouchMove + * @param {Any} event + **/ + function (event) { + event.preventDefault(); + for(var i = 0; i < event.changedTouches.length; i++) { + this._game.input.updatePointer(event.changedTouches[i]); + } + }; + Touch.prototype.onTouchEnd = /** + * + * @method onTouchEnd + * @param {Any} event + **/ + function (event) { + event.preventDefault(); + // For touch end its a list of the touch points that have been removed from the surface + // https://developer.mozilla.org/en-US/docs/DOM/TouchList + // event.changedTouches = the touches that CHANGED in this event, not the total number of them + for(var i = 0; i < event.changedTouches.length; i++) { + this._game.input.stopPointer(event.changedTouches[i]); + } + }; + Touch.prototype.stop = /** + * Stop the event listeners + * @method stop + */ + function () { + if(this._game.device.touch) { + //this._domElement.addEventListener('touchstart', (event) => this.onTouchStart(event), false); + //this._domElement.addEventListener('touchmove', (event) => this.onTouchMove(event), false); + //this._domElement.addEventListener('touchend', (event) => this.onTouchEnd(event), false); + //this._domElement.addEventListener('touchenter', (event) => this.onTouchEnter(event), false); + //this._domElement.addEventListener('touchleave', (event) => this.onTouchLeave(event), false); + //this._domElement.addEventListener('touchcancel', (event) => this.onTouchCancel(event), false); + } + }; + return Touch; + })(); + Phaser.Touch = Touch; +})(Phaser || (Phaser = {})); +/// +/// +/// +/// /// /// /// -/// -/// +/// +/// +/// /** * Phaser - Input * @@ -9591,7 +10359,6 @@ var Phaser; // Add Tilemap, ScrollZone, etc? })(Phaser || (Phaser = {})); /// -/// /// /// /// @@ -9608,6 +10375,8 @@ var Phaser; this._dy = 0; this._dw = 0; this._dh = 0; + this._fx = 1; + this._fy = 1; this._game = game; } CanvasRenderer.prototype.render = function () { @@ -9636,14 +10405,26 @@ var Phaser; var globalAlpha = sprite.texture.context.globalAlpha; sprite.texture.context.globalAlpha = sprite.texture.alpha; } + this._fx = sprite.scale.x; + this._fy = sprite.scale.y; this._sx = 0; this._sy = 0; this._sw = sprite.frameBounds.width; this._sh = sprite.frameBounds.height; + //if (sprite.texture.flippedX) + //{ + // this._fx = -1; + //} + //if (sprite.texture.flippedY) + //{ + // this._fy = -1; + //} this._dx = (camera.scaledX * sprite.scrollFactor.x) + sprite.frameBounds.x - (camera.worldView.x * sprite.scrollFactor.x); this._dy = (camera.scaledY * sprite.scrollFactor.y) + sprite.frameBounds.y - (camera.worldView.y * sprite.scrollFactor.y); - this._dw = sprite.frameBounds.width * sprite.scale.x; - this._dh = sprite.frameBounds.height * sprite.scale.y; + //this._dw = sprite.frameBounds.width * sprite.scale.x; + //this._dh = sprite.frameBounds.height * sprite.scale.y; + this._dw = sprite.frameBounds.width; + this._dh = sprite.frameBounds.height; /* if (this._dynamicTexture == false && this.animations.currentFrame !== null) { @@ -9662,21 +10443,56 @@ var Phaser; //this._dx -= (camera.worldView.x * this.scrollFactor.x); //this._dy -= (camera.worldView.y * this.scrollFactor.y); } + // Apply origin / alignment + if(sprite.origin.x != 0 || sprite.origin.y != 0) { + //this._dx += (sprite.origin.x * sprite.scale.x); + //this._dy += (sprite.origin.y * sprite.scale.y); + } // Rotation and Flipped - if(sprite.position.rotation !== 0 || sprite.position.rotationOffset !== 0 || sprite.texture.flippedX || sprite.texture.flippedY) { + if(sprite.scale.x != 1 || sprite.scale.y != 1 || sprite.position.rotation != 0 || sprite.position.rotationOffset != 0 || sprite.texture.flippedX || sprite.texture.flippedY)//if (sprite.position.rotation != 0 || sprite.position.rotationOffset != 0 || sprite.texture.flippedX || sprite.texture.flippedY) + { sprite.texture.context.save(); - sprite.texture.context.translate(this._dx + (this._dw / 2), this._dy + (this._dh / 2)); + if(sprite.texture.flippedX) { + this._dx += this._dw * sprite.scale.x; + } + if(sprite.texture.flippedY) { + this._dy += this._dh * sprite.scale.y; + } + sprite.texture.context.translate(this._dx, this._dy); + //sprite.texture.context.translate(this._dx + (this._dw / 2), this._dy + (this._dh / 2)); + //sprite.texture.context.translate(this._dx + (sprite.origin.x * sprite.scale.x), this._dy + (sprite.origin.y * sprite.scale.y)); + //sprite.texture.context.translate(this._dx + sprite.origin.x, this._dy + sprite.origin.y); + //sprite.texture.context.translate(this._dx + sprite.origin.x - (this._dw / 2), this._dy + sprite.origin.y - (this._dh / 2)); if(sprite.texture.renderRotation == true && (sprite.position.rotation !== 0 || sprite.position.rotationOffset !== 0)) { // Apply point of rotation here sprite.texture.context.rotate((sprite.position.rotationOffset + sprite.position.rotation) * (Math.PI / 180)); } - this._dx = -(this._dw / 2); - this._dy = -(this._dh / 2); - if(sprite.texture.flippedX || sprite.texture.flippedY) { + if(sprite.scale.x != 1 || sprite.scale.y != 1 || sprite.texture.flippedX || sprite.texture.flippedY) { if(sprite.texture.flippedX) { - sprite.texture.context.scale(-1, 1); + this._fx = -sprite.scale.x; } + if(sprite.texture.flippedY) { + this._fy = -sprite.scale.y; + } + sprite.texture.context.scale(this._fx, this._fy); } + //if (sprite.texture.flippedX || sprite.texture.flippedY) + //{ + // sprite.texture.context.scale(this._fx, this._fy); + //} + this._dx = -(sprite.origin.x * sprite.scale.x); + this._dy = -(sprite.origin.y * sprite.scale.y); + //this._dx = -(sprite.origin.x * sprite.scale.x); + //this._dy = -(sprite.origin.y * sprite.scale.y); + //this._dx = -(this._dw / 2) * sprite.scale.x; + //this._dy = -(this._dh / 2) * sprite.scale.y; + //this._dx = 0; + //this._dy = 0; + } else { + if(sprite.origin.x != 0 || sprite.origin.y != 0) { + //this._dx -= (sprite.origin.x * sprite.scale.x); + //this._dy -= (sprite.origin.y * sprite.scale.y); + } } this._sx = Math.round(this._sx); this._sy = Math.round(this._sy); @@ -9704,7 +10520,8 @@ var Phaser; // this.context.fillStyle = this.fillColor; // this.context.fillRect(this._dx, this._dy, this._dw, this._dh); //} - if(sprite.position.rotation !== 0 || sprite.position.rotationOffset !== 0 || sprite.texture.flippedX || sprite.texture.flippedY) { + if(sprite.scale.x != 1 || sprite.scale.y != 1 || sprite.position.rotation != 0 || sprite.position.rotationOffset != 0 || sprite.texture.flippedX || sprite.texture.flippedY)//if (sprite.position.rotation != 0 || sprite.position.rotationOffset != 0 || sprite.texture.flippedX || sprite.texture.flippedY) + { //this.context.translate(0, 0); sprite.texture.context.restore(); } @@ -10519,203 +11336,6 @@ var Phaser; Phaser.Rectangle = Rectangle; })(Phaser || (Phaser = {})); /// -/// -/// -/** -* Phaser - ScrollRegion -* -* Creates a scrolling region within a ScrollZone. -* It is scrolled via the scrollSpeed.x/y properties. -*/ -var Phaser; -(function (Phaser) { - var ScrollRegion = (function () { - /** - * ScrollRegion constructor - * Create a new ScrollRegion. - * - * @param x {number} X position in world coordinate. - * @param y {number} Y position in world coordinate. - * @param width {number} Width of this object. - * @param height {number} Height of this object. - * @param speedX {number} X-axis scrolling speed. - * @param speedY {number} Y-axis scrolling speed. - */ - function ScrollRegion(x, y, width, height, speedX, speedY) { - this._anchorWidth = 0; - this._anchorHeight = 0; - this._inverseWidth = 0; - this._inverseHeight = 0; - /** - * Will this region be rendered? (default to true) - * @type {boolean} - */ - this.visible = true; - // Our seamless scrolling quads - this._A = new Phaser.Rectangle(x, y, width, height); - this._B = new Phaser.Rectangle(x, y, width, height); - this._C = new Phaser.Rectangle(x, y, width, height); - this._D = new Phaser.Rectangle(x, y, width, height); - this._scroll = new Phaser.Vec2(); - this._bounds = new Phaser.Rectangle(x, y, width, height); - this.scrollSpeed = new Phaser.Vec2(speedX, speedY); - } - ScrollRegion.prototype.update = /** - * Update region scrolling with tick time. - * @param delta {number} Elapsed time since last update. - */ - function (delta) { - this._scroll.x += this.scrollSpeed.x; - this._scroll.y += this.scrollSpeed.y; - if(this._scroll.x > this._bounds.right) { - this._scroll.x = this._bounds.x; - } - if(this._scroll.x < this._bounds.x) { - this._scroll.x = this._bounds.right; - } - if(this._scroll.y > this._bounds.bottom) { - this._scroll.y = this._bounds.y; - } - if(this._scroll.y < this._bounds.y) { - this._scroll.y = this._bounds.bottom; - } - // Anchor Dimensions - this._anchorWidth = (this._bounds.width - this._scroll.x) + this._bounds.x; - this._anchorHeight = (this._bounds.height - this._scroll.y) + this._bounds.y; - if(this._anchorWidth > this._bounds.width) { - this._anchorWidth = this._bounds.width; - } - if(this._anchorHeight > this._bounds.height) { - this._anchorHeight = this._bounds.height; - } - this._inverseWidth = this._bounds.width - this._anchorWidth; - this._inverseHeight = this._bounds.height - this._anchorHeight; - // Rectangle A - this._A.setTo(this._scroll.x, this._scroll.y, this._anchorWidth, this._anchorHeight); - // Rectangle B - this._B.y = this._scroll.y; - this._B.width = this._inverseWidth; - this._B.height = this._anchorHeight; - // Rectangle C - this._C.x = this._scroll.x; - this._C.width = this._anchorWidth; - this._C.height = this._inverseHeight; - // Rectangle D - this._D.width = this._inverseWidth; - this._D.height = this._inverseHeight; - }; - ScrollRegion.prototype.render = /** - * Render this region to specific context. - * @param context {CanvasRenderingContext2D} Canvas context this region will be rendered to. - * @param texture {object} The texture to be rendered. - * @param dx {number} X position in world coordinate. - * @param dy {number} Y position in world coordinate. - * @param width {number} Width of this region to be rendered. - * @param height {number} Height of this region to be rendered. - */ - function (context, texture, dx, dy, dw, dh) { - if(this.visible == false) { - return; - } - // dx/dy are the world coordinates to render the FULL ScrollZone into. - // This ScrollRegion may be smaller than that and offset from the dx/dy coordinates. - this.crop(context, texture, this._A.x, this._A.y, this._A.width, this._A.height, dx, dy, dw, dh, 0, 0); - this.crop(context, texture, this._B.x, this._B.y, this._B.width, this._B.height, dx, dy, dw, dh, this._A.width, 0); - this.crop(context, texture, this._C.x, this._C.y, this._C.width, this._C.height, dx, dy, dw, dh, 0, this._A.height); - this.crop(context, texture, this._D.x, this._D.y, this._D.width, this._D.height, dx, dy, dw, dh, this._C.width, this._A.height); - //context.fillStyle = 'rgb(255,255,255)'; - //context.font = '18px Arial'; - //context.fillText('RectangleA: ' + this._A.toString(), 32, 450); - //context.fillText('RectangleB: ' + this._B.toString(), 32, 480); - //context.fillText('RectangleC: ' + this._C.toString(), 32, 510); - //context.fillText('RectangleD: ' + this._D.toString(), 32, 540); - }; - ScrollRegion.prototype.crop = /** - * Crop part of the texture and render it to the given context. - * @param context {CanvasRenderingContext2D} Canvas context the texture will be rendered to. - * @param texture {object} Texture to be rendered. - * @param srcX {number} Target region top-left x coordinate in the texture. - * @param srcX {number} Target region top-left y coordinate in the texture. - * @param srcW {number} Target region width in the texture. - * @param srcH {number} Target region height in the texture. - * @param destX {number} Render region top-left x coordinate in the context. - * @param destX {number} Render region top-left y coordinate in the context. - * @param destW {number} Target region width in the context. - * @param destH {number} Target region height in the context. - * @param offsetX {number} X offset to the context. - * @param offsetY {number} Y offset to the context. - */ - function (context, texture, srcX, srcY, srcW, srcH, destX, destY, destW, destH, offsetX, offsetY) { - offsetX += destX; - offsetY += destY; - if(srcW > (destX + destW) - offsetX) { - srcW = (destX + destW) - offsetX; - } - if(srcH > (destY + destH) - offsetY) { - srcH = (destY + destH) - offsetY; - } - srcX = Math.floor(srcX); - srcY = Math.floor(srcY); - srcW = Math.floor(srcW); - srcH = Math.floor(srcH); - offsetX = Math.floor(offsetX + this._bounds.x); - offsetY = Math.floor(offsetY + this._bounds.y); - if(srcW > 0 && srcH > 0) { - context.drawImage(texture, srcX, srcY, srcW, srcH, offsetX, offsetY, srcW, srcH); - } - }; - return ScrollRegion; - })(); - Phaser.ScrollRegion = ScrollRegion; -})(Phaser || (Phaser = {})); -/// -/** -* Phaser - Polygon -* -*/ -var Phaser; -(function (Phaser) { - var Polygon = (function () { - /** - * A *convex* clockwise polygon - * @class Polygon - * @constructor - * @param {Vec2} pos A vector representing the origin of the polygon (all other points are relative to this one) - * @param {Array.} points An Array of vectors representing the points in the polygon, in clockwise order. - **/ - function Polygon(pos, points, parent) { - if (typeof pos === "undefined") { pos = new Phaser.Vec2(); } - if (typeof points === "undefined") { points = []; } - if (typeof parent === "undefined") { parent = null; } - this.pos = pos; - this.points = points; - this.parent = parent; - this.recalc(); - } - Polygon.prototype.recalc = /** - * Recalculate the edges and normals of the polygon. This - * MUST be called if the points array is modified at all and - * the edges or normals are to be accessed. - */ - function () { - var points = this.points; - var len = points.length; - this.edges = []; - this.normals = []; - for(var i = 0; i < len; i++) { - var p1 = points[i]; - var p2 = i < len - 1 ? points[i + 1] : points[0]; - var e = new Phaser.Vec2().copyFrom(p2).sub(p1); - var n = new Phaser.Vec2().copyFrom(e).perp().normalize(); - this.edges.push(e); - this.normals.push(n); - } - }; - return Polygon; - })(); - Phaser.Polygon = Polygon; -})(Phaser || (Phaser = {})); -/// /// /// /// @@ -10751,7 +11371,8 @@ var Phaser; * @return {Boolean} True if the coordinates are within this circle, otherwise false. **/ function contains(a, x, y) { - return (a.radius * a.radius >= Collision.distanceSquared(a.x, a.y, x, y)); + //return (a.radius * a.radius >= Collision.distanceSquared(a.x, a.y, x, y)); + return true; }; CircleUtils.containsPoint = /** * Return true if the coordinates of the given Point object are within this Circle object. @@ -10772,7 +11393,8 @@ var Phaser; * @return {Boolean} True if the coordinates are within this circle, otherwise false. **/ function containsCircle(a, b) { - return ((a.radius + b.radius) * (a.radius + b.radius)) >= Collision.distanceSquared(a.x, a.y, b.x, b.y); + //return ((a.radius + b.radius) * (a.radius + b.radius)) >= Collision.distanceSquared(a.x, a.y, b.x, b.y); + return true; }; CircleUtils.distanceBetween = /** * Returns the distance from the center of the Circle object to the given object (can be Circle, Point or anything with x/y properties) @@ -10835,823 +11457,7 @@ var Phaser; Phaser.CircleUtils = CircleUtils; })(Phaser || (Phaser = {})); /// -/// -/** -* Phaser - Response -* -*/ -var Phaser; -(function (Phaser) { - var Response = (function () { - /** - * An object representing the result of an intersection. Contain information about: - * - The two objects participating in the intersection - * - The vector representing the minimum change necessary to extract the first object - * from the second one. - * - Whether the first object is entirely inside the second, or vice versa. - * - * @constructor - */ - function Response() { - this.a = null; - this.b = null; - this.overlapN = new Phaser.Vec2(); - this.overlapV = new Phaser.Vec2(); - this.clear(); - } - Response.prototype.clear = /** - * Set some values of the response back to their defaults. Call this between tests if - * you are going to reuse a single Response object for multiple intersection tests (recommented) - * - * @return {Response} This for chaining - */ - function () { - this.aInB = true; - this.bInA = true; - this.overlap = Number.MAX_VALUE; - return this; - }; - return Response; - })(); - Phaser.Response = Response; -})(Phaser || (Phaser = {})); -/// -/// -/// -/** -* Phaser - RectangleUtils -* -* A collection of methods useful for manipulating and comparing Rectangle objects. -* -* TODO: Check docs + overlap + intersect + toPolygon? -*/ -var Phaser; -(function (Phaser) { - var RectangleUtils = (function () { - function RectangleUtils() { } - RectangleUtils.getTopLeftAsPoint = /** - * Get the location of the Rectangles top-left corner as a Point object. - * @method getTopLeftAsPoint - * @param {Rectangle} a - The Rectangle object. - * @param {Point} out - Optional Point to store the value in, if not supplied a new Point object will be created. - * @return {Point} The new Point object. - **/ - function getTopLeftAsPoint(a, out) { - if (typeof out === "undefined") { out = new Phaser.Point(); } - return out.setTo(a.x, a.y); - }; - RectangleUtils.getBottomRightAsPoint = /** - * Get the location of the Rectangles bottom-right corner as a Point object. - * @method getTopLeftAsPoint - * @param {Rectangle} a - The Rectangle object. - * @param {Point} out - Optional Point to store the value in, if not supplied a new Point object will be created. - * @return {Point} The new Point object. - **/ - function getBottomRightAsPoint(a, out) { - if (typeof out === "undefined") { out = new Phaser.Point(); } - return out.setTo(a.right, a.bottom); - }; - RectangleUtils.inflate = /** - * Increases the size of the Rectangle object by the specified amounts. The center point of the Rectangle object stays the same, and its size increases to the left and right by the dx value, and to the top and the bottom by the dy value. - * @method inflate - * @param {Rectangle} a - The Rectangle object. - * @param {Number} dx The amount to be added to the left side of the Rectangle. - * @param {Number} dy The amount to be added to the bottom side of the Rectangle. - * @return {Rectangle} This Rectangle object. - **/ - function inflate(a, dx, dy) { - a.x -= dx; - a.width += 2 * dx; - a.y -= dy; - a.height += 2 * dy; - return a; - }; - RectangleUtils.inflatePoint = /** - * Increases the size of the Rectangle object. This method is similar to the Rectangle.inflate() method except it takes a Point object as a parameter. - * @method inflatePoint - * @param {Rectangle} a - The Rectangle object. - * @param {Point} point The x property of this Point object is used to increase the horizontal dimension of the Rectangle object. The y property is used to increase the vertical dimension of the Rectangle object. - * @return {Rectangle} The Rectangle object. - **/ - function inflatePoint(a, point) { - return RectangleUtils.inflate(a, point.x, point.y); - }; - RectangleUtils.size = /** - * The size of the Rectangle object, expressed as a Point object with the values of the width and height properties. - * @method size - * @param {Rectangle} a - The Rectangle object. - * @param {Point} output Optional Point object. If given the values will be set into the object, otherwise a brand new Point object will be created and returned. - * @return {Point} The size of the Rectangle object - **/ - function size(a, output) { - if (typeof output === "undefined") { output = new Phaser.Point(); } - return output.setTo(a.width, a.height); - }; - RectangleUtils.clone = /** - * Returns a new Rectangle object with the same values for the x, y, width, and height properties as the original Rectangle object. - * @method clone - * @param {Rectangle} a - The Rectangle object. - * @param {Rectangle} output Optional Rectangle object. If given the values will be set into the object, otherwise a brand new Rectangle object will be created and returned. - * @return {Rectangle} - **/ - function clone(a, output) { - if (typeof output === "undefined") { output = new Phaser.Rectangle(); } - return output.setTo(a.x, a.y, a.width, a.height); - }; - RectangleUtils.contains = /** - * Determines whether the specified coordinates are contained within the region defined by this Rectangle object. - * @method contains - * @param {Rectangle} a - The Rectangle object. - * @param {Number} x The x coordinate of the point to test. - * @param {Number} y The y coordinate of the point to test. - * @return {Boolean} A value of true if the Rectangle object contains the specified point; otherwise false. - **/ - function contains(a, x, y) { - return (x >= a.x && x <= a.right && y >= a.y && y <= a.bottom); - }; - RectangleUtils.containsPoint = /** - * Determines whether the specified point is contained within the rectangular region defined by this Rectangle object. This method is similar to the Rectangle.contains() method, except that it takes a Point object as a parameter. - * @method containsPoint - * @param {Rectangle} a - The Rectangle object. - * @param {Point} point The point object being checked. Can be Point or any object with .x and .y values. - * @return {Boolean} A value of true if the Rectangle object contains the specified point; otherwise false. - **/ - function containsPoint(a, point) { - return RectangleUtils.contains(a, point.x, point.y); - }; - RectangleUtils.containsRect = /** - * Determines whether the first Rectangle object is fully contained within the second Rectangle object. - * A Rectangle object is said to contain another if the second Rectangle object falls entirely within the boundaries of the first. - * @method containsRect - * @param {Rectangle} a - The first Rectangle object. - * @param {Rectangle} b - The second Rectangle object. - * @return {Boolean} A value of true if the Rectangle object contains the specified point; otherwise false. - **/ - function containsRect(a, b) { - // If the given rect has a larger volume than this one then it can never contain it - if(a.volume > b.volume) { - return false; - } - return (a.x >= b.x && a.y >= b.y && a.right <= b.right && a.bottom <= b.bottom); - }; - RectangleUtils.equals = /** - * Determines whether the two Rectangles are equal. - * This method compares the x, y, width and height properties of each Rectangle. - * @method equals - * @param {Rectangle} a - The first Rectangle object. - * @param {Rectangle} b - The second Rectangle object. - * @return {Boolean} A value of true if the two Rectangles have exactly the same values for the x, y, width and height properties; otherwise false. - **/ - function equals(a, b) { - return (a.x == b.x && a.y == b.y && a.width == b.width && a.height == b.height); - }; - RectangleUtils.intersection = /** - * If the Rectangle object specified in the toIntersect parameter intersects with this Rectangle object, returns the area of intersection as a Rectangle object. If the rectangles do not intersect, this method returns an empty Rectangle object with its properties set to 0. - * @method intersection - * @param {Rectangle} a - The first Rectangle object. - * @param {Rectangle} b - The second Rectangle object. - * @param {Rectangle} output Optional Rectangle object. If given the intersection values will be set into this object, otherwise a brand new Rectangle object will be created and returned. - * @return {Rectangle} A Rectangle object that equals the area of intersection. If the rectangles do not intersect, this method returns an empty Rectangle object; that is, a rectangle with its x, y, width, and height properties set to 0. - **/ - function intersection(a, b, out) { - if (typeof out === "undefined") { out = new Phaser.Rectangle(); } - if(RectangleUtils.intersects(a, b)) { - out.x = Math.max(a.x, b.x); - out.y = Math.max(a.y, b.y); - out.width = Math.min(a.right, b.right) - out.x; - out.height = Math.min(a.bottom, b.bottom) - out.y; - } - return out; - }; - RectangleUtils.intersects = /** - * Determines whether the two Rectangles intersect with each other. - * This method checks the x, y, width, and height properties of the Rectangles. - * @method intersects - * @param {Rectangle} a - The first Rectangle object. - * @param {Rectangle} b - The second Rectangle object. - * @param {Number} tolerance A tolerance value to allow for an intersection test with padding, default to 0 - * @return {Boolean} A value of true if the specified object intersects with this Rectangle object; otherwise false. - **/ - function intersects(a, b, tolerance) { - if (typeof tolerance === "undefined") { tolerance = 0; } - // ? - //return (a.right > b.x) && (a.x < b.right) && (a.bottom > b.y) && (a.y < b.bottom); - return !(a.left > b.right + tolerance || a.right < b.left - tolerance || a.top > b.bottom + tolerance || a.bottom < b.top - tolerance); - //if (a.x >= b.right || a.right <= b.x || a.bottom <= b.y || a.y >= b.bottom) - //{ - // return false; - //} - //return true; - }; - RectangleUtils.intersectsRaw = /** - * Determines whether the object specified intersects (overlaps) with the given values. - * @method intersectsRaw - * @param {Number} left - * @param {Number} right - * @param {Number} top - * @param {Number} bottomt - * @param {Number} tolerance A tolerance value to allow for an intersection test with padding, default to 0 - * @return {Boolean} A value of true if the specified object intersects with the Rectangle; otherwise false. - **/ - function intersectsRaw(a, left, right, top, bottom, tolerance) { - if (typeof tolerance === "undefined") { tolerance = 0; } - return !(left > a.right + tolerance || right < a.left - tolerance || top > a.bottom + tolerance || bottom < a.top - tolerance); - }; - RectangleUtils.union = /** - * Adds two rectangles together to create a new Rectangle object, by filling in the horizontal and vertical space between the two rectangles. - * @method union - * @param {Rectangle} a - The first Rectangle object. - * @param {Rectangle} b - The second Rectangle object. - * @param {Rectangle} output Optional Rectangle object. If given the new values will be set into this object, otherwise a brand new Rectangle object will be created and returned. - * @return {Rectangle} A Rectangle object that is the union of the two rectangles. - **/ - function union(a, b, out) { - if (typeof out === "undefined") { out = new Phaser.Rectangle(); } - return out.setTo(Math.min(a.x, b.x), Math.min(a.y, b.y), Math.max(a.right, b.right), Math.max(a.bottom, b.bottom)); - }; - return RectangleUtils; - })(); - Phaser.RectangleUtils = RectangleUtils; -})(Phaser || (Phaser = {})); -/// -/** -* Phaser - TilemapLayer -* -* A Tilemap Layer. Tiled format maps can have multiple overlapping layers. -*/ -var Phaser; -(function (Phaser) { - var TilemapLayer = (function () { - /** - * TilemapLayer constructor - * Create a new TilemapLayer. - * - * @param game {Phaser.Game} Current game instance. - * @param parent {Tilemap} The tilemap that contains this layer. - * @param key {string} Asset key for this map. - * @param mapFormat {number} Format of this map data, available: Tilemap.FORMAT_CSV or Tilemap.FORMAT_TILED_JSON. - * @param name {string} Name of this layer, so you can get this layer by its name. - * @param tileWidth {number} Width of tiles in this map. - * @param tileHeight {number} Height of tiles in this map. - */ - function TilemapLayer(game, parent, key, mapFormat, name, tileWidth, tileHeight) { - this._startX = 0; - this._startY = 0; - this._maxX = 0; - this._maxY = 0; - this._tx = 0; - this._ty = 0; - this._dx = 0; - this._dy = 0; - this._oldCameraX = 0; - this._oldCameraY = 0; - /** - * Opacity of this layer. - * @type {number} - */ - this.alpha = 1; - /** - * Controls whether update() and draw() are automatically called. - * @type {boolean} - */ - this.exists = true; - /** - * Controls whether draw() are automatically called. - * @type {boolean} - */ - this.visible = true; - /** - * How many tiles in each row. - * Read-only variable, do NOT recommend changing after the map is loaded! - * @type {number} - */ - this.widthInTiles = 0; - /** - * How many tiles in each column. - * Read-only variable, do NOT recommend changing after the map is loaded! - * @type {number} - */ - this.heightInTiles = 0; - /** - * Read-only variable, do NOT recommend changing after the map is loaded! - * @type {number} - */ - this.widthInPixels = 0; - /** - * Read-only variable, do NOT recommend changing after the map is loaded! - * @type {number} - */ - this.heightInPixels = 0; - /** - * Distance between REAL tiles to the tileset texture bound. - * @type {number} - */ - this.tileMargin = 0; - /** - * Distance between every 2 neighbor tile in the tileset texture. - * @type {number} - */ - this.tileSpacing = 0; - this._game = game; - this._parent = parent; - this.name = name; - this.mapFormat = mapFormat; - this.tileWidth = tileWidth; - this.tileHeight = tileHeight; - this.boundsInTiles = new Phaser.Rectangle(); - //this.scrollFactor = new MicroPoint(1, 1); - this.canvas = game.stage.canvas; - this.context = game.stage.context; - this.mapData = []; - this._tempTileBlock = []; - this._texture = this._game.cache.getImage(key); - } - TilemapLayer.prototype.putTile = /** - * Set a specific tile with its x and y in tiles. - * @param x {number} X position of this tile. - * @param y {number} Y position of this tile. - * @param index {number} The index of this tile type in the core map data. - */ - function (x, y, index) { - x = this._game.math.snapToFloor(x, this.tileWidth) / this.tileWidth; - y = this._game.math.snapToFloor(y, this.tileHeight) / this.tileHeight; - if(y >= 0 && y < this.mapData.length) { - if(x >= 0 && x < this.mapData[y].length) { - this.mapData[y][x] = index; - } - } - }; - TilemapLayer.prototype.swapTile = /** - * Swap tiles with 2 kinds of indexes. - * @param tileA {number} First tile index. - * @param tileB {number} Second tile index. - * @param [x] {number} specify a rectangle of tiles to operate. The x position in tiles of rectangle's left-top corner. - * @param [y] {number} specify a rectangle of tiles to operate. The y position in tiles of rectangle's left-top corner. - * @param [width] {number} specify a rectangle of tiles to operate. The width in tiles. - * @param [height] {number} specify a rectangle of tiles to operate. The height in tiles. - */ - function (tileA, tileB, x, y, width, height) { - if (typeof x === "undefined") { x = 0; } - if (typeof y === "undefined") { y = 0; } - if (typeof width === "undefined") { width = this.widthInTiles; } - if (typeof height === "undefined") { height = this.heightInTiles; } - this.getTempBlock(x, y, width, height); - for(var r = 0; r < this._tempTileBlock.length; r++) { - // First sweep marking tileA as needing a new index - if(this._tempTileBlock[r].tile.index == tileA) { - this._tempTileBlock[r].newIndex = true; - } - // In the same pass we can swap tileB to tileA - if(this._tempTileBlock[r].tile.index == tileB) { - this.mapData[this._tempTileBlock[r].y][this._tempTileBlock[r].x] = tileA; - } - } - for(var r = 0; r < this._tempTileBlock.length; r++) { - // And now swap our newIndex tiles for tileB - if(this._tempTileBlock[r].newIndex == true) { - this.mapData[this._tempTileBlock[r].y][this._tempTileBlock[r].x] = tileB; - } - } - }; - TilemapLayer.prototype.fillTile = /** - * Fill a tile block with a specific tile index. - * @param index {number} Index of tiles you want to fill with. - * @param [x] {number} x position (in tiles) of block's left-top corner. - * @param [y] {number} y position (in tiles) of block's left-top corner. - * @param [width] {number} width of block. - * @param [height] {number} height of block. - */ - function (index, x, y, width, height) { - if (typeof x === "undefined") { x = 0; } - if (typeof y === "undefined") { y = 0; } - if (typeof width === "undefined") { width = this.widthInTiles; } - if (typeof height === "undefined") { height = this.heightInTiles; } - this.getTempBlock(x, y, width, height); - for(var r = 0; r < this._tempTileBlock.length; r++) { - this.mapData[this._tempTileBlock[r].y][this._tempTileBlock[r].x] = index; - } - }; - TilemapLayer.prototype.randomiseTiles = /** - * Set random tiles to a specific tile block. - * @param tiles {number[]} Tiles with indexes in this array will be randomly set to the given block. - * @param [x] {number} x position (in tiles) of block's left-top corner. - * @param [y] {number} y position (in tiles) of block's left-top corner. - * @param [width] {number} width of block. - * @param [height] {number} height of block. - */ - function (tiles, x, y, width, height) { - if (typeof x === "undefined") { x = 0; } - if (typeof y === "undefined") { y = 0; } - if (typeof width === "undefined") { width = this.widthInTiles; } - if (typeof height === "undefined") { height = this.heightInTiles; } - this.getTempBlock(x, y, width, height); - for(var r = 0; r < this._tempTileBlock.length; r++) { - this.mapData[this._tempTileBlock[r].y][this._tempTileBlock[r].x] = this._game.math.getRandom(tiles); - } - }; - TilemapLayer.prototype.replaceTile = /** - * Replace one kind of tiles to another kind. - * @param tileA {number} Index of tiles you want to replace. - * @param tileB {number} Index of tiles you want to set. - * @param [x] {number} x position (in tiles) of block's left-top corner. - * @param [y] {number} y position (in tiles) of block's left-top corner. - * @param [width] {number} width of block. - * @param [height] {number} height of block. - */ - function (tileA, tileB, x, y, width, height) { - if (typeof x === "undefined") { x = 0; } - if (typeof y === "undefined") { y = 0; } - if (typeof width === "undefined") { width = this.widthInTiles; } - if (typeof height === "undefined") { height = this.heightInTiles; } - this.getTempBlock(x, y, width, height); - for(var r = 0; r < this._tempTileBlock.length; r++) { - if(this._tempTileBlock[r].tile.index == tileA) { - this.mapData[this._tempTileBlock[r].y][this._tempTileBlock[r].x] = tileB; - } - } - }; - TilemapLayer.prototype.getTileBlock = /** - * Get a tile block with specific position and size.(both are in tiles) - * @param x {number} X position of block's left-top corner. - * @param y {number} Y position of block's left-top corner. - * @param width {number} Width of block. - * @param height {number} Height of block. - */ - function (x, y, width, height) { - var output = []; - this.getTempBlock(x, y, width, height); - for(var r = 0; r < this._tempTileBlock.length; r++) { - output.push({ - x: this._tempTileBlock[r].x, - y: this._tempTileBlock[r].y, - tile: this._tempTileBlock[r].tile - }); - } - return output; - }; - TilemapLayer.prototype.getTileFromWorldXY = /** - * Get a tile with specific position (in world coordinate). (thus you give a position of a point which is within the tile) - * @param x {number} X position of the point in target tile. - * @param x {number} Y position of the point in target tile. - */ - function (x, y) { - x = this._game.math.snapToFloor(x, this.tileWidth) / this.tileWidth; - y = this._game.math.snapToFloor(y, this.tileHeight) / this.tileHeight; - return this.getTileIndex(x, y); - }; - TilemapLayer.prototype.getTileOverlaps = /** - * Get tiles overlaps the given object. - * @param object {GameObject} Tiles you want to get that overlaps this. - * @return {array} Array with tiles informations. (Each contains x, y and the tile.) - */ - function (object) { - // If the object is outside of the world coordinates then abort the check (tilemap has to exist within world bounds) - if(object.collisionMask.x < 0 || object.collisionMask.x > this.widthInPixels || object.collisionMask.y < 0 || object.collisionMask.bottom > this.heightInPixels) { - return; - } - // What tiles do we need to check against? - this._tempTileX = this._game.math.snapToFloor(object.collisionMask.x, this.tileWidth) / this.tileWidth; - this._tempTileY = this._game.math.snapToFloor(object.collisionMask.y, this.tileHeight) / this.tileHeight; - this._tempTileW = (this._game.math.snapToCeil(object.collisionMask.width, this.tileWidth) + this.tileWidth) / this.tileWidth; - this._tempTileH = (this._game.math.snapToCeil(object.collisionMask.height, this.tileHeight) + this.tileHeight) / this.tileHeight; - // Loop through the tiles we've got and check overlaps accordingly (the results are stored in this._tempTileBlock) - this._tempBlockResults = []; - this.getTempBlock(this._tempTileX, this._tempTileY, this._tempTileW, this._tempTileH, true); - Collision.TILE_OVERLAP = false; - for(var r = 0; r < this._tempTileBlock.length; r++) { - if(Collision.separateTile(object, this._tempTileBlock[r].x * this.tileWidth, this._tempTileBlock[r].y * this.tileHeight, this.tileWidth, this.tileHeight, this._tempTileBlock[r].tile.mass, this._tempTileBlock[r].tile.collideLeft, this._tempTileBlock[r].tile.collideRight, this._tempTileBlock[r].tile.collideUp, this._tempTileBlock[r].tile.collideDown, this._tempTileBlock[r].tile.separateX, this._tempTileBlock[r].tile.separateY) == true) { - this._tempBlockResults.push({ - x: this._tempTileBlock[r].x, - y: this._tempTileBlock[r].y, - tile: this._tempTileBlock[r].tile - }); - } - } - return this._tempBlockResults; - }; - TilemapLayer.prototype.getTempBlock = /** - * Get a tile block with its position and size. (This method does not return, it'll set result to _tempTileBlock) - * @param x {number} X position of block's left-top corner. - * @param y {number} Y position of block's left-top corner. - * @param width {number} Width of block. - * @param height {number} Height of block. - * @param collisionOnly {boolean} Whethor or not ONLY return tiles which will collide (its allowCollisions value is not Collision.NONE). - */ - function (x, y, width, height, collisionOnly) { - if (typeof collisionOnly === "undefined") { collisionOnly = false; } - if(x < 0) { - x = 0; - } - if(y < 0) { - y = 0; - } - if(width > this.widthInTiles) { - width = this.widthInTiles; - } - if(height > this.heightInTiles) { - height = this.heightInTiles; - } - this._tempTileBlock = []; - for(var ty = y; ty < y + height; ty++) { - for(var tx = x; tx < x + width; tx++) { - if(collisionOnly) { - // We only want to consider the tile for checking if you can actually collide with it - if(this.mapData[ty] && this.mapData[ty][tx] && this._parent.tiles[this.mapData[ty][tx]].allowCollisions != Collision.NONE) { - this._tempTileBlock.push({ - x: tx, - y: ty, - tile: this._parent.tiles[this.mapData[ty][tx]] - }); - } - } else { - if(this.mapData[ty] && this.mapData[ty][tx]) { - this._tempTileBlock.push({ - x: tx, - y: ty, - tile: this._parent.tiles[this.mapData[ty][tx]] - }); - } - } - } - } - }; - TilemapLayer.prototype.getTileIndex = /** - * Get the tile index of specific position (in tiles). - * @param x {number} X position of the tile. - * @param y {number} Y position of the tile. - * @return {number} Index of the tile at that position. Return null if there isn't a tile there. - */ - function (x, y) { - if(y >= 0 && y < this.mapData.length) { - if(x >= 0 && x < this.mapData[y].length) { - return this.mapData[y][x]; - } - } - return null; - }; - TilemapLayer.prototype.addColumn = /** - * Add a column of tiles into the layer. - * @param column {string[]/number[]} An array of tile indexes to be added. - */ - function (column) { - var data = []; - for(var c = 0; c < column.length; c++) { - data[c] = parseInt(column[c]); - } - if(this.widthInTiles == 0) { - this.widthInTiles = data.length; - this.widthInPixels = this.widthInTiles * this.tileWidth; - } - this.mapData.push(data); - this.heightInTiles++; - this.heightInPixels += this.tileHeight; - }; - TilemapLayer.prototype.updateBounds = /** - * Update boundsInTiles with widthInTiles and heightInTiles. - */ - function () { - this.boundsInTiles.setTo(0, 0, this.widthInTiles, this.heightInTiles); - }; - TilemapLayer.prototype.parseTileOffsets = /** - * Parse tile offsets from map data. - * @return {number} length of _tileOffsets array. - */ - function () { - this._tileOffsets = []; - var i = 0; - if(this.mapFormat == Tilemap.FORMAT_TILED_JSON) { - // For some reason Tiled counts from 1 not 0 - this._tileOffsets[0] = null; - i = 1; - } - for(var ty = this.tileMargin; ty < this._texture.height; ty += (this.tileHeight + this.tileSpacing)) { - for(var tx = this.tileMargin; tx < this._texture.width; tx += (this.tileWidth + this.tileSpacing)) { - this._tileOffsets[i] = { - x: tx, - y: ty - }; - i++; - } - } - return this._tileOffsets.length; - }; - TilemapLayer.prototype.renderDebugInfo = function (x, y, color) { - if (typeof color === "undefined") { color = 'rgb(255,255,255)'; } - this.context.fillStyle = color; - this.context.fillText('TilemapLayer: ' + this.name, x, y); - this.context.fillText('startX: ' + this._startX + ' endX: ' + this._maxX, x, y + 14); - this.context.fillText('startY: ' + this._startY + ' endY: ' + this._maxY, x, y + 28); - this.context.fillText('dx: ' + this._dx + ' dy: ' + this._dy, x, y + 42); - }; - TilemapLayer.prototype.render = /** - * Render this layer to a specific camera with offset to camera. - * @param camera {Camera} The camera the layer is going to be rendered. - * @param dx {number} X offset to the camera. - * @param dy {number} Y offset to the camera. - * @return {boolean} Return false if layer is invisible or has a too low opacity(will stop rendering), return true if succeed. - */ - function (camera, dx, dy) { - if(this.visible === false || this.alpha < 0.1) { - return false; - } - // Work out how many tiles we can fit into our camera and round it up for the edges - this._maxX = this._game.math.ceil(camera.width / this.tileWidth) + 1; - this._maxY = this._game.math.ceil(camera.height / this.tileHeight) + 1; - // And now work out where in the tilemap the camera actually is - this._startX = this._game.math.floor(camera.worldView.x / this.tileWidth); - this._startY = this._game.math.floor(camera.worldView.y / this.tileHeight); - // Tilemap bounds check - if(this._startX < 0) { - this._startX = 0; - } - if(this._startY < 0) { - this._startY = 0; - } - if(this._maxX > this.widthInTiles) { - this._maxX = this.widthInTiles; - } - if(this._maxY > this.heightInTiles) { - this._maxY = this.heightInTiles; - } - if(this._startX + this._maxX > this.widthInTiles) { - this._startX = this.widthInTiles - this._maxX; - } - if(this._startY + this._maxY > this.heightInTiles) { - this._startY = this.heightInTiles - this._maxY; - } - // Finally get the offset to avoid the blocky movement - this._dx = dx; - this._dy = dy; - this._dx += -(camera.worldView.x - (this._startX * this.tileWidth)); - this._dy += -(camera.worldView.y - (this._startY * this.tileHeight)); - this._tx = this._dx; - this._ty = this._dy; - // Apply camera difference - /* - if (this.scrollFactor.x !== 1.0 || this.scrollFactor.y !== 1.0) - { - this._dx -= (camera.worldView.x * this.scrollFactor.x); - this._dy -= (camera.worldView.y * this.scrollFactor.y); - } - */ - // Alpha - if(this.alpha !== 1) { - var globalAlpha = this.context.globalAlpha; - this.context.globalAlpha = this.alpha; - } - for(var row = this._startY; row < this._startY + this._maxY; row++) { - this._columnData = this.mapData[row]; - for(var tile = this._startX; tile < this._startX + this._maxX; tile++) { - if(this._tileOffsets[this._columnData[tile]]) { - this.context.drawImage(this._texture, // Source Image - this._tileOffsets[this._columnData[tile]].x, // Source X (location within the source image) - this._tileOffsets[this._columnData[tile]].y, // Source Y - this.tileWidth, // Source Width - this.tileHeight, // Source Height - this._tx, // Destination X (where on the canvas it'll be drawn) - this._ty, // Destination Y - this.tileWidth, // Destination Width (always same as Source Width unless scaled) - this.tileHeight); - // Destination Height (always same as Source Height unless scaled) - } - this._tx += this.tileWidth; - } - this._tx = this._dx; - this._ty += this.tileHeight; - } - if(globalAlpha > -1) { - this.context.globalAlpha = globalAlpha; - } - return true; - }; - return TilemapLayer; - })(); - Phaser.TilemapLayer = TilemapLayer; -})(Phaser || (Phaser = {})); -/// -/** -* Phaser - Tile -* -* A Tile is a single representation of a tile within a Tilemap -*/ -var Phaser; -(function (Phaser) { - var Tile = (function () { - /** - * Tile constructor - * Create a new Tile. - * - * @param tilemap {Tilemap} the tilemap this tile belongs to. - * @param index {number} The index of this tile type in the core map data. - * @param width {number} Width of the tile. - * @param height number} Height of the tile. - */ - function Tile(game, tilemap, index, width, height) { - /** - * The virtual mass of the tile. - * @type {number} - */ - this.mass = 1.0; - /** - * Indicating collide with any object on the left. - * @type {boolean} - */ - this.collideLeft = false; - /** - * Indicating collide with any object on the right. - * @type {boolean} - */ - this.collideRight = false; - /** - * Indicating collide with any object on the top. - * @type {boolean} - */ - this.collideUp = false; - /** - * Indicating collide with any object on the bottom. - * @type {boolean} - */ - this.collideDown = false; - /** - * Enable separation at x-axis. - * @type {boolean} - */ - this.separateX = true; - /** - * Enable separation at y-axis. - * @type {boolean} - */ - this.separateY = true; - this._game = game; - this.tilemap = tilemap; - this.index = index; - this.width = width; - this.height = height; - this.allowCollisions = Collision.NONE; - } - Tile.prototype.destroy = /** - * Clean up memory. - */ - function () { - this.tilemap = null; - }; - Tile.prototype.setCollision = /** - * Set collision configs. - * @param collision {number} Bit field of flags. (see Tile.allowCollision) - * @param resetCollisions {boolean} Reset collision flags before set. - * @param separateX {boolean} Enable seprate at x-axis. - * @param separateY {boolean} Enable seprate at y-axis. - */ - function (collision, resetCollisions, separateX, separateY) { - if(resetCollisions) { - this.resetCollision(); - } - this.separateX = separateX; - this.separateY = separateY; - this.allowCollisions = collision; - if(collision & Collision.ANY) { - this.collideLeft = true; - this.collideRight = true; - this.collideUp = true; - this.collideDown = true; - return; - } - if(collision & Collision.LEFT || collision & Collision.WALL) { - this.collideLeft = true; - } - if(collision & Collision.RIGHT || collision & Collision.WALL) { - this.collideRight = true; - } - if(collision & Collision.UP || collision & Collision.CEILING) { - this.collideUp = true; - } - if(collision & Collision.DOWN || collision & Collision.CEILING) { - this.collideDown = true; - } - }; - Tile.prototype.resetCollision = /** - * Reset collision status flags. - */ - function () { - this.allowCollisions = Collision.NONE; - this.collideLeft = false; - this.collideRight = false; - this.collideUp = false; - this.collideDown = false; - }; - Tile.prototype.toString = /** - * Returns a string representation of this object. - * @method toString - * @return {string} a string representation of the object. - **/ - function () { - return "[{Tiled (index=" + this.index + " collisions=" + this.allowCollisions + " width=" + this.width + " height=" + this.height + ")}]"; - }; - return Tile; - })(); - Phaser.Tile = Tile; -})(Phaser || (Phaser = {})); -/// +/// /** * Phaser - LinkedList * @@ -11688,6 +11494,7 @@ var __extends = this.__extends || function (d, b) { }; /// /// +/// /** * Phaser - QuadTree * @@ -11715,30 +11522,28 @@ var Phaser; this._headB = this._tailB = new Phaser.LinkedList(); //Copy the parent's children (if there are any) if(parent != null) { - var iterator; - var ot; if(parent._headA.object != null) { - iterator = parent._headA; - while(iterator != null) { + this._iterator = parent._headA; + while(this._iterator != null) { if(this._tailA.object != null) { - ot = this._tailA; + this._ot = this._tailA; this._tailA = new Phaser.LinkedList(); - ot.next = this._tailA; + this._ot.next = this._tailA; } - this._tailA.object = iterator.object; - iterator = iterator.next; + this._tailA.object = this._iterator.object; + this._iterator = this._iterator.next; } } if(parent._headB.object != null) { - iterator = parent._headB; - while(iterator != null) { + this._iterator = parent._headB; + while(this._iterator != null) { if(this._tailB.object != null) { - ot = this._tailB; + this._ot = this._tailB; this._tailB = new Phaser.LinkedList(); - ot.next = this._tailB; + this._ot.next = this._tailB; } - this._tailB.object = iterator.object; - iterator = iterator.next; + this._tailB.object = this._iterator.object; + this._iterator = this._iterator.next; } } } else { @@ -11796,8 +11601,8 @@ var Phaser; QuadTree.prototype.load = /** * Load objects and/or groups into the quad tree, and register notify and processing callbacks. * - * @param {Basic} objectOrGroup1 Any object that is or extends GameObject or Group. - * @param {Basic} objectOrGroup2 Any object that is or extends GameObject or Group. If null, the first parameter will be checked against itself. + * @param {} objectOrGroup1 Any object that is or extends IGameObject or Group. + * @param {} objectOrGroup2 Any object that is or extends IGameObject or Group. If null, the first parameter will be checked against itself. * @param {Function} notifyCallback A function with the form myFunction(Object1:GameObject,Object2:GameObject) that is called whenever two objects are found to overlap in world space, and either no processCallback is specified, or the processCallback returns true. * @param {Function} processCallback A function with the form myFunction(Object1:GameObject,Object2:GameObject):bool that is called whenever two objects are found to overlap in world space. The notifyCallback is only called if this function returns true. See GameObject.separate(). * @param context The context in which the callbacks will be called @@ -11823,23 +11628,22 @@ var Phaser; * This function will recursively add all group members, but * not the groups themselves. * - * @param {Basic} objectOrGroup GameObjects are just added, Groups are recursed and their applicable members added accordingly. + * @param {} objectOrGroup GameObjects are just added, Groups are recursed and their applicable members added accordingly. * @param {Number} list A uint flag indicating the list to which you want to add the objects. Options are QuadTree.A_LIST and QuadTree.B_LIST. */ function (objectOrGroup, list) { QuadTree._list = list; if(objectOrGroup.isGroup == true) { - var i = 0; - var basic; - var members = objectOrGroup['members']; - var l = objectOrGroup['length']; - while(i < l) { - basic = members[i++]; - if((basic != null) && basic.exists) { - if(basic.isGroup) { - this.add(basic, list); + this._i = 0; + this._members = objectOrGroup['members']; + this._l = objectOrGroup['length']; + while(this._i < this._l) { + this._basic = this._members[this._i++]; + if(this._basic != null && this._basic.exists) { + if(this._basic.type == Phaser.Types.GROUP) { + this.add(this._basic, list); } else { - QuadTree._object = basic; + QuadTree._object = this._basic; if(QuadTree._object.exists && QuadTree._object.allowCollisions) { this.addObject(); } @@ -11926,19 +11730,18 @@ var Phaser; * Internal function for recursively adding objects to leaf lists. */ function () { - var ot; if(QuadTree._list == QuadTree.A_LIST) { if(this._tailA.object != null) { - ot = this._tailA; + this._ot = this._tailA; this._tailA = new Phaser.LinkedList(); - ot.next = this._tailA; + this._ot.next = this._tailA; } this._tailA.object = QuadTree._object; } else { if(this._tailB.object != null) { - ot = this._tailB; + this._ot = this._tailB; this._tailB = new Phaser.LinkedList(); - ot.next = this._tailB; + this._ot.next = this._tailB; } this._tailB.object = QuadTree._object; } @@ -11965,37 +11768,36 @@ var Phaser; * @return {Boolean} Whether or not any overlaps were found. */ function () { - var overlapProcessed = false; - var iterator; + this._overlapProcessed = false; if(this._headA.object != null) { - iterator = this._headA; - while(iterator != null) { - QuadTree._object = iterator.object; + this._iterator = this._headA; + while(this._iterator != null) { + QuadTree._object = this._iterator.object; if(QuadTree._useBothLists) { QuadTree._iterator = this._headB; } else { - QuadTree._iterator = iterator.next; + QuadTree._iterator = this._iterator.next; } if(QuadTree._object.exists && (QuadTree._object.allowCollisions > 0) && (QuadTree._iterator != null) && (QuadTree._iterator.object != null) && QuadTree._iterator.object.exists && this.overlapNode()) { - overlapProcessed = true; + this._overlapProcessed = true; } - iterator = iterator.next; + this._iterator = this._iterator.next; } } //Advance through the tree by calling overlap on each child if((this._northWestTree != null) && this._northWestTree.execute()) { - overlapProcessed = true; + this._overlapProcessed = true; } if((this._northEastTree != null) && this._northEastTree.execute()) { - overlapProcessed = true; + this._overlapProcessed = true; } if((this._southEastTree != null) && this._southEastTree.execute()) { - overlapProcessed = true; + this._overlapProcessed = true; } if((this._southWestTree != null) && this._southWestTree.execute()) { - overlapProcessed = true; + this._overlapProcessed = true; } - return overlapProcessed; + return this._overlapProcessed; }; QuadTree.prototype.overlapNode = /** * A private for comparing an object against the contents of a node. @@ -12004,531 +11806,38 @@ var Phaser; */ function () { //Walk the list and check for overlaps - var overlapProcessed = false; - var checkObject; + this._overlapProcessed = false; while(QuadTree._iterator != null) { if(!QuadTree._object.exists || (QuadTree._object.allowCollisions <= 0)) { break; } - checkObject = QuadTree._iterator.object; - if((QuadTree._object === checkObject) || !checkObject.exists || (checkObject.allowCollisions <= 0)) { + this._checkObject = QuadTree._iterator.object; + if((QuadTree._object === this._checkObject) || !this._checkObject.exists || (this._checkObject.allowCollisions <= 0)) { QuadTree._iterator = QuadTree._iterator.next; continue; } - if(QuadTree._object.collisionMask.checkHullIntersection(checkObject.collisionMask)) { + if(QuadTree._object.collisionMask.checkHullIntersection(this._checkObject.collisionMask)) { //Execute callback functions if they exist - if((QuadTree._processingCallback == null) || QuadTree._processingCallback(QuadTree._object, checkObject)) { - overlapProcessed = true; + if((QuadTree._processingCallback == null) || QuadTree._processingCallback(QuadTree._object, this._checkObject)) { + this._overlapProcessed = true; } - if(overlapProcessed && (QuadTree._notifyCallback != null)) { + if(this._overlapProcessed && (QuadTree._notifyCallback != null)) { if(QuadTree._callbackContext !== null) { - QuadTree._notifyCallback.call(QuadTree._callbackContext, QuadTree._object, checkObject); + QuadTree._notifyCallback.call(QuadTree._callbackContext, QuadTree._object, this._checkObject); } else { - QuadTree._notifyCallback(QuadTree._object, checkObject); + QuadTree._notifyCallback(QuadTree._object, this._checkObject); } } } QuadTree._iterator = QuadTree._iterator.next; } - return overlapProcessed; + return this._overlapProcessed; }; return QuadTree; })(Phaser.Rectangle); Phaser.QuadTree = QuadTree; })(Phaser || (Phaser = {})); /// -/// -/** -* Phaser - Touch -* -* The Touch class handles touch interactions with the game and the resulting Pointer objects. -* http://www.w3.org/TR/touch-events/ -* https://developer.mozilla.org/en-US/docs/DOM/TouchList -* http://www.html5rocks.com/en/mobile/touchandmouse/ -* Note: Android 2.x only supports 1 touch event at once, no multi-touch -*/ -var Phaser; -(function (Phaser) { - var Touch = (function () { - /** - * Constructor - * @param {Game} game. - * @return {Touch} This object. - */ - function Touch(game) { - /** - * You can disable all Input by setting disabled = true. While set all new input related events will be ignored. - * @type {Boolean} - */ - this.disabled = false; - this._game = game; - } - Touch.prototype.start = /** - * Starts the event listeners running - * @method start - */ - function () { - var _this = this; - if(this._game.device.touch) { - this._game.stage.canvas.addEventListener('touchstart', function (event) { - return _this.onTouchStart(event); - }, false); - this._game.stage.canvas.addEventListener('touchmove', function (event) { - return _this.onTouchMove(event); - }, false); - this._game.stage.canvas.addEventListener('touchend', function (event) { - return _this.onTouchEnd(event); - }, false); - this._game.stage.canvas.addEventListener('touchenter', function (event) { - return _this.onTouchEnter(event); - }, false); - this._game.stage.canvas.addEventListener('touchleave', function (event) { - return _this.onTouchLeave(event); - }, false); - this._game.stage.canvas.addEventListener('touchcancel', function (event) { - return _this.onTouchCancel(event); - }, false); - document.addEventListener('touchmove', function (event) { - return _this.consumeTouchMove(event); - }, false); - } - }; - Touch.prototype.consumeTouchMove = /** - * Prevent iOS bounce-back (doesn't work?) - * @method consumeTouchMove - * @param {Any} event - **/ - function (event) { - event.preventDefault(); - }; - Touch.prototype.onTouchStart = /** - * - * @method onTouchStart - * @param {Any} event - **/ - function (event) { - if(this._game.input.disabled || this.disabled) { - return; - } - event.preventDefault(); - // event.targetTouches = list of all touches on the TARGET ELEMENT (i.e. game dom element) - // event.touches = list of all touches on the ENTIRE DOCUMENT, not just the target element - // event.changedTouches = the touches that CHANGED in this event, not the total number of them - for(var i = 0; i < event.changedTouches.length; i++) { - this._game.input.startPointer(event.changedTouches[i]); - } - }; - Touch.prototype.onTouchCancel = /** - * Touch cancel - touches that were disrupted (perhaps by moving into a plugin or browser chrome) - * Occurs for example on iOS when you put down 4 fingers and the app selector UI appears - * @method onTouchCancel - * @param {Any} event - **/ - function (event) { - if(this._game.input.disabled || this.disabled) { - return; - } - event.preventDefault(); - // Touch cancel - touches that were disrupted (perhaps by moving into a plugin or browser chrome) - // http://www.w3.org/TR/touch-events/#dfn-touchcancel - for(var i = 0; i < event.changedTouches.length; i++) { - this._game.input.stopPointer(event.changedTouches[i]); - } - }; - Touch.prototype.onTouchEnter = /** - * For touch enter and leave its a list of the touch points that have entered or left the target - * Doesn't appear to be supported by most browsers yet - * @method onTouchEnter - * @param {Any} event - **/ - function (event) { - if(this._game.input.disabled || this.disabled) { - return; - } - event.preventDefault(); - for(var i = 0; i < event.changedTouches.length; i++) { - console.log('touch enter'); - } - }; - Touch.prototype.onTouchLeave = /** - * For touch enter and leave its a list of the touch points that have entered or left the target - * Doesn't appear to be supported by most browsers yet - * @method onTouchLeave - * @param {Any} event - **/ - function (event) { - event.preventDefault(); - for(var i = 0; i < event.changedTouches.length; i++) { - console.log('touch leave'); - } - }; - Touch.prototype.onTouchMove = /** - * - * @method onTouchMove - * @param {Any} event - **/ - function (event) { - event.preventDefault(); - for(var i = 0; i < event.changedTouches.length; i++) { - this._game.input.updatePointer(event.changedTouches[i]); - } - }; - Touch.prototype.onTouchEnd = /** - * - * @method onTouchEnd - * @param {Any} event - **/ - function (event) { - event.preventDefault(); - // For touch end its a list of the touch points that have been removed from the surface - // https://developer.mozilla.org/en-US/docs/DOM/TouchList - // event.changedTouches = the touches that CHANGED in this event, not the total number of them - for(var i = 0; i < event.changedTouches.length; i++) { - this._game.input.stopPointer(event.changedTouches[i]); - } - }; - Touch.prototype.stop = /** - * Stop the event listeners - * @method stop - */ - function () { - if(this._game.device.touch) { - //this._domElement.addEventListener('touchstart', (event) => this.onTouchStart(event), false); - //this._domElement.addEventListener('touchmove', (event) => this.onTouchMove(event), false); - //this._domElement.addEventListener('touchend', (event) => this.onTouchEnd(event), false); - //this._domElement.addEventListener('touchenter', (event) => this.onTouchEnter(event), false); - //this._domElement.addEventListener('touchleave', (event) => this.onTouchLeave(event), false); - //this._domElement.addEventListener('touchcancel', (event) => this.onTouchCancel(event), false); - } - }; - return Touch; - })(); - Phaser.Touch = Touch; -})(Phaser || (Phaser = {})); -/// -/** -* Phaser - Mouse -* -* The Mouse class handles mouse interactions with the game and the resulting events. -*/ -var Phaser; -(function (Phaser) { - var Mouse = (function () { - function Mouse(game) { - /** - * You can disable all Input by setting disabled = true. While set all new input related events will be ignored. - * @type {Boolean} - */ - this.disabled = false; - this._game = game; - } - Mouse.LEFT_BUTTON = 0; - Mouse.MIDDLE_BUTTON = 1; - Mouse.RIGHT_BUTTON = 2; - Mouse.prototype.start = /** - * Starts the event listeners running - * @method start - */ - function () { - var _this = this; - this._game.stage.canvas.addEventListener('mousedown', function (event) { - return _this.onMouseDown(event); - }, true); - this._game.stage.canvas.addEventListener('mousemove', function (event) { - return _this.onMouseMove(event); - }, true); - this._game.stage.canvas.addEventListener('mouseup', function (event) { - return _this.onMouseUp(event); - }, true); - }; - Mouse.prototype.onMouseDown = /** - * @param {MouseEvent} event - */ - function (event) { - if(this._game.input.disabled || this.disabled) { - return; - } - event['identifier'] = 0; - this._game.input.mousePointer.start(event); - }; - Mouse.prototype.onMouseMove = /** - * @param {MouseEvent} event - */ - function (event) { - if(this._game.input.disabled || this.disabled) { - return; - } - event['identifier'] = 0; - this._game.input.mousePointer.move(event); - }; - Mouse.prototype.onMouseUp = /** - * @param {MouseEvent} event - */ - function (event) { - if(this._game.input.disabled || this.disabled) { - return; - } - event['identifier'] = 0; - this._game.input.mousePointer.stop(event); - }; - Mouse.prototype.stop = /** - * Stop the event listeners - * @method stop - */ - function () { - //this._game.stage.canvas.addEventListener('mousedown', (event: MouseEvent) => this.onMouseDown(event), true); - //this._game.stage.canvas.addEventListener('mousemove', (event: MouseEvent) => this.onMouseMove(event), true); - //this._game.stage.canvas.addEventListener('mouseup', (event: MouseEvent) => this.onMouseUp(event), true); - }; - return Mouse; - })(); - Phaser.Mouse = Mouse; -})(Phaser || (Phaser = {})); -/// -/** -* Phaser - Keyboard -* -* The Keyboard class handles keyboard interactions with the game and the resulting events. -* The avoid stealing all browser input we don't use event.preventDefault. If you would like to trap a specific key however -* then use the addKeyCapture() method. -*/ -var Phaser; -(function (Phaser) { - var Keyboard = (function () { - function Keyboard(game) { - this._keys = { - }; - this._capture = { - }; - /** - * You can disable all Input by setting disabled = true. While set all new input related events will be ignored. - * @type {Boolean} - */ - this.disabled = false; - this._game = game; - } - Keyboard.prototype.start = function () { - var _this = this; - document.body.addEventListener('keydown', function (event) { - return _this.onKeyDown(event); - }, false); - document.body.addEventListener('keyup', function (event) { - return _this.onKeyUp(event); - }, false); - }; - Keyboard.prototype.addKeyCapture = /** - * By default when a key is pressed Phaser will not stop the event from propagating up to the browser. - * There are some keys this can be annoying for, like the arrow keys or space bar, which make the browser window scroll. - * You can use addKeyCapture to consume the keyboard event for specific keys so it doesn't bubble up to the the browser. - * Pass in either a single keycode or an array of keycodes. - * @param {Any} keycode - */ - function (keycode) { - if(typeof keycode === 'object') { - for(var i = 0; i < keycode.length; i++) { - this._capture[keycode[i]] = true; - } - } else { - this._capture[keycode] = true; - } - }; - Keyboard.prototype.removeKeyCapture = /** - * @param {Number} keycode - */ - function (keycode) { - delete this._capture[keycode]; - }; - Keyboard.prototype.clearCaptures = function () { - this._capture = { - }; - }; - Keyboard.prototype.onKeyDown = /** - * @param {KeyboardEvent} event - */ - function (event) { - if(this._game.input.disabled || this.disabled) { - return; - } - if(this._capture[event.keyCode]) { - event.preventDefault(); - } - if(!this._keys[event.keyCode]) { - this._keys[event.keyCode] = { - isDown: true, - timeDown: this._game.time.now, - timeUp: 0 - }; - } else { - this._keys[event.keyCode].isDown = true; - this._keys[event.keyCode].timeDown = this._game.time.now; - } - }; - Keyboard.prototype.onKeyUp = /** - * @param {KeyboardEvent} event - */ - function (event) { - if(this._game.input.disabled || this.disabled) { - return; - } - if(this._capture[event.keyCode]) { - event.preventDefault(); - } - if(!this._keys[event.keyCode]) { - this._keys[event.keyCode] = { - isDown: false, - timeDown: 0, - timeUp: this._game.time.now - }; - } else { - this._keys[event.keyCode].isDown = false; - this._keys[event.keyCode].timeUp = this._game.time.now; - } - }; - Keyboard.prototype.reset = function () { - for(var key in this._keys) { - this._keys[key].isDown = false; - } - }; - Keyboard.prototype.justPressed = /** - * @param {Number} keycode - * @param {Number} [duration] - * @return {Boolean} - */ - function (keycode, duration) { - if (typeof duration === "undefined") { duration = 250; } - if(this._keys[keycode] && this._keys[keycode].isDown === true && (this._game.time.now - this._keys[keycode].timeDown < duration)) { - return true; - } else { - return false; - } - }; - Keyboard.prototype.justReleased = /** - * @param {Number} keycode - * @param {Number} [duration] - * @return {Boolean} - */ - function (keycode, duration) { - if (typeof duration === "undefined") { duration = 250; } - if(this._keys[keycode] && this._keys[keycode].isDown === false && (this._game.time.now - this._keys[keycode].timeUp < duration)) { - return true; - } else { - return false; - } - }; - Keyboard.prototype.isDown = /** - * @param {Number} keycode - * @return {Boolean} - */ - function (keycode) { - if(this._keys[keycode]) { - return this._keys[keycode].isDown; - } else { - return false; - } - }; - Keyboard.A = "A".charCodeAt(0); - Keyboard.B = "B".charCodeAt(0); - Keyboard.C = "C".charCodeAt(0); - Keyboard.D = "D".charCodeAt(0); - Keyboard.E = "E".charCodeAt(0); - Keyboard.F = "F".charCodeAt(0); - Keyboard.G = "G".charCodeAt(0); - Keyboard.H = "H".charCodeAt(0); - Keyboard.I = "I".charCodeAt(0); - Keyboard.J = "J".charCodeAt(0); - Keyboard.K = "K".charCodeAt(0); - Keyboard.L = "L".charCodeAt(0); - Keyboard.M = "M".charCodeAt(0); - Keyboard.N = "N".charCodeAt(0); - Keyboard.O = "O".charCodeAt(0); - Keyboard.P = "P".charCodeAt(0); - Keyboard.Q = "Q".charCodeAt(0); - Keyboard.R = "R".charCodeAt(0); - Keyboard.S = "S".charCodeAt(0); - Keyboard.T = "T".charCodeAt(0); - Keyboard.U = "U".charCodeAt(0); - Keyboard.V = "V".charCodeAt(0); - Keyboard.W = "W".charCodeAt(0); - Keyboard.X = "X".charCodeAt(0); - Keyboard.Y = "Y".charCodeAt(0); - Keyboard.Z = "Z".charCodeAt(0); - Keyboard.ZERO = "0".charCodeAt(0); - Keyboard.ONE = "1".charCodeAt(0); - Keyboard.TWO = "2".charCodeAt(0); - Keyboard.THREE = "3".charCodeAt(0); - Keyboard.FOUR = "4".charCodeAt(0); - Keyboard.FIVE = "5".charCodeAt(0); - Keyboard.SIX = "6".charCodeAt(0); - Keyboard.SEVEN = "7".charCodeAt(0); - Keyboard.EIGHT = "8".charCodeAt(0); - Keyboard.NINE = "9".charCodeAt(0); - Keyboard.NUMPAD_0 = 96; - Keyboard.NUMPAD_1 = 97; - Keyboard.NUMPAD_2 = 98; - Keyboard.NUMPAD_3 = 99; - Keyboard.NUMPAD_4 = 100; - Keyboard.NUMPAD_5 = 101; - Keyboard.NUMPAD_6 = 102; - Keyboard.NUMPAD_7 = 103; - Keyboard.NUMPAD_8 = 104; - Keyboard.NUMPAD_9 = 105; - Keyboard.NUMPAD_MULTIPLY = 106; - Keyboard.NUMPAD_ADD = 107; - Keyboard.NUMPAD_ENTER = 108; - Keyboard.NUMPAD_SUBTRACT = 109; - Keyboard.NUMPAD_DECIMAL = 110; - Keyboard.NUMPAD_DIVIDE = 111; - Keyboard.F1 = 112; - Keyboard.F2 = 113; - Keyboard.F3 = 114; - Keyboard.F4 = 115; - Keyboard.F5 = 116; - Keyboard.F6 = 117; - Keyboard.F7 = 118; - Keyboard.F8 = 119; - Keyboard.F9 = 120; - Keyboard.F10 = 121; - Keyboard.F11 = 122; - Keyboard.F12 = 123; - Keyboard.F13 = 124; - Keyboard.F14 = 125; - Keyboard.F15 = 126; - Keyboard.COLON = 186; - Keyboard.EQUALS = 187; - Keyboard.UNDERSCORE = 189; - Keyboard.QUESTION_MARK = 191; - Keyboard.TILDE = 192; - Keyboard.OPEN_BRACKET = 219; - Keyboard.BACKWARD_SLASH = 220; - Keyboard.CLOSED_BRACKET = 221; - Keyboard.QUOTES = 222; - Keyboard.BACKSPACE = 8; - Keyboard.TAB = 9; - Keyboard.CLEAR = 12; - Keyboard.ENTER = 13; - Keyboard.SHIFT = 16; - Keyboard.CONTROL = 17; - Keyboard.ALT = 18; - Keyboard.CAPS_LOCK = 20; - Keyboard.ESC = 27; - Keyboard.SPACEBAR = 32; - Keyboard.PAGE_UP = 33; - Keyboard.PAGE_DOWN = 34; - Keyboard.END = 35; - Keyboard.HOME = 36; - Keyboard.LEFT = 37; - Keyboard.UP = 38; - Keyboard.RIGHT = 39; - Keyboard.DOWN = 40; - Keyboard.INSERT = 45; - Keyboard.DELETE = 46; - Keyboard.HELP = 47; - Keyboard.NUM_LOCK = 144; - return Keyboard; - })(); - Phaser.Keyboard = Keyboard; -})(Phaser || (Phaser = {})); -/// /** * Phaser - Line * @@ -12861,11 +12170,11 @@ var Phaser; this.add = game.add; this.camera = game.camera; this.cache = game.cache; - this.collision = game.collision; + //this.collision = game.collision; this.input = game.input; this.loader = game.loader; this.math = game.math; - this.motion = game.motion; + //this.motion = game.motion; this.sound = game.sound; this.stage = game.stage; this.time = game.time; @@ -12905,24 +12214,20 @@ var Phaser; */ function () { }; - State.prototype.collide = /** - * Checks for overlaps between two objects using the world QuadTree. Can be GameObject vs. GameObject, GameObject vs. Group or Group vs. Group. - * Note: Does not take the objects scrollFactor into account. All overlaps are check in world space. - * @param object1 The first GameObject or Group to check. If null the world.group is used. - * @param object2 The second GameObject or Group to check. - * @param notifyCallback A callback function that is called if the objects overlap. The two objects will be passed to this function in the same order in which you passed them to Collision.overlap. - * @param processCallback A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then notifyCallback will only be called if processCallback returns true. - * @param context The context in which the callbacks will be called - * @returns {boolean} true if the objects overlap, otherwise false. - */ - function (objectOrGroup1, objectOrGroup2, notifyCallback, context) { - if (typeof objectOrGroup1 === "undefined") { objectOrGroup1 = null; } - if (typeof objectOrGroup2 === "undefined") { objectOrGroup2 = null; } - if (typeof notifyCallback === "undefined") { notifyCallback = null; } - if (typeof context === "undefined") { context = this.game.callbackContext; } - return this.collision.overlap(objectOrGroup1, objectOrGroup2, notifyCallback, Collision.separate, context); - }; return State; })(); Phaser.State = State; -})(Phaser || (Phaser = {})); + /** + * Checks for overlaps between two objects using the world QuadTree. Can be GameObject vs. GameObject, GameObject vs. Group or Group vs. Group. + * Note: Does not take the objects scrollFactor into account. All overlaps are check in world space. + * @param object1 The first GameObject or Group to check. If null the world.group is used. + * @param object2 The second GameObject or Group to check. + * @param notifyCallback A callback function that is called if the objects overlap. The two objects will be passed to this function in the same order in which you passed them to Collision.overlap. + * @param processCallback A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then notifyCallback will only be called if processCallback returns true. + * @param context The context in which the callbacks will be called + * @returns {boolean} true if the objects overlap, otherwise false. + */ + //public collide(objectOrGroup1 = null, objectOrGroup2 = null, notifyCallback = null, context? = this.game.callbackContext): bool { + // return this.collision.overlap(objectOrGroup1, objectOrGroup2, notifyCallback, Collision.separate, context); + //} + })(Phaser || (Phaser = {}));