From 3c0c34908902b04ffb0dfc98629b726154df448a Mon Sep 17 00:00:00 2001 From: Richard Davey Date: Tue, 28 May 2013 21:38:37 +0100 Subject: [PATCH] More refactoring for 1.0.0 --- Phaser/AnimationManager.d.ts | 28 - Phaser/Basic.d.ts | 23 - Phaser/Basic.ts | 150 - Phaser/Cache.d.ts | 26 - Phaser/CameraManager.d.ts | 17 - Phaser/Collision.d.ts | 53 - Phaser/Collision.ts | 38 +- Phaser/DynamicTexture.d.ts | 32 - Phaser/FXManager.d.ts | 18 - Phaser/Game.d.ts | 88 - Phaser/Game.ts | 96 +- Phaser/GameMath.d.ts | 110 - Phaser/Group.d.ts | 39 - Phaser/Loader.d.ts | 34 - Phaser/Motion.d.ts | 23 - Phaser/Phaser.csproj | 170 +- Phaser/Phaser.d.ts | 3 - Phaser/Phaser.ts | 7 +- Phaser/RenderManager.ts | 25 - Phaser/Signal.d.ts | 26 - Phaser/SignalBinding.d.ts | 21 - Phaser/SoundManager.d.ts | 16 - Phaser/Stage.d.ts | 47 - Phaser/Stage.ts | 12 +- Phaser/State.ts | 2 +- Phaser/Statics.ts | 29 + Phaser/Time.d.ts | 25 - Phaser/TweenManager.d.ts | 15 - Phaser/World.d.ts | 32 - Phaser/World.ts | 155 +- Phaser/cameras/Camera.ts | 103 +- Phaser/cameras/CameraManager.ts | 16 +- Phaser/cameras/OrthographicCamera.ts | 0 .../ScrollRegion.ts | 49 +- Phaser/{system => components}/Tile.ts | 6 + Phaser/{system => components}/TilemapLayer.ts | 0 .../{ => components}/animation/Animation.ts | 0 .../animation/AnimationManager.ts | 12 +- Phaser/{ => components}/animation/Frame.ts | 0 .../{ => components}/animation/FrameData.ts | 0 .../camera/CameraFX.ts} | 11 +- .../sprite}/CollisionMask.ts | 0 Phaser/components/sprite/Debug.ts | 90 + Phaser/components/sprite/Input.ts | 29 + Phaser/components/sprite/Physics.ts | 69 +- Phaser/components/sprite/Position.ts | 65 + Phaser/components/sprite/Properties.ts | 36 + Phaser/components/sprite/Texture.ts | 159 +- Phaser/core/Circle.ts | 12 +- Phaser/{ => core}/Group.ts | 443 +- Phaser/core/Point.ts | 15 - Phaser/core/Rectangle.ts | 10 + Phaser/{ => core}/Signal.ts | 0 Phaser/{ => core}/SignalBinding.ts | 0 Phaser/core/Vec2.ts | 10 + Phaser/{ => gameobjects}/DynamicTexture.ts | 24 +- Phaser/gameobjects/Emitter.d.ts | 38 - Phaser/gameobjects/GameObject.d.ts | 84 - Phaser/gameobjects/GameObject.ts | 897 - Phaser/{ => gameobjects}/GameObjectFactory.ts | 55 +- Phaser/gameobjects/GeomSprite.d.ts | 40 - Phaser/gameobjects/GeomSprite.ts | 21 +- Phaser/gameobjects/OldSprite.ts | 355 + Phaser/gameobjects/Particle.d.ts | 11 - Phaser/gameobjects/ScrollRegion.d.ts | 22 - Phaser/gameobjects/ScrollZone.d.ts | 23 - Phaser/gameobjects/ScrollZone.ts | 6 +- Phaser/gameobjects/Sprite.d.ts | 34 - Phaser/gameobjects/Sprite.ts | 447 +- Phaser/gameobjects/Tilemap.d.ts | 31 - Phaser/gameobjects/Tilemap.ts | 9 +- Phaser/geom/Circle.d.ts | 34 - Phaser/geom/IntersectResult.d.ts | 15 - Phaser/geom/Line.d.ts | 27 - Phaser/geom/MicroPoint.d.ts | 16 - Phaser/geom/Point.d.ts | 28 - Phaser/geom/Polygon.ts | 18 +- Phaser/geom/Quad.d.ts | 19 - Phaser/geom/Rectangle.d.ts | 57 - Phaser/geom/Response.ts | 8 +- Phaser/input/Gestures.ts | 2 +- Phaser/input/Input.ts | 16 +- Phaser/input/Keyboard.ts | 2 +- Phaser/input/MSPointer.ts | 2 +- Phaser/input/Mouse.ts | 2 +- Phaser/input/Pointer.ts | 16 +- Phaser/input/Touch.ts | 2 +- .../{animation => loader}/AnimationLoader.ts | 2 +- Phaser/{ => math}/GameMath.ts | 2 +- Phaser/{system => math}/LinkedList.ts | 0 Phaser/{system => math}/QuadTree.ts | 0 .../{system => math}/RandomDataGenerator.ts | 0 Phaser/math/Vector2.ts | 457 - Phaser/phaser.js | 20 +- Phaser/renderers/CanvasRenderer.ts | 184 + Phaser/renderers/HeadlessRenderer.ts | 36 + Phaser/renderers/IRenderer.ts | 16 + Phaser/sound/Sound.ts | 2 +- Phaser/sound/SoundManager.ts | 4 +- Phaser/system/Camera.d.ts | 80 - Phaser/system/Device.d.ts | 49 - Phaser/system/LinkedList.d.ts | 9 - Phaser/system/QuadTree.d.ts | 53 - Phaser/system/RandomDataGenerator.d.ts | 26 - Phaser/system/RequestAnimationFrame.d.ts | 20 - Phaser/system/Sound.d.ts | 23 - Phaser/system/StageScaleMode.d.ts | 21 - Phaser/system/Tile.d.ts | 22 - Phaser/system/TilemapLayer.d.ts | 51 - Phaser/system/Tween.d.ts | 42 - Phaser/system/screens/BootScreen.d.ts | 15 - Phaser/system/screens/PauseScreen.d.ts | 17 - Phaser/tweens/TweenManager.ts | 4 +- Phaser/tweens/easing/Back.d.ts | 8 - Phaser/tweens/easing/Bounce.d.ts | 8 - Phaser/tweens/easing/Circular.d.ts | 8 - Phaser/tweens/easing/Cubic.d.ts | 8 - Phaser/tweens/easing/Elastic.d.ts | 8 - Phaser/tweens/easing/Exponential.d.ts | 8 - Phaser/tweens/easing/Linear.d.ts | 6 - Phaser/tweens/easing/Quadratic.d.ts | 8 - Phaser/tweens/easing/Quartic.d.ts | 8 - Phaser/tweens/easing/Quintic.d.ts | 8 - Phaser/tweens/easing/Sinusoidal.d.ts | 8 - Phaser/{geom => utils}/CircleUtils.ts | 0 Phaser/{geom => utils}/PointUtils.ts | 0 Phaser/{geom => utils}/RectangleUtils.ts | 0 Phaser/utils/SpriteUtils.ts | 425 + Plugins/Plugins.csproj | 36 +- README.md | 23 +- build/phaser.js | 20671 +++++++--------- 131 files changed, 10572 insertions(+), 16680 deletions(-) delete mode 100644 Phaser/AnimationManager.d.ts delete mode 100644 Phaser/Basic.d.ts delete mode 100644 Phaser/Basic.ts delete mode 100644 Phaser/Cache.d.ts delete mode 100644 Phaser/CameraManager.d.ts delete mode 100644 Phaser/Collision.d.ts delete mode 100644 Phaser/DynamicTexture.d.ts delete mode 100644 Phaser/FXManager.d.ts delete mode 100644 Phaser/Game.d.ts delete mode 100644 Phaser/GameMath.d.ts delete mode 100644 Phaser/Group.d.ts delete mode 100644 Phaser/Loader.d.ts delete mode 100644 Phaser/Motion.d.ts delete mode 100644 Phaser/Phaser.d.ts delete mode 100644 Phaser/RenderManager.ts delete mode 100644 Phaser/Signal.d.ts delete mode 100644 Phaser/SignalBinding.d.ts delete mode 100644 Phaser/SoundManager.d.ts delete mode 100644 Phaser/Stage.d.ts create mode 100644 Phaser/Statics.ts delete mode 100644 Phaser/Time.d.ts delete mode 100644 Phaser/TweenManager.d.ts delete mode 100644 Phaser/World.d.ts delete mode 100644 Phaser/cameras/OrthographicCamera.ts rename Phaser/{gameobjects => components}/ScrollRegion.ts (84%) rename Phaser/{system => components}/Tile.ts (99%) rename Phaser/{system => components}/TilemapLayer.ts (100%) rename Phaser/{ => components}/animation/Animation.ts (100%) rename Phaser/{ => components}/animation/AnimationManager.ts (96%) rename Phaser/{ => components}/animation/Frame.ts (100%) rename Phaser/{ => components}/animation/FrameData.ts (100%) rename Phaser/{FXManager.ts => components/camera/CameraFX.ts} (96%) rename Phaser/{system => components/sprite}/CollisionMask.ts (100%) create mode 100644 Phaser/components/sprite/Debug.ts create mode 100644 Phaser/components/sprite/Input.ts create mode 100644 Phaser/components/sprite/Position.ts create mode 100644 Phaser/components/sprite/Properties.ts rename Phaser/{ => core}/Group.ts (63%) rename Phaser/{ => core}/Signal.ts (100%) rename Phaser/{ => core}/SignalBinding.ts (100%) rename Phaser/{ => gameobjects}/DynamicTexture.ts (94%) delete mode 100644 Phaser/gameobjects/Emitter.d.ts delete mode 100644 Phaser/gameobjects/GameObject.d.ts delete mode 100644 Phaser/gameobjects/GameObject.ts rename Phaser/{ => gameobjects}/GameObjectFactory.ts (80%) delete mode 100644 Phaser/gameobjects/GeomSprite.d.ts create mode 100644 Phaser/gameobjects/OldSprite.ts delete mode 100644 Phaser/gameobjects/Particle.d.ts delete mode 100644 Phaser/gameobjects/ScrollRegion.d.ts delete mode 100644 Phaser/gameobjects/ScrollZone.d.ts delete mode 100644 Phaser/gameobjects/Sprite.d.ts delete mode 100644 Phaser/gameobjects/Tilemap.d.ts delete mode 100644 Phaser/geom/Circle.d.ts delete mode 100644 Phaser/geom/IntersectResult.d.ts delete mode 100644 Phaser/geom/Line.d.ts delete mode 100644 Phaser/geom/MicroPoint.d.ts delete mode 100644 Phaser/geom/Point.d.ts delete mode 100644 Phaser/geom/Quad.d.ts delete mode 100644 Phaser/geom/Rectangle.d.ts rename Phaser/{animation => loader}/AnimationLoader.ts (99%) rename Phaser/{ => math}/GameMath.ts (99%) rename Phaser/{system => math}/LinkedList.ts (100%) rename Phaser/{system => math}/QuadTree.ts (100%) rename Phaser/{system => math}/RandomDataGenerator.ts (100%) delete mode 100644 Phaser/math/Vector2.ts create mode 100644 Phaser/renderers/CanvasRenderer.ts create mode 100644 Phaser/renderers/HeadlessRenderer.ts create mode 100644 Phaser/renderers/IRenderer.ts delete mode 100644 Phaser/system/Camera.d.ts delete mode 100644 Phaser/system/Device.d.ts delete mode 100644 Phaser/system/LinkedList.d.ts delete mode 100644 Phaser/system/QuadTree.d.ts delete mode 100644 Phaser/system/RandomDataGenerator.d.ts delete mode 100644 Phaser/system/RequestAnimationFrame.d.ts delete mode 100644 Phaser/system/Sound.d.ts delete mode 100644 Phaser/system/StageScaleMode.d.ts delete mode 100644 Phaser/system/Tile.d.ts delete mode 100644 Phaser/system/TilemapLayer.d.ts delete mode 100644 Phaser/system/Tween.d.ts delete mode 100644 Phaser/system/screens/BootScreen.d.ts delete mode 100644 Phaser/system/screens/PauseScreen.d.ts delete mode 100644 Phaser/tweens/easing/Back.d.ts delete mode 100644 Phaser/tweens/easing/Bounce.d.ts delete mode 100644 Phaser/tweens/easing/Circular.d.ts delete mode 100644 Phaser/tweens/easing/Cubic.d.ts delete mode 100644 Phaser/tweens/easing/Elastic.d.ts delete mode 100644 Phaser/tweens/easing/Exponential.d.ts delete mode 100644 Phaser/tweens/easing/Linear.d.ts delete mode 100644 Phaser/tweens/easing/Quadratic.d.ts delete mode 100644 Phaser/tweens/easing/Quartic.d.ts delete mode 100644 Phaser/tweens/easing/Quintic.d.ts delete mode 100644 Phaser/tweens/easing/Sinusoidal.d.ts rename Phaser/{geom => utils}/CircleUtils.ts (100%) rename Phaser/{geom => utils}/PointUtils.ts (100%) rename Phaser/{geom => utils}/RectangleUtils.ts (100%) create mode 100644 Phaser/utils/SpriteUtils.ts diff --git a/Phaser/AnimationManager.d.ts b/Phaser/AnimationManager.d.ts deleted file mode 100644 index f8e535b0..00000000 --- a/Phaser/AnimationManager.d.ts +++ /dev/null @@ -1,28 +0,0 @@ -/// -/// -/// -/// -/// -/// -module Phaser { - class AnimationManager { - constructor(game: Game, parent: Sprite); - private _game; - private _parent; - private _anims; - private _frameIndex; - private _frameData; - public currentAnim: Animation; - public currentFrame: Frame; - public loadFrameData(frameData: FrameData): void; - public add(name: string, frames?: any[], frameRate?: number, loop?: bool, useNumericIndex?: bool): void; - private validateFrames(frames, useNumericIndex); - public play(name: string, frameRate?: number, loop?: bool): void; - public stop(name: string): void; - public update(): void; - public frameData : FrameData; - public frameTotal : number; - public frame : number; - public frameName : string; - } -} diff --git a/Phaser/Basic.d.ts b/Phaser/Basic.d.ts deleted file mode 100644 index 80795a46..00000000 --- a/Phaser/Basic.d.ts +++ /dev/null @@ -1,23 +0,0 @@ -/// -module Phaser { - class Basic { - constructor(game: Game); - public _game: Game; - public name: string; - public ID: number; - public isGroup: bool; - public exists: bool; - public active: bool; - public visible: bool; - public alive: bool; - public ignoreDrawDebug: bool; - public destroy(): void; - public preUpdate(): void; - public update(): void; - public postUpdate(): void; - public render(camera: Camera, cameraOffsetX: number, cameraOffsetY: number): void; - public kill(): void; - public revive(): void; - public toString(): string; - } -} diff --git a/Phaser/Basic.ts b/Phaser/Basic.ts deleted file mode 100644 index 1dcb7f75..00000000 --- a/Phaser/Basic.ts +++ /dev/null @@ -1,150 +0,0 @@ -/// - -/** -* Phaser - Basic -* -* A useful "generic" object on which all GameObjects and Groups are based. -* It has no size, position or graphical data. -*/ - -module Phaser { - - export class Basic { - - /** - * Instantiate the basic object. - */ - constructor(game: Game) { - - 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; - - } - - /** - * 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() { } - - /** - * Pre-update is called right before update() on each object in the game loop. - */ - public preUpdate() { - } - - /** - * 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 = false) { - } - - /** - * Post-update is called right after update() on each object in the game loop. - */ - public postUpdate() { - } - - public render(camera: Camera, cameraOffsetX: number, cameraOffsetY: number, forceRender?: bool = false) { - } - - /** - * 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() { - this.alive = false; - this.exists = false; - } - - /** - * 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() { - this.alive = true; - this.exists = true; - } - - /** - * Convert object to readable string name. Useful for debugging, save games, etc. - */ - public toString(): string { - return ""; - } - - } - -} \ No newline at end of file diff --git a/Phaser/Cache.d.ts b/Phaser/Cache.d.ts deleted file mode 100644 index 5a3f6a02..00000000 --- a/Phaser/Cache.d.ts +++ /dev/null @@ -1,26 +0,0 @@ -/// -module Phaser { - class Cache { - constructor(game: Game); - private _game; - private _canvases; - private _images; - private _sounds; - private _text; - public addCanvas(key: string, canvas: HTMLCanvasElement, context: CanvasRenderingContext2D): void; - public addSpriteSheet(key: string, url: string, data, frameWidth: number, frameHeight: number, frameMax: number): void; - public addTextureAtlas(key: string, url: string, data, jsonData): void; - public addImage(key: string, url: string, data): void; - public addSound(key: string, url: string, data): void; - public decodedSound(key: string, data): void; - public addText(key: string, url: string, data): void; - public getCanvas(key: string); - public getImage(key: string); - public getFrameData(key: string): FrameData; - public getSound(key: string); - public isSoundDecoded(key: string): bool; - public isSpriteSheet(key: string): bool; - public getText(key: string); - public destroy(): void; - } -} diff --git a/Phaser/CameraManager.d.ts b/Phaser/CameraManager.d.ts deleted file mode 100644 index 12f16417..00000000 --- a/Phaser/CameraManager.d.ts +++ /dev/null @@ -1,17 +0,0 @@ -/// -/// -module Phaser { - class CameraManager { - constructor(game: Game, x: number, y: number, width: number, height: number); - private _game; - private _cameras; - private _cameraInstance; - public current: Camera; - public getAll(): Camera[]; - public update(): void; - public render(): void; - public addCamera(x: number, y: number, width: number, height: number): Camera; - public removeCamera(id: number): bool; - public destroy(): void; - } -} diff --git a/Phaser/Collision.d.ts b/Phaser/Collision.d.ts deleted file mode 100644 index af37f01a..00000000 --- a/Phaser/Collision.d.ts +++ /dev/null @@ -1,53 +0,0 @@ -/// -/// -/// -/// -/// -/// -/// -/// -module Phaser { - class Collision { - constructor(game: Game); - private _game; - static LEFT: number; - static RIGHT: number; - static UP: number; - static DOWN: number; - static NONE: number; - static CEILING: number; - static FLOOR: number; - static WALL: number; - static ANY: number; - static OVERLAP_BIAS: number; - static TILE_OVERLAP: bool; - static _tempBounds: Quad; - static lineToLine(line1: Line, line2: Line, output?: IntersectResult): IntersectResult; - static lineToLineSegment(line: Line, seg: Line, output?: IntersectResult): IntersectResult; - static lineToRawSegment(line: Line, x1: number, y1: number, x2: number, y2: number, output?: IntersectResult): IntersectResult; - static lineToRay(line1: Line, ray: Line, output?: IntersectResult): IntersectResult; - static lineToCircle(line: Line, circle: Circle, output?: IntersectResult): IntersectResult; - static lineToRectangle(line: Line, rect: Rectangle, output?: IntersectResult): IntersectResult; - static lineSegmentToLineSegment(line1: Line, line2: Line, output?: IntersectResult): IntersectResult; - static lineSegmentToRay(line: Line, ray: Line, output?: IntersectResult): IntersectResult; - static lineSegmentToCircle(seg: Line, circle: Circle, output?: IntersectResult): IntersectResult; - static lineSegmentToRectangle(seg: Line, rect: Rectangle, output?: IntersectResult): IntersectResult; - static rayToRectangle(ray: Line, rect: Rectangle, output?: IntersectResult): IntersectResult; - static rayToLineSegment(rayX1, rayY1, rayX2, rayY2, lineX1, lineY1, lineX2, lineY2, output?: IntersectResult): IntersectResult; - static pointToRectangle(point, rect: Rectangle, output?: IntersectResult): IntersectResult; - static rectangleToRectangle(rect1: Rectangle, rect2: Rectangle, output?: IntersectResult): IntersectResult; - static rectangleToCircle(rect: Rectangle, circle: Circle, output?: IntersectResult): IntersectResult; - static circleToCircle(circle1: Circle, circle2: Circle, output?: IntersectResult): IntersectResult; - static circleToRectangle(circle: Circle, rect: Rectangle, output?: IntersectResult): IntersectResult; - static circleContainsPoint(circle: Circle, point, output?: IntersectResult): IntersectResult; - public overlap(object1?: Basic, object2?: Basic, notifyCallback?, processCallback?): bool; - static separate(object1, object2): bool; - static separateTile(object: GameObject, x: number, y: number, width: number, height: number, mass: number, collideLeft: bool, collideRight: bool, collideUp: bool, collideDown: bool): bool; - static separateTileX(object: GameObject, x: number, y: number, width: number, height: number, mass: number, collideLeft: bool, collideRight: bool): bool; - static separateTileY(object: GameObject, x: number, y: number, width: number, height: number, mass: number, collideUp: bool, collideDown: bool): bool; - static separateX(object1, object2): bool; - static separateY(object1, object2): bool; - static distance(x1: number, y1: number, x2: number, y2: number): number; - static distanceSquared(x1: number, y1: number, x2: number, y2: number): number; - } -} diff --git a/Phaser/Collision.ts b/Phaser/Collision.ts index 2ba41621..13684b81 100644 --- a/Phaser/Collision.ts +++ b/Phaser/Collision.ts @@ -1,13 +1,12 @@ /// -/// -/// -/// -/// +/// +/// +/// /// /// /// -/// -/// +/// +/// /** * Phaser - Collision @@ -31,7 +30,7 @@ module Phaser { for (var i = 0; i < 10; i++) { - Collision.T_VECTORS.push(new Vector2); + Collision.T_VECTORS.push(new Vec2); } Collision.T_ARRAYS = []; @@ -115,10 +114,10 @@ module Phaser { public static TILE_OVERLAP: bool = false; /** - * A temporary Quad used in the separation process to help avoid gc spikes - * @type {Quad} + * A temporary Rectangle used in the separation process to help avoid gc spikes + * @type {Rectangle} */ - public static _tempBounds: Quad; + public static _tempBounds: Rectangle; /** * Checks for Line to Line intersection and returns an IntersectResult object containing the results of the intersection. @@ -498,7 +497,7 @@ module Phaser { /** * 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 point The Point or Point 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 @@ -507,7 +506,8 @@ module Phaser { output.setTo(point.x, point.y); - output.result = rect.containsPoint(point); + //output.result = rect.containsPoint(point); + return output; @@ -591,7 +591,7 @@ module Phaser { /** * 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 point A Point or Point 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 */ @@ -700,7 +700,7 @@ module Phaser { // Check if the X hulls actually overlap var objDeltaAbs: number = (objDelta > 0) ? objDelta : -objDelta; //var objDeltaAbs: number = object.collisionMask.deltaXAbs; - var objBounds: Quad = new Quad(object.x - ((objDelta > 0) ? objDelta : 0), object.last.y, object.width + ((objDelta > 0) ? objDelta : -objDelta), object.height); + var objBounds: Rectangle = new Rectangle(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)) { @@ -780,7 +780,7 @@ module Phaser { { // 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); + var objBounds: Rectangle = new Rectangle(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)) { @@ -858,7 +858,7 @@ module Phaser { { // 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); + //var objBounds: Rectangle = new Rectangle(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)) @@ -940,7 +940,7 @@ module Phaser { { // 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); + //var objBounds: Rectangle = new Rectangle(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)) @@ -1263,7 +1263,7 @@ module Phaser { * * @type {Array.} */ - public static T_VECTORS: Vector2[]; + public static T_VECTORS: Vec2[]; /** * Pool of Arrays used in calculations. @@ -1399,7 +1399,7 @@ module Phaser { * MIDDLE_VORNOI_REGION (0) if it is the middle region, * RIGHT_VORNOI_REGION (1) if it is the right region. */ - public static vornoiRegion(line: Vector2, point: Vector2): number { + public static vornoiRegion(line: Vec2, point: Vec2): number { var len2 = line.length2(); var dp = point.dot(line); diff --git a/Phaser/DynamicTexture.d.ts b/Phaser/DynamicTexture.d.ts deleted file mode 100644 index 4e499c14..00000000 --- a/Phaser/DynamicTexture.d.ts +++ /dev/null @@ -1,32 +0,0 @@ -/// -module Phaser { - class DynamicTexture { - constructor(game: Game, width: number, height: number); - private _game; - private _sx; - private _sy; - private _sw; - private _sh; - private _dx; - private _dy; - private _dw; - private _dh; - public bounds: Rectangle; - public canvas: HTMLCanvasElement; - public context: CanvasRenderingContext2D; - public getPixel(x: number, y: number): number; - public getPixel32(x: number, y: number): number; - public getPixels(rect: Rectangle): ImageData; - public setPixel(x: number, y: number, color: number): void; - public setPixel32(x: number, y: number, color: number): void; - public setPixels(rect: Rectangle, input): void; - public fillRect(rect: Rectangle, color: number): void; - public pasteImage(key: string, frame?: number, destX?: number, destY?: number, destWidth?: number, destHeight?: number): void; - public copyPixels(sourceTexture: DynamicTexture, sourceRect: Rectangle, destPoint: Point): void; - public clear(): void; - public width : number; - public height : number; - private getColor32(alpha, red, green, blue); - private getColor(red, green, blue); - } -} diff --git a/Phaser/FXManager.d.ts b/Phaser/FXManager.d.ts deleted file mode 100644 index 4a202ca2..00000000 --- a/Phaser/FXManager.d.ts +++ /dev/null @@ -1,18 +0,0 @@ -/// -module Phaser { - class FXManager { - constructor(game: Game); - private _fx; - private _length; - private _game; - public active: bool; - public visible: bool; - public add(effect): any; - public preUpdate(): void; - public postUpdate(): void; - public preRender(camera: Camera, cameraX: number, cameraY: number, cameraWidth: number, cameraHeight: number): void; - public render(camera: Camera, cameraX: number, cameraY: number, cameraWidth: number, cameraHeight: number): void; - public postRender(camera: Camera, cameraX: number, cameraY: number, cameraWidth: number, cameraHeight: number): void; - public destroy(): void; - } -} diff --git a/Phaser/Game.d.ts b/Phaser/Game.d.ts deleted file mode 100644 index e9a63ebc..00000000 --- a/Phaser/Game.d.ts +++ /dev/null @@ -1,88 +0,0 @@ -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -module Phaser { - class Game { - constructor(callbackContext, parent?: string, width?: number, height?: number, initCallback?, createCallback?, updateCallback?, renderCallback?); - private _raf; - private _maxAccumulation; - private _accumulator; - private _step; - private _loadComplete; - private _paused; - private _pendingState; - public callbackContext; - public onInitCallback; - public onCreateCallback; - public onUpdateCallback; - public onRenderCallback; - public onPausedCallback; - public cache: Cache; - public collision: Collision; - public input: Input; - public loader: Loader; - public math: GameMath; - public motion: Motion; - public sound: SoundManager; - public stage: Stage; - public time: Time; - public tweens: TweenManager; - public world: World; - public rnd: RandomDataGenerator; - public device: Device; - public isBooted: bool; - public isRunning: bool; - private boot(parent, width, height); - private loadComplete(); - private bootLoop(); - private pausedLoop(); - private loop(); - private startState(); - public setCallbacks(initCallback?, createCallback?, updateCallback?, renderCallback?): void; - public switchState(state, clearWorld?: bool, clearCache?: bool): void; - public destroy(): void; - public paused : bool; - public framerate : number; - public createCamera(x: number, y: number, width: number, height: number): Camera; - public createGeomSprite(x: number, y: number): GeomSprite; - public createSprite(x: number, y: number, key?: string): Sprite; - public createDynamicTexture(width: number, height: number): DynamicTexture; - public createGroup(MaxSize?: number): Group; - public createParticle(): Particle; - public createEmitter(x?: number, y?: number, size?: number): Emitter; - public createScrollZone(key: string, x?: number, y?: number, width?: number, height?: number): ScrollZone; - public createTilemap(key: string, mapData: string, format: number, resizeWorld?: bool, tileWidth?: number, tileHeight?: number): Tilemap; - public createTween(obj): Tween; - public collide(objectOrGroup1?: Basic, objectOrGroup2?: Basic, notifyCallback?): bool; - public camera : Camera; - } -} diff --git a/Phaser/Game.ts b/Phaser/Game.ts index a8befff3..4d03a574 100644 --- a/Phaser/Game.ts +++ b/Phaser/Game.ts @@ -1,39 +1,23 @@ -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// /// /// -/// -/// +/// /// -/// /// -/// /// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// +/// +/// +/// +/// /** * Phaser - Game @@ -189,7 +173,7 @@ module Phaser { * Reference to the collision helper. * @type {Collision} */ - public collision: Collision; + //public collision: Collision; /** * Reference to the input manager @@ -213,7 +197,7 @@ module Phaser { * Reference to the motion helper. * @type {Motion} */ - public motion: Motion; + //public motion: Motion; /** * Reference to the sound manager. @@ -239,12 +223,6 @@ module Phaser { */ public tweens: TweenManager; - /** - * Reference to the verlet manager. - * @type {VerletManager} - */ - public verlet: Phaser.Verlet.VerletManager; - /** * Reference to the world. * @type {World} @@ -263,6 +241,12 @@ module Phaser { */ public device: Device; + /** + * Reference to the render manager + * @type {RenderManager} + */ + public renderer: IRenderer; + /** * Whether the game engine is booted, aka available. * @type {boolean} @@ -295,20 +279,21 @@ module Phaser { else { this.device = new Device(); - this.motion = new Motion(this); + //this.motion = new Motion(this); this.math = new GameMath(this); this.stage = new Stage(this, parent, width, height); this.world = new World(this, width, height); this.add = new GameObjectFactory(this); this.sound = new SoundManager(this); this.cache = new Cache(this); - this.collision = new Collision(this); + //this.collision = new Collision(this); this.loader = new Loader(this, this.loadComplete); this.time = new Time(this); this.tweens = new TweenManager(this); this.input = new Input(this); this.rnd = new 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; @@ -341,6 +326,24 @@ module Phaser { } + public setRenderer(type: number) { + + 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 :) + } + + } + /** * Called when the loader has finished after init was run. */ @@ -385,7 +388,6 @@ module Phaser { this.tweens.update(); this.input.update(); this.stage.update(); - this.verlet.update(); this._accumulator += this.time.delta; @@ -406,7 +408,7 @@ module Phaser { this.onUpdateCallback.call(this.callbackContext); } - this.world.render(); + this.renderer.render(); if (this._loadComplete && this.onRenderCallback) { @@ -637,9 +639,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: Basic = null, objectOrGroup2: Basic = null, notifyCallback = null, context? = this.callbackContext): bool { - return this.collision.overlap(objectOrGroup1, objectOrGroup2, notifyCallback, Collision.separate, context); - } + //public collide(objectOrGroup1 = null, objectOrGroup2 = null, notifyCallback = null, context? = this.callbackContext): bool { + // return this.collision.overlap(objectOrGroup1, objectOrGroup2, notifyCallback, Collision.separate, context); + //} public get camera(): Camera { return this.world.cameras.current; diff --git a/Phaser/GameMath.d.ts b/Phaser/GameMath.d.ts deleted file mode 100644 index 50b05b2a..00000000 --- a/Phaser/GameMath.d.ts +++ /dev/null @@ -1,110 +0,0 @@ -/// -module Phaser { - class GameMath { - constructor(game: Game); - private _game; - static PI: number; - static PI_2: number; - static PI_4: number; - static PI_8: number; - static PI_16: number; - static TWO_PI: number; - static THREE_PI_2: number; - static E: number; - static LN10: number; - static LN2: number; - static LOG10E: number; - static LOG2E: number; - static SQRT1_2: number; - static SQRT2: number; - static DEG_TO_RAD: number; - static RAD_TO_DEG: number; - static B_16: number; - static B_31: number; - static B_32: number; - static B_48: number; - static B_53: number; - static B_64: number; - static ONE_THIRD: number; - static TWO_THIRDS: number; - static ONE_SIXTH: number; - static COS_PI_3: number; - static SIN_2PI_3: number; - static CIRCLE_ALPHA: number; - static ON: bool; - static OFF: bool; - static SHORT_EPSILON: number; - static PERC_EPSILON: number; - static EPSILON: number; - static LONG_EPSILON: number; - public cosTable: any[]; - public sinTable: any[]; - public fuzzyEqual(a: number, b: number, epsilon?: number): bool; - public fuzzyLessThan(a: number, b: number, epsilon?: number): bool; - public fuzzyGreaterThan(a: number, b: number, epsilon?: number): bool; - public fuzzyCeil(val: number, epsilon?: number): number; - public fuzzyFloor(val: number, epsilon?: number): number; - public average(...args: any[]): number; - public slam(value: number, target: number, epsilon?: number): number; - public percentageMinMax(val: number, max: number, min?: number): number; - public sign(n: number): number; - public truncate(n: number): number; - public shear(n: number): number; - public wrap(val: number, max: number, min?: number): number; - public arithWrap(value: number, max: number, min?: number): number; - public clamp(input: number, max: number, min?: number): number; - public snapTo(input: number, gap: number, start?: number): number; - public snapToFloor(input: number, gap: number, start?: number): number; - public snapToCeil(input: number, gap: number, start?: number): number; - public snapToInArray(input: number, arr: number[], sort?: bool): number; - public roundTo(value: number, place?: number, base?: number): number; - public floorTo(value: number, place?: number, base?: number): number; - public ceilTo(value: number, place?: number, base?: number): number; - public interpolateFloat(a: number, b: number, weight: number): number; - public radiansToDegrees(angle: number): number; - public degreesToRadians(angle: number): number; - public angleBetween(x1: number, y1: number, x2: number, y2: number): number; - public normalizeAngle(angle: number, radians?: bool): number; - public nearestAngleBetween(a1: number, a2: number, radians?: bool): number; - public normalizeAngleToAnother(dep: number, ind: number, radians?: bool): number; - public normalizeAngleAfterAnother(dep: number, ind: number, radians?: bool): number; - public normalizeAngleBeforeAnother(dep: number, ind: number, radians?: bool): number; - public interpolateAngles(a1: number, a2: number, weight: number, radians?: bool, ease?): number; - public logBaseOf(value: number, base: number): number; - public GCD(m: number, n: number): number; - public LCM(m: number, n: number): number; - public factorial(value: number): number; - public gammaFunction(value: number): number; - public fallingFactorial(base: number, exp: number): number; - public risingFactorial(base: number, exp: number): number; - public binCoef(n: number, k: number): number; - public risingBinCoef(n: number, k: number): number; - public chanceRoll(chance?: number): bool; - public maxAdd(value: number, amount: number, max: number): number; - public minSub(value: number, amount: number, min: number): number; - public wrapValue(value: number, amount: number, max: number): number; - public randomSign(): number; - public isOdd(n: number): bool; - public isEven(n: number): bool; - public wrapAngle(angle: number): number; - public angleLimit(angle: number, min: number, max: number): number; - public linearInterpolation(v, k); - public bezierInterpolation(v, k): number; - public catmullRomInterpolation(v, k); - public linear(p0, p1, t); - public bernstein(n, i): number; - public catmullRom(p0, p1, p2, p3, t); - public difference(a: number, b: number): number; - public globalSeed: number; - public random(): number; - public srand(Seed: number): number; - public getRandom(Objects, StartIndex?: number, Length?: number); - public floor(Value: number): number; - public ceil(Value: number): number; - public sinCosGenerator(length: number, sinAmplitude?: number, cosAmplitude?: number, frequency?: number): any[]; - public shiftSinTable(): number; - public shiftCosTable(): number; - public vectorLength(dx: number, dy: number): number; - public dotProduct(ax: number, ay: number, bx: number, by: number): number; - } -} diff --git a/Phaser/Group.d.ts b/Phaser/Group.d.ts deleted file mode 100644 index 1c60bb4a..00000000 --- a/Phaser/Group.d.ts +++ /dev/null @@ -1,39 +0,0 @@ -/// -/// -module Phaser { - class Group extends Basic { - constructor(game: Game, MaxSize?: number); - static ASCENDING: number; - static DESCENDING: number; - public members: Basic[]; - public length: number; - private _maxSize; - private _marker; - private _sortIndex; - private _sortOrder; - public destroy(): void; - public update(): void; - public render(camera: Camera, cameraOffsetX: number, cameraOffsetY: number): void; - public maxSize : number; - public add(Object: Basic): Basic; - public recycle(ObjectClass?); - public remove(Object: Basic, Splice?: bool): Basic; - public replace(OldObject: Basic, NewObject: Basic): Basic; - public sort(Index?: string, Order?: number): void; - public setAll(VariableName: string, Value: Object, Recurse?: bool): void; - public callAll(FunctionName: string, Recurse?: bool): void; - public forEach(callback, recursive?: bool): void; - public forEachAlive(context, callback, recursive?: bool): void; - public getFirstAvailable(ObjectClass?); - public getFirstNull(): number; - public getFirstExtant(): Basic; - public getFirstAlive(): Basic; - public getFirstDead(): Basic; - public countLiving(): number; - public countDead(): number; - public getRandom(StartIndex?: number, Length?: number): Basic; - public clear(): void; - public kill(): void; - public sortHandler(Obj1: Basic, Obj2: Basic): number; - } -} diff --git a/Phaser/Loader.d.ts b/Phaser/Loader.d.ts deleted file mode 100644 index 4f5436fa..00000000 --- a/Phaser/Loader.d.ts +++ /dev/null @@ -1,34 +0,0 @@ -/// -module Phaser { - class Loader { - constructor(game: Game, callback); - private _game; - private _keys; - private _fileList; - private _gameCreateComplete; - private _onComplete; - private _onFileLoad; - private _progressChunk; - private _xhr; - private _queueSize; - public hasLoaded: bool; - public progress: number; - public reset(): void; - public queueSize : number; - public addImageFile(key: string, url: string): void; - public addSpriteSheet(key: string, url: string, frameWidth: number, frameHeight: number, frameMax?: number): void; - public addTextureAtlas(key: string, url: string, jsonURL?: string, jsonData?): void; - public addAudioFile(key: string, url: string): void; - public addTextFile(key: string, url: string): void; - public removeFile(key: string): void; - public removeAll(): void; - public load(onFileLoadCallback?, onCompleteCallback?): void; - private loadFile(); - private fileError(key); - private fileComplete(key); - private jsonLoadComplete(key); - private jsonLoadError(key); - private nextFile(previousKey, success); - private checkKeyExists(key); - } -} diff --git a/Phaser/Motion.d.ts b/Phaser/Motion.d.ts deleted file mode 100644 index 05bb4b8a..00000000 --- a/Phaser/Motion.d.ts +++ /dev/null @@ -1,23 +0,0 @@ -/// -/// -module Phaser { - class Motion { - constructor(game: Game); - private _game; - public computeVelocity(Velocity: number, Acceleration?: number, Drag?: number, Max?: number): number; - public velocityFromAngle(angle: number, speed: number): Point; - public moveTowardsObject(source: GameObject, dest: GameObject, speed?: number, maxTime?: number): void; - public accelerateTowardsObject(source: GameObject, dest: GameObject, speed: number, xSpeedMax: number, ySpeedMax: number): void; - public moveTowardsMouse(source: GameObject, speed?: number, maxTime?: number): void; - public accelerateTowardsMouse(source: GameObject, speed: number, xSpeedMax: number, ySpeedMax: number): void; - public moveTowardsPoint(source: GameObject, target: Point, speed?: number, maxTime?: number): void; - public accelerateTowardsPoint(source: GameObject, target: Point, speed: number, xSpeedMax: number, ySpeedMax: number): void; - public distanceBetween(a: GameObject, b: GameObject): number; - public distanceToPoint(a: GameObject, target: Point): number; - public distanceToMouse(a: GameObject): number; - public angleBetweenPoint(a: GameObject, target: Point, asDegrees?: bool): number; - public angleBetween(a: GameObject, b: GameObject, asDegrees?: bool): number; - public velocityFromFacing(parent: GameObject, speed: number): Point; - public angleBetweenMouse(a: GameObject, asDegrees?: bool): number; - } -} diff --git a/Phaser/Phaser.csproj b/Phaser/Phaser.csproj index c52c9cbb..1b7e793e 100644 --- a/Phaser/Phaser.csproj +++ b/Phaser/Phaser.csproj @@ -58,18 +58,23 @@ - + AnimationManager.ts - - - OrthographicCamera.ts - - - Collision.ts - + + + + + CameraFX.ts + + + Position.ts + + + Texture.ts + Point.ts @@ -80,64 +85,58 @@ Vec2.ts - + DynamicTexture.ts - - - FXManager.ts - Game.ts - + + GameMath.ts - - + + GameObjectFactory.ts - - Emitter.ts - - - GameObject.ts - - - GeomSprite.ts - - - Particle.ts - - - - + + ScrollRegion.ts - - ScrollZone.ts - Sprite.ts - - Tilemap.ts - - - - + + + + + + + HeadlessRenderer.ts + + + + IRenderer.ts + + + Statics.ts + + + CanvasRenderer.ts + + CircleUtils.ts - + PointUtils.ts Polygon.ts - - + + RectangleUtils.ts @@ -152,14 +151,10 @@ Line.ts - - + + Vec2Utils.ts - - - Vector2.ts - SoundManager.ts @@ -167,10 +162,6 @@ - - - CollisionMask.ts - Gestures.ts @@ -192,16 +183,16 @@ - + Animation.ts - + AnimationLoader.ts - + Frame.ts - + FrameData.ts @@ -210,13 +201,13 @@ Device.ts - + LinkedList.ts - + QuadTree.ts - + RandomDataGenerator.ts @@ -225,23 +216,23 @@ StageScaleMode.ts - + Tile.ts - - + + TilemapLayer.ts Tween.ts - + - - - + + + @@ -304,35 +295,26 @@ - - - - + + + + - - - - - - - + Group.ts Loader.ts - - Motion.ts - Phaser.ts - + Signal.ts - + SignalBinding.ts @@ -347,6 +329,10 @@ TweenManager.ts + + + SpriteUtils.ts + World.ts @@ -355,20 +341,15 @@ - - + + - - - + + - - - - - Basic.ts - + + Cache.ts @@ -377,7 +358,6 @@ - diff --git a/Phaser/Phaser.d.ts b/Phaser/Phaser.d.ts deleted file mode 100644 index a743b1ff..00000000 --- a/Phaser/Phaser.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -module Phaser { - var VERSION: string; -} diff --git a/Phaser/Phaser.ts b/Phaser/Phaser.ts index a2f663b4..11d83616 100644 --- a/Phaser/Phaser.ts +++ b/Phaser/Phaser.ts @@ -1,13 +1,14 @@ /** * 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." @@ -16,6 +17,6 @@ module Phaser { - export var VERSION: string = 'Phaser version 0.9.6'; + export var VERSION: string = 'Phaser version 1.0.0'; } diff --git a/Phaser/RenderManager.ts b/Phaser/RenderManager.ts deleted file mode 100644 index 319ec95a..00000000 --- a/Phaser/RenderManager.ts +++ /dev/null @@ -1,25 +0,0 @@ -// Interface -interface IPoint { - getDist(): number; -} - -// Module -module Shapes { - - // Class - export class Point implements IPoint { - // Constructor - constructor (public x: number, public y: number) { } - - // Instance member - getDist() { return Math.sqrt(this.x * this.x + this.y * this.y); } - - // Static member - static origin = new Point(0, 0); - } - -} - -// Local variables -var p: IPoint = new Shapes.Point(3, 4); -var dist = p.getDist(); \ No newline at end of file diff --git a/Phaser/Signal.d.ts b/Phaser/Signal.d.ts deleted file mode 100644 index c7810ee9..00000000 --- a/Phaser/Signal.d.ts +++ /dev/null @@ -1,26 +0,0 @@ -/// -module Phaser { - class Signal { - private _bindings; - private _prevParams; - static VERSION: string; - public memorize: bool; - private _shouldPropagate; - public active: bool; - public validateListener(listener, fnName): void; - private _registerListener(listener, isOnce, listenerContext, priority); - private _addBinding(binding); - private _indexOfListener(listener, context); - public has(listener, context?: any): bool; - public add(listener, listenerContext?: any, priority?: number): SignalBinding; - public addOnce(listener, listenerContext?: any, priority?: number): SignalBinding; - public remove(listener, context?: any); - public removeAll(): void; - public getNumListeners(): number; - public halt(): void; - public dispatch(...paramsArr: any[]): void; - public forget(): void; - public dispose(): void; - public toString(): string; - } -} diff --git a/Phaser/SignalBinding.d.ts b/Phaser/SignalBinding.d.ts deleted file mode 100644 index 2f949792..00000000 --- a/Phaser/SignalBinding.d.ts +++ /dev/null @@ -1,21 +0,0 @@ -/// -module Phaser { - class SignalBinding { - constructor(signal: Signal, listener, isOnce: bool, listenerContext, priority?: number); - private _listener; - private _isOnce; - public context; - private _signal; - public priority: number; - public active: bool; - public params; - public execute(paramsArr?: any[]); - public detach(); - public isBound(): bool; - public isOnce(): bool; - public getListener(); - public getSignal(): Signal; - public _destroy(): void; - public toString(): string; - } -} diff --git a/Phaser/SoundManager.d.ts b/Phaser/SoundManager.d.ts deleted file mode 100644 index 9fe94071..00000000 --- a/Phaser/SoundManager.d.ts +++ /dev/null @@ -1,16 +0,0 @@ -/// -/// -module Phaser { - class SoundManager { - constructor(game: Game); - private _game; - private _context; - private _gainNode; - private _volume; - public mute(): void; - public unmute(): void; - public volume : number; - public decode(key: string, callback?, sound?: Sound): void; - public play(key: string, volume?: number, loop?: bool): Sound; - } -} diff --git a/Phaser/Stage.d.ts b/Phaser/Stage.d.ts deleted file mode 100644 index a4443e02..00000000 --- a/Phaser/Stage.d.ts +++ /dev/null @@ -1,47 +0,0 @@ -/// -/// -/// -/// -/// -module Phaser { - class Stage { - constructor(game: Game, parent: string, width: number, height: number); - private _game; - private _bgColor; - private _bootScreen; - private _pauseScreen; - static ORIENTATION_LANDSCAPE: number; - static ORIENTATION_PORTRAIT: number; - public bounds: Rectangle; - public aspectRatio: number; - public clear: bool; - public canvas: HTMLCanvasElement; - public context: CanvasRenderingContext2D; - public disablePauseScreen: bool; - public disableBootScreen: bool; - public offset: Point; - public scale: StageScaleMode; - public scaleMode: number; - public minScaleX: number; - public maxScaleX: number; - public minScaleY: number; - public maxScaleY: number; - public update(): void; - private visibilityChange(event); - private getOffset(element); - public strokeStyle: string; - public lineWidth: number; - public fillStyle: string; - public saveCanvasValues(): void; - public restoreCanvasValues(): void; - public backgroundColor : string; - public x : number; - public y : number; - public width : number; - public height : number; - public centerX : number; - public centerY : number; - public randomX : number; - public randomY : number; - } -} diff --git a/Phaser/Stage.ts b/Phaser/Stage.ts index 38ee1305..d3ec2896 100644 --- a/Phaser/Stage.ts +++ b/Phaser/Stage.ts @@ -52,7 +52,7 @@ module Phaser { this.context = this.canvas.getContext('2d'); this.offset = this.getOffset(this.canvas); - this.bounds = new Quad(this.offset.x, this.offset.y, width, height); + this.bounds = new Rectangle(this.offset.x, this.offset.y, width, height); this.aspectRatio = width / height; this.scaleMode = StageScaleMode.NO_SCALE; this.scale = new StageScaleMode(this._game); @@ -92,9 +92,9 @@ module Phaser { /** * Bound of this stage. - * @type {Quad} + * @type {Rectangle} */ - public bounds: Quad; + public bounds: Rectangle; /** * Asperct ratio, thus: width / height. @@ -138,7 +138,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). @@ -227,7 +227,7 @@ module Phaser { /** * Get the DOM offset values of the given element */ - private getOffset(element): MicroPoint { + private getOffset(element): Point { var box = element.getBoundingClientRect(); @@ -236,7 +236,7 @@ module Phaser { var scrollTop = window.pageYOffset || element.scrollTop || document.body.scrollTop; var scrollLeft = window.pageXOffset || element.scrollLeft || document.body.scrollLeft; - return new MicroPoint(box.left + scrollLeft - clientLeft, box.top + scrollTop - clientTop); + return new Point(box.left + scrollLeft - clientLeft, box.top + scrollTop - clientTop); } diff --git a/Phaser/State.ts b/Phaser/State.ts index 8925dd7a..e7bee94b 100644 --- a/Phaser/State.ts +++ b/Phaser/State.ts @@ -161,7 +161,7 @@ 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: Basic = null, objectOrGroup2: Basic = null, notifyCallback = null, context? = this.game.callbackContext): bool { + 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/Statics.ts b/Phaser/Statics.ts new file mode 100644 index 00000000..472a1d3c --- /dev/null +++ b/Phaser/Statics.ts @@ -0,0 +1,29 @@ +module Phaser { + + /** + * Constants used to define game object types (faster than doing typeof object checks in core loops) + */ + export class Types { + + static RENDERER_AUTO_DETECT: number = 0; + static RENDERER_HEADLESS: number = 1; + static RENDERER_CANVAS: number = 2; + static RENDERER_WEBGL: number = 3; + + static GROUP: number = 0; + static SPRITE: number = 1; + static GEOMSPRITE: number = 2; + static PARTICLE: number = 3; + static EMITTER: number = 4; + static TILEMAP: number = 5; + static SCROLLZONE: number = 6; + + static GEOM_POINT: number = 0; + static GEOM_CIRCLE: number = 1; + static GEOM_RECTANGLE: number = 2; + static GEOM_LINE: number = 3; + static GEOM_POLYGON: number = 4; + + } + +} diff --git a/Phaser/Time.d.ts b/Phaser/Time.d.ts deleted file mode 100644 index 946a0236..00000000 --- a/Phaser/Time.d.ts +++ /dev/null @@ -1,25 +0,0 @@ -/// -module Phaser { - class Time { - constructor(game: Game); - private _game; - private _started; - public timeScale: number; - public elapsed: number; - public time: number; - public now: number; - public delta: number; - public totalElapsedSeconds : number; - public fps: number; - public fpsMin: number; - public fpsMax: number; - public msMin: number; - public msMax: number; - public frames: number; - private _timeLastSecond; - public update(): void; - public elapsedSince(since: number): number; - public elapsedSecondsSince(since: number): number; - public reset(): void; - } -} diff --git a/Phaser/TweenManager.d.ts b/Phaser/TweenManager.d.ts deleted file mode 100644 index 21d47a5d..00000000 --- a/Phaser/TweenManager.d.ts +++ /dev/null @@ -1,15 +0,0 @@ -/// -/// -module Phaser { - class TweenManager { - constructor(game: Game); - private _game; - private _tweens; - public getAll(): Tween[]; - public removeAll(): void; - public create(object): Tween; - public add(tween: Tween): Tween; - public remove(tween: Tween): void; - public update(): bool; - } -} diff --git a/Phaser/World.d.ts b/Phaser/World.d.ts deleted file mode 100644 index 0c672981..00000000 --- a/Phaser/World.d.ts +++ /dev/null @@ -1,32 +0,0 @@ -/// -module Phaser { - class World { - constructor(game: Game, width: number, height: number); - private _game; - public cameras: CameraManager; - public group: Group; - public bounds: Rectangle; - public worldDivisions: number; - public update(): void; - public render(): void; - public destroy(): void; - public setSize(width: number, height: number, updateCameraBounds?: bool): void; - public width : number; - public height : number; - public centerX : number; - public centerY : number; - public randomX : number; - public randomY : number; - public createCamera(x: number, y: number, width: number, height: number): Camera; - public removeCamera(id: number): bool; - public getAllCameras(): Camera[]; - public createSprite(x: number, y: number, key?: string): Sprite; - public createGeomSprite(x: number, y: number): GeomSprite; - public createDynamicTexture(width: number, height: number): DynamicTexture; - public createGroup(MaxSize?: number): Group; - public createScrollZone(key: string, x?: number, y?: number, width?: number, height?: number): ScrollZone; - public createTilemap(key: string, mapData: string, format: number, resizeWorld?: bool, tileWidth?: number, tileHeight?: number): Tilemap; - public createParticle(): Particle; - public createEmitter(x?: number, y?: number, size?: number): Emitter; - } -} diff --git a/Phaser/World.ts b/Phaser/World.ts index d490d497..31d6f568 100644 --- a/Phaser/World.ts +++ b/Phaser/World.ts @@ -1,4 +1,7 @@ /// +/// +/// +/// /** * Phaser - World @@ -64,28 +67,15 @@ 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() { - this.group.preUpdate(); this.group.update(); - this.group.postUpdate(); - this.cameras.update(); } - /** - * Render every thing to the screen, automatically called after update(). - */ - public render() { - - // Unlike in flixel our render process is camera driven, not group driven - this.cameras.render(); - - } - /** * Clean up memory. */ @@ -97,18 +87,14 @@ module Phaser { } - // World methods - /** - * 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 = true, updateVerletBounds: bool = true) { + public setSize(width: number, height: number, updateCameraBounds: bool = true) { this.bounds.width = width; this.bounds.height = height; @@ -118,11 +104,7 @@ module Phaser { 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 } @@ -158,31 +140,6 @@ module Phaser { return Math.round(Math.random() * this.bounds.height); } - // 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. - */ - public createCamera(x: number, y: number, width: number, height: number): Camera { - return this.cameras.addCamera(x, y, width, height); - } - - /** - * 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 { - return this.cameras.removeCamera(id); - } - /** * Get all the cameras. * @@ -192,102 +149,6 @@ module Phaser { return this.cameras.getAll(); } - // 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. - */ - public createSprite(x: number, y: number, key?: string = ''): Sprite { - return this.group.add(new Sprite(this._game, x, y, key)); - } - - /** - * 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 { - return this.group.add(new GeomSprite(this._game, x, y)); - } - - /** - * 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 { - return new DynamicTexture(this._game, width, height); - } - - /** - * Create a new object container. - * - * @param [maxSize] {number} capacity of this group. - * @returns {Group} The newly created group. - */ - public createGroup(maxSize?: number = 0): Group { - return this.group.add(new Group(this._game, maxSize)); - } - - /** - * 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 = 0, y?: number = 0, width?: number = 0, height?: number = 0): ScrollZone { - return this.group.add(new ScrollZone(this._game, key, x, y, width, height)); - } - - /** - * 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 = true, tileWidth?: number = 0, tileHeight?: number = 0): Tilemap { - return this.group.add(new Tilemap(this._game, key, mapData, format, resizeWorld, tileWidth, tileHeight)); - } - - /** - * Create a new Particle. - * - * @return {Particle} The newly created particle object. - */ - public createParticle(): Particle { - return new Particle(this._game); - } - - /** - * 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 = 0, y?: number = 0, size?: number = 0): Emitter { - return this.group.add(new Emitter(this._game, x, y, size)); - } - } } \ No newline at end of file diff --git a/Phaser/cameras/Camera.ts b/Phaser/cameras/Camera.ts index 46853963..0a839ffc 100644 --- a/Phaser/cameras/Camera.ts +++ b/Phaser/cameras/Camera.ts @@ -3,6 +3,7 @@ /// /// /// +/// /** * Phaser - Camera @@ -17,8 +18,6 @@ module Phaser { export 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. @@ -35,7 +34,9 @@ module Phaser { this.ID = id; this._stageX = x; this._stageY = y; - this.fx = new FXManager(this._game, this); + this.scaledX = x; + this.scaledY = x; + this.fx = new CameraFX(this._game, this); // The view into the world canvas we wish to render this.worldView = new Rectangle(0, 0, width, height); @@ -54,8 +55,11 @@ module Phaser { private _stageY: number; private _rotation: number = 0; private _target: Sprite = null; - private _sx: number = 0; - private _sy: number = 0; + //private _sx: number = 0; + //private _sy: number = 0; + + public scaledX: number; + public scaledY: number; /** * Camera "follow" style preset: camera has no deadzone, just tracks the focus object directly. @@ -164,9 +168,55 @@ module Phaser { /** * Effects manager. - * @type {FXManager} + * @type {CameraFX} */ - public fx: FXManager; + 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) { + + if (this.isHidden(object) == false) + { + object['cameraBlacklist'].push(this.ID); + } + + } + + /** + * Returns true if the object is hidden from this Camera. + * + * @param object {Sprite/Group} The object to check. + */ + public isHidden(object): bool { + + if (object['cameraBlacklist'] && object['cameraBlacklist'].length > 0 && object['cameraBlacklist'].indexOf(this.ID) == -1) + { + return true; + } + + return false; + + } + + /** + * 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) { + + if (this.isHidden(object) == true) + { + object['cameraBlacklist'].slice(object['cameraBlacklist'].indexOf(this.ID), 1); + } + + } /** * Tells this camera object what sprite to track. @@ -339,9 +389,9 @@ module Phaser { } /** - * Draw background, shadow, effects, and objects if this is visible. + * Camera preRender */ - public render() { + public preRender() { if (this.visible === false || this.alpha < 0.1) { @@ -360,32 +410,32 @@ module Phaser { this._game.stage.context.globalAlpha = this.alpha; } - this._sx = this._stageX; - this._sy = this._stageY; + 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._sx = this._sx / this.scale.x; - this._sy = this._sy / 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._sx + this.worldView.halfWidth, this._sy + this.worldView.halfHeight); + 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._sx + this.worldView.halfWidth), -(this._sy + this.worldView.halfHeight)); + 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._sx, this._sy, this.worldView.width, this.worldView.height); + 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); @@ -394,13 +444,17 @@ module Phaser { 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.rect(this.scaledX, this.scaledY, this.worldView.width, this.worldView.height); this._game.stage.context.closePath(); this._game.stage.context.clip(); } - // Render all the Sprites - this._game.world.group.render(this, this._sx, this._sy); + } + + /** + * Camera postRender + */ + public postRender() { // Scale off if (this.scale.x !== 1 || this.scale.y !== 1) @@ -408,7 +462,7 @@ module Phaser { this._game.stage.context.scale(1, 1); } - this.fx.postRender(this, this._sx, this._sy, this.worldView.width, this.worldView.height); + this.fx.postRender(this, this.scaledX, this.scaledY, this.worldView.width, this.worldView.height); if (this._rotation !== 0 || (this._clip && this.disableClipping == false)) { @@ -474,6 +528,15 @@ module Phaser { } + /** + * Destroys this camera, associated FX and removes itself from the CameraManager. + */ + public destroy() { + + this._game.world.cameras.removeCamera(this.ID); + this.fx.destroy(); + } + public get x(): number { return this._stageX; } diff --git a/Phaser/cameras/CameraManager.ts b/Phaser/cameras/CameraManager.ts index 272a5f7e..17cf6c31 100644 --- a/Phaser/cameras/CameraManager.ts +++ b/Phaser/cameras/CameraManager.ts @@ -1,5 +1,5 @@ -/// -/// +/// +/// /** * Phaser - CameraManager @@ -46,6 +46,9 @@ module Phaser { */ private _cameraInstance: number = 0; + public static CAMERA_TYPE_ORTHOGRAPHIC: number = 0; + public static CAMERA_TYPE_ISOMETRIC: number = 1; + /** * Currently used camera. */ @@ -67,13 +70,6 @@ module Phaser { this._cameras.forEach((camera) => camera.update()); } - /** - * Render cameras. - */ - public render() { - this._cameras.forEach((camera) => camera.render()); - } - /** * Create a new camera with specific position and size. * @@ -83,7 +79,7 @@ module Phaser { * @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 { + public addCamera(x: number, y: number, width: number, height: number, type: number = CameraManager.CAMERA_TYPE_ORTHOGRAPHIC): Camera { var newCam: Camera = new Camera(this._game, this._cameraInstance, x, y, width, height); diff --git a/Phaser/cameras/OrthographicCamera.ts b/Phaser/cameras/OrthographicCamera.ts deleted file mode 100644 index e69de29b..00000000 diff --git a/Phaser/gameobjects/ScrollRegion.ts b/Phaser/components/ScrollRegion.ts similarity index 84% rename from Phaser/gameobjects/ScrollRegion.ts rename to Phaser/components/ScrollRegion.ts index 42c80219..aa75d28d 100644 --- a/Phaser/gameobjects/ScrollRegion.ts +++ b/Phaser/components/ScrollRegion.ts @@ -1,5 +1,6 @@ /// -/// +/// +/// /** * Phaser - ScrollRegion @@ -26,23 +27,23 @@ module Phaser { constructor(x: number, y: number, width: number, height: number, speedX:number, speedY:number) { // Our seamless scrolling quads - this._A = new Quad(x, y, width, height); - this._B = new Quad(x, y, width, height); - this._C = new Quad(x, y, width, height); - this._D = new Quad(x, y, width, height); - this._scroll = new MicroPoint(); - this._bounds = new Quad(x, y, width, height); - this.scrollSpeed = new MicroPoint(speedX, speedY); + this._A = new Rectangle(x, y, width, height); + this._B = new Rectangle(x, y, width, height); + this._C = new Rectangle(x, y, width, height); + this._D = new Rectangle(x, y, width, height); + this._scroll = new Vec2(); + this._bounds = new Rectangle(x, y, width, height); + this.scrollSpeed = new Vec2(speedX, speedY); } - private _A: Quad; - private _B: Quad; - private _C: Quad; - private _D: Quad; + private _A: Rectangle; + private _B: Rectangle; + private _C: Rectangle; + private _D: Rectangle; - private _bounds: Quad; - private _scroll: MicroPoint; + private _bounds: Rectangle; + private _scroll: Vec2; private _anchorWidth: number = 0; private _anchorHeight: number = 0; @@ -57,9 +58,9 @@ module Phaser { /** * Region scrolling speed. - * @type {MicroPoint} + * @type {Vec2} */ - public scrollSpeed: MicroPoint; + public scrollSpeed: Vec2; /** * Update region scrolling with tick time. @@ -107,20 +108,20 @@ module Phaser { this._inverseWidth = this._bounds.width - this._anchorWidth; this._inverseHeight = this._bounds.height - this._anchorHeight; - // Quad A + // Rectangle A this._A.setTo(this._scroll.x, this._scroll.y, this._anchorWidth, this._anchorHeight); - // Quad B + // Rectangle B this._B.y = this._scroll.y; this._B.width = this._inverseWidth; this._B.height = this._anchorHeight; - // Quad C + // Rectangle C this._C.x = this._scroll.x; this._C.width = this._anchorWidth; this._C.height = this._inverseHeight; - // Quad D + // Rectangle D this._D.width = this._inverseWidth; this._D.height = this._inverseHeight; @@ -152,10 +153,10 @@ module Phaser { //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); + //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); } diff --git a/Phaser/system/Tile.ts b/Phaser/components/Tile.ts similarity index 99% rename from Phaser/system/Tile.ts rename to Phaser/components/Tile.ts index 5f1287d7..ab7f955b 100644 --- a/Phaser/system/Tile.ts +++ b/Phaser/components/Tile.ts @@ -47,11 +47,13 @@ module Phaser { * @type {number} */ public mass: number = 1.0; + /** * Tile width. * @type {number} */ public width: number; + /** * Tile height. * @type {number} @@ -69,16 +71,19 @@ module Phaser { * @type {boolean} */ public collideLeft: bool = false; + /** * Indicating collide with any object on the right. * @type {boolean} */ public collideRight: bool = false; + /** * Indicating collide with any object on the top. * @type {boolean} */ public collideUp: bool = false; + /** * Indicating collide with any object on the bottom. * @type {boolean} @@ -90,6 +95,7 @@ module Phaser { * @type {boolean} */ public separateX: bool = true; + /** * Enable separation at y-axis. * @type {boolean} diff --git a/Phaser/system/TilemapLayer.ts b/Phaser/components/TilemapLayer.ts similarity index 100% rename from Phaser/system/TilemapLayer.ts rename to Phaser/components/TilemapLayer.ts diff --git a/Phaser/animation/Animation.ts b/Phaser/components/animation/Animation.ts similarity index 100% rename from Phaser/animation/Animation.ts rename to Phaser/components/animation/Animation.ts diff --git a/Phaser/animation/AnimationManager.ts b/Phaser/components/animation/AnimationManager.ts similarity index 96% rename from Phaser/animation/AnimationManager.ts rename to Phaser/components/animation/AnimationManager.ts index 8c530f37..e2e46477 100644 --- a/Phaser/animation/AnimationManager.ts +++ b/Phaser/components/animation/AnimationManager.ts @@ -1,9 +1,9 @@ -/// -/// -/// -/// -/// -/// +/// +/// +/// +/// +/// +/// /** * Phaser - AnimationManager diff --git a/Phaser/animation/Frame.ts b/Phaser/components/animation/Frame.ts similarity index 100% rename from Phaser/animation/Frame.ts rename to Phaser/components/animation/Frame.ts diff --git a/Phaser/animation/FrameData.ts b/Phaser/components/animation/FrameData.ts similarity index 100% rename from Phaser/animation/FrameData.ts rename to Phaser/components/animation/FrameData.ts diff --git a/Phaser/FXManager.ts b/Phaser/components/camera/CameraFX.ts similarity index 96% rename from Phaser/FXManager.ts rename to Phaser/components/camera/CameraFX.ts index 70149bcf..909403c3 100644 --- a/Phaser/FXManager.ts +++ b/Phaser/components/camera/CameraFX.ts @@ -1,14 +1,15 @@ -/// +/// +/// /** -* Phaser - FXManager +* Phaser - CameraFX * -* The FXManager controls all special effects applied to game objects such as Cameras. +* CameraFX controls all special effects applied to game Cameras. */ module Phaser { - export class FXManager { + export class CameraFX { constructor(game: Game, parent) { @@ -69,7 +70,7 @@ module Phaser { } else { - throw new Error("Invalid object given to Phaser.FXManager.add"); + throw new Error("Invalid object given to Phaser.CameraFX.add"); } // Check for methods now to avoid having to do this every loop diff --git a/Phaser/system/CollisionMask.ts b/Phaser/components/sprite/CollisionMask.ts similarity index 100% rename from Phaser/system/CollisionMask.ts rename to Phaser/components/sprite/CollisionMask.ts diff --git a/Phaser/components/sprite/Debug.ts b/Phaser/components/sprite/Debug.ts new file mode 100644 index 00000000..5ffa22eb --- /dev/null +++ b/Phaser/components/sprite/Debug.ts @@ -0,0 +1,90 @@ +/** +* Phaser - Components - Debug +* +* +*/ + +module Phaser.Components { + + export class Debug { + + /** + * Render bound of this sprite for debugging? (default to false) + * @type {boolean} + */ + public renderDebug: bool = false; + + /** + * Color of the Sprite when no image is present. Format is a css color string. + * @type {string} + */ + public fillColor: string = 'rgb(255,255,255)'; + + /** + * Color of bound when render debug. (see renderDebug) Format is a css color string. + * @type {string} + */ + public renderDebugColor: string = 'rgba(0,255,0,0.5)'; + + /** + * Color of points when render debug. (see renderDebug) Format is a css color string. + * @type {string} + */ + public renderDebugPointColor: string = 'rgba(255,255,255,1)'; + + /** + * 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: Camera, cameraOffsetX: number, cameraOffsetY: number) { + + 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 + + } + */ + + /** + * 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 = '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); + + } + */ + + } + +} \ No newline at end of file diff --git a/Phaser/components/sprite/Input.ts b/Phaser/components/sprite/Input.ts new file mode 100644 index 00000000..75a23b04 --- /dev/null +++ b/Phaser/components/sprite/Input.ts @@ -0,0 +1,29 @@ +/** +* Phaser - Components - Input +* +* +*/ + +module Phaser.Components { + + export class Input { + + // Input + //public inputEnabled: bool = false; + //private _inputOver: bool = false; + + //public onInputOver: Phaser.Signal; + //public onInputOut: Phaser.Signal; + //public onInputDown: Phaser.Signal; + //public onInputUp: Phaser.Signal; + + /** + * Update input. + */ + private updateInput() { + } + + + } + +} \ No newline at end of file diff --git a/Phaser/components/sprite/Physics.ts b/Phaser/components/sprite/Physics.ts index 37a5fa42..8fc6aff4 100644 --- a/Phaser/components/sprite/Physics.ts +++ b/Phaser/components/sprite/Physics.ts @@ -1,3 +1,6 @@ +/// +/// + /** * Phaser - Components - Physics * @@ -22,9 +25,9 @@ module Phaser.Components { * 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} + * @type {Vec2} */ - public velocity: MicroPoint; + public velocity: Vec2; /** * The virtual mass of the object. @@ -42,21 +45,21 @@ module Phaser.Components { * How fast the speed of this object is changing. * @type {number} */ - public acceleration: MicroPoint; + public acceleration: Vec2; /** * This isn't drag exactly, more like deceleration that is only applied * when acceleration is not affecting the sprite. - * @type {MicroPoint} + * @type {Vec2} */ - public drag: MicroPoint; + public drag: Vec2; /** * It will cap the speed automatically if you use the acceleration * to change its velocity. - * @type {MicroPoint} + * @type {Vec2} */ - public maxVelocity: MicroPoint; + public maxVelocity: Vec2; /** * How fast this object is rotating. @@ -110,15 +113,41 @@ module Phaser.Components { /** * Important variable for collision processing. - * @type {MicroPoint} + * @type {Vec2} */ - public last: MicroPoint; + public last: Vec2; + + /** + * 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 { + return (this.touching & direction) > Collision.NONE; + } + + /** + * 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 { + return ((this.touching & direction) > Collision.NONE) && ((this.wasTouching & direction) <= Collision.NONE); + } + /** * Internal function for updating the position and speed of this object. */ public update() { +/* var delta: number; var velocityDelta: number; @@ -138,9 +167,31 @@ module Phaser.Components { delta = this.velocity.y * this._game.time.elapsed; this.velocity.y += velocityDelta; this.frameBounds.y += delta; +*/ } + /** + * 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 get solid(): bool { + return (this.allowCollisions & Collision.ANY) > Collision.NONE; + } + + public set solid(value: bool) { + + if (value) + { + this.allowCollisions = Collision.ANY; + } + else + { + this.allowCollisions = Collision.NONE; + } + + } } diff --git a/Phaser/components/sprite/Position.ts b/Phaser/components/sprite/Position.ts new file mode 100644 index 00000000..4528af45 --- /dev/null +++ b/Phaser/components/sprite/Position.ts @@ -0,0 +1,65 @@ +/// + +/** +* Phaser - Components - Position +* +* Sprite position, both world and screen, and rotation values and methods. +*/ + +module Phaser.Components { + + export class Position { + + constructor(parent: Sprite, x: number, y: number) { + + 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); + + } + + /** + * Reference to the Image stored in the Game.Cache that is used as the texture for the Sprite. + */ + private _sprite: Sprite; + + public world: Phaser.Vec2; + public screen: Phaser.Vec2; + + public offset: Phaser.Vec2; + public midpoint: Phaser.Vec2; + + /** + * Rotation angle of this object. + * @type {number} + */ + private _rotation: number = 0; + + /** + * Z-order value of the object. + */ + public z: number = 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} + */ + public rotationOffset: number = 0; + + public get rotation(): number { + return this._rotation; + } + + public set rotation(value: number) { + this._rotation = this._sprite.game.math.wrap(value, 360, 0); + } + + } + +} \ No newline at end of file diff --git a/Phaser/components/sprite/Properties.ts b/Phaser/components/sprite/Properties.ts new file mode 100644 index 00000000..3171afe9 --- /dev/null +++ b/Phaser/components/sprite/Properties.ts @@ -0,0 +1,36 @@ +/** +* Phaser - Components - Properties +* +* +*/ + +module Phaser.Components { + + export class Properties { + + /** + * Handy for storing health percentage or armor points or whatever. + * @type {number} + */ + public health: number; + + /** + * 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) { + + this.health = this.health - damage; + + if (this.health <= 0) + { + //this.kill(); + } + + } + + } + +} \ No newline at end of file diff --git a/Phaser/components/sprite/Texture.ts b/Phaser/components/sprite/Texture.ts index 55563df5..02e59962 100644 --- a/Phaser/components/sprite/Texture.ts +++ b/Phaser/components/sprite/Texture.ts @@ -1,14 +1,171 @@ +/// +/// +/// + /** * Phaser - Components - Texture * -* The Sprite GameObject is an extension of the core GameObject that includes support for animation and dynamic textures. +* The Texture being used to render the Sprite. Either Image based on a DynamicTexture. */ module Phaser.Components { export class Texture { + constructor(parent: Sprite, key?: string = '', canvas?: HTMLCanvasElement = null, context?: CanvasRenderingContext2D = null) { + 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); + } + + } + + /** + * Reference to the Image stored in the Game.Cache that is used as the texture for the Sprite. + */ + private _sprite: Sprite; + + /** + * Reference to the Image stored in the Game.Cache that is used as the texture for the Sprite. + */ + private _imageTexture = null; + + /** + * Reference to the DynamicTexture that is used as the texture for the Sprite. + * @type {DynamicTexture} + */ + private _dynamicTexture: DynamicTexture = null; + + /** + * 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 = true; + + /** + * Flip the graphic horizontally (defaults to false) + * @type {boolean} + */ + public flippedX: bool = false; + + /** + * Flip the graphic vertically (defaults to false) + * @type {boolean} + */ + public flippedY: bool = false; + + /** + * Updates the texture being used to render the Sprite. + * Called automatically by SpriteUtils.loadTexture and SpriteUtils.loadDynamicTexture. + */ + public setTo(image = null, dynamic?: DynamicTexture = null): Sprite { + + if (dynamic) + { + this._dynamicTexture = dynamic; + this.texture = this._dynamicTexture.canvas; + } + else + { + this._imageTexture = image; + this.texture = this._imageTexture; + } + + return this._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 = true): Sprite { + return Phaser.SpriteUtils.loadTexture(this._sprite, key, clearAnimations); + } + + /** + * 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 { + return Phaser.SpriteUtils.loadDynamicTexture(this._sprite, texture); + } + + /** + * Getter only. The width of the texture. + * @type {number} + */ + public get width(): number { + + if (this._dynamicTexture) + { + return this._dynamicTexture.width; + } + else + { + return this._imageTexture.width; + } + } + + /** + * Getter only. The height of the texture. + * @type {number} + */ + public get height(): number { + + if (this._dynamicTexture) + { + return this._dynamicTexture.height; + } + else + { + return this._imageTexture.height; + } + + } } diff --git a/Phaser/core/Circle.ts b/Phaser/core/Circle.ts index ca8af3b6..e2468462 100644 --- a/Phaser/core/Circle.ts +++ b/Phaser/core/Circle.ts @@ -27,7 +27,7 @@ module Phaser { private _diameter: number = 0; private _radius: number = 0; - private _pos: Vector2; + //private _pos: Vec2; /** * The x coordinate of the center of the circle @@ -249,6 +249,16 @@ module Phaser { } + /** + * 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 { + return this.setTo(source.x, source.y, source.diameter); + } + /** * Determines whether or not this Circle object is empty. * @method empty diff --git a/Phaser/Group.ts b/Phaser/core/Group.ts similarity index 63% rename from Phaser/Group.ts rename to Phaser/core/Group.ts index f830cbd4..f112d177 100644 --- a/Phaser/Group.ts +++ b/Phaser/core/Group.ts @@ -1,5 +1,5 @@ -/// -/// +/// +/// /** * Phaser - Group @@ -9,18 +9,22 @@ module Phaser { - export class Group extends Basic { + export class Group { - constructor(game: Game, MaxSize?: number = 0) { + constructor(game: Game, maxSize?: number = 0) { - super(game); + this.game = game; + this.type = Phaser.Types.GROUP; + this.exists = true; + this.visible = true; - this.isGroup = true; this.members = []; this.length = 0; - this._maxSize = MaxSize; + + this._maxSize = maxSize; this._marker = 0; this._sortIndex = null; + this.cameraBlacklist = []; } @@ -46,6 +50,35 @@ module Phaser { */ private _sortOrder: number; + /** + * Temp vars to help avoid gc spikes + */ + private _member; + private _length: number; + private _i: number; + private _prevAlpha: number; + private _count: number; + + /** + * 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. */ @@ -57,9 +90,9 @@ module Phaser { public static DESCENDING: number = 1; /** - * 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. @@ -89,43 +122,6 @@ 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) { - - if (this.cameraBlacklist.indexOf(camera.ID) == -1) - { - this.cameraBlacklist.push(camera.ID); - } - - } - - /** - * Make this object only visible to a specific camera. - * - * @param camera {Camera} The camera you wish it to be visible. - */ - public showToCamera(camera: Camera) { - - if (this.cameraBlacklist.indexOf(camera.ID) !== -1) - { - this.cameraBlacklist.slice(this.cameraBlacklist.indexOf(camera.ID), 1); - } - - } - - /** - * This clears the camera black list, making the GameObject visible to all cameras. - */ - public clearCameraList() { - - this.cameraBlacklist.length = 0; - - } - /** * Override this function to handle any deleting or "shutdown" type operations you might need, * such as removing traditional Flash children like Basic objects. @@ -134,16 +130,15 @@ module Phaser { if (this.members != null) { - var basic: Basic; - var i: number = 0; + this._i = 0; - while (i < this.length) + while (this._i < this.length) { - basic = this.members[i++]; + this._member = this.members[this._i++]; - if (basic != null) + if (this._member != null) { - basic.destroy(); + this._member.destroy(); } } @@ -155,79 +150,69 @@ module Phaser { } /** - * 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 = false) { - if (this.ignoreGlobalUpdate && forceUpdate == false) + this._i = 0; + + while (this._i < this.length) { - return; - } + this._member = this.members[this._i++]; - var basic: Basic; - var i: number = 0; - - while (i < this.length) - { - basic = this.members[i++]; - - if ((basic != null) && basic.exists && basic.active && basic.ignoreGlobalUpdate == false) + if (this._member != null && this._member.exists && this._member.active) { - basic.preUpdate(); - basic.update(forceUpdate); - basic.postUpdate(); + this._member.preUpdate(); + this._member.update(forceUpdate); + this._member.postUpdate(); } } } /** - * Automatically goes through and calls render on everything you added. - */ - public render(camera: Camera, cameraOffsetX: number, cameraOffsetY: number, forceRender?: bool = false) { + * 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) { - if (this.cameraBlacklist.indexOf(camera.ID) !== -1) - { - return; - } - - if (this.ignoreGlobalRender && forceRender == false) + 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: number = 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: Basic; - var i: number = 0; + this._i = 0; - while (i < this.length) + while (this._i < this.length) { - basic = this.members[i++]; + this._member = this.members[this._i++]; - if ((basic != null) && basic.exists && basic.visible && basic.ignoreGlobalRender == false) + if (this._member != null && this._member.exists && this._member.visible && camera.isHidden(this._member) == false) { - basic.render(camera, cameraOffsetX, cameraOffsetY, forceRender); + 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(); } } @@ -250,23 +235,22 @@ module Phaser { 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: Basic; - var i: number = this._maxSize; - var l: number = this.members.length; + this._i = this._maxSize; + this._length = this.members.length; - while (i < l) + while (this._i < this._length) { - basic = this.members[i++]; + this._member = this.members[this._i++]; - if (basic != null) + if (this._member != null) { - basic.destroy(); + this._member.destroy(); } } @@ -285,33 +269,33 @@ 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 { //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: number = 0; - var l: number = this.members.length; + this._i = 0; + this._length = this.members.length; - while (i < l) + while (this._i < this._length) { - if (this.members[i] == null) + if (this.members[this._i] == null) { - this.members[i] = Object; + this.members[this._i] = object; - if (i >= this.length) + if (this._i >= this.length) { - this.length = i + 1; + this.length = this._i + 1; } - return Object; + return object; } - i++; + this._i++; } //Failing that, expand the array (if we can) and add the object. @@ -319,7 +303,7 @@ module Phaser { { if (this.members.length >= this._maxSize) { - return Object; + return object; } else if (this.members.length * 2 <= this._maxSize) { @@ -337,10 +321,10 @@ module 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; + this.members[this._i] = object; + this.length = this._i + 1; - return Object; + return object; } @@ -367,48 +351,46 @@ 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 = null) { - - var basic; + public recycle(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); + this._member = this.getFirstAvailable(objectClass); - if (basic != null) + if (this._member != null) { - return basic; + 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)); } } @@ -420,23 +402,23 @@ module Phaser { * * @return {Basic} The removed object. */ - public remove(object: Basic, splice: bool = false): Basic { + public remove(object, splice: bool = false) { - var index: number = this.members.indexOf(object); + this._i = this.members.indexOf(object); - if ((index < 0) || (index >= this.members.length)) + 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; @@ -451,16 +433,16 @@ module Phaser { * * @return {Basic} The new object. */ - public replace(oldObject: Basic, newObject: Basic): Basic { + public replace(oldObject, newObject) { - var index: number = this.members.indexOf(oldObject); + this._i = this.members.indexOf(oldObject); - if ((index < 0) || (index >= this.members.length)) + if (this._i < 0 || (this._i >= this.members.length)) { return null; } - this.members[index] = newObject; + this.members[this._i] = newObject; return newObject; @@ -491,24 +473,23 @@ 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 = true) { + public setAll(variableName: string, value: Object, recurse: bool = true) { - var basic: Basic; - var i: number = 0; + this._i = 0; - while (i < length) + while (this._i < this.length) { - basic = this.members[i++]; + this._member = this.members[this._i++]; - if (basic != null) + if (this._member != null) { - if (Recurse && (basic.isGroup == true)) + if (recurse && this._member.type == Phaser.Types.GROUP) { - basic['setAll'](VariableName, Value, Recurse); + this._member.setAll(variableName, value, recurse); } else { - basic[VariableName] = Value; + this._member[variableName] = value; } } } @@ -521,24 +502,23 @@ 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 = true) { + public callAll(functionName: string, recurse: bool = true) { - var basic: Basic; - var i: number = 0; + this._i = 0; - while (i < this.length) + while (this._i < this.length) { - basic = this.members[i++]; + this._member = this.members[this._i++]; - if (basic != null) + if (this._member != null) { - if (Recurse && (basic.isGroup == true)) + if (recurse && this._member.type == Phaser.Types.GROUP) { - basic['callAll'](FunctionName, Recurse); + this._member.callAll(functionName, recurse); } else { - basic[FunctionName](); + this._member[functionName](); } } } @@ -550,22 +530,21 @@ module Phaser { */ public forEach(callback, recursive: bool = false) { - var basic; - var i: number = 0; + this._i = 0; - while (i < this.length) + while (this._i < this.length) { - basic = this.members[i++]; + this._member = this.members[this._i++]; - if (basic != null) + if (this._member != null) { - if (recursive && (basic.isGroup == true)) + if (recursive && this._member.type == Phaser.Types.GROUP) { - basic.forEach(callback, true); + this._member.forEach(callback, true); } else { - callback.call(this, basic); + callback.call(this, this._member); } } } @@ -579,22 +558,21 @@ module Phaser { */ public forEachAlive(context, callback, recursive: bool = false) { - var basic; - var i: number = 0; + this._i = 0; - while (i < this.length) + while (this._i < this.length) { - basic = this.members[i++]; + this._member = this.members[this._i++]; - if (basic != null && basic.alive) + if (this._member != null && this._member.alive) { - if (recursive && (basic.isGroup == true)) + if (recursive && this._member.type == Phaser.Types.GROUP) { - basic.forEachAlive(context, callback, true); + this._member.forEachAlive(context, callback, true); } else { - callback.call(context, basic); + callback.call(context, this._member); } } } @@ -609,18 +587,17 @@ module Phaser { * * @return {any} A Basic currently flagged as not existing. */ - public getFirstAvailable(ObjectClass = null) { + public getFirstAvailable(objectClass = null) { - var basic; - var i: number = 0; + this._i = 0; - while (i < this.length) + while (this._i < this.length) { - basic = this.members[i++]; + this._member = this.members[this._i++]; - if ((basic != null) && !basic.exists && ((ObjectClass == null) || (typeof basic === ObjectClass))) + if ((this._member != null) && !this._member.exists && ((objectClass == null) || (typeof this._member === objectClass))) { - return basic; + return this._member; } } @@ -636,19 +613,17 @@ module Phaser { */ public getFirstNull(): number { - var basic: Basic; - var i: number = 0; - var l: number = this.members.length; + this._i = 0; - while (i < l) + while (this._i < this.length) { - if (this.members[i] == null) + if (this.members[this._i] == null) { - return i; + return this._i; } else { - i++; + this._i++; } } @@ -662,18 +637,17 @@ module Phaser { * * @return {Basic} A Basic currently flagged as existing. */ - public getFirstExtant(): Basic { + public getFirstExtant() { - var basic: Basic; - var i: number = 0; + this._i = 0; - while (i < length) + while (this._i < this.length) { - basic = this.members[i++]; + this._member = this.members[this._i++]; - if ((basic != null) && basic.exists) + if (this._member != null && this._member.exists) { - return basic; + return this._member; } } @@ -687,18 +661,17 @@ module Phaser { * * @return {Basic} A Basic currently flagged as not dead. */ - public getFirstAlive(): Basic { + public getFirstAlive() { - var basic: Basic; - var i: number = 0; + this._i = 0; - while (i < this.length) + while (this._i < this.length) { - basic = this.members[i++]; + this._member = this.members[this._i++]; - if ((basic != null) && basic.exists && basic.alive) + if ((this._member != null) && this._member.exists && this._member.alive) { - return basic; + return this._member; } } @@ -712,18 +685,17 @@ module Phaser { * * @return {Basic} A Basic currently flagged as dead. */ - public getFirstDead(): Basic { + public getFirstDead() { - var basic: Basic; - var i: number = 0; + this._i = 0; - while (i < this.length) + while (this._i < this.length) { - basic = this.members[i++]; + this._member = this.members[this._i++]; - if ((basic != null) && !basic.alive) + if ((this._member != null) && !this._member.alive) { - return basic; + return this._member; } } @@ -738,29 +710,28 @@ module Phaser { */ public countLiving(): number { - var count: number = -1; - var basic: Basic; - var i: number = 0; + this._count = -1; + this._i = 0; - while (i < this.length) + while (this._i < this.length) { - basic = this.members[i++]; + this._member = this.members[this._i++]; - if (basic != null) + if (this._member != null) { - if (count < 0) + if (this._count < 0) { - count = 0; + this._count = 0; } - if (basic.exists && basic.alive) + if (this._member.exists && this._member.alive) { - count++; + this._count++; } } } - return count; + return this._count; } @@ -771,29 +742,28 @@ module Phaser { */ public countDead(): number { - var count: number = -1; - var basic: Basic; - var i: number = 0; + this._count = -1; + this._i = 0; - while (i < this.length) + while (this._i < this.length) { - basic = this.members[i++]; + this._member = this.members[this._i++]; - if (basic != null) + if (this._member != null) { - if (count < 0) + if (this._count < 0) { - count = 0; + this._count = 0; } - if (!basic.alive) + if (!this._member.alive) { - count++; + this._count++; } } } - return count; + return this._count; } @@ -805,14 +775,14 @@ module Phaser { * * @return {Basic} A Basic from the members list. */ - public getRandom(StartIndex: number = 0, Length: number = 0): Basic { + public getRandom(startIndex: number = 0, length: number = 0) { - if (Length == 0) + if (length == 0) { - Length = this.length; + length = this.length; } - return this._game.math.getRandom(this.members, StartIndex, Length); + return this.game.math.getRandom(this.members, startIndex, length); } @@ -829,16 +799,15 @@ module Phaser { */ public kill() { - var basic: Basic; - var i: number = 0; + this._i = 0; - while (i < this.length) + while (this._i < this.length) { - basic = this.members[i++]; + this._member = this.members[this._i++]; - if ((basic != null) && basic.exists) + if ((this._member != null) && this._member.exists) { - basic.kill(); + this._member.kill(); } } @@ -852,13 +821,13 @@ 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 { - if (Obj1[this._sortIndex] < Obj2[this._sortIndex]) + 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; } diff --git a/Phaser/core/Point.ts b/Phaser/core/Point.ts index 95ed250f..0e93d78e 100644 --- a/Phaser/core/Point.ts +++ b/Phaser/core/Point.ts @@ -37,21 +37,6 @@ module Phaser { return this.setTo(source.x, source.y); } - /** - * Copies the x and y values from this Point to any given object. - * @method copyTo - * @param {any} target - The object to copy to. - * @return {any} The target object. - **/ - public copyTo(target: any): Point { - - target.x = this.x; - target.y = this.y; - - return target; - - } - /** * Inverts the x and y values of this Point * @method invert diff --git a/Phaser/core/Rectangle.ts b/Phaser/core/Rectangle.ts index 159a7da6..9cced955 100644 --- a/Phaser/core/Rectangle.ts +++ b/Phaser/core/Rectangle.ts @@ -300,6 +300,16 @@ module Phaser { } + /** + * 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 { + return this.setTo(source.x, source.y, source.width, source.height); + } + /** * Returns a string representation of this object. * @method toString diff --git a/Phaser/Signal.ts b/Phaser/core/Signal.ts similarity index 100% rename from Phaser/Signal.ts rename to Phaser/core/Signal.ts diff --git a/Phaser/SignalBinding.ts b/Phaser/core/SignalBinding.ts similarity index 100% rename from Phaser/SignalBinding.ts rename to Phaser/core/SignalBinding.ts diff --git a/Phaser/core/Vec2.ts b/Phaser/core/Vec2.ts index 3c2cb324..f33eca21 100644 --- a/Phaser/core/Vec2.ts +++ b/Phaser/core/Vec2.ts @@ -39,6 +39,16 @@ module Phaser { **/ 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 { + return this.setTo(source.x, source.y); + } + /** * Sets the x and y properties of the Vector. * @param {Number} x The x position of the vector diff --git a/Phaser/DynamicTexture.ts b/Phaser/gameobjects/DynamicTexture.ts similarity index 94% rename from Phaser/DynamicTexture.ts rename to Phaser/gameobjects/DynamicTexture.ts index a9876a43..e5d5f11d 100644 --- a/Phaser/DynamicTexture.ts +++ b/Phaser/gameobjects/DynamicTexture.ts @@ -1,4 +1,4 @@ -/// +/// /** * Phaser - DynamicTexture @@ -23,7 +23,8 @@ module Phaser { */ constructor(game: Game, width: number, height: number) { - this._game = game; + this.game = game; + this.type = Phaser.Types.GEOMSPRITE; this.canvas = document.createElement('canvas'); this.canvas.width = width; @@ -35,9 +36,14 @@ module Phaser { } /** - * Local private reference to game. + * Reference to game. */ - private _game: Game; + public game: Game; + + /** + * The type of game object. + */ + public type: number; private _sx: number = 0; private _sy: number = 0; @@ -176,15 +182,15 @@ module Phaser { // TODO - Load a frame from a sprite sheet, otherwise we'll draw the whole lot if (frame > -1) { - //if (this._game.cache.isSpriteSheet(key)) + //if (this.game.cache.isSpriteSheet(key)) //{ - // texture = this._game.cache.getImage(key); - //this.animations.loadFrameData(this._game.cache.getFrameData(key)); + // texture = this.game.cache.getImage(key); + //this.animations.loadFrameData(this.game.cache.getFrameData(key)); //} } else { - texture = this._game.cache.getImage(key); + texture = this.game.cache.getImage(key); this._sw = texture.width; this._sh = texture.height; this._dw = texture.width; @@ -270,7 +276,7 @@ module Phaser { */ public render(x?: number = 0, y?: number = 0) { - this._game.stage.context.drawImage(this.canvas, x, y); + this.game.stage.context.drawImage(this.canvas, x, y); } diff --git a/Phaser/gameobjects/Emitter.d.ts b/Phaser/gameobjects/Emitter.d.ts deleted file mode 100644 index 564fb553..00000000 --- a/Phaser/gameobjects/Emitter.d.ts +++ /dev/null @@ -1,38 +0,0 @@ -/// -/// -module Phaser { - class Emitter extends Group { - constructor(game: Game, X?: number, Y?: number, Size?: number); - public x: number; - public y: number; - public width: number; - public height: number; - public minParticleSpeed: MicroPoint; - public maxParticleSpeed: MicroPoint; - public particleDrag: MicroPoint; - public minRotation: number; - public maxRotation: number; - public gravity: number; - public on: bool; - public frequency: number; - public lifespan: number; - public bounce: number; - public particleClass; - private _quantity; - private _explode; - private _timer; - private _counter; - private _point; - public destroy(): void; - public makeParticles(Graphics, Quantity?: number, BakedRotations?: number, Multiple?: bool, Collide?: number): Emitter; - public update(): void; - public kill(): void; - public start(Explode?: bool, Lifespan?: number, Frequency?: number, Quantity?: number): void; - public emitParticle(): void; - public setSize(Width: number, Height: number): void; - public setXSpeed(Min?: number, Max?: number): void; - public setYSpeed(Min?: number, Max?: number): void; - public setRotation(Min?: number, Max?: number): void; - public at(Object): void; - } -} diff --git a/Phaser/gameobjects/GameObject.d.ts b/Phaser/gameobjects/GameObject.d.ts deleted file mode 100644 index c7d821e7..00000000 --- a/Phaser/gameobjects/GameObject.d.ts +++ /dev/null @@ -1,84 +0,0 @@ -/// -/// -/// -module Phaser { - class GameObject extends Basic { - constructor(game: Game, x?: number, y?: number, width?: number, height?: number); - private _angle; - static ALIGN_TOP_LEFT: number; - static ALIGN_TOP_CENTER: number; - static ALIGN_TOP_RIGHT: number; - static ALIGN_CENTER_LEFT: number; - static ALIGN_CENTER: number; - static ALIGN_CENTER_RIGHT: number; - static ALIGN_BOTTOM_LEFT: number; - static ALIGN_BOTTOM_CENTER: number; - static ALIGN_BOTTOM_RIGHT: number; - static OUT_OF_BOUNDS_STOP: number; - static OUT_OF_BOUNDS_KILL: number; - public _point: MicroPoint; - public cameraBlacklist: number[]; - public bounds: Rectangle; - public worldBounds: Quad; - public outOfBoundsAction: number; - public align: number; - public facing: number; - public alpha: number; - public scale: MicroPoint; - public origin: MicroPoint; - public z: number; - public rotationOffset: number; - public renderRotation: bool; - public immovable: bool; - public velocity: MicroPoint; - public mass: number; - public elasticity: number; - public acceleration: MicroPoint; - public drag: MicroPoint; - public maxVelocity: MicroPoint; - public angularVelocity: number; - public angularAcceleration: number; - public angularDrag: number; - public maxAngular: number; - public scrollFactor: MicroPoint; - public health: number; - public moves: bool; - public touching: number; - public wasTouching: number; - public allowCollisions: number; - public last: MicroPoint; - public inputEnabled: bool; - private _inputOver; - public onInputOver: Signal; - public onInputOut: Signal; - public onInputDown: Signal; - public onInputUp: Signal; - public preUpdate(): void; - public update(): void; - public postUpdate(): void; - private updateInput(); - private updateMotion(); - public overlaps(ObjectOrGroup, InScreenSpace?: bool, Camera?: Camera): bool; - public overlapsAt(X: number, Y: number, ObjectOrGroup, InScreenSpace?: bool, Camera?: Camera): bool; - public overlapsPoint(point: Point, InScreenSpace?: bool, Camera?: Camera): bool; - public onScreen(Camera?: Camera): bool; - public getScreenXY(point?: MicroPoint, Camera?: Camera): MicroPoint; - public solid : bool; - public getMidpoint(point?: MicroPoint): MicroPoint; - public reset(X: number, Y: number): void; - public isTouching(Direction: number): bool; - public justTouched(Direction: number): bool; - public hurt(Damage: number): void; - public setBounds(x: number, y: number, width: number, height: number): void; - public hideFromCamera(camera: Camera): void; - public showToCamera(camera: Camera): void; - public clearCameraList(): void; - public destroy(): void; - public x : number; - public y : number; - public rotation : number; - public angle : number; - public width : number; - public height : number; - } -} diff --git a/Phaser/gameobjects/GameObject.ts b/Phaser/gameobjects/GameObject.ts deleted file mode 100644 index b4a945bd..00000000 --- a/Phaser/gameobjects/GameObject.ts +++ /dev/null @@ -1,897 +0,0 @@ -/// -/// -/// -/// - -/** -* 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 { - - export 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 = 0, y?: number = 0, width?: number = 16, height?: number = 16) { - - super(game); - - this.canvas = game.stage.canvas; - this.context = game.stage.context; - - this.frameBounds = new 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 MicroPoint(1, 1); - - this.last = new 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 = Collision.NONE; - this.wasTouching = Collision.NONE; - this.allowCollisions = Collision.ANY; - - this.velocity = new MicroPoint(); - this.acceleration = new MicroPoint(); - this.drag = new MicroPoint(); - this.maxVelocity = new MicroPoint(10000, 10000); - - this.angle = 0; - this.angularVelocity = 0; - this.angularAcceleration = 0; - this.angularDrag = 0; - this.maxAngular = 10000; - - this.cameraBlacklist = []; - this.scrollFactor = new MicroPoint(1, 1); - this.collisionMask = new CollisionMask(game, this, x, y, width, height); - - } - - /** - * Angle of this object. - * @type {number} - */ - private _angle: number = 0; - - /** - * Pivot position enum: at the top-left corner. - * @type {number} - */ - public static ALIGN_TOP_LEFT: number = 0; - - /** - * Pivot position enum: at the top-center corner. - * @type {number} - */ - public static ALIGN_TOP_CENTER: number = 1; - - /** - * Pivot position enum: at the top-right corner. - * @type {number} - */ - public static ALIGN_TOP_RIGHT: number = 2; - - /** - * Pivot position enum: at the center-left corner. - * @type {number} - */ - public static ALIGN_CENTER_LEFT: number = 3; - - /** - * Pivot position enum: at the center corner. - * @type {number} - */ - public static ALIGN_CENTER: number = 4; - - /** - * Pivot position enum: at the center-right corner. - * @type {number} - */ - public static ALIGN_CENTER_RIGHT: number = 5; - - /** - * Pivot position enum: at the bottom-left corner. - * @type {number} - */ - public static ALIGN_BOTTOM_LEFT: number = 6; - - /** - * Pivot position enum: at the bottom-center corner. - * @type {number} - */ - public static ALIGN_BOTTOM_CENTER: number = 7; - - /** - * Pivot position enum: at the bottom-right corner. - * @type {number} - */ - public static ALIGN_BOTTOM_RIGHT: number = 8; - - /** - * Enum value for outOfBoundsAction. Stop the object when is out of world bounds. - * @type {number} - */ - public static OUT_OF_BOUNDS_STOP: number = 0; - - /** - * Enum value for outOfBoundsAction. Kill the object when is out of world bounds. - * @type {number} - */ - public static OUT_OF_BOUNDS_KILL: number = 1; - - /** - * 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 = 0; - - /** - * 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 = 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} - */ - public rotationOffset: number = 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} - */ - public renderRotation: bool = true; - - // Physics properties - - /** - * 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 = true; - - /** - * 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; - - // Input - public inputEnabled: bool = false; - private _inputOver: bool = false; - - public onInputOver: Phaser.Signal; - public onInputOut: Phaser.Signal; - public onInputDown: Phaser.Signal; - public onInputUp: Phaser.Signal; - - /** - * 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() { - - 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; - - } - - /** - * Update input. - */ - private updateInput() { - } - - /** - * Internal function for updating the position and speed of this object. - */ - private updateMotion() { - - var delta: number; - var velocityDelta: number; - - 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; - - } - - /** - * 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 = 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. - */ - public 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. - */ - public 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. - */ - public 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. - */ - public 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; - - } - - /** - * 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 get solid(): bool { - return (this.allowCollisions & Collision.ANY) > Collision.NONE; - } - - public set solid(value: bool) { - - if (value) - { - this.allowCollisions = Collision.ANY; - } - else - { - this.allowCollisions = Collision.NONE; - } - - } - - /** - * 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 = null): MicroPoint { - - if (point == null) - { - point = new MicroPoint(); - } - - point.copyFrom(this.frameBounds.center); - - return point; - - } - - /** - * 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) { - - 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; - - } - - /** - * 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 { - return (this.touching & direction) > Collision.NONE; - } - - /** - * 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 { - return ((this.touching & direction) > Collision.NONE) && ((this.wasTouching & direction) <= Collision.NONE); - } - - /** - * 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) { - - this.health = this.health - damage; - - if (this.health <= 0) - { - this.kill(); - } - - } - - /** - * 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) { - - this.worldBounds = new Quad(x, y, width, height); - - } - - /** - * 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 = 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; - - } - - /** - * 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) { - - if (this.cameraBlacklist.indexOf(camera.ID) == -1) - { - this.cameraBlacklist.push(camera.ID); - } - - } - - - /** - * Make this object only visible to a specific camera. - * - * @param camera {Camera} The camera you wish it to be visible. - */ - public showToCamera(camera: Camera) { - - if (this.cameraBlacklist.indexOf(camera.ID) !== -1) - { - this.cameraBlacklist.slice(this.cameraBlacklist.indexOf(camera.ID), 1); - } - - } - - /** - * This clears the camera black list, making the GameObject visible to all cameras. - */ - public clearCameraList() { - - this.cameraBlacklist.length = 0; - - } - - /** - * Clean up memory. - */ - public destroy() { - } - - public setPosition(x: number, y: number) { - - this.x = x; - this.y = y; - - } - - public get x(): number { - return this.frameBounds.x; - } - - public set x(value: number) { - this.frameBounds.x = value; - } - - public get y(): number { - return this.frameBounds.y; - } - - public set y(value: number) { - this.frameBounds.y = value; - } - - 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); - } - - public set width(value:number) { - this.frameBounds.width = value; - } - - public set height(value:number) { - this.frameBounds.height = value; - } - - public get width(): number { - return this.frameBounds.width; - } - - public get height(): number { - return this.frameBounds.height; - } - - } - -} \ No newline at end of file diff --git a/Phaser/GameObjectFactory.ts b/Phaser/gameobjects/GameObjectFactory.ts similarity index 80% rename from Phaser/GameObjectFactory.ts rename to Phaser/gameobjects/GameObjectFactory.ts index 8be5beed..3c9ffefe 100644 --- a/Phaser/GameObjectFactory.ts +++ b/Phaser/gameobjects/GameObjectFactory.ts @@ -1,4 +1,5 @@ -/// +/// +/// /** * Phaser - GameObjectFactory @@ -41,7 +42,7 @@ module Phaser { * @returns {Camera} The newly created camera object. */ public camera(x: number, y: number, width: number, height: number): Camera { - return this._world.createCamera(x, y, width, height); + return this._world.cameras.addCamera(x, y, width, height); } /** @@ -51,9 +52,9 @@ module Phaser { * @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 { - return this._world.createGeomSprite(x, y); - } + //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. @@ -64,7 +65,7 @@ module Phaser { * @returns {Sprite} The newly created sprite object. */ public sprite(x: number, y: number, key?: string = ''): Sprite { - return this._world.createSprite(x, y, key); + return this._world.group.add(new Sprite(this._game, x, y, key)); } /** @@ -75,7 +76,7 @@ module Phaser { * @returns {DynamicTexture} The newly created dynamic texture object. */ public dynamicTexture(width: number, height: number): DynamicTexture { - return this._world.createDynamicTexture(width, height); + return new DynamicTexture(this._game, width, height); } /** @@ -85,7 +86,7 @@ module Phaser { * @returns {Group} The newly created group. */ public group(maxSize?: number = 0): Group { - return this._world.createGroup(maxSize); + return this._world.group.add(new Group(this._game, maxSize)); } /** @@ -93,9 +94,9 @@ module Phaser { * * @return {Particle} The newly created particle object. */ - public particle(): Particle { - return this._world.createParticle(); - } + //public particle(): Particle { + // return new Particle(this._game); + //} /** * Create a new Emitter. @@ -105,9 +106,9 @@ module Phaser { * @param size {number} Optional, size of this emitter. * @return {Emitter} The newly created emitter object. */ - public emitter(x?: number = 0, y?: number = 0, size?: number = 0): Emitter { - return this._world.createEmitter(x, y, size); - } + //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. @@ -119,9 +120,9 @@ module Phaser { * @param height {number} Height of this object. * @returns {ScrollZone} The newly created scroll zone object. */ - public scrollZone(key: string, x?: number = 0, y?: number = 0, width?: number = 0, height?: number = 0): ScrollZone { - return this._world.createScrollZone(key, x, y, width, height); - } + //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. @@ -135,7 +136,7 @@ module Phaser { * @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.createTilemap(key, mapData, format, resizeWorld, tileWidth, tileHeight); + return this._world.group.add(new Tilemap(this._game, key, mapData, format, resizeWorld, tileWidth, tileHeight)); } /** @@ -166,9 +167,9 @@ module Phaser { * @param sprite The GeomSprite to add to the Game World * @return {Phaser.GeomSprite} The GeomSprite object */ - public existingGeomSprite(sprite: GeomSprite): GeomSprite { - return this._world.group.add(sprite); - } + //public existingGeomSprite(sprite: GeomSprite): GeomSprite { + // return this._world.group.add(sprite); + //} /** * Add an existing Emitter to the current world. @@ -177,9 +178,9 @@ module Phaser { * @param emitter The Emitter to add to the Game World * @return {Phaser.Emitter} The Emitter object */ - public existingEmitter(emitter: Emitter): Emitter { - return this._world.group.add(emitter); - } + //public existingEmitter(emitter: Emitter): Emitter { + // return this._world.group.add(emitter); + //} /** * Add an existing ScrollZone to the current world. @@ -188,9 +189,9 @@ module Phaser { * @param scrollZone The ScrollZone to add to the Game World * @return {Phaser.ScrollZone} The ScrollZone object */ - public existingScrollZone(scrollZone: ScrollZone): ScrollZone { - return this._world.group.add(scrollZone); - } + //public existingScrollZone(scrollZone: ScrollZone): ScrollZone { + // return this._world.group.add(scrollZone); + //} /** * Add an existing Tilemap to the current world. diff --git a/Phaser/gameobjects/GeomSprite.d.ts b/Phaser/gameobjects/GeomSprite.d.ts deleted file mode 100644 index bc84c8cc..00000000 --- a/Phaser/gameobjects/GeomSprite.d.ts +++ /dev/null @@ -1,40 +0,0 @@ -/// -module Phaser { - class GeomSprite extends GameObject { - constructor(game: Game, x?: number, y?: number); - private _dx; - private _dy; - private _dw; - private _dh; - public type: number; - static UNASSIGNED: number; - static CIRCLE: number; - static LINE: number; - static POINT: number; - static RECTANGLE: number; - public circle: Circle; - public line: Line; - public point: Point; - public rect: Rectangle; - public renderOutline: bool; - public renderFill: bool; - public lineWidth: number; - public lineColor: string; - public fillColor: string; - public loadCircle(circle: Circle): GeomSprite; - public loadLine(line: Line): GeomSprite; - public loadPoint(point: Point): GeomSprite; - public loadRectangle(rect: Rectangle): GeomSprite; - public createCircle(diameter: number): GeomSprite; - public createLine(x: number, y: number): GeomSprite; - public createPoint(): GeomSprite; - public createRectangle(width: number, height: number): GeomSprite; - public refresh(): void; - public update(): void; - public inCamera(camera: Rectangle): bool; - public render(camera: Camera, cameraOffsetX: number, cameraOffsetY: number): bool; - public renderPoint(offsetX, offsetY, point, size): void; - public renderDebugInfo(x: number, y: number, color?: string): void; - public collide(source: GeomSprite): bool; - } -} diff --git a/Phaser/gameobjects/GeomSprite.ts b/Phaser/gameobjects/GeomSprite.ts index 053c3dd6..81ac326e 100644 --- a/Phaser/gameobjects/GeomSprite.ts +++ b/Phaser/gameobjects/GeomSprite.ts @@ -1,5 +1,6 @@ /// /// +/// /** * Phaser - GeomSprite @@ -11,7 +12,7 @@ module Phaser { - export class GeomSprite extends GameObject { + export class GeomSprite extends Sprite { /** * GeomSprite constructor @@ -262,11 +263,11 @@ module Phaser { * @param height {Number} Height of the rectangle * @return {GeomSprite} GeomSprite instance. */ - createPolygon(points?: Vector2[] = []): GeomSprite { + createPolygon(points?: Vec2[] = []): GeomSprite { - this.refresh(); - this.polygon = new Polygon(new Vector2(this.x, this.y), points); - this.type = GeomSprite.POLYGON; + //this.refresh(); + //this.polygon = new Polygon(new Vec2(this.x, this.y), points); + //this.type = GeomSprite.POLYGON; //this.frameBounds.copyFrom(this.rect); return this; @@ -326,6 +327,7 @@ module Phaser { * @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 { if (this.scrollFactor.x !== 1.0 || this.scrollFactor.y !== 1.0) @@ -343,6 +345,7 @@ module Phaser { } } + */ /** * Render this sprite to specific camera. Called by game loop after update(). @@ -354,10 +357,10 @@ module Phaser { public render(camera: Camera, cameraOffsetX: number, cameraOffsetY: number): bool { // 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) - { - return false; - } + //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) + //{ + // return false; + //} // Alpha if (this.alpha !== 1) diff --git a/Phaser/gameobjects/OldSprite.ts b/Phaser/gameobjects/OldSprite.ts new file mode 100644 index 00000000..1e28f513 --- /dev/null +++ b/Phaser/gameobjects/OldSprite.ts @@ -0,0 +1,355 @@ +/// +/// +/// +/// + +/** +* 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 { + + export class OldSprite { + + /** + * 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. + * @param [width] {number} The width of the object. + * @param [height] {number} The height of the object. + */ + constructor(game: Game, x?: number = 0, y?: number = 0, key?: string = null, width?: number = 16, height?: number = 16) { + + this.canvas = game.stage.canvas; + this.context = game.stage.context; + + this.frameBounds = new 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 MicroPoint(1, 1); + + this.last = new 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 = Collision.NONE; + this.wasTouching = Collision.NONE; + this.allowCollisions = Collision.ANY; + + this.velocity = new MicroPoint(); + this.acceleration = new MicroPoint(); + this.drag = new MicroPoint(); + this.maxVelocity = new MicroPoint(10000, 10000); + + this.angle = 0; + this.angularVelocity = 0; + this.angularAcceleration = 0; + this.angularDrag = 0; + this.maxAngular = 10000; + + this.cameraBlacklist = []; + this.scrollFactor = new MicroPoint(1, 1); + this.collisionMask = new CollisionMask(game, this, x, y, width, height); + + + this._texture = null; + + this.animations = new AnimationManager(this._game, this); + + if (key !== null) + { + this.cacheKey = key; + this.loadGraphic(key); + } + else + { + this.frameBounds.width = 16; + this.frameBounds.height = 16; + } + + } + + /** + * The essential reference to the main game object + */ + public _game: Game; + + /** + * Controls whether update() is automatically called by State/Group. + */ + public active: bool; + + /** + * Controls whether draw() is automatically called by State/Group. + */ + public visible: 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; + + /** + * An Array of Cameras to which this GameObject won't render + * @type {Array} + */ + public cameraBlacklist: 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; + + /** + * 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 = true; + + /** + * 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; + + /** + * 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; + + /** + * 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; + + /** + * Texture of this sprite to be rendered. + */ + private _texture; + + /** + * Texture of this sprite is DynamicTexture? (default to false) + * @type {boolean} + */ + private _dynamicTexture: bool = false; + + + /** + * 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; + + + /** + * Flip the graphic horizontally? (defaults to false) + * @type {boolean} + */ + public flipped: bool = false; + + + + /** + * 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() { + } + + public set width(value:number) { + this.frameBounds.width = value; + } + + public set height(value:number) { + this.frameBounds.height = value; + } + + public get width(): number { + return this.frameBounds.width; + } + + public get height(): number { + return this.frameBounds.height; + } + + public set frame(value: number) { + this.animations.frame = value; + } + + public get frame(): number { + return this.animations.frame; + } + + public set frameName(value: string) { + this.animations.frameName = value; + } + + public get frameName(): string { + return this.animations.frameName; + } + + /** + * 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() { + this.alive = false; + this.exists = false; + } + + /** + * 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() { + this.alive = true; + this.exists = true; + } + + /** + * Convert object to readable string name. Useful for debugging, save games, etc. + */ + public toString(): string { + return ""; + } + + + } + +} \ No newline at end of file diff --git a/Phaser/gameobjects/Particle.d.ts b/Phaser/gameobjects/Particle.d.ts deleted file mode 100644 index 6ba96084..00000000 --- a/Phaser/gameobjects/Particle.d.ts +++ /dev/null @@ -1,11 +0,0 @@ -/// -/// -module Phaser { - class Particle extends Sprite { - constructor(game: Game); - public lifespan: number; - public friction: number; - public update(): void; - public onEmit(): void; - } -} diff --git a/Phaser/gameobjects/ScrollRegion.d.ts b/Phaser/gameobjects/ScrollRegion.d.ts deleted file mode 100644 index 075a5a71..00000000 --- a/Phaser/gameobjects/ScrollRegion.d.ts +++ /dev/null @@ -1,22 +0,0 @@ -/// -/// -module Phaser { - class ScrollRegion { - 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; - public visible: bool; - public scrollSpeed: MicroPoint; - public update(delta: number): void; - public render(context: CanvasRenderingContext2D, texture, dx: number, dy: number, dw: number, dh: number): void; - private crop(context, texture, srcX, srcY, srcW, srcH, destX, destY, destW, destH, offsetX, offsetY); - } -} diff --git a/Phaser/gameobjects/ScrollZone.d.ts b/Phaser/gameobjects/ScrollZone.d.ts deleted file mode 100644 index 745abdb4..00000000 --- a/Phaser/gameobjects/ScrollZone.d.ts +++ /dev/null @@ -1,23 +0,0 @@ -/// -/// -/// -module Phaser { - class ScrollZone extends GameObject { - constructor(game: Game, key: string, x?: number, y?: number, width?: number, height?: number); - private _texture; - private _dynamicTexture; - private _dx; - private _dy; - private _dw; - private _dh; - public currentRegion: ScrollRegion; - public regions: ScrollRegion[]; - public flipped: bool; - public addRegion(x: number, y: number, width: number, height: number, speedX?: number, speedY?: number): ScrollRegion; - public setSpeed(x: number, y: number): ScrollZone; - public update(): void; - public inCamera(camera: Rectangle): bool; - public render(camera: Camera, cameraOffsetX: number, cameraOffsetY: number): bool; - private createRepeatingTexture(regionWidth, regionHeight); - } -} diff --git a/Phaser/gameobjects/ScrollZone.ts b/Phaser/gameobjects/ScrollZone.ts index 67ea911e..8252e871 100644 --- a/Phaser/gameobjects/ScrollZone.ts +++ b/Phaser/gameobjects/ScrollZone.ts @@ -1,6 +1,6 @@ /// -/// -/// +/// +/// /** * Phaser - ScrollZone @@ -13,7 +13,7 @@ module Phaser { - export class ScrollZone extends GameObject { + export class ScrollZone extends Sprite { /** * ScrollZone constructor diff --git a/Phaser/gameobjects/Sprite.d.ts b/Phaser/gameobjects/Sprite.d.ts deleted file mode 100644 index 8e68f1a0..00000000 --- a/Phaser/gameobjects/Sprite.d.ts +++ /dev/null @@ -1,34 +0,0 @@ -/// -/// -/// -/// -module Phaser { - class Sprite extends GameObject { - constructor(game: Game, x?: number, y?: number, key?: string); - private _texture; - private _dynamicTexture; - private _sx; - private _sy; - private _sw; - private _sh; - private _dx; - private _dy; - private _dw; - private _dh; - public animations: AnimationManager; - public renderDebug: bool; - public renderDebugColor: string; - public renderDebugPointColor: string; - public flipped: bool; - public loadGraphic(key: string): Sprite; - public loadDynamicTexture(texture: DynamicTexture): Sprite; - public makeGraphic(width: number, height: number, color?: number): Sprite; - public inCamera(camera: Rectangle): bool; - public postUpdate(): void; - public frame : number; - public frameName : string; - public render(camera: Camera, cameraOffsetX: number, cameraOffsetY: number): bool; - private renderBounds(camera, cameraOffsetX, cameraOffsetY); - public renderDebugInfo(x: number, y: number, color?: string): void; - } -} diff --git a/Phaser/gameobjects/Sprite.ts b/Phaser/gameobjects/Sprite.ts index e58917cf..c7806818 100644 --- a/Phaser/gameobjects/Sprite.ts +++ b/Phaser/gameobjects/Sprite.ts @@ -1,456 +1,133 @@ /// -/// -/// -/// +/// +/// +/// +/// /** * 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 { - export class Sprite extends GameObject { + export class Sprite { /** - * 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. + * @param [width] {number} The width of the object. + * @param [height] {number} The height of the object. */ - constructor(game: Game, x?: number = 0, y?: number = 0, key?: string = null) { + constructor(game: Game, x?: number = 0, y?: number = 0, key?: string = null, width?: number = 16, height?: number = 16) { - super(game, x, y); + this.game = game; + this.type = Phaser.Types.SPRITE; + this.render = game.renderer.renderSprite; - this._texture = null; + this.exists = true; + this.active = true; + this.visible = true; + this.alive = true; - this.animations = new AnimationManager(this._game, this); + this.scrollFactor = new Phaser.Vec2(1, 1); + this.scale = new Phaser.Vec2(1, 1); - if (key !== null) - { - this.cacheKey = key; - this.loadGraphic(key); - } - else - { - this.frameBounds.width = 16; - this.frameBounds.height = 16; - } + this.position = new Phaser.Components.Position(this, x, y); + this.texture = new Phaser.Components.Texture(this, key, game.stage.canvas, game.stage.context); } /** - * Texture of this sprite to be rendered. + * Reference to the main game object */ - private _texture; + public game: Game; /** - * Texture of this sprite is DynamicTexture? (default to false) - * @type {boolean} + * The type of game object. */ - private _dynamicTexture: bool = false; - - // local rendering related temp vars to help avoid gc spikes - private _sx: number = 0; - private _sy: number = 0; - private _sw: number = 0; - private _sh: number = 0; - private _dx: number = 0; - private _dy: number = 0; - private _dw: number = 0; - private _dh: number = 0; + public type: number; /** - * This manages animations of the sprite. You can modify animations though it. (see AnimationManager) - * @type AnimationManager + * Reference to the Renderer.renderSprite method. Can be overriden by custom classes. */ - public animations: AnimationManager; + public render; /** - * The cache key that was used for this texture (if any) + * Controls if both update and render are called by the core game loop. */ - public cacheKey: string; + public exists: bool; /** - * Render bound of this sprite for debugging? (default to false) - * @type {boolean} + * Controls if update() is automatically called by the core game loop. */ - public renderDebug: bool = false; + public active: bool; /** - * Color of the Sprite when no image is present. Format is a css color string. - * @type {string} + * Controls if this Sprite is rendered or skipped during the core game loop. */ - public fillColor: string = 'rgb(255,255,255)'; + public visible: bool; /** - * Color of bound when render debug. (see renderDebug) Format is a css color string. - * @type {string} + * */ - public renderDebugColor: string = 'rgba(0,255,0,0.5)'; + public alive: bool; /** - * Color of points when render debug. (see renderDebug) Format is a css color string. - * @type {string} + * The position of the Sprite in world and screen coordinates. */ - public renderDebugPointColor: string = 'rgba(255,255,255,1)'; + public position: Phaser.Components.Position; /** - * Flip the graphic horizontally? (defaults to false) - * @type {boolean} + * The texture used to render the Sprite. */ - public flipped: bool = false; + public texture: Phaser.Components.Texture; /** - * 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. + * 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 loadGraphic(key: string, clearAnimations: bool = true): Sprite { + public frameBounds: Phaser.Rectangle; - if (clearAnimations && this.animations.frameData !== null) - { - this.animations.destroy(); - } + public scale: Phaser.Vec2; + public scrollFactor: Phaser.Vec2; - 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; + /** + * x value of the object. + */ + public get x(): number { + return this.position.world.x; + } + public set x(value: number) { + this.position.world.x = value; } /** - * Load a DynamicTexture as its texture. - * @param texture {DynamicTexture} The texture object to be used by this sprite. - * @return {Sprite} Sprite instance itself. + * y value of the object. */ - public loadDynamicTexture(texture: DynamicTexture): Sprite { - - this._texture = texture; - - this.frameBounds.width = this._texture.width; - this.frameBounds.height = this._texture.height; - - this._dynamicTexture = true; - - return this; + public get y(): number { + return this.position.world.y; + } + public set y(value: number) { + this.position.world.y = value; } /** - * 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. + * z value of the object. */ - public 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; + public get z(): number { + return this.position.z; } - /** - * 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 { - - // 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); - - } - - /** - * Automatically called after update() by the game loop, this function just updates animations. - */ - public postUpdate() { - - this.animations.update(); - - super.postUpdate(); - - } - - public set frame(value: number) { - this.animations.frame = value; - } - - public get frame(): number { - return this.animations.frame; - } - - public set frameName(value: string) { - this.animations.frameName = value; - } - - public get frameName(): string { - return this.animations.frameName; - } - - /** - * 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 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 == GameObject.ALIGN_TOP_CENTER) - { - this._dx -= this.frameBounds.halfWidth * this.scale.x; - } - else if (this.align == GameObject.ALIGN_TOP_RIGHT) - { - this._dx -= this.frameBounds.width * this.scale.x; - } - else if (this.align == GameObject.ALIGN_CENTER_LEFT) - { - this._dy -= this.frameBounds.halfHeight * this.scale.y; - } - else if (this.align == GameObject.ALIGN_CENTER) - { - this._dx -= this.frameBounds.halfWidth * this.scale.x; - this._dy -= this.frameBounds.halfHeight * this.scale.y; - } - else if (this.align == GameObject.ALIGN_CENTER_RIGHT) - { - this._dx -= this.frameBounds.width * this.scale.x; - this._dy -= this.frameBounds.halfHeight * this.scale.y; - } - else if (this.align == GameObject.ALIGN_BOTTOM_LEFT) - { - this._dy -= this.frameBounds.height * this.scale.y; - } - else if (this.align == GameObject.ALIGN_BOTTOM_CENTER) - { - this._dx -= this.frameBounds.halfWidth * this.scale.x; - this._dy -= this.frameBounds.height * this.scale.y; - } - else if (this.align == 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; - - } - - /** - * 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:Camera, cameraOffsetX:number, cameraOffsetY:number) { - - 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 - - } - - /** - * 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 = '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); - + public set z(value: number) { + this.position.z = value; } } diff --git a/Phaser/gameobjects/Tilemap.d.ts b/Phaser/gameobjects/Tilemap.d.ts deleted file mode 100644 index 23941256..00000000 --- a/Phaser/gameobjects/Tilemap.d.ts +++ /dev/null @@ -1,31 +0,0 @@ -/// -/// -/// -/// -module Phaser { - class Tilemap extends GameObject { - constructor(game: Game, key: string, mapData: string, format: number, resizeWorld?: bool, tileWidth?: number, tileHeight?: number); - static FORMAT_CSV: number; - static FORMAT_TILED_JSON: number; - public tiles: Tile[]; - public layers: TilemapLayer[]; - public currentLayer: TilemapLayer; - public collisionLayer: TilemapLayer; - public mapFormat: number; - public update(): void; - public render(camera: Camera, cameraOffsetX: number, cameraOffsetY: number): void; - private parseCSV(data, key, tileWidth, tileHeight); - private parseTiledJSON(data, key); - private generateTiles(qty); - public widthInPixels : number; - public heightInPixels : number; - public setCollisionRange(start: number, end: number, collision?: number, resetCollisions?: bool): void; - public setCollisionByIndex(values: number[], collision?: number, resetCollisions?: bool): void; - public getTile(x: number, y: number, layer?: number): Tile; - public getTileFromWorldXY(x: number, y: number, layer?: number): Tile; - public getTileFromInputXY(layer?: number): Tile; - public getTileOverlaps(object: GameObject): bool; - public collide(objectOrGroup?, callback?): bool; - public collideGameObject(object: GameObject): bool; - } -} diff --git a/Phaser/gameobjects/Tilemap.ts b/Phaser/gameobjects/Tilemap.ts index a04f0419..746d7df5 100644 --- a/Phaser/gameobjects/Tilemap.ts +++ b/Phaser/gameobjects/Tilemap.ts @@ -1,7 +1,6 @@ /// -/// -/// -/// +/// +/// /** * Phaser - Tilemap @@ -12,7 +11,7 @@ module Phaser { - export class Tilemap extends GameObject { + export class Tilemap { /** * Tilemap constructor @@ -28,7 +27,7 @@ module Phaser { */ constructor(game: Game, key: string, mapData: string, format: number, resizeWorld: bool = true, tileWidth?: number = 0, tileHeight?: number = 0) { - super(game); + //super(game); this.isGroup = false; diff --git a/Phaser/geom/Circle.d.ts b/Phaser/geom/Circle.d.ts deleted file mode 100644 index de0e9237..00000000 --- a/Phaser/geom/Circle.d.ts +++ /dev/null @@ -1,34 +0,0 @@ -/// -module Phaser { - class Circle { - constructor(x?: number, y?: number, diameter?: number); - private _diameter; - private _radius; - public x: number; - public y: number; - public diameter : number; - public radius : number; - public circumference(): number; - public bottom : number; - public left : number; - public right : number; - public top : number; - public area : number; - public isEmpty : bool; - public intersectCircleLine(line: Line): bool; - public clone(output?: Circle): Circle; - public contains(x: number, y: number): bool; - public containsPoint(point: Point): bool; - public containsCircle(circle: Circle): bool; - public copyFrom(source: Circle): Circle; - public copyTo(target: Circle): Circle; - public distanceTo(target: any, round?: bool): number; - public equals(toCompare: Circle): bool; - public intersects(toIntersect: Circle): bool; - public circumferencePoint(angle: number, asDegrees?: bool, output?: Point): Point; - public offset(dx: number, dy: number): Circle; - public offsetPoint(point: Point): Circle; - public setTo(x: number, y: number, diameter: number): Circle; - public toString(): string; - } -} diff --git a/Phaser/geom/IntersectResult.d.ts b/Phaser/geom/IntersectResult.d.ts deleted file mode 100644 index 0557082b..00000000 --- a/Phaser/geom/IntersectResult.d.ts +++ /dev/null @@ -1,15 +0,0 @@ -/// -module Phaser { - class IntersectResult { - public result: bool; - public x: number; - public y: number; - public x1: number; - public y1: number; - public x2: number; - public y2: number; - public width: number; - public height: number; - public setTo(x1: number, y1: number, x2?: number, y2?: number, width?: number, height?: number): void; - } -} diff --git a/Phaser/geom/Line.d.ts b/Phaser/geom/Line.d.ts deleted file mode 100644 index b8b0fbd6..00000000 --- a/Phaser/geom/Line.d.ts +++ /dev/null @@ -1,27 +0,0 @@ -/// -module Phaser { - class Line { - constructor(x1?: number, y1?: number, x2?: number, y2?: number); - public x1: number; - public y1: number; - public x2: number; - public y2: number; - public clone(output?: Line): Line; - public copyFrom(source: Line): Line; - public copyTo(target: Line): Line; - public setTo(x1?: number, y1?: number, x2?: number, y2?: number): Line; - public width : number; - public height : number; - public length : number; - public getY(x: number): number; - public angle : number; - public slope : number; - public perpSlope : number; - public yIntercept : number; - public isPointOnLine(x: number, y: number): bool; - public isPointOnLineSegment(x: number, y: number): bool; - public intersectLineLine(line): any; - public perp(x: number, y: number, output?: Line): Line; - public toString(): string; - } -} diff --git a/Phaser/geom/MicroPoint.d.ts b/Phaser/geom/MicroPoint.d.ts deleted file mode 100644 index 48e9145f..00000000 --- a/Phaser/geom/MicroPoint.d.ts +++ /dev/null @@ -1,16 +0,0 @@ -/// -module Phaser { - class MicroPoint { - constructor(x?: number, y?: number, parent?: any); - private _x; - private _y; - public parent: any; - public x : number; - public y : number; - public copyFrom(source: any): MicroPoint; - public copyTo(target: any): MicroPoint; - public setTo(x: number, y: number, callParent?: bool): MicroPoint; - public equals(toCompare): bool; - public toString(): string; - } -} diff --git a/Phaser/geom/Point.d.ts b/Phaser/geom/Point.d.ts deleted file mode 100644 index f93c2002..00000000 --- a/Phaser/geom/Point.d.ts +++ /dev/null @@ -1,28 +0,0 @@ -/// -module Phaser { - class Point { - constructor(x?: number, y?: number); - public x: number; - public y: number; - public add(toAdd: Point, output?: Point): Point; - public addTo(x?: number, y?: number): Point; - public subtractFrom(x?: number, y?: number): Point; - public invert(): Point; - public clamp(min: number, max: number): Point; - public clampX(min: number, max: number): Point; - public clampY(min: number, max: number): Point; - public clone(output?: Point): Point; - public copyFrom(source: Point): Point; - public copyTo(target: Point): Point; - public distanceTo(target: Point, round?: bool): number; - static distanceBetween(pointA: Point, pointB: Point, round?: bool): number; - public distanceCompare(target: Point, distance: number): bool; - public equals(toCompare: Point): bool; - public interpolate(pointA, pointB, f): void; - public offset(dx: number, dy: number): Point; - public polar(length, angle): void; - public setTo(x: number, y: number): Point; - public subtract(point: Point, output?: Point): Point; - public toString(): string; - } -} diff --git a/Phaser/geom/Polygon.ts b/Phaser/geom/Polygon.ts index cef1b05c..b262fc7d 100644 --- a/Phaser/geom/Polygon.ts +++ b/Phaser/geom/Polygon.ts @@ -13,10 +13,10 @@ module Phaser { * 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. + * @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?: Vector2 = new Vector2, points?: Vector2[] = [], parent?:any = null) { + constructor(pos?: Vec2 = new Vec2, points?: Vec2[] = [], parent?:any = null) { this.pos = pos; this.points = points; @@ -26,10 +26,10 @@ module Phaser { } public parent: any; - public pos: Vector2; - public points: Vector2[]; - public edges: Vector2[]; - public normals: Vector2[]; + public pos: Vec2; + public points: Vec2[]; + public edges: Vec2[]; + public normals: Vec2[]; /** * Recalculate the edges and normals of the polygon. This @@ -48,8 +48,8 @@ module Phaser { { var p1 = points[i]; var p2 = i < len - 1 ? points[i + 1] : points[0]; - var e = new Vector2().copyFrom(p2).sub(p1); - var n = new Vector2().copyFrom(e).perp().normalize(); + var e = new Vec2().copyFrom(p2).sub(p1); + var n = new Vec2().copyFrom(e).perp().normalize(); this.edges.push(e); this.normals.push(n); } diff --git a/Phaser/geom/Quad.d.ts b/Phaser/geom/Quad.d.ts deleted file mode 100644 index 3a8425f5..00000000 --- a/Phaser/geom/Quad.d.ts +++ /dev/null @@ -1,19 +0,0 @@ -/// -module Phaser { - class Quad { - constructor(x?: number, y?: number, width?: number, height?: number); - public x: number; - public y: number; - public width: number; - public height: number; - 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; - public intersects(q, t?: number): bool; - public toString(): string; - } -} diff --git a/Phaser/geom/Rectangle.d.ts b/Phaser/geom/Rectangle.d.ts deleted file mode 100644 index e09befbd..00000000 --- a/Phaser/geom/Rectangle.d.ts +++ /dev/null @@ -1,57 +0,0 @@ -/// -/// -module Phaser { - class Rectangle { - constructor(x?: number, y?: number, width?: number, height?: number); - private _tempX; - private _tempY; - private _tempWidth; - private _tempHeight; - public x : number; - public y : number; - public topLeft: MicroPoint; - public topCenter: MicroPoint; - public topRight: MicroPoint; - public leftCenter: MicroPoint; - public center: MicroPoint; - public rightCenter: MicroPoint; - public bottomLeft: MicroPoint; - public bottomCenter: MicroPoint; - public bottomRight: MicroPoint; - private _width; - private _height; - private _halfWidth; - private _halfHeight; - public length: number; - public updateBounds(): void; - public width : number; - public height : number; - public halfWidth : number; - public halfHeight : number; - public bottom : number; - public left : number; - public right : number; - public size(output?: Point): Point; - public volume : number; - public perimeter : number; - public top : number; - public clone(output?: Rectangle): Rectangle; - public contains(x: number, y: number): bool; - public containsPoint(point: any): bool; - public containsRect(rect: Rectangle): bool; - public copyFrom(source: Rectangle): Rectangle; - public copyTo(target: Rectangle): Rectangle; - public equals(toCompare: Rectangle): bool; - public inflate(dx: number, dy: number): Rectangle; - public inflatePoint(point: Point): Rectangle; - public intersection(toIntersect: Rectangle, output?: Rectangle): Rectangle; - public intersects(r2: Rectangle, t?: number): bool; - public isEmpty : bool; - public offset(dx: number, dy: number): Rectangle; - public offsetPoint(point: Point): Rectangle; - public setEmpty(): Rectangle; - public setTo(x: number, y: number, width: number, height: number): Rectangle; - public union(toUnion: Rectangle, output?: Rectangle): Rectangle; - public toString(): string; - } -} diff --git a/Phaser/geom/Response.ts b/Phaser/geom/Response.ts index 563f25cb..fa5fc323 100644 --- a/Phaser/geom/Response.ts +++ b/Phaser/geom/Response.ts @@ -23,8 +23,8 @@ module Phaser { this.a = null; this.b = null; - this.overlapN = new Vector2; - this.overlapV = new Vector2; + this.overlapN = new Vec2; + this.overlapV = new Vec2; this.clear(); @@ -43,13 +43,13 @@ module Phaser { /** * The shortest colliding axis (unit-vector) */ - public overlapN: Vector2; + 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: Vector2; + public overlapV: Vec2; /** * Whether the first object is completely inside the second. diff --git a/Phaser/input/Gestures.ts b/Phaser/input/Gestures.ts index f572112b..7a18a6a2 100644 --- a/Phaser/input/Gestures.ts +++ b/Phaser/input/Gestures.ts @@ -1,4 +1,4 @@ -/// +/// /// /** diff --git a/Phaser/input/Input.ts b/Phaser/input/Input.ts index 3449a437..f8087e0d 100644 --- a/Phaser/input/Input.ts +++ b/Phaser/input/Input.ts @@ -1,8 +1,10 @@ -/// -/// +/// +/// /// /// /// +/// +/// /** * Phaser - Input @@ -37,7 +39,7 @@ module Phaser { this.onTap = new Phaser.Signal(); this.onHold = new Phaser.Signal(); - this.position = new Vector2; + this.position = new Vec2; this.circle = new Circle(0, 0, 44); this.currentPointers = 0; @@ -112,9 +114,9 @@ module Phaser { /** * A vector object representing the current position of the Pointer. * @property vector - * @type {Vector2} + * @type {Vec2} **/ - public position: Vector2 = null; + public position: Vec2 = null; /** * A Circle object centered on the x/y screen coordinates of the Input. @@ -855,7 +857,7 @@ module Phaser { * @param {Pointer} pointer2 **/ public getDistance(pointer1: Pointer, pointer2: Pointer): number { - return pointer1.position.distance(pointer2.position); + return Vec2Utils.distance(pointer1.position, pointer2.position); } /** @@ -865,7 +867,7 @@ module Phaser { * @param {Pointer} pointer2 **/ public getAngle(pointer1: Pointer, pointer2: Pointer): number { - return pointer1.position.angle(pointer2.position); + return Vec2Utils.angle(pointer1.position, pointer2.position); } } diff --git a/Phaser/input/Keyboard.ts b/Phaser/input/Keyboard.ts index f2a87657..8709925d 100644 --- a/Phaser/input/Keyboard.ts +++ b/Phaser/input/Keyboard.ts @@ -1,4 +1,4 @@ -/// +/// /** * Phaser - Keyboard diff --git a/Phaser/input/MSPointer.ts b/Phaser/input/MSPointer.ts index a23d76bf..17939aa2 100644 --- a/Phaser/input/MSPointer.ts +++ b/Phaser/input/MSPointer.ts @@ -1,4 +1,4 @@ -/// +/// /// /** diff --git a/Phaser/input/Mouse.ts b/Phaser/input/Mouse.ts index c32a4ee7..6ea05f22 100644 --- a/Phaser/input/Mouse.ts +++ b/Phaser/input/Mouse.ts @@ -1,4 +1,4 @@ -/// +/// /** * Phaser - Mouse diff --git a/Phaser/input/Pointer.ts b/Phaser/input/Pointer.ts index f12bc62e..93e3913a 100644 --- a/Phaser/input/Pointer.ts +++ b/Phaser/input/Pointer.ts @@ -1,5 +1,5 @@ -/// -/// +/// +/// /** * Phaser - Pointer @@ -22,8 +22,8 @@ module Phaser { this.id = id; this.active = false; - this.position = new Vector2; - this.positionDown = new Vector2; + this.position = new Vec2; + this.positionDown = new Vec2; this.circle = new Circle(0, 0, 44); if (id == 0) @@ -91,16 +91,16 @@ 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 = null; + public positionDown: Vec2 = null; /** * A Vector object containing the current position of the Pointer on the screen. * @property position - * @type {Vector2} + * @type {Vec2} **/ - public position: Vector2 = null; + public position: Vec2 = null; /** * A Circle object centered on the x/y screen coordinates of the Pointer. diff --git a/Phaser/input/Touch.ts b/Phaser/input/Touch.ts index 71b74c98..7ddad452 100644 --- a/Phaser/input/Touch.ts +++ b/Phaser/input/Touch.ts @@ -1,4 +1,4 @@ -/// +/// /// /** diff --git a/Phaser/animation/AnimationLoader.ts b/Phaser/loader/AnimationLoader.ts similarity index 99% rename from Phaser/animation/AnimationLoader.ts rename to Phaser/loader/AnimationLoader.ts index 711face3..8860799f 100644 --- a/Phaser/animation/AnimationLoader.ts +++ b/Phaser/loader/AnimationLoader.ts @@ -1,4 +1,4 @@ -/// +/// /** * Phaser - AnimationLoader diff --git a/Phaser/GameMath.ts b/Phaser/math/GameMath.ts similarity index 99% rename from Phaser/GameMath.ts rename to Phaser/math/GameMath.ts index 1264e46f..d41ec49a 100644 --- a/Phaser/GameMath.ts +++ b/Phaser/math/GameMath.ts @@ -1,4 +1,4 @@ -/// +/// /** * Phaser - GameMath diff --git a/Phaser/system/LinkedList.ts b/Phaser/math/LinkedList.ts similarity index 100% rename from Phaser/system/LinkedList.ts rename to Phaser/math/LinkedList.ts diff --git a/Phaser/system/QuadTree.ts b/Phaser/math/QuadTree.ts similarity index 100% rename from Phaser/system/QuadTree.ts rename to Phaser/math/QuadTree.ts diff --git a/Phaser/system/RandomDataGenerator.ts b/Phaser/math/RandomDataGenerator.ts similarity index 100% rename from Phaser/system/RandomDataGenerator.ts rename to Phaser/math/RandomDataGenerator.ts diff --git a/Phaser/math/Vector2.ts b/Phaser/math/Vector2.ts deleted file mode 100644 index e592cde5..00000000 --- a/Phaser/math/Vector2.ts +++ /dev/null @@ -1,457 +0,0 @@ -/// - -/** -* 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.Math { - - export class Vec2 { - - /** - * 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 = 0, y: number = 0) { - - //var GLMAT_ARRAY_TYPE = (typeof Float32Array !== 'undefined') ? Float32Array : Array; - this.x = x; - this.y = y; - - } - - public x: number; - public y: number; - - public setTo(x: number, y: number): Vector2 { - this.x = x; - this.y = y; - return this; - } - - /** - * 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 = new Vector2): Vector2 { - return output.setTo(this.x + v.x, this.y + v.y); - } - - /** - * 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 = new Vector2): Vector2 { - return output.setTo(this.x - v.x, this.y - v.y); - } - - /** - * 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 = new Vector2): Vector2 { - return output.setTo(this.x * v.x, this.y * v.y); - } - - /** - * 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 = new Vector2): Vector2 { - return output.setTo(this.x / v.x, this.y / v.y); - } - - /** - * 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 = null, output?:Vector2 = new Vector2): Vector2 { - - if (y === null) - { - y = x; - } - - return output.setTo(this.x * x, this.y * y); - - } - - /** - * Rotate this vector by 90 degrees - * - * @return {Vector} This for chaining. - */ - public perp(output?: Vector2 = this): Vector2 { - var x = this.x; - return output.setTo(this.y, -x); - } - - // Same as copyFrom, used by VerletManager - public mutableSet(v: Vector2): Vector2 { - this.x = v.x; - this.y = v.y; - return this; - } - - /** - * Add another vector to this one. - * - * @param {Vector} other The other Vector. - * @return {Vector} This for chaining. - */ - public mutableAdd(v: Vector2): Vector2 { - this.x += v.x; - this.y += v.y; - return this; - } - - /** - * Subtract another vector from this one. - * - * @param {Vector} other The other Vector. - * @return {Vector} This for chaining. - */ - public mutableSub(v: Vector2): Vector2 { - this.x -= v.x; - this.y -= v.y; - return this; - } - - /** - * Multiply another vector with this one. - * - * @param {Vector} other The other Vector. - * @return {Vector} This for chaining. - */ - public mutableMul(v: Vector2): Vector2 { - this.x *= v.x; - this.y *= v.y; - return this; - } - - /** - * Divide this vector by another one. - * - * @param {Vector} other The other Vector. - * @return {Vector} This for chaining. - */ - public mutableDiv(v: Vector2): Vector2 { - this.x /= v.x; - this.y /= v.y; - return this; - } - - /** - * 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 { - this.x *= x; - this.y *= y || x; - return this; - } - - /** - * Multiply this vector by the given scalar. - * - * @param {number} scalar - * @return {Vector2} This for chaining. - */ - public mutableMultiplyByScalar(scalar: number): Vector2 { - this.x *= scalar; - this.y *= scalar; - return this; - } - - /** - * Divide this vector by the given scalar. - * - * @param {number} scalar - * @return {Vector2} This for chaining. - */ - public mutableDivideByScalar(scalar: number): Vector2 { - this.x /= scalar; - this.y /= scalar; - return this; - } - - - /** - * Reverse this vector. - * - * @return {Vector} This for chaining. - */ - public reverse(): Vector2 { - this.x = -this.x; - this.y = -this.y; - return this; - } - - public edge(v: Vector2, output?: Vector2 = new Vector2): Vector2 { - return this.sub(v, output); - } - - public equals(v: Vector2): bool { - return this.x == v.x && this.y == v.y; - } - - public epsilonEquals(v: Vector2, epsilon:number): bool { - return Math.abs(this.x - v.x) <= epsilon && Math.abs(this.y - v.y) <= epsilon; - } - - /** - * Get the length of this vector. - * - * @return {number} The length of this vector. - */ - public length(): number { - return Math.sqrt((this.x * this.x) + (this.y * this.y)); - } - - /** - * Get the length^2 of this vector. - * - * @return {number} The length^2 of this vector. - */ - public length2(): number { - return (this.x * this.x) + (this.y * this.y); - } - - /** - * Get the distance between this vector and the given vector. - * - * @return {Vector2} v The vector to check - */ - public distance(v: Vector2): number { - return Math.sqrt(this.distance2(v)); - } - - /** - * Get the distance^2 between this vector and the given vector. - * - * @return {Vector2} v The vector to check - */ - public distance2(v: Vector2): number { - return ((v.x - this.x) * (v.x - this.x)) + ((v.y - this.y) * (v.y - this.y)); - } - - /** - * 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 { - - var amt = this.dot(other) / other.length2(); - - if (amt != 0) - { - this.x = amt * other.x; - this.y = amt * other.y; - } - - return this; - - } - - /** - * 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 { - - var amt = this.dot(other); - - if (amt != 0) - { - this.x = amt * other.x; - this.y = amt * other.y; - } - - return this; - - } - - /** - * Reflect this vector on an arbitrary axis. - * - * @param {Vector} axis The vector representing the axis. - * @return {Vector} This for chaining. - */ - public reflect(axis): Vector2 { - - 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 {Vector} axis The unit vector representing the axis. - * @return {Vector} This for chaining. - */ - public reflectN(axis): Vector2 { - - var x = this.x; - var y = this.y; - this.projectN(axis).scale(2); - this.x -= x; - this.y -= y; - - return this; - - } - - public getProjectionMagnitude(v: Vector2): number { - - var den = v.dot(v); - - if (den == 0) - { - return 0; - } - else - { - return Math.abs(this.dot(v) / den); - } - - } - - public direction(output?: Vector2 = new Vector2): Vector2 { - - output.copyFrom(this); - return this.normalize(output); - - } - - public normalRightHand(output?: Vector2 = this): Vector2 { - return output.setTo(this.y * -1, this.x); - } - - /** - * Normalize (make unit length) this vector. - * - * @return {Vector} This for chaining. - */ - public normalize(output?: Vector2 = this): Vector2 { - - var m = this.length(); - - if (m != 0) - { - output.setTo(this.x / m, this.y / m); - } - - return output; - } - - public getMagnitude(): number { - return Math.sqrt(Math.pow(this.x, 2) + Math.pow(this.y, 2)); - } - - /** - * 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 { - return ((this.x * v.x) + (this.y * v.y)); - } - - /** - * 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 { - return ((this.x * v.y) - (this.y * v.x)); - } - - /** - * Get the angle between this vector and the given vector. - * - * @return {Vector2} v The vector to check - */ - public angle(v: Vector2): number { - return Math.atan2(this.x * v.y - this.y * v.x, this.x * v.x + this.y * v.y); - } - - public angle2(vLeft: Vector2, vRight: Vector2): number { - return vLeft.sub(this).angle(vRight.sub(this)); - } - - /** - * 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 = new Vector2): 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); - } - - public clone(output?: Vector2 = new Vector2): Vector2 { - return output.setTo(this.x, this.y); - } - - public copyFrom(v: Vector2): Vector2 { - this.x = v.x; - this.y = v.y; - return this; - } - - public copyTo(v: Vector2): Vector2 { - return v.setTo(this.x, this.y); - } - - /** - * Returns a string representation of this object. - * @method toString - * @return {string} a string representation of the object. - **/ - public toString(): string { - return "[{Vector2 (x=" + this.x + " y=" + this.y + ")}]"; - } - - } - -} \ No newline at end of file diff --git a/Phaser/phaser.js b/Phaser/phaser.js index b1b78739..ec56656e 100644 --- a/Phaser/phaser.js +++ b/Phaser/phaser.js @@ -1,22 +1,4 @@ var Phaser; (function (Phaser) { - Phaser.VERSION = 'Phaser version 0.9.6'; - Phaser.Point = (typeof Float32Array !== 'undefined') ? Float32Array : Array; - Phaser.Vec2 = (typeof Float32Array !== 'undefined') ? Float32Array : Array; - Phaser.Matrix = (typeof Float32Array !== 'undefined') ? Float32Array : Array; -})(Phaser || (Phaser = {})); -var Phaser; -(function (Phaser) { - (function (Geom2) { - var Point = (function () { - function Point() { } - Point.prototype.add = function (a, b) { - a[0] = b[0]; - return a; - }; - return Point; - })(); - Geom2.Point = Point; - })(Phaser.Geom2 || (Phaser.Geom2 = {})); - var Geom2 = Phaser.Geom2; + Phaser.VERSION = 'Phaser version 1.0.0'; })(Phaser || (Phaser = {})); diff --git a/Phaser/renderers/CanvasRenderer.ts b/Phaser/renderers/CanvasRenderer.ts new file mode 100644 index 00000000..577e7548 --- /dev/null +++ b/Phaser/renderers/CanvasRenderer.ts @@ -0,0 +1,184 @@ +/// +/// +/// +/// +/// + +module Phaser { + + export class CanvasRenderer implements Phaser.IRenderer { + + constructor(game: Game) { + + this._game = game; + + } + + /** + * The essential reference to the main game object + */ + private _game: Game; + + // local rendering related temp vars to help avoid gc spikes with var creation + private _sx: number = 0; + private _sy: number = 0; + private _sw: number = 0; + private _sh: number = 0; + private _dx: number = 0; + private _dy: number = 0; + private _dw: number = 0; + private _dh: number = 0; + + private _cameraList; + private _camera: Camera; + private _groupLength: number; + + public render() { + + // 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(); + } + + } + + /** + * 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 { + + // Render checks (needs inCamera check added) + if (sprite.scale.x == 0 || sprite.scale.y == 0 || sprite.texture.alpha < 0.1) + { + return false; + } + + // Alpha + if (sprite.texture.alpha !== 1) + { + var globalAlpha = sprite.texture.context.globalAlpha; + sprite.texture.context.globalAlpha = sprite.texture.alpha; + } + + this._sx = 0; + this._sy = 0; + this._sw = sprite.frameBounds.width; + this._sh = sprite.frameBounds.height; + + 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; + + /* + 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 (sprite.scrollFactor.x !== 1 || sprite.scrollFactor.y !== 1) + { + //this._dx -= (camera.worldView.x * this.scrollFactor.x); + //this._dy -= (camera.worldView.y * this.scrollFactor.y); + } + + // Rotation and Flipped + 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.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.texture.flippedX) + { + sprite.texture.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) + //{ + 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.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) + { + sprite.texture.context.globalAlpha = globalAlpha; + } + + return true; + + } + + + } + +} \ No newline at end of file diff --git a/Phaser/renderers/HeadlessRenderer.ts b/Phaser/renderers/HeadlessRenderer.ts new file mode 100644 index 00000000..9df50ebc --- /dev/null +++ b/Phaser/renderers/HeadlessRenderer.ts @@ -0,0 +1,36 @@ +/// +/// +/// + +module Phaser { + + export class HeadlessRenderer implements Phaser.IRenderer { + + constructor(game: Game) { + this._game = game; + } + + /** + * The essential reference to the main game object + */ + private _game: Game; + + public render() {} + + public renderSprite(camera: Camera, sprite: Sprite): bool { + + // Render checks (needs inCamera check added) + if (sprite.scale.x == 0 || sprite.scale.y == 0 || sprite.texture.alpha < 0.1) + { + return false; + } + + return true; + + } + + // Add Tilemap, ScrollZone, etc? + + } + +} \ No newline at end of file diff --git a/Phaser/renderers/IRenderer.ts b/Phaser/renderers/IRenderer.ts new file mode 100644 index 00000000..60e5c4ca --- /dev/null +++ b/Phaser/renderers/IRenderer.ts @@ -0,0 +1,16 @@ +/// + +module Phaser { + + export interface IRenderer { + + // properties + _game: Game; + + // methods + render(); + renderSprite(camera: Camera, sprite: Sprite): bool; + + } + +} \ No newline at end of file diff --git a/Phaser/sound/Sound.ts b/Phaser/sound/Sound.ts index 111be181..83670f07 100644 --- a/Phaser/sound/Sound.ts +++ b/Phaser/sound/Sound.ts @@ -1,5 +1,5 @@ /// -/// +/// /** * Phaser - Sound diff --git a/Phaser/sound/SoundManager.ts b/Phaser/sound/SoundManager.ts index db65260d..5b6d9eba 100644 --- a/Phaser/sound/SoundManager.ts +++ b/Phaser/sound/SoundManager.ts @@ -1,5 +1,5 @@ -/// -/// +/// +/// /** * Phaser - SoundManager diff --git a/Phaser/system/Camera.d.ts b/Phaser/system/Camera.d.ts deleted file mode 100644 index 63e7f02b..00000000 --- a/Phaser/system/Camera.d.ts +++ /dev/null @@ -1,80 +0,0 @@ -/// -/// -module Phaser { - class Camera { - constructor(game: Game, id: number, x: number, y: number, width: number, height: number); - private _game; - private _clip; - private _stageX; - private _stageY; - private _rotation; - private _target; - private _sx; - private _sy; - private _fxFlashColor; - private _fxFlashComplete; - private _fxFlashDuration; - private _fxFlashAlpha; - private _fxFadeColor; - private _fxFadeComplete; - private _fxFadeDuration; - private _fxFadeAlpha; - private _fxShakeIntensity; - private _fxShakeDuration; - private _fxShakeComplete; - private _fxShakeOffset; - private _fxShakeDirection; - private _fxShakePrevX; - private _fxShakePrevY; - static STYLE_LOCKON: number; - static STYLE_PLATFORMER: number; - static STYLE_TOPDOWN: number; - static STYLE_TOPDOWN_TIGHT: number; - static SHAKE_BOTH_AXES: number; - static SHAKE_HORIZONTAL_ONLY: number; - static SHAKE_VERTICAL_ONLY: number; - public ID: number; - public worldView: Rectangle; - public totalSpritesRendered: number; - public scale: MicroPoint; - public scroll: MicroPoint; - public bounds: Rectangle; - public deadzone: Rectangle; - public showBorder: bool; - public borderColor: string; - public opaque: bool; - private _bgColor; - private _bgTexture; - private _bgTextureRepeat; - public showShadow: bool; - public shadowColor: string; - public shadowBlur: number; - public shadowOffset: MicroPoint; - public visible: bool; - public alpha: number; - public inputX: number; - public inputY: number; - public fx: FXManager; - public flash(color?: number, duration?: number, onComplete?, force?: bool): void; - public fade(color?: number, duration?: number, onComplete?, force?: bool): void; - public shake(intensity?: number, duration?: number, onComplete?, force?: bool, direction?: number): void; - public stopFX(): void; - public follow(target: Sprite, style?: number): void; - public focusOnXY(x: number, y: number): void; - public focusOn(point): void; - public setBounds(x?: number, y?: number, width?: number, height?: number): void; - public update(): void; - public render(): void; - public backgroundColor : string; - public setTexture(key: string, repeat?: string): void; - public setPosition(x: number, y: number): void; - public setSize(width: number, height: number): void; - 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(); - } -} diff --git a/Phaser/system/Device.d.ts b/Phaser/system/Device.d.ts deleted file mode 100644 index 793bd2ea..00000000 --- a/Phaser/system/Device.d.ts +++ /dev/null @@ -1,49 +0,0 @@ -/// -module Phaser { - class Device { - constructor(); - public desktop: bool; - public iOS: bool; - public android: bool; - public chromeOS: bool; - public linux: bool; - public macOS: bool; - public windows: bool; - public canvas: bool; - public file: bool; - public fileSystem: bool; - public localStorage: bool; - public webGL: bool; - public worker: bool; - public touch: bool; - public css3D: bool; - public arora: bool; - public chrome: bool; - public epiphany: bool; - public firefox: bool; - public ie: bool; - public ieVersion: number; - public mobileSafari: bool; - public midori: bool; - public opera: bool; - public safari: bool; - public webApp: bool; - public audioData: bool; - public webaudio: bool; - public ogg: bool; - public mp3: bool; - public wav: bool; - public m4a: bool; - public iPhone: bool; - public iPhone4: bool; - public iPad: bool; - public pixelRatio: number; - private _checkOS(); - private _checkFeatures(); - private _checkBrowser(); - private _checkAudio(); - private _checkDevice(); - private _checkCSS3D(); - public getAll(): string; - } -} diff --git a/Phaser/system/LinkedList.d.ts b/Phaser/system/LinkedList.d.ts deleted file mode 100644 index e5602ec3..00000000 --- a/Phaser/system/LinkedList.d.ts +++ /dev/null @@ -1,9 +0,0 @@ -/// -module Phaser { - class LinkedList { - constructor(); - public object: Basic; - public next: LinkedList; - public destroy(): void; - } -} diff --git a/Phaser/system/QuadTree.d.ts b/Phaser/system/QuadTree.d.ts deleted file mode 100644 index 48867e3b..00000000 --- a/Phaser/system/QuadTree.d.ts +++ /dev/null @@ -1,53 +0,0 @@ -/// -/// -module Phaser { - class QuadTree extends Rectangle { - constructor(X: number, Y: number, Width: number, Height: number, Parent?: QuadTree); - static A_LIST: number; - static B_LIST: number; - static divisions: number; - private _canSubdivide; - private _headA; - private _tailA; - private _headB; - private _tailB; - private static _min; - private _northWestTree; - private _northEastTree; - private _southEastTree; - private _southWestTree; - private _leftEdge; - private _rightEdge; - private _topEdge; - private _bottomEdge; - private _halfWidth; - private _halfHeight; - private _midpointX; - private _midpointY; - private static _object; - private static _objectLeftEdge; - private static _objectTopEdge; - private static _objectRightEdge; - private static _objectBottomEdge; - private static _list; - private static _useBothLists; - private static _processingCallback; - private static _notifyCallback; - private static _iterator; - private static _objectHullX; - private static _objectHullY; - private static _objectHullWidth; - private static _objectHullHeight; - private static _checkObjectHullX; - private static _checkObjectHullY; - private static _checkObjectHullWidth; - private static _checkObjectHullHeight; - public destroy(): void; - public load(ObjectOrGroup1: Basic, ObjectOrGroup2?: Basic, NotifyCallback?, ProcessCallback?): void; - public add(ObjectOrGroup: Basic, List: number): void; - private addObject(); - private addToList(); - public execute(): bool; - private overlapNode(); - } -} diff --git a/Phaser/system/RandomDataGenerator.d.ts b/Phaser/system/RandomDataGenerator.d.ts deleted file mode 100644 index 4c61ff20..00000000 --- a/Phaser/system/RandomDataGenerator.d.ts +++ /dev/null @@ -1,26 +0,0 @@ -/// -module Phaser { - class RandomDataGenerator { - constructor(seeds?: string[]); - private s0; - private s1; - private s2; - private c; - private uint32(); - private fract32(); - private rnd(); - private hash(data); - public sow(seeds?: string[]): void; - public integer : number; - public frac : number; - public real : number; - public integerInRange(min: number, max: number): number; - public realInRange(min: number, max: number): number; - public normal : number; - public uuid : string; - public pick(array); - public weightedPick(array); - public timestamp(min?: number, max?: number): number; - public angle : number; - } -} diff --git a/Phaser/system/RequestAnimationFrame.d.ts b/Phaser/system/RequestAnimationFrame.d.ts deleted file mode 100644 index c1e1a503..00000000 --- a/Phaser/system/RequestAnimationFrame.d.ts +++ /dev/null @@ -1,20 +0,0 @@ -/// -module Phaser { - class RequestAnimationFrame { - constructor(callback, callbackContext); - private _callback; - private _callbackContext; - public setCallback(callback): void; - private _timeOutID; - private _isSetTimeOut; - public isUsingSetTimeOut(): bool; - public isUsingRAF(): bool; - public lastTime: number; - public currentTime: number; - public isRunning: bool; - public start(callback?): void; - public stop(): void; - public RAFUpdate(): void; - public SetTimeoutUpdate(): void; - } -} diff --git a/Phaser/system/Sound.d.ts b/Phaser/system/Sound.d.ts deleted file mode 100644 index e17ee97f..00000000 --- a/Phaser/system/Sound.d.ts +++ /dev/null @@ -1,23 +0,0 @@ -/// -/// -module Phaser { - class Sound { - constructor(context, gainNode, data, volume?: number, loop?: bool); - private _context; - private _gainNode; - private _localGainNode; - private _buffer; - private _volume; - private _sound; - public loop: bool; - public duration: number; - public isPlaying: bool; - public isDecoding: bool; - public setDecodedBuffer(data): void; - public play(): void; - public stop(): void; - public mute(): void; - public unmute(): void; - public volume : number; - } -} diff --git a/Phaser/system/StageScaleMode.d.ts b/Phaser/system/StageScaleMode.d.ts deleted file mode 100644 index bb8dc966..00000000 --- a/Phaser/system/StageScaleMode.d.ts +++ /dev/null @@ -1,21 +0,0 @@ -/// -module Phaser { - class StageScaleMode { - constructor(game: Game); - private _game; - private _startHeight; - private _iterations; - private _check; - static EXACT_FIT: number; - static NO_SCALE: number; - static SHOW_ALL: number; - public width: number; - public height: number; - public orientation; - public update(): void; - public isLandscape : bool; - private checkOrientation(event); - private refresh(); - private setScreenSize(); - } -} diff --git a/Phaser/system/Tile.d.ts b/Phaser/system/Tile.d.ts deleted file mode 100644 index fdd124c6..00000000 --- a/Phaser/system/Tile.d.ts +++ /dev/null @@ -1,22 +0,0 @@ -/// -module Phaser { - class Tile { - constructor(game: Game, tilemap: Tilemap, index: number, width: number, height: number); - private _game; - public name: string; - public mass: number; - public width: number; - public height: number; - public allowCollisions: number; - public collideLeft: bool; - public collideRight: bool; - public collideUp: bool; - public collideDown: bool; - public tilemap: Tilemap; - public index: number; - public destroy(): void; - public setCollision(collision: number, resetCollisions: bool): void; - public resetCollision(): void; - public toString(): string; - } -} diff --git a/Phaser/system/TilemapLayer.d.ts b/Phaser/system/TilemapLayer.d.ts deleted file mode 100644 index b9bda845..00000000 --- a/Phaser/system/TilemapLayer.d.ts +++ /dev/null @@ -1,51 +0,0 @@ -/// -module Phaser { - class TilemapLayer { - constructor(game: Game, parent: Tilemap, key: string, mapFormat: number, name: string, tileWidth: number, tileHeight: number); - private _game; - private _parent; - 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; - public name: string; - public alpha: number; - public exists: bool; - public visible: bool; - public orientation: string; - public properties: {}; - public mapData; - public mapFormat: number; - public boundsInTiles: Rectangle; - public tileWidth: number; - public tileHeight: number; - public widthInTiles: number; - public heightInTiles: number; - public widthInPixels: number; - public heightInPixels: number; - public tileMargin: number; - public tileSpacing: number; - public getTileFromWorldXY(x: number, y: number): number; - public getTileOverlaps(object: GameObject): bool; - public getTileBlock(x: number, y: number, width: number, height: number): any[]; - public getTileIndex(x: number, y: number): number; - public addColumn(column): void; - public updateBounds(): void; - public parseTileOffsets(): number; - public renderDebugInfo(x: number, y: number, color?: string): void; - public render(camera: Camera, dx, dy): bool; - } -} diff --git a/Phaser/system/Tween.d.ts b/Phaser/system/Tween.d.ts deleted file mode 100644 index 2f032aa4..00000000 --- a/Phaser/system/Tween.d.ts +++ /dev/null @@ -1,42 +0,0 @@ -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -module Phaser { - class Tween { - constructor(object, game: Game); - private _game; - private _manager; - private _object; - private _pausedTime; - private _valuesStart; - private _valuesEnd; - private _duration; - private _delayTime; - private _startTime; - private _easingFunction; - private _interpolationFunction; - private _chainedTweens; - public onStart: Signal; - public onUpdate: Signal; - public onComplete: Signal; - public to(properties, duration?: number, ease?: any, autoStart?: bool): Tween; - public start(): Tween; - public stop(): Tween; - public parent : Game; - public delay : number; - public easing : any; - public interpolation : any; - public chain(tween: Tween): Tween; - public debugValue; - public update(time): bool; - } -} diff --git a/Phaser/system/screens/BootScreen.d.ts b/Phaser/system/screens/BootScreen.d.ts deleted file mode 100644 index 6a8b7094..00000000 --- a/Phaser/system/screens/BootScreen.d.ts +++ /dev/null @@ -1,15 +0,0 @@ -/// -module Phaser { - class BootScreen { - constructor(game: Game); - private _game; - private _logo; - private _logoData; - private _color1; - private _color2; - private _fade; - public update(): void; - public render(): void; - private colorCycle(); - } -} diff --git a/Phaser/system/screens/PauseScreen.d.ts b/Phaser/system/screens/PauseScreen.d.ts deleted file mode 100644 index 42ee5864..00000000 --- a/Phaser/system/screens/PauseScreen.d.ts +++ /dev/null @@ -1,17 +0,0 @@ -/// -module Phaser { - class PauseScreen { - constructor(game: Game, width: number, height: number); - private _game; - private _canvas; - private _context; - private _color; - private _fade; - public onPaused(): void; - public onResume(): void; - public update(): void; - public render(): void; - private fadeOut(); - private fadeIn(); - } -} diff --git a/Phaser/tweens/TweenManager.ts b/Phaser/tweens/TweenManager.ts index f6d1a897..91d0ad31 100644 --- a/Phaser/tweens/TweenManager.ts +++ b/Phaser/tweens/TweenManager.ts @@ -1,5 +1,5 @@ -/// -/// +/// +/// /** * Phaser - TweenManager diff --git a/Phaser/tweens/easing/Back.d.ts b/Phaser/tweens/easing/Back.d.ts deleted file mode 100644 index b111dd51..00000000 --- a/Phaser/tweens/easing/Back.d.ts +++ /dev/null @@ -1,8 +0,0 @@ -/// -module Phaser.Easing { - class Back { - static In(k): number; - static Out(k): number; - static InOut(k): number; - } -} diff --git a/Phaser/tweens/easing/Bounce.d.ts b/Phaser/tweens/easing/Bounce.d.ts deleted file mode 100644 index a23a0f58..00000000 --- a/Phaser/tweens/easing/Bounce.d.ts +++ /dev/null @@ -1,8 +0,0 @@ -/// -module Phaser.Easing { - class Bounce { - static In(k): number; - static Out(k): number; - static InOut(k): number; - } -} diff --git a/Phaser/tweens/easing/Circular.d.ts b/Phaser/tweens/easing/Circular.d.ts deleted file mode 100644 index 0abe1ccf..00000000 --- a/Phaser/tweens/easing/Circular.d.ts +++ /dev/null @@ -1,8 +0,0 @@ -/// -module Phaser.Easing { - class Circular { - static In(k): number; - static Out(k): number; - static InOut(k): number; - } -} diff --git a/Phaser/tweens/easing/Cubic.d.ts b/Phaser/tweens/easing/Cubic.d.ts deleted file mode 100644 index 7199265d..00000000 --- a/Phaser/tweens/easing/Cubic.d.ts +++ /dev/null @@ -1,8 +0,0 @@ -/// -module Phaser.Easing { - class Cubic { - static In(k): number; - static Out(k): number; - static InOut(k): number; - } -} diff --git a/Phaser/tweens/easing/Elastic.d.ts b/Phaser/tweens/easing/Elastic.d.ts deleted file mode 100644 index 40deb36c..00000000 --- a/Phaser/tweens/easing/Elastic.d.ts +++ /dev/null @@ -1,8 +0,0 @@ -/// -module Phaser.Easing { - class Elastic { - static In(k): number; - static Out(k): number; - static InOut(k): number; - } -} diff --git a/Phaser/tweens/easing/Exponential.d.ts b/Phaser/tweens/easing/Exponential.d.ts deleted file mode 100644 index 48bb9a87..00000000 --- a/Phaser/tweens/easing/Exponential.d.ts +++ /dev/null @@ -1,8 +0,0 @@ -/// -module Phaser.Easing { - class Exponential { - static In(k): number; - static Out(k): number; - static InOut(k): number; - } -} diff --git a/Phaser/tweens/easing/Linear.d.ts b/Phaser/tweens/easing/Linear.d.ts deleted file mode 100644 index 9ae91006..00000000 --- a/Phaser/tweens/easing/Linear.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -/// -module Phaser.Easing { - class Linear { - static None(k); - } -} diff --git a/Phaser/tweens/easing/Quadratic.d.ts b/Phaser/tweens/easing/Quadratic.d.ts deleted file mode 100644 index e3ccb3ac..00000000 --- a/Phaser/tweens/easing/Quadratic.d.ts +++ /dev/null @@ -1,8 +0,0 @@ -/// -module Phaser.Easing { - class Quadratic { - static In(k): number; - static Out(k): number; - static InOut(k): number; - } -} diff --git a/Phaser/tweens/easing/Quartic.d.ts b/Phaser/tweens/easing/Quartic.d.ts deleted file mode 100644 index 342bb6b4..00000000 --- a/Phaser/tweens/easing/Quartic.d.ts +++ /dev/null @@ -1,8 +0,0 @@ -/// -module Phaser.Easing { - class Quartic { - static In(k): number; - static Out(k): number; - static InOut(k): number; - } -} diff --git a/Phaser/tweens/easing/Quintic.d.ts b/Phaser/tweens/easing/Quintic.d.ts deleted file mode 100644 index 7c3782de..00000000 --- a/Phaser/tweens/easing/Quintic.d.ts +++ /dev/null @@ -1,8 +0,0 @@ -/// -module Phaser.Easing { - class Quintic { - static In(k): number; - static Out(k): number; - static InOut(k): number; - } -} diff --git a/Phaser/tweens/easing/Sinusoidal.d.ts b/Phaser/tweens/easing/Sinusoidal.d.ts deleted file mode 100644 index 1dfd2310..00000000 --- a/Phaser/tweens/easing/Sinusoidal.d.ts +++ /dev/null @@ -1,8 +0,0 @@ -/// -module Phaser.Easing { - class Sinusoidal { - static In(k): number; - static Out(k): number; - static InOut(k): number; - } -} diff --git a/Phaser/geom/CircleUtils.ts b/Phaser/utils/CircleUtils.ts similarity index 100% rename from Phaser/geom/CircleUtils.ts rename to Phaser/utils/CircleUtils.ts diff --git a/Phaser/geom/PointUtils.ts b/Phaser/utils/PointUtils.ts similarity index 100% rename from Phaser/geom/PointUtils.ts rename to Phaser/utils/PointUtils.ts diff --git a/Phaser/geom/RectangleUtils.ts b/Phaser/utils/RectangleUtils.ts similarity index 100% rename from Phaser/geom/RectangleUtils.ts rename to Phaser/utils/RectangleUtils.ts diff --git a/Phaser/utils/SpriteUtils.ts b/Phaser/utils/SpriteUtils.ts new file mode 100644 index 00000000..090dfe63 --- /dev/null +++ b/Phaser/utils/SpriteUtils.ts @@ -0,0 +1,425 @@ +/// +/// +/// +/// +/// + +/** +* Phaser - SpriteUtils +* +* A collection of methods useful for manipulating and checking Sprites. +* +* TODO: +*/ + +module Phaser { + + export class SpriteUtils { + + /** + * Pivot position enum: at the top-left corner. + * @type {number} + */ + static ALIGN_TOP_LEFT: number = 0; + + /** + * Pivot position enum: at the top-center corner. + * @type {number} + */ + static ALIGN_TOP_CENTER: number = 1; + + /** + * Pivot position enum: at the top-right corner. + * @type {number} + */ + static ALIGN_TOP_RIGHT: number = 2; + + /** + * Pivot position enum: at the center-left corner. + * @type {number} + */ + static ALIGN_CENTER_LEFT: number = 3; + + /** + * Pivot position enum: at the center corner. + * @type {number} + */ + static ALIGN_CENTER: number = 4; + + /** + * Pivot position enum: at the center-right corner. + * @type {number} + */ + static ALIGN_CENTER_RIGHT: number = 5; + + /** + * Pivot position enum: at the bottom-left corner. + * @type {number} + */ + static ALIGN_BOTTOM_LEFT: number = 6; + + /** + * Pivot position enum: at the bottom-center corner. + * @type {number} + */ + static ALIGN_BOTTOM_CENTER: number = 7; + + /** + * Pivot position enum: at the bottom-right corner. + * @type {number} + */ + static ALIGN_BOTTOM_RIGHT: number = 8; + + /** + * 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 + */ + static setBounds(x: number, y: number, width: number, height: number) { + + //this.worldBounds = new Quad(x, y, width, height); + + } + + /** + * 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. + * @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; + } + */ + + } + +} \ No newline at end of file diff --git a/Plugins/Plugins.csproj b/Plugins/Plugins.csproj index aa2b3b6c..a44ba840 100644 --- a/Plugins/Plugins.csproj +++ b/Plugins/Plugins.csproj @@ -1,4 +1,4 @@ - + Debug @@ -15,32 +15,6 @@ - - - AngleConstraint.ts - - - Composite.ts - - - DistanceConstraint.ts - - - Particle.ts - - - PinConstraint.ts - - - VerletManager.ts - - - - - - - - 10.0 $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) @@ -69,16 +43,14 @@ - ES3 + ES5 true - true - AMD + false - ES3 + ES5 false false - AMD \ No newline at end of file diff --git a/README.md b/README.md index 926fa3a1..16e98d7d 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ Phaser ====== -Version: 0.9.6 - Released: In Progress +Version: 1.0.0 - Released: In Progress By Richard Davey, [Photon Storm](http://www.photonstorm.com) @@ -20,6 +20,27 @@ Try out the [Phaser Test Suite](http://gametest.mobi/phaser/) Latest Update ------------- +TODO: + +* Dispatch world resize event +* Removed ignoreGlobalUpdate because it checks exists etc in the Group update, so remove those checks from Sprite.update (same for render) + + + +V1.0.0 + +* Massive refactoring across the entire codebase. +* Removed Basic and GameObject and put Sprite on a diet. 127 properties and methods, now down to < 30. +* Added a new headless renderer for non-display related performance testing. +* Added camera type to the CameraManager for future non-orthographic cameras. +* Added Camera.destroy - now clears down the FX and unregisters itself from the CameraManager. +* Added Camera.hide/show to hide Sprites or Groups from rendering (and removed corresponding hideFromCamera methods from Sprites/Groups) +* 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. + + + V0.9.6 * Virtually every class now has documentation - if you spot a typo or something missing please shout (thanks pixelpicosean). diff --git a/build/phaser.js b/build/phaser.js index 7e3c9c17..f7b1ad0c 100644 --- a/build/phaser.js +++ b/build/phaser.js @@ -1,2463 +1,666 @@ -/// -/** -* 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 - Line +* Phaser - Loader * -* A Line object is an infinte line through space. The two sets of x/y coordinates define the Line Segment. +* 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 Line = (function () { + var Loader = (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 Phaser.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 Phaser.Math.max(this.x1, this.x2) - Phaser.Math.min(this.x1, this.x2); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Line.prototype, "height", { - get: function () { - return Phaser.Math.max(this.y1, this.y2) - Phaser.Math.min(this.y1, this.y2); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Line.prototype, "length", { - get: /** - * - * @method length - * @return {Number} - */ - function () { - return Phaser.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 Phaser.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 = Phaser.Math.min(this.x1, this.x2); - var xMax = Phaser.Math.max(this.x1, this.x2); - var yMin = Phaser.Math.min(this.y1, this.y2); - var yMax = Phaser.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 Phaser.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 Phaser.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 - 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 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 Vector2().copyFrom(p2).sub(p1); - var n = new Vector2().copyFrom(e).perp().normalize(); - this.edges.push(e); - this.normals.push(n); - } - }; - return Polygon; - })(); - Phaser.Polygon = Polygon; -})(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 Vector2(); - this.overlapV = new 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 - 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 LinkedList(); - this._headB = this._tailB = new 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 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 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; - Phaser.QuadTree._object = null; - Phaser.QuadTree._processingCallback = null; - Phaser.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, Phaser.QuadTree.A_LIST); - if(objectOrGroup2 != null) { - this.add(objectOrGroup2, Phaser.QuadTree.B_LIST); - Phaser.QuadTree._useBothLists = true; - } else { - Phaser.QuadTree._useBothLists = false; - } - Phaser.QuadTree._notifyCallback = notifyCallback; - Phaser.QuadTree._processingCallback = processCallback; - Phaser.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) { - Phaser.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 { - Phaser.QuadTree._object = basic; - if(Phaser.QuadTree._object.exists && Phaser.QuadTree._object.allowCollisions) { - this.addObject(); - } - } - } - } - } else { - Phaser.QuadTree._object = objectOrGroup; - if(Phaser.QuadTree._object.exists && Phaser.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 >= Phaser.QuadTree._object.collisionMask.x) && (this._rightEdge <= Phaser.QuadTree._object.collisionMask.right) && (this._topEdge >= Phaser.QuadTree._object.collisionMask.y) && (this._bottomEdge <= Phaser.QuadTree._object.collisionMask.bottom))) { - this.addToList(); - return; - } - //See if the selected object fits completely inside any of the quadrants - if((Phaser.QuadTree._object.collisionMask.x > this._leftEdge) && (Phaser.QuadTree._object.collisionMask.right < this._midpointX)) { - if((Phaser.QuadTree._object.collisionMask.y > this._topEdge) && (Phaser.QuadTree._object.collisionMask.bottom < this._midpointY)) { - if(this._northWestTree == null) { - this._northWestTree = new Phaser.QuadTree(this._leftEdge, this._topEdge, this._halfWidth, this._halfHeight, this); - } - this._northWestTree.addObject(); - return; - } - if((Phaser.QuadTree._object.collisionMask.y > this._midpointY) && (Phaser.QuadTree._object.collisionMask.bottom < this._bottomEdge)) { - if(this._southWestTree == null) { - this._southWestTree = new Phaser.QuadTree(this._leftEdge, this._midpointY, this._halfWidth, this._halfHeight, this); - } - this._southWestTree.addObject(); - return; - } - } - if((Phaser.QuadTree._object.collisionMask.x > this._midpointX) && (Phaser.QuadTree._object.collisionMask.right < this._rightEdge)) { - if((Phaser.QuadTree._object.collisionMask.y > this._topEdge) && (Phaser.QuadTree._object.collisionMask.bottom < this._midpointY)) { - if(this._northEastTree == null) { - this._northEastTree = new Phaser.QuadTree(this._midpointX, this._topEdge, this._halfWidth, this._halfHeight, this); - } - this._northEastTree.addObject(); - return; - } - if((Phaser.QuadTree._object.collisionMask.y > this._midpointY) && (Phaser.QuadTree._object.collisionMask.bottom < this._bottomEdge)) { - if(this._southEastTree == null) { - this._southEastTree = new Phaser.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((Phaser.QuadTree._object.collisionMask.right > this._leftEdge) && (Phaser.QuadTree._object.collisionMask.x < this._midpointX) && (Phaser.QuadTree._object.collisionMask.bottom > this._topEdge) && (Phaser.QuadTree._object.collisionMask.y < this._midpointY)) { - if(this._northWestTree == null) { - this._northWestTree = new Phaser.QuadTree(this._leftEdge, this._topEdge, this._halfWidth, this._halfHeight, this); - } - this._northWestTree.addObject(); - } - if((Phaser.QuadTree._object.collisionMask.right > this._midpointX) && (Phaser.QuadTree._object.collisionMask.x < this._rightEdge) && (Phaser.QuadTree._object.collisionMask.bottom > this._topEdge) && (Phaser.QuadTree._object.collisionMask.y < this._midpointY)) { - if(this._northEastTree == null) { - this._northEastTree = new Phaser.QuadTree(this._midpointX, this._topEdge, this._halfWidth, this._halfHeight, this); - } - this._northEastTree.addObject(); - } - if((Phaser.QuadTree._object.collisionMask.right > this._midpointX) && (Phaser.QuadTree._object.collisionMask.x < this._rightEdge) && (Phaser.QuadTree._object.collisionMask.bottom > this._midpointY) && (Phaser.QuadTree._object.collisionMask.y < this._bottomEdge)) { - if(this._southEastTree == null) { - this._southEastTree = new Phaser.QuadTree(this._midpointX, this._midpointY, this._halfWidth, this._halfHeight, this); - } - this._southEastTree.addObject(); - } - if((Phaser.QuadTree._object.collisionMask.right > this._leftEdge) && (Phaser.QuadTree._object.collisionMask.x < this._midpointX) && (Phaser.QuadTree._object.collisionMask.bottom > this._midpointY) && (Phaser.QuadTree._object.collisionMask.y < this._bottomEdge)) { - if(this._southWestTree == null) { - this._southWestTree = new Phaser.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(Phaser.QuadTree._list == Phaser.QuadTree.A_LIST) { - if(this._tailA.object != null) { - ot = this._tailA; - this._tailA = new Phaser.LinkedList(); - ot.next = this._tailA; - } - this._tailA.object = Phaser.QuadTree._object; - } else { - if(this._tailB.object != null) { - ot = this._tailB; - this._tailB = new Phaser.LinkedList(); - ot.next = this._tailB; - } - this._tailB.object = Phaser.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) { - Phaser.QuadTree._object = iterator.object; - if(Phaser.QuadTree._useBothLists) { - Phaser.QuadTree._iterator = this._headB; - } else { - Phaser.QuadTree._iterator = iterator.next; - } - if(Phaser.QuadTree._object.exists && (Phaser.QuadTree._object.allowCollisions > 0) && (Phaser.QuadTree._iterator != null) && (Phaser.QuadTree._iterator.object != null) && Phaser.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(Phaser.QuadTree._iterator != null) { - if(!Phaser.QuadTree._object.exists || (Phaser.QuadTree._object.allowCollisions <= 0)) { - break; - } - checkObject = Phaser.QuadTree._iterator.object; - if((Phaser.QuadTree._object === checkObject) || !checkObject.exists || (checkObject.allowCollisions <= 0)) { - Phaser.QuadTree._iterator = Phaser.QuadTree._iterator.next; - continue; - } - if(Phaser.QuadTree._object.collisionMask.checkHullIntersection(checkObject.collisionMask)) { - //Execute callback functions if they exist - if((Phaser.QuadTree._processingCallback == null) || Phaser.QuadTree._processingCallback(Phaser.QuadTree._object, checkObject)) { - overlapProcessed = true; - } - if(overlapProcessed && (Phaser.QuadTree._notifyCallback != null)) { - if(Phaser.QuadTree._callbackContext !== null) { - Phaser.QuadTree._notifyCallback.call(Phaser.QuadTree._callbackContext, Phaser.QuadTree._object, checkObject); - } else { - Phaser.QuadTree._notifyCallback(Phaser.QuadTree._object, checkObject); - } - } - } - Phaser.QuadTree._iterator = Phaser.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 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 = Phaser.Collision.UP; - Collision.FLOOR = Phaser.Collision.DOWN; - Collision.WALL = Phaser.Collision.LEFT | Phaser.Collision.RIGHT; - Collision.ANY = Phaser.Collision.LEFT | Phaser.Collision.RIGHT | Phaser.Collision.UP | Phaser.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 = Phaser.Math.max(seg.x1, seg.x2); - var minX = Phaser.Math.min(seg.x1, seg.x2); - var maxY = Phaser.Math.max(seg.y1, seg.y2); - var minY = Phaser.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 = Phaser.Math.max(x1, x2); - var minX = Phaser.Math.min(x1, x2); - var maxY = Phaser.Math.max(y1, y2); - var minY = Phaser.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 - Phaser.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 - Phaser.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 - Phaser.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 - Phaser.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(); } - Phaser.Collision.lineToLineSegment(line1, line2); - if(output.result === true) { - if(!(output.x >= Phaser.Math.min(line1.x1, line1.x2) && output.x <= Phaser.Math.max(line1.x1, line1.x2) && output.y >= Phaser.Math.min(line1.y1, line1.y2) && output.y <= Phaser.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(); } - Phaser.Collision.lineToRay(line, ray, output); - if(output.result === true) { - if(!(output.x >= Phaser.Math.min(line.x1, line.x2) && output.x <= Phaser.Math.max(line.x1, line.x2) && output.y >= Phaser.Math.min(line.y1, line.y2) && output.y <= Phaser.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 = Phaser.Math.max(seg.x1, seg.x2); - var minX = Phaser.Math.min(seg.x1, seg.x2); - var maxY = Phaser.Math.max(seg.y1, seg.y2); - var minY = Phaser.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(Phaser.Collision.circleContainsPoint(circle, { - x: seg.x1, - y: seg.y1 - }) || Phaser.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 - Phaser.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 - Phaser.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 - Phaser.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 - Phaser.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 - Phaser.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 = Phaser.Math.max(rect1.x, rect2.x); - var rightX = Phaser.Math.min(rect1.right, rect2.right); - var topY = Phaser.Math.max(rect1.y, rect2.y); - var bottomY = Phaser.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 Phaser.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)) >= Phaser.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 >= Phaser.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 = Phaser.Collision.separateX(object1, object2); - var separatedY = Phaser.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 = Phaser.Collision.separateTileX(object, x, y, width, height, mass, collideLeft, collideRight, separateX); - var separatedY = Phaser.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 + Phaser.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 & Phaser.Collision.RIGHT) || collideLeft == false) { - overlap = 0; - } else { - object.touching |= Phaser.Collision.RIGHT; - } - } else if(objDelta < 0) { - overlap = object.x - width - x; - if((-overlap > maxOverlap) || !(object.allowCollisions & Phaser.Collision.LEFT) || collideRight == false) { - overlap = 0; - } else { - object.touching |= Phaser.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); - } - Phaser.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 + Phaser.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 & Phaser.Collision.DOWN) || collideUp == false) { - overlap = 0; - } else { - object.touching |= Phaser.Collision.DOWN; - } - } else if(objDelta < 0) { - overlap = object.y - height - y; - if((-overlap > maxOverlap) || !(object.allowCollisions & Phaser.Collision.UP) || collideDown == false) { - overlap = 0; - } else { - object.touching |= Phaser.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); - } - Phaser.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 + Phaser.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 & Phaser.Collision.RIGHT) || collideLeft == false) { - overlap = 0; - } else { - object.touching |= Phaser.Collision.RIGHT; - } - } else if(object.collisionMask.deltaX < 0) { - //overlap = object.x - width - x; - overlap = object.collisionMask.x - width - x; - if((-overlap > maxOverlap) || !(object.allowCollisions & Phaser.Collision.LEFT) || collideRight == false) { - overlap = 0; - } else { - object.touching |= Phaser.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); - } - Phaser.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 + Phaser.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 & Phaser.Collision.DOWN) || collideUp == false) { - overlap = 0; - } else { - object.touching |= Phaser.Collision.DOWN; - } - } else if(object.collisionMask.deltaY < 0) { - //overlap = object.y - height - y; - overlap = object.collisionMask.y - height - y; - if((-overlap > maxOverlap) || !(object.allowCollisions & Phaser.Collision.UP) || collideDown == false) { - overlap = 0; - } else { - object.touching |= Phaser.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); - } - Phaser.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 + Phaser.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 & Phaser.Collision.RIGHT) || !(object2.allowCollisions & Phaser.Collision.LEFT)) { - overlap = 0; - } else { - object1.touching |= Phaser.Collision.RIGHT; - object2.touching |= Phaser.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 & Phaser.Collision.LEFT) || !(object2.allowCollisions & Phaser.Collision.RIGHT)) { - overlap = 0; - } else { - object1.touching |= Phaser.Collision.LEFT; - object2.touching |= Phaser.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 = Phaser.Math.sqrt((obj2Velocity * obj2Velocity * object2.mass) / object1.mass) * ((obj2Velocity > 0) ? 1 : -1); - var obj2NewVelocity = Phaser.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 + Phaser.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 & Phaser.Collision.DOWN) || !(object2.allowCollisions & Phaser.Collision.UP)) { - overlap = 0; - } else { - object1.touching |= Phaser.Collision.DOWN; - object2.touching |= Phaser.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 & Phaser.Collision.UP) || !(object2.allowCollisions & Phaser.Collision.DOWN)) { - overlap = 0; - } else { - object1.touching |= Phaser.Collision.UP; - object2.touching |= Phaser.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 = Phaser.Math.sqrt((obj2Velocity * obj2Velocity * object2.mass) / object1.mass) * ((obj2Velocity > 0) ? 1 : -1); - var obj2NewVelocity = Phaser.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 Phaser.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 = Phaser.Collision.T_ARRAYS.pop(); - var rangeB = Phaser.Collision.T_ARRAYS.pop(); - // Get the magnitude of the offset between the two polygons - var offsetV = Phaser.Collision.T_VECTORS.pop().copyFrom(bPos).sub(aPos); - var projectedOffset = offsetV.dot(axis); - // Project the polygons onto the axis. - Phaser.Collision.flattenPointsOn(aPoints, axis, rangeA); - Phaser.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]) { - Phaser.Collision.T_VECTORS.push(offsetV); - Phaser.Collision.T_ARRAYS.push(rangeA); - Phaser.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 = Phaser.Math.abs(overlap); - if(absOverlap < response.overlap) { - response.overlap = absOverlap; - response.overlapN.copyFrom(axis); - if(overlap < 0) { - response.overlapN.reverse(); - } - } - } - Phaser.Collision.T_VECTORS.push(offsetV); - Phaser.Collision.T_ARRAYS.push(rangeA); - Phaser.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 Phaser.Collision.LEFT_VORNOI_REGION; - } else if(dp > len2) { - return Phaser.Collision.RIGHT_VORNOI_REGION; - } else { - return Phaser.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 = Phaser.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 - Phaser.Collision.T_VECTORS.push(differenceV); - return false; - } - // They intersect. If we're calculating a response, calculate the overlap. - if(response) { - var dist = Phaser.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; - } - Phaser.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 = Phaser.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 === Phaser.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 = Phaser.Collision.T_VECTORS.pop().copyFrom(circlePos).sub(points[prev]); - region = Collision.vornoiRegion(edge, point2); - if(region === Phaser.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 - Phaser.Collision.T_VECTORS.push(circlePos); - Phaser.Collision.T_VECTORS.push(edge); - Phaser.Collision.T_VECTORS.push(point); - Phaser.Collision.T_VECTORS.push(point2); - return false; - } else if(response) { - // It intersects, calculate the overlap - response.bInA = false; - overlapN = point.normalize(); - overlap = radius - dist; - } - } - Phaser.Collision.T_VECTORS.push(point2); - } else if(region === Phaser.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 === Phaser.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 - Phaser.Collision.T_VECTORS.push(circlePos); - Phaser.Collision.T_VECTORS.push(edge); - Phaser.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 = Phaser.Math.abs(dist); - // If the circle is on the outside of the edge, there is no intersection - if(dist > 0 && distAbs > radius) { - Phaser.Collision.T_VECTORS.push(circlePos); - Phaser.Collision.T_VECTORS.push(normal); - Phaser.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 && Phaser.Math.abs(overlap) < Phaser.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); - } - Phaser.Collision.T_VECTORS.push(circlePos); - Phaser.Collision.T_VECTORS.push(edge); - Phaser.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 = Phaser.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(Phaser.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(Phaser.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. + * Loader constructor * * @param game {Phaser.Game} Current game instance. - * @param width {number} Init width of this texture. - * @param height {number} Init height of this texture. + * @param callback {function} This will be called when assets completely loaded. */ - 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; + function Loader(game, callback) { + /** + * The crossOrigin value applied to loaded images + * @type {string} + */ + this.crossOrigin = ''; 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 Rectangle(0, 0, width, height); + this._gameCreateComplete = callback; + this._keys = []; + this._fileList = { + }; + this._xhr = new XMLHttpRequest(); + this._queueSize = 0; } - 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. + 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.context.clearRect(0, 0, this.bounds.width, this.bounds.height); + this._queueSize = 0; }; - 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", { + Object.defineProperty(Loader.prototype, "queueSize", { get: function () { - return this.bounds.width; + return this._queueSize; }, 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) + 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 (alpha, red, green, blue) { - return alpha << 24 | red << 16 | green << 8 | blue; + 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); + } }; - 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) + 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 (red, green, blue) { - return red << 16 | green << 8 | blue; + 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); + } }; - return DynamicTexture; + 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. + */ + 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); + } + } + }; + 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; + } + }; + Loader.prototype.fileError = /** + * Error occured when load a file. + * @param key {string} Key of the error loading file. + */ + function (key) { + this._fileList[key].loaded = true; + this._fileList[key].error = true; + this.nextFile(key, false); + }; + Loader.prototype.fileComplete = /** + * Called when a file is successfully loaded. + * @param key {string} Key of the successfully loaded file. + */ + 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); + } + }; + 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 { + 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 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; })(); - Phaser.DynamicTexture = DynamicTexture; + Phaser.Loader = Loader; })(Phaser || (Phaser = {})); -/// +/// /** -* Phaser - FXManager +* Phaser - Cache * -* The FXManager controls all special effects applied to game objects such as Cameras. +* A game only has one instance of a Cache and it is used to store all externally loaded assets such +* as images, sounds and data files as a result of Loader calls. Cache items use string based keys for look-up. */ var Phaser; (function (Phaser) { - var FXManager = (function () { - function FXManager(game, parent) { + var Cache = (function () { + /** + * Cache constructor + */ + function Cache(game) { this._game = game; - this._parent = parent; - this._fx = []; - this.active = true; - this.visible = true; - } - 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 + this._canvases = { }; - 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; + this._images = { + }; + this._sounds = { + }; + this._text = { + }; + } + Cache.prototype.addCanvas = /** + * Add a new canvas. + * @param key {string} Asset key for this canvas. + * @param canvas {HTMLCanvasElement} Canvas DOM element. + * @param context {CanvasRenderingContext2D} Render context of this canvas. + */ + function (key, canvas, context) { + this._canvases[key] = { + canvas: canvas, + context: context + }; + }; + Cache.prototype.addSpriteSheet = /** + * Add a new sprite sheet. + * @param key {string} Asset key for the sprite sheet. + * @param url {string} URL of this sprite sheet file. + * @param data {object} Extra sprite sheet data. + * @param frameWidth {number} Width of the sprite sheet. + * @param frameHeight {number} Height of the sprite sheet. + * @param frameMax {number} How many frames stored in the sprite sheet. + */ + function (key, url, data, frameWidth, frameHeight, frameMax) { + this._images[key] = { + url: url, + data: data, + spriteSheet: true, + frameWidth: frameWidth, + frameHeight: frameHeight + }; + this._images[key].frameData = Phaser.AnimationLoader.parseSpriteSheet(this._game, key, frameWidth, frameHeight, frameMax); + }; + Cache.prototype.addTextureAtlas = /** + * Add a new texture atlas. + * @param key {string} Asset key for the texture atlas. + * @param url {string} URL of this texture atlas file. + * @param data {object} Extra texture atlas data. + * @param atlasData {object} Texture atlas frames data. + */ + function (key, url, data, atlasData, format) { + this._images[key] = { + url: url, + data: data, + spriteSheet: true + }; + if(format == Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY) { + this._images[key].frameData = Phaser.AnimationLoader.parseJSONData(this._game, atlasData); + } else if(format == Phaser.Loader.TEXTURE_ATLAS_XML_STARLING) { + this._images[key].frameData = Phaser.AnimationLoader.parseXMLData(this._game, atlasData, format); } }; - FXManager.prototype.preUpdate = /** - * Pre-update is called at the start of the objects update cycle, before any other updates have taken place. + Cache.prototype.addImage = /** + * Add a new image. + * @param key {string} Asset key for the image. + * @param url {string} URL of this image file. + * @param data {object} Extra image data. + */ + function (key, url, data) { + this._images[key] = { + url: url, + data: data, + spriteSheet: false + }; + }; + Cache.prototype.addSound = /** + * Add a new sound. + * @param key {string} Asset key for the sound. + * @param url {string} URL of this sound file. + * @param data {object} Extra sound data. + */ + function (key, url, data) { + this._sounds[key] = { + url: url, + data: data, + decoded: false + }; + }; + Cache.prototype.decodedSound = /** + * Add a new decoded sound. + * @param key {string} Asset key for the sound. + * @param url {string} URL of this sound file. + * @param data {object} Extra sound data. + */ + function (key, data) { + this._sounds[key].data = data; + this._sounds[key].decoded = true; + }; + Cache.prototype.addText = /** + * Add a new text data. + * @param key {string} Asset key for the text data. + * @param url {string} URL of this text data file. + * @param data {object} Extra text data. + */ + function (key, url, data) { + this._text[key] = { + url: url, + data: data + }; + }; + Cache.prototype.getCanvas = /** + * Get canvas by key. + * @param key Asset key of the canvas you want. + * @return {object} The canvas you want. + */ + function (key) { + if(this._canvases[key]) { + return this._canvases[key].canvas; + } + return null; + }; + Cache.prototype.getImage = /** + * Get image data by key. + * @param key Asset key of the image you want. + * @return {object} The image data you want. + */ + function (key) { + if(this._images[key]) { + return this._images[key].data; + } + return null; + }; + Cache.prototype.getFrameData = /** + * Get frame data by key. + * @param key Asset key of the frame data you want. + * @return {object} The frame data you want. + */ + function (key) { + if(this._images[key] && this._images[key].spriteSheet == true) { + return this._images[key].frameData; + } + return null; + }; + Cache.prototype.getSound = /** + * Get sound data by key. + * @param key Asset key of the sound you want. + * @return {object} The sound data you want. + */ + function (key) { + if(this._sounds[key]) { + return this._sounds[key].data; + } + return null; + }; + Cache.prototype.isSoundDecoded = /** + * Check whether an asset is decoded sound. + * @param key Asset key of the sound you want. + * @return {object} The sound data you want. + */ + function (key) { + if(this._sounds[key]) { + return this._sounds[key].decoded; + } + }; + Cache.prototype.isSpriteSheet = /** + * Check whether an asset is sprite sheet. + * @param key Asset key of the sprite sheet you want. + * @return {object} The sprite sheet data you want. + */ + function (key) { + if(this._images[key]) { + return this._images[key].spriteSheet; + } + }; + Cache.prototype.getText = /** + * Get text data by key. + * @param key Asset key of the text data you want. + * @return {object} The text data you want. + */ + function (key) { + if(this._text[key]) { + return this._text[key].data; + } + return null; + }; + Cache.prototype.destroy = /** + * Clean up cache memory. */ function () { - if(this.active) { - for(var i = 0; i < this._length; i++) { - if(this._fx[i].preUpdate) { - this._fx[i].effect.preUpdate(); - } - } + for(var item in this._canvases) { + delete this._canvases[item['key']]; + } + for(var item in this._images) { + delete this._images[item['key']]; + } + for(var item in this._sounds) { + delete this._sounds[item['key']]; + } + for(var item in this._text) { + delete this._text[item['key']]; } }; - FXManager.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(); - } - } - } - }; - 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 Cache; })(); - Phaser.FXManager = FXManager; + Phaser.Cache = Cache; })(Phaser || (Phaser = {})); -/// +/// /** * Phaser - GameMath * @@ -2474,7 +677,7 @@ var Phaser; /** * The global random number generator seed (for deterministic behavior in recordings and saves). */ - this.globalSeed = Phaser.Math.random(); + this.globalSeed = Math.random(); this._game = game; } GameMath.PI = 3.141592653589793; @@ -2513,7 +716,7 @@ var Phaser; GameMath.LONG_EPSILON = 0.00000001; GameMath.prototype.fuzzyEqual = function (a, b, epsilon) { if (typeof epsilon === "undefined") { epsilon = 0.0001; } - return Phaser.Math.abs(a - b) < epsilon; + return Math.abs(a - b) < epsilon; }; GameMath.prototype.fuzzyLessThan = function (a, b, epsilon) { if (typeof epsilon === "undefined") { epsilon = 0.0001; } @@ -2525,11 +728,11 @@ var Phaser; }; GameMath.prototype.fuzzyCeil = function (val, epsilon) { if (typeof epsilon === "undefined") { epsilon = 0.0001; } - return Phaser.Math.ceil(val - epsilon); + return Math.ceil(val - epsilon); }; GameMath.prototype.fuzzyFloor = function (val, epsilon) { if (typeof epsilon === "undefined") { epsilon = 0.0001; } - return Phaser.Math.floor(val + epsilon); + return Math.floor(val + epsilon); }; GameMath.prototype.average = function () { var args = []; @@ -2544,7 +747,7 @@ var Phaser; }; GameMath.prototype.slam = function (value, target, epsilon) { if (typeof epsilon === "undefined") { epsilon = 0.0001; } - return (Phaser.Math.abs(value - target) < epsilon) ? target : value; + return (Math.abs(value - target) < epsilon) ? target : value; }; GameMath.prototype.percentageMinMax = /** * ratio of value to a range @@ -2565,13 +768,13 @@ var Phaser; */ function (n) { if(n) { - return n / Phaser.Math.abs(n); + return n / Math.abs(n); } else { return 0; } }; GameMath.prototype.truncate = function (n) { - return (n > 0) ? Phaser.Math.floor(n) : Phaser.Math.ceil(n); + return (n > 0) ? Math.floor(n) : Math.ceil(n); }; GameMath.prototype.shear = function (n) { return n % 1; @@ -2602,7 +805,7 @@ var Phaser; if(max == 0) { return min; } - return value - max * Phaser.Math.floor((value - min) / max); + return value - max * Math.floor((value - min) / max); }; GameMath.prototype.clamp = /** * force a value within the boundaries of two values @@ -2611,7 +814,7 @@ var Phaser; */ function (input, max, min) { if (typeof min === "undefined") { min = 0; } - return Phaser.Math.max(min, Phaser.Math.min(max, input)); + return Math.max(min, Math.min(max, input)); }; GameMath.prototype.snapTo = /** * Snap a value to nearest grid slice, using rounding. @@ -2628,7 +831,7 @@ var Phaser; return input; } input -= start; - input = gap * Phaser.Math.round(input / gap); + input = gap * Math.round(input / gap); return start + input; }; GameMath.prototype.snapToFloor = /** @@ -2646,7 +849,7 @@ var Phaser; return input; } input -= start; - input = gap * Phaser.Math.floor(input / gap); + input = gap * Math.floor(input / gap); return start + input; }; GameMath.prototype.snapToCeil = /** @@ -2664,7 +867,7 @@ var Phaser; return input; } input -= start; - input = gap * Phaser.Math.ceil(input / gap); + input = gap * Math.ceil(input / gap); return start + input; }; GameMath.prototype.snapToInArray = /** @@ -2725,20 +928,20 @@ var Phaser; function (value, place, base) { if (typeof place === "undefined") { place = 0; } if (typeof base === "undefined") { base = 10; } - var p = Phaser.Math.pow(base, -place); - return Phaser.Math.round(value * p) / p; + var p = Math.pow(base, -place); + return Math.round(value * p) / p; }; GameMath.prototype.floorTo = function (value, place, base) { if (typeof place === "undefined") { place = 0; } if (typeof base === "undefined") { base = 10; } - var p = Phaser.Math.pow(base, -place); - return Phaser.Math.floor(value * p) / p; + var p = Math.pow(base, -place); + return Math.floor(value * p) / p; }; GameMath.prototype.ceilTo = function (value, place, base) { if (typeof place === "undefined") { place = 0; } if (typeof base === "undefined") { base = 10; } - var p = Phaser.Math.pow(base, -place); - return Phaser.Math.ceil(value * p) / p; + var p = Math.pow(base, -place); + return Math.ceil(value * p) / p; }; GameMath.prototype.interpolateFloat = /** * a one dimensional linear interpolation of a value. @@ -2750,26 +953,26 @@ var Phaser; * convert radians to degrees */ function (angle) { - return angle * Phaser.GameMath.RAD_TO_DEG; + return angle * GameMath.RAD_TO_DEG; }; GameMath.prototype.degreesToRadians = /** * convert degrees to radians */ function (angle) { - return angle * Phaser.GameMath.DEG_TO_RAD; + return angle * GameMath.DEG_TO_RAD; }; GameMath.prototype.angleBetween = /** * Find the angle of a segment from (x1, y1) -> (x2, y2 ) */ function (x1, y1, x2, y2) { - return Phaser.Math.atan2(y2 - y1, x2 - x1); + return Math.atan2(y2 - y1, x2 - x1); }; GameMath.prototype.normalizeAngle = /** * set an angle with in the bounds of -PI to PI */ function (angle, radians) { if (typeof radians === "undefined") { radians = true; } - var rd = (radians) ? Phaser.GameMath.PI : 180; + var rd = (radians) ? GameMath.PI : 180; return this.wrap(angle, rd, -rd); }; GameMath.prototype.nearestAngleBetween = /** @@ -2778,7 +981,7 @@ var Phaser; */ function (a1, a2, radians) { if (typeof radians === "undefined") { radians = true; } - var rd = (radians) ? Phaser.GameMath.PI : 180; + var rd = (radians) ? GameMath.PI : 180; a1 = this.normalizeAngle(a1, radians); a2 = this.normalizeAngle(a2, radians); if(a1 < -rd / 2 && a2 > rd / 2) { @@ -2844,7 +1047,7 @@ var Phaser; * which would return 2, because 4^2 = 16 */ function (value, base) { - return Phaser.Math.log(value) / Phaser.Math.log(base); + return Math.log(value) / Math.log(base); }; GameMath.prototype.GCD = /** * Greatest Common Denominator using Euclid's algorithm @@ -2852,8 +1055,8 @@ var Phaser; function (m, n) { var r; //make sure positive, GCD is always positive - m = Phaser.Math.abs(m); - n = Phaser.Math.abs(n); + m = Math.abs(m); + n = Math.abs(n); //m must be >= n if(m < n) { r = m; @@ -2960,7 +1163,7 @@ var Phaser; } else if(chance >= 100) { return true; } else { - if(Phaser.Math.random() * 100 >= chance) { + if(Math.random() * 100 >= chance) { return false; } else { return true; @@ -3008,9 +1211,9 @@ var Phaser; */ function (value, amount, max) { var diff; - value = Phaser.Math.abs(value); - amount = Phaser.Math.abs(amount); - max = Phaser.Math.abs(max); + value = Math.abs(value); + amount = Math.abs(amount); + max = Math.abs(max); diff = (value + amount) % max; return diff; }; @@ -3020,7 +1223,7 @@ var Phaser; * @return 1 or -1 */ function () { - return (Phaser.Math.random() > 0.5) ? 1 : -1; + return (Math.random() > 0.5) ? 1 : -1; }; GameMath.prototype.isOdd = /** * Returns true if the number given is odd. @@ -3098,7 +1301,7 @@ var Phaser; function (v, k) { var m = v.length - 1; var f = m * k; - var i = Phaser.Math.floor(f); + var i = Math.floor(f); if(k < 0) { return this.linear(v[0], v[1], f); } @@ -3117,7 +1320,7 @@ var Phaser; var b = 0; var n = v.length - 1; for(var i = 0; i <= n; i++) { - b += Phaser.Math.pow(1 - k, n - i) * Phaser.Math.pow(k, i) * v[i] * this.bernstein(n, i); + b += Math.pow(1 - k, n - i) * Math.pow(k, i) * v[i] * this.bernstein(n, i); } return b; }; @@ -3130,10 +1333,10 @@ var Phaser; function (v, k) { var m = v.length - 1; var f = m * k; - var i = Phaser.Math.floor(f); + var i = Math.floor(f); if(v[0] === v[m]) { if(k < 0) { - i = Phaser.Math.floor(f = m * (1 + k)); + i = Math.floor(f = m * (1 + k)); } return this.catmullRom(v[(i - 1 + m) % m], v[i], v[(i + 1) % m], v[(i + 2) % m], f - i); } else { @@ -3179,7 +1382,7 @@ var Phaser; return (2 * p1 - 2 * p2 + v0 + v1) * t3 + (-3 * p1 + 3 * p2 - 2 * v0 - v1) * t2 + v0 * t + p1; }; GameMath.prototype.difference = function (a, b) { - return Phaser.Math.abs(a - b); + return Math.abs(a - b); }; GameMath.prototype.random = /** * Generates a random number. Deterministic, meaning safe @@ -3219,7 +1422,7 @@ var Phaser; l = objects.length - startIndex; } if(l > 0) { - return objects[startIndex + Phaser.Math.floor(Phaser.Math.random() * l)]; + return objects[startIndex + Math.floor(Math.random() * l)]; } } return null; @@ -3266,7 +1469,7 @@ var Phaser; if (typeof frequency === "undefined") { frequency = 1.0; } var sin = sinAmplitude; var cos = cosAmplitude; - var frq = frequency * Phaser.Math.PI / length; + var frq = frequency * Math.PI / length; this.cosTable = []; this.sinTable = []; for(var c = 0; c < length; c++) { @@ -3310,7 +1513,7 @@ var Phaser; * @return */ function (dx, dy) { - return Phaser.Math.sqrt(dx * dx + dy * dy); + return Math.sqrt(dx * dx + dy * dy); }; GameMath.prototype.dotProduct = /** * Finds the dot product value of two vectors @@ -3332,7 +1535,7 @@ var Phaser; */ function (array) { for(var i = array.length - 1; i > 0; i--) { - var j = Phaser.Math.floor(Phaser.Math.random() * (i + 1)); + var j = Math.floor(Math.random() * (i + 1)); var temp = array[i]; array[i] = array[j]; array[j] = temp; @@ -3349,7 +1552,7 @@ var Phaser; function distanceBetween(x1, y1, x2, y2) { var dx = x1 - x2; var dy = y1 - y2; - return Phaser.Math.sqrt(dx * dx + dy * dy); + return Math.sqrt(dx * dx + dy * dy); }; GameMath.prototype.rotatePoint = /** * Rotates the point around the x/y coordinates given to the desired angle and distance @@ -3365,21 +1568,3477 @@ var Phaser; if (typeof asDegrees === "undefined") { asDegrees = false; } if (typeof distance === "undefined") { distance = null; } if(asDegrees) { - angle = angle * Phaser.GameMath.DEG_TO_RAD; + angle = angle * GameMath.DEG_TO_RAD; } // Get distance from origin to the point if(distance === null) { - distance = Phaser.Math.sqrt(((x1 - point.x) * (x1 - point.x)) + ((y1 - point.y) * (y1 - point.y))); + distance = Math.sqrt(((x1 - point.x) * (x1 - point.x)) + ((y1 - point.y) * (y1 - point.y))); } - point.x = x1 + distance * Phaser.Math.cos(angle); - point.y = y1 + distance * Phaser.Math.sin(angle); + point.x = x1 + distance * Math.cos(angle); + point.y = y1 + distance * Math.sin(angle); return point; }; return GameMath; })(); 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 - 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(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 - 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); + }; + 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; + /** + * 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._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; } + return Phaser.SpriteUtils.loadTexture(this._sprite, key, clearAnimations); + }; + 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) { + return Phaser.SpriteUtils.loadDynamicTexture(this._sprite, texture); + }; + 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.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); + } + 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 + }); + 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.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 * @@ -3406,19 +5065,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. @@ -3428,7 +5087,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. @@ -3438,7 +5097,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. @@ -3448,17 +5107,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.tilemap = /** * 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. @@ -3466,13 +5125,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. @@ -3482,14 +5138,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. @@ -3504,7 +5156,7 @@ var Phaser; 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); + return this._world.group.add(new Tilemap(this._game, key, mapData, format, resizeWorld, tileWidth, tileHeight)); }; GameObjectFactory.prototype.tween = /** * Create a tween object for a specific object. @@ -3525,37 +5177,37 @@ var Phaser; function (sprite) { return this._world.group.add(sprite); }; - GameObjectFactory.prototype.existingGeomSprite = /** + GameObjectFactory.prototype.existingTilemap = /** * 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. * @@ -3579,8 +5231,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 * @@ -3588,11 +5267,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. @@ -3606,54 +5283,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; @@ -3661,56 +5314,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", { @@ -3728,17 +5374,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; @@ -3758,28 +5403,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 { @@ -3790,9 +5435,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. @@ -3817,31 +5462,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 = /** @@ -3854,15 +5498,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; }; @@ -3875,11 +5519,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 = /** @@ -3894,7 +5538,7 @@ var Phaser; */ function (index, order) { if (typeof index === "undefined") { index = "y"; } - if (typeof order === "undefined") { order = Phaser.Group.ASCENDING; } + if (typeof order === "undefined") { order = Group.ASCENDING; } this._sortIndex = index; this._sortOrder = order; this.members.sort(this.sortHandler); @@ -3906,17 +5550,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; } } } @@ -3928,17 +5571,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](); } } } @@ -3949,15 +5591,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); } } } @@ -3969,15 +5610,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); } } } @@ -3990,14 +5630,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; @@ -4009,14 +5648,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; @@ -4028,12 +5665,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; @@ -4045,12 +5681,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; @@ -4062,12 +5697,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; @@ -4078,21 +5712,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. @@ -4100,21 +5733,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. @@ -4124,13 +5756,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. @@ -4143,12 +5775,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(); } } }; @@ -4160,16 +5791,16 @@ 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 = {})); /// @@ -4536,1222 +6167,227 @@ var Phaser; Phaser.Signal = Signal; })(Phaser || (Phaser = {})); /// +/// /** -* Phaser - CollisionMask +* Phaser - Sound +* +* A Sound file, used by the Game.SoundManager for playback. */ var Phaser; (function (Phaser) { - var CollisionMask = (function () { + var Sound = (function () { /** - * CollisionMask constructor. Creates a new CollisionMask for the given GameObject. - * - * @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. + * Sound constructor + * @param context {object} The AudioContext instance. + * @param gainNode {object} Gain node instance. + * @param data {object} Sound data. + * @param [volume] {number} volume of this sound when playing. + * @param [loop] {boolean} loop this sound when playing? (Default to false) */ - function CollisionMask(game, parent, x, y, width, height) { - /** - * Geom type of this sprite. (available: QUAD, POINT, CIRCLE, LINE, RECTANGLE, POLYGON) - * @type {number} - */ - this.type = 0; - 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; - } - 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. - */ - function () { - this.last.x = this.x; - this.last.y = this.y; - }; - 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, Phaser.Math.PI * 2); - this._parent.context.fill(); - this._parent.context.closePath(); + function Sound(context, gainNode, data, volume, loop) { + if (typeof volume === "undefined") { volume = 1; } + if (typeof loop === "undefined") { loop = false; } + this.loop = false; + this.isPlaying = false; + this.isDecoding = false; + this._context = context; + this._gainNode = gainNode; + this._buffer = data; + this._volume = volume; + this.loop = loop; + // Local volume control + if(this._context !== null) { + this._localGainNode = this._context.createGainNode(); + this._localGainNode.connect(this._gainNode); + this._localGainNode.gain.value = this._volume; } - }; - 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; + if(this._buffer === null) { + this.isDecoding = true; } else { - return false; + this.play(); + } + } + Sound.prototype.setDecodedBuffer = function (data) { + this._buffer = data; + this.isDecoding = false; + //this.play(); + }; + Sound.prototype.play = /** + * Play this sound. + */ + function () { + if(this._buffer === null || this.isDecoding === true) { + return; + } + this._sound = this._context.createBufferSource(); + this._sound.buffer = this._buffer; + this._sound.connect(this._localGainNode); + if(this.loop) { + this._sound.loop = true; + } + this._sound.noteOn(0)// the zero is vitally important, crashes iOS6 without it + ; + this.duration = this._sound.buffer.duration; + this.isPlaying = true; + }; + Sound.prototype.stop = /** + * Stop playing this sound. + */ + function () { + if(this.isPlaying === true) { + this.isPlaying = false; + this._sound.noteOff(0); } }; - Object.defineProperty(CollisionMask.prototype, "hullWidth", { + Sound.prototype.mute = /** + * Mute the sound. + */ + function () { + this._localGainNode.gain.value = 0; + }; + Sound.prototype.unmute = /** + * Enable the sound. + */ + function () { + this._localGainNode.gain.value = this._volume; + }; + Object.defineProperty(Sound.prototype, "volume", { get: function () { - if(this.deltaX > 0) { - return this.width + this.deltaX; - } else { - return this.width - this.deltaX; - } - }, - 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; + return this._volume; }, set: function (value) { - //this.quad.height = value; - this._ref.height = value; + this._volume = value; + this._localGainNode.gain.value = this._volume; }, 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; + return Sound; })(); - Phaser.CollisionMask = CollisionMask; + Phaser.Sound = Sound; })(Phaser || (Phaser = {})); /// -/// -/// -/// +/// /** -* Phaser - GameObject +* Phaser - SoundManager * -* 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. +* This is an embroyonic web audio sound management class. There is a lot of work still to do here. */ var Phaser; (function (Phaser) { - var GameObject = (function (_super) { - __extends(GameObject, _super); + var SoundManager = (function () { /** - * 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. + * SoundManager constructor + * Create a new SoundManager. */ - 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); + function SoundManager(game) { /** - * Angle of this object. - * @type {number} + * Reference to AudioContext instance. */ - 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 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 MicroPoint(1, 1); - this.last = new 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 = Collision.NONE; - this.wasTouching = Collision.NONE; - this.allowCollisions = Collision.ANY; - this.velocity = new MicroPoint(); - this.acceleration = new MicroPoint(); - this.drag = new MicroPoint(); - this.maxVelocity = new MicroPoint(10000, 10000); - this.angle = 0; - this.angularVelocity = 0; - this.angularAcceleration = 0; - this.angularDrag = 0; - this.maxAngular = 10000; - this.cameraBlacklist = []; - this.scrollFactor = new MicroPoint(1, 1); - this.collisionMask = new 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 == Phaser.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(); - } - }; - 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 - */ - 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 = Phaser.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); - } - }; - GameObject.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); - } - }; - 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 - Motion -* -* The Motion class contains lots of useful functions for moving game objects around in world space. -*/ -var Phaser; -(function (Phaser) { - var Motion = (function () { - function Motion(game) { + this._context = null; this._game = game; + if(game.device.webaudio == true) { + if(!!window['AudioContext']) { + this._context = new window['AudioContext'](); + } else if(!!window['webkitAudioContext']) { + this._context = new window['webkitAudioContext'](); + } + if(this._context !== null) { + this._gainNode = this._context.createGainNode(); + this._gainNode.connect(this._context.destination); + this._volume = 1; + } + } } - Motion.prototype.computeVelocity = /** - * 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. + SoundManager.prototype.mute = /** + * Mute sounds. */ - 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; + function () { + this._gainNode.gain.value = 0; + }; + SoundManager.prototype.unmute = /** + * Enable sounds. + */ + function () { + this._gainNode.gain.value = this._volume; + }; + Object.defineProperty(SoundManager.prototype, "volume", { + get: function () { + return this._volume; + }, + set: function (value) { + this._volume = value; + this._gainNode.gain.value = this._volume; + }, + enumerable: true, + configurable: true + }); + SoundManager.prototype.decode = /** + * Decode a sound with its assets key. + * @param key {string} Assets key of the sound to be decoded. + * @param callback {function} This will be invoked when finished decoding. + * @param [sound] {Sound} its bufer will be set to decoded data. + */ + function (key, callback, sound) { + if (typeof callback === "undefined") { callback = null; } + if (typeof sound === "undefined") { sound = null; } + var soundData = this._game.cache.getSound(key); + if(soundData) { + if(this._game.cache.isSoundDecoded(key) === false) { + var that = this; + this._context.decodeAudioData(soundData, function (buffer) { + that._game.cache.decodedSound(key, buffer); + if(sound) { + sound.setDecodedBuffer(buffer); + } + callback(); + }); + } + } + }; + SoundManager.prototype.play = /** + * Play a sound with its assets key. + * @param key {string} Assets key of the sound you want to play. + * @param [volume] {number} volume of the sound you want to play. + * @param [loop] {boolean} loop when it finished playing? (Default to false) + * @return {Sound} The playing sound object. + */ + function (key, volume, loop) { + if (typeof volume === "undefined") { volume = 1; } + if (typeof loop === "undefined") { loop = false; } + if(this._context === null) { + return; + } + var soundData = this._game.cache.getSound(key); + if(soundData) { + // Does the sound need decoding? + if(this._game.cache.isSoundDecoded(key) === true) { + return new Phaser.Sound(this._context, this._gainNode, soundData, volume, loop); } else { - Velocity = 0; + var tempSound = new Phaser.Sound(this._context, this._gainNode, null, volume, loop); + // this is an async process, so we can return the Sound object anyway, it just won't be playing yet + this.decode(key, function () { + return tempSound.play(); + }, tempSound); + return tempSound; } } - if((Velocity != 0) && (Max != 10000)) { - if(Velocity > Max) { - Velocity = Max; - } else if(Velocity < -Max) { - Velocity = -Max; - } - } - 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((Phaser.Math.cos(a) * speed), (Phaser.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 = Phaser.Math.cos(a) * speed; - source.velocity.y = Phaser.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 = Phaser.Math.cos(a) * speed; - source.acceleration.y = Phaser.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 = Phaser.Math.cos(a) * speed; - source.velocity.y = Phaser.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 = Phaser.Math.cos(a) * speed; - source.acceleration.y = Phaser.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 = Phaser.Math.cos(a) * speed; - source.velocity.y = Phaser.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 = Phaser.Math.cos(a) * speed; - source.acceleration.y = Phaser.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(Phaser.Math.atan2(dy, dx)); - } else { - return Phaser.Math.atan2(dy, dx); - } - }; - 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) - */ - 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(Phaser.Math.atan2(dy, dx)); - } else { - return Phaser.Math.atan2(dy, dx); - } - }; - 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 - */ - 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(Phaser.Math.cos(a) * speed, Phaser.Math.sin(a) * speed); - }; - 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) - */ - 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(Phaser.Math.atan2(dy, dx)); - } else { - return Phaser.Math.atan2(dy, dx); - } - }; - return Motion; + return SoundManager; })(); - Phaser.Motion = Motion; + Phaser.SoundManager = SoundManager; })(Phaser || (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." @@ -5759,7 +6395,7 @@ var Phaser; */ var Phaser; (function (Phaser) { - Phaser.VERSION = 'Phaser version 0.9.6'; + Phaser.VERSION = 'Phaser version 1.0.0'; })(Phaser || (Phaser = {})); /// /** @@ -5776,6 +6412,7 @@ var Phaser; * StageScaleMode constructor */ function StageScaleMode(game) { + var _this = this; /** * Stage height when start the game. * @type {number} @@ -5871,7 +6508,7 @@ var Phaser; * The core update loop, called by Phaser.Stage */ function () { - if(this._game.stage.scaleMode !== Phaser.StageScaleMode.NO_SCALE && (window.innerWidth !== this.width || window.innerHeight !== this.height)) { + if(this._game.stage.scaleMode !== StageScaleMode.NO_SCALE && (window.innerWidth !== this.width || window.innerHeight !== this.height)) { this.refresh(); } }; @@ -5899,7 +6536,7 @@ var Phaser; } else { this.enterPortrait.dispatch(this.orientation); } - if(this._game.stage.scaleMode !== Phaser.StageScaleMode.NO_SCALE) { + if(this._game.stage.scaleMode !== StageScaleMode.NO_SCALE) { this.refresh(); } }; @@ -5917,7 +6554,7 @@ var Phaser; } else { this.enterPortrait.dispatch(this.orientation); } - if(this._game.stage.scaleMode !== Phaser.StageScaleMode.NO_SCALE) { + if(this._game.stage.scaleMode !== StageScaleMode.NO_SCALE) { this.refresh(); } }; @@ -5958,7 +6595,7 @@ var Phaser; if(window.innerHeight > this._startHeight || this._iterations < 0) { // Set minimum height of content to new window height document.documentElement.style.minHeight = window.innerHeight + 'px'; - if(this._game.stage.scaleMode == Phaser.StageScaleMode.EXACT_FIT) { + if(this._game.stage.scaleMode == StageScaleMode.EXACT_FIT) { if(this.maxWidth && window.innerWidth > this.maxWidth) { this.width = this.maxWidth; } else { @@ -5969,10 +6606,10 @@ var Phaser; } else { this.height = window.innerHeight; } - } else if(this._game.stage.scaleMode == Phaser.StageScaleMode.SHOW_ALL) { - var multiplier = Phaser.Math.min((window.innerHeight / this._game.stage.height), (window.innerWidth / this._game.stage.width)); - this.width = Phaser.Math.round(this._game.stage.width * multiplier); - this.height = Phaser.Math.round(this._game.stage.height * multiplier); + } else if(this._game.stage.scaleMode == StageScaleMode.SHOW_ALL) { + var multiplier = Math.min((window.innerHeight / this._game.stage.height), (window.innerWidth / this._game.stage.width)); + this.width = Math.round(this._game.stage.width * multiplier); + this.height = Math.round(this._game.stage.height * multiplier); if(this.maxWidth && this.width > this.maxWidth) { this.width = this.maxWidth; } @@ -6045,12 +6682,12 @@ var Phaser; if(this._fade == null) { this.colorCycle(); } - this._color1.r = Phaser.Math.round(this._color1.r); - this._color1.g = Phaser.Math.round(this._color1.g); - this._color1.b = Phaser.Math.round(this._color1.b); - this._color2.r = Phaser.Math.round(this._color2.r); - this._color2.g = Phaser.Math.round(this._color2.g); - this._color2.b = Phaser.Math.round(this._color2.b); + this._color1.r = Math.round(this._color1.r); + this._color1.g = Math.round(this._color1.g); + this._color1.b = Math.round(this._color1.b); + this._color2.r = Math.round(this._color2.r); + this._color2.g = Math.round(this._color2.g); + this._color2.b = Math.round(this._color2.b); }; BootScreen.prototype.render = /** * Render BootScreen. @@ -6087,9 +6724,9 @@ var Phaser; function () { this._fade = this._game.add.tween(this._color2); this._fade.to({ - r: Phaser.Math.random() * 250, - g: Phaser.Math.random() * 250, - b: Phaser.Math.random() * 250 + r: Math.random() * 250, + g: Math.random() * 250, + b: Math.random() * 250 }, 3000, Phaser.Easing.Linear.None); this._fade.onComplete.add(this.colorCycle, this); this._fade.start(); @@ -6146,9 +6783,9 @@ var Phaser; * Update background color. */ function () { - this._color.r = Phaser.Math.round(this._color.r); - this._color.g = Phaser.Math.round(this._color.g); - this._color.b = Phaser.Math.round(this._color.b); + this._color.r = Math.round(this._color.r); + this._color.g = Math.round(this._color.g); + this._color.b = Math.round(this._color.b); }; PauseScreen.prototype.render = /** * Render PauseScreen. @@ -6158,8 +6795,8 @@ var Phaser; this._game.stage.context.fillStyle = 'rgba(0, 0, 0, 0.4)'; this._game.stage.context.fillRect(0, 0, this._game.stage.width, this._game.stage.height); // Draw a 'play' arrow - var arrowWidth = Phaser.Math.round(this._game.stage.width / 2); - var arrowHeight = Phaser.Math.round(this._game.stage.height / 2); + var arrowWidth = Math.round(this._game.stage.width / 2); + var arrowHeight = Math.round(this._game.stage.height / 2); var sx = this._game.stage.centerX - arrowWidth / 2; var sy = this._game.stage.centerY - arrowHeight / 2; this._game.stage.context.beginPath(); @@ -6224,6 +6861,7 @@ var Phaser; * @param height {number} Height of the stage. */ function Stage(game, parent, width, height) { + var _this = this; /** * Background color of the stage (defaults to black) * @type {string} @@ -6266,12 +6904,12 @@ var Phaser; }; this.context = this.canvas.getContext('2d'); this.offset = this.getOffset(this.canvas); - this.bounds = new 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 = StageScaleMode.NO_SCALE; - this.scale = new StageScaleMode(this._game); - this._bootScreen = new BootScreen(this._game); - this._pauseScreen = new PauseScreen(this._game, width, height); + this.scaleMode = Phaser.StageScaleMode.NO_SCALE; + this.scale = new Phaser.StageScaleMode(this._game); + this._bootScreen = new Phaser.BootScreen(this._game); + this._pauseScreen = new Phaser.PauseScreen(this._game, width, height); document.addEventListener('visibilitychange', function (event) { return _this.visibilityChange(event); }, false); @@ -6340,7 +6978,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. @@ -6412,14 +7050,14 @@ var Phaser; }); Object.defineProperty(Stage.prototype, "randomX", { get: function () { - return Phaser.Math.round(Phaser.Math.random() * this.bounds.width); + return Math.round(Math.random() * this.bounds.width); }, enumerable: true, configurable: true }); Object.defineProperty(Stage.prototype, "randomY", { get: function () { - return Phaser.Math.round(Phaser.Math.random() * this.bounds.height); + return Math.round(Math.random() * this.bounds.height); }, enumerable: true, configurable: true @@ -6537,13 +7175,13 @@ var Phaser; //this.now = Date.now(); // mark this.delta = this.now - this.time// elapsedMS ; - this.msMin = Phaser.Math.min(this.msMin, this.delta); - this.msMax = Phaser.Math.max(this.msMax, this.delta); + this.msMin = Math.min(this.msMin, this.delta); + this.msMax = Math.max(this.msMax, this.delta); this.frames++; if(this.now > this._timeLastSecond + 1000) { - this.fps = Phaser.Math.round((this.frames * 1000) / (this.now - this._timeLastSecond)); - this.fpsMin = Phaser.Math.min(this.fpsMin, this.fps); - this.fpsMax = Phaser.Math.max(this.fpsMax, this.fps); + this.fps = Math.round((this.frames * 1000) / (this.now - this._timeLastSecond)); + this.fpsMin = Math.min(this.fpsMin, this.fps); + this.fpsMax = Math.max(this.fpsMax, this.fps); this._timeLastSecond = this.now; this.frames = 0; } @@ -6579,7 +7217,101 @@ var Phaser; })(); Phaser.Time = Time; })(Phaser || (Phaser = {})); +/// +/// +/** +* Phaser - TweenManager +* +* The Game has a single instance of the TweenManager through which all Tween objects are created and updated. +* Tweens are hooked into the game clock and pause system, adjusting based on the game state. +* TweenManager is based heavily on tween.js by sole (http://soledadpenades.com). +* I converted it to TypeScript, swapped the callbacks for signals and patched a few issues with regard +* to properties and completion errors. Please see https://github.com/sole/tween.js for a full list of contributors. +*/ +var Phaser; +(function (Phaser) { + var TweenManager = (function () { + /** + * TweenManager constructor + * @param game {Game} A reference to the current Game. + */ + function TweenManager(game) { + this._game = game; + this._tweens = []; + } + TweenManager.prototype.getAll = /** + * Get all the tween objects in an array. + * @return {Phaser.Tween[]} Array with all tween objects. + */ + function () { + return this._tweens; + }; + TweenManager.prototype.removeAll = /** + * Remove all tween objects. + */ + function () { + this._tweens.length = 0; + }; + TweenManager.prototype.create = /** + * Create a tween object for a specific object. + * + * @param object {object} Object you wish the tween will affect. + * @return {Phaser.Tween} The newly created tween object. + */ + function (object) { + return new Phaser.Tween(object, this._game); + }; + TweenManager.prototype.add = /** + * Add an exist tween object to the manager. + * + * @param tween {Phaser.Tween} The tween object you want to add. + * @return {Phaser.Tween} The tween object you added to the manager. + */ + function (tween) { + tween.parent = this._game; + this._tweens.push(tween); + return tween; + }; + TweenManager.prototype.remove = /** + * Remove a tween from this manager. + * + * @param tween {Phaser.Tween} The tween object you want to remove. + */ + function (tween) { + var i = this._tweens.indexOf(tween); + if(i !== -1) { + this._tweens.splice(i, 1); + } + }; + TweenManager.prototype.update = /** + * Update all the tween objects you added to this manager. + * + * @return {boolean} Return false if there's no tween to update, otherwise return true. + */ + function () { + if(this._tweens.length === 0) { + return false; + } + var i = 0; + var numTweens = this._tweens.length; + while(i < numTweens) { + if(this._tweens[i].update(this._game.time.now)) { + i++; + } else { + this._tweens.splice(i, 1); + numTweens--; + } + } + return true; + }; + return TweenManager; + })(); + Phaser.TweenManager = TweenManager; +})(Phaser || (Phaser = {})); /// +/// +/// +/// /** * Phaser - World * @@ -6601,27 +7333,18 @@ var Phaser; */ function World(game, width, height) { this._game = game; - this.cameras = new CameraManager(this._game, 0, 0, width, height); - this.group = new Group(this._game, 0); - this.bounds = new Rectangle(0, 0, width, height); + this.cameras = new Phaser.CameraManager(this._game, 0, 0, width, height); + this.group = new Phaser.Group(this._game, 0); + this.bounds = new Phaser.Rectangle(0, 0, width, height); 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. */ @@ -6629,29 +7352,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; @@ -6688,40 +7404,18 @@ var Phaser; }); Object.defineProperty(World.prototype, "randomX", { get: function () { - return Phaser.Math.round(Phaser.Math.random() * this.bounds.width); + return Math.round(Math.random() * this.bounds.width); }, enumerable: true, configurable: true }); Object.defineProperty(World.prototype, "randomY", { get: function () { - return Phaser.Math.round(Phaser.Math.random() * this.bounds.height); + return Math.round(Math.random() * this.bounds.height); }, 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. * @@ -6730,105 +7424,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; @@ -7251,233 +7846,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 Phaser.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[~~(Phaser.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. @@ -7603,4911 +7971,8 @@ var Phaser; Phaser.RequestAnimationFrame = RequestAnimationFrame; })(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 MicroPoint(-100, -100); - this.maxParticleSpeed = new MicroPoint(100, 100); - this.minRotation = -360; - this.maxRotation = 360; - this.gravity = 0; - this.particleClass = null; - this.particleDrag = new 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 MicroPoint(); - } - 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); - }; - 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 = Phaser.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 = Phaser.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 = Phaser.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 = Phaser.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 = Phaser.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 = Phaser.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 = Phaser.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 = Phaser.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 Vector2(this.x, this.y), points); - this.type = Phaser.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 == Phaser.GeomSprite.UNASSIGNED) { - return; - } else if(this.type == Phaser.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 == Phaser.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 == Phaser.GeomSprite.POINT) { - this.point.x = this.x; - this.point.y = this.y; - } else if(this.type == Phaser.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 == Phaser.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) { - 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 = Phaser.Math.round(this._dx); - this._dy = Phaser.Math.round(this._dy); - this._dw = Phaser.Math.round(this._dw); - this._dh = Phaser.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 == Phaser.GeomSprite.CIRCLE) { - this.context.beginPath(); - this.context.arc(this._dx, this._dy, this.circle.radius, 0, Phaser.Math.PI * 2); - if(this.renderOutline) { - this.context.stroke(); - } - if(this.renderFill) { - this.context.fill(); - } - this.context.closePath(); - } else if(this.type == Phaser.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 == Phaser.GeomSprite.POINT) { - this.context.fillRect(this._dx, this._dy, 2, 2); - } else if(this.type == Phaser.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 == Phaser.GeomSprite.CIRCLE && source.type == Phaser.GeomSprite.CIRCLE) { - return Phaser.Collision.circleToCircle(this.circle, source.circle).result; - } - // Circle vs. Rect - if(this.type == Phaser.GeomSprite.CIRCLE && source.type == Phaser.GeomSprite.RECTANGLE) { - return Phaser.Collision.circleToRectangle(this.circle, source.rect).result; - } - // Circle vs. Point - if(this.type == Phaser.GeomSprite.CIRCLE && source.type == Phaser.GeomSprite.POINT) { - return Phaser.Collision.circleContainsPoint(this.circle, source.point).result; - } - // Circle vs. Line - if(this.type == Phaser.GeomSprite.CIRCLE && source.type == Phaser.GeomSprite.LINE) { - return Phaser.Collision.lineToCircle(source.line, this.circle).result; - } - // Rect vs. Rect - if(this.type == Phaser.GeomSprite.RECTANGLE && source.type == Phaser.GeomSprite.RECTANGLE) { - return Phaser.Collision.rectangleToRectangle(this.rect, source.rect).result; - } - // Rect vs. Circle - if(this.type == Phaser.GeomSprite.RECTANGLE && source.type == Phaser.GeomSprite.CIRCLE) { - return Phaser.Collision.circleToRectangle(source.circle, this.rect).result; - } - // Rect vs. Point - if(this.type == Phaser.GeomSprite.RECTANGLE && source.type == Phaser.GeomSprite.POINT) { - return Phaser.Collision.pointToRectangle(source.point, this.rect).result; - } - // Rect vs. Line - if(this.type == Phaser.GeomSprite.RECTANGLE && source.type == Phaser.GeomSprite.LINE) { - return Phaser.Collision.lineToRectangle(source.line, this.rect).result; - } - // Point vs. Point - if(this.type == Phaser.GeomSprite.POINT && source.type == Phaser.GeomSprite.POINT) { - return this.point.equals(source.point); - } - // Point vs. Circle - if(this.type == Phaser.GeomSprite.POINT && source.type == Phaser.GeomSprite.CIRCLE) { - return Phaser.Collision.circleContainsPoint(source.circle, this.point).result; - } - // Point vs. Rect - if(this.type == Phaser.GeomSprite.POINT && source.type == Phaser.GeomSprite.RECTANGLE) { - return Phaser.Collision.pointToRectangle(this.point, source.rect).result; - } - // Point vs. Line - if(this.type == Phaser.GeomSprite.POINT && source.type == Phaser.GeomSprite.LINE) { - return source.line.isPointOnLine(this.point.x, this.point.y); - } - // Line vs. Line - if(this.type == Phaser.GeomSprite.LINE && source.type == Phaser.GeomSprite.LINE) { - return Phaser.Collision.lineSegmentToLineSegment(this.line, source.line).result; - } - // Line vs. Circle - if(this.type == Phaser.GeomSprite.LINE && source.type == Phaser.GeomSprite.CIRCLE) { - return Phaser.Collision.lineToCircle(this.line, source.circle).result; - } - // Line vs. Rect - if(this.type == Phaser.GeomSprite.LINE && source.type == Phaser.GeomSprite.RECTANGLE) { - return Phaser.Collision.lineSegmentToRectangle(this.line, source.rect).result; - } - // Line vs. Point - if(this.type == Phaser.GeomSprite.LINE && source.type == Phaser.GeomSprite.POINT) { - return this.line.isPointOnLine(source.point.x, source.point.y); - } - return false; - }; - return GeomSprite; - })(Phaser.GameObject); - Phaser.GeomSprite = GeomSprite; -})(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 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) * (Phaser.Math.PI / 180)); - } - this._dx = -(this._dw / 2); - this._dy = -(this._dh / 2); - if(this.flipped == true) { - this.context.scale(-1, 1); - } - } - this._sx = Phaser.Math.round(this._sx); - this._sy = Phaser.Math.round(this._sy); - this._sw = Phaser.Math.round(this._sw); - this._sh = Phaser.Math.round(this._sh); - this._dx = Phaser.Math.round(this._dx); - this._dy = Phaser.Math.round(this._dy); - this._dw = Phaser.Math.round(this._dw); - this._dh = Phaser.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 - }; - 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 - 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 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; - })(); - 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 & 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, Phaser.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, Phaser.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 || (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 Quad(x, y, width, height); - this._B = new Quad(x, y, width, height); - this._C = new Quad(x, y, width, height); - this._D = new Quad(x, y, width, height); - this._scroll = new MicroPoint(); - this._bounds = new Quad(x, y, width, height); - this.scrollSpeed = new 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 = Phaser.Math.floor(srcX); - srcY = Phaser.Math.floor(srcY); - srcW = Phaser.Math.floor(srcW); - srcH = Phaser.Math.floor(srcH); - offsetX = Phaser.Math.floor(offsetX + this._bounds.x); - offsetY = Phaser.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} - */ - 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; - } - } - } - 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); - } - }; - 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. - */ - 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) { - return false; - } - // Alpha - if(this.alpha !== 1) { - var globalAlpha = this.context.globalAlpha; - this.context.globalAlpha = this.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; - // 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 * (Phaser.Math.PI / 180)); - } - this._dx = -(this._dw / 2); - this._dy = -(this._dh / 2); - if(this.flipped == true) { - this.context.scale(-1, 1); - } - } - this._dx = Phaser.Math.round(this._dx); - this._dy = Phaser.Math.round(this._dy); - this._dw = Phaser.Math.round(this._dw); - this._dh = Phaser.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(globalAlpha > -1) { - this.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 = Phaser.Math.ceil(this._texture.width / regionWidth) * regionWidth; - var tileHeight = Phaser.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; -})(Phaser || (Phaser = {})); -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/** -* 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 -*/ -var Phaser; -(function (Phaser) { - var Game = (function () { - /** - * 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. - */ - function Game(callbackContext, parent, width, height, initCallback, createCallback, updateCallback, renderCallback, destroyCallback) { - if (typeof parent === "undefined") { parent = ''; } - if (typeof width === "undefined") { width = 800; } - if (typeof height === "undefined") { height = 600; } - if (typeof initCallback === "undefined") { initCallback = null; } - if (typeof createCallback === "undefined") { createCallback = null; } - if (typeof updateCallback === "undefined") { updateCallback = null; } - if (typeof renderCallback === "undefined") { renderCallback = null; } - if (typeof destroyCallback === "undefined") { destroyCallback = null; } - /** - * Max allowable accumulation. - * @type {number} - */ - this._maxAccumulation = 32; - /** - * Total number of milliseconds elapsed since last update loop. - * @type {number} - */ - this._accumulator = 0; - /** - * Milliseconds of time per step of the game loop. - * @type {number} - */ - this._step = 0; - /** - * Whether loader complete loading or not. - * @type {boolean} - */ - this._loadComplete = false; - /** - * Game is paused? - * @type {boolean} - */ - this._paused = false; - /** - * The state to be switched to in the next frame. - * @type {State} - */ - this._pendingState = null; - /** - * The current State object (defaults to null) - * @type {State} - */ - this.state = null; - /** - * This will be called when init states. (loading assets...) - * @type {function} - */ - this.onInitCallback = null; - /** - * This will be called when create states. (setup states...) - * @type {function} - */ - this.onCreateCallback = null; - /** - * This will be called when update states. - * @type {function} - */ - this.onUpdateCallback = null; - /** - * This will be called when render states. - * @type {function} - */ - this.onRenderCallback = null; - /** - * This will be called when states paused. - * @type {function} - */ - this.onPausedCallback = null; - /** - * This will be called when the state is destroyed (i.e. swapping to a new state) - * @type {function} - */ - this.onDestroyCallback = null; - /** - * Whether the game engine is booted, aka available. - * @type {boolean} - */ - this.isBooted = false; - /** - * Is game running or paused? - * @type {boolean} - */ - this.isRunning = false; - this.callbackContext = callbackContext; - this.onInitCallback = initCallback; - this.onCreateCallback = createCallback; - this.onUpdateCallback = updateCallback; - this.onRenderCallback = renderCallback; - this.onDestroyCallback = destroyCallback; - if(document.readyState === 'complete' || document.readyState === 'interactive') { - setTimeout(function () { - return _this.boot(parent, width, height); - }); - } else { - document.addEventListener('DOMContentLoaded', function () { - return _this.boot(parent, width, height); - }, false); - window.addEventListener('load', function () { - return _this.boot(parent, width, height); - }, false); - } - } - Game.prototype.boot = /** - * 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. - */ - function (parent, width, height) { - var _this = this; - if(this.isBooted == true) { - return; - } - if(!document.body) { - window.setTimeout(function () { - return _this.boot(parent, width, height); - }, 13); - } else { - this.device = new Phaser.Device(); - this.motion = new Phaser.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.loader = new Phaser.Loader(this, this.loadComplete); - this.time = new Phaser.Time(this); - this.tweens = new Phaser.TweenManager(this); - this.input = new Phaser.Input(this); - this.rnd = new Phaser.RandomDataGenerator([ - (Date.now() * Phaser.Math.random()).toString() - ]); - this.verlet = new Phaser.Verlet.VerletManager(this, width, height); - this.framerate = 60; - this.isBooted = true; - this.input.start(); - // Display the default game screen? - if(this.onInitCallback == null && this.onCreateCallback == null && this.onUpdateCallback == null && this.onRenderCallback == null && this._pendingState == null) { - this._raf = new Phaser.RequestAnimationFrame(this, this.bootLoop); - } else { - this.isRunning = true; - this._loadComplete = false; - this._raf = new Phaser.RequestAnimationFrame(this, this.loop); - if(this._pendingState) { - this.switchState(this._pendingState, false, false); - } else { - this.startState(); - } - } - } - }; - Game.prototype.loadComplete = /** - * Called when the loader has finished after init was run. - */ - function () { - this._loadComplete = true; - }; - Game.prototype.bootLoop = /** - * Game loop method will be called when it's booting. - */ - function () { - this.tweens.update(); - this.input.update(); - this.stage.update(); - }; - Game.prototype.pausedLoop = /** - * Game loop method will be called when it's paused. - */ - function () { - this.tweens.update(); - this.input.update(); - this.stage.update(); - if(this.onPausedCallback !== null) { - this.onPausedCallback.call(this.callbackContext); - } - }; - Game.prototype.loop = /** - * Game loop method will be called when it's running. - */ - function () { - 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; - } - while(this._accumulator >= this._step) { - this.time.elapsed = this.time.timeScale * (this._step / 1000); - this.world.update(); - this._accumulator = this._accumulator - this._step; - } - if(this._loadComplete && this.onUpdateCallback) { - this.onUpdateCallback.call(this.callbackContext); - } - this.world.render(); - if(this._loadComplete && this.onRenderCallback) { - this.onRenderCallback.call(this.callbackContext); - } - }; - Game.prototype.startState = /** - * Start current state. - */ - function () { - if(this.onInitCallback !== null) { - this.loader.reset(); - this.onInitCallback.call(this.callbackContext); - // Is the loader empty? - if(this.loader.queueSize == 0) { - if(this.onCreateCallback !== null) { - this.onCreateCallback.call(this.callbackContext); - } - this._loadComplete = true; - } - } else { - // No init? Then there was nothing to load either - if(this.onCreateCallback !== null) { - this.onCreateCallback.call(this.callbackContext); - } - this._loadComplete = true; - } - }; - Game.prototype.setCallbacks = /** - * 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. - */ - function (initCallback, createCallback, updateCallback, renderCallback, destroyCallback) { - if (typeof initCallback === "undefined") { initCallback = null; } - if (typeof createCallback === "undefined") { createCallback = null; } - if (typeof updateCallback === "undefined") { updateCallback = null; } - if (typeof renderCallback === "undefined") { renderCallback = null; } - if (typeof destroyCallback === "undefined") { destroyCallback = null; } - this.onInitCallback = initCallback; - this.onCreateCallback = createCallback; - this.onUpdateCallback = updateCallback; - this.onRenderCallback = renderCallback; - this.onDestroyCallback = destroyCallback; - }; - Game.prototype.switchState = /** - * 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) - */ - function (state, clearWorld, clearCache) { - if (typeof clearWorld === "undefined") { clearWorld = true; } - if (typeof clearCache === "undefined") { clearCache = false; } - if(this.isBooted == false) { - this._pendingState = state; - return; - } - // Destroy current state? - if(this.onDestroyCallback !== null) { - this.onDestroyCallback.call(this.callbackContext); - } - this.input.reset(true); - // Prototype? - if(typeof state === 'function') { - this.state = new state(this); - } - // Ok, have we got the right functions? - if(this.state['create'] || this.state['update']) { - this.callbackContext = this.state; - this.onInitCallback = null; - this.onCreateCallback = null; - this.onUpdateCallback = null; - this.onRenderCallback = null; - this.onPausedCallback = null; - this.onDestroyCallback = null; - // Bingo, let's set them up - if(this.state['init']) { - this.onInitCallback = this.state['init']; - } - if(this.state['create']) { - this.onCreateCallback = this.state['create']; - } - if(this.state['update']) { - this.onUpdateCallback = this.state['update']; - } - if(this.state['render']) { - this.onRenderCallback = this.state['render']; - } - if(this.state['paused']) { - this.onPausedCallback = this.state['paused']; - } - if(this.state['destroy']) { - this.onDestroyCallback = this.state['destroy']; - } - if(clearWorld) { - this.world.destroy(); - if(clearCache == true) { - this.cache.destroy(); - } - } - this._loadComplete = false; - this.startState(); - } else { - throw new Error("Invalid State object given. Must contain at least a create or update function."); - } - }; - Game.prototype.destroy = /** - * Nuke the whole game from orbit - */ - function () { - this.callbackContext = null; - this.onInitCallback = null; - this.onCreateCallback = null; - this.onUpdateCallback = null; - this.onRenderCallback = null; - this.onPausedCallback = null; - this.onDestroyCallback = null; - this.cache = null; - this.input = null; - this.loader = null; - this.sound = null; - this.stage = null; - this.time = null; - this.world = null; - this.isBooted = false; - }; - Object.defineProperty(Game.prototype, "paused", { - get: function () { - return this._paused; - }, - set: function (value) { - if(value == true && this._paused == false) { - this._paused = true; - this._raf.callback = this.pausedLoop; - } else if(value == false && this._paused == true) { - this._paused = false; - //this.time.time = window.performance.now ? (performance.now() + performance.timing.navigationStart) : Date.now(); - this.input.reset(); - if(this.isRunning == false) { - this._raf.callback = this.bootLoop; - } else { - this._raf.callback = this.loop; - } - } - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Game.prototype, "framerate", { - get: function () { - return 1000 / this._step; - }, - set: function (value) { - this._step = 1000 / value; - if(this._maxAccumulation < this._step) { - this._maxAccumulation = this._step; - } - }, - 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 () { - return this.world.cameras.current; - }, - enumerable: true, - configurable: true - }); - return Game; - })(); - Phaser.Game = Game; -})(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 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; - } - 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); - }; - Point.prototype.copyTo = /** - * Copies the x and y values from this Point 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; - }; - 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.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 () { - return '[{Point (x=' + this.x + ' y=' + this.y + ')}]'; - }; - return Point; - })(); - 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 Phaser.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 Phaser.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.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 = {})); -var Phaser; -(function (Phaser) { - /** - * Phaser - Components - Texture - * - * The Sprite GameObject is an extension of the core GameObject that includes support for animation and dynamic textures. - */ - (function (Components) { - var Texture = (function () { - function Texture() { } - return Texture; - })(); - Components.Texture = Texture; - })(Phaser.Components || (Phaser.Components = {})); - var Components = Phaser.Components; -})(Phaser || (Phaser = {})); -// Module -var Shapes; -(function (Shapes) { - // Class - var Point = (function () { - // Constructor - function Point(x, y) { - this.x = x; - this.y = y; - } - Point.prototype.getDist = // Instance member - function () { - return Math.sqrt(this.x * this.x + this.y * this.y); - }; - Point.origin = new Point(0, 0); - return Point; - })(); - Shapes.Point = Point; -})(Shapes || (Shapes = {})); -// Local variables -var p = new Shapes.Point(3, 4); -var dist = p.getDist(); -/// -/** -* 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.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 Phaser.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 Phaser.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 Phaser.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 - 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 = Phaser.Math.max(Phaser.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 = Phaser.Math.max(Phaser.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 Phaser.Math.round(Phaser.Math.sqrt(dx * dx + dy * dy)); - } else { - return Phaser.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 = Phaser.Math.sqrt(((x - a.x) * (x - a.x)) + ((y - a.y) * (y - a.y))); - } - return a.setTo(x + distance * Phaser.Math.cos(angle), y + distance * Phaser.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 - 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.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 * (Phaser.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 Phaser.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; - }; - 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 - 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 >= Phaser.Collision.distanceSquared(a.x, a.y, x, y)); - }; - 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)) >= Phaser.Collision.distanceSquared(a.x, a.y, b.x, b.y); - }; - 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 Phaser.Math.round(Phaser.Math.sqrt(dx * dx + dy * dy)); - } else { - return Phaser.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 * Phaser.Math.cos(angle), a.y + a.radius * Phaser.Math.sin(angle)); - }; - return CircleUtils; - })(); - Phaser.CircleUtils = CircleUtils; -})(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 = Phaser.Math.max(a.x, b.x); - out.y = Phaser.Math.max(a.y, b.y); - out.width = Phaser.Math.min(a.right, b.right) - out.x; - out.height = Phaser.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(Phaser.Math.min(a.x, b.x), Phaser.Math.min(a.y, b.y), Phaser.Math.max(a.right, b.right), Phaser.Math.max(a.bottom, b.bottom)); - }; - return RectangleUtils; - })(); - Phaser.RectangleUtils = RectangleUtils; -})(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 Phaser.Math.abs(a.x - b.x) <= epsilon && Phaser.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 Phaser.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 Phaser.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 * Phaser.Math.cos(theta) - y * Phaser.Math.sin(theta) + b.x, x * Phaser.Math.sin(theta) + y * Phaser.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 = {})); -var Phaser; -(function (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. Brandon Jones, Colin MacKenzie IV - */ - (function (Math) { - var Vec2 = (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 Vec2(x, y) { - if (typeof x === "undefined") { x = 0; } - if (typeof y === "undefined") { y = 0; } - //var GLMAT_ARRAY_TYPE = (typeof Float32Array !== 'undefined') ? Float32Array : Array; - this.x = x; - this.y = y; - } - Vec2.prototype.setTo = function (x, y) { - this.x = x; - this.y = y; - return this; - }; - Vec2.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); - }; - Vec2.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); - }; - Vec2.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); - }; - Vec2.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); - }; - Vec2.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); - }; - Vec2.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); - }; - Vec2.prototype.mutableSet = // Same as copyFrom, used by VerletManager - function (v) { - this.x = v.x; - this.y = v.y; - return this; - }; - Vec2.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; - }; - Vec2.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; - }; - Vec2.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; - }; - Vec2.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; - }; - Vec2.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; - }; - Vec2.prototype.mutableMultiplyByScalar = /** - * Multiply this vector by the given scalar. - * - * @param {number} scalar - * @return {Vector2} This for chaining. - */ - function (scalar) { - this.x *= scalar; - this.y *= scalar; - return this; - }; - Vec2.prototype.mutableDivideByScalar = /** - * Divide this vector by the given scalar. - * - * @param {number} scalar - * @return {Vector2} This for chaining. - */ - function (scalar) { - this.x /= scalar; - this.y /= scalar; - return this; - }; - Vec2.prototype.reverse = /** - * Reverse this vector. - * - * @return {Vector} This for chaining. - */ - function () { - this.x = -this.x; - this.y = -this.y; - return this; - }; - Vec2.prototype.edge = function (v, output) { - if (typeof output === "undefined") { output = new Vector2(); } - return this.sub(v, output); - }; - Vec2.prototype.equals = function (v) { - return this.x == v.x && this.y == v.y; - }; - Vec2.prototype.epsilonEquals = function (v, epsilon) { - return Math.abs(this.x - v.x) <= epsilon && Math.abs(this.y - v.y) <= epsilon; - }; - 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.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); - }; - Vec2.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)); - }; - Vec2.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)); - }; - Vec2.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; - }; - Vec2.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; - }; - Vec2.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; - }; - Vec2.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; - }; - Vec2.prototype.getProjectionMagnitude = function (v) { - var den = v.dot(v); - if(den == 0) { - return 0; - } else { - return Math.abs(this.dot(v) / den); - } - }; - Vec2.prototype.direction = function (output) { - if (typeof output === "undefined") { output = new Vector2(); } - output.copyFrom(this); - return this.normalize(output); - }; - Vec2.prototype.normalRightHand = function (output) { - if (typeof output === "undefined") { output = this; } - return output.setTo(this.y * -1, this.x); - }; - Vec2.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; - }; - Vec2.prototype.getMagnitude = function () { - return Math.sqrt(Math.pow(this.x, 2) + Math.pow(this.y, 2)); - }; - Vec2.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)); - }; - Vec2.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)); - }; - Vec2.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); - }; - Vec2.prototype.angle2 = function (vLeft, vRight) { - return vLeft.sub(this).angle(vRight.sub(this)); - }; - Vec2.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); - }; - Vec2.prototype.clone = function (output) { - if (typeof output === "undefined") { output = new Vector2(); } - return output.setTo(this.x, this.y); - }; - Vec2.prototype.copyFrom = function (v) { - this.x = v.x; - this.y = v.y; - return this; - }; - Vec2.prototype.copyTo = function (v) { - return v.setTo(this.x, this.y); - }; - Vec2.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 Vec2; - })(); - Math.Vec2 = Vec2; - })(Phaser.Math || (Phaser.Math = {})); - var Math = Phaser.Math; -})(Phaser || (Phaser = {})); -// Module -var Shapes; -(function (Shapes) { - // Class - var Point = (function () { - // Constructor - function Point(x, y) { - this.x = x; - this.y = y; - } - Point.prototype.getDist = // Instance member - function () { - return Math.sqrt(this.x * this.x + this.y * this.y); - }; - Point.origin = new Shapes.Point(0, 0); - return Point; - })(); - Shapes.Point = Point; -})(Shapes || (Shapes = {})); -// Local variables -var p = new Shapes.Point(3, 4); -var dist = p.getDist(); -/// -/// -/** * Phaser - Pointer * * A Pointer object is used by the Touch and MSPoint managers and represents a single finger on the touch screen. @@ -12545,13 +8010,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; /** @@ -12660,8 +8125,8 @@ var Phaser; this._game = game; this.id = id; this.active = false; - this.position = new Vector2(); - this.positionDown = new 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; @@ -12875,7 +8340,7 @@ var Phaser; return; } this._game.stage.context.beginPath(); - this._game.stage.context.arc(this.x, this.y, this.circle.radius, 0, Phaser.Math.PI * 2); + this._game.stage.context.arc(this.x, this.y, this.circle.radius, 0, Math.PI * 2); if(this.active) { this._game.stage.context.fillStyle = 'rgba(0,255,0,0.5)'; this._game.stage.context.strokeStyle = 'rgb(0,255,0)'; @@ -12911,7 +8376,7 @@ var Phaser; })(); Phaser.Pointer = Pointer; })(Phaser || (Phaser = {})); -/// +/// /// /** * Phaser - MSPointer @@ -13008,7 +8473,7 @@ var Phaser; })(); Phaser.MSPointer = MSPointer; })(Phaser || (Phaser = {})); -/// +/// /// /** * Phaser - Gestures @@ -13045,1698 +8510,503 @@ var Phaser; Phaser.Gestures = Gestures; })(Phaser || (Phaser = {})); /// -/// -/** -* Phaser - Sound -* -* A Sound file, used by the Game.SoundManager for playback. -*/ -var Phaser; -(function (Phaser) { - var Sound = (function () { - /** - * Sound constructor - * @param context {object} The AudioContext instance. - * @param gainNode {object} Gain node instance. - * @param data {object} Sound data. - * @param [volume] {number} volume of this sound when playing. - * @param [loop] {boolean} loop this sound when playing? (Default to false) - */ - function Sound(context, gainNode, data, volume, loop) { - if (typeof volume === "undefined") { volume = 1; } - if (typeof loop === "undefined") { loop = false; } - this.loop = false; - this.isPlaying = false; - this.isDecoding = false; - this._context = context; - this._gainNode = gainNode; - this._buffer = data; - this._volume = volume; - this.loop = loop; - // Local volume control - if(this._context !== null) { - this._localGainNode = this._context.createGainNode(); - this._localGainNode.connect(this._gainNode); - this._localGainNode.gain.value = this._volume; - } - if(this._buffer === null) { - this.isDecoding = true; - } else { - this.play(); - } - } - Sound.prototype.setDecodedBuffer = function (data) { - this._buffer = data; - this.isDecoding = false; - //this.play(); - }; - Sound.prototype.play = /** - * Play this sound. - */ - function () { - if(this._buffer === null || this.isDecoding === true) { - return; - } - this._sound = this._context.createBufferSource(); - this._sound.buffer = this._buffer; - this._sound.connect(this._localGainNode); - if(this.loop) { - this._sound.loop = true; - } - this._sound.noteOn(0)// the zero is vitally important, crashes iOS6 without it - ; - this.duration = this._sound.buffer.duration; - this.isPlaying = true; - }; - Sound.prototype.stop = /** - * Stop playing this sound. - */ - function () { - if(this.isPlaying === true) { - this.isPlaying = false; - this._sound.noteOff(0); - } - }; - Sound.prototype.mute = /** - * Mute the sound. - */ - function () { - this._localGainNode.gain.value = 0; - }; - Sound.prototype.unmute = /** - * Enable the sound. - */ - function () { - this._localGainNode.gain.value = this._volume; - }; - Object.defineProperty(Sound.prototype, "volume", { - get: function () { - return this._volume; - }, - set: function (value) { - this._volume = value; - this._localGainNode.gain.value = this._volume; - }, - enumerable: true, - configurable: true - }); - return Sound; - })(); - Phaser.Sound = Sound; -})(Phaser || (Phaser = {})); -/// -/// -/** -* Phaser - SoundManager -* -* This is an embroyonic web audio sound management class. There is a lot of work still to do here. -*/ -var Phaser; -(function (Phaser) { - var SoundManager = (function () { - /** - * SoundManager constructor - * Create a new SoundManager. - */ - function SoundManager(game) { - /** - * Reference to AudioContext instance. - */ - this._context = null; - this._game = game; - if(game.device.webaudio == true) { - if(!!window['AudioContext']) { - this._context = new window['AudioContext'](); - } else if(!!window['webkitAudioContext']) { - this._context = new window['webkitAudioContext'](); - } - if(this._context !== null) { - this._gainNode = this._context.createGainNode(); - this._gainNode.connect(this._context.destination); - this._volume = 1; - } - } - } - SoundManager.prototype.mute = /** - * Mute sounds. - */ - function () { - this._gainNode.gain.value = 0; - }; - SoundManager.prototype.unmute = /** - * Enable sounds. - */ - function () { - this._gainNode.gain.value = this._volume; - }; - Object.defineProperty(SoundManager.prototype, "volume", { - get: function () { - return this._volume; - }, - set: function (value) { - this._volume = value; - this._gainNode.gain.value = this._volume; - }, - enumerable: true, - configurable: true - }); - SoundManager.prototype.decode = /** - * Decode a sound with its assets key. - * @param key {string} Assets key of the sound to be decoded. - * @param callback {function} This will be invoked when finished decoding. - * @param [sound] {Sound} its bufer will be set to decoded data. - */ - function (key, callback, sound) { - if (typeof callback === "undefined") { callback = null; } - if (typeof sound === "undefined") { sound = null; } - var soundData = this._game.cache.getSound(key); - if(soundData) { - if(this._game.cache.isSoundDecoded(key) === false) { - var that = this; - this._context.decodeAudioData(soundData, function (buffer) { - that._game.cache.decodedSound(key, buffer); - if(sound) { - sound.setDecodedBuffer(buffer); - } - callback(); - }); - } - } - }; - SoundManager.prototype.play = /** - * Play a sound with its assets key. - * @param key {string} Assets key of the sound you want to play. - * @param [volume] {number} volume of the sound you want to play. - * @param [loop] {boolean} loop when it finished playing? (Default to false) - * @return {Sound} The playing sound object. - */ - function (key, volume, loop) { - if (typeof volume === "undefined") { volume = 1; } - if (typeof loop === "undefined") { loop = false; } - if(this._context === null) { - return; - } - var soundData = this._game.cache.getSound(key); - if(soundData) { - // Does the sound need decoding? - if(this._game.cache.isSoundDecoded(key) === true) { - return new Phaser.Sound(this._context, this._gainNode, soundData, volume, loop); - } else { - var tempSound = new Phaser.Sound(this._context, this._gainNode, null, volume, loop); - // this is an async process, so we can return the Sound object anyway, it just won't be playing yet - this.decode(key, function () { - return tempSound.play(); - }, tempSound); - return tempSound; - } - } - }; - return SoundManager; - })(); - Phaser.SoundManager = SoundManager; -})(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 - Phaser.Math.sqrt(1 - k * k); - }; - Circular.Out = function Out(k) { - return Phaser.Math.sqrt(1 - (--k * k)); - }; - Circular.InOut = function InOut(k) { - if((k *= 2) < 1) { - return -0.5 * (Phaser.Math.sqrt(1 - k * k) - 1); - } - return 0.5 * (Phaser.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 * Phaser.Math.asin(1 / a) / (2 * Phaser.Math.PI); - } - return -(a * Phaser.Math.pow(2, 10 * (k -= 1)) * Phaser.Math.sin((k - s) * (2 * Phaser.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 * Phaser.Math.asin(1 / a) / (2 * Phaser.Math.PI); - } - return (a * Phaser.Math.pow(2, -10 * k) * Phaser.Math.sin((k - s) * (2 * Phaser.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 * Phaser.Math.asin(1 / a) / (2 * Phaser.Math.PI); - } - if((k *= 2) < 1) { - return -0.5 * (a * Phaser.Math.pow(2, 10 * (k -= 1)) * Phaser.Math.sin((k - s) * (2 * Phaser.Math.PI) / p)); - } - return a * Phaser.Math.pow(2, -10 * (k -= 1)) * Phaser.Math.sin((k - s) * (2 * Phaser.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 : Phaser.Math.pow(1024, k - 1); - }; - Exponential.Out = function Out(k) { - return k === 1 ? 1 : 1 - Phaser.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 * Phaser.Math.pow(1024, k - 1); - } - return 0.5 * (-Phaser.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 - Phaser.Math.cos(k * Phaser.Math.PI / 2); - }; - Sinusoidal.Out = function Out(k) { - return Phaser.Math.sin(k * Phaser.Math.PI / 2); - }; - Sinusoidal.InOut = function InOut(k) { - return 0.5 * (1 - Phaser.Math.cos(Phaser.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 - 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 - Camera +* Phaser - Vec2Utils +* +* A collection of methods useful for manipulating and performing operations on 2D vectors. * -* 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. + var Vec2Utils = (function () { + function Vec2Utils() { } + Vec2Utils.add = /** + * Adds two 2D vectors. * - * @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. + * @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 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 {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.fx = new FXManager(this._game, this); - // The view into the world canvas we wish to render - this.worldView = new 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 = Phaser.Camera.STYLE_LOCKON; } - this._target = target; - var helper; - switch(style) { - case Phaser.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 Phaser.Camera.STYLE_TOPDOWN: - helper = Phaser.Math.max(this.width, this.height) / 4; - this.deadzone = new Phaser.Rectangle((this.width - helper) / 2, (this.height - helper) / 2, helper, helper); - break; - case Phaser.Camera.STYLE_TOPDOWN_TIGHT: - helper = Phaser.Math.max(this.width, this.height) / 8; - this.deadzone = new Phaser.Rectangle((this.width - helper) / 2, (this.height - helper) / 2, helper, helper); - break; - case Phaser.Camera.STYLE_LOCKON: - default: - this.deadzone = null; - break; - } + function add(a, b, out) { + if (typeof out === "undefined") { out = new Phaser.Vec2(); } + return out.setTo(a.x + b.x, a.y + b.y); }; - 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 = Phaser.Math.round(x - this.worldView.halfWidth); - this.scroll.y = Phaser.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 = Phaser.Math.round(point.x - this.worldView.halfWidth); - this.scroll.y = Phaser.Math.round(point.y - this.worldView.halfHeight); - }; - Camera.prototype.setBounds = /** - * Specify the boundaries of the world or where the camera is allowed to move. + Vec2Utils.subtract = /** + * Subtracts two 2D vectors. * - * @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). + * @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 (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(); + function subtract(a, b, out) { + if (typeof out === "undefined") { out = new Phaser.Vec2(); } + return out.setTo(a.x - b.x, a.y - b.y); }; - 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(); - } - 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; - // 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 * (Phaser.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)); - } - // Background - if(this.opaque) { - this._game.stage.context.fillStyle = this.backgroundColor; - this._game.stage.context.fillRect(this._sx, this._sy, 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._sx, this._sy, this.worldView.width, this.worldView.height); - this._game.stage.context.closePath(); - this._game.stage.context.clip(); - } - // Render all the Sprites - this._game.world.group.render(this, this._sx, this._sy); - // 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; - } - }; - 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 - 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 = /** + Vec2Utils.multiply = /** + * Multiplies two 2D vectors. * - * @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]); - } + * @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); }; - 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 = /** + Vec2Utils.divide = /** + * Divides two 2D vectors. * - * @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]); - } + * @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); }; - Touch.prototype.onTouchEnd = /** + Vec2Utils.scale = /** + * Scales a 2D vector. * - * @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 + * @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 () { - 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); - } + function scale(a, s, out) { + if (typeof out === "undefined") { out = new Phaser.Vec2(); } + return out.setTo(a.x * s, a.y * s); }; - 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 + 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 () { - 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); + function perp(a, out) { + if (typeof out === "undefined") { out = new Phaser.Vec2(); } + return out.setTo(a.y, -a.x); }; - 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] + 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 (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; - } + function equals(a, b) { + return a.x == b.x && a.y == b.y; }; - Keyboard.prototype.justReleased = /** - * @param {Number} keycode - * @param {Number} [duration] + 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 (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; - } + function epsilonEquals(a, b, epsilon) { + return Math.abs(a.x - b.x) <= epsilon && Math.abs(a.y - b.y) <= epsilon; }; - Keyboard.prototype.isDown = /** - * @param {Number} keycode - * @return {Boolean} + 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 (keycode) { - if(this._keys[keycode]) { - return this._keys[keycode].isDown; - } else { - return false; - } + function distance(a, b) { + return Math.sqrt(Vec2Utils.distanceSq(a, b)); }; - 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; + 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.Keyboard = Keyboard; -})(Phaser || (Phaser = {})); -/// -/// + 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 - Input * @@ -14760,7 +9030,7 @@ var Phaser; /** * A vector object representing the current position of the Pointer. * @property vector - * @type {Vector2} + * @type {Vec2} **/ this.position = null; /** @@ -14900,7 +9170,7 @@ var Phaser; this.onUp = new Phaser.Signal(); this.onTap = new Phaser.Signal(); this.onHold = new Phaser.Signal(); - this.position = new Vector2(); + this.position = new Phaser.Vec2(); this.circle = new Phaser.Circle(0, 0, 44); this.currentPointers = 0; } @@ -14917,7 +9187,7 @@ var Phaser; return this._x; }, set: function (value) { - this._x = Phaser.Math.round(value); + this._x = Math.round(value); }, enumerable: true, configurable: true @@ -14932,7 +9202,7 @@ var Phaser; return this._y; }, set: function (value) { - this._y = Phaser.Math.round(value); + this._y = Math.round(value); }, enumerable: true, configurable: true @@ -15282,7 +9552,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 @@ -15291,540 +9561,3287 @@ 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 = {})); -/// +/// +/// +/// +var Phaser; +(function (Phaser) { + var HeadlessRenderer = (function () { + function HeadlessRenderer(game) { + this._game = game; + } + HeadlessRenderer.prototype.render = function () { + }; + 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; + } + return true; + }; + return HeadlessRenderer; + })(); + Phaser.HeadlessRenderer = HeadlessRenderer; + // Add Tilemap, ScrollZone, etc? + })(Phaser || (Phaser = {})); +/// +/// +/// +/// +/// +var Phaser; +(function (Phaser) { + 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; + this._dy = 0; + this._dw = 0; + this._dh = 0; + this._game = game; + } + 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(); + } + }; + 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, 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(sprite.texture.alpha !== 1) { + var globalAlpha = sprite.texture.context.globalAlpha; + sprite.texture.context.globalAlpha = sprite.texture.alpha; + } + this._sx = 0; + this._sy = 0; + this._sw = sprite.frameBounds.width; + this._sh = sprite.frameBounds.height; + 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; + /* + 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(sprite.scrollFactor.x !== 1 || sprite.scrollFactor.y !== 1) { + //this._dx -= (camera.worldView.x * this.scrollFactor.x); + //this._dy -= (camera.worldView.y * this.scrollFactor.y); + } + // Rotation and Flipped + 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.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.texture.flippedX) { + sprite.texture.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) + //{ + 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.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) { + sprite.texture.context.globalAlpha = globalAlpha; + } + return true; + }; + return CanvasRenderer; + })(); + Phaser.CanvasRenderer = CanvasRenderer; +})(Phaser || (Phaser = {})); +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// /** -* 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 */ var Phaser; (function (Phaser) { - var FrameData = (function () { + var Game = (function () { /** - * 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. */ - function FrameData() { - this._frames = []; - this._frameNames = []; + function Game(callbackContext, parent, width, height, initCallback, createCallback, updateCallback, renderCallback, destroyCallback) { + if (typeof parent === "undefined") { parent = ''; } + if (typeof width === "undefined") { width = 800; } + if (typeof height === "undefined") { height = 600; } + if (typeof initCallback === "undefined") { initCallback = null; } + if (typeof createCallback === "undefined") { createCallback = null; } + if (typeof updateCallback === "undefined") { updateCallback = null; } + if (typeof renderCallback === "undefined") { renderCallback = null; } + if (typeof destroyCallback === "undefined") { destroyCallback = null; } + var _this = this; + /** + * Max allowable accumulation. + * @type {number} + */ + this._maxAccumulation = 32; + /** + * Total number of milliseconds elapsed since last update loop. + * @type {number} + */ + this._accumulator = 0; + /** + * Milliseconds of time per step of the game loop. + * @type {number} + */ + this._step = 0; + /** + * Whether loader complete loading or not. + * @type {boolean} + */ + this._loadComplete = false; + /** + * Game is paused? + * @type {boolean} + */ + this._paused = false; + /** + * The state to be switched to in the next frame. + * @type {State} + */ + this._pendingState = null; + /** + * The current State object (defaults to null) + * @type {State} + */ + this.state = null; + /** + * This will be called when init states. (loading assets...) + * @type {function} + */ + this.onInitCallback = null; + /** + * This will be called when create states. (setup states...) + * @type {function} + */ + this.onCreateCallback = null; + /** + * This will be called when update states. + * @type {function} + */ + this.onUpdateCallback = null; + /** + * This will be called when render states. + * @type {function} + */ + this.onRenderCallback = null; + /** + * This will be called when states paused. + * @type {function} + */ + this.onPausedCallback = null; + /** + * This will be called when the state is destroyed (i.e. swapping to a new state) + * @type {function} + */ + this.onDestroyCallback = null; + /** + * Whether the game engine is booted, aka available. + * @type {boolean} + */ + this.isBooted = false; + /** + * Is game running or paused? + * @type {boolean} + */ + this.isRunning = false; + this.callbackContext = callbackContext; + this.onInitCallback = initCallback; + this.onCreateCallback = createCallback; + this.onUpdateCallback = updateCallback; + this.onRenderCallback = renderCallback; + this.onDestroyCallback = destroyCallback; + if(document.readyState === 'complete' || document.readyState === 'interactive') { + setTimeout(function () { + return _this.boot(parent, width, height); + }); + } else { + document.addEventListener('DOMContentLoaded', function () { + return _this.boot(parent, width, height); + }, false); + window.addEventListener('load', function () { + return _this.boot(parent, width, height); + }, false); + } } - Object.defineProperty(FrameData.prototype, "total", { + Game.prototype.boot = /** + * 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. + */ + function (parent, width, height) { + var _this = this; + if(this.isBooted == true) { + return; + } + if(!document.body) { + window.setTimeout(function () { + return _this.boot(parent, width, height); + }, 13); + } else { + this.device = new Phaser.Device(); + //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 Collision(this); + this.loader = new Phaser.Loader(this, this.loadComplete); + this.time = new Phaser.Time(this); + this.tweens = new Phaser.TweenManager(this); + this.input = new Phaser.Input(this); + this.rnd = new Phaser.RandomDataGenerator([ + (Date.now() * Math.random()).toString() + ]); + this.setRenderer(Phaser.Types.RENDERER_CANVAS); + this.framerate = 60; + this.isBooted = true; + this.input.start(); + // Display the default game screen? + if(this.onInitCallback == null && this.onCreateCallback == null && this.onUpdateCallback == null && this.onRenderCallback == null && this._pendingState == null) { + this._raf = new Phaser.RequestAnimationFrame(this, this.bootLoop); + } else { + this.isRunning = true; + this._loadComplete = false; + this._raf = new Phaser.RequestAnimationFrame(this, this.loop); + if(this._pendingState) { + this.switchState(this._pendingState, false, false); + } else { + this.startState(); + } + } + } + }; + 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. + */ + function () { + this._loadComplete = true; + }; + Game.prototype.bootLoop = /** + * Game loop method will be called when it's booting. + */ + function () { + this.tweens.update(); + this.input.update(); + this.stage.update(); + }; + Game.prototype.pausedLoop = /** + * Game loop method will be called when it's paused. + */ + function () { + this.tweens.update(); + this.input.update(); + this.stage.update(); + if(this.onPausedCallback !== null) { + this.onPausedCallback.call(this.callbackContext); + } + }; + Game.prototype.loop = /** + * Game loop method will be called when it's running. + */ + function () { + this.tweens.update(); + this.input.update(); + this.stage.update(); + this._accumulator += this.time.delta; + if(this._accumulator > this._maxAccumulation) { + this._accumulator = this._maxAccumulation; + } + while(this._accumulator >= this._step) { + this.time.elapsed = this.time.timeScale * (this._step / 1000); + this.world.update(); + this._accumulator = this._accumulator - this._step; + } + if(this._loadComplete && this.onUpdateCallback) { + this.onUpdateCallback.call(this.callbackContext); + } + this.renderer.render(); + if(this._loadComplete && this.onRenderCallback) { + this.onRenderCallback.call(this.callbackContext); + } + }; + Game.prototype.startState = /** + * Start current state. + */ + function () { + if(this.onInitCallback !== null) { + this.loader.reset(); + this.onInitCallback.call(this.callbackContext); + // Is the loader empty? + if(this.loader.queueSize == 0) { + if(this.onCreateCallback !== null) { + this.onCreateCallback.call(this.callbackContext); + } + this._loadComplete = true; + } + } else { + // No init? Then there was nothing to load either + if(this.onCreateCallback !== null) { + this.onCreateCallback.call(this.callbackContext); + } + this._loadComplete = true; + } + }; + Game.prototype.setCallbacks = /** + * 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. + */ + function (initCallback, createCallback, updateCallback, renderCallback, destroyCallback) { + if (typeof initCallback === "undefined") { initCallback = null; } + if (typeof createCallback === "undefined") { createCallback = null; } + if (typeof updateCallback === "undefined") { updateCallback = null; } + if (typeof renderCallback === "undefined") { renderCallback = null; } + if (typeof destroyCallback === "undefined") { destroyCallback = null; } + this.onInitCallback = initCallback; + this.onCreateCallback = createCallback; + this.onUpdateCallback = updateCallback; + this.onRenderCallback = renderCallback; + this.onDestroyCallback = destroyCallback; + }; + Game.prototype.switchState = /** + * 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) + */ + function (state, clearWorld, clearCache) { + if (typeof clearWorld === "undefined") { clearWorld = true; } + if (typeof clearCache === "undefined") { clearCache = false; } + if(this.isBooted == false) { + this._pendingState = state; + return; + } + // Destroy current state? + if(this.onDestroyCallback !== null) { + this.onDestroyCallback.call(this.callbackContext); + } + this.input.reset(true); + // Prototype? + if(typeof state === 'function') { + this.state = new state(this); + } + // Ok, have we got the right functions? + if(this.state['create'] || this.state['update']) { + this.callbackContext = this.state; + this.onInitCallback = null; + this.onCreateCallback = null; + this.onUpdateCallback = null; + this.onRenderCallback = null; + this.onPausedCallback = null; + this.onDestroyCallback = null; + // Bingo, let's set them up + if(this.state['init']) { + this.onInitCallback = this.state['init']; + } + if(this.state['create']) { + this.onCreateCallback = this.state['create']; + } + if(this.state['update']) { + this.onUpdateCallback = this.state['update']; + } + if(this.state['render']) { + this.onRenderCallback = this.state['render']; + } + if(this.state['paused']) { + this.onPausedCallback = this.state['paused']; + } + if(this.state['destroy']) { + this.onDestroyCallback = this.state['destroy']; + } + if(clearWorld) { + this.world.destroy(); + if(clearCache == true) { + this.cache.destroy(); + } + } + this._loadComplete = false; + this.startState(); + } else { + throw new Error("Invalid State object given. Must contain at least a create or update function."); + } + }; + Game.prototype.destroy = /** + * Nuke the whole game from orbit + */ + function () { + this.callbackContext = null; + this.onInitCallback = null; + this.onCreateCallback = null; + this.onUpdateCallback = null; + this.onRenderCallback = null; + this.onPausedCallback = null; + this.onDestroyCallback = null; + this.cache = null; + this.input = null; + this.loader = null; + this.sound = null; + this.stage = null; + this.time = null; + this.world = null; + this.isBooted = false; + }; + Object.defineProperty(Game.prototype, "paused", { get: function () { - return this._frames.length; + return this._paused; + }, + set: function (value) { + if(value == true && this._paused == false) { + this._paused = true; + this._raf.callback = this.pausedLoop; + } else if(value == false && this._paused == true) { + this._paused = false; + //this.time.time = window.performance.now ? (performance.now() + performance.timing.navigationStart) : Date.now(); + this.input.reset(); + if(this.isRunning == false) { + this._raf.callback = this.bootLoop; + } else { + this._raf.callback = this.loop; + } + } }, 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); + Object.defineProperty(Game.prototype, "framerate", { + get: function () { + return 1000 / this._step; + }, + set: function (value) { + this._step = 1000 / value; + if(this._maxAccumulation < this._step) { + this._maxAccumulation = this._step; } - } - 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; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Game.prototype, "camera", { + 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, + configurable: true + }); + return Game; })(); - Phaser.FrameData = FrameData; + Phaser.Game = Game; })(Phaser || (Phaser = {})); -/// +/// /** -* Phaser - Frame +* Phaser - Point * -* A Frame is a single frame of an animation and is part of a FrameData collection. +* 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 Frame = (function () { + var Point = (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'; + * 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; + } + 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); + }; + 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.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 () { + return '[{Point (x=' + this.x + ' y=' + this.y + ')}]'; + }; + return Point; + })(); + 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; - 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 - 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 = Phaser.Math.round(width / frameWidth); - var column = Phaser.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, Phaser.Math.abs(frame.frameX.nodeValue), Phaser.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; + 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(Animation.prototype, "frame", { - get: function () { - if(this.currentFrame !== null) { - return this.currentFrame.index; - } else { - return this._frameIndex; - } + Object.defineProperty(Rectangle.prototype, "halfHeight", { + get: /** + * Half of the height of the rectangle + * @property halfHeight + * @type Number + **/ + function () { + return Math.round(this.height / 2); }, - 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 + }); + 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 }); - 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(); - } + 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.currentFrame = this._frameData.getFrame(this._frames[this._frameIndex]); + this.width = this.right - value; } - this._timeLastFrame = this._game.time.now; - this._timeNextFrame = this._game.time.now + this.delay; - return true; - } - return false; + 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; }; - 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; + 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); }; - Animation.prototype.onComplete = /** - * Animation complete callback method. - */ + 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 () { - this.isPlaying = false; - this.isFinished = true; - // callback goes here - }; - return Animation; + return "[{Rectangle (x=" + this.x + " y=" + this.y + " width=" + this.width + " height=" + this.height + " empty=" + this.empty + ")}]"; + }; + return Rectangle; })(); - Phaser.Animation = Animation; + Phaser.Rectangle = Rectangle; })(Phaser || (Phaser = {})); -/// -/// +/// +/// +/// /** -* Phaser - TweenManager +* Phaser - ScrollRegion * -* The Game has a single instance of the TweenManager through which all Tween objects are created and updated. -* Tweens are hooked into the game clock and pause system, adjusting based on the game state. -* TweenManager is based heavily on tween.js by sole (http://soledadpenades.com). -* I converted it to TypeScript, swapped the callbacks for signals and patched a few issues with regard -* to properties and completion errors. Please see https://github.com/sole/tween.js for a full list of contributors. +* Creates a scrolling region within a ScrollZone. +* It is scrolled via the scrollSpeed.x/y properties. */ var Phaser; (function (Phaser) { - var TweenManager = (function () { + var ScrollRegion = (function () { /** - * TweenManager constructor - * @param game {Game} A reference to the current Game. + * 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 TweenManager(game) { - this._game = game; - this._tweens = []; + 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); } - TweenManager.prototype.getAll = /** - * Get all the tween objects in an array. - * @return {Phaser.Tween[]} Array with all tween objects. + ScrollRegion.prototype.update = /** + * Update region scrolling with tick time. + * @param delta {number} Elapsed time since last update. */ - function () { - return this._tweens; + 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; }; - TweenManager.prototype.removeAll = /** - * Remove all tween objects. + 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 () { - this._tweens.length = 0; - }; - TweenManager.prototype.create = /** - * Create a tween object for a specific object. - * - * @param object {object} Object you wish the tween will affect. - * @return {Phaser.Tween} The newly created tween object. + 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 (object) { - return new Phaser.Tween(object, this._game); - }; - TweenManager.prototype.add = /** - * Add an exist tween object to the manager. - * - * @param tween {Phaser.Tween} The tween object you want to add. - * @return {Phaser.Tween} The tween object you added to the manager. - */ - function (tween) { - tween.parent = this._game; - this._tweens.push(tween); - return tween; - }; - TweenManager.prototype.remove = /** - * Remove a tween from this manager. - * - * @param tween {Phaser.Tween} The tween object you want to remove. - */ - function (tween) { - var i = this._tweens.indexOf(tween); - if(i !== -1) { - this._tweens.splice(i, 1); + 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); } }; - TweenManager.prototype.update = /** - * Update all the tween objects you added to this manager. - * - * @return {boolean} Return false if there's no tween to update, otherwise return true. + 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 () { - if(this._tweens.length === 0) { + 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 = {})); +/// +/// +/// +/// +/** +* 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)); + }; + 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); + }; + 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 - 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; } - var i = 0; - var numTweens = this._tweens.length; - while(i < numTweens) { - if(this._tweens[i].update(this._game.time.now)) { - i++; - } else { - this._tweens.splice(i, 1); - numTweens--; + 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 TweenManager; + return TilemapLayer; })(); - Phaser.TweenManager = TweenManager; + 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 +* +* 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) { + 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 - 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 +* +* 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 = {})); /// /** @@ -15903,967 +12920,9 @@ var Phaser; 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 this.collision.overlap(objectOrGroup1, objectOrGroup2, notifyCallback, Collision.separate, context); }; return State; })(); Phaser.State = State; })(Phaser || (Phaser = {})); -/// -/** -* 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 Loader = (function () { - /** - * Loader constructor - * - * @param game {Phaser.Game} Current game instance. - * @param callback {function} This will be called when assets completely loaded. - */ - function Loader(game, callback) { - /** - * The crossOrigin value applied to loaded images - * @type {string} - */ - this.crossOrigin = ''; - this._game = game; - this._gameCreateComplete = callback; - this._keys = []; - this._fileList = { - }; - this._xhr = new XMLHttpRequest(); - this._queueSize = 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. - */ - function () { - this._queueSize = 0; - }; - 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 = Phaser.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 == Phaser.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 == Phaser.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. - */ - 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); - } - } - }; - 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; - } - }; - Loader.prototype.fileError = /** - * Error occured when load a file. - * @param key {string} Key of the error loading file. - */ - function (key) { - this._fileList[key].loaded = true; - this._fileList[key].error = true; - this.nextFile(key, false); - }; - Loader.prototype.fileComplete = /** - * Called when a file is successfully loaded. - * @param key {string} Key of the successfully loaded file. - */ - 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 == Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY) { - this._xhr.onload = function () { - return _this.jsonLoadComplete(file.key); - }; - } else if(file.format == Phaser.Loader.TEXTURE_ATLAS_XML_STARLING) { - this._xhr.onload = function () { - return _this.xmlLoadComplete(file.key); - }; - } - 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 { - 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 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 = Phaser.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; - })(); - Phaser.Loader = Loader; -})(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 = {})); -/// -/// -/** -* 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 - Cache -* -* A game only has one instance of a Cache and it is used to store all externally loaded assets such -* as images, sounds and data files as a result of Loader calls. Cache items use string based keys for look-up. -*/ -var Phaser; -(function (Phaser) { - var Cache = (function () { - /** - * Cache constructor - */ - function Cache(game) { - this._game = game; - this._canvases = { - }; - this._images = { - }; - this._sounds = { - }; - this._text = { - }; - } - Cache.prototype.addCanvas = /** - * Add a new canvas. - * @param key {string} Asset key for this canvas. - * @param canvas {HTMLCanvasElement} Canvas DOM element. - * @param context {CanvasRenderingContext2D} Render context of this canvas. - */ - function (key, canvas, context) { - this._canvases[key] = { - canvas: canvas, - context: context - }; - }; - Cache.prototype.addSpriteSheet = /** - * Add a new sprite sheet. - * @param key {string} Asset key for the sprite sheet. - * @param url {string} URL of this sprite sheet file. - * @param data {object} Extra sprite sheet data. - * @param frameWidth {number} Width of the sprite sheet. - * @param frameHeight {number} Height of the sprite sheet. - * @param frameMax {number} How many frames stored in the sprite sheet. - */ - function (key, url, data, frameWidth, frameHeight, frameMax) { - this._images[key] = { - url: url, - data: data, - spriteSheet: true, - frameWidth: frameWidth, - frameHeight: frameHeight - }; - this._images[key].frameData = Phaser.AnimationLoader.parseSpriteSheet(this._game, key, frameWidth, frameHeight, frameMax); - }; - Cache.prototype.addTextureAtlas = /** - * Add a new texture atlas. - * @param key {string} Asset key for the texture atlas. - * @param url {string} URL of this texture atlas file. - * @param data {object} Extra texture atlas data. - * @param atlasData {object} Texture atlas frames data. - */ - function (key, url, data, atlasData, format) { - this._images[key] = { - url: url, - data: data, - spriteSheet: true - }; - if(format == Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY) { - this._images[key].frameData = Phaser.AnimationLoader.parseJSONData(this._game, atlasData); - } else if(format == Phaser.Loader.TEXTURE_ATLAS_XML_STARLING) { - this._images[key].frameData = Phaser.AnimationLoader.parseXMLData(this._game, atlasData, format); - } - }; - Cache.prototype.addImage = /** - * Add a new image. - * @param key {string} Asset key for the image. - * @param url {string} URL of this image file. - * @param data {object} Extra image data. - */ - function (key, url, data) { - this._images[key] = { - url: url, - data: data, - spriteSheet: false - }; - }; - Cache.prototype.addSound = /** - * Add a new sound. - * @param key {string} Asset key for the sound. - * @param url {string} URL of this sound file. - * @param data {object} Extra sound data. - */ - function (key, url, data) { - this._sounds[key] = { - url: url, - data: data, - decoded: false - }; - }; - Cache.prototype.decodedSound = /** - * Add a new decoded sound. - * @param key {string} Asset key for the sound. - * @param url {string} URL of this sound file. - * @param data {object} Extra sound data. - */ - function (key, data) { - this._sounds[key].data = data; - this._sounds[key].decoded = true; - }; - Cache.prototype.addText = /** - * Add a new text data. - * @param key {string} Asset key for the text data. - * @param url {string} URL of this text data file. - * @param data {object} Extra text data. - */ - function (key, url, data) { - this._text[key] = { - url: url, - data: data - }; - }; - Cache.prototype.getCanvas = /** - * Get canvas by key. - * @param key Asset key of the canvas you want. - * @return {object} The canvas you want. - */ - function (key) { - if(this._canvases[key]) { - return this._canvases[key].canvas; - } - return null; - }; - Cache.prototype.getImage = /** - * Get image data by key. - * @param key Asset key of the image you want. - * @return {object} The image data you want. - */ - function (key) { - if(this._images[key]) { - return this._images[key].data; - } - return null; - }; - Cache.prototype.getFrameData = /** - * Get frame data by key. - * @param key Asset key of the frame data you want. - * @return {object} The frame data you want. - */ - function (key) { - if(this._images[key] && this._images[key].spriteSheet == true) { - return this._images[key].frameData; - } - return null; - }; - Cache.prototype.getSound = /** - * Get sound data by key. - * @param key Asset key of the sound you want. - * @return {object} The sound data you want. - */ - function (key) { - if(this._sounds[key]) { - return this._sounds[key].data; - } - return null; - }; - Cache.prototype.isSoundDecoded = /** - * Check whether an asset is decoded sound. - * @param key Asset key of the sound you want. - * @return {object} The sound data you want. - */ - function (key) { - if(this._sounds[key]) { - return this._sounds[key].decoded; - } - }; - Cache.prototype.isSpriteSheet = /** - * Check whether an asset is sprite sheet. - * @param key Asset key of the sprite sheet you want. - * @return {object} The sprite sheet data you want. - */ - function (key) { - if(this._images[key]) { - return this._images[key].spriteSheet; - } - }; - Cache.prototype.getText = /** - * Get text data by key. - * @param key Asset key of the text data you want. - * @return {object} The text data you want. - */ - function (key) { - if(this._text[key]) { - return this._text[key].data; - } - return null; - }; - Cache.prototype.destroy = /** - * Clean up cache memory. - */ - function () { - for(var item in this._canvases) { - delete this._canvases[item['key']]; - } - for(var item in this._images) { - delete this._images[item['key']]; - } - for(var item in this._sounds) { - delete this._sounds[item['key']]; - } - for(var item in this._text) { - delete this._text[item['key']]; - } - }; - return Cache; - })(); - Phaser.Cache = Cache; -})(Phaser || (Phaser = {}));